forked from tikv/raft-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_raw_node.rs
More file actions
1985 lines (1743 loc) · 66.3 KB
/
test_raw_node.rs
File metadata and controls
1985 lines (1743 loc) · 66.3 KB
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 2019 TiKV Project Authors. Licensed under Apache-2.0.
// Copyright 2015 CoreOS, Inc.
//
// 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.
// See the License for the specific language governing permissions and
// limitations under the License.
use harness::Network;
use protobuf::{Message as PbMessage, ProtobufEnum as _};
use raft::eraftpb::*;
use raft::storage::MemStorage;
use raft::*;
use raft_proto::*;
use slog::Logger;
use crate::test_util::*;
fn conf_change(t: ConfChangeType, node_id: u64) -> ConfChange {
let mut cc = ConfChange::default();
cc.set_change_type(t);
cc.node_id = node_id;
cc
}
#[allow(clippy::too_many_arguments)]
fn must_cmp_ready(
r: &Ready,
ss: &Option<SoftState>,
hs: &Option<HardState>,
entries: &[Entry],
committed_entries: &[Entry],
snapshot: &Option<Snapshot>,
msg_is_empty: bool,
persisted_msg_is_empty: bool,
must_sync: bool,
) {
assert_eq!(r.ss(), ss.as_ref());
assert_eq!(r.hs(), hs.as_ref());
assert_eq!(r.entries().as_slice(), entries);
assert_eq!(r.committed_entries().as_slice(), committed_entries);
assert_eq!(r.must_sync(), must_sync);
assert!(r.read_states().is_empty());
assert_eq!(
r.snapshot(),
snapshot.as_ref().unwrap_or(&Snapshot::default())
);
assert_eq!(r.messages().is_empty(), msg_is_empty);
assert_eq!(r.persisted_messages().is_empty(), persisted_msg_is_empty);
}
fn new_raw_node(
id: u64,
peers: Vec<u64>,
election_tick: usize,
heartbeat_tick: usize,
storage: MemStorage,
logger: &Logger,
) -> RawNode<MemStorage> {
let config = new_test_config(id, election_tick, heartbeat_tick);
new_raw_node_with_config(peers, &config, storage, logger)
}
fn new_raw_node_with_config(
peers: Vec<u64>,
config: &Config,
storage: MemStorage,
logger: &Logger,
) -> RawNode<MemStorage> {
if storage.initial_state().unwrap().initialized() && peers.is_empty() {
panic!("new_raw_node with empty peers on initialized store");
}
if !peers.is_empty() && !storage.initial_state().unwrap().initialized() {
storage
.wl()
.apply_snapshot(new_snapshot(1, 1, peers))
.unwrap();
}
RawNode::new(config, storage, logger).unwrap()
}
/// Ensures that RawNode::step ignore local message.
#[test]
fn test_raw_node_step() {
let l = default_logger();
for msg_t in MessageType::values() {
let s = new_storage();
s.wl().set_hardstate(hard_state(1, 1, 0));
// Append an empty entry to make sure the non-local messages (like
// vote requests) are ignored and don't trigger assertions.
s.wl().append(&[new_entry(1, 1, None)]).unwrap();
s.wl().apply_snapshot(new_snapshot(1, 1, vec![1])).unwrap();
let mut raw_node = new_raw_node(1, vec![1], 10, 1, new_storage(), &l);
let res = raw_node.step(new_message(0, 0, *msg_t, 0));
// LocalMsg should be ignored.
if raw_node::is_local_msg(*msg_t) {
assert_eq!(res, Err(Error::StepLocalMsg), "{msg_t:?}");
}
}
}
/// Ensures that MsgReadIndex to old leader gets forwarded to the new leader and
/// 'send' method does not attach its term.
#[test]
fn test_raw_node_read_index_to_old_leader() {
let l = default_logger();
let r1 = new_test_raft(1, vec![1, 2, 3], 10, 1, new_storage(), &l);
let r2 = new_test_raft(2, vec![1, 2, 3], 10, 1, new_storage(), &l);
let r3 = new_test_raft(3, vec![1, 2, 3], 10, 1, new_storage(), &l);
let mut nt = Network::new(vec![Some(r1), Some(r2), Some(r3)], &l);
// elect r1 as leader
nt.send(vec![new_message(1, 1, MessageType::MsgHup, 0)]);
let mut test_entries = Entry::default();
test_entries.data = (b"testdata" as &'static [u8]).into();
// send readindex request to r2(follower)
let _ = nt.peers.get_mut(&2).unwrap().step(new_message_with_entries(
2,
2,
MessageType::MsgReadIndex,
vec![test_entries.clone()],
));
// verify r2(follower) forwards this message to r1(leader) with term not set
assert_eq!(nt.peers[&2].msgs.len(), 1);
let read_index_msg1 =
new_message_with_entries(2, 1, MessageType::MsgReadIndex, vec![test_entries.clone()]);
assert_eq!(read_index_msg1, nt.peers[&2].msgs[0]);
// send readindex request to r3(follower)
let _ = nt.peers.get_mut(&3).unwrap().step(new_message_with_entries(
3,
3,
MessageType::MsgReadIndex,
vec![test_entries.clone()],
));
// verify r3(follower) forwards this message to r1(leader) with term not set as well.
assert_eq!(nt.peers[&3].msgs.len(), 1);
let read_index_msg2 =
new_message_with_entries(3, 1, MessageType::MsgReadIndex, vec![test_entries.clone()]);
assert_eq!(nt.peers[&3].msgs[0], read_index_msg2);
// now elect r3 as leader
nt.send(vec![new_message(3, 3, MessageType::MsgHup, 0)]);
// let r1 steps the two messages previously we got from r2, r3
let _ = nt.peers.get_mut(&1).unwrap().step(read_index_msg1);
let _ = nt.peers.get_mut(&1).unwrap().step(read_index_msg2);
// verify r1(follower) forwards these messages again to r3(new leader)
assert_eq!(nt.peers[&1].msgs.len(), 2);
assert_eq!(
nt.peers[&1].msgs[0],
new_message_with_entries(2, 3, MessageType::MsgReadIndex, vec![test_entries.clone()])
);
assert_eq!(
nt.peers[&1].msgs[1],
new_message_with_entries(3, 3, MessageType::MsgReadIndex, vec![test_entries])
);
}
/// Tests the configuration change mechanism. Each test case sends a configuration
/// change which is either simple or joint, verifies that it applies and that the
/// resulting ConfState matches expectations, and for joint configurations makes
/// sure that they are exited successfully.
#[test]
fn test_raw_node_propose_and_conf_change() {
let l = default_logger();
let mut test_cases: Vec<(Box<dyn ConfChangeI>, _, _)> = vec![
// V1 config change.
(
Box::new(conf_change(ConfChangeType::AddNode, 2)),
conf_state(vec![1, 2], vec![]),
None,
),
];
// Proposing the same as a V2 change works just the same, without entering
// a joint config.
let single = new_conf_change_single(2, ConfChangeType::AddNode);
test_cases.push((
Box::new(conf_change_v2(vec![single])),
conf_state(vec![1, 2], vec![]),
None,
));
// Ditto if we add it as a learner instead.
let single = new_conf_change_single(2, ConfChangeType::AddLearnerNode);
test_cases.push((
Box::new(conf_change_v2(vec![single])),
conf_state(vec![1], vec![2]),
None,
));
// We can ask explicitly for joint consensus if we want it.
let single = new_conf_change_single(2, ConfChangeType::AddLearnerNode);
let mut cc = conf_change_v2(vec![single]);
cc.set_transition(ConfChangeTransition::Explicit);
let cs = conf_state_v2(vec![1], vec![2], vec![1], vec![], false);
test_cases.push((Box::new(cc), cs, Some(conf_state(vec![1], vec![2]))));
// Ditto, but with implicit transition (the harness checks this).
let single = new_conf_change_single(2, ConfChangeType::AddLearnerNode);
let mut cc = conf_change_v2(vec![single]);
cc.set_transition(ConfChangeTransition::Implicit);
let cs = conf_state_v2(vec![1], vec![2], vec![1], vec![], true);
test_cases.push((Box::new(cc), cs, Some(conf_state(vec![1], vec![2]))));
// Add a new node and demote n1. This exercises the interesting case in
// which we really need joint config changes and also need LearnersNext.
let cc = conf_change_v2(vec![
new_conf_change_single(2, ConfChangeType::AddNode),
new_conf_change_single(1, ConfChangeType::AddLearnerNode),
new_conf_change_single(3, ConfChangeType::AddLearnerNode),
]);
let cs = conf_state_v2(vec![2], vec![3], vec![1], vec![1], true);
test_cases.push((Box::new(cc), cs, Some(conf_state(vec![2], vec![1, 3]))));
// Ditto explicit.
let mut cc = conf_change_v2(vec![
new_conf_change_single(2, ConfChangeType::AddNode),
new_conf_change_single(1, ConfChangeType::AddLearnerNode),
new_conf_change_single(3, ConfChangeType::AddLearnerNode),
]);
cc.set_transition(ConfChangeTransition::Explicit);
let cs = conf_state_v2(vec![2], vec![3], vec![1], vec![1], false);
test_cases.push((Box::new(cc), cs, Some(conf_state(vec![2], vec![1, 3]))));
// Ditto implicit.
let mut cc = conf_change_v2(vec![
new_conf_change_single(2, ConfChangeType::AddNode),
new_conf_change_single(1, ConfChangeType::AddLearnerNode),
new_conf_change_single(3, ConfChangeType::AddLearnerNode),
]);
cc.set_transition(ConfChangeTransition::Implicit);
let cs = conf_state_v2(vec![2], vec![3], vec![1], vec![1], true);
test_cases.push((Box::new(cc), cs, Some(conf_state(vec![2], vec![1, 3]))));
for (cc, exp, exp2) in test_cases {
let s = new_storage();
let mut raw_node = new_raw_node(1, vec![1], 10, 1, s.clone(), &l);
raw_node.campaign().unwrap();
let mut proposed = false;
let mut ccdata = vec![];
// Propose the ConfChange, wait until it applies, save the resulting ConfState.
let mut cs = None;
while cs.is_none() {
let mut rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
let mut handle_committed_entries =
|rn: &mut RawNode<MemStorage>, committed_entries: Vec<Entry>| {
for e in committed_entries {
if e.get_entry_type() == EntryType::EntryConfChange {
let mut cc = ConfChange::default();
cc.merge_from_bytes(e.get_data()).unwrap();
cs = Some(rn.apply_conf_change(&cc).unwrap());
} else if e.get_entry_type() == EntryType::EntryConfChangeV2 {
let mut cc = ConfChangeV2::default();
cc.merge_from_bytes(e.get_data()).unwrap();
cs = Some(rn.apply_conf_change(&cc).unwrap());
}
}
};
handle_committed_entries(&mut raw_node, rd.take_committed_entries());
let is_leader = rd.ss().is_some_and(|ss| ss.leader_id == raw_node.raft.id);
let mut light_rd = raw_node.advance(rd);
handle_committed_entries(&mut raw_node, light_rd.take_committed_entries());
raw_node.advance_apply();
// Once we are the leader, propose a command and a ConfChange.
if !proposed && is_leader {
raw_node.propose(vec![], b"somedata".to_vec()).unwrap();
if let Some(v1) = cc.as_v1() {
ccdata = v1.write_to_bytes().unwrap();
raw_node.propose_conf_change(vec![], v1.clone()).unwrap();
} else {
let v2 = cc.as_v2().clone().into_owned();
ccdata = v2.write_to_bytes().unwrap();
raw_node.propose_conf_change(vec![], v2).unwrap();
}
proposed = true;
}
}
// Check that the last index is exactly the conf change we put in,
// down to the bits. Note that this comes from the Storage, which
// will not reflect any unstable entries that we'll only be presented
// with in the next Ready.
let last_index = s.last_index().unwrap();
let entries = s
.entries(
last_index - 1,
last_index + 1,
NO_LIMIT,
GetEntriesContext::empty(false),
)
.unwrap();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].get_data(), b"somedata");
if cc.as_v1().is_some() {
assert_eq!(entries[1].get_entry_type(), EntryType::EntryConfChange);
} else {
assert_eq!(entries[1].get_entry_type(), EntryType::EntryConfChangeV2);
}
assert_eq!(ccdata, entries[1].get_data());
assert_eq!(exp, cs.unwrap());
let conf_index = if cc.as_v2().enter_joint() == Some(true) {
// If this is an auto-leaving joint conf change, it will have
// appended the entry that auto-leaves, so add one to the last
// index that forms the basis of our expectations on
// pendingConfIndex. (Recall that lastIndex was taken from stable
// storage, but this auto-leaving entry isn't on stable storage
// yet).
last_index + 1
} else {
last_index
};
assert_eq!(conf_index, raw_node.raft.pending_conf_index);
// Move the RawNode along. If the ConfChange was simple, nothing else
// should happen. Otherwise, we're in a joint state, which is either
// left automatically or not. If not, we add the proposal that leaves
// it manually.
let mut rd = raw_node.ready();
let mut context = vec![];
if !exp.auto_leave {
assert!(rd.entries().is_empty());
if exp2.is_none() {
continue;
}
context = b"manual".to_vec();
let mut cc = conf_change_v2(vec![]);
cc.set_context(context.clone().into());
raw_node.propose_conf_change(vec![], cc).unwrap();
rd = raw_node.ready();
}
// Check that the right ConfChange comes out.
assert_eq!(rd.entries().len(), 1);
assert_eq!(
rd.entries()[0].get_entry_type(),
EntryType::EntryConfChangeV2
);
let mut leave_cc = ConfChangeV2::default();
leave_cc
.merge_from_bytes(rd.entries()[0].get_data())
.unwrap();
assert_eq!(context, leave_cc.get_context(), "{:?}", cc.as_v2());
// Lie and pretend the ConfChange applied. It won't do so because now
// we require the joint quorum and we're only running one node.
let cs = raw_node.apply_conf_change(&leave_cc).unwrap();
assert_eq!(cs, exp2.unwrap());
}
}
/// Tests the configuration change auto leave even leader lost leadership.
#[test]
fn test_raw_node_joint_auto_leave() {
let l = default_logger();
let single = new_conf_change_single(2, ConfChangeType::AddLearnerNode);
let mut test_cc = conf_change_v2(vec![single]);
test_cc.set_transition(ConfChangeTransition::Implicit);
let exp_cs = conf_state_v2(vec![1], vec![2], vec![1], vec![], true);
let exp_cs2 = conf_state(vec![1], vec![2]);
let s = new_storage();
let mut raw_node = new_raw_node(1, vec![1], 10, 1, s.clone(), &l);
raw_node.campaign().unwrap();
let mut proposed = false;
let ccdata = test_cc.write_to_bytes().unwrap();
// Propose the ConfChange, wait until it applies, save the resulting ConfState.
let mut cs = None;
while cs.is_none() {
let mut rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
let mut handle_committed_entries =
|rn: &mut RawNode<MemStorage>, committed_entries: Vec<Entry>| {
for e in committed_entries {
if e.get_entry_type() == EntryType::EntryConfChangeV2 {
let mut cc = ConfChangeV2::default();
cc.merge_from_bytes(e.get_data()).unwrap();
// Force it step down.
let mut msg = new_message(1, 1, MessageType::MsgHeartbeatResponse, 0);
msg.term = rn.raft.term + 1;
rn.step(msg).unwrap();
cs = Some(rn.apply_conf_change(&cc).unwrap());
}
}
};
handle_committed_entries(&mut raw_node, rd.take_committed_entries());
let is_leader = rd.ss().is_some_and(|ss| ss.leader_id == raw_node.raft.id);
let mut light_rd = raw_node.advance(rd);
handle_committed_entries(&mut raw_node, light_rd.take_committed_entries());
raw_node.advance_apply();
// Once we are the leader, propose a command and a ConfChange.
if !proposed && is_leader {
raw_node.propose(vec![], b"somedata".to_vec()).unwrap();
raw_node
.propose_conf_change(vec![], test_cc.clone())
.unwrap();
proposed = true;
}
}
// Check that the last index is exactly the conf change we put in,
// down to the bits. Note that this comes from the Storage, which
// will not reflect any unstable entries that we'll only be presented
// with in the next Ready.
let last_index = s.last_index().unwrap();
let entries = s
.entries(
last_index - 1,
last_index + 1,
NO_LIMIT,
GetEntriesContext::empty(false),
)
.unwrap();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].get_data(), b"somedata");
assert_eq!(entries[1].get_entry_type(), EntryType::EntryConfChangeV2);
assert_eq!(ccdata, entries[1].get_data());
assert_eq!(exp_cs, cs.unwrap());
assert_eq!(0, raw_node.raft.pending_conf_index);
// Move the RawNode along. It should not leave joint because it's follower.
let mut rd = raw_node.ready();
assert!(rd.entries().is_empty());
let _ = raw_node.advance(rd);
// Make it leader again. It should leave joint automatically after moving apply index.
raw_node.campaign().unwrap();
rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
let _ = raw_node.advance(rd);
rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
// Check that the right ConfChange comes out.
assert_eq!(rd.entries().len(), 1);
assert_eq!(
rd.entries()[0].get_entry_type(),
EntryType::EntryConfChangeV2
);
let mut leave_cc = ConfChangeV2::default();
leave_cc
.merge_from_bytes(rd.entries()[0].get_data())
.unwrap();
assert!(leave_cc.get_context().is_empty());
// Lie and pretend the ConfChange applied. It won't do so because now
// we require the joint quorum and we're only running one node.
let cs = raw_node.apply_conf_change(&leave_cc).unwrap();
assert_eq!(cs, exp_cs2);
}
/// Ensures that two proposes to add the same node should not affect the later propose
/// to add new node.
#[test]
fn test_raw_node_propose_add_duplicate_node() {
let l = default_logger();
let s = new_storage();
let mut raw_node = new_raw_node(1, vec![1], 10, 1, s.clone(), &l);
raw_node.campaign().expect("");
loop {
let rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
if rd.ss().is_some_and(|ss| ss.leader_id == raw_node.raft.id) {
let _ = raw_node.advance(rd);
break;
}
let _ = raw_node.advance(rd);
}
let mut propose_conf_change_and_apply = |cc| {
raw_node.propose_conf_change(vec![], cc).expect("");
let mut rd = raw_node.ready();
s.wl().append(rd.entries()).expect("");
let handle_committed_entries =
|rn: &mut RawNode<MemStorage>, committed_entries: Vec<Entry>| {
for e in committed_entries {
if e.get_entry_type() == EntryType::EntryConfChange {
let mut conf_change = ConfChange::default();
conf_change.merge_from_bytes(&e.data).unwrap();
rn.apply_conf_change(&conf_change).unwrap();
}
}
};
handle_committed_entries(&mut raw_node, rd.take_committed_entries());
let mut light_rd = raw_node.advance(rd);
handle_committed_entries(&mut raw_node, light_rd.take_committed_entries());
raw_node.advance_apply();
};
let cc1 = conf_change(ConfChangeType::AddNode, 1);
let ccdata1 = cc1.write_to_bytes().unwrap();
propose_conf_change_and_apply(cc1.clone());
// try to add the same node again
propose_conf_change_and_apply(cc1);
// the new node join should be ok
let cc2 = conf_change(ConfChangeType::AddNode, 2);
let ccdata2 = cc2.write_to_bytes().unwrap();
propose_conf_change_and_apply(cc2);
let last_index = s.last_index().unwrap();
// the last three entries should be: ConfChange cc1, cc1, cc2
let mut entries = s
.entries(
last_index - 2,
last_index + 1,
None,
GetEntriesContext::empty(false),
)
.unwrap();
assert_eq!(entries.len(), 3);
assert_eq!(entries[0].take_data(), ccdata1);
assert_eq!(entries[2].take_data(), ccdata2);
}
#[test]
fn test_raw_node_propose_add_learner_node() -> Result<()> {
let l = default_logger();
let s = new_storage();
let mut raw_node = new_raw_node(1, vec![1], 10, 1, s.clone(), &l);
let rd = raw_node.ready();
must_cmp_ready(&rd, &None, &None, &[], &[], &None, true, true, false);
let _ = raw_node.advance(rd);
raw_node.campaign().expect("");
loop {
let rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
if rd.ss().is_some_and(|ss| ss.leader_id == raw_node.raft.id) {
let _ = raw_node.advance(rd);
break;
}
let _ = raw_node.advance(rd);
}
// propose add learner node and check apply state
let cc = conf_change(ConfChangeType::AddLearnerNode, 2);
raw_node.propose_conf_change(vec![], cc).expect("");
let rd = raw_node.ready();
s.wl().append(rd.entries()).expect("");
let light_rd = raw_node.advance(rd);
assert_eq!(
light_rd.committed_entries().len(),
1,
"should committed the conf change entry"
);
let e = &light_rd.committed_entries()[0];
assert_eq!(e.get_entry_type(), EntryType::EntryConfChange);
let mut conf_change = ConfChange::default();
conf_change.merge_from_bytes(&e.data).unwrap();
let conf_state = raw_node.apply_conf_change(&conf_change)?;
assert_eq!(conf_state.voters, vec![1]);
assert_eq!(conf_state.learners, vec![2]);
Ok(())
}
/// Ensures that RawNode.read_index sends the MsgReadIndex message to the underlying
/// raft. It also ensures that ReadState can be read out.
#[test]
fn test_raw_node_read_index() {
let l = default_logger();
let wrequest_ctx = b"somedata".to_vec();
let wrs = vec![ReadState {
index: 2u64,
request_ctx: wrequest_ctx.clone(),
}];
let s = new_storage();
let mut raw_node = new_raw_node(1, vec![1], 10, 1, s.clone(), &l);
raw_node.campaign().expect("");
loop {
let rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
if rd.ss().is_some_and(|ss| ss.leader_id == raw_node.raft.id) {
let _ = raw_node.advance(rd);
// Once we are the leader, issue a read index request
raw_node.read_index(wrequest_ctx);
break;
}
let _ = raw_node.advance(rd);
}
// ensure the read_states can be read out
assert!(!raw_node.raft.read_states.is_empty());
assert!(raw_node.has_ready());
let rd = raw_node.ready();
assert_eq!(*rd.read_states(), wrs);
s.wl().append(rd.entries()).expect("");
let _ = raw_node.advance(rd);
// ensure raft.read_states is reset after advance
assert!(!raw_node.has_ready());
assert!(raw_node.raft.read_states.is_empty());
}
/// Ensures that a node can be started correctly. Note that RawNode requires the
/// application to bootstrap the state, i.e. it does not accept peers and will not
/// create faux configuration change entries.
#[test]
fn test_raw_node_start() {
let l = default_logger();
let store = new_storage();
let mut raw_node = new_raw_node(1, vec![1], 10, 1, store.clone(), &l);
let rd = raw_node.ready();
must_cmp_ready(&rd, &None, &None, &[], &[], &None, true, true, false);
let _ = raw_node.advance(rd);
raw_node.campaign().expect("");
let rd = raw_node.ready();
must_cmp_ready(
&rd,
&Some(soft_state(1, StateRole::Leader)),
&Some(hard_state(2, 1, 1)),
&[new_entry(2, 2, None)],
&[],
&None,
true,
true,
true,
);
store.wl().append(rd.entries()).expect("");
let light_rd = raw_node.advance(rd);
assert_eq!(light_rd.commit_index(), Some(2));
assert_eq!(*light_rd.committed_entries(), vec![new_entry(2, 2, None)]);
assert!(!raw_node.has_ready());
raw_node.propose(vec![], b"somedata".to_vec()).expect("");
let rd = raw_node.ready();
must_cmp_ready(
&rd,
&None,
&None,
&[new_entry(2, 3, SOME_DATA)],
&[],
&None,
true,
true,
true,
);
store.wl().append(rd.entries()).expect("");
let light_rd = raw_node.advance(rd);
assert_eq!(light_rd.commit_index(), Some(3));
assert_eq!(
*light_rd.committed_entries(),
vec![new_entry(2, 3, SOME_DATA)]
);
assert!(!raw_node.has_ready());
}
#[test]
fn test_raw_node_restart() {
let l = default_logger();
let entries = vec![empty_entry(1, 1), new_entry(1, 2, Some("foo"))];
let mut raw_node = {
let store = new_storage();
store.wl().set_hardstate(hard_state(1, 1, 0));
store.wl().append(&entries).unwrap();
new_raw_node(1, vec![], 10, 1, store, &l)
};
let rd = raw_node.ready();
must_cmp_ready(
&rd,
&None,
&None,
&[],
&entries[..1],
&None,
true,
true,
false,
);
let _ = raw_node.advance(rd);
assert!(!raw_node.has_ready());
}
#[test]
fn test_raw_node_restart_from_snapshot() {
let l = default_logger();
let snap = new_snapshot(2, 1, vec![1, 2]);
let entries = vec![new_entry(1, 3, Some("foo"))];
let mut raw_node = {
let store = new_storage();
store.wl().apply_snapshot(snap).unwrap();
store.wl().append(&entries).unwrap();
store.wl().set_hardstate(hard_state(1, 3, 0));
RawNode::new(&new_test_config(1, 10, 1), store, &l).unwrap()
};
let rd = raw_node.ready();
must_cmp_ready(&rd, &None, &None, &[], &entries, &None, true, true, false);
let _ = raw_node.advance(rd);
assert!(!raw_node.has_ready());
}
// test_skip_bcast_commit ensures that empty commit message is not sent out
// when skip_bcast_commit is true.
#[test]
fn test_skip_bcast_commit() {
let l = default_logger();
let mut config = new_test_config(1, 10, 1);
config.skip_bcast_commit = true;
let s = MemStorage::new_with_conf_state((vec![1, 2, 3], vec![]));
let r1 = new_test_raft_with_config(&config, s, &l);
let r2 = new_test_raft(2, vec![1, 2, 3], 10, 1, new_storage(), &l);
let r3 = new_test_raft(3, vec![1, 2, 3], 10, 1, new_storage(), &l);
let mut nt = Network::new(vec![Some(r1), Some(r2), Some(r3)], &l);
// elect r1 as leader
nt.send(vec![new_message(1, 1, MessageType::MsgHup, 0)]);
// Without bcast commit, followers will not update its commit index immediately.
let mut test_entries = Entry::default();
test_entries.data = (b"testdata" as &'static [u8]).into();
let msg = new_message_with_entries(1, 1, MessageType::MsgPropose, vec![test_entries]);
nt.send(vec![msg.clone()]);
assert_eq!(nt.peers[&1].raft_log.committed, 2);
assert_eq!(nt.peers[&2].raft_log.committed, 1);
assert_eq!(nt.peers[&3].raft_log.committed, 1);
// After bcast heartbeat, followers will be informed the actual commit index.
for _ in 0..nt.peers[&1].randomized_election_timeout() {
nt.peers.get_mut(&1).unwrap().tick();
}
nt.send(vec![new_message(1, 1, MessageType::MsgHup, 0)]);
assert_eq!(nt.peers[&2].raft_log.committed, 2);
assert_eq!(nt.peers[&3].raft_log.committed, 2);
// The feature should be able to be adjusted at run time.
nt.peers.get_mut(&1).unwrap().skip_bcast_commit(false);
nt.send(vec![msg.clone()]);
assert_eq!(nt.peers[&1].raft_log.committed, 3);
assert_eq!(nt.peers[&2].raft_log.committed, 3);
assert_eq!(nt.peers[&3].raft_log.committed, 3);
nt.peers.get_mut(&1).unwrap().skip_bcast_commit(true);
// Later proposal should commit former proposal.
nt.send(vec![msg.clone()]);
nt.send(vec![msg]);
assert_eq!(nt.peers[&1].raft_log.committed, 5);
assert_eq!(nt.peers[&2].raft_log.committed, 4);
assert_eq!(nt.peers[&3].raft_log.committed, 4);
// When committing conf change, leader should always bcast commit.
let mut cc = ConfChange::default();
cc.set_change_type(ConfChangeType::RemoveNode);
cc.node_id = 3;
let data = cc.write_to_bytes().unwrap();
let mut cc_entry = Entry::default();
cc_entry.set_entry_type(EntryType::EntryConfChange);
cc_entry.data = data.into();
nt.send(vec![new_message_with_entries(
1,
1,
MessageType::MsgPropose,
vec![cc_entry],
)]);
assert!(nt.peers[&1].should_bcast_commit());
assert!(nt.peers[&2].should_bcast_commit());
assert!(nt.peers[&3].should_bcast_commit());
assert_eq!(nt.peers[&1].raft_log.committed, 6);
assert_eq!(nt.peers[&2].raft_log.committed, 6);
assert_eq!(nt.peers[&3].raft_log.committed, 6);
}
/// test_set_priority checks the set_priority function in RawNode.
#[test]
fn test_set_priority() {
let l = default_logger();
let mut raw_node = new_raw_node(1, vec![1], 10, 1, new_storage(), &l);
let priorities = vec![0, 1, 5, 10, 10000];
for p in priorities {
raw_node.set_priority(p);
assert_eq!(raw_node.raft.priority, p);
}
}
// TestNodeBoundedLogGrowthWithPartition tests a scenario where a leader is
// partitioned from a quorum of nodes. It verifies that the leader's log is
// protected from unbounded growth even as new entries continue to be proposed.
// This protection is provided by the max_uncommitted_size configuration.
#[test]
fn test_bounded_uncommitted_entries_growth_with_partition() {
let l = default_logger();
let config = &Config {
id: 1,
max_uncommitted_size: 12,
..Config::default()
};
let s = new_storage();
let mut raw_node = new_raw_node_with_config(vec![1], config, s.clone(), &l);
// wait raw_node to be leader
raw_node.campaign().unwrap();
loop {
let rd = raw_node.ready();
s.wl().set_hardstate(rd.hs().unwrap().clone());
s.wl().append(rd.entries()).unwrap();
if rd
.ss()
.is_some_and(|ss| ss.leader_id == raw_node.raft.leader_id)
{
let _ = raw_node.advance(rd);
break;
}
let _ = raw_node.advance(rd);
}
// should be accepted
let data = b"hello world!";
raw_node.propose(vec![], data.to_vec()).unwrap();
// shoule be dropped
let result = raw_node.propose(vec![], data.to_vec());
assert_eq!(result.unwrap_err(), Error::ProposalDropped);
// should be accepted when previous data has been committed
let rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
let _ = raw_node.advance(rd);
let data = b"hello world!".to_vec();
raw_node.propose(vec![], data).unwrap();
}
fn prepare_async_entries(raw_node: &mut RawNode<MemStorage>, s: &MemStorage) {
raw_node.raft.become_candidate();
raw_node.raft.become_leader();
let rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();
let _ = raw_node.advance(rd);
let data: Vec<u8> = vec![1; 1000];
for _ in 0..10 {
raw_node.propose(vec![], data.to_vec()).unwrap();
}
let rd = raw_node.ready();
let entries = rd.entries().clone();
assert_eq!(entries.len(), 10);
s.wl().append(&entries).unwrap();
let msgs = rd.messages();
// 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).
assert_eq!(msgs.len(), 1);
assert_eq!(msgs[0].msg_type, MessageType::MsgAppend);
assert_eq!(msgs[0].entries.len(), 2);
let _ = raw_node.advance_append(rd);
s.wl().trigger_log_unavailable(true);
// Become replicate state
let mut append_response = new_message(2, 1, MessageType::MsgAppendResponse, 0);
append_response.set_term(2);
append_response.set_index(2);
raw_node.step(append_response).unwrap();
}
// Test entries are handled properly when they are fetched asynchronously
#[test]
fn test_raw_node_with_async_entries() {
let l = default_logger();
let mut cfg = new_test_config(1, 10, 1);
cfg.max_size_per_msg = 2048;
let s = new_storage();
let mut raw_node = new_raw_node_with_config(vec![1, 2], &cfg, s.clone(), &l);
prepare_async_entries(&mut raw_node, &s);
// No entries are sent because the entries are temporarily unavailable
let rd = raw_node.ready();
let entries = rd.entries().clone();
s.wl().append(&entries).unwrap();
let msgs = rd.messages();
assert_eq!(msgs.len(), 0);
let _ = raw_node.advance_append(rd);
// Entries are sent when the entries are ready which is informed by `on_entries_fetched`.
s.wl().trigger_log_unavailable(false);
let context = s.wl().take_get_entries_context().unwrap();
raw_node.on_entries_fetched(context);
let rd = raw_node.ready();
let entries = rd.entries().clone();
s.wl().append(&entries).unwrap();
let msgs = rd.messages();
assert_eq!(msgs.len(), 5);
assert_eq!(msgs[0].msg_type, MessageType::MsgAppend);
assert_eq!(msgs[0].entries.len(), 2);
let _ = raw_node.advance_append(rd);
}
// Test if async fetch entries works well when there is a remove node conf-change.
#[test]
fn test_raw_node_with_async_entries_to_removed_node() {
let l = default_logger();
let mut cfg = new_test_config(1, 10, 1);
cfg.max_size_per_msg = 2048;
let s = new_storage();
let mut raw_node = new_raw_node_with_config(vec![1, 2], &cfg, s.clone(), &l);
prepare_async_entries(&mut raw_node, &s);
raw_node.apply_conf_change(&remove_node(2)).unwrap();
// Entries are not sent due to the node is removed.
s.wl().trigger_log_unavailable(false);
let context = s.wl().take_get_entries_context().unwrap();
raw_node.on_entries_fetched(context);
let rd = raw_node.ready();
assert_eq!(rd.entries().len(), 0);
assert_eq!(rd.messages().len(), 0);
let _ = raw_node.advance_append(rd);
}
// Test if async fetch entries works well when there is a leader step-down.
#[test]
fn test_raw_node_with_async_entries_on_follower() {
let l = default_logger();
let mut cfg = new_test_config(1, 10, 1);
cfg.max_size_per_msg = 2048;
let s = new_storage();
let mut raw_node = new_raw_node_with_config(vec![1, 2], &cfg, s.clone(), &l);
prepare_async_entries(&mut raw_node, &s);
// Set recent inactive to step down leader
raw_node.raft.mut_prs().get_mut(2).unwrap().recent_active = false;
let mut msg = Message::new();
msg.set_to(1);
msg.set_msg_type(MessageType::MsgCheckQuorum);
raw_node.raft.step(msg).unwrap();
assert_ne!(raw_node.raft.state, StateRole::Leader);
// Entries are not sent due to the leader is changed.
s.wl().trigger_log_unavailable(false);
let context = s.wl().take_get_entries_context().unwrap();
raw_node.on_entries_fetched(context);
let rd = raw_node.ready();
assert_eq!(rd.entries().len(), 0);
assert_eq!(rd.messages().len(), 0);
let _ = raw_node.advance_append(rd);
}
#[test]
fn test_raw_node_async_entries_with_leader_change() {
let l = default_logger();
let mut cfg = new_test_config(1, 10, 1);
cfg.max_size_per_msg = 2048;
let s = new_storage();
let mut raw_node = new_raw_node_with_config(vec![1, 2], &cfg, s.clone(), &l);
raw_node.raft.become_candidate();
raw_node.raft.become_leader();
let rd = raw_node.ready();
s.wl().append(rd.entries()).unwrap();