raftMain.c 10.3 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"
S
common  
Shengliang Guan 已提交
13
#include "tcommon.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
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) {
M
Minghao Li 已提交
107
		printf("%llu -- %d -- %s\n", c->servers[i].id, c->servers[i].role, c->servers[i].address);
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
	}
}

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 已提交
165 166 167 168 169 170 171 172 173 174 175 176
void raft_change_cb_add(struct raft_change *req, int status) {
	printf("raft_change_cb_add status:%d ... \n", status);
}

void raft_change_cb_assign(struct raft_change *req, int status) {
	printf("raft_change_cb_assign status:%d ... \n", status);
}

void raft_change_cb_remove(struct raft_change *req, int status) {
	printf("raft_change_cb_remove status:%d ... \n", status);
}

M
Minghao Li 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
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;
		}

195 196 197 198 199 200 201 202 203 204 205
		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) {
M
Minghao Li 已提交
206
			//printf("not support \n");
207 208 209 210 211 212 213

			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));
M
Minghao Li 已提交
214
			int r = raft_add(&pRaftServer->raft, req, rid, param1, raft_change_cb_add);
215
			if (r != 0) {
M
Minghao Li 已提交
216
				printf("raft_add error: %s \n", raft_errmsg(&pRaftServer->raft));
217 218 219 220
			}
			printf("add node: %lu %s \n", rid, param1);

			struct raft_change *req2 = raft_malloc(sizeof(*req2));
M
Minghao Li 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
			r = raft_assign(&pRaftServer->raft, req2, rid, RAFT_VOTER, raft_change_cb_assign);
			if (r != 0) {
				printf("raft_assign error: %s \n", raft_errmsg(&pRaftServer->raft));
			}
			printf("raft_assign: %s %d \n", param1, RAFT_VOTER);

		} else if (strcmp(cmd, "activate") == 0) {
			char host[HOST_LEN];
			uint32_t port;
			parseAddr(param1, host, HOST_LEN, &port);
			uint64_t rid = raftId(host, port);


			struct raft_change *req2 = raft_malloc(sizeof(*req2));
			int r = raft_assign(&pRaftServer->raft, req2, rid, RAFT_VOTER, raft_change_cb_assign);
236
			if (r != 0) {
M
Minghao Li 已提交
237
				printf("raft_assign error: %s \n", raft_errmsg(&pRaftServer->raft));
238
			}
M
Minghao Li 已提交
239 240 241 242 243
			printf("raft_assign: %s %d \n", param1, RAFT_VOTER);




244 245

		} else if (strcmp(cmd, "dropnode") == 0) {
M
Minghao Li 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258
			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_remove(&pRaftServer->raft, req, rid, raft_change_cb_remove);
			if (r != 0) {
				printf("raft_remove: %s \n", raft_errmsg(&pRaftServer->raft));
			}
			printf("drop node: %lu %s \n", rid, param1);
			

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

		} 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");
M
Minghao Li 已提交
276
			printf("activate \"127.0.0.1:8888\" \n");
277 278 279 280 281 282 283 284 285 286
			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 已提交
287 288 289 290 291 292 293 294 295 296
	}
}

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

// Config ---------------------------------
297 298
void usage() {
	printf("\nusage: \n");
M
Minghao Li 已提交
299 300 301
	printf("%s --me=127.0.0.1:10000 --dir=./data --voter \n", exe_name);
	printf("%s --me=127.0.0.1:10001 --dir=./data \n", exe_name);
	printf("%s --me=127.0.0.1:10002 --dir=./data \n", exe_name);
302 303 304 305 306 307
	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 已提交
308 309

void parseConf(int argc, char **argv, SRaftServerConfig *pConf) {
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'},
M
Minghao Li 已提交
316
        {"voter", no_argument, NULL, 'v'},
317 318 319 320 321 322
        {"peers", required_argument, NULL, 'p'},
        {"me", required_argument, NULL, 'm'},
        {"dir", required_argument, NULL, 'd'},
        {NULL, 0, NULL, 0}
    };

M
Minghao Li 已提交
323 324
	pConf->voter = 0;
    while ((option_value = getopt_long(argc, argv, "hvp:m:d:", long_options, &option_index)) != -1) {
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        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;
			}

M
Minghao Li 已提交
342 343 344 345
			case 'v': {
				pConf->voter = 1;
				break;
			}
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

			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 已提交
364 365
}

M
Minghao Li 已提交
366
void printConf(SRaftServerConfig *pConf) {
367 368 369 370 371 372 373 374
	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 已提交
375

M
Minghao Li 已提交
376 377
}

378

M
Minghao Li 已提交
379 380 381 382 383
int main(int argc, char **argv) { 
	srand(time(NULL));
	int32_t ret;

	exe_name = argv[0];
384
	if (argc < 3) {
M
Minghao Li 已提交
385 386 387 388
		usage();
		exit(-1);
	}

M
Minghao Li 已提交
389 390
	signal(SIGPIPE, SIG_IGN);

M
Minghao Li 已提交
391 392
	SRaftServerConfig conf;
	parseConf(argc, argv, &conf);
M
Minghao Li 已提交
393 394
	printConf(&conf);	

395 396 397 398
	char cmd_buf[COMMAND_LEN];
    snprintf(cmd_buf, sizeof(cmd_buf), "mkdir -p %s", conf.dataDir);
    system(cmd_buf);

M
Minghao Li 已提交
399 400 401 402
	struct raft_fsm fsm;
	initFsm(&fsm);

	SRaftServer raftServer;
403
	ret = raftServerInit(&raftServer, &conf, &fsm);
M
Minghao Li 已提交
404
	assert(ret == 0);
M
Minghao Li 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417

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

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

	while (1) {
		sleep(10);
	}

	return 0;
}