raftMain.c 2.3 KB
Newer Older
M
Minghao Li 已提交
1 2 3 4 5 6 7 8
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <stdlib.h>
#include <getopt.h>
M
Minghao Li 已提交
9 10
#include <raft.h>
#include <raft/uv.h>
M
Minghao Li 已提交
11
#include "raftServer.h"
M
Minghao Li 已提交
12
#include "common.h"
M
Minghao Li 已提交
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 51 52 53 54 55 56 57 58 59 60

const char *exe_name;

void *startServerFunc(void *param) {
	SRaftServer *pServer = (SRaftServer*)param;
	int32_t r = raftServerStart(pServer);
	assert(r == 0);

	return NULL;
}

// Console ---------------------------------
void console(SRaftServer *pRaftServer) {
	while (1) {
		char cmd_buf[COMMAND_LEN];
		memset(cmd_buf, 0, sizeof(cmd_buf));
		char *ret = fgets(cmd_buf, COMMAND_LEN, stdin);
		if (!ret) {
			exit(-1);
		}

		int pos = strlen(cmd_buf);                  
		if(cmd_buf[pos - 1] == '\n') {
			cmd_buf[pos - 1] = '\0';
		}

		if (strncmp(cmd_buf, "", COMMAND_LEN) == 0) {
			continue;
		}

		printf("cmd_buf: [%s] \n", cmd_buf);
	}
}

void *startConsoleFunc(void *param) {
	SRaftServer *pServer = (SRaftServer*)param;
	console(pServer);
	return NULL;
}

// Config ---------------------------------
typedef struct SRaftServerConfig {
	char host[HOST_LEN];
	uint32_t port;
	char dir[DIR_LEN];
} SRaftServerConfig;

void parseConf(int argc, char **argv, SRaftServerConfig *pConf) {
M
Minghao Li 已提交
61
	snprintf(pConf->host, sizeof(pConf->host), "%s", argv[1]);
M
Minghao Li 已提交
62 63 64 65
	sscanf(argv[2], "%u", &pConf->port);
	snprintf(pConf->dir, sizeof(pConf->dir), "%s", argv[3]);
}

M
Minghao Li 已提交
66 67 68 69
void printConf(SRaftServerConfig *pConf) {
	printf("conf: %s:%u %s \n", pConf->host, pConf->port, pConf->dir);
}

M
Minghao Li 已提交
70 71 72 73
// -----------------------------------------
void usage() {
	printf("\n");
	printf("usage: %s host port dir \n", exe_name);
M
Minghao Li 已提交
74 75 76
	printf("\n");
	printf("eg: \n");
	printf("%s 127.0.0.1 10000 ./data \n", exe_name);
M
Minghao Li 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	printf("\n");
}

int main(int argc, char **argv) { 
	srand(time(NULL));
	int32_t ret;

	exe_name = argv[0];
	if (argc != 4) {
		usage();
		exit(-1);
	}

	SRaftServerConfig conf;
	parseConf(argc, argv, &conf);
M
Minghao Li 已提交
92 93
	printConf(&conf);	

M
Minghao Li 已提交
94 95 96 97
	struct raft_fsm fsm;
	initFsm(&fsm);

	SRaftServer raftServer;
M
Minghao Li 已提交
98 99
	ret = raftServerInit(&raftServer, conf.host, conf.port, conf.dir, &fsm);
	assert(ret == 0);
M
Minghao Li 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112

	pthread_t tidRaftServer;
	pthread_create(&tidRaftServer, NULL, startServerFunc, &raftServer);

	pthread_t tidConsole;
	pthread_create(&tidConsole, NULL, startConsoleFunc, &raftServer);

	while (1) {
		sleep(10);
	}

	return 0;
}