forked from RedisLabs/redisraft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raft.c
2425 lines (2028 loc) · 76.8 KB
/
raft.c
1
2
3
4
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
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
78
79
80
81
82
83
84
85
86
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of RedisRaft.
*
* Copyright (c) 2020-2021 Redis Ltd.
*
* RedisRaft is licensed under the Redis Source Available License (RSAL).
*/
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <ctype.h>
#include <strings.h>
#include <inttypes.h>
#include "redisraft.h"
const char *RaftReqTypeStr[] = {
"<undef>",
"RR_CLUSTER_INIT",
"RR_CLUSTER_JOIN",
"RR_CFGCHANGE_ADDNODE",
"RR_CFGCHANGE_REMOVENODE",
"RR_APPENDENTRIES",
"RR_REQUESTVOTE",
"RR_REDISCOMMAND",
"RR_INFO",
"RR_SNAPSHOT",
"RR_COMPACT",
"RR_CLIENT_DISCONNECT",
"RR_SHARDGROUP_ADD",
"RR_SHARDGROUP_GET",
"RR_SHARDGROUP_LINK",
"RR_TRANSFER_LEADER",
"RR_TIMEOUT_NOW",
};
/* Forward declarations */
static void initRaftLibrary(RedisRaftCtx *rr);
static void configureFromSnapshot(RedisRaftCtx *rr);
static void applyShardGroupChange(RedisRaftCtx *rr, raft_entry_t *entry);
static RaftReqHandler RaftReqHandlers[];
static bool processExiting = false;
static void __setProcessExiting(void) {
processExiting = true;
}
/* A dict that maps client ID to MultiClientState structs */
static RedisModuleDict *multiClientState = NULL;
/* ------------------------------------ Common helpers ------------------------------------ */
static RaftReq *entryDetachRaftReq(RedisRaftCtx *rr, raft_entry_t *entry)
{
RaftReq* req = entry->user_data;
if (!req) {
return NULL;
}
entry->user_data = NULL;
entry->free_func = NULL;
rr->client_attached_entries--;
return req;
}
/* Set up a Raft log entry with an attached RaftReq. We use this when a user command provided
* in a RaftReq should keep the client blocked until the log entry is committed and applied.
*/
static void entryFreeAttachedRaftReq(raft_entry_t *ety)
{
RaftReq *req = entryDetachRaftReq(&redis_raft, ety);
if (req) {
RedisModule_ReplyWithError(req->ctx, "TIMEOUT not committed yet");
RaftReqFree(req);
}
RedisModule_Free(ety);
}
/* Attach a RaftReq to a Raft log entry. The common case for this is when a user request
* needs to block until it gets committed, and only then a reply should be produced.
*
* To do that, we link the RaftReq to the Raft log entry and keep the client blocked.
* When the entry will later reach the apply flow, the linkage to the RaftReq will
* make it possible to generate the reply to the user.
*/
static void entryAttachRaftReq(RedisRaftCtx *rr, raft_entry_t *entry, RaftReq *req)
{
entry->user_data = req;
entry->free_func = entryFreeAttachedRaftReq;
rr->client_attached_entries++;
}
/* ------------------------------------ RaftRedisCommand ------------------------------------ */
/* ---------------------- RAFT MULTI/EXEC Handlig ---------------------------- */
/* There are several concerns about MULTI/EXEC Handling:
*
* 1. We want to make sure that the commands are executed atomically across all
* cluster nodes. To do this, we need to pack them as a single Raft log entry.
* 2. When executing the MULTI/EXEC we don't really need to wrap it because Redis
* wraps all module commands in MULTI/EXEC (although no harm is done).
* 3. The MULTI/EXEC wrapping also ensures that any WATCHed keys will fail the
* transaction. We do have to be careful though and never proxy such operations
* to a leader, as we don't synchronize WATCH. (Note: we should also avoid
* proxying WATCH commands of course).
*/
/* ------------------------------------ Log Execution ------------------------------------ */
/* Execute all commands in a specified RaftRedisCommandArray.
*
* The commands are executed on ctx, which can be a real or thread-safe
* context. Caller is responsible to hold the lock.
*
* If reply_ctx is non-NULL, replies are delivered to it.
* Otherwise no replies are delivered.
*/
static void executeRaftRedisCommandArray(RaftRedisCommandArray *array,
RedisModuleCtx *ctx, RedisModuleCtx *reply_ctx)
{
int i;
for (i = 0; i < array->len; i++) {
RaftRedisCommand *c = array->commands[i];
size_t cmdlen;
const char *cmd = RedisModule_StringPtrLen(c->argv[0], &cmdlen);
/* We need to handle MULTI as a special case:
* 1. Skip the command (no need to execute MULTI in a Module context).
* 2. If we're returning a response, group it as an array (multibulk).
*/
if (i == 0 && cmdlen == 5 && !strncasecmp(cmd, "MULTI", 5)) {
if (reply_ctx) {
RedisModule_ReplyWithArray(reply_ctx, array->len - 1);
}
continue;
}
enterRedisModuleCall();
RedisModuleCallReply *reply = RedisModule_Call(
ctx, cmd, redis_raft.resp_call_fmt, &c->argv[1], c->argc - 1);
int ret_errno = errno;
exitRedisModuleCall();
if (reply_ctx) {
if (reply) {
RedisModule_ReplyWithCallReply(reply_ctx, reply);
} else {
/* Try to produce an error message which is similar to Redis */
int trunc_cmdlen = cmdlen > 256 ? 256 : cmdlen;
size_t errmsg_len = 128 + trunc_cmdlen; /* Big enough for msg + cmd */
char *errmsg = RedisModule_Alloc(errmsg_len);
switch (ret_errno) {
case ENOENT:
snprintf(errmsg, errmsg_len, "ERR unknown command `%.*s`", trunc_cmdlen, cmd);
break;
case EINVAL:
snprintf(errmsg, errmsg_len, "ERR wrong number of arguments for '%.*s' command",
trunc_cmdlen, cmd);
break;
default:
snprintf(errmsg, errmsg_len, "ERR failed to execute command '%.*s'",
trunc_cmdlen, cmd);
}
RedisModule_ReplyWithError(reply_ctx, errmsg);
RedisModule_Free(errmsg);
}
}
if (reply) {
RedisModule_FreeCallReply(reply);
}
}
}
/*
* Execution of Raft log on the local instance.
*
* There are two variants:
* 1) Execution of a raft entry received from another node.
* 2) Execution of a locally initiated command.
*/
static void executeLogEntry(RedisRaftCtx *rr, raft_entry_t *entry, raft_index_t entry_idx)
{
assert(entry->type == RAFT_LOGTYPE_NORMAL);
/* TODO: optimize and avoid deserialization here, we can use the
* original argv in RaftReq
*/
RaftRedisCommandArray entry_cmds = { 0 };
if (RaftRedisCommandArrayDeserialize(&entry_cmds, entry->data, entry->data_len) != RR_OK) {
PANIC("Invalid Raft entry");
}
RaftReq *req = entry->user_data;
RedisModuleCtx *ctx = req ? req->ctx : rr->ctx;
/* Redis Module API requires commands executing on a locked thread
* safe context.
*/
RedisModule_ThreadSafeContextLock(ctx);
executeRaftRedisCommandArray(&entry_cmds, ctx, req? req->ctx : NULL);
/* Update snapshot info in Redis dataset. This must be done now so it's
* always consistent with what we applied and we never end up applying
* an entry onto a snapshot where it was applied already.
*/
rr->snapshot_info.last_applied_term = entry->term;
rr->snapshot_info.last_applied_idx = entry_idx;
RedisModule_ThreadSafeContextUnlock(ctx);
RaftRedisCommandArrayFree(&entry_cmds);
if (req) {
/* Free request now, we don't need it anymore */
entryDetachRaftReq(rr, entry);
RaftReqFree(req);
}
}
static void raftSendNodeShutdown(raft_node_t *raft_node)
{
if (!raft_node) {
return;
}
Node *node = raft_node_get_udata(raft_node);
if (!node) {
return;
}
if (!ConnIsConnected(node->conn)) {
NODE_TRACE(node, "not connected, state=%s", ConnGetStateStr(node->conn));
return;
}
if (redisAsyncCommand(ConnGetRedisCtx(node->conn), NULL, NULL,
"RAFT.NODESHUTDOWN %d",
(int) raft_node_get_id(raft_node)) != REDIS_OK) {
NODE_TRACE(node, "failed to send raft.nodeshutdown");
}
}
/* ------------------------------------ RequestVote ------------------------------------ */
static void handleRequestVoteResponse(redisAsyncContext *c, void *r, void *privdata)
{
Node *node = privdata;
RedisRaftCtx *rr = node->rr;
redisReply *reply = r;
NodeDismissPendingResponse(node);
if (!reply) {
NODE_LOG_DEBUG(node, "RAFT.REQUESTVOTE failed: connection dropped.");
ConnMarkDisconnected(node->conn);
return;
}
if (reply->type == REDIS_REPLY_ERROR) {
NODE_LOG_DEBUG(node, "RAFT.REQUESTVOTE error: %s", reply->str);
return;
}
if (reply->type != REDIS_REPLY_ARRAY || reply->elements != 4 ||
reply->element[0]->type != REDIS_REPLY_INTEGER ||
reply->element[1]->type != REDIS_REPLY_INTEGER ||
reply->element[2]->type != REDIS_REPLY_INTEGER ||
reply->element[3]->type != REDIS_REPLY_INTEGER) {
NODE_LOG_ERROR(node, "invalid RAFT.REQUESTVOTE reply");
return;
}
msg_requestvote_response_t response = {
.prevote = reply->element[0]->integer,
.request_term = reply->element[1]->integer,
.term = reply->element[2]->integer,
.vote_granted = reply->element[3]->integer
};
raft_node_t *raft_node = raft_get_node(rr->raft, node->id);
if (!raft_node) {
NODE_LOG_DEBUG(node, "RAFT.REQUESTVOTE stale reply.");
return;
}
int ret;
if ((ret = raft_recv_requestvote_response(
rr->raft,
raft_node,
&response)) != 0) {
TRACE("raft_recv_requestvote_response failed, error %d", ret);
}
}
static int raftSendRequestVote(raft_server_t *raft, void *user_data,
raft_node_t *raft_node, msg_requestvote_t *msg)
{
Node *node = (Node *) raft_node_get_udata(raft_node);
if (!ConnIsConnected(node->conn)) {
NODE_TRACE(node, "not connected, state=%s", ConnGetStateStr(node->conn));
return 0;
}
/* RAFT.REQUESTVOTE <src_node_id> <term> <candidate_id> <last_log_idx> <last_log_term> */
if (redisAsyncCommand(ConnGetRedisCtx(node->conn), handleRequestVoteResponse,
node, "RAFT.REQUESTVOTE %d %d %d:%ld:%d:%ld:%ld:%d",
raft_node_get_id(raft_node),
raft_get_nodeid(raft),
msg->prevote,
msg->term,
msg->candidate_id,
msg->last_log_idx,
msg->last_log_term,
msg->transfer_leader) != REDIS_OK) {
NODE_TRACE(node, "failed requestvote");
} else {
NodeAddPendingResponse(node, false);
}
return 0;
}
/* ------------------------------------ AppendEntries ------------------------------------ */
static void handleAppendEntriesResponse(redisAsyncContext *c, void *r, void *privdata)
{
Node *node = privdata;
RedisRaftCtx *rr = node->rr;
NodeDismissPendingResponse(node);
redisReply *reply = r;
if (!reply) {
NODE_TRACE(node, "RAFT.AE failed: connection dropped.");
ConnMarkDisconnected(node->conn);
return;
}
if (reply->type == REDIS_REPLY_ERROR) {
NODE_TRACE(node, "RAFT.AE error: %s", reply->str);
return;
}
if (reply->type != REDIS_REPLY_ARRAY || reply->elements != 4 ||
reply->element[0]->type != REDIS_REPLY_INTEGER ||
reply->element[1]->type != REDIS_REPLY_INTEGER ||
reply->element[2]->type != REDIS_REPLY_INTEGER ||
reply->element[3]->type != REDIS_REPLY_INTEGER) {
NODE_LOG_ERROR(node, "invalid RAFT.AE reply");
return;
}
msg_appendentries_response_t response = {
.term = reply->element[0]->integer,
.success = reply->element[1]->integer,
.current_idx = reply->element[2]->integer,
.msg_id = reply->element[3]->integer
};
raft_node_t *raft_node = raft_get_node(rr->raft, node->id);
int ret;
if ((ret = raft_recv_appendentries_response(
rr->raft,
raft_node,
&response)) != 0) {
NODE_TRACE(node, "raft_recv_appendentries_response failed, error %d", ret);
}
/* Maybe we have pending stuff to apply now */
raft_apply_all(rr->raft);
raft_process_read_queue(rr->raft);
}
static int raftSendAppendEntries(raft_server_t *raft, void *user_data,
raft_node_t *raft_node, msg_appendentries_t *msg)
{
Node *node = (Node *) raft_node_get_udata(raft_node);
int argc = 5 + msg->n_entries * 2;
char **argv = NULL;
size_t *argvlen = NULL;
if (!ConnIsConnected(node->conn)) {
NODE_TRACE(node, "not connected, state=%s", ConnGetStateStr(node->conn));
return 0;
}
argv = RedisModule_Alloc(sizeof(argv[0]) * argc);
argvlen = RedisModule_Alloc(sizeof(argvlen[0]) * argc);
char target_node_str[12];
char source_node_str[12];
char msg_str[100];
char nentries_str[12];
argv[0] = "RAFT.AE";
argvlen[0] = strlen(argv[0]);
argv[1] = target_node_str;
argvlen[1] = snprintf(target_node_str, sizeof(target_node_str)-1, "%d", raft_node_get_id(raft_node));
argv[2] = source_node_str;
argvlen[2] = snprintf(source_node_str, sizeof(source_node_str)-1, "%d", raft_get_nodeid(raft));
argv[3] = msg_str;
argvlen[3] = snprintf(msg_str, sizeof(msg_str)-1, "%d:%ld:%ld:%ld:%ld:%lu",
msg->leader_id,
msg->term,
msg->prev_log_idx,
msg->prev_log_term,
msg->leader_commit,
msg->msg_id);
argv[4] = nentries_str;
argvlen[4] = snprintf(nentries_str, sizeof(nentries_str)-1, "%d", msg->n_entries);
int i;
for (i = 0; i < msg->n_entries; i++) {
raft_entry_t *e = msg->entries[i];
argv[5 + i*2] = RedisModule_Alloc(64);
argvlen[5 + i*2] = snprintf(argv[5 + i*2], 63, "%ld:%d:%d", e->term, e->id, e->type);
argvlen[6 + i*2] = e->data_len;
argv[6 + i*2] = e->data;
}
if (redisAsyncCommandArgv(ConnGetRedisCtx(node->conn), handleAppendEntriesResponse,
node, argc, (const char **)argv, argvlen) != REDIS_OK) {
NODE_TRACE(node, "failed appendentries");
} else{
NodeAddPendingResponse(node, false);
}
for (i = 0; i < msg->n_entries; i++) {
RedisModule_Free(argv[5 + i*2]);
}
RedisModule_Free(argv);
RedisModule_Free(argvlen);
return 0;
}
/* ------------------------------------ Timeout Follower --------------------------------- */
static void handleTimeoutNowResponse(redisAsyncContext *c, void *r, void *privdata)
{
Node *node = privdata;
//RedisRaftCtx *rr = node->rr;
NodeDismissPendingResponse(node);
redisReply *reply = r;
if (!reply) {
NODE_TRACE(node, "RAFT.TIMEOUT_NOW failed: connection dropped.");
ConnMarkDisconnected(node->conn);
return;
}
if (reply->type == REDIS_REPLY_ERROR) {
NODE_TRACE(node, "RAFT.TIMEOUT_NOW error: %s", reply->str);
return;
}
if (reply->type != REDIS_REPLY_STATUS || strcmp("OK", reply->str)) {
NODE_LOG_ERROR(node, "invalid RAFT.TIMEOUT_NOW reply");
return;
}
}
static int raftSendTimeoutNow(raft_server_t *raft, raft_node_t *raft_node)
{
Node *node = raft_node_get_udata(raft_node);
if (!ConnIsConnected(node->conn)) {
NODE_TRACE(node, "not connected, state=%s", ConnGetStateStr(node->conn));
return 0;
}
if (redisAsyncCommand(ConnGetRedisCtx(node->conn), handleTimeoutNowResponse,
node, "RAFT.TIMEOUT_NOW") != REDIS_OK) {
NODE_TRACE(node, "failed timeout now");
} else {
NodeAddPendingResponse(node, false);
}
return 0;
}
/* ------------------------------------ Log Callbacks ------------------------------------ */
static int raftPersistVote(raft_server_t *raft, void *user_data, raft_node_id_t vote)
{
RedisRaftCtx *rr = (RedisRaftCtx *) user_data;
if (!rr->log || rr->state == REDIS_RAFT_LOADING) {
return 0;
}
if (RaftLogSetVote(rr->log, vote) != RR_OK) {
LOG_ERROR("ERROR: RaftLogSetVote");
return RAFT_ERR_SHUTDOWN;
}
return 0;
}
static int raftPersistTerm(raft_server_t *raft, void *user_data, raft_term_t term, raft_node_id_t vote)
{
RedisRaftCtx *rr = (RedisRaftCtx *) user_data;
if (!rr->log || rr->state == REDIS_RAFT_LOADING) {
return 0;
}
if (RaftLogSetTerm(rr->log, term, vote) != RR_OK) {
LOG_ERROR("ERROR: RaftLogSetTerm");
return RAFT_ERR_SHUTDOWN;
}
return 0;
}
static int raftApplyLog(raft_server_t *raft, void *user_data, raft_entry_t *entry, raft_index_t entry_idx)
{
RedisRaftCtx *rr = user_data;
RaftCfgChange *req;
RaftReq *raftReq;
switch (entry->type) {
case RAFT_LOGTYPE_REMOVE_NODE:
raftReq = entryDetachRaftReq(rr, entry);
req = (RaftCfgChange *) entry->data;
// unblock client on removal of node, if this is the node it was submitted on
if (raftReq) {
RedisModule_ReplyWithSimpleString(raftReq->ctx, "OK");
RaftReqFree(raftReq);
}
if (req->id == raft_get_nodeid(raft)) {
// doesn't matter to unblock leader on removal, as node will exit anyways
LOG_DEBUG("Removing this node from the cluster");
return RAFT_ERR_SHUTDOWN;
}
if (raft_is_leader(raft)) {
raftSendNodeShutdown(raft_get_node(raft, req->id));
}
break;
case RAFT_LOGTYPE_NORMAL:
executeLogEntry(rr, entry, entry_idx);
break;
case RAFT_LOGTYPE_ADD_SHARDGROUP:
case RAFT_LOGTYPE_UPDATE_SHARDGROUP:
applyShardGroupChange(rr, entry);
default:
break;
}
rr->snapshot_info.last_applied_term = entry->term;
rr->snapshot_info.last_applied_idx = entry_idx;
return 0;
}
/* ------------------------------------ Utility Callbacks ------------------------------------ */
static void raftLog(raft_server_t *raft, raft_node_id_t node, void *user_data, const char *buf)
{
raft_node_t* raft_node = raft_get_node(raft, node);
if (raft_node) {
Node *n = raft_node_get_udata(raft_node);
if (n) {
NODE_TRACE(n, "<raftlib> %s", buf);
return;
}
}
TRACE("<raftlib> %s", buf);
}
static raft_node_id_t raftLogGetNodeId(raft_server_t *raft, void *user_data, raft_entry_t *entry,
raft_index_t entry_idx)
{
RaftCfgChange *req = (RaftCfgChange *) entry->data;
return req->id;
}
static int raftNodeHasSufficientLogs(raft_server_t *raft, void *user_data, raft_node_t *raft_node)
{
RedisRaftCtx *rr = (RedisRaftCtx *) user_data;
if (rr->state == REDIS_RAFT_LOADING)
return 0;
/* Node may have sufficient logs to be promoted but be scheduled for
* removal at the same time (i.e. RAFT_LOGTYPE_REMOVE_NODE already created
* for its removal).
*
* In this case we don't want to create a promotion entry as it will
* result with an unexpected state transition.
*
* We return -1 so we *WILL* get a chance to be notified again. For
* example, if the removal entry is rolled back and the node becomes
* active again.
*/
if (!raft_node_is_active(raft_node)) {
return -1;
}
Node *node = raft_node_get_udata(raft_node);
assert (node != NULL);
TRACE("node:%d has sufficient logs now, adding as voting node.", node->id);
raft_entry_t *entry = raft_entry_new(sizeof(RaftCfgChange));
entry->id = rand();
entry->type = RAFT_LOGTYPE_ADD_NODE;
msg_entry_response_t response;
RaftCfgChange *cfgchange = (RaftCfgChange *) entry->data;
cfgchange->id = node->id;
cfgchange->addr = node->addr;
int e = raft_recv_entry(raft, entry, &response);
assert(e == 0);
raft_entry_release(entry);
return 0;
}
void raftNotifyMembershipEvent(raft_server_t *raft, void *user_data, raft_node_t *raft_node,
raft_entry_t *entry, raft_membership_e type)
{
RedisRaftCtx *rr = (RedisRaftCtx *) user_data;
RaftCfgChange *cfgchange;
raft_node_id_t my_id = raft_get_nodeid(raft);
Node *node;
switch (type) {
case RAFT_MEMBERSHIP_ADD:
/* When raft_add_node() is called explicitly, we get no entry so we
* have nothing to do.
*/
if (!entry) {
addUsedNodeId(rr, my_id);
break;
}
/* Ignore our own node, as we don't maintain a Node structure for it */
assert(entry->type == RAFT_LOGTYPE_ADD_NODE || entry->type == RAFT_LOGTYPE_ADD_NONVOTING_NODE);
cfgchange = (RaftCfgChange *) entry->data;
if (cfgchange->id == my_id) {
break;
}
/* Allocate a new node */
node = NodeCreate(rr, cfgchange->id, &cfgchange->addr);
assert(node != NULL);
addUsedNodeId(rr, cfgchange->id);
raft_node_set_udata(raft_node, node);
break;
case RAFT_MEMBERSHIP_REMOVE:
node = raft_node_get_udata(raft_node);
if (node != NULL) {
ConnAsyncTerminate(node->conn);
raft_node_set_udata(raft_node, NULL);
}
break;
default:
assert(0);
}
}
static char *raftMembershipInfoString(raft_server_t *raft)
{
size_t buflen = 1024;
char *buf = RedisModule_Calloc(1, buflen);
int i;
buf = catsnprintf(buf, &buflen, "term:%ld index:%ld nodes:",
raft_get_current_term(raft),
raft_get_current_idx(raft));
for (i = 0; i < raft_get_num_nodes(raft); i++) {
raft_node_t *rn = raft_get_node_from_idx(raft, i);
Node *n = raft_node_get_udata(rn);
char addr[512];
if (n) {
snprintf(addr, sizeof(addr) - 1, "%s:%u",
n->addr.host, n->addr.port);
} else {
addr[0] = '-';
addr[1] = '\0';
}
buf = catsnprintf(buf, &buflen, " id=%d,voting=%d,active=%d,addr=%s",
raft_node_get_id(rn),
raft_node_is_voting(rn),
raft_node_is_active(rn),
addr);
}
return buf;
}
static void handleTransferLeaderComplete(raft_server_t *raft, raft_transfer_state_e state);
/* just keep libraft callbacks together
* so this just calls the redisraft RaftReq compleition function, which is kept together with its functions
*/
static void raftNotifyTransferEvent(raft_server_t *raft, void *user_data, raft_transfer_state_e state)
{
handleTransferLeaderComplete(raft, state);
}
static void raftNotifyStateEvent(raft_server_t *raft, void *user_data, raft_state_e state)
{
switch (state) {
case RAFT_STATE_FOLLOWER:
LOG_INFO("State change: Node is now a follower, term %ld",
raft_get_current_term(raft));
break;
case RAFT_STATE_PRECANDIDATE:
LOG_INFO("State change: Election starting, node is now a pre-candidate, term %ld",
raft_get_current_term(raft));
break;
case RAFT_STATE_CANDIDATE:
LOG_INFO("State change: Node is now a candidate, term %ld",
raft_get_current_term(raft));
break;
case RAFT_STATE_LEADER:
LOG_INFO("State change: Node is now a leader, term %ld",
raft_get_current_term(raft));
break;
default:
break;
}
char *s = raftMembershipInfoString(raft);
LOG_INFO("Cluster Membership: %s", s);
RedisModule_Free(s);
}
raft_cbs_t redis_raft_callbacks = {
.send_requestvote = raftSendRequestVote,
.send_appendentries = raftSendAppendEntries,
.persist_vote = raftPersistVote,
.persist_term = raftPersistTerm,
.log = raftLog,
.get_node_id = raftLogGetNodeId,
.applylog = raftApplyLog,
.node_has_sufficient_logs = raftNodeHasSufficientLogs,
.send_snapshot = raftSendSnapshot,
.load_snapshot = raftLoadSnapshot,
.clear_snapshot = raftClearSnapshot,
.get_snapshot_chunk = raftGetSnapshotChunk,
.store_snapshot_chunk = raftStoreSnapshotChunk,
.notify_membership_event = raftNotifyMembershipEvent,
.notify_state_event = raftNotifyStateEvent,
.send_timeoutnow = raftSendTimeoutNow,
.notify_transfer_event = raftNotifyTransferEvent,
};
/* ------------------------------------ Raft Thread ------------------------------------ */
/*
* Handling of the Redis Raft context, including its own thread and
* async I/O loop.
*/
RRStatus applyLoadedRaftLog(RedisRaftCtx *rr)
{
/* Make sure the log we're going to apply matches the RDB we've loaded */
if (rr->snapshot_info.loaded) {
if (strcmp(rr->snapshot_info.dbid, rr->log->dbid)) {
PANIC("Log and snapshot have different dbids: [log=%s/snapshot=%s]",
rr->log->dbid, rr->snapshot_info.dbid);
}
if (rr->snapshot_info.last_applied_term < rr->log->snapshot_last_term) {
PANIC("Log term (%lu) does not match snapshot term (%lu), aborting.",
rr->log->snapshot_last_term, rr->snapshot_info.last_applied_term);
}
if (rr->snapshot_info.last_applied_idx + 1 < rr->log->snapshot_last_idx) {
PANIC("Log initial index (%lu) does not match snapshot last index (%lu), aborting.",
rr->log->snapshot_last_idx, rr->snapshot_info.last_applied_idx);
}
} else {
/* If there is no snapshot, the log should also not refer to it */
if (rr->log->snapshot_last_idx) {
PANIC("Log refers to snapshot (term=%lu/index=%lu which was not loaded, aborting.",
rr->log->snapshot_last_term, rr->log->snapshot_last_idx);
}
}
/* Reset the log if snapshot is more advanced */
if (RaftLogCurrentIdx(rr->log) < rr->snapshot_info.last_applied_idx) {
RaftLogImpl.reset(rr, rr->snapshot_info.last_applied_idx + 1,
rr->snapshot_info.last_applied_term);
}
/* Special case: if no other nodes, set commit index to the latest
* entry in the log.
*/
if (raft_get_num_voting_nodes(rr->raft) == 1 || raft_get_num_nodes(rr->raft) == 1) {
LOG_DEBUG("No other voting nodes, setting commit index to %ld",
raft_get_current_idx(rr->raft));
raft_set_commit_idx(rr->raft, raft_get_current_idx(rr->raft));
} else {
raft_set_commit_idx(rr->raft, rr->snapshot_info.last_applied_idx);
}
memcpy(rr->snapshot_info.dbid, rr->log->dbid, RAFT_DBID_LEN);
rr->snapshot_info.dbid[RAFT_DBID_LEN] = '\0';
raft_set_snapshot_metadata(rr->raft, rr->snapshot_info.last_applied_term,
rr->snapshot_info.last_applied_idx);
raft_apply_all(rr->raft);
raft_set_current_term(rr->raft, rr->log->term);
raft_vote_for_nodeid(rr->raft, rr->log->vote);
LOG_INFO("Raft Log: loaded current term=%lu, vote=%d", rr->log->term, rr->log->vote);
LOG_INFO("Raft state after applying log: log_count=%lu, current_idx=%lu, last_applied_idx=%lu",
raft_get_log_count(rr->raft),
raft_get_current_idx(rr->raft),
raft_get_last_applied_idx(rr->raft));
return RR_OK;
}
/* Check if Redis is loading an RDB file */
static bool checkRedisLoading(RedisRaftCtx *rr)
{
char *val = RedisInfoGetParam(rr, "persistence", "loading");
assert(val != NULL);
bool loading = (!strcmp(val, "1"));
RedisModule_Free(val);
return loading;
}
RRStatus loadRaftLog(RedisRaftCtx *rr);
static void handleLoadingState(RedisRaftCtx *rr)
{
if (!checkRedisLoading(rr)) {
/* If Redis loaded a snapshot (RDB), log some information and configure the
* raft library as necessary.
*/
LOG_INFO("Loading: Redis loading complete, snapshot %s",
rr->snapshot_info.loaded ? "LOADED" : "NOT LOADED");
/* If id is configured, confirm the log matches. If not, we set it from
* the log.
*/
if (!rr->config->id) {
rr->config->id = rr->log->node_id;
} else {
if (rr->config->id != rr->log->node_id) {
PANIC("Raft log node id [%d] does not match configured id [%d]",
rr->log->node_id, rr->config->id);
}
}
initRaftLibrary(rr);
raft_node_t *self = raft_add_non_voting_node(rr->raft, NULL, rr->config->id, 1);
if (!self) {
PANIC("Failed to create local Raft node [id %d]", rr->config->id);
}
initSnapshotTransferData(rr);
if (rr->snapshot_info.loaded) {
createOutgoingSnapshotMmap(rr);
configureFromSnapshot(rr);
}
if (loadRaftLog(rr) == RR_OK) {
if (rr->log->snapshot_last_term) {
LOG_INFO("Loading: Log starts from snapshot term=%lu, index=%lu",
rr->log->snapshot_last_term, rr->log->snapshot_last_idx);
} else {
LOG_INFO("Loading: Log is complete.");
}
applyLoadedRaftLog(rr);
rr->state = REDIS_RAFT_UP;
} else {
rr->state = REDIS_RAFT_UNINITIALIZED;
}
}
}
static void callRaftPeriodic(uv_timer_t *handle)
{
RedisRaftCtx *rr = (RedisRaftCtx *) uv_handle_get_data((uv_handle_t *) handle);
int ret;
if (processExiting) {
return;
}
/* If we're in LOADING state, we need to wait for Redis to finish loading before
* we can apply the log.
*/
if (rr->state == REDIS_RAFT_LOADING) {
handleLoadingState(rr);
}
/* Proceed only if we're initialized */
if (rr->state != REDIS_RAFT_UP) {
return;
}
/* If we're creating a persistent snapshot, check if we're done */
if (rr->snapshot_in_progress) {
SnapshotResult sr;
ret = pollSnapshotStatus(rr, &sr);
if (ret == -1) {
LOG_ERROR("Snapshot operation failed, cancelling.");
cancelSnapshot(rr, &sr);
} else if (ret) {
LOG_DEBUG("Snapshot operation completed successfully.");
finalizeSnapshot(rr, &sr);
} /* else we're still in progress */
}
ret = raft_periodic(rr->raft, rr->config->raft_interval);
if (ret == 0) {
ret = raft_apply_all(rr->raft);
}
if (ret == RAFT_ERR_SHUTDOWN) {
LOG_INFO("*** NODE REMOVED, SHUTTING DOWN.");
if (rr->config->raft_log_filename)
RaftLogArchiveFiles(rr);
if (rr->config->rdb_filename)
archiveSnapshot(rr);
exit(0);
}
assert(ret == 0);
/* Compact cache */
if (rr->config->raft_log_max_cache_size) {
EntryCacheCompact(rr->logcache, rr->config->raft_log_max_cache_size);
}
/* Initiate snapshot if log size exceeds raft-log-file-max */
if (!rr->snapshot_in_progress && rr->config->raft_log_max_file_size &&
raft_get_num_snapshottable_logs(rr->raft) > 0 &&
rr->log->file_size > rr->config->raft_log_max_file_size) {
LOG_DEBUG("Raft log file size is %lu, initiating snapshot.",
rr->log->file_size);
initiateSnapshot(rr);
}
/* Call cluster */
if (rr->config->sharding) {
ShardingPeriodicCall(rr);
}
}
/* A libuv callback that invokes HandleNodeStates(), to handle node connection
* management (reconnects, etc.).
*/
static void callHandleNodeStates(uv_timer_t *handle)
{
RedisRaftCtx *rr = (RedisRaftCtx *) uv_handle_get_data((uv_handle_t *) handle);
if (processExiting) {
return;
}
HandleIdleConnections(rr);
HandleNodeStates(rr);
}