raftServer.c 2.2 KB
Newer Older
M
Minghao Li 已提交
1 2
#include <stdlib.h>
#include "common.h"
M
Minghao Li 已提交
3 4
#include "raftServer.h"

M
Minghao Li 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
uint64_t raftId(const char *host, uint32_t port) {
    uint32_t host_uint32 = (uint32_t)inet_addr(host);
    assert(host_uint32 != (uint32_t)-1);
    uint64_t code = ((uint64_t)host_uint32) << 32 | port;
	return code;
}

int32_t raftServerInit(SRaftServer *pRaftServer, const char *host, uint32_t port, const char *dir, struct raft_fsm *pFsm) {
	int ret;

	char cmd_buf[COMMAND_LEN];
	snprintf(cmd_buf, sizeof(cmd_buf), "mkdir -p %s", dir);
	system(cmd_buf);

    snprintf(pRaftServer->host, sizeof(pRaftServer->host), "%s", host);
	pRaftServer->port = port;
    snprintf(pRaftServer->address, sizeof(pRaftServer->address), "%s:%u", host, port);
	strncpy(pRaftServer->dir, dir, sizeof(pRaftServer->dir));

	pRaftServer->raftId = raftId(pRaftServer->host, pRaftServer->port);
	pRaftServer->fsm = pFsm;

	ret = uv_loop_init(&pRaftServer->loop);
	if (!ret) {
		fprintf(stderr, "%s \n", raft_errmsg(&pRaftServer->raft));
	}

	ret = raft_uv_tcp_init(&pRaftServer->transport, &pRaftServer->loop);
	if (!ret) {
		fprintf(stderr, "%s \n", raft_errmsg(&pRaftServer->raft));
	}

	ret = raft_uv_init(&pRaftServer->io, &pRaftServer->loop, dir, &pRaftServer->transport);
	if (!ret) {
		fprintf(stderr, "%s \n", raft_errmsg(&pRaftServer->raft));
	}

	ret = raft_init(&pRaftServer->raft, &pRaftServer->io, pRaftServer->fsm, pRaftServer->raftId, pRaftServer->address);
	if (!ret) {
		fprintf(stderr, "%s \n", raft_errmsg(&pRaftServer->raft));
	}

    struct raft_configuration conf;
    raft_configuration_init(&conf);
    raft_configuration_add(&conf, pRaftServer->raftId, pRaftServer->address, RAFT_VOTER);
    raft_bootstrap(&pRaftServer->raft, &conf);
M
Minghao Li 已提交
51 52 53 54 55

	return 0;
}

int32_t raftServerStart(SRaftServer *pRaftServer) {
M
Minghao Li 已提交
56 57 58 59 60
	int ret;
	ret = raft_start(&pRaftServer->raft);
	if (!ret) {
		fprintf(stderr, "%s \n", raft_errmsg(&pRaftServer->raft));
	}
M
Minghao Li 已提交
61

M
Minghao Li 已提交
62
	uv_run(&pRaftServer->loop, UV_RUN_DEFAULT);
M
Minghao Li 已提交
63 64 65 66 67 68 69 70
}


void raftServerClose(SRaftServer *pRaftServer) {

}


M
Minghao Li 已提交
71 72 73 74 75 76 77 78 79
int fsmApplyCb(struct raft_fsm *pFsm, const struct raft_buffer *buf, void **result) {
    char *msg = (char*)buf->base;
    printf("%s \n", msg);

    return 0;
}

int32_t initFsm(struct raft_fsm *fsm) {
	fsm->apply = fsmApplyCb;
M
Minghao Li 已提交
80 81
	return 0;
}