-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathraft.h
2448 lines (2230 loc) · 104 KB
/
raft.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2025 AntGroup CO., Ltd.
* Copyright 2015 The etcd Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// written by botu.wzy, inspired by etcd raft
#pragma once
#include "util.h"
#include "read_only.h"
#include "tracker/tracker.h"
#include "quorum/quorum.h"
#include "log.h"
#include "confchange/restore.h"
#include "raftpb/confstate.h"
#include "raftpb/confchange.h"
namespace eraft {
// Possible values for StateType.
enum StateType {
StateFollower = 0,
StateCandidate,
StateLeader,
StatePreCandidate,
numStates
};
inline std::string ToString(StateType st) {
switch (st) {
case StateType::StateFollower:
return "StateFollower";
case StateType::StateCandidate:
return "StateCandidate";
case StateType::StateLeader:
return "StateLeader";
case StateType::StatePreCandidate:
return "StatePreCandidate";
default:
ERAFT_FATAL("unknown state type");
return "UnknownStateType";
};
}
// CampaignType represents the type of campaigning
// the reason we use the type of string instead of uint64
// is because it's simpler to compare and fill in raft entries
typedef std::string CampaignType;
// Possible values for CampaignType
// campaignPreElection represents the first phase of a normal election when
// Config.PreVote is true.
const CampaignType campaignPreElection = "CampaignPreElection";
// campaignElection represents a normal (time-based) election (the second phase
// of the election when Config.PreVote is true).
const CampaignType campaignElection = "CampaignElection";
// campaignTransfer represents the type of leader transfer
const CampaignType campaignTransfer = "CampaignTransfer";
// ErrProposalDropped is returned when the proposal is ignored by some cases,
// so that the proposer can be notified and fail fast.
const Error ErrProposalDropped("raft proposal dropped");
// SoftState provides state that is useful for logging and debugging.
// The state is volatile and does not need to be persisted to the WAL.
struct SoftState {
uint64_t lead_ = 0; // must use atomic operations to access; keep 64-bit aligned.
StateType raftState_ = StateFollower;
SoftState() = default;
SoftState(uint64_t lead, StateType raftState) : lead_(lead), raftState_(raftState) {}
bool operator==(const SoftState& state) const {
return lead_ == state.lead_ && raftState_ == state.raftState_;
}
bool operator!=(const SoftState& state) const {
return lead_ != state.lead_ || raftState_ != state.raftState_;
}
};
// Ready encapsulates the entries and messages that are ready to read,
// be saved to stable storage, committed or sent to other peers.
// All fields in Ready are read-only.
struct Ready {
// The current volatile state of a Node.
// SoftState will be nil if there is no update.
// It is not required to consume or store SoftState.
std::shared_ptr<SoftState> softState_;
// The current state of a Node to be saved to stable storage BEFORE
// Messages are sent.
// HardState will be equal to empty state if there is no update.
raftpb::HardState hardState_;
// ReadStates can be used for node to serve linearizable read requests locally
// when its applied index is greater than the index in ReadState.
// Note that the readState will be returned when raft receives msgReadIndex.
// The returned is only valid for the request that requested to read.
std::vector<ReadState> readStates_;
// Entries specifies entries to be saved to stable storage BEFORE
// Messages are sent.
std::vector<raftpb::Entry> entries_;
// Snapshot specifies the snapshot to be saved to stable storage.
raftpb::Snapshot snapshot_;
// CommittedEntries specifies entries to be committed to a
// store/state-machine. These have previously been committed to stable
// store.
std::vector<raftpb::Entry> committedEntries_;
// Messages specifies outbound messages to be sent AFTER Entries are
// committed to stable storage.
// If it contains a MsgSnap message, the application MUST report back to raft
// when the snapshot has been received or has failed by calling ReportSnapshot.
std::vector<raftpb::Message> messages_;
// MustSync indicates whether the HardState and Entries must be synchronously
// written to disk or if an asynchronous write is permissible.
bool mustSync_ = false;
bool operator==(const Ready& r) const {
if ((!softState_ && r.softState_) || (softState_ && !r.softState_)) {
return false;
}
if (softState_ && r.softState_ && *softState_ != *r.softState_) {
return false;
}
if (!google::protobuf::util::MessageDifferencer::Equals(hardState_, r.hardState_)) {
return false;
}
if (readStates_.size() != r.readStates_.size()) {
return false;
}
for (size_t i = 0; i < readStates_.size(); i++) {
if (readStates_.at(i) != r.readStates_.at(i)) {
return false;
}
}
if (!VectorEquals(entries_, r.entries_)) {
return false;
}
if (!google::protobuf::util::MessageDifferencer::Equals(snapshot_, r.snapshot_)) {
return false;
}
if (!VectorEquals(committedEntries_, r.committedEntries_)) {
return false;
}
if (!VectorEquals(messages_, r.messages_)) {
return false;
}
if (mustSync_ != r.mustSync_) {
return false;
}
return true;
}
bool containsUpdates() const {
return softState_ != nullptr || !IsEmptyHardState(hardState_) ||
!IsEmptySnap(snapshot_) || !entries_.empty() ||
!committedEntries_.empty() || !messages_.empty() || !readStates_.empty();
}
// appliedCursor extracts from the Ready the highest index the client has
// applied (once the Ready is confirmed via Advance). If no information is
// contained in the Ready, returns zero.
uint64_t appliedCursor() const {
auto n = committedEntries_.size();
if (n > 0) {
return committedEntries_[n-1].index();
}
auto index = snapshot_.metadata().index();
if (index > 0) {
return index;
}
return 0;
}
};
// Config contains the parameters to start a raft.
struct Config {
// ID is the identity of the local raft. ID cannot be 0.
uint64_t id_ = 0;
// ElectionTick is 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. ElectionTick must be greater than
// HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
// unnecessary leader switching.
int64_t electionTick_ = 0;
// 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 HeartbeatTick ticks.
int64_t heartbeatTick_ = 0;
// Storage is the storage for raft. raft generates entries and states to be
// stored in storage. raft reads the persisted entries and states out of
// Storage when it needs. raft reads out the previous state and configuration
// out of storage when restarting.
std::shared_ptr<Storage> storage_;
// 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.
uint64_t applied_ = 0;
// AsyncStorageWrites configures the raft node to write to its local storage
// (raft log and state machine) using a request/response message passing
// interface instead of the default Ready/Advance function call interface.
// Local storage messages can be pipelined and processed asynchronously
// (with respect to Ready iteration), facilitating reduced interference
// between Raft proposals and increased batching of log appends and state
// machine application. As a result, use of asynchronous storage writes can
// reduce end-to-end commit latency and increase maximum throughput.
//
// When true, the Ready.Message slice will include MsgStorageAppend and
// MsgStorageApply messages. The messages will target a LocalAppendThread
// and a LocalApplyThread, respectively. Messages to the same target must be
// reliably processed in order. In other words, they can't be dropped (like
// messages over the network) and those targeted at the same thread can't be
// reordered. Messages to different targets can be processed in any order.
//
// MsgStorageAppend carries Raft log entries to append, election votes /
// term changes / updated commit indexes to persist, and snapshots to apply.
// All writes performed in service of a MsgStorageAppend must be durable
// before response messages are delivered. However, if the MsgStorageAppend
// carries no response messages, durability is not required. The message
// assumes the role of the Entries, HardState, and Snapshot fields in Ready.
//
// MsgStorageApply carries committed entries to apply. Writes performed in
// service of a MsgStorageApply need not be durable before response messages
// are delivered. The message assumes the role of the CommittedEntries field
// in Ready.
//
// Local messages each carry one or more response messages which should be
// delivered after the corresponding storage write has been completed. These
// responses may target the same node or may target other nodes. The storage
// threads are not responsible for understanding the response messages, only
// for delivering them to the correct target after performing the storage
// write.
bool AsyncStorageWrites_ = false;
// MaxSizePerMsg limits the max byte 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.MaxUint64 for unlimited,
// 0 for at most one entry per message.
uint64_t maxSizePerMsg_ = 0;
// MaxCommittedSizePerReady limits the size of the committed entries which
// can be applying at the same time.
//
// Despite its name (preserved for compatibility), this quota applies across
// Ready structs to encompass all outstanding entries in unacknowledged
// MsgStorageApply messages when AsyncStorageWrites is enabled.
uint64_t maxCommittedSizePerReady_ = 0;
// MaxUncommittedEntriesSize limits the aggregate byte size of the
// uncommitted entries that may be appended to a leader's log. Once this
// limit is exceeded, proposals will begin to return ErrProposalDropped
// errors. Note: 0 for no limit.
uint64_t maxUncommittedEntriesSize_ = 0;
// MaxInflightMsgs limits 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. Setting MaxInflightMsgs to avoid
// overflowing that sending buffer. TODO (xiangli): feedback to application to
// limit the proposal rate?
int64_t maxInflightMsgs_ = 0;
// MaxInflightBytes limits the number of in-flight bytes in append messages.
// Complements MaxInflightMsgs. Ignored if zero.
//
// This effectively bounds the bandwidth-delay product. Note that especially
// in high-latency deployments setting this too low can lead to a dramatic
// reduction in throughput. For example, with a peer that has a round-trip
// latency of 100ms to the leader and this setting is set to 1 MB, there is a
// throughput limit of 10 MB/s for this group. With RTT of 400ms, this drops
// to 2.5 MB/s. See Little's law to understand the maths behind.
uint64_t maxInflightBytes_ = 0;
// CheckQuorum specifies if the leader should check quorum activity. Leader
// steps down when quorum is not active for an electionTimeout.
bool checkQuorum_ = false;
// PreVote 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.
bool preVote_ = false;
// ReadOnlyOption specifies how the read only request is processed.
//
// ReadOnlySafe guarantees the linearizability of the read only request by
// communicating with the quorum. It is the default and suggested option.
//
// ReadOnlyLeaseBased ensures linearizability of the read only request by
// relying on the leader lease. It can be affected by clock drift.
// If the clock drift is unbounded, leader might keep the lease longer than it
// should (clock can move backward/pause without any bound). ReadIndex is not safe
// in that case.
// CheckQuorum MUST be enabled if ReadOnlyOption is ReadOnlyLeaseBased.
ReadOnlyOption readOnlyOption_ = ReadOnlySafe;
// DisableProposalForwarding set to true means that followers will drop
// proposals, rather than forwarding them to the leader. One use case for
// this feature would be in a situation where the Raft leader is used to
// compute the data of a proposal, for example, adding a timestamp from a
// hybrid logical clock to data in a monotonically increasing way. Forwarding
// should be disabled to prevent a follower with an inaccurate hybrid
// logical clock from assigning the timestamp and then forwarding the data
// to the leader.
bool disableProposalForwarding_ = false;
// DisableConfChangeValidation turns off propose-time verification of
// configuration changes against the currently active configuration of the
// raft instance. These checks are generally sensible (cannot leave a joint
// config unless in a joint config, et cetera) but they have false positives
// because the active configuration may not be the most recent
// configuration. This is because configurations are activated during log
// application, and even the leader can trail log application by an
// unbounded number of entries.
// Symmetrically, the mechanism has false negatives - because the check may
// not run against the "actual" config that will be the predecessor of the
// newly proposed one, the check may pass but the new config may be invalid
// when it is being applied. In other words, the checks are best-effort.
//
// Users should *not* use this option unless they have a reliable mechanism
// (above raft) that serializes and verifies configuration changes. If an
// invalid configuration change enters the log and gets applied, a panic
// will result.
//
// This option may be removed once false positives are no longer possible.
// See: https://github.com/etcd-io/raft/issues/80
bool disableConfChangeValidation_ = false;
// StepDownOnRemoval makes the leader step down when it is removed from the
// group or demoted to a learner.
//
// This behavior will become unconditional in the future. See:
// https://github.com/etcd-io/raft/issues/83
bool stepDownOnRemoval_ = false;
Error validate() {
if (id_ == None) {
return Error("cannot use none as id");
}
if (IsLocalMsgTarget(id_)) {
return Error("cannot use local target as id");
}
if (heartbeatTick_ <= 0) {
return Error("heartbeat tick must be greater than 0");
}
if (electionTick_ <= heartbeatTick_) {
return Error("election tick must be greater than heartbeat tick");
}
if (storage_ == nullptr) {
return Error("storage cannot be nil");
}
if (maxUncommittedEntriesSize_ == 0) {
maxUncommittedEntriesSize_ = noLimit;
}
// default MaxCommittedSizePerReady to MaxSizePerMsg because they were
// previously the same parameter.
if (maxCommittedSizePerReady_ == 0) {
maxCommittedSizePerReady_ = maxSizePerMsg_;
}
if (maxInflightMsgs_ <= 0) {
return Error("max inflight messages must be greater than 0");
}
if (maxInflightBytes_ == 0) {
maxInflightBytes_ = noLimit;
} else if (maxInflightBytes_ < maxSizePerMsg_) {
return Error("max inflight bytes must be >= max message size");
}
if (readOnlyOption_ == ReadOnlyLeaseBased && !checkQuorum_) {
return Error("CheckQuorum must be enabled when ReadOnlyOption is ReadOnlyLeaseBased");
}
return {};
};
};
namespace detail {
struct raft {
uint64_t id_ = 0;
uint64_t term_ = 0;
uint64_t vote_ = 0;
std::vector<ReadState> readStates_;
// the log
std::shared_ptr<RaftLog> raftLog_;
uint64_t maxMsgSize_ = 0;
uint64_t maxUncommittedSize_ = 0;
// TODO(tbg): rename to trk.
tracker::ProgressTracker trk_;
StateType state_ = StateFollower;
// isLearner is true if the local raft node is a learner.
bool isLearner_ = false;
// msgs contains the list of messages that should be sent out immediately to
// other nodes.
//
// Messages in this list must target other nodes.
std::vector<raftpb::Message> msgs_;
// msgsAfterAppend contains the list of messages that should be sent after
// the accumulated unstable state (e.g. term, vote, []entry, and snapshot)
// has been persisted to durable storage. This includes waiting for any
// unstable state that is already in the process of being persisted (i.e.
// has already been handed out in a prior Ready struct) to complete.
//
// Messages in this list may target other nodes or may target this node.
//
// Messages in this list have the type MsgAppResp, MsgVoteResp, or
// MsgPreVoteResp. See the comment in raft.send for details.
std::vector<raftpb::Message> msgsAfterAppend_;
// the leader id
uint64_t lead_ = 0;
// leadTransferee is id of the leader transfer target when its value is not zero.
// Follow the procedure defined in raft thesis 3.10.
uint64_t leadTransferee_ = 0;
// Only one conf change may be pending (in the log, but not yet
// applied) at a time. This is enforced via pendingConfIndex, 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.
uint64_t pendingConfIndex_ = 0;
// disableConfChangeValidation is Config.DisableConfChangeValidation,
// see there for details.
bool disableConfChangeValidation_ = false;
// an estimate of the size of the uncommitted tail of the Raft log. Used to
// prevent unbounded log growth. Only maintained by the leader. Reset on
// term changes.
uint64_t uncommittedSize_ = 0;
std::shared_ptr<ReadOnly> readOnly_;
// number of 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.
int64_t electionElapsed_ = 0;
// number of ticks since it reached last heartbeatTimeout.
// only leader keeps heartbeatElapsed.
int64_t heartbeatElapsed_ = 0;
bool checkQuorum_ = false;
bool preVote_ = false;
int64_t heartbeatTimeout_ = 0;
int64_t electionTimeout_ = 0;
// randomizedElectionTimeout is a random number between
// [electiontimeout, 2 * electiontimeout - 1]. It gets reset
// when raft changes its state to follower or candidate.
int64_t randomizedElectionTimeout_ = 0;
bool disableProposalForwarding_ = false;
bool stepDownOnRemoval_ = false;
std::function<void()> tick_;
std::function<Error(raft & , raftpb::Message)> step_;
// pendingReadIndexMessages is used to store messages of type MsgReadIndex
// that can't be answered as new leader didn't committed any log in
// current term. Those will be handled as fast as first log is committed in
// current term.
std::vector<raftpb::Message> pendingReadIndexMessages_;
bool hasLeader();
SoftState softState();
raftpb::HardState hardState();
void send(raftpb::Message m);
void sendAppend(uint64_t to);
bool maybeSendAppend(uint64_t to, bool sendIfEmpty);
void sendHeartbeat(uint64_t to, std::string ctx);
void bcastAppend();
void bcastHeartbeat();
void bcastHeartbeatWithCtx(const std::string& ctx);
void appliedTo(uint64_t index, uint64_t size);
void appliedSnap(const raftpb::Snapshot& snap);
bool maybeCommit();
void reset(uint64_t term);
bool appendEntry(std::vector<raftpb::Entry> es);
void tickElection();
void tickHeartbeat();
void becomeFollower(uint64_t term, uint64_t lead);
void becomeCandidate();
void becomePreCandidate();
void becomeLeader();
bool hasUnappliedConfChanges();
void hup(const CampaignType& t);
void campaign(const CampaignType& t);
std::tuple<size_t, size_t, quorum::VoteResult> poll(uint64_t id, raftpb::MessageType t, bool v);
Error Step(raftpb::Message m);
void handleAppendEntries(raftpb::Message m);
void handleHeartbeat(raftpb::Message m);
void handleSnapshot(raftpb::Message m);
bool restore(raftpb::Snapshot s);
bool promotable();
raftpb::ConfState applyConfChange(raftpb::ConfChangeV2 cc);
raftpb::ConfState switchToConfig(tracker::Config cfg, tracker::ProgressMap prs);
void loadState(const raftpb::HardState& state);
bool pastElectionTimeout() const;
void resetRandomizedElectionTimeout();
void sendTimeoutNow(uint64_t to);
void abortLeaderTransfer();
bool committedEntryInCurrentTerm();
raftpb::Message responseToReadIndexReq(raftpb::Message req, uint64_t readIndex);
bool increaseUncommittedSize(const std::vector<raftpb::Entry>& ents);
void reduceUncommittedSize(uint64_t s);
};
std::shared_ptr<raft> newRaft(Config& c);
Error stepLeader(raft& r, raftpb::Message m);
Error stepCandidate(raft& r, raftpb::Message m);
Error stepFollower(raft& r, raftpb::Message m);
void releasePendingReadIndexMessages(raft& r);
void sendMsgReadIndexResponse(raft& r, raftpb::Message m);
inline std::shared_ptr<raft> newRaft(Config& c) {
auto err = c.validate();
if (err != nullptr) {
ERAFT_FATAL(err.String().c_str());
}
auto raftlog = detail::newLogWithSize(c.storage_, c.maxCommittedSizePerReady_);
raftpb::HardState hs;
raftpb::ConfState cs;
std::tie(hs, cs, err) = c.storage_->InitialState();
if (err != nullptr) {
ERAFT_FATAL(err.String().c_str()); // TODO(bdarnell)
}
std::shared_ptr<raft> r(new raft());
r->id_ = c.id_;
r->lead_ = None;
r->isLearner_ = false;
r->raftLog_ = raftlog;
r->maxMsgSize_ = c.maxSizePerMsg_;
r->maxUncommittedSize_ = c.maxUncommittedEntriesSize_;
r->trk_ = tracker::MakeProgressTracker(c.maxInflightMsgs_, c.maxInflightBytes_);
r->electionTimeout_ = c.electionTick_;
r->heartbeatTimeout_ = c.heartbeatTick_;
r->checkQuorum_ = c.checkQuorum_;
r->preVote_ = c.preVote_;
r->readOnly_ = detail::newReadOnly(c.readOnlyOption_);
r->disableProposalForwarding_ = c.disableProposalForwarding_;
r->disableConfChangeValidation_ = c.disableConfChangeValidation_;
r->stepDownOnRemoval_ = c.stepDownOnRemoval_;
tracker::Config cfg;
tracker::ProgressMap prs;
std::tie(cfg, prs, err) = confchange::Restore({r->trk_, raftlog->lastIndex()}, cs);
if (err != nullptr) {
ERAFT_FATAL(err.String().c_str());
}
err = raftpb::Equivalent(cs, r->switchToConfig(cfg, prs));
if (err != nullptr) {
ERAFT_FATAL(err.String().c_str());
}
if (!IsEmptyHardState(hs)) {
r->loadState(hs);
}
if (c.applied_ > 0) {
raftlog->appliedTo(c.applied_, 0);
}
r->becomeFollower(r->term_, None);
std::vector<std::string> nodesStrs;
for (auto n: r->trk_.VoterNodes()) {
nodesStrs.push_back(format("%x", n));
}
ERAFT_INFO("newRaft %x [peers: [%s], term: %llu, commit: %llu, applied: %llu, lastindex: %llu, lastterm: %llu]",
r->id_, Join(nodesStrs, ",").c_str(), r->term_,
r->raftLog_->committed_, r->raftLog_->applied_, r->raftLog_->lastIndex(),
r->raftLog_->lastTerm());
return r;
}
inline bool raft::hasLeader() { return lead_ != None; }
inline SoftState raft::softState() {
return {lead_, state_};
}
inline raftpb::HardState raft::hardState() {
raftpb::HardState hs;
hs.set_term(term_);
hs.set_vote(vote_);
hs.set_commit(raftLog_->committed_);
return hs;
}
// send schedules persisting state to a stable storage and AFTER that
// sending the message (as part of next Ready message processing).
inline void raft::send(raftpb::Message m) {
if (m.from() == None) {
m.set_from(id_);
}
if (m.type() == raftpb::MsgVote || m.type() == raftpb::MsgVoteResp || m.type() == raftpb::MsgPreVote ||
m.type() == raftpb::MsgPreVoteResp) {
if (m.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
ERAFT_FATAL("term should be set when sending %s", raftpb::MessageType_Name(m.type()).c_str());
}
} else {
if (m.term() != 0) {
ERAFT_FATAL("term should not be set when sending %s (was %d)", raftpb::MessageType_Name(m.type()).c_str(),
m.term());
}
// do not attach term to MsgProp, 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.type() != raftpb::MsgProp && m.type() != raftpb::MsgReadIndex) {
m.set_term(term_);
}
}
if (m.type() == raftpb::MsgAppResp || m.type() == raftpb::MsgVoteResp || m.type() == raftpb::MsgPreVoteResp) {
// If async storage writes are enabled, messages added to the msgs slice
// are allowed to be sent out before unstable state (e.g. log entry
// writes and election votes) have been durably synced to the local
// disk.
//
// For most message types, this is not an issue. However, response
// messages that relate to "voting" on either leader election or log
// appends require durability before they can be sent. It would be
// incorrect to publish a vote in an election before that vote has been
// synced to stable storage locally. Similarly, it would be incorrect to
// acknowledge a log append to the leader before that entry has been
// synced to stable storage locally.
//
// Per the Raft thesis, section 3.8 Persisted state and server restarts:
//
// > Raft servers must persist enough information to stable storage to
// > survive server restarts safely. In particular, each server persists
// > its current term and vote; this is necessary to prevent the server
// > from voting twice in the same term or replacing log entries from a
// > newer leader with those from a deposed leader. Each server also
// > persists new log entries before they are counted towards the entries’
// > commitment; this prevents committed entries from being lost or
// > “uncommitted” when servers restart
//
// To enforce this durability requirement, these response messages are
// queued to be sent out as soon as the current collection of unstable
// state (the state that the response message was predicated upon) has
// been durably persisted. This unstable state may have already been
// passed to a Ready struct whose persistence is in progress or may be
// waiting for the next Ready struct to begin being written to Storage.
// These messages must wait for all of this state to be durable before
// being published.
//
// Rejected responses (m.Reject == true) present an interesting case
// where the durability requirement is less unambiguous. A rejection may
// be predicated upon unstable state. For instance, a node may reject a
// vote for one peer because it has already begun syncing its vote for
// another peer. Or it may reject a vote from one peer because it has
// unstable log entries that indicate that the peer is behind on its
// log. In these cases, it is likely safe to send out the rejection
// response immediately without compromising safety in the presence of a
// server restart. However, because these rejections are rare and
// because the safety of such behavior has not been formally verified,
// we err on the side of safety and omit a `&& !m.Reject` condition
// above.
msgsAfterAppend_.push_back(std::move(m));
} else {
if (m.to() == id_) {
ERAFT_FATAL("message should not be self-addressed when sending %s",
raftpb::MessageType_Name(m.type()).c_str());
}
msgs_.push_back(std::move(m));
}
}
// sendAppend sends an append RPC with new entries (if any) and the
// current commit index to the given peer.
inline void raft::sendAppend(uint64_t to) {
maybeSendAppend(to, true);
}
// maybeSendAppend sends an append RPC with new entries to the given peer,
// if necessary. Returns true if a message was sent. The sendIfEmpty
// argument controls whether messages with no entries will be sent
// ("empty" messages are useful to convey updated Commit indexes, but
// are undesirable when we're sending multiple messages in a batch).
inline bool raft::maybeSendAppend(uint64_t to, bool sendIfEmpty) {
auto& pr = trk_.progress_[to];
if (pr->IsPaused()) {
return false;
}
auto lastIndex = pr->next_-1;
auto nextIndex = pr->next_;
uint64_t lastTerm = 0;
Error err, errt, erre;
std::tie(lastTerm, errt) = raftLog_->term(lastIndex);
std::vector<raftpb::Entry> ents;
// In a throttled StateReplicate only send empty MsgApp, to ensure progress.
// Otherwise, if we had a full Inflights and all inflight messages were in
// fact dropped, replication to that follower would stall. Instead, an empty
// MsgApp will eventually reach the follower (heartbeats responses prompt the
// leader to send an append), allowing it to be acked or rejected, both of
// which will clear out Inflights.
if (pr->state_ != tracker::StateType::StateReplicate || !pr->inflights_->Full()) {
std::tie(ents, erre) = raftLog_->entries(nextIndex, maxMsgSize_);
}
if (ents.empty() && !sendIfEmpty) {
return false;
}
if (errt != nullptr || erre != nullptr) { // send snapshot if we failed to get term or entries
if (!pr->recentActive_) {
ERAFT_DEBUG("ignore sending snapshot to %x since it is not recently active", to);
return false;
}
raftpb::Snapshot snapshot;
std::tie(snapshot, err) = raftLog_->snapshot();
if (err != nullptr) {
if (err == ErrSnapshotTemporarilyUnavailable) {
ERAFT_DEBUG("%x failed to send snapshot to %x because snapshot is temporarily unavailable", id_, to);
return false;
}
ERAFT_FATAL(err.String().c_str()) // TODO(bdarnell)
}
if (IsEmptySnap(snapshot)) {
ERAFT_FATAL("need non-empty snapshot");
}
auto sindex = snapshot.metadata().index();
auto sterm = snapshot.metadata().term();
ERAFT_DEBUG("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
id_, raftLog_->firstIndex(), raftLog_->committed_, sindex, sterm, to, pr->String().c_str());
pr->BecomeSnapshot(sindex);
ERAFT_DEBUG("%x paused sending replication messages to %x [%s]", id_, to, pr->String().c_str());
raftpb::Message msg;
msg.set_to(to);
msg.set_type(raftpb::MsgSnap);
*msg.mutable_snapshot() = snapshot;
send(std::move(msg));
return true;
}
// Send the actual MsgApp otherwise, and update the progress accordingly.
err = pr->UpdateOnEntriesSend(ents.size(), payloadsSize(ents), nextIndex);
if (err != nullptr) {
ERAFT_FATAL("%x: %s", id_, err.String().c_str());
}
raftpb::Message msg;
msg.set_to(to);
msg.set_type(raftpb::MsgApp);
msg.set_index(lastIndex);
msg.set_logterm(lastTerm);
*msg.mutable_entries() = {std::make_move_iterator(ents.begin()), std::make_move_iterator(ents.end())};
msg.set_commit(raftLog_->committed_);
send(std::move(msg));
return true;
}
// sendHeartbeat sends a heartbeat RPC to the given peer.
inline void raft::sendHeartbeat(uint64_t to, std::string ctx) {
// Attach the commit as min(to.matched, r.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.
auto commit = std::min(trk_.progress_[to]->match_, raftLog_->committed_);
raftpb::Message m;
m.set_to(to);
m.set_type(raftpb::MsgHeartbeat);
m.set_commit(commit);
m.set_context(std::move(ctx));
send(std::move(m));
}
// bcastAppend sends RPC, with entries to all peers that are not up-to-date
// according to the progress recorded in r.prs.
inline void raft::bcastAppend() {
trk_.Visit([this](uint64_t id, std::shared_ptr<tracker::Progress>&) {
if (id == id_) {
return;
}
sendAppend(id);
});
}
// bcastHeartbeat sends RPC, without entries to all the peers.
inline void raft::bcastHeartbeat() {
const auto& lastCtx = readOnly_->lastPendingRequestCtx();
bcastHeartbeatWithCtx(lastCtx);
}
inline void raft::bcastHeartbeatWithCtx(const std::string& ctx) {
trk_.Visit([this, ctx](uint64_t id, std::shared_ptr<tracker::Progress>&) {
if (id == id_) {
return;
}
sendHeartbeat(id, ctx);
});
}
inline void raft::appliedTo(uint64_t index, uint64_t size) {
auto oldApplied = raftLog_->applied_;
auto newApplied = std::max(index, oldApplied);
raftLog_->appliedTo(newApplied, size);
if (trk_.config_.autoLeave_ && newApplied >= pendingConfIndex_ && state_ == StateLeader) {
// If the current (and most recent, at least for this leader's term)
// configuration should be auto-left, initiate that now. We use a
// nil Data which unmarshals into an empty ConfChangeV2 and has the
// benefit that appendEntry can never refuse it based on its size
// (which registers as zero).
raftpb::Message m;
Error err;
std::tie(m, err) = raftpb::detail::confChangeToMsg(nullptr);
if (err != nullptr) {
ERAFT_FATAL(err.String().c_str());
}
// NB: this proposal can't be dropped due to size, but can be
// dropped if a leadership transfer is in progress. We'll keep
// checking this condition on each applied entry, so either the
// leadership transfer will succeed and the new leader will leave
// the joint configuration, or the leadership transfer will fail,
// and we will propose the config change on the next advance.
err = Step(m);
if (err != nullptr) {
ERAFT_DEBUG("not initiating automatic transition out of joint configuration %s: %s",
trk_.config_.String().c_str(), err.String().c_str())
} else {
ERAFT_INFO("initiating automatic transition out of joint configuration %s", trk_.config_.String().c_str());
}
}
}
inline void raft::appliedSnap(const raftpb::Snapshot& snap) {
auto index = snap.metadata().index();
raftLog_->stableSnapTo(index);
appliedTo(index, 0 /* size */);
}
// maybeCommit attempts to advance the commit index. Returns true if
// the commit index changed (in which case the caller should call
// r.bcastAppend).
inline bool raft::maybeCommit() {
auto mci = trk_.Committed();
return raftLog_->maybeCommit(mci, term_);
}
inline void raft::reset(uint64_t term) {
if (term_ != term) {
term_ = term;
vote_ = None;
}
lead_ = None;
electionElapsed_ = 0;
heartbeatElapsed_ = 0;
resetRandomizedElectionTimeout();
abortLeaderTransfer();
trk_.ResetVotes();
trk_.Visit([this](uint64_t id, std::shared_ptr<tracker::Progress>& pr) {
auto new_pr = new tracker::Progress();
new_pr->match_ = 0;
new_pr->next_ = raftLog_->lastIndex() + 1;
new_pr->inflights_ = tracker::NewInflights(trk_.maxInflight_, trk_.maxInflightBytes_);
new_pr->isLearner_ = pr->isLearner_;
pr.reset(new_pr);
if (id == id_) {
pr->match_ = raftLog_->lastIndex();
}
});
pendingConfIndex_ = 0;
uncommittedSize_ = 0;
readOnly_ = detail::newReadOnly(readOnly_->option_);
}
inline bool raft::appendEntry(std::vector<raftpb::Entry> es) {
auto li = raftLog_->lastIndex();
for (size_t i = 0; i < es.size(); i++) {
es[i].set_term(term_);
es[i].set_index(li + 1 + i);
}
// Track the size of this uncommitted proposal.
if (!increaseUncommittedSize(es)) {
ERAFT_WARN("%x appending new entries to log would exceed uncommitted entry size limit; dropping proposal", id_);
// Drop the proposal.
return false;
}
// use latest "last" index after truncate/append
li = raftLog_->append(std::move(es));
// The leader needs to self-ack the entries just appended once they have
// been durably persisted (since it doesn't send an MsgApp to itself). This
// response message will be added to msgsAfterAppend and delivered back to
// this node after these entries have been written to stable storage. When
// handled, this is roughly equivalent to:
//
// r.prs.Progress[r.id].MaybeUpdate(e.Index)
// if r.maybeCommit() {
// r.bcastAppend()
// }
raftpb::Message msg;
msg.set_to(id_);
msg.set_type(raftpb::MsgAppResp);
msg.set_index(li);
send(std::move(msg));
return true;
}
// tickElection is run by followers and candidates after r.electionTimeout.
inline void raft::tickElection() {
electionElapsed_++;
if (promotable() && pastElectionTimeout()) {
electionElapsed_ = 0;
raftpb::Message m;
m.set_from(id_);
m.set_type(raftpb::MsgHup);