-
Notifications
You must be signed in to change notification settings - Fork 399
/
raft.rs
2019 lines (1861 loc) · 74.4 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::{Progress, ProgressSet, ProgressState};
use super::raft_log::{self, RaftLog};
use super::read_only::{ReadOnly, ReadOnlyOption, ReadState};
use super::storage::Storage;
use super::Config;
// 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;
/// 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 persistent 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.
///
/// Learners are not permitted to vote in elections, and are not counted for commit quorums.
/// They do replicate data from the leader.
pub is_learner: bool,
/// The current votes for this node in an election.
///
/// Reset when changing role.
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.
///
/// If this is Some(id), we 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,
/// Enable the prevote algorithm.
///
/// This enables a pre-election vote round on Candidates prior to disrupting the cluster.
///
/// Enable this if greater cluster stability is preferred over faster elections.
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,
/// Tag is only used for logging
tag: String,
}
trait AssertSend: Send {}
impl<T: Storage + Send> AssertSend for Raft<T> {}
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) -> Result<Raft<T>> {
c.validate()?;
let rs = store.initial_state()?;
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::with_capacity(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(),
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 = Progress::new(1, r.max_inflight);
if let Err(e) = r.mut_prs().insert_voter(*p, pr) {
panic!("{}", e);
}
}
for p in learners {
let pr = Progress::new(1, r.max_inflight);
if let Err(e) = r.mut_prs().insert_learner(*p, pr) {
panic!("{}", e);
};
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().voters().collect::<Vec<_>>(),
r.term,
r.raft_log.committed,
r.raft_log.get_applied(),
r.raft_log.last_index(),
r.raft_log.last_term()
);
Ok(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().voter_ids().len())
}
/// For testing leader lease
#[doc(hidden)]
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
}
/// Set whether skip broadcast empty commit messages at runtime.
#[inline]
pub fn skip_bcast_commit(&mut self, skip: bool) {
self.skip_bcast_commit = skip;
}
// 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)
}
#[cfg_attr(feature = "cargo-clippy", 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 voter_count = self.prs().voter_ids().len();
let mis = if voter_count <= 5 {
&mut mis_arr[..voter_count]
} else {
mis_vec = vec![0; voter_count];
mis_vec.as_mut_slice()
};
for (i, pr) in self.prs().voters().map(|(_, v)| v).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.clear();
self.pending_conf_index = 0;
self.read_only = ReadOnly::new(self.read_only.option);
let last_index = self.raft_log.last_index();
let self_id = self.id;
for (&id, pr) in self.mut_prs().iter_mut() {
pr.reset(last_index + 1);
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;
// 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 = self.raft_log.last_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()
}
/// Campaign to attempt to become a leader.
///
/// If prevote is enabled, this is handled as well.
pub 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.voter_ids()
.iter()
.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());
}
self.send(m);
});
self.set_prs(prs);
}
/// Sets the vote of `id` to `vote`.
///
/// Returns the number of votes for the `id` currently.
fn poll(&mut self, id: u64, msg_type: MessageType, vote: bool) -> usize {
if vote {
info!(
"{} received {:?} from {} at term {}",
self.tag, msg_type, id, self.term
)
} else {
info!(
"{} received {:?} rejection from {} at term {}",
self.tag, msg_type, id, self.term
)
}
self.votes.entry(id).or_insert(vote);
self.votes.values().filter(|x| **x).count()
}
/// Steps the raft along via a message. This should be called everytime your raft receives a
/// message from a peer.
pub fn step(&mut self, m: Message) -> Result<()> {
// Handle the message term, which may result in our stepping down to a follower.
if m.get_term() == 0 {
// local message
} else if m.get_term() > self.term {
if m.get_msg_type() == MessageType::MsgRequestVote
|| m.get_msg_type() == MessageType::MsgRequestPreVote
{
let force = m.get_context() == CAMPAIGN_TRANSFER;
let in_lease = self.check_quorum
&& self.leader_id != INVALID_ID
&& self.election_elapsed < self.election_timeout;
if !force && in_lease {
// if a server receives RequestVote request within the minimum election
// timeout of hearing from a current leader, it does not update its term
// or grant its vote
info!(
"{} [logterm: {}, index: {}, vote: {}] ignored {:?} vote from \
{} [logterm: {}, index: {}] at term {}: lease is not expired \
(remaining ticks: {})",
self.tag,
self.raft_log.last_term(),
self.raft_log.last_index(),
self.vote,
m.get_msg_type(),
m.get_from(),
m.get_log_term(),
m.get_index(),
self.term,
self.election_timeout - self.election_elapsed
);
return Ok(());
}
}
if m.get_msg_type() == MessageType::MsgRequestPreVote
|| (m.get_msg_type() == MessageType::MsgRequestPreVoteResponse && !m.get_reject())
{
// For a pre-vote request:
// Never change our term in response to a pre-vote request.
//
// For a pre-vote response with pre-vote granted:
// We send pre-vote requests with a term in our future. If the
// pre-vote is granted, we will increment our term when we get a
// quorum. If it is not, the term comes from the node that
// rejected our vote so we should become a follower at the new
// term.
} else {
info!(
"{} [term: {}] received a {:?} message with higher term from {} [term: {}]",
self.tag,
self.term,
m.get_msg_type(),
m.get_from(),
m.get_term()
);
if m.get_msg_type() == MessageType::MsgAppend
|| m.get_msg_type() == MessageType::MsgHeartbeat
|| m.get_msg_type() == MessageType::MsgSnapshot
{
self.become_follower(m.get_term(), m.get_from());
} else {
self.become_follower(m.get_term(), INVALID_ID);
}
}
} else if m.get_term() < self.term {
if (self.check_quorum || self.pre_vote)
&& (m.get_msg_type() == MessageType::MsgHeartbeat
|| m.get_msg_type() == MessageType::MsgAppend)
{
// We have received messages from a leader at a lower term. It is possible
// that these messages were simply delayed in the network, but this could
// also mean that this node has advanced its term number during a network
// partition, and it is now unable to either win an election or to rejoin
// the majority on the old term. If checkQuorum is false, this will be
// handled by incrementing term numbers in response to MsgVote with a higher
// term, but if checkQuorum is true we may not advance the term on MsgVote and
// must generate other messages to advance the term. The net result of these
// two features is to minimize the disruption caused by nodes that have been
// removed from the cluster's configuration: a removed node will send MsgVotes
// which will be ignored, but it will not receive MsgApp or MsgHeartbeat, so it
// will not create disruptive term increases, by notifying leader of this node's
// activeness.
// The above comments also true for Pre-Vote
//
// When follower gets isolated, it soon starts an election ending
// up with a higher term than leader, although it won't receive enough
// votes to win the election. When it regains connectivity, this response
// with "pb.MsgAppResp" of higher term would force leader to step down.
// However, this disruption is inevitable to free this stuck node with
// fresh election. This can be prevented with Pre-Vote phase.
let to_send = new_message(m.get_from(), MessageType::MsgAppendResponse, None);
self.send(to_send);
} else if m.get_msg_type() == MessageType::MsgRequestPreVote {
// Before pre_vote enable, there may be a recieving candidate with higher term,
// but less log. After update to pre_vote, the cluster may deadlock if
// we drop messages with a lower term.
info!(
"{} [log_term: {}, index: {}, vote: {}] rejected {:?} from {} [log_term: {}, index: {}] at term {}",
self.id,
self.raft_log.last_term(),
self.raft_log.last_index(),
self.vote,
m.get_msg_type(),
m.get_from(),
m.get_log_term(),
m.get_index(),
self.term,
);
let mut to_send =
new_message(m.get_from(), MessageType::MsgRequestPreVoteResponse, None);
to_send.set_term(self.term);
to_send.set_reject(true);
self.send(to_send);
} else {
// ignore other cases
info!(
"{} [term: {}] ignored a {:?} message with lower term from {} [term: {}]",
self.tag,
self.term,
m.get_msg_type(),
m.get_from(),
m.get_term()
);
}
return Ok(());
}
#[cfg(feature = "failpoint")]
fail_point!("before_step");
match m.get_msg_type() {
MessageType::MsgHup => if self.state != StateRole::Leader {
let ents = self
.raft_log
.slice(
self.raft_log.applied + 1,
self.raft_log.committed + 1,
raft_log::NO_LIMIT,
).expect("unexpected error getting unapplied entries");