raftMain.c 8.7 KB
Newer Older
M
Minghao Li 已提交
1 2 3 4 5
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>
6
#include <getopt.h>
M
Minghao Li 已提交
7 8 9
#include <time.h>
#include <stdlib.h>
#include <getopt.h>
M
Minghao Li 已提交
10 11
#include <raft.h>
#include <raft/uv.h>
M
Minghao Li 已提交
12
#include "raftServer.h"
M
Minghao Li 已提交
13
#include "common.h"
M
Minghao Li 已提交
14 15 16

const char *exe_name;

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
void parseAddr(const char *addr, char *host, int len, uint32_t *port) {
	char* tmp = (char*)malloc(strlen(addr) + 1);
	strcpy(tmp, addr);

	char* context;
	char* separator = ":";
	char* token = strtok_r(tmp, separator, &context);
	if (token) {
		snprintf(host, len, "%s", token);
	}

	token = strtok_r(NULL, separator, &context);
	if (token) {
		sscanf(token, "%u", port);
	}

	free(tmp);
}

// only parse 3 tokens
int parseCommand(const char* str, char* token1, char* token2, char* token3, int len)
{
    char* tmp = (char*)malloc(strlen(str) + 1);
    strcpy(tmp, str);

    char* context;
    char* separator = " ";
    int n = 0;

    char* token = strtok_r(tmp, separator, &context);
    if (!token) {
 	   goto ret;
    }
    if (strcmp(token, "") != 0) {
    	strncpy(token1, token, len);
    	n++;
    }

    token = strtok_r(NULL, separator, &context);
    if (!token) {
    	goto ret;
   	}
    if (strcmp(token, "") != 0) {
    	strncpy(token2, token, len);
    	n++;
    }

    token = strtok_r(NULL, separator, &context);
    if (!token) {
    	goto ret;
    }
    if (strcmp(token, "") != 0) {
    	strncpy(token3, token, len);
    	n++;
    }

ret:
    return n;
    free(tmp);
}

M
Minghao Li 已提交
78 79 80 81 82 83 84 85 86
void *startServerFunc(void *param) {
	SRaftServer *pServer = (SRaftServer*)param;
	int32_t r = raftServerStart(pServer);
	assert(r == 0);

	return NULL;
}

// Console ---------------------------------
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
const char* state2String(unsigned short state) {
    if (state == RAFT_UNAVAILABLE) {
        return "RAFT_UNAVAILABLE";

    } else if (state == RAFT_FOLLOWER) {
        return "RAFT_FOLLOWER";

    } else if (state == RAFT_CANDIDATE) {
        return "RAFT_CANDIDATE";

    } else if (state == RAFT_LEADER) {
        return "RAFT_LEADER";

    }
    return "UNKNOWN_RAFT_STATE";
}

void printRaftConfiguration(struct raft_configuration *c) {
	printf("configuration: \n");
	for (int i = 0; i < c->n; ++i) {
		printf("%llu -- %d -- %s\n", c->servers->id, c->servers->role, c->servers->address);
	}
}

void printRaftState(struct raft *r) {
    printf("----Raft State: -----------\n");
    printf("my_id: %llu \n", r->id);
    printf("address: %s \n", r->address);
    printf("current_term: %llu \n", r->current_term);
    printf("voted_for: %llu \n", r->voted_for);
    printf("role: %s \n", state2String(r->state));
    printf("commit_index: %llu \n", r->commit_index);
    printf("last_applied: %llu \n", r->last_applied);
    printf("last_stored: %llu \n", r->last_stored);

	/*
    printf("configuration_index: %llu \n", r->configuration_index);
    printf("configuration_uncommitted_index: %llu \n", r->configuration_uncommitted_index);
	printRaftConfiguration(&r->configuration);
	*/

	printf("----------------------------\n");
}

void putValueCb(struct raft_apply *req, int status, void *result) {
    raft_free(req);
	struct raft *r = req->data;
	if (status != 0) {
		printf("putValueCb: %s \n", raft_errmsg(r));
	} else {
		printf("putValueCb: %s \n", "ok");
	}
}

void putValue(struct raft *r, const char *value) {
    struct raft_buffer buf;

    buf.len = TOKEN_LEN;;
    buf.base = raft_malloc(buf.len);
	snprintf(buf.base, buf.len, "%s", value);

    struct raft_apply *req = raft_malloc(sizeof(struct raft_apply));
	req->data = r;
    int ret = raft_apply(r, req, &buf, 1, putValueCb);
	if (ret == 0) {
    	printf("put %s \n", (char*)buf.base);
	} else {
		printf("put error: %s \n", raft_errmsg(r));
	}
}

void getValue(const char *key) {
	char *ptr = getKV(key);
	if (ptr) {
		printf("get value: [%s] \n", ptr);
	} else {
		printf("value not found for key: [%s] \n", key);
	}
}

M
Minghao Li 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
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;
		}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
		char cmd[TOKEN_LEN];
		memset(cmd, 0, sizeof(cmd));

		char param1[TOKEN_LEN];
		memset(param1, 0, sizeof(param1));

		char param2[TOKEN_LEN];
		memset(param2, 0, sizeof(param2));

		parseCommand(cmd_buf, cmd, param1, param2, TOKEN_LEN);
		if (strcmp(cmd, "addnode") == 0) {
			printf("not support \n");

			/*
			char host[HOST_LEN];
			uint32_t port;
			parseAddr(param1, host, HOST_LEN, &port);
			uint64_t rid = raftId(host, port);

			struct raft_change *req = raft_malloc(sizeof(*req));
			int r = raft_add(&pRaftServer->raft, req, rid, param1, NULL);
			if (r != 0) {
				printf("raft_add: %s \n", raft_errmsg(&pRaftServer->raft));
			}
			printf("add node: %lu %s \n", rid, param1);

			struct raft_change *req2 = raft_malloc(sizeof(*req2));
			r = raft_assign(&pRaftServer->raft, req2, rid, RAFT_VOTER, NULL);
			if (r != 0) {
				printf("raft_assign: %s \n", raft_errmsg(&pRaftServer->raft));
			}
			*/

		} else if (strcmp(cmd, "dropnode") == 0) {
			printf("not support \n");

		} else if (strcmp(cmd, "put") == 0) {
			char buf[256];
			snprintf(buf, sizeof(buf), "%s--%s", param1, param2);
			putValue(&pRaftServer->raft, buf);

		} else if (strcmp(cmd, "get") == 0) {
			getValue(param1);

		} else if (strcmp(cmd, "state") == 0) {
			printRaftState(&pRaftServer->raft);

		} else if (strcmp(cmd, "snapshot") == 0) {
			printf("not support \n");

		} else if (strcmp(cmd, "help") == 0) {
			printf("addnode \"127.0.0.1:8888\" \n");
			printf("dropnode \"127.0.0.1:8888\" \n");
			printf("put key value \n");
			printf("get key \n");
			printf("state \n");

		} else {
			printf("unknown command: [%s], type \"help\" to see help \n", cmd);
		}

		//printf("cmd_buf: [%s] \n", cmd_buf);
M
Minghao Li 已提交
247 248 249 250 251 252 253 254 255 256
	}
}

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

// Config ---------------------------------
257 258 259 260 261 262 263 264 265
void usage() {
	printf("\nusage: \n");
	printf("%s --me=127.0.0.1:10000 --dir=./data \n", exe_name);
	printf("\n");
	printf("%s --me=127.0.0.1:10000 --peers=127.0.0.1:10001,127.0.0.1:10002 --dir=./data \n", exe_name);
	printf("%s --me=127.0.0.1:10001 --peers=127.0.0.1:10000,127.0.0.1:10002 --dir=./data \n", exe_name);
	printf("%s --me=127.0.0.1:10002 --peers=127.0.0.1:10000,127.0.0.1:10001 --dir=./data \n", exe_name);
	printf("\n");
}
M
Minghao Li 已提交
266 267

void parseConf(int argc, char **argv, SRaftServerConfig *pConf) {
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
	memset(pConf, 0, sizeof(*pConf));

    int option_index, option_value;
    option_index = 0;
    static struct option long_options[] = {
        {"help", no_argument, NULL, 'h'},
        {"peers", required_argument, NULL, 'p'},
        {"me", required_argument, NULL, 'm'},
        {"dir", required_argument, NULL, 'd'},
        {NULL, 0, NULL, 0}
    };

    while ((option_value = getopt_long(argc, argv, "hp:m:d:", long_options, &option_index)) != -1) {
        switch (option_value) {
        	case 'm': {
				parseAddr(optarg, pConf->me.host, sizeof(pConf->me.host), &pConf->me.port);
				break;
        	}

			case 'p': {
				char tokens[MAX_PEERS][MAX_TOKEN_LEN];
				int peerCount = splitString(optarg, ",", tokens, MAX_PEERS);
				pConf->peersCount = peerCount;
				for (int i = 0; i < peerCount; ++i) {
					Addr *pAddr = &pConf->peers[i];
					parseAddr(tokens[i], pAddr->host, sizeof(pAddr->host), &pAddr->port);
				}
				break;
			}


			case 'd': {
				snprintf(pConf->dir, sizeof(pConf->dir), "%s", optarg);
				break;
			}

			case 'h': {
				usage();
				exit(-1);
			}

			default: {
				usage();
				exit(-1);
			}
		}
	}
	snprintf(pConf->dataDir, sizeof(pConf->dataDir), "%s/%s:%u", pConf->dir, pConf->me.host, pConf->me.port);
M
Minghao Li 已提交
316 317
}

M
Minghao Li 已提交
318
void printConf(SRaftServerConfig *pConf) {
319 320 321 322 323 324 325 326
	printf("\nconf: \n");
	printf("me: %s:%u \n", pConf->me.host, pConf->me.port);
	printf("peersCount: %d \n", pConf->peersCount);
	for (int i = 0; i < pConf->peersCount; ++i) {
		Addr *pAddr = &pConf->peers[i];
		printf("peer%d: %s:%u \n", i, pAddr->host, pAddr->port);
	}
	printf("dataDir: %s \n\n", pConf->dataDir);
M
Minghao Li 已提交
327

M
Minghao Li 已提交
328 329
}

330

M
Minghao Li 已提交
331 332 333 334 335
int main(int argc, char **argv) { 
	srand(time(NULL));
	int32_t ret;

	exe_name = argv[0];
336
	if (argc < 3) {
M
Minghao Li 已提交
337 338 339 340 341 342
		usage();
		exit(-1);
	}

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

345 346 347 348
	char cmd_buf[COMMAND_LEN];
    snprintf(cmd_buf, sizeof(cmd_buf), "mkdir -p %s", conf.dataDir);
    system(cmd_buf);

M
Minghao Li 已提交
349 350 351 352
	struct raft_fsm fsm;
	initFsm(&fsm);

	SRaftServer raftServer;
353
	ret = raftServerInit(&raftServer, &conf, &fsm);
M
Minghao Li 已提交
354
	assert(ret == 0);
M
Minghao Li 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367

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

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

	while (1) {
		sleep(10);
	}

	return 0;
}