-
Notifications
You must be signed in to change notification settings - Fork 542
/
raft.go
1773 lines (1619 loc) · 47 KB
/
raft.go
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 2017-2019 Lei Ni (nilei81@gmail.com)
//
// 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.
/*
Package raft is a distributed consensus package that implements the Raft
protocol.
This package is internally used by Dragonboat, applications are not expected
to import this package.
*/
package raft
import (
"fmt"
"math"
"sort"
"github.com/lni/dragonboat/config"
"github.com/lni/dragonboat/internal/settings"
"github.com/lni/dragonboat/internal/utils/logutil"
"github.com/lni/dragonboat/internal/utils/random"
"github.com/lni/dragonboat/logger"
pb "github.com/lni/dragonboat/raftpb"
)
var (
plog = logger.GetLogger("raft")
)
const (
// NoLeader is the flag used to indcate that there is no leader or the leader
// is unknown.
NoLeader uint64 = 0
// NoNode is the flag used to indicate that the node id field is not set.
NoNode uint64 = 0
noLimit uint64 = math.MaxUint64
numMessageTypes uint64 = 25
)
var (
emptyState = pb.State{}
)
// State is the state of a raft node defined in the raft paper, possible states
// are leader, follower, candidate and observer. Observer is non-voting member
// node.
type State uint64
const (
follower State = iota
candidate
leader
observer
numStates
)
var stateNames = [...]string{
"Follower",
"Candidate",
"Leader",
"Observer",
}
func (st State) String() string {
return stateNames[uint64(st)]
}
// NodeID returns a human friendly form of NodeID for logging purposes.
func NodeID(nodeID uint64) string {
return logutil.NodeID(nodeID)
}
// ClusterID returns a human friendly form of ClusterID for logging purposes.
func ClusterID(clusterID uint64) string {
return logutil.ClusterID(clusterID)
}
type handlerFunc func(pb.Message)
type stepFunc func(*raft, pb.Message)
// Status is the struct that captures the status of a raft node.
type Status struct {
NodeID uint64
ClusterID uint64
Applied uint64
LeaderID uint64
NodeState State
pb.State
}
// IsLeader returns a boolean value indicating whether the node is leader.
func (s *Status) IsLeader() bool {
return s.NodeState == leader
}
// IsFollower returns a boolean value indicating whether the node is a follower.
func (s *Status) IsFollower() bool {
return s.NodeState == follower
}
// getLocalStatus gets a copy of the current raft status.
func getLocalStatus(r *raft) Status {
return Status{
NodeID: r.nodeID,
ClusterID: r.clusterID,
NodeState: r.state,
Applied: r.log.applied,
LeaderID: r.leaderID,
State: r.raftState(),
}
}
//
// Struct raft implements the raft protocol published in Diego Ongarno's PhD
// thesis. Almost all features covered in Diego Ongarno's thesis have been
// implemented, including -
// * leader election
// * log replication
// * flow control
// * membership configuration change
// * snapshotting and streaming
// * log compaction
// * ReadIndex protocol for read-only queries
// * leadership transfer
// * non-voting members
// * idempotent updates
// * quorum check
// * batching
// * pipelining
//
// Features currently being worked on -
// * pre-vote
//
//
// This implementation made references to etcd raft's design in the following
// aspects:
// * it models the raft protocol state as a state machine
// * restricting to at most one pending leadership change at a time
// * replication flow control
//
// 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.
//
//
// When compared with etcd raft, this implementation is quite different,
// including in areas that we made reference to etcd raft -
// * brand new implementation
// * better bootstrapping procedure
// * log entries are partitioned based on whether they are required in
// immediate future rather than whether they have been persisted to disk
// * zero disk read when replicating raft log entries
// * committed entries are applied in a fully asynchronous manner
// * snapshots are applied in a fully asynchronous manner
// * replication messages can be serialized and sent in fully asynchronous manner
// * pagination support when applying committed entries
// * making proposals are fully batched
// * ReadIndex protocol implementation are fully batched
// * unsafe read-only queries that rely on local clock is not supported
// * non-voting members are implemented as a special raft state
// * non-voting members can initiate both new proposal and ReadIndex requests
// * simplified flow control
//
type raft struct {
applied uint64
nodeID uint64
clusterID uint64
term uint64
vote uint64
log *entryLog
remotes map[uint64]*remote
observers map[uint64]*remote
state State
votes map[uint64]bool
msgs []pb.Message
leaderID uint64
leaderTransferTarget uint64
isLeaderTransferTarget bool
pendingConfigChange bool
readIndex *readIndex
readyToRead []pb.ReadyToRead
checkQuorum bool
tickCount uint64
electionTick uint64
heartbeatTick uint64
heartbeatTimeout uint64
electionTimeout uint64
randomizedElectionTimeout uint64
handlers [numStates][numMessageTypes]handlerFunc
handle stepFunc
matched []uint64
hasNotAppliedConfigChange func() bool
recordLeader func(uint64)
}
func newRaft(c *config.Config, logdb ILogDB) *raft {
if err := c.Validate(); err != nil {
panic(err)
}
if logdb == nil {
panic("logdb is nil")
}
r := &raft{
clusterID: c.ClusterID,
nodeID: c.NodeID,
leaderID: NoLeader,
msgs: make([]pb.Message, 0),
log: newEntryLog(logdb),
remotes: make(map[uint64]*remote),
observers: make(map[uint64]*remote),
electionTimeout: c.ElectionRTT,
heartbeatTimeout: c.HeartbeatRTT,
checkQuorum: c.CheckQuorum,
readIndex: newReadIndex(),
}
st, members := logdb.NodeState()
for p := range members.Addresses {
r.remotes[p] = &remote{
next: 1,
}
}
for p := range members.Observers {
r.observers[p] = &remote{
next: 1,
}
}
r.resetMatchValueArray()
if !pb.IsEmptyState(st) {
r.loadState(st)
}
if c.IsObserver {
r.state = observer
r.becomeObserver(r.term, NoLeader)
} else {
// see first paragraph section 5.2 of the raft paper
r.becomeFollower(r.term, NoLeader)
}
r.initializeHandlerMap()
r.checkHandlerMap()
r.handle = defaultHandle
return r
}
func (r *raft) setTestPeers(peers []uint64) {
if len(r.remotes) == 0 {
for _, p := range peers {
r.remotes[p] = &remote{next: 1}
}
}
}
func (r *raft) setApplied(applied uint64) {
r.applied = applied
}
func (r *raft) getApplied() uint64 {
return r.applied
}
func (r *raft) resetMatchValueArray() {
r.matched = make([]uint64, len(r.remotes))
}
func (r *raft) describe() string {
li := r.log.lastIndex()
t, err := r.log.term(li)
if err != nil && err != ErrCompacted {
panic(err)
}
fmtstr := "[f-idx:%d,l-idx:%d,logterm:%d,commit:%d,applied:%d] %s term %d"
return fmt.Sprintf(fmtstr,
r.log.firstIndex(), r.log.lastIndex(), t, r.log.committed,
r.log.applied, logutil.DescribeNode(r.clusterID, r.nodeID), r.term)
}
func (r *raft) isObserver() bool {
return r.state == observer
}
func (r *raft) setLeaderID(leaderID uint64) {
r.leaderID = leaderID
if r.recordLeader != nil {
r.recordLeader(r.leaderID)
}
}
func (r *raft) leaderTransfering() bool {
return r.leaderTransferTarget != NoNode && r.state == leader
}
func (r *raft) abortLeaderTransfer() {
r.leaderTransferTarget = NoNode
}
func (r *raft) quorum() int {
return len(r.remotes)/2 + 1
}
func (r *raft) isSingleNodeQuorum() bool {
return r.quorum() == 1
}
func (r *raft) leaderHasQuorum() bool {
c := 0
for nid := range r.remotes {
if nid == r.nodeID || r.remotes[nid].isActive() {
c++
r.remotes[nid].setNotActive()
}
}
return c >= r.quorum()
}
func (r *raft) nodes() []uint64 {
nodes := make([]uint64, 0, len(r.remotes)+len(r.observers))
for id := range r.remotes {
nodes = append(nodes, id)
}
for id := range r.observers {
nodes = append(nodes, id)
}
sort.Slice(nodes, func(i, j int) bool { return nodes[i] < nodes[j] })
return nodes
}
func (r *raft) raftState() pb.State {
return pb.State{
Term: r.term,
Vote: r.vote,
Commit: r.log.committed,
}
}
func (r *raft) loadState(st pb.State) {
if st.Commit < r.log.committed || st.Commit > r.log.lastIndex() {
plog.Panicf("%s got out of range state, st.commit %d, range[%d,%d]",
r.describe(), st.Commit, r.log.committed, r.log.lastIndex())
}
r.log.committed = st.Commit
r.term = st.Term
r.vote = st.Vote
}
func (r *raft) restore(ss pb.Snapshot) bool {
if ss.Index <= r.log.committed {
plog.Infof("%s, ss.Index <= committed", r.describe())
return false
}
if !r.isObserver() {
for nid := range ss.Membership.Observers {
if nid == r.nodeID {
plog.Panicf("%s converting to observer, index %d, committed %d, %+v",
r.describe(), ss.Index, r.log.committed, ss)
}
}
}
// p52 of the raft thesis
if r.log.matchTerm(ss.Index, ss.Term) {
// a snapshot at index X implies that X has been committed
r.log.commitTo(ss.Index)
return false
}
plog.Infof("%s starts to restore snapshot index %d term %d",
r.describe(), ss.Index, ss.Term)
r.log.restore(ss)
return true
}
func (r *raft) restoreRemotes(ss pb.Snapshot) {
r.remotes = make(map[uint64]*remote)
for id := range ss.Membership.Addresses {
_, ok := r.observers[id]
if ok {
r.becomeFollower(r.term, r.leaderID)
}
match := uint64(0)
next := r.log.lastIndex() + 1
if id == r.nodeID {
match = next - 1
}
r.setRemote(id, match, next)
plog.Infof("%s restored remote progress of %s [%s]",
r.describe(), NodeID(id), r.remotes[id])
}
r.observers = make(map[uint64]*remote)
for id := range ss.Membership.Observers {
match := uint64(0)
next := r.log.lastIndex() + 1
if id == r.nodeID {
match = next - 1
}
r.setObserver(id, match, next)
plog.Infof("%s restored observer progress of %s [%s]",
r.describe(), NodeID(id), r.observers[id])
}
r.resetMatchValueArray()
}
//
// tick related functions
//
func (r *raft) timeForElection() bool {
return r.electionTick >= r.randomizedElectionTimeout
}
func (r *raft) timeForHearbeat() bool {
return r.heartbeatTick >= r.heartbeatTimeout
}
// p69 of the raft thesis mentions that check quorum is performed when an
// election timeout elapses
func (r *raft) timeForCheckQuorum() bool {
return r.electionTick >= r.electionTimeout
}
// p29 of the raft thesis mentions that leadership transfer should abort
// when an election timeout elapses
func (r *raft) timeToAbortLeaderTransfer() bool {
return r.leaderTransfering() && r.electionTick >= r.electionTimeout
}
func (r *raft) tick() {
r.tickCount++
if r.state == leader {
r.leaderTick()
} else {
r.nonLeaderTick()
}
}
func (r *raft) nonLeaderTick() {
if r.state == leader {
panic("noleader tick called on leader node")
}
r.electionTick++
// section 4.2.1 of the raft thesis
// non-voting member is not to do anything related to election
if r.isObserver() {
return
}
// 6th paragraph section 5.2 of the raft paper
if !r.selfRemoved() && r.timeForElection() {
r.electionTick = 0
r.Handle(pb.Message{
From: r.nodeID,
Type: pb.Election,
})
}
}
func (r *raft) leaderTick() {
if r.state != leader {
panic("leaderTick called on a non-leader node")
}
r.electionTick++
timeToAbortLeaderTransfer := r.timeToAbortLeaderTransfer()
if r.timeForCheckQuorum() {
r.electionTick = 0
if r.checkQuorum {
r.Handle(pb.Message{
From: r.nodeID,
Type: pb.CheckQuorum,
})
}
}
if timeToAbortLeaderTransfer {
r.abortLeaderTransfer()
}
r.heartbeatTick++
if r.timeForHearbeat() {
r.heartbeatTick = 0
r.Handle(pb.Message{
From: r.nodeID,
Type: pb.LeaderHeartbeat,
})
}
}
func (r *raft) quiescedTick() {
r.electionTick++
}
func (r *raft) setRandomizedElectionTimeout() {
randTime := random.LockGuardedRand.Uint64() % r.electionTimeout
r.randomizedElectionTimeout = r.electionTimeout + randTime
}
//
// send and broadcast functions
//
func (r *raft) finalizeMessageTerm(m pb.Message) pb.Message {
if m.Term == 0 && m.Type == pb.RequestVote {
plog.Panicf("sending RequestVote with 0 term")
}
if m.Term > 0 && m.Type != pb.RequestVote {
plog.Panicf("term unexpectedly set for message type %d", m.Type)
}
if !isRequestMessage(m.Type) {
m.Term = r.term
}
return m
}
func (r *raft) send(m pb.Message) {
m.From = r.nodeID
m = r.finalizeMessageTerm(m)
r.msgs = append(r.msgs, m)
}
func (r *raft) makeInstallSnapshotMessage(to uint64, m *pb.Message) uint64 {
m.To = to
m.Type = pb.InstallSnapshot
snapshot := r.log.snapshot()
if pb.IsEmptySnapshot(snapshot) {
panic("got an empty snapshot")
}
m.Snapshot = snapshot
return snapshot.Index
}
func (r *raft) makeReplicateMessage(to uint64,
next uint64, maxSize uint64) (pb.Message, error) {
term, err := r.log.term(next - 1)
if err != nil {
return pb.Message{}, err
}
entries, err := r.log.entries(next, maxSize)
if err != nil {
return pb.Message{}, err
}
if len(entries) > 0 {
if entries[len(entries)-1].Index != next-1+uint64(len(entries)) {
plog.Panicf("expected last index in Replicate %d, got %d",
next-1+uint64(len(entries)), entries[len(entries)-1].Index)
}
}
return pb.Message{
To: to,
Type: pb.Replicate,
LogIndex: next - 1,
LogTerm: term,
Entries: entries,
Commit: r.log.committed,
}, nil
}
func (r *raft) sendReplicateMessage(to uint64) {
var rp *remote
if v, ok := r.remotes[to]; ok {
rp = v
} else {
rp, ok = r.observers[to]
if !ok {
panic("failed to get the remote instance")
}
}
if rp.isPaused() {
return
}
m, err := r.makeReplicateMessage(to, rp.next, settings.Soft.MaxEntrySize)
if err != nil {
// log not available due to compaction, send snapshot
if !rp.isActive() {
plog.Warningf("node %s is not active, sending snapshot is skipped",
NodeID(to))
return
}
index := r.makeInstallSnapshotMessage(to, &m)
plog.Infof("%s is sending snapshot (%d) to %s, r.Next %d, r.Match %d, %v",
r.describe(), index, NodeID(to), rp.next, rp.match, err)
rp.becomeSnapshot(index)
} else {
if len(m.Entries) > 0 {
lastIndex := m.Entries[len(m.Entries)-1].Index
rp.progress(lastIndex)
}
}
r.send(m)
}
func (r *raft) broadcastReplicateMessage() {
for nid := range r.remotes {
if nid != r.nodeID {
r.sendReplicateMessage(nid)
}
}
for nid := range r.observers {
if nid == r.nodeID {
panic("observer is trying to broadcast Replicate msg")
}
r.sendReplicateMessage(nid)
}
}
func (r *raft) sendHeartbeatMessage(to uint64,
hint pb.SystemCtx, toObserver bool) {
var match uint64
if toObserver {
match = r.observers[to].match
} else {
match = r.remotes[to].match
}
commit := min(match, r.log.committed)
r.send(pb.Message{
To: to,
Type: pb.Heartbeat,
Commit: commit,
Hint: hint.Low,
HintHigh: hint.High,
})
}
// p72 of the raft thesis describe how to use Heartbeat message in the ReadIndex
// protocol.
func (r *raft) broadcastHeartbeatMessage() {
if r.readIndex.hasPendingRequest() {
ctx := r.readIndex.peepCtx()
r.broadcastHeartbeatMessageWithHint(ctx)
} else {
r.broadcastHeartbeatMessageWithHint(pb.SystemCtx{})
}
}
func (r *raft) broadcastHeartbeatMessageWithHint(ctx pb.SystemCtx) {
zeroCtx := pb.SystemCtx{}
for id := range r.remotes {
if id != r.nodeID {
r.sendHeartbeatMessage(id, ctx, false)
}
}
if ctx == zeroCtx {
for id := range r.observers {
r.sendHeartbeatMessage(id, zeroCtx, true)
}
}
}
func (r *raft) sendTimeoutNowMessage(target uint64) {
r.send(pb.Message{
Type: pb.TimeoutNow,
To: target,
})
}
//
// log append and commit
//
func (r *raft) sortMatchValues() {
// unrolled bubble sort, sort.Slice is not allocation free
if len(r.matched) == 3 {
if r.matched[0] > r.matched[1] {
v := r.matched[0]
r.matched[0] = r.matched[1]
r.matched[1] = v
}
if r.matched[1] > r.matched[2] {
v := r.matched[1]
r.matched[1] = r.matched[2]
r.matched[2] = v
}
if r.matched[0] > r.matched[1] {
v := r.matched[0]
r.matched[0] = r.matched[1]
r.matched[1] = v
}
} else {
sort.Slice(r.matched, func(i, j int) bool {
return r.matched[i] < r.matched[j]
})
}
}
func (r *raft) tryCommit() bool {
if len(r.remotes) != len(r.matched) {
r.resetMatchValueArray()
}
idx := 0
for _, v := range r.remotes {
r.matched[idx] = v.match
idx++
}
r.sortMatchValues()
q := r.matched[len(r.remotes)-r.quorum()]
// see p8 raft paper
// "Raft never commits log entries from previous terms by counting replicas.
// Only log entries from the leader’s current term are committed by counting
// replicas"
return r.log.tryCommit(q, r.term)
}
func (r *raft) appendEntries(entries []pb.Entry) {
lastIndex := r.log.lastIndex()
for i := range entries {
entries[i].Term = r.term
entries[i].Index = lastIndex + 1 + uint64(i)
}
r.log.append(entries)
r.remotes[r.nodeID].tryUpdate(r.log.lastIndex())
if r.isSingleNodeQuorum() {
r.tryCommit()
}
}
//
// state transition related functions
//
func (r *raft) becomeObserver(term uint64, leaderID uint64) {
if r.state != observer {
panic("transitioning to observer state from non-observer")
}
r.reset(term)
r.setLeaderID(leaderID)
plog.Infof("%s became an observer", r.describe())
}
func (r *raft) becomeFollower(term uint64, leaderID uint64) {
r.state = follower
r.reset(term)
r.setLeaderID(leaderID)
plog.Infof("%s became a follower", r.describe())
}
func (r *raft) becomeCandidate() {
if r.state == leader {
panic("transitioning to candidate state from leader")
}
if r.state == observer {
panic("observer is becoming candidate")
}
r.state = candidate
// 2nd paragraph section 5.2 of the raft paper
r.reset(r.term + 1)
r.vote = r.nodeID
plog.Infof("%s became a candidate", r.describe())
}
func (r *raft) becomeLeader() {
if r.state == follower {
panic("transitioning to leader state from follower")
}
if r.state == observer {
panic("observer is become leader")
}
r.state = leader
r.reset(r.term)
r.setLeaderID(r.nodeID)
r.preLeaderPromotionHandleConfigChange()
// p72 of the raft thesis
r.appendEntries([]pb.Entry{{Type: pb.ApplicationEntry, Cmd: nil}})
plog.Infof("%s became the leader", r.describe())
}
func (r *raft) reset(term uint64) {
if r.term != term {
r.term = term
r.vote = NoLeader
}
r.setLeaderID(NoLeader)
r.votes = make(map[uint64]bool)
r.electionTick = 0
r.heartbeatTick = 0
r.setRandomizedElectionTimeout()
r.readIndex = newReadIndex()
r.clearPendingConfigChange()
r.abortLeaderTransfer()
r.resetRemotes()
r.resetObservers()
r.resetMatchValueArray()
}
func (r *raft) preLeaderPromotionHandleConfigChange() {
n := r.getPendingConfigChangeCount()
if n > 1 {
panic("multiple uncommitted config change entries")
} else if n == 1 {
plog.Infof("%s is becoming a leader with pending Config Change",
r.describe())
r.setPendingConfigChange()
}
}
// see section 5.3 of the raft paper
// "When a leader first comes to power, it initializes all nextIndex values to
// the index just after the last one in its log"
func (r *raft) resetRemotes() {
for id := range r.remotes {
r.remotes[id] = &remote{
next: r.log.lastIndex() + 1,
}
if id == r.nodeID {
r.remotes[id].match = r.log.lastIndex()
}
}
}
func (r *raft) resetObservers() {
for id := range r.observers {
r.observers[id] = &remote{
next: r.log.lastIndex() + 1,
}
if id == r.nodeID {
r.observers[id].match = r.log.lastIndex()
}
}
}
//
// election related functions
//
func (r *raft) handleVoteResp(from uint64, rejected bool) int {
if rejected {
plog.Infof("%s received RequestVoteResp rejection from %s at term %d",
r.describe(), NodeID(from), r.term)
} else {
plog.Infof("%s received RequestVoteResp from %s at term %d",
r.describe(), NodeID(from), r.term)
}
votedFor := 0
if _, ok := r.votes[from]; !ok {
r.votes[from] = !rejected
}
for _, v := range r.votes {
if v {
votedFor++
}
}
return votedFor
}
func (r *raft) campaign() {
plog.Infof("%s campaign called, remotes len: %d", r.describe(), len(r.remotes))
r.becomeCandidate()
term := r.term
r.handleVoteResp(r.nodeID, false)
if r.isSingleNodeQuorum() {
r.becomeLeader()
return
}
var hint uint64
if r.isLeaderTransferTarget {
hint = r.nodeID
r.isLeaderTransferTarget = false
}
for k := range r.remotes {
if k == r.nodeID {
continue
}
r.send(pb.Message{
Term: term,
To: k,
Type: pb.RequestVote,
LogIndex: r.log.lastIndex(),
LogTerm: r.log.lastTerm(),
Hint: hint,
})
plog.Infof("%s sent RequestVote to node %s", r.describe(), NodeID(k))
}
}
//
// membership management
//
func (r *raft) selfRemoved() bool {
if r.state == observer {
_, ok := r.observers[r.nodeID]
return !ok
}
_, ok := r.remotes[r.nodeID]
return !ok
}
func (r *raft) addNode(nodeID uint64) {
r.clearPendingConfigChange()
if _, ok := r.remotes[nodeID]; ok {
// already a voting member
return
}
if rp, ok := r.observers[nodeID]; ok {
// promoting to full member with inheriated progress info
r.deleteObserver(nodeID)
r.remotes[nodeID] = rp
// local peer promoted, become follower
if nodeID == r.nodeID {
r.becomeFollower(r.term, r.leaderID)
}
} else {
r.setRemote(nodeID, 0, r.log.lastIndex()+1)
}
}
func (r *raft) addObserver(nodeID uint64) {
r.clearPendingConfigChange()
if _, ok := r.observers[nodeID]; ok {
return
}
r.setObserver(nodeID, 0, r.log.lastIndex()+1)
}
func (r *raft) removeNode(nodeID uint64) {
r.deleteRemote(nodeID)
r.deleteObserver(nodeID)
r.clearPendingConfigChange()
if r.leaderTransfering() && r.leaderTransferTarget == nodeID {
r.abortLeaderTransfer()
}
if len(r.remotes) > 0 {
if r.tryCommit() {
r.broadcastReplicateMessage()
}
}
}
func (r *raft) deleteRemote(nodeID uint64) {
delete(r.remotes, nodeID)
r.resetMatchValueArray()
}
func (r *raft) deleteObserver(nodeID uint64) {
delete(r.observers, nodeID)
}
func (r *raft) setRemote(nodeID uint64, match uint64, next uint64) {
plog.Infof("%s set remote, id %s, match %d, next %d",
r.describe(), NodeID(nodeID), match, next)
r.remotes[nodeID] = &remote{
next: next,
match: match,
}
r.resetMatchValueArray()
}
func (r *raft) setObserver(nodeID uint64, match uint64, next uint64) {
plog.Infof("%s set observer, id %s, match %d, next %d",
r.describe(), NodeID(nodeID), match, next)
r.observers[nodeID] = &remote{
next: next,
match: match,
}
}
//
// helper methods required for the membership change implementation
//
// p33-35 of the raft thesis describes a simple membership change protocol which
// requires only one node can be added or removed at a time. its safety is
// guarded by the fact that when there is only one node to be added or removed
// at a time, the old and new quorum are guaranteed to overlap.
// the protocol described in the raft thesis requires the membership change
// entry to be executed as soon as it is appended. this also introduces an extra
// troublesome step to roll back to an old membership configuration when
// necessary.
// similar to etcd raft, we treat such membership change entry as regular
// entries that are only executed after being committed (by the old quorum).
// to do that, however, we need to further restrict the leader to only has at
// most one pending not applied membership change entry in its log. this is to
// avoid the situation that two pending membership change entries are committed
// in one go with the same quorum while they actually require different quorums.
// consider the following situation -
// for a 3 nodes cluster with existing members X, Y and Z, let's say we first
// propose a membership change to add a new node A, before A gets committed and
// applied, say we propose another membership change to add a new node B. When
// B gets committed, A will be committed as well, both will be using the 3 node
// membership quorum meaning both entries concerning A and B will become
// committed when any two of the X, Y, Z cluster have them replicated. this thus
// violates the safety requirement as B will require 3 out of the 4 nodes (X,
// Y, Z, A) to have it replicated before it can be committed.
// we use the following pendingConfigChange flag to help tracking whether there
// is already a pending membership change entry in the log waiting to be
// executed.
//