-
Notifications
You must be signed in to change notification settings - Fork 407
/
Copy pathraft.rs
2178 lines (2000 loc) · 80.3 KB
/
raft.rs
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 2016 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
// 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.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::cmp;
use eraftpb::{Entry, EntryType, HardState, Message, MessageType, Snapshot};
use fxhash::FxHashMap;
use protobuf::RepeatedField;
use rand::{self, Rng};
use super::errors::{Error, Result, StorageError};
use super::progress::{Inflights, Progress, ProgressSet, ProgressState};
use super::raft_log::{self, RaftLog};
use super::read_only::{ReadOnly, ReadOnlyOption, ReadState};
use super::storage::Storage;
// CAMPAIGN_PRE_ELECTION represents the first phase of a normal election when
// Config.pre_vote is true.
const CAMPAIGN_PRE_ELECTION: &[u8] = b"CampaignPreElection";
// CAMPAIGN_ELECTION represents a normal (time-based) election (the second phase
// of the election when Config.pre_vote is true).
const CAMPAIGN_ELECTION: &[u8] = b"CampaignElection";
// CAMPAIGN_TRANSFER represents the type of leader transfer.
const CAMPAIGN_TRANSFER: &[u8] = b"CampaignTransfer";
/// The role of the node.
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum StateRole {
/// The node is a follower of the leader.
Follower,
/// The node could become a leader.
Candidate,
/// The node is a leader.
Leader,
/// The node could become a candidate, if `prevote` is enabled.
PreCandidate,
}
impl Default for StateRole {
fn default() -> StateRole {
StateRole::Follower
}
}
/// A constant represents invalid id of raft.
pub const INVALID_ID: u64 = 0;
/// A constant represents invalid index of raft log.
pub const INVALID_INDEX: u64 = 0;
/// Config contains the parameters to start a raft.
pub struct Config {
/// The identity of the local raft. It cannot be 0, and must be unique in the group.
pub id: u64,
/// The IDs of all nodes (including self) in
/// the raft cluster. It should only be set when starting a new
/// raft cluster.
/// Restarting raft from previous configuration will panic if
/// peers is set.
/// peer is private and only used for testing right now.
pub peers: Vec<u64>,
/// The IDs of all learner nodes (maybe include self if
/// the local node is a learner) in the raft cluster.
/// learners only receives entries from the leader node. It does not vote
/// or promote itself.
pub learners: Vec<u64>,
/// The number of node.tick invocations that must pass between
/// elections. That is, if a follower does not receive any message from the
/// leader of current term before ElectionTick has elapsed, it will become
/// candidate and start an election. election_tick must be greater than
/// HeartbeatTick. We suggest election_tick = 10 * HeartbeatTick to avoid
/// unnecessary leader switching
pub election_tick: usize,
/// HeartbeatTick is the number of node.tick invocations that must pass between
/// heartbeats. That is, a leader sends heartbeat messages to maintain its
/// leadership every heartbeat ticks.
pub heartbeat_tick: usize,
/// Applied is the last applied index. It should only be set when restarting
/// raft. raft will not return entries to the application smaller or equal to Applied.
/// If Applied is unset when restarting, raft might return previous applied entries.
/// This is a very application dependent configuration.
pub applied: u64,
/// Limit the max size of each append message. Smaller value lowers
/// the raft recovery cost(initial probing and message lost during normal operation).
/// On the other side, it might affect the throughput during normal replication.
/// Note: math.MaxUusize64 for unlimited, 0 for at most one entry per message.
pub max_size_per_msg: u64,
/// Limit the max number of in-flight append messages during optimistic
/// replication phase. The application transportation layer usually has its own sending
/// buffer over TCP/UDP. Set to avoid overflowing that sending buffer.
/// TODO: feedback to application to limit the proposal rate?
pub max_inflight_msgs: usize,
/// Specify if the leader should check quorum activity. Leader steps down when
/// quorum is not active for an electionTimeout.
pub check_quorum: bool,
/// Enables the Pre-Vote algorithm described in raft thesis section
/// 9.6. This prevents disruption when a node that has been partitioned away
/// rejoins the cluster.
pub pre_vote: bool,
/// The range of election timeout. In some cases, we hope some nodes has less possibility
/// to become leader. This configuration ensures that the randomized election_timeout
/// will always be suit in [min_election_tick, max_election_tick).
/// If it is 0, then election_tick will be chosen.
pub min_election_tick: usize,
/// If it is 0, then 2 * election_tick will be chosen.
pub max_election_tick: usize,
/// Choose the linearizability mode or the lease mode to read data. If you don’t care about the read consistency and want a higher read performance, you can use the lease mode.
pub read_only_option: ReadOnlyOption,
/// Don't broadcast an empty raft entry to notify follower to commit an entry.
/// This may make follower wait a longer time to apply an entry. This configuration
/// May affect proposal forwarding and follower read.
pub skip_bcast_commit: bool,
/// A human-friendly tag used for logging.
pub tag: String,
}
impl Default for Config {
fn default() -> Self {
const HEARTBEAT_TICK: usize = 2;
Self {
id: 0,
peers: vec![],
learners: vec![],
election_tick: HEARTBEAT_TICK * 10,
heartbeat_tick: HEARTBEAT_TICK,
applied: 0,
max_size_per_msg: 0,
max_inflight_msgs: 256,
check_quorum: false,
pre_vote: false,
min_election_tick: 0,
max_election_tick: 0,
read_only_option: ReadOnlyOption::Safe,
skip_bcast_commit: false,
tag: "".into(),
}
}
}
impl Config {
/// Creates a new config.
pub fn new(id: u64) -> Self {
Self {
id,
tag: format!("{}", id),
..Self::default()
}
}
/// The minimum number of ticks before an election.
#[inline]
pub fn min_election_tick(&self) -> usize {
if self.min_election_tick == 0 {
self.election_tick
} else {
self.min_election_tick
}
}
/// The maximum number of ticks before an election.
#[inline]
pub fn max_election_tick(&self) -> usize {
if self.max_election_tick == 0 {
2 * self.election_tick
} else {
self.max_election_tick
}
}
/// Runs validations against the config.
pub fn validate(&self) -> Result<()> {
if self.id == INVALID_ID {
return Err(Error::ConfigInvalid("invalid node id".to_owned()));
}
if self.heartbeat_tick == 0 {
return Err(Error::ConfigInvalid(
"heartbeat tick must greater than 0".to_owned(),
));
}
if self.election_tick <= self.heartbeat_tick {
return Err(Error::ConfigInvalid(
"election tick must be greater than heartbeat tick".to_owned(),
));
}
let min_timeout = self.min_election_tick();
let max_timeout = self.max_election_tick();
if min_timeout < self.election_tick {
return Err(Error::ConfigInvalid(format!(
"min election tick {} must not be less than election_tick {}",
min_timeout, self.election_tick
)));
}
if min_timeout >= max_timeout {
return Err(Error::ConfigInvalid(format!(
"min election tick {} should be less than max election tick {}",
min_timeout, max_timeout
)));
}
if self.max_inflight_msgs == 0 {
return Err(Error::ConfigInvalid(
"max inflight messages must be greater than 0".to_owned(),
));
}
Ok(())
}
}
/// SoftState provides state that is useful for logging and debugging.
/// The state is volatile and does not need to be persisted to the WAL.
#[derive(Default, PartialEq, Debug)]
pub struct SoftState {
/// The potential leader of the cluster.
pub leader_id: u64,
/// The soft role this node may take.
pub raft_state: StateRole,
}
/// A struct that represents the raft consensus itself. Stores details concerning the current
/// and possible state the system can take.
#[derive(Default)]
pub struct Raft<T: Storage> {
/// The current election term.
pub term: u64,
/// Which peer this raft is voting for.
pub vote: u64,
/// The ID of this node.
pub id: u64,
/// The current read states
pub read_states: Vec<ReadState>,
/// The log
pub raft_log: RaftLog<T>,
/// The maximum number of messages that can be inflight.
pub max_inflight: usize,
/// The maximum length (in bytes) of all the entries.
pub max_msg_size: u64,
prs: Option<ProgressSet>,
/// The current role of this node.
pub state: StateRole,
/// Whether this is a learner node.
pub is_learner: bool,
/// The current votes.
pub votes: FxHashMap<u64, bool>,
/// The list of messages.
pub msgs: Vec<Message>,
/// The leader id
pub leader_id: u64,
/// ID of the leader transfer target when its value is not None.
/// Follow the procedure defined in raft thesis 3.10.
pub lead_transferee: Option<u64>,
/// Only one conf change may be pending (in the log, but not yet
/// applied) at a time. This is enforced via pending_conf_index, which
/// is set to a value >= the log index of the latest pending
/// configuration change (if any). Config changes are only allowed to
/// be proposed if the leader's applied index is greater than this
/// value.
pub pending_conf_index: u64,
/// The queue of read-only requests.
pub read_only: ReadOnly,
/// Ticks since it reached last electionTimeout when it is leader or candidate.
/// Number of ticks since it reached last electionTimeout or received a
/// valid message from current leader when it is a follower.
pub election_elapsed: usize,
/// Number of ticks since it reached last heartbeatTimeout.
/// only leader keeps heartbeatElapsed.
heartbeat_elapsed: usize,
/// Whether to check the quorum
pub check_quorum: bool,
#[doc(hidden)]
pub pre_vote: bool,
skip_bcast_commit: bool,
heartbeat_timeout: usize,
election_timeout: usize,
// randomized_election_timeout is a random number between
// [min_election_timeout, max_election_timeout - 1]. It gets reset
// when raft changes its state to follower or candidate.
randomized_election_timeout: usize,
min_election_timeout: usize,
max_election_timeout: usize,
/// Will be called when step** is about to be called.
/// return false will skip step**. Only used for test purpose.
#[doc(hidden)]
pub before_step_state: Option<Box<FnMut(&Message) -> bool + Send>>,
/// Tag is only used for logging
tag: String,
}
trait AssertSend: Send {}
impl<T: Storage + Send> AssertSend for Raft<T> {}
fn new_progress(next_idx: u64, ins_size: usize) -> Progress {
Progress {
next_idx,
ins: Inflights::new(ins_size),
..Default::default()
}
}
fn new_message(to: u64, field_type: MessageType, from: Option<u64>) -> Message {
let mut m = Message::new();
m.set_to(to);
if let Some(id) = from {
m.set_from(id);
}
m.set_msg_type(field_type);
m
}
/// Maps vote and pre_vote message types to their correspond responses.
pub fn vote_resp_msg_type(t: MessageType) -> MessageType {
match t {
MessageType::MsgRequestVote => MessageType::MsgRequestVoteResponse,
MessageType::MsgRequestPreVote => MessageType::MsgRequestPreVoteResponse,
_ => panic!("Not a vote message: {:?}", t),
}
}
/// Calculate the quorum of a Raft cluster with the specified total nodes.
pub fn quorum(total: usize) -> usize {
total / 2 + 1
}
impl<T: Storage> Raft<T> {
/// Creates a new raft for use on the node.
pub fn new(c: &Config, store: T) -> Raft<T> {
c.validate().expect("configuration is invalid");
let rs = store.initial_state().expect("");
let conf_state = &rs.conf_state;
let raft_log = RaftLog::new(store, c.tag.clone());
let mut peers: &[u64] = &c.peers;
let mut learners: &[u64] = &c.learners;
if !conf_state.get_nodes().is_empty() || !conf_state.get_learners().is_empty() {
if !peers.is_empty() || !learners.is_empty() {
// TODO: the peers argument is always nil except in
// tests; the argument should be removed and these tests should be
// updated to specify their nodes through a snap
panic!(
"{} cannot specify both new(peers/learners) and ConfState.(Nodes/Learners)",
c.tag
)
}
peers = conf_state.get_nodes();
learners = conf_state.get_learners();
}
let mut r = Raft {
id: c.id,
read_states: Default::default(),
raft_log,
max_inflight: c.max_inflight_msgs,
max_msg_size: c.max_size_per_msg,
prs: Some(ProgressSet::new(peers.len(), learners.len())),
state: StateRole::Follower,
is_learner: false,
check_quorum: c.check_quorum,
pre_vote: c.pre_vote,
read_only: ReadOnly::new(c.read_only_option),
heartbeat_timeout: c.heartbeat_tick,
election_timeout: c.election_tick,
votes: Default::default(),
msgs: Default::default(),
leader_id: Default::default(),
lead_transferee: None,
term: Default::default(),
election_elapsed: Default::default(),
pending_conf_index: Default::default(),
before_step_state: None,
vote: Default::default(),
heartbeat_elapsed: Default::default(),
randomized_election_timeout: 0,
min_election_timeout: c.min_election_tick(),
max_election_timeout: c.max_election_tick(),
skip_bcast_commit: c.skip_bcast_commit,
tag: c.tag.to_owned(),
};
for p in peers {
let pr = new_progress(1, r.max_inflight);
r.mut_prs().insert_voter(*p, pr);
}
for p in learners {
let mut pr = new_progress(1, r.max_inflight);
pr.is_learner = true;
r.mut_prs().insert_learner(*p, pr);
if *p == r.id {
r.is_learner = true;
}
}
if rs.hard_state != HardState::new() {
r.load_state(&rs.hard_state);
}
if c.applied > 0 {
r.raft_log.applied_to(c.applied);
}
let term = r.term;
r.become_follower(term, INVALID_ID);
info!(
"{} newRaft [peers: {:?}, term: {:?}, commit: {}, applied: {}, last_index: {}, \
last_term: {}]",
r.tag,
r.prs().nodes(),
r.term,
r.raft_log.committed,
r.raft_log.get_applied(),
r.raft_log.last_index(),
r.raft_log.last_term()
);
r
}
/// Grabs an immutable reference to the store.
#[inline]
pub fn get_store(&self) -> &T {
self.raft_log.get_store()
}
/// Grabs a mutable reference to the store.
#[inline]
pub fn mut_store(&mut self) -> &mut T {
self.raft_log.mut_store()
}
/// Grabs a reference to the snapshot
#[inline]
pub fn get_snap(&self) -> Option<&Snapshot> {
self.raft_log.get_unstable().snapshot.as_ref()
}
/// Returns the number of pending read-only messages.
#[inline]
pub fn pending_read_count(&self) -> usize {
self.read_only.pending_read_count()
}
/// Returns how many read states exist.
#[inline]
pub fn ready_read_count(&self) -> usize {
self.read_states.len()
}
/// Returns a value representing the softstate at the time of calling.
pub fn soft_state(&self) -> SoftState {
SoftState {
leader_id: self.leader_id,
raft_state: self.state,
}
}
/// Returns a value representing the hardstate at the time of calling.
pub fn hard_state(&self) -> HardState {
let mut hs = HardState::new();
hs.set_term(self.term);
hs.set_vote(self.vote);
hs.set_commit(self.raft_log.committed);
hs
}
/// Returns whether the current raft is in lease.
pub fn in_lease(&self) -> bool {
self.state == StateRole::Leader && self.check_quorum
}
fn quorum(&self) -> usize {
quorum(self.prs().voters().len())
}
/// For testing leader lease
pub fn set_randomized_election_timeout(&mut self, t: usize) {
assert!(self.min_election_timeout <= t && t < self.max_election_timeout);
self.randomized_election_timeout = t;
}
/// Fetch the length of the election timeout.
pub fn get_election_timeout(&self) -> usize {
self.election_timeout
}
/// Fetch the length of the heartbeat timeout
pub fn get_heartbeat_timeout(&self) -> usize {
self.heartbeat_timeout
}
/// Return the length of the current randomized election timeout.
pub fn get_randomized_election_timeout(&self) -> usize {
self.randomized_election_timeout
}
// send persists state to stable storage and then sends to its mailbox.
fn send(&mut self, mut m: Message) {
m.set_from(self.id);
if m.get_msg_type() == MessageType::MsgRequestVote
|| m.get_msg_type() == MessageType::MsgRequestPreVote
|| m.get_msg_type() == MessageType::MsgRequestVoteResponse
|| m.get_msg_type() == MessageType::MsgRequestPreVoteResponse
{
if m.get_term() == 0 {
// All {pre-,}campaign messages need to have the term set when
// sending.
// - MsgVote: m.Term is the term the node is campaigning for,
// non-zero as we increment the term when campaigning.
// - MsgVoteResp: m.Term is the new r.Term if the MsgVote was
// granted, non-zero for the same reason MsgVote is
// - MsgPreVote: m.Term is the term the node will campaign,
// non-zero as we use m.Term to indicate the next term we'll be
// campaigning for
// - MsgPreVoteResp: m.Term is the term received in the original
// MsgPreVote if the pre-vote was granted, non-zero for the
// same reasons MsgPreVote is
panic!(
"{} term should be set when sending {:?}",
self.tag,
m.get_msg_type()
);
}
} else {
if m.get_term() != 0 {
panic!(
"{} term should not be set when sending {:?} (was {})",
self.tag,
m.get_msg_type(),
m.get_term()
);
}
// do not attach term to MsgPropose, MsgReadIndex
// proposals are a way to forward to the leader and
// should be treated as local message.
// MsgReadIndex is also forwarded to leader.
if m.get_msg_type() != MessageType::MsgPropose
&& m.get_msg_type() != MessageType::MsgReadIndex
{
m.set_term(self.term);
}
}
self.msgs.push(m);
}
fn prepare_send_snapshot(&mut self, m: &mut Message, pr: &mut Progress, to: u64) -> bool {
if !pr.recent_active {
debug!(
"{} ignore sending snapshot to {} since it is not recently active",
self.tag, to
);
return false;
}
m.set_msg_type(MessageType::MsgSnapshot);
let snapshot_r = self.raft_log.snapshot();
if let Err(e) = snapshot_r {
if e == Error::Store(StorageError::SnapshotTemporarilyUnavailable) {
debug!(
"{} failed to send snapshot to {} because snapshot is temporarily \
unavailable",
self.tag, to
);
return false;
}
panic!("{} unexpected error: {:?}", self.tag, e);
}
let snapshot = snapshot_r.unwrap();
if snapshot.get_metadata().get_index() == 0 {
panic!("{} need non-empty snapshot", self.tag);
}
let (sindex, sterm) = (
snapshot.get_metadata().get_index(),
snapshot.get_metadata().get_term(),
);
m.set_snapshot(snapshot);
debug!(
"{} [firstindex: {}, commit: {}] sent snapshot[index: {}, term: {}] to {} \
[{:?}]",
self.tag,
self.raft_log.first_index(),
self.raft_log.committed,
sindex,
sterm,
to,
pr
);
pr.become_snapshot(sindex);
debug!(
"{} paused sending replication messages to {} [{:?}]",
self.tag, to, pr
);
true
}
fn prepare_send_entries(
&mut self,
m: &mut Message,
pr: &mut Progress,
term: u64,
ents: Vec<Entry>,
) {
m.set_msg_type(MessageType::MsgAppend);
m.set_index(pr.next_idx - 1);
m.set_log_term(term);
m.set_entries(RepeatedField::from_vec(ents));
m.set_commit(self.raft_log.committed);
if !m.get_entries().is_empty() {
match pr.state {
ProgressState::Replicate => {
let last = m.get_entries().last().unwrap().get_index();
pr.optimistic_update(last);
pr.ins.add(last);
}
ProgressState::Probe => pr.pause(),
_ => panic!(
"{} is sending append in unhandled state {:?}",
self.tag, pr.state
),
}
}
}
/// Sends RPC, with entries to the given peer.
pub fn send_append(&mut self, to: u64, pr: &mut Progress) {
if pr.is_paused() {
return;
}
let term = self.raft_log.term(pr.next_idx - 1);
let ents = self.raft_log.entries(pr.next_idx, self.max_msg_size);
let mut m = Message::new();
m.set_to(to);
if term.is_err() || ents.is_err() {
// send snapshot if we failed to get term or entries
if !self.prepare_send_snapshot(&mut m, pr, to) {
return;
}
} else {
self.prepare_send_entries(&mut m, pr, term.unwrap(), ents.unwrap());
}
self.send(m);
}
// send_heartbeat sends an empty MsgAppend
fn send_heartbeat(&mut self, to: u64, pr: &Progress, ctx: Option<Vec<u8>>) {
// Attach the commit as min(to.matched, self.raft_log.committed).
// When the leader sends out heartbeat message,
// the receiver(follower) might not be matched with the leader
// or it might not have all the committed entries.
// The leader MUST NOT forward the follower's commit to
// an unmatched index.
let mut m = Message::new();
m.set_to(to);
m.set_msg_type(MessageType::MsgHeartbeat);
let commit = cmp::min(pr.matched, self.raft_log.committed);
m.set_commit(commit);
if let Some(context) = ctx {
m.set_context(context);
}
self.send(m);
}
/// Sends RPC, with entries to all peers that are not up-to-date
/// according to the progress recorded in r.prs().
pub fn bcast_append(&mut self) {
let self_id = self.id;
let mut prs = self.take_prs();
prs.iter_mut()
.filter(|&(id, _)| *id != self_id)
.for_each(|(id, pr)| self.send_append(*id, pr));
self.set_prs(prs);
}
/// Sends RPC, without entries to all the peers.
pub fn bcast_heartbeat(&mut self) {
let ctx = self.read_only.last_pending_request_ctx();
self.bcast_heartbeat_with_ctx(ctx)
}
#[allow(needless_pass_by_value)]
fn bcast_heartbeat_with_ctx(&mut self, ctx: Option<Vec<u8>>) {
let self_id = self.id;
let mut prs = self.take_prs();
prs.iter_mut()
.filter(|&(id, _)| *id != self_id)
.for_each(|(id, pr)| self.send_heartbeat(*id, pr, ctx.clone()));
self.set_prs(prs);
}
/// Attempts to advance the commit index. Returns true if the commit index
/// changed (in which case the caller should call `r.bcast_append`).
pub fn maybe_commit(&mut self) -> bool {
let mut mis_arr = [0; 5];
let mut mis_vec;
let mis = if self.prs().voters().len() <= 5 {
&mut mis_arr[..self.prs().voters().len()]
} else {
mis_vec = vec![0; self.prs().voters().len()];
mis_vec.as_mut_slice()
};
for (i, pr) in self.prs().voters().values().enumerate() {
mis[i] = pr.matched;
}
// reverse sort
mis.sort_by(|a, b| b.cmp(a));
let mci = mis[self.quorum() - 1];
self.raft_log.maybe_commit(mci, self.term)
}
/// Resets the current node to a given term.
pub fn reset(&mut self, term: u64) {
if self.term != term {
self.term = term;
self.vote = INVALID_ID;
}
self.leader_id = INVALID_ID;
self.reset_randomized_election_timeout();
self.election_elapsed = 0;
self.heartbeat_elapsed = 0;
self.abort_leader_transfer();
self.votes = FxHashMap::default();
self.pending_conf_index = 0;
self.read_only = ReadOnly::new(self.read_only.option);
let (last_index, max_inflight) = (self.raft_log.last_index(), self.max_inflight);
let self_id = self.id;
for (&id, pr) in self.mut_prs().iter_mut() {
let is_learner = pr.is_learner;
*pr = new_progress(last_index + 1, max_inflight);
pr.is_learner = is_learner;
if id == self_id {
pr.matched = last_index;
}
}
}
/// Appends a slice of entries to the log. The entries are updated to match
/// the current index and term.
pub fn append_entry(&mut self, es: &mut [Entry]) {
let mut li = self.raft_log.last_index();
for (i, e) in es.iter_mut().enumerate() {
e.set_term(self.term);
e.set_index(li + 1 + i as u64);
}
// use latest "last" index after truncate/append
li = self.raft_log.append(es);
let self_id = self.id;
self.mut_prs().get_mut(self_id).unwrap().maybe_update(li);
// Regardless of maybe_commit's return, our caller will call bcastAppend.
self.maybe_commit();
}
/// Returns true to indicate that there will probably be some readiness need to be handled.
pub fn tick(&mut self) -> bool {
match self.state {
StateRole::Follower | StateRole::PreCandidate | StateRole::Candidate => {
self.tick_election()
}
StateRole::Leader => self.tick_heartbeat(),
}
}
// TODO: revoke pub when there is a better way to test.
/// Run by followers and candidates after self.election_timeout.
///
/// Returns true to indicate that there will probably be some readiness need to be handled.
pub fn tick_election(&mut self) -> bool {
self.election_elapsed += 1;
if !self.pass_election_timeout() || !self.promotable() {
return false;
}
self.election_elapsed = 0;
let m = new_message(INVALID_ID, MessageType::MsgHup, Some(self.id));
self.step(m).is_ok();
true
}
// tick_heartbeat is run by leaders to send a MsgBeat after self.heartbeat_timeout.
// Returns true to indicate that there will probably be some readiness need to be handled.
fn tick_heartbeat(&mut self) -> bool {
self.heartbeat_elapsed += 1;
self.election_elapsed += 1;
let mut has_ready = false;
if self.election_elapsed >= self.election_timeout {
self.election_elapsed = 0;
if self.check_quorum {
let m = new_message(INVALID_ID, MessageType::MsgCheckQuorum, Some(self.id));
has_ready = true;
self.step(m).is_ok();
}
if self.state == StateRole::Leader && self.lead_transferee.is_some() {
self.abort_leader_transfer()
}
}
if self.state != StateRole::Leader {
return has_ready;
}
if self.heartbeat_elapsed >= self.heartbeat_timeout {
self.heartbeat_elapsed = 0;
has_ready = true;
let m = new_message(INVALID_ID, MessageType::MsgBeat, Some(self.id));
self.step(m).is_ok();
}
has_ready
}
/// Converts this node to a follower.
pub fn become_follower(&mut self, term: u64, leader_id: u64) {
self.reset(term);
self.leader_id = leader_id;
self.state = StateRole::Follower;
info!("{} became follower at term {}", self.tag, self.term);
}
// TODO: revoke pub when there is a better way to test.
/// Converts this node to a candidate
///
/// # Panics
///
/// Panics if a leader already exists.
pub fn become_candidate(&mut self) {
assert_ne!(
self.state,
StateRole::Leader,
"invalid transition [leader -> candidate]"
);
let term = self.term + 1;
self.reset(term);
let id = self.id;
self.vote = id;
self.state = StateRole::Candidate;
info!("{} became candidate at term {}", self.tag, self.term);
}
/// Converts this node to a pre-candidate
///
/// # Panics
///
/// Panics if a leader already exists.
pub fn become_pre_candidate(&mut self) {
assert_ne!(
self.state,
StateRole::Leader,
"invalid transition [leader -> pre-candidate]"
);
// Becoming a pre-candidate changes our state.
// but doesn't change anything else. In particular it does not increase
// self.term or change self.vote.
self.state = StateRole::PreCandidate;
self.votes = FxHashMap::default();
// If a network partition happens, and leader is in minority partition,
// it will step down, and become follower without notifying others.
self.leader_id = INVALID_ID;
info!("{} became pre-candidate at term {}", self.tag, self.term);
}
// TODO: revoke pub when there is a better way to test.
/// Makes this raft the leader.
///
/// # Panics
///
/// Panics if this is a follower node.
pub fn become_leader(&mut self) {
assert_ne!(
self.state,
StateRole::Follower,
"invalid transition [follower -> leader]"
);
let term = self.term;
self.reset(term);
self.leader_id = self.id;
self.state = StateRole::Leader;
let begin = self.raft_log.committed + 1;
let ents = self.raft_log
.entries(begin, raft_log::NO_LIMIT)
.expect("unexpected error getting uncommitted entries");
// Conservatively set the pending_conf_index to the last index in the
// log. There may or may not be a pending config change, but it's
// safe to delay any future proposals until we commit all our
// pending log entries, and scanning the entire tail of the log
// could be expensive.
self.pending_conf_index = ents.last().map_or(0, |e| e.get_index());
self.append_entry(&mut [Entry::new()]);
info!("{} became leader at term {}", self.tag, self.term);
}
fn num_pending_conf(&self, ents: &[Entry]) -> usize {
ents.into_iter()
.filter(|e| e.get_entry_type() == EntryType::EntryConfChange)
.count()
}
fn campaign(&mut self, campaign_type: &[u8]) {
let (vote_msg, term) = if campaign_type == CAMPAIGN_PRE_ELECTION {
self.become_pre_candidate();
// Pre-vote RPCs are sent for next term before we've incremented self.term.
(MessageType::MsgRequestPreVote, self.term + 1)
} else {
self.become_candidate();
(MessageType::MsgRequestVote, self.term)
};
let self_id = self.id;
if self.quorum() == self.poll(self_id, vote_resp_msg_type(vote_msg), true) {
// We won the election after voting for ourselves (which must mean that
// this is a single-node cluster). Advance to the next state.
if campaign_type == CAMPAIGN_PRE_ELECTION {
self.campaign(CAMPAIGN_ELECTION);
} else {
self.become_leader();
}
return;
}
// Only send vote request to voters.
let prs = self.take_prs();
prs.voters()
.keys()
.filter(|&id| *id != self_id)
.for_each(|&id| {
info!(
"{} [logterm: {}, index: {}] sent {:?} request to {} at term {}",
self.tag,
self.raft_log.last_term(),
self.raft_log.last_index(),
vote_msg,
id,
self.term
);
let mut m = new_message(id, vote_msg, None);
m.set_term(term);
m.set_index(self.raft_log.last_index());
m.set_log_term(self.raft_log.last_term());
if campaign_type == CAMPAIGN_TRANSFER {
m.set_context(campaign_type.to_vec());
}