This repository was archived by the owner on Mar 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathreplication.c
1581 lines (1331 loc) · 46.2 KB
/
replication.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
#include <string.h>
#include "assert.h"
#include "configuration.h"
#include "convert.h"
#include "entry.h"
#ifdef __GLIBC__
#include "error.h"
#endif
#include "err.h"
#include "heap.h"
#include "log.h"
#include "membership.h"
#include "progress.h"
#include "queue.h"
#include "replication.h"
#include "request.h"
#include "snapshot.h"
#include "tracing.h"
/* Set to 1 to enable tracing. */
#if 0
#define tracef(...) Tracef(r->tracer, __VA_ARGS__)
#else
#define tracef(...)
#endif
#ifndef max
#define max(a, b) ((a) < (b) ? (b) : (a))
#endif
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
/* Context of a RAFT_IO_APPEND_ENTRIES request that was submitted with
* raft_io_>send(). */
struct sendAppendEntries
{
struct raft *raft; /* Instance sending the entries. */
struct raft_io_send send; /* Underlying I/O send request. */
raft_index index; /* Index of the first entry in the request. */
struct raft_entry *entries; /* Entries referenced in the request. */
unsigned n; /* Length of the entries array. */
raft_id server_id; /* Destination server. */
};
/* Callback invoked after request to send an AppendEntries RPC has completed. */
static void sendAppendEntriesCb(struct raft_io_send *send, const int status)
{
struct sendAppendEntries *req = send->data;
struct raft *r = req->raft;
unsigned i = configurationIndexOf(&r->configuration, req->server_id);
if (r->state == RAFT_LEADER && i < r->configuration.n) {
if (status != 0) {
tracef("failed to send append entries to server %u: %s",
req->server_id, raft_strerror(status));
/* Go back to probe mode. */
progressToProbe(r, i);
}
}
/* Tell the log that we're done referencing these entries. */
logRelease(&r->log, req->index, req->entries, req->n);
raft_free(req);
}
/* Send an AppendEntries message to the i'th server, including all log entries
* from the given point onwards. */
static int sendAppendEntries(struct raft *r,
const unsigned i,
const raft_index prev_index,
const raft_term prev_term)
{
struct raft_server *server = &r->configuration.servers[i];
struct raft_message message;
struct raft_append_entries *args = &message.append_entries;
struct sendAppendEntries *req;
raft_index next_index = prev_index + 1;
int rv;
args->term = r->current_term;
args->prev_log_index = prev_index;
args->prev_log_term = prev_term;
/* TODO: implement a limit to the total size of the entries being sent */
rv = logAcquire(&r->log, next_index, &args->entries, &args->n_entries);
if (rv != 0) {
goto err;
}
/* From Section 3.5:
*
* The leader keeps track of the highest index it knows to be committed,
* and it includes that index in future AppendEntries RPCs (including
* heartbeats) so that the other servers eventually find out. Once a
* follower learns that a log entry is committed, it applies the entry to
* its local state machine (in log order)
*/
args->leader_commit = r->commit_index;
tracef("send %u entries starting at %llu to server %u (last index %llu)",
args->n_entries, args->prev_log_index, server->id,
logLastIndex(&r->log));
message.type = RAFT_IO_APPEND_ENTRIES;
message.server_id = server->id;
message.server_address = server->address;
req = raft_malloc(sizeof *req);
if (req == NULL) {
rv = RAFT_NOMEM;
goto err_after_entries_acquired;
}
req->raft = r;
req->index = args->prev_log_index + 1;
req->entries = args->entries;
req->n = args->n_entries;
req->server_id = server->id;
req->send.data = req;
rv = r->io->send(r->io, &req->send, &message, sendAppendEntriesCb);
if (rv != 0) {
goto err_after_req_alloc;
}
if (progressState(r, i) == PROGRESS__PIPELINE) {
/* Optimistically update progress. */
progressOptimisticNextIndex(r, i, req->index + req->n);
}
progressUpdateLastSend(r, i);
return 0;
err_after_req_alloc:
raft_free(req);
err_after_entries_acquired:
logRelease(&r->log, next_index, args->entries, args->n_entries);
err:
assert(rv != 0);
return rv;
}
/* Context of a RAFT_IO_INSTALL_SNAPSHOT request that was submitted with
* raft_io_>send(). */
struct sendInstallSnapshot
{
struct raft *raft; /* Instance sending the snapshot. */
struct raft_io_snapshot_get get; /* Snapshot get request. */
struct raft_io_send send; /* Underlying I/O send request. */
struct raft_snapshot *snapshot; /* Snapshot to send. */
raft_id server_id; /* Destination server. */
};
static void sendInstallSnapshotCb(struct raft_io_send *send, int status)
{
struct sendInstallSnapshot *req = send->data;
struct raft *r = req->raft;
const struct raft_server *server;
server = configurationGet(&r->configuration, req->server_id);
if (status != 0) {
tracef("send install snapshot: %s", raft_strerror(status));
if (r->state == RAFT_LEADER && server != NULL) {
unsigned i;
i = configurationIndexOf(&r->configuration, req->server_id);
progressAbortSnapshot(r, i);
}
}
snapshotClose(req->snapshot);
raft_free(req->snapshot);
raft_free(req);
}
static void sendSnapshotGetCb(struct raft_io_snapshot_get *get,
struct raft_snapshot *snapshot,
int status)
{
struct sendInstallSnapshot *req = get->data;
struct raft *r = req->raft;
struct raft_message message;
struct raft_install_snapshot *args = &message.install_snapshot;
const struct raft_server *server = NULL;
bool progress_state_is_snapshot = false;
unsigned i = 0;
int rv;
if (status != 0) {
tracef("get snapshot %s", raft_strerror(status));
goto abort;
}
if (r->state != RAFT_LEADER) {
goto abort_with_snapshot;
}
server = configurationGet(&r->configuration, req->server_id);
if (server == NULL) {
/* Probably the server was removed in the meantime. */
goto abort_with_snapshot;
}
i = configurationIndexOf(&r->configuration, req->server_id);
progress_state_is_snapshot = progressState(r, i) == PROGRESS__SNAPSHOT;
if (!progress_state_is_snapshot) {
/* Something happened in the meantime. */
goto abort_with_snapshot;
}
assert(snapshot->n_bufs == 1);
message.type = RAFT_IO_INSTALL_SNAPSHOT;
message.server_id = server->id;
message.server_address = server->address;
args->term = r->current_term;
args->last_index = snapshot->index;
args->last_term = snapshot->term;
args->conf_index = snapshot->configuration_index;
args->conf = snapshot->configuration;
args->data = snapshot->bufs[0];
req->snapshot = snapshot;
req->send.data = req;
tracef("sending snapshot with last index %llu to %u", snapshot->index,
server->id);
rv = r->io->send(r->io, &req->send, &message, sendInstallSnapshotCb);
if (rv != 0) {
goto abort_with_snapshot;
}
goto out;
abort_with_snapshot:
snapshotClose(snapshot);
raft_free(snapshot);
abort:
if (r->state == RAFT_LEADER && server != NULL &&
progress_state_is_snapshot) {
progressAbortSnapshot(r, i);
}
raft_free(req);
out:
return;
}
/* Send the latest snapshot to the i'th server */
static int sendSnapshot(struct raft *r, const unsigned i)
{
struct raft_server *server = &r->configuration.servers[i];
struct sendInstallSnapshot *request;
int rv;
progressToSnapshot(r, i);
request = raft_malloc(sizeof *request);
if (request == NULL) {
rv = RAFT_NOMEM;
goto err;
}
request->raft = r;
request->server_id = server->id;
request->get.data = request;
/* TODO: make sure that the I/O implementation really returns the latest
* snapshot *at this time* and not any snapshot that might be stored at a
* later point. Otherwise the progress snapshot_index would be wrong. */
rv = r->io->snapshot_get(r->io, &request->get, sendSnapshotGetCb);
if (rv != 0) {
goto err_after_req_alloc;
}
progressUpdateSnapshotLastSend(r, i);
return 0;
err_after_req_alloc:
raft_free(request);
err:
progressAbortSnapshot(r, i);
assert(rv != 0);
return rv;
}
int replicationProgress(struct raft *r, unsigned i)
{
struct raft_server *server = &r->configuration.servers[i];
bool progress_state_is_snapshot = progressState(r, i) == PROGRESS__SNAPSHOT;
raft_index snapshot_index = logSnapshotIndex(&r->log);
raft_index next_index = progressNextIndex(r, i);
raft_index prev_index;
raft_term prev_term;
assert(r->state == RAFT_LEADER);
assert(server->id != r->id);
assert(next_index >= 1);
if (!progressShouldReplicate(r, i)) {
return 0;
}
/* From Section 3.5:
*
* When sending an AppendEntries RPC, the leader includes the index and
* term of the entry in its log that immediately precedes the new
* entries. If the follower does not find an entry in its log with the
* same index and term, then it refuses the new entries. The consistency
* check acts as an induction step: the initial empty state of the logs
* satisfies the Log Matching Property, and the consistency check
* preserves the Log Matching Property whenever logs are extended. As a
* result, whenever AppendEntries returns successfully, the leader knows
* that the follower's log is identical to its own log up through the new
* entries (Log Matching Property in Figure 3.2).
*/
if (next_index == 1) {
/* We're including the very first entry, so prevIndex and prevTerm are
* null. If the first entry is not available anymore, send the last
* snapshot if we're not already sending one. */
if (snapshot_index > 0 && !progress_state_is_snapshot) {
raft_index last_index = logLastIndex(&r->log);
assert(last_index > 0); /* The log can't be empty */
goto send_snapshot;
}
prev_index = 0;
prev_term = 0;
} else {
/* Set prevIndex and prevTerm to the index and term of the entry at
* next_index - 1. */
prev_index = next_index - 1;
prev_term = logTermOf(&r->log, prev_index);
/* If the entry is not anymore in our log, send the last snapshot if we're
* not doing so already. */
if (prev_term == 0 && !progress_state_is_snapshot) {
assert(prev_index < snapshot_index);
tracef("missing entry at index %lld -> send snapshot", prev_index);
goto send_snapshot;
}
}
/* Send empty AppendEntries RPC when installing a snaphot */
if (progress_state_is_snapshot) {
prev_index = logLastIndex(&r->log);
prev_term = logLastTerm(&r->log);
}
return sendAppendEntries(r, i, prev_index, prev_term);
send_snapshot:
return sendSnapshot(r, i);
}
/* Possibly trigger I/O requests for newly appended log entries or heartbeats.
*
* This function loops through all followers and triggers replication on them.
*
* It must be called only by leaders. */
static int triggerAll(struct raft *r)
{
unsigned i;
int rv;
assert(r->state == RAFT_LEADER);
/* Trigger replication for servers we didn't hear from recently. */
for (i = 0; i < r->configuration.n; i++) {
struct raft_server *server = &r->configuration.servers[i];
if (server->id == r->id) {
continue;
}
/* Skip spare servers, unless they're being promoted. */
if (server->role == RAFT_SPARE &&
server->id != r->leader_state.promotee_id) {
continue;
}
rv = replicationProgress(r, i);
if (rv != 0 && rv != RAFT_NOCONNECTION) {
/* This is not a critical failure, let's just log it. */
tracef("failed to send append entries to server %u: %s (%d)",
server->id, raft_strerror(rv), rv);
}
}
return 0;
}
int replicationHeartbeat(struct raft *r)
{
return triggerAll(r);
}
/* Context for a write log entries request that was submitted by a leader. */
struct appendLeader
{
struct raft *raft; /* Instance that has submitted the request */
raft_index index; /* Index of the first entry in the request. */
struct raft_entry *entries; /* Entries referenced in the request. */
unsigned n; /* Length of the entries array. */
struct raft_io_append req;
};
/* Called after a successful append entries I/O request to update the index of
* the last entry stored on disk. Return how many new entries that are still
* present in our in-memory log were stored. */
static size_t updateLastStored(struct raft *r,
raft_index first_index,
struct raft_entry *entries,
size_t n_entries)
{
size_t i;
/* Check which of these entries is still in our in-memory log */
for (i = 0; i < n_entries; i++) {
struct raft_entry *entry = &entries[i];
raft_index index = first_index + i;
raft_term local_term = logTermOf(&r->log, index);
/* If we have no entry at this index, or if the entry we have now has a
* different term, it means that this entry got truncated, so let's stop
* here. */
if (local_term == 0 || (local_term > 0 && local_term != entry->term)) {
break;
}
/* If we do have an entry at this index, its term must match the one of
* the entry we wrote on disk. */
assert(local_term != 0 && local_term == entry->term);
}
r->last_stored += i;
return i;
}
/* Get the request matching the given index and type, if any. */
static struct request *getRequest(struct raft *r,
const raft_index index,
int type)
{
queue *head;
struct request *req;
if (r->state != RAFT_LEADER) {
return NULL;
}
QUEUE_FOREACH(head, &r->leader_state.requests)
{
req = QUEUE_DATA(head, struct request, queue);
if (req->index == index) {
assert(req->type == type);
QUEUE_REMOVE(head);
return req;
}
}
return NULL;
}
/* Invoked once a disk write request for new entries has been completed. */
static void appendLeaderCb(struct raft_io_append *req, int status)
{
struct appendLeader *request = req->data;
struct raft *r = request->raft;
size_t server_index;
int rv;
tracef("leader: written %u entries starting at %lld: status %d", request->n,
request->index, status);
/* In case of a failed disk write, if we were the leader creating these
* entries in the first place, truncate our log too (since we have appended
* these entries to it) and fire the request callback. */
if (status != 0) {
struct raft_apply *apply;
ErrMsgTransfer(r->io->errmsg, r->errmsg, "io");
apply =
(struct raft_apply *)getRequest(r, request->index, RAFT_COMMAND);
if (apply != NULL) {
if (apply->cb != NULL) {
apply->cb(apply, status, NULL);
}
}
goto out;
}
updateLastStored(r, request->index, request->entries, request->n);
/* If we are not leader anymore, just discard the result. */
if (r->state != RAFT_LEADER) {
tracef("local server is not leader -> ignore write log result");
goto out;
}
/* If Check if we have reached a quorum. */
server_index = configurationIndexOf(&r->configuration, r->id);
/* Only update the next index if we are part of the current
* configuration. The only case where this is not true is when we were
* asked to remove ourselves from the cluster.
*
* From Section 4.2.2:
*
* there will be a period of time (while it is committing Cnew) when a
* leader can manage a cluster that does not include itself; it
* replicates log entries but does not count itself in majorities.
*/
if (server_index < r->configuration.n) {
r->leader_state.progress[server_index].match_index = r->last_stored;
} else {
const struct raft_entry *entry = logGet(&r->log, r->last_stored);
assert(entry->type == RAFT_CHANGE);
}
/* Check if we can commit some new entries. */
replicationQuorum(r, r->last_stored);
rv = replicationApply(r);
if (rv != 0) {
/* TODO: just log the error? */
}
out:
/* Tell the log that we're done referencing these entries. */
logRelease(&r->log, request->index, request->entries, request->n);
if (status != 0) {
logTruncate(&r->log, request->index);
}
raft_free(request);
}
/* Submit a disk write for all entries from the given index onward. */
static int appendLeader(struct raft *r, raft_index index)
{
struct raft_entry *entries;
unsigned n;
struct appendLeader *request;
int rv;
assert(r->state == RAFT_LEADER);
assert(index > 0);
assert(index > r->last_stored);
/* Acquire all the entries from the given index onwards. */
rv = logAcquire(&r->log, index, &entries, &n);
if (rv != 0) {
goto err;
}
/* We expect this function to be called only when there are actually
* some entries to write. */
assert(n > 0);
/* Allocate a new request. */
request = raft_malloc(sizeof *request);
if (request == NULL) {
rv = RAFT_NOMEM;
goto err_after_entries_acquired;
}
request->raft = r;
request->index = index;
request->entries = entries;
request->n = n;
request->req.data = request;
rv = r->io->append(r->io, &request->req, entries, n, appendLeaderCb);
if (rv != 0) {
ErrMsgTransfer(r->io->errmsg, r->errmsg, "io");
goto err_after_request_alloc;
}
return 0;
err_after_request_alloc:
raft_free(request);
err_after_entries_acquired:
logRelease(&r->log, index, entries, n);
err:
assert(rv != 0);
return rv;
}
int replicationTrigger(struct raft *r, raft_index index)
{
int rv;
rv = appendLeader(r, index);
if (rv != 0) {
return rv;
}
return triggerAll(r);
}
/* Helper to be invoked after a promotion of a non-voting server has been
* requested via @raft_assign and that server has caught up with logs.
*
* This function changes the local configuration marking the server being
* promoted as actually voting, appends the a RAFT_CHANGE entry with the new
* configuration to the local log and triggers its replication. */
static int triggerActualPromotion(struct raft *r)
{
raft_index index;
raft_term term = r->current_term;
size_t server_index;
struct raft_server *server;
int old_role;
int rv;
assert(r->state == RAFT_LEADER);
assert(r->leader_state.promotee_id != 0);
server_index =
configurationIndexOf(&r->configuration, r->leader_state.promotee_id);
assert(server_index < r->configuration.n);
server = &r->configuration.servers[server_index];
assert(server->role != RAFT_VOTER);
/* Update our current configuration. */
old_role = server->role;
server->role = RAFT_VOTER;
/* Index of the entry being appended. */
index = logLastIndex(&r->log) + 1;
/* Encode the new configuration and append it to the log. */
rv = logAppendConfiguration(&r->log, term, &r->configuration);
if (rv != 0) {
goto err;
}
/* Start writing the new log entry to disk and send it to the followers. */
rv = replicationTrigger(r, index);
if (rv != 0) {
goto err_after_log_append;
}
r->leader_state.promotee_id = 0;
r->configuration_uncommitted_index = logLastIndex(&r->log);
return 0;
err_after_log_append:
logTruncate(&r->log, index);
err:
server->role = old_role;
assert(rv != 0);
return rv;
}
int replicationUpdate(struct raft *r,
const struct raft_server *server,
const struct raft_append_entries_result *result)
{
bool is_being_promoted;
raft_index last_index;
unsigned i;
int rv;
i = configurationIndexOf(&r->configuration, server->id);
assert(r->state == RAFT_LEADER);
assert(i < r->configuration.n);
progressMarkRecentRecv(r, i);
/* If the RPC failed because of a log mismatch, retry.
*
* From Figure 3.1:
*
* [Rules for servers] Leaders:
*
* - If AppendEntries fails because of log inconsistency:
* decrement nextIndex and retry.
*/
if (result->rejected > 0) {
bool retry;
retry = progressMaybeDecrement(r, i, result->rejected,
result->last_log_index);
if (retry) {
/* Retry, ignoring errors. */
tracef("log mismatch -> send old entries to %u", server->id);
replicationProgress(r, i);
}
return 0;
}
/* In case of success the remote server is expected to send us back the
* value of prevLogIndex + len(entriesToAppend). If it has a longer log, it
* might be a leftover from previous terms. */
last_index = result->last_log_index;
if (last_index > logLastIndex(&r->log)) {
last_index = logLastIndex(&r->log);
}
/* If the RPC succeeded, update our counters for this server.
*
* From Figure 3.1:
*
* [Rules for servers] Leaders:
*
* If successful update nextIndex and matchIndex for follower.
*/
if (!progressMaybeUpdate(r, i, last_index)) {
return 0;
}
switch (progressState(r, i)) {
case PROGRESS__SNAPSHOT:
/* If a snapshot has been installed, transition back to probe */
if (progressSnapshotDone(r, i)) {
progressToProbe(r, i);
}
break;
case PROGRESS__PROBE:
/* Transition to pipeline */
progressToPipeline(r, i);
}
/* If the server is currently being promoted and is catching with logs,
* update the information about the current catch-up round, and possibly
* proceed with the promotion. */
is_being_promoted = r->leader_state.promotee_id != 0 &&
r->leader_state.promotee_id == server->id;
if (is_being_promoted) {
bool is_up_to_date = membershipUpdateCatchUpRound(r);
if (is_up_to_date) {
rv = triggerActualPromotion(r);
if (rv != 0) {
return rv;
}
}
}
/* Check if we can commit some new entries. */
replicationQuorum(r, r->last_stored);
rv = replicationApply(r);
if (rv != 0) {
/* TODO: just log the error? */
}
/* Abort here we have been removed and we are not leaders anymore. */
if (r->state != RAFT_LEADER) {
goto out;
}
/* Get again the server index since it might have been removed from the
* configuration. */
i = configurationIndexOf(&r->configuration, server->id);
if (i < r->configuration.n) {
/* If we are transferring leadership to this follower, check if its log
* is now up-to-date and, if so, send it a TimeoutNow RPC (unless we
* already did). */
if (r->transfer != NULL && r->transfer->id == server->id) {
if (progressIsUpToDate(r, i) && r->transfer->send.data == NULL) {
rv = membershipLeadershipTransferStart(r);
if (rv != 0) {
membershipLeadershipTransferClose(r);
}
}
}
/* If this follower is in pipeline mode, send it more entries. */
if (progressState(r, i) == PROGRESS__PIPELINE) {
replicationProgress(r, i);
}
}
out:
return 0;
}
static void sendAppendEntriesResultCb(struct raft_io_send *req, int status)
{
(void)status;
HeapFree(req);
}
static void sendAppendEntriesResult(
struct raft *r,
const struct raft_append_entries_result *result)
{
struct raft_message message;
struct raft_io_send *req;
int rv;
message.type = RAFT_IO_APPEND_ENTRIES_RESULT;
message.server_id = r->follower_state.current_leader.id;
message.server_address = r->follower_state.current_leader.address;
message.append_entries_result = *result;
req = raft_malloc(sizeof *req);
if (req == NULL) {
return;
}
req->data = r;
rv = r->io->send(r->io, req, &message, sendAppendEntriesResultCb);
if (rv != 0) {
raft_free(req);
}
}
/* Context for a write log entries request that was submitted by a follower. */
struct appendFollower
{
struct raft *raft; /* Instance that has submitted the request */
raft_index index; /* Index of the first entry in the request. */
struct raft_append_entries args;
struct raft_io_append req;
};
static void appendFollowerCb(struct raft_io_append *req, int status)
{
struct appendFollower *request = req->data;
struct raft *r = request->raft;
struct raft_append_entries *args = &request->args;
struct raft_append_entries_result result;
size_t i;
size_t j;
int rv;
tracef("I/O completed on follower: status %d", status);
assert(args->entries != NULL);
assert(args->n_entries > 0);
result.term = r->current_term;
if (status != 0) {
if (r->state != RAFT_FOLLOWER) {
tracef("local server is not follower -> ignore I/O failure");
goto out;
}
result.rejected = args->prev_log_index + 1;
goto respond;
}
/* If we're shutting down or have errored, ignore the result. */
if (r->state == RAFT_UNAVAILABLE) {
tracef("local server is unavailable -> ignore I/O result");
goto out;
}
/* We received an InstallSnapshot RCP while these entries were being
* persisted to disk */
if (replicationInstallSnapshotBusy(r)) {
goto out;
}
i = updateLastStored(r, request->index, args->entries, args->n_entries);
/* If none of the entries that we persisted is present anymore in our
* in-memory log, there's nothing to report or to do. We just discard
* them. */
if (i == 0 || r->state != RAFT_FOLLOWER) {
goto out;
}
/* Possibly apply configuration changes as uncommitted. */
for (j = 0; j < i; j++) {
struct raft_entry *entry = &args->entries[j];
raft_index index = request->index + j;
raft_term local_term = logTermOf(&r->log, index);
assert(local_term != 0 && local_term == entry->term);
if (entry->type == RAFT_CHANGE) {
rv = membershipUncommittedChange(r, index, entry);
if (rv != 0) {
goto out;
}
}
}
/* From Figure 3.1:
*
* AppendEntries RPC: Receiver implementation: If leaderCommit >
* commitIndex, set commitIndex = min(leaderCommit, index of last new
* entry).
*/
if (args->leader_commit > r->commit_index) {
r->commit_index = min(args->leader_commit, r->last_stored);
rv = replicationApply(r);
if (rv != 0) {
goto out;
}
}
if (r->state != RAFT_FOLLOWER) {
tracef("local server is not follower -> don't send result");
goto out;
}
result.rejected = 0;
respond:
result.last_log_index = r->last_stored;
sendAppendEntriesResult(r, &result);
out:
logRelease(&r->log, request->index, request->args.entries,
request->args.n_entries);
raft_free(request);
}
/* Check the log matching property against an incoming AppendEntries request.
*
* From Figure 3.1:
*
* [AppendEntries RPC] Receiver implementation:
*
* 2. Reply false if log doesn't contain an entry at prevLogIndex whose
* term matches prevLogTerm.
*
* Return 0 if the check passed.
*
* Return 1 if the check did not pass and the request needs to be rejected.
*
* Return -1 if there's a conflict and we need to shutdown. */
static int checkLogMatchingProperty(struct raft *r,
const struct raft_append_entries *args)
{
raft_term local_prev_term;
/* If this is the very first entry, there's nothing to check. */
if (args->prev_log_index == 0) {
return 0;
}
local_prev_term = logTermOf(&r->log, args->prev_log_index);
if (local_prev_term == 0) {
tracef("no entry at index %llu -> reject", args->prev_log_index);
return 1;
}
if (local_prev_term != args->prev_log_term) {
if (args->prev_log_index <= r->commit_index) {
/* Should never happen; something is seriously wrong! */
tracef(
"conflicting terms %llu and %llu for entry %llu (commit "
"index %llu) -> shutdown",
local_prev_term, args->prev_log_term, args->prev_log_index,
r->commit_index);
return -1;
}
tracef("previous term mismatch -> reject");
return 1;
}
return 0;
}
/* Delete from our log all entries that conflict with the ones in the given
* AppendEntries request.
*
* From Figure 3.1:
*
* [AppendEntries RPC] Receiver implementation:
*
* 3. If an existing entry conflicts with a new one (same index but
* different terms), delete the existing entry and all that follow it.
*
* The i output parameter will be set to the array index of the first new log
* entry that we don't have yet in our log, among the ones included in the given
* AppendEntries request. */
static int deleteConflictingEntries(struct raft *r,
const struct raft_append_entries *args,
size_t *i)
{
size_t j;
int rv;
for (j = 0; j < args->n_entries; j++) {
struct raft_entry *entry = &args->entries[j];
raft_index entry_index = args->prev_log_index + 1 + j;
raft_term local_term = logTermOf(&r->log, entry_index);
if (local_term > 0 && local_term != entry->term) {
if (entry_index <= r->commit_index) {
/* Should never happen; something is seriously wrong! */
tracef("new index conflicts with committed entry -> shutdown");
return RAFT_SHUTDOWN;
}
tracef("log mismatch -> truncate (%llu)", entry_index);
/* Possibly discard uncommitted configuration changes. */
if (r->configuration_uncommitted_index >= entry_index) {
rv = membershipRollback(r);
if (rv != 0) {
return rv;