-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathraft_test.cpp
4610 lines (3998 loc) · 164 KB
/
raft_test.cpp
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
/**
* Copyright 2025 AntGroup CO., Ltd.
* Copyright 2015 The etcd Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// written by botu.wzy, inspired by etcd raft
#include <gtest/gtest.h>
#include <utility>
#include "tracker/state.h"
#include "raft.h"
namespace eraft {
using namespace detail;
std::string ltoa(std::shared_ptr<RaftLog> l) {
char str[1024] = {0};
sprintf(str, "committed: %lu\n", l->committed_);
sprintf(str, "applied: %lu\n", l->applied_);
auto ents = l->allEntries();
for (size_t i = 0; i < ents.size(); i++) {
sprintf(str, "#%lu: %s\n", i, ents[i].ShortDebugString().c_str());
}
return str;
}
void advanceMessagesAfterAppend(const std::shared_ptr<raft>& r);
// nextEnts returns the appliable entries and updates the applied index
std::vector<raftpb::Entry> nextEnts(const std::shared_ptr<raft>& r, const std::shared_ptr<MemoryStorage>& s) {
// Append unstable entries.
s->Append(r->raftLog_->nextUnstableEnts());
r->raftLog_->stableTo(r->raftLog_->lastIndex(), r->raftLog_->lastTerm());
// Run post-append steps.
advanceMessagesAfterAppend(r);
// Return committed entries.
auto ents = r->raftLog_->nextCommittedEnts(true);
r->raftLog_->appliedTo(r->raftLog_->committed_, 0 /* size */);
return ents;
}
void mustAppendEntry(std::shared_ptr<raft> r, const std::vector<raftpb::Entry>& ents) {
if (!r->appendEntry(ents)) {
ERAFT_FATAL("entry unexpectedly dropped");
}
}
Config newTestConfig(uint64_t id, int election, int heartbeat, std::shared_ptr<Storage> storage) {
Config config;
config.id_ = id;
config.electionTick_ = election;
config.heartbeatTick_ = heartbeat;
config.storage_ = std::move(storage);
config.maxSizePerMsg_ = noLimit;
config.maxInflightMsgs_ = 256;
return config;
}
std::shared_ptr<raft> newTestRaft(uint64_t id, int election, int heartbeat, std::shared_ptr<Storage> storage) {
auto config = newTestConfig(id, election, heartbeat, std::move(storage));
return newRaft(config);
}
using testMemoryStorageOptions = std::function<void(std::shared_ptr<MemoryStorage>&)>;
std::shared_ptr<MemoryStorage> newTestMemoryStorage(const std::vector<testMemoryStorageOptions>& opts) {
auto ms = NewMemoryStorage();
for (auto& o : opts) {
o(ms);
}
return ms;
}
std::shared_ptr<raft> newTestLearnerRaft(uint64_t id, int election, int heartbeat, std::shared_ptr<Storage> storage) {
auto cfg = newTestConfig(id, election, heartbeat, std::move(storage));
return newRaft(cfg);
}
std::vector<raftpb::Message> readMessages(const std::shared_ptr<raft>& r) {
advanceMessagesAfterAppend(r);
auto msgs = r->msgs_;
r->msgs_.clear();
return msgs;
}
std::vector<raftpb::Message> takeMessagesAfterAppend(const std::shared_ptr<raft>& r) {
auto msgs = r->msgsAfterAppend_;
r->msgsAfterAppend_.clear();
return msgs;
}
Error stepOrSend(const std::shared_ptr<raft>& r, std::vector<raftpb::Message> msgs) {
for (auto& m : msgs) {
if (m.to() == r->id_) {
auto err = r->Step(m);
if (err != nullptr) {
return err;
}
} else {
r->msgs_.push_back(m);
}
}
return {};
}
void advanceMessagesAfterAppend(const std::shared_ptr<raft>& r) {
while(true) {
auto msgs = takeMessagesAfterAppend(r);
if (msgs.empty()) {
break;
}
stepOrSend(r, msgs);
}
}
testMemoryStorageOptions withPeers(const std::vector<uint64_t>& peers) {
return [peers](std::shared_ptr<MemoryStorage>& ms) {
*ms->snapshot_.mutable_metadata()->mutable_conf_state()->mutable_voters() = {peers.begin(), peers.end()};
};
}
testMemoryStorageOptions withLearners(const std::vector<uint64_t>& learners) {
return [learners](std::shared_ptr<MemoryStorage>& ms) {
*ms->snapshot_.mutable_metadata()->mutable_conf_state()->mutable_learners() = {learners.begin(), learners.end()};
};
}
TEST(raft, TestProgressLeader) {
auto r = newTestRaft(1, 5, 1, newTestMemoryStorage({withPeers({1, 2})}));
r->becomeCandidate();
r->becomeLeader();
r->trk_.progress_[2]->BecomeReplicate();
// Send proposals to r1. The first 5 entries should be queued in the unstable log.
raftpb::Message propMsg;
propMsg.set_from(1);
propMsg.set_to(1);
propMsg.set_type(raftpb::MsgProp);
propMsg.mutable_entries()->Add()->set_data("foo");
for (uint64_t i = 0; i < 5; i++) {
EXPECT_EQ(r->Step(propMsg), nullptr);
}
auto m = r->trk_.progress_[1]->match_;
EXPECT_EQ(m, 0);
auto ents = r->raftLog_->nextUnstableEnts();
if ((ents.size() != 6) || ents[0].data().size() > 0 || ents[5].data() != "foo") {
EXPECT_TRUE(false);
}
advanceMessagesAfterAppend(r);
EXPECT_EQ(r->trk_.progress_[1]->match_, 6);
EXPECT_EQ(r->trk_.progress_[1]->next_, 7);
}
// TestProgressResumeByHeartbeatResp ensures raft.heartbeat reset progress.paused by heartbeat response.
TEST(raft, TestProgressResumeByHeartbeatResp) {
auto r = newTestRaft(1, 5, 1, newTestMemoryStorage({withPeers({1, 2})}));
r->becomeCandidate();
r->becomeLeader();
r->trk_.progress_[2]->msgAppFlowPaused_ = true;
raftpb::Message msg;
msg.set_from(1);
msg.set_to(1);
msg.set_type(raftpb::MsgBeat);
r->Step(msg);
EXPECT_TRUE(r->trk_.progress_[2]->msgAppFlowPaused_);
r->trk_.progress_[2]->BecomeReplicate();
msg.Clear();
msg.set_from(2);
msg.set_to(1);
msg.set_type(raftpb::MsgHeartbeatResp);
r->Step(msg);
EXPECT_FALSE(r->trk_.progress_[2]->msgAppFlowPaused_);
}
TEST(raft, TestProgressPaused) {
auto r = newTestRaft(1, 5, 1, newTestMemoryStorage({withPeers({1, 2})}));
r->becomeCandidate();
r->becomeLeader();
raftpb::Message msg;
msg.set_from(1);
msg.set_to(1);
msg.set_type(raftpb::MsgProp);
msg.mutable_entries()->Add()->set_data("somedata");
r->Step(msg);
r->Step(msg);
r->Step(msg);
auto ms = readMessages(r);
EXPECT_EQ(ms.size(), 1);
}
TEST(raft, TestProgressFlowControl) {
auto cfg = newTestConfig(1, 5, 1, newTestMemoryStorage({withPeers({1, 2})}));
cfg.maxInflightMsgs_ = 3;
cfg.maxSizePerMsg_ = 2048;
cfg.maxInflightBytes_ = 9000; // A little over MaxInflightMsgs * MaxSizePerMsg.
auto r = newRaft(cfg);
r->becomeCandidate();
r->becomeLeader();
// Throw away all the messages relating to the initial election.
readMessages(r);
// While node 2 is in probe state, propose a bunch of entries.
r->trk_.progress_[2]->BecomeProbe();
std::string blob(1000, 'a');
std::string large(5000, 'b');
for (auto i = 0; i < 22; i++) {
auto newblob = blob;
if (i >= 10 && i < 16) {
// Temporarily send large messages.
newblob = large;
}
raftpb::Message msg;
msg.set_from(1);
msg.set_to(1);
msg.set_type(raftpb::MsgProp);
msg.mutable_entries()->Add()->set_data(newblob);
r->Step(msg);
}
auto ms = readMessages(r);
// First append has two entries: the empty entry to confirm the
// election, and the first proposal (only one proposal gets sent
// because we're in probe state).
EXPECT_FALSE(ms.size() != 1 || ms[0].type() != raftpb::MsgApp);
EXPECT_EQ(ms[0].entries().size(), 2);
EXPECT_FALSE(ms[0].entries(0).data().size() != 0 || ms[0].entries(1).data().size() != 1000);
auto ackAndVerify = [&r](uint64_t index, std::vector<int> expEntries) {
raftpb::Message msg;
msg.set_from(2);
msg.set_to(1);
msg.set_type(raftpb::MsgAppResp);
msg.set_index(index);
r->Step(msg);
auto ms = readMessages(r);
EXPECT_EQ(ms.size(), expEntries.size());
for (size_t i = 0; i < ms.size(); i++) {
EXPECT_EQ(ms[i].type(), raftpb::MsgApp);
EXPECT_EQ(ms[i].entries().size(), expEntries[i]);
}
auto last = ms[ms.size()-1].entries();
if (last.empty()) {
return index;
}
return last[last.size()-1].index();
};
// When this append is acked, we change to replicate state and can
// send multiple messages at once.
auto index = ackAndVerify(ms[0].entries(1).index(), {2, 2, 2});
// Ack all three of those messages together and get another 3 messages. The
// third message contains a single large entry, in contrast to 2 before.
index = ackAndVerify(index, {2, 1, 1});
// All subsequent messages contain one large entry, and we cap at 2 messages
// because it overflows MaxInflightBytes.
index = ackAndVerify(index, {1, 1});
index = ackAndVerify(index, {1, 1});
// Start getting small messages again.
index = ackAndVerify(index, {1, 2, 2});
ackAndVerify(index, {2});
}
TEST(raft, TestUncommittedEntryLimit) {
// Use a relatively large number of entries here to prevent regression of a
// bug which computed the size before it was fixed. This test would fail
// with the bug, either because we'd get dropped proposals earlier than we
// expect them, or because the final tally ends up nonzero. (At the time of
// writing, the former).
const auto maxEntries = 1024;
raftpb::Entry testEntry;
testEntry.set_data("testdata");
auto maxEntrySize = maxEntries * payloadSize(testEntry);
EXPECT_EQ(payloadSize(raftpb::Entry()), 0);
auto cfg = newTestConfig(1, 5, 1, newTestMemoryStorage({withPeers({1, 2, 3})}));
cfg.maxUncommittedEntriesSize_ = maxEntrySize;
cfg.maxInflightMsgs_ = 2 * 1024; // avoid interference
auto r = newRaft(cfg);
r->becomeCandidate();
r->becomeLeader();
EXPECT_EQ(r->uncommittedSize_, 0);
// Set the two followers to the replicate state. Commit to tail of log.
const auto numFollowers = 2;
r->trk_.progress_[2]->BecomeReplicate();
r->trk_.progress_[3]->BecomeReplicate();
r->uncommittedSize_ = 0;
// Send proposals to r1. The first 5 entries should be appended to the log.
raftpb::Message propMsg;
propMsg.set_from(1);
propMsg.set_to(1);
propMsg.set_type(raftpb::MsgProp);
*propMsg.mutable_entries()->Add() = testEntry;
//propEnts := make([]pb.Entry, maxEntries)
std::vector<raftpb::Entry> propEnts(maxEntries);
for (auto i = 0; i < maxEntries; i++) {
EXPECT_EQ(r->Step(propMsg), nullptr);
propEnts[i] = testEntry;
}
// Send one more proposal to r1. It should be rejected.
EXPECT_EQ(r->Step(propMsg), ErrProposalDropped);
// Read messages and reduce the uncommitted size as if we had committed
// these entries.
auto ms = readMessages(r);
EXPECT_EQ(maxEntries * numFollowers, ms.size());
r->reduceUncommittedSize(payloadsSize(propEnts));
EXPECT_EQ(r->uncommittedSize_, 0);
// Send a single large proposal to r1. Should be accepted even though it
// pushes us above the limit because we were beneath it before the proposal.
propEnts.clear();
propEnts.resize(2*maxEntries, testEntry);
raftpb::Message propMsgLarge;
propMsgLarge.set_from(1);
propMsgLarge.set_to(1);
propMsgLarge.set_type(raftpb::MsgProp);
*propMsgLarge.mutable_entries() = {propEnts.begin(), propEnts.end()};
EXPECT_EQ(r->Step(propMsgLarge), nullptr);
// Send one more proposal to r1. It should be rejected, again.
EXPECT_EQ(r->Step(propMsg), ErrProposalDropped);
// But we can always append an entry with no Data. This is used both for the
// leader's first empty entry and for auto-transitioning out of joint config
// states.
raftpb::Message msg;
msg.set_from(1);
msg.set_to(1);
msg.set_type(raftpb::MsgProp);
msg.mutable_entries()->Add();
EXPECT_EQ(r->Step(msg), nullptr);
// Read messages and reduce the uncommitted size as if we had committed
// these entries.
ms = readMessages(r);
EXPECT_EQ(2 * numFollowers, ms.size());
r->reduceUncommittedSize(payloadsSize(propEnts));
EXPECT_EQ(r->uncommittedSize_, 0);
}
void preVoteConfig(Config* c) {
c->preVote_ = true;
}
struct stateMachine {
virtual Error Step(raftpb::Message) = 0;
virtual std::vector<raftpb::Message> readMessages() = 0;
virtual void advanceMessagesAfterAppend() = 0;
};
struct blackHole : public stateMachine {
Error Step(raftpb::Message) override {
return {};
}
std::vector<raftpb::Message> readMessages() override {
return {};
}
void advanceMessagesAfterAppend() override {}
};
auto nopStepper = std::make_shared<blackHole>();
struct raftWarp : public stateMachine {
explicit raftWarp(std::shared_ptr<raft> raft) : raft_(std::move(raft)) {}
Error Step(raftpb::Message m) override {
return raft_->Step(std::move(m));
}
std::vector<raftpb::Message> readMessages() override {
return ::eraft::readMessages(raft_);
}
void advanceMessagesAfterAppend() override {
::eraft::advanceMessagesAfterAppend(raft_);
}
std::shared_ptr<raft> raft_;
};
std::shared_ptr<raftWarp> entsWithConfig(const std::function<void(Config*)>& configFunc, std::vector<uint64_t> terms) {
auto storage = NewMemoryStorage();
for (size_t i = 0; i < terms.size(); i++) {
storage->Append({EntryHelper{.index = i + 1, .term = terms[i]}.Done()});
}
auto cfg = newTestConfig(1, 5, 1, storage);
if (configFunc) {
configFunc(&cfg);
}
auto sm = newRaft(cfg);
sm->reset(terms[terms.size()-1]);
return std::make_shared<raftWarp>(sm);
}
// votedWithConfig creates a raft state machine with Vote and Term set
// to the given value but no log entries (indicating that it voted in
// the given term but has not received any logs).
std::shared_ptr<raftWarp> votedWithConfig(const std::function<void(Config*)>& configFunc, uint64_t vote, uint64_t term) {
auto storage = NewMemoryStorage();
raftpb::HardState hs;
hs.set_vote(vote);
hs.set_term(term);
storage->SetHardState(hs);
auto cfg = newTestConfig(1, 5, 1, storage);
if (configFunc){
configFunc(&cfg);
}
auto sm = newRaft(cfg);
sm->reset(term);
return std::make_shared<raftWarp>(sm);
}
struct connem {
uint64_t from;
uint64_t to;
bool operator<(const connem& r) const {
if (from < r.from) {
return true;
} else if (from > r.from) {
return false;
} else {
return to < r.to;
}
}
};
struct network {
std::unordered_map<uint64_t, std::shared_ptr<stateMachine>> peers;
std::unordered_map<uint64_t, std::shared_ptr<MemoryStorage>> storage;
std::map<connem, float> dropm;
std::unordered_map<raftpb::MessageType, bool> ignorem;
// msgHook is called for each message sent. It may inspect the
// message and return true to send it or false to drop it.
std::function<bool(const raftpb::Message&)> msgHook;
std::vector<raftpb::Message>filter(const std::vector<raftpb::Message>& msgs) {
std::vector<raftpb::Message> mm;
for (auto& m : msgs) {
if (ignorem.count(m.type()) > 0 && ignorem.at(m.type())) {
continue;
}
switch (m.type()) {
case raftpb::MsgHup: {
// hups never go over the network, so don't drop them but panic
ERAFT_FATAL("unexpected msgHup");
break;
}
default: {
float perc = 0;
if (dropm.count(connem{m.from(), m.to()}) > 0) {
perc = dropm.at(connem{m.from(), m.to()});
}
auto n = float(random(std::numeric_limits<int64_t>::max() - 1)) /
float(std::numeric_limits<int64_t>::max());
if (n < perc) {
continue;
}
}
}
if (msgHook) {
if (!msgHook(m)) {
continue;
}
}
mm.push_back(m);
}
return mm;
}
void send(std::vector<raftpb::Message> msgs) {
while (!msgs.empty()) {
auto& m = msgs[0];
auto& p = peers.at(m.to());
p->Step(m);
p->advanceMessagesAfterAppend();
msgs.erase(msgs.begin());
auto append = filter(p->readMessages());
msgs.insert(msgs.end(), append.begin(), append.end());
}
}
void drop(uint64_t from, uint64_t to , float perc) {
dropm[(connem{from, to})] = perc;
}
void cut(uint64_t one, uint64_t other) {
drop(one, other, 2.0); // always drop
drop(other, one, 2.0); // always drop
}
void isolate(uint64_t id) {
for (size_t i = 0; i < peers.size(); i++) {
auto nid = i + 1;
if (nid != id) {
drop(id, nid, 1.0); // always drop
drop(nid, id, 1.0); // always drop
}
}
}
void ignore(raftpb::MessageType t) {
ignorem[t] = true;
}
void recover() {
dropm.clear();
ignorem.clear();
}
};
std::vector<uint64_t> idsBySize(int size) {
std::vector<uint64_t> ids(size, 0);
for (auto i = 0; i < size; i++) {
ids[i] = 1 + i;
}
return ids;
}
// newNetworkWithConfig is like newNetwork but calls the given func to
// modify the configuration of any state machines it creates.
std::shared_ptr<network> newNetworkWithConfig(const std::function<void(Config*)>& configFunc, const std::vector<std::shared_ptr<stateMachine>>& peers) {
auto size = peers.size();
auto peerAddrs = idsBySize(size);
std::unordered_map<uint64_t, std::shared_ptr<stateMachine>> npeers;
std::unordered_map<uint64_t, std::shared_ptr<MemoryStorage>> nstorage(size);
for (size_t j = 0; j < peers.size(); j++) {
auto& p = peers[j];
auto id = peerAddrs[j];
//switch v := p.(type) {
if (!p) {
nstorage[id] = newTestMemoryStorage({withPeers(peerAddrs)});
auto cfg = newTestConfig(id, 10, 1, nstorage[id]);
if (configFunc) {
configFunc(&cfg);
}
auto sm = newRaft(cfg);
npeers[id] = std::make_shared<raftWarp>(sm);
} else if (std::dynamic_pointer_cast<raftWarp>(p)) {
// TODO(tbg): this is all pretty confused. Clean this up.
std::unordered_map<uint64_t, bool> learners;
auto rw = std::dynamic_pointer_cast<raftWarp>(p);
auto v = rw->raft_;
for (auto &i: v->trk_.config_.learners_) {
learners[i] = true;
}
v->id_ = id;
v->trk_ = tracker::MakeProgressTracker(v->trk_.maxInflight_, v->trk_.maxInflightBytes_);
for (size_t i = 0; i < size; i++) {
auto pr = std::make_shared<tracker::Progress>();
if (learners.count(peerAddrs[i]) > 0) {
pr->isLearner_ = true;
v->trk_.config_.learners_.insert(peerAddrs[i]);
} else {
v->trk_.config_.voters_[0].data().insert(peerAddrs[i]);
}
v->trk_.progress_.data()[peerAddrs[i]] = pr;
}
v->reset(v->term_);
npeers[id] = rw;
} else if (std::dynamic_pointer_cast<blackHole>(p)) {
npeers[id] = std::dynamic_pointer_cast<blackHole>(p);
} else {
ERAFT_FATAL("unexpected state machine type");
}
}
auto ret = std::make_shared<network>();
ret->peers = npeers;
ret->storage = nstorage;
return ret;
}
// newNetwork initializes a network from peers.
// A nil node will be replaced with a new *stateMachine.
// A *stateMachine will get its k, id.
// When using stateMachine, the address list is always [1, n].
std::shared_ptr<network> newNetwork(const std::vector<std::shared_ptr<stateMachine>>& peers) {
return newNetworkWithConfig(nullptr, peers);
}
// setRandomizedElectionTimeout set up the value by caller instead of choosing
// by system, in some test scenario we need to fill in some expected value to
// ensure the certainty
void setRandomizedElectionTimeout(const std::shared_ptr<raft>& r, int64_t v) {
r->randomizedElectionTimeout_ = v;
}
void testLeaderElection(bool preVote) {
std::function<void(Config*)> cfg;
auto candState = StateCandidate;
uint64_t candTerm = 1;
if (preVote) {
cfg = preVoteConfig;
// In pre-vote mode, an election that fails to complete
// leaves the node in pre-candidate state without advancing
// the term.
candState = StatePreCandidate;
candTerm = 0;
}
struct Test {
std::shared_ptr<network> network_;
StateType state;
uint64_t expTerm;
};
std::vector<Test> tests = {
{newNetworkWithConfig(cfg, {nullptr, nullptr, nullptr}), StateLeader, 1},
{newNetworkWithConfig(cfg, {nullptr, nullptr, nopStepper}), StateLeader, 1},
{newNetworkWithConfig(cfg, {nullptr, nopStepper, nopStepper}), candState, candTerm},
{newNetworkWithConfig(cfg, {nullptr, nopStepper, nopStepper, nullptr}), candState, candTerm},
{newNetworkWithConfig(cfg, {nullptr, nopStepper, nopStepper, nullptr, nullptr}), StateLeader, 1},
// three logs further along than 0, but in the same term so rejections
// are returned instead of the votes being ignored.
{newNetworkWithConfig(cfg,
{nullptr, entsWithConfig(cfg, {1}), entsWithConfig(cfg, {1}), entsWithConfig(cfg, {1, 1}), nullptr}),
StateFollower, 1},
};
for (auto &tt : tests) {
raftpb::Message m;
m.set_from(1);
m.set_to(1);
m.set_type(raftpb::MsgHup);
tt.network_->send({m});
auto sm = std::dynamic_pointer_cast<raftWarp>(tt.network_->peers.at(1))->raft_;
EXPECT_EQ(sm->state_, tt.state);
EXPECT_EQ(sm->term_, tt.expTerm);
}
}
TEST(raft, TestLeaderElection) {
testLeaderElection(false);
}
TEST(raft, TestLeaderElectionPreVote) {
testLeaderElection(true);
}
// TestLearnerElectionTimeout verfies that the leader should not start election even
// when times out.
TEST(raft, TestLearnerElectionTimeout) {
auto n1 = newTestLearnerRaft(1, 10, 1, newTestMemoryStorage({withPeers({1}), withLearners({2})}));
auto n2 = newTestLearnerRaft(2, 10, 1, newTestMemoryStorage({withPeers({1}), withLearners({2})}));
n1->becomeFollower(1, None);
n2->becomeFollower(1, None);
// n2 is learner. Learner should not start election even when times out.
setRandomizedElectionTimeout(n2, n2->electionTimeout_);
for (auto i = 0; i < n2->electionTimeout_; i++) {
n2->tick_();
}
EXPECT_EQ(n2->state_, StateFollower);
}
// TestLearnerPromotion verifies that the learner should not election until
// it is promoted to a normal peer.
TEST(raft, TestLearnerPromotion) {
auto n1 = newTestLearnerRaft(1, 10, 1, newTestMemoryStorage({withPeers({1}), withLearners({2})}));
auto n2 = newTestLearnerRaft(2, 10, 1, newTestMemoryStorage({withPeers({1}), withLearners({2})}));
n1->becomeFollower(1, None);
n2->becomeFollower(1, None);
auto nt = newNetwork({std::make_shared<raftWarp>(n1), std::make_shared<raftWarp>(n2)});
EXPECT_NE(n1->state_, StateLeader);
// n1 should become leader
setRandomizedElectionTimeout(n1, n1->electionTimeout_);
for (int i = 0; i < n1->electionTimeout_; i++) {
n1->tick_();
}
advanceMessagesAfterAppend(n1);
EXPECT_EQ(n1->state_, StateLeader);
EXPECT_EQ(n2->state_, StateFollower);
raftpb::Message msg;
msg.set_from(1);
msg.set_to(1);
msg.set_type(raftpb::MsgBeat);
nt->send({msg});
raftpb::ConfChange cc;
cc.set_node_id(2);
cc.set_type(raftpb::ConfChangeAddNode);
raftpb::ConfChangeWrap ccw(std::move(cc));
n1->applyConfChange(ccw.AsV2());
n2->applyConfChange(ccw.AsV2());
EXPECT_FALSE(n2->isLearner_);
// n2 start election, should become leader
setRandomizedElectionTimeout(n2, n2->electionTimeout_);
for (int i = 0; i < n2->electionTimeout_; i++) {
n2->tick_();
}
advanceMessagesAfterAppend(n2);
msg.Clear();
msg.set_from(2);
msg.set_to(2);
msg.set_type(raftpb::MsgBeat);
nt->send({msg});
EXPECT_EQ(n1->state_, StateFollower);
EXPECT_EQ(n2->state_, StateLeader);
}
// TestLearnerCanVote checks that a learner can vote when it receives a valid Vote request.
// See (*raft).Step for why this is necessary and correct behavior.
TEST(raft, TestLearnerCanVote) {
auto n2 = newTestLearnerRaft(2, 10, 1, newTestMemoryStorage({withPeers({1}), withLearners({2})}));
n2->becomeFollower(1, None);
raftpb::Message msg;
msg.set_from(1);
msg.set_to(2);
msg.set_term(2);
msg.set_type(raftpb::MsgVote);
msg.set_logterm(11);
msg.set_index(11);
n2->Step(msg);
auto msgs = readMessages(n2);
EXPECT_EQ(msgs.size(), 1);
EXPECT_EQ(msgs[0].type(), raftpb::MsgVoteResp);
EXPECT_FALSE(msgs[0].reject());
}
// testLeaderCycle verifies that each node in a cluster can campaign
// and be elected in turn. This ensures that elections (including
// pre-vote) work when not starting from a clean slate (as they do in
// TestLeaderElection)
void testLeaderCycle(bool preVote) {
std::function<void(Config*)> cfg;
if (preVote) {
cfg = preVoteConfig;
}
auto n = newNetworkWithConfig(cfg, {nullptr, nullptr, nullptr});
for (uint64_t campaignerID = 1; campaignerID <= 3; campaignerID++) {
raftpb::Message m;
m.set_from(campaignerID);
m.set_to(campaignerID);
m.set_type(raftpb::MsgHup);
n->send({m});
for (auto& pair: n->peers) {
auto sm = std::dynamic_pointer_cast<raftWarp>(pair.second);
EXPECT_FALSE(sm->raft_->id_ == campaignerID && sm->raft_->state_ != StateLeader);
EXPECT_FALSE(sm->raft_->id_ != campaignerID && sm->raft_->state_ != StateFollower);
}
}
}
TEST(raft, TestLeaderCycle) {
testLeaderCycle(false);
}
TEST(raft, TestLeaderCyclePreVote) {
testLeaderCycle(true);
}
void testLeaderElectionOverwriteNewerLogs(bool preVote) {
std::function<void(Config*)> cfg;
if (preVote) {
cfg = preVoteConfig;
}
// This network represents the results of the following sequence of
// events:
// - Node 1 won the election in term 1.
// - Node 1 replicated a log entry to node 2 but died before sending
// it to other nodes.
// - Node 3 won the second election in term 2.
// - Node 3 wrote an entry to its logs but died without sending it
// to any other nodes.
//
// At this point, nodes 1, 2, and 3 all have uncommitted entries in
// their logs and could win an election at term 3. The winner's log
// entry overwrites the losers'. (TestLeaderSyncFollowerLog tests
// the case where older log entries are overwritten, so this test
// focuses on the case where the newer entries are lost).
auto n = newNetworkWithConfig(cfg,{
entsWithConfig(cfg, {1}), // Node 1: Won first election
entsWithConfig(cfg, {1}), // Node 2: Got logs from node 1
entsWithConfig(cfg, {2}), // Node 3: Won second election
votedWithConfig(cfg, 3, 2), // Node 4: Voted but didn't get logs
votedWithConfig(cfg, 3, 2)}); // Node 5: Voted but didn't get logs
// Node 1 campaigns. The election fails because a quorum of nodes
// know about the election that already happened at term 2. Node 1's
// term is pushed ahead to 2.
raftpb::Message m;
m.set_from(1);
m.set_to(1);
m.set_type(raftpb::MsgHup);
n->send({m});
auto sm1 = std::dynamic_pointer_cast<raftWarp>(n->peers[1]);
EXPECT_EQ(sm1->raft_->state_, StateFollower);
EXPECT_EQ(sm1->raft_->term_, 2);
// Node 1 campaigns again with a higher term. This time it succeeds.
raftpb::Message msg;
msg.set_from(1);
msg.set_to(1);
msg.set_type(raftpb::MsgHup);
n->send({msg});
EXPECT_EQ(sm1->raft_->state_, StateLeader);
EXPECT_EQ(sm1->raft_->term_, 3);
// Now all nodes agree on a log entry with term 1 at index 1 (and
// term 3 at index 2).
for (auto& pair : n->peers) {
auto sm = std::dynamic_pointer_cast<raftWarp>(pair.second);
auto entries = sm->raft_->raftLog_->allEntries();
EXPECT_EQ(entries.size(), 2);
EXPECT_EQ(entries[0].term(), 1);
EXPECT_EQ(entries[1].term(), 3);
}
}
// TestLeaderElectionOverwriteNewerLogs tests a scenario in which a
// newly-elected leader does *not* have the newest (i.e. highest term)
// log entries, and must overwrite higher-term log entries with
// lower-term ones.
TEST(raft, TestLeaderElectionOverwriteNewerLogs) {
testLeaderElectionOverwriteNewerLogs(false);
}
TEST(raft, TestLeaderElectionOverwriteNewerLogsPreVote) {
testLeaderElectionOverwriteNewerLogs(true);
}
void testVoteFromAnyState(raftpb::MessageType vt) {
for (auto n = 0; n < (int)numStates; n++) {
auto r = newTestRaft(1, 10, 1, newTestMemoryStorage({withPeers({1, 2, 3})}));
r->term_ = 1;
auto st = (StateType)n;
switch (st) {
case StateFollower:
r->becomeFollower(r->term_, 3);
break;
case StatePreCandidate:
r->becomePreCandidate();
break;
case StateCandidate:
r->becomeCandidate();
break;
case StateLeader:
r->becomeCandidate();
r->becomeLeader();
break;
case numStates:
// Just to fix the compiler warnings
break;
}
// Note that setting our state above may have advanced r.Term
// past its initial value.
auto origTerm = r->term_;
auto newTerm = r->term_ + 1;
raftpb::Message msg;
msg.set_from(2);
msg.set_to(1);
msg.set_type(vt);
msg.set_term(newTerm);
msg.set_logterm(newTerm);
msg.set_index(42);
auto err = r->Step(msg);
EXPECT_EQ(err, nullptr);
auto msgs = readMessages(r);
EXPECT_EQ(msgs.size(),1);
auto& resp = msgs[0];
EXPECT_EQ(resp.type(), voteRespMsgType(vt));
EXPECT_FALSE(resp.reject());
// If this was a real vote, we reset our state and term.
if (vt == raftpb::MsgVote) {
EXPECT_EQ(r->state_, StateFollower);
EXPECT_EQ(r->term_, newTerm);
EXPECT_EQ(r->vote_, 2);
} else {
// In a prevote, nothing changes.
EXPECT_EQ(r->state_, st);
EXPECT_EQ(r->term_, origTerm);
// if st == StateFollower or StatePreCandidate, r hasn't voted yet.
// In StateCandidate or StateLeader, it's voted for itself.
EXPECT_FALSE(r->vote_ != None && r->vote_ != 1);
}
}
}
TEST(raft, TestVoteFromAnyState) {
testVoteFromAnyState(raftpb::MsgVote);
}
TEST(raft, TestPreVoteFromAnyState) {
testVoteFromAnyState(raftpb::MsgPreVote);
}
TEST(raft, TestLogReplication) {
struct Test {
std::shared_ptr<network> net;
std::vector<raftpb::Message> msgs;
uint64_t wcommitted;
};
std::vector<Test> tests =
{
{
newNetwork({nullptr, nullptr, nullptr}),
{MessageHelper{.from = 1, .to = 1, .type = raftpb::MsgProp, .entries = {EntryHelper{.data = "somedata"}.Done()}}.Done()},
2,
},
{
newNetwork({nullptr, nullptr, nullptr}),
{
MessageHelper{.from = 1,.to = 1,.type = raftpb::MsgProp, .entries = {EntryHelper{.data = "somedata"}.Done()}}.Done(),
MessageHelper{.from = 1,.to = 2,.type = raftpb::MsgHup}.Done(),
MessageHelper{.from = 1,.to = 2,.type = raftpb::MsgProp, .entries = {EntryHelper{.data = "somedata"}.Done()}}.Done(),
},
4,
}
};
for (auto& tt : tests) {
tt.net->send({MessageHelper{.from = 1,.to = 1,.type = raftpb::MsgHup}.Done()});
for (auto& m : tt.msgs) {
tt.net->send({m});
}
for (auto& pair : tt.net->peers) {
auto sm = std::dynamic_pointer_cast<raftWarp>(pair.second);
EXPECT_EQ(sm->raft_->raftLog_->committed_, tt.wcommitted);
std::vector<raftpb::Entry> ents;
for (auto& e : nextEnts(sm->raft_, tt.net->storage.at(pair.first))) {
if (!e.data().empty()) {
ents.push_back(e);
}
}
std::vector<raftpb::Message> props;
for (auto& m : tt.msgs) {
if (m.type() == raftpb::MsgProp) {
props.push_back(m);
}
}
for (size_t k = 0; k < props.size(); k++) {
EXPECT_EQ(ents[k].data(), props[k].entries(0).data());
}
}
}
}
// TestLearnerLogReplication tests that a learner can receive entries from the leader.
TEST(raft, TestLearnerLogReplication) {
auto n1 = newTestLearnerRaft(1, 10, 1, newTestMemoryStorage({withPeers({1}), withLearners({2})}));
auto n2 = newTestLearnerRaft(2, 10, 1, newTestMemoryStorage({withPeers({1}), withLearners({2})}));
auto nt = newNetwork({std::make_shared<raftWarp>(n1), std::make_shared<raftWarp>(n2)});
n1->becomeFollower(1, None);
n2->becomeFollower(1, None);
setRandomizedElectionTimeout(n1, n1->electionTimeout_);
for (auto i = 0; i < n1->electionTimeout_; i++) {
n1->tick_();
}
advanceMessagesAfterAppend(n1);
nt->send({MessageHelper{.from = 1, .to = 1, .type = raftpb::MsgBeat}.Done()});
// n1 is leader and n2 is learner
EXPECT_EQ(n1->state_, StateLeader);
EXPECT_TRUE(n2->isLearner_);
auto nextCommitted = 2;
nt->send({MessageHelper{.from = 1,.to = 1,.type = raftpb::MsgProp, .entries = {EntryHelper{.data = "somedata"}.Done()}}.Done()});
EXPECT_EQ(n1->raftLog_->committed_, nextCommitted);
EXPECT_EQ(n1->raftLog_->committed_, n2->raftLog_->committed_);
auto match = n1->trk_.progress_[2]->match_;