-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraft.go
More file actions
2531 lines (2356 loc) · 122 KB
/
Copy pathraft.go
File metadata and controls
2531 lines (2356 loc) · 122 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 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.
package raft
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"math"
"math/big"
"sort"
"strings"
"sync"
"go.etcd.io/raft/v3/confchange"
"go.etcd.io/raft/v3/quorum"
pb "go.etcd.io/raft/v3/raftpb"
"go.etcd.io/raft/v3/tracker"
)
const (
// None is a placeholder node ID used when there is no leader.
None uint64 = 0
// LocalAppendThread is a reference to a local thread that saves unstable
// log entries and snapshots to stable storage. The identifier is used as a
// target for MsgStorageAppend messages when AsyncStorageWrites is enabled.
LocalAppendThread uint64 = math.MaxUint64
// LocalApplyThread is a reference to a local thread that applies committed
// log entries to the local state machine. The identifier is used as a
// target for MsgStorageApply messages when AsyncStorageWrites is enabled.
LocalApplyThread uint64 = math.MaxUint64 - 1
)
// Possible values for StateType.
const (
StateFollower StateType = iota
StateCandidate
StateLeader
StatePreCandidate
numStates
)
type ReadOnlyOption int
const (
// ReadOnlySafe guarantees the linearizability of the read only request by
// communicating with the quorum. It is the default and suggested option.
// ReadOnlySafe通过与法定人数通信,保证了只读请求的线性化。这是默认和建议的选项。
ReadOnlySafe ReadOnlyOption = iota
// 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.
// ReadOnlyLeaseBased通过依赖领导者租约来保证只读请求的线性化。它可能会受到时钟漂移的影响。
// 如果时钟漂移是无界的,领导者可能会保留比规定时间来说更长的租约(时钟可以在没有任何限制的情况下向后移动/暂停)。
// 在这种情况下,ReadIndex是不安全的。
ReadOnlyLeaseBased
)
// Possible values for CampaignType
const (
// campaignPreElection represents the first phase of a normal election when
// Config.PreVote is true.
// campaignPreElection 表示Config.PreVote为true时正常选举的第一阶段
campaignPreElection CampaignType = "CampaignPreElection"
// campaignElection represents a normal (time-based) election (the second phase
// of the election when Config.PreVote is true).
// campaignElection 表示正常(基于时间的)选举(Config.PreVote为true时的第二阶段)
campaignElection CampaignType = "CampaignElection"
// campaignTransfer represents the type of leader transfer
campaignTransfer CampaignType = "CampaignTransfer"
)
const noLimit = math.MaxUint64
// ErrProposalDropped is returned when the proposal is ignored by some cases,
// so that the proposer can be notified and fail fast.
var ErrProposalDropped = errors.New("raft proposal dropped")
// lockedRand is a small wrapper around rand.Rand to provide
// synchronization among multiple raft groups. Only the methods needed
// by the code are exposed (e.g. Intn).
type lockedRand struct {
mu sync.Mutex
}
func (r *lockedRand) Intn(n int) int {
r.mu.Lock()
v, _ := rand.Int(rand.Reader, big.NewInt(int64(n)))
r.mu.Unlock()
return int(v.Int64())
}
var globalRand = &lockedRand{}
// 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
type CampaignType string
// StateType represents the role of a node in a cluster.
type StateType uint64
var stmap = [...]string{
"StateFollower",
"StateCandidate",
"StateLeader",
"StatePreCandidate",
}
func (st StateType) String() string {
return stmap[st]
}
// Config contains the parameters to start a raft.
type Config struct {
// ID is the identity of the local raft. ID cannot be 0.
ID uint64
// 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.
// ElectionTick是必须在选举之间传递的Node.Tick调用次数。也就是说,如果在ElectionTick过去之前,
// 跟随者没有收到当前任期的领导者的任何消息,它将成为候选者并开始选举。ElectionTick必须大于HeartbeatTick。
// 我们建议ElectionTick = 10 * HeartbeatTick,以避免不必要的领导者切换。
ElectionTick int
// 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.
// HeartbeatTick是必须在心跳之间传递的Node.Tick调用次数。也就是说,领导者每HeartbeatTick个tick
// 发送一次心跳消息以维持其领导地位。
HeartbeatTick int
// 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.
// Storage是raft的存储。raft生成要存储在存储中的条目和状态。当需要时,raft从存储中读取持久化的条目和状态。
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.
// Applied是最后应用的索引。只有在重新启动raft时才应该设置。raft不会返回小于或等于Applied的条目给应用程序。
// 如果在重新启动时未设置Applied,raft可能会返回先前应用的条目。这是一个非常依赖于应用程序的配置。
Applied uint64
// 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.
// AsyncStorageWrites配置raft节点使用请求/响应消息传递接口而不是
// 默认的Ready/Advance函数调用接口将数据写入本地存储(raft日志和状态机)。
// 本地存储消息可以进行流水线处理并异步处理(与Ready迭代相对),有助于减少Raft提案之间的干扰,
// 并增加日志附加和状态机应用的批处理。因此,使用异步存储写入可以减少端到端提交延迟并增加最大吞吐量。
//
// 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.
// 当为true时,Ready.Message切片将包含MsgStorageAppend和MsgStorageApply消息。
// 这些消息将分别针对LocalAppendThread和LocalApplyThread。必须按顺序可靠地处理相同目标的消息。
// 换句话说,它们不能被丢弃(例如网络上的消息),并且针对同一线程的消息不能被重新排序。
// 可以以任何顺序处理针对不同目标的消息。
//
// 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.
// MsgStorageAppend携带要附加的Raft日志条目、选举投票/任期更改/更新的提交索引以及要应用的快照。
// 在传递响应消息之前,MsgStorageAppend中执行的所有写操作都必须是持久的。
// 但是,如果MsgStorageAppend不携带响应消息,则不需要持久性。该消息扮演Ready中的Entries、HardState和Snapshot字段的角色。
//
// 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.
// MsgStorageApply携带要应用的已提交条目。在传递响应消息之前,MsgStorageApply中执行的写操作无需是持久的。
// 该消息扮演Ready中的CommittedEntries字段的角色。
//
// 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.
// 本地消息每个携带一个或多个响应消息,这些响应消息应在相应的存储写入完成后传递。
// 这些响应可能针对同一节点,也可能针对其他节点。存储线程不负责理解响应消息,只负责在执行存储写入后将其传递到正确的目标。
AsyncStorageWrites bool
// 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.
// MaxSizePerMsg限制每个附加消息的最大字节大小。较小的值降低了raft恢复成本(初始探测和正常操作期间丢失的消息)。
MaxSizePerMsg uint64
// MaxCommittedSizePerReady limits the size of the committed entries which
// can be applying at the same time.
// MaxCommittedSizePerReady限制了可以同时应用的已提交条目的大小。
//
// 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.
// 尽管它的名称(为了兼容性而保留)是这样的,但是当启用AsyncStorageWrites时,此配额适用于Ready结构,
MaxCommittedSizePerReady uint64
// 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.
// MaxUncommittedEntriesSize限制了可以附加到领导者日志中的未提交条目的聚合字节大小。
// 一旦超过此限制,提案将开始返回ErrProposalDropped错误。注意:0表示没有限制。
MaxUncommittedEntriesSize uint64
// 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?
// MaxInflightMsgs限制了乐观复制阶段中在途附加消息的最大数量。
// 应用传输层通常具有自己的TCP/UDP发送缓冲区。设置MaxInflightMsgs以避免溢出发送缓冲区。
// TODO(xiangli):反馈给应用程序以限制提案速率?
MaxInflightMsgs int
// MaxInflightBytes limits the number of in-flight bytes in append messages.
// Complements MaxInflightMsgs. Ignored if zero.
// MaxInflightBytes限制了附加消息中在途字节的数量。补充MaxInflightMsgs。如果为零,则忽略。
//
// 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.
// 这有效地限制了带宽延迟乘积。请注意,特别是在高延迟部署中,将此设置得太低可能会导致吞吐量大幅减少。
// 例如,对于一个与leader之间的往返延迟为100ms的对等节点,如果此设置为1MB,则该组的吞吐量限制为10MB/s。
// 如果RTT为400ms,则降至2.5MB/s。请参见Little's law以了解背后的数学原理。
MaxInflightBytes uint64
// CheckQuorum specifies if the leader should check quorum activity. Leader
// steps down when quorum is not active for an electionTimeout.
// CheckQuorum指定领导者是否应检查法定活动。当选举超时时,领导者会下台。
CheckQuorum bool
// 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.
// PreVote启用了raft论文第9.6节中描述的Pre-Vote算法。当一个被分区的节点重新加入集群时,这可以防止中断。
PreVote bool
// ReadOnlyOption specifies how the read only request is processed.
// ReadOnlyOption指定如何处理只读请求。
//
// ReadOnlySafe guarantees the linearizability of the read only request by
// communicating with the quorum. It is the default and suggested option.
// ReadOnlySafe通过与法定人数通信,保证了只读请求的线性化。这是默认和建议的选项。
//
// 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.
// ReadOnlyLeaseBased通过依赖领导者租约来保证只读请求的线性化。它可能会受到时钟漂移的影响。
// 如果时钟漂移是无界的,领导者可能会保留比规定时间来说更长的租约(时钟可以在没有任何限制的情况下向后移动/暂停)。
// 在这种情况下,ReadIndex是不安全的。
// 如果ReadOnlyOption是ReadOnlyLeaseBased,则必须启用CheckQuorum。
ReadOnlyOption ReadOnlyOption
// Logger is the logger used for raft log. For multinode which can host
// multiple raft group, each raft group can have its own logger
// Logger是用于raft日志的记录器。对于可以托管多个raft组的多节点,每个raft组都可以有自己的记录器
Logger Logger
// 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.
// 将DisableProposalForwarding设置为true意味着跟随者将丢弃提案,而不是将其转发给领导者。
// 此功能的一个用例是在Raft领导者用于计算提案的数据的情况下,例如,以单调递增的方式向数据添加混合逻辑时钟的时间戳。
// 应禁用转发以防止具有不准确混合逻辑时钟的跟随者分配时间戳,然后将数据转发给领导者。
DisableProposalForwarding bool
// 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.
// DisableConfChangeValidation禁用对配置更改在raft实例的当前活动配置中的验证。
// 这些检查通常是明智的(除非在联合配置中,否则不能离开联合配置等),但它们有误报,因为活动配置可能不是最新的配置。
// 这是因为配置是在日志应用期间激活的,即使领导者也可能落后于日志应用,而日志应用的条目数量是无界的。
//
// 对称地,该机制存在误报,因为检查可能不会针对将成为新提议的配置的“实际”配置运行,检查可能会通过,
// 但在应用时新配置可能无效。换句话说,这些检查是尽力而为的。
// 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.
// 用户不应使用此选项,除非他们有一个可靠的机制(在raft之上)来串行化和验证配置更改。
// 如果无效的配置更改进入日志并被应用,将导致恐慌。
//
// This option may be removed once false positives are no longer possible.
// See: https://github.com/etcd-io/raft/issues/80
// 一旦不再可能出现误报,此选项可能会被删除。请参见:
DisableConfChangeValidation bool
// StepDownOnRemoval makes the leader step down when it is removed from the
// group or demoted to a learner.
// StepDownOnRemoval使领导者在从组中删除或降级为学习者时下台。
//
// This behavior will become unconditional in the future. See:
// https://github.com/etcd-io/raft/issues/83
StepDownOnRemoval bool
}
func (c *Config) validate() error {
if c.ID == None {
return errors.New("cannot use none as id")
}
if IsLocalMsgTarget(c.ID) {
return errors.New("cannot use local target as id")
}
if c.HeartbeatTick <= 0 {
return errors.New("heartbeat tick must be greater than 0")
}
if c.ElectionTick <= c.HeartbeatTick {
return errors.New("election tick must be greater than heartbeat tick")
}
if c.Storage == nil {
return errors.New("storage cannot be nil")
}
if c.MaxUncommittedEntriesSize == 0 {
c.MaxUncommittedEntriesSize = noLimit
}
// default MaxCommittedSizePerReady to MaxSizePerMsg because they were
// previously the same parameter.
if c.MaxCommittedSizePerReady == 0 {
c.MaxCommittedSizePerReady = c.MaxSizePerMsg
}
if c.MaxInflightMsgs <= 0 {
return errors.New("max inflight messages must be greater than 0")
}
if c.MaxInflightBytes == 0 {
c.MaxInflightBytes = noLimit
} else if c.MaxInflightBytes < c.MaxSizePerMsg {
return errors.New("max inflight bytes must be >= max message size")
}
if c.Logger == nil {
c.Logger = getLogger()
}
if c.ReadOnlyOption == ReadOnlyLeaseBased && !c.CheckQuorum {
return errors.New("CheckQuorum must be enabled when ReadOnlyOption is ReadOnlyLeaseBased")
}
return nil
}
type raft struct {
id uint64
Term uint64
Vote uint64
readStates []ReadState
// the log
raftLog *raftLog
maxMsgSize entryEncodingSize
maxUncommittedSize entryPayloadSize
trk tracker.ProgressTracker
state StateType
// isLearner is true if the local raft node is a learner.
isLearner bool
// msgs contains the list of messages that should be sent out immediately to
// other nodes.
// msgs 包含应立即发送到其他节点的消息列表。
//
// Messages in this list must target other nodes.
// 此列表中的消息必须针对其他节点。
msgs []pb.Message
// 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.
// msgsAfterAppend 包含了一系列消息,当累积的不稳定状态(例如term、vote、[]entry和snapshot)已
// 经被持久化到持久存储后,这些消息应该被发送。
// 这包括等待任何处于被持久化过程中的unstable state(即已在先前的Ready结构中分发)完成持久化操作,
// 之后发送这些消息标记着已经完成持久化操作。
//
// 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.
// 此列表中的消息类型为MsgAppResp、MsgVoteResp或MsgPreVoteResp。有关详细信息,请参见raft.send中的注释。
// 里面存放的是Response类型消息,而这些消息大多数依赖于某些unstable state,只有当这些unstable state被持久化后才能发送
msgsAfterAppend []pb.Message
// the leader id
lead uint64
// leadTransferee is id of the leader transfer target when its value is not zero.
// Follow the procedure defined in raft thesis 3.10.
// 当其值不为零时,leadTransferee是领导者转移目标的id。
// 遵循raft论文3.10中定义的过程。
leadTransferee uint64
// 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.
// 只有一个配置变更可以是挂起的(在日志中,但尚未应用)。
// 这是通过pendingConfIndex强制执行的,该值设置为>=最新挂起的配置更改的日志索引(如果有)。
// 只有当leader的应用索引大于此值时,才允许提议配置更改。
pendingConfIndex uint64
// disableConfChangeValidation is Config.DisableConfChangeValidation,
// see there for details.
// disableConfChangeValidation是Config.DisableConfChangeValidation,有关详细信息,请参见那里。
// 配置更改验证是否被禁用,一般情况下是不会被禁用的
disableConfChangeValidation bool
// 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.
// Raft日志未提交尾部大小的估计。用于防止无限制的日志增长。仅由leader维护。在term更改时重置。
uncommittedSize entryPayloadSize
// readOnly用于处理只读请求。
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.
electionElapsed int
// number of ticks since it reached last heartbeatTimeout.
// only leader keeps heartbeatElapsed.
heartbeatElapsed int
// 可选项:Leader应定期检查集群中的大多数节点是否活跃。如果Leader在选举超时期间没有收到大多数节点的消息,则它将放弃领导权。
checkQuorum bool
// 可选项:Leader在选举超时期间是否应该进行预投票。预投票是一种防止节点在重新加入集群时发生中断的机制。
preVote bool
heartbeatTimeout int
electionTimeout int
// randomizedElectionTimeout is a random number between
// [electiontimeout, 2 * electiontimeout - 1]. It gets reset
// when raft changes its state to follower or candidate.
randomizedElectionTimeout int
disableProposalForwarding bool
stepDownOnRemoval bool
tick func()
step stepFunc
logger Logger
// 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.
// pendingReadIndexMessages用于存储MsgReadIndex类型的消息,
// 因为新领导者在当前任期中没有提交任何日志,所以无法回答这些消息。
// 这些消息将在当前任期中提交第一条日志时尽快处理。
pendingReadIndexMessages []pb.Message
}
func newRaft(c *Config) *raft {
if err := c.validate(); err != nil {
panic(err.Error())
}
raftlog := newLogWithSize(c.Storage, c.Logger, entryEncodingSize(c.MaxCommittedSizePerReady))
hs, cs, err := c.Storage.InitialState()
if err != nil {
panic(err) // TODO(bdarnell)
}
r := &raft{
id: c.ID,
lead: None,
isLearner: false,
raftLog: raftlog,
maxMsgSize: entryEncodingSize(c.MaxSizePerMsg),
maxUncommittedSize: entryPayloadSize(c.MaxUncommittedEntriesSize),
trk: tracker.MakeProgressTracker(c.MaxInflightMsgs, c.MaxInflightBytes),
electionTimeout: c.ElectionTick,
heartbeatTimeout: c.HeartbeatTick,
logger: c.Logger,
checkQuorum: c.CheckQuorum,
preVote: c.PreVote,
readOnly: newReadOnly(c.ReadOnlyOption),
disableProposalForwarding: c.DisableProposalForwarding,
disableConfChangeValidation: c.DisableConfChangeValidation,
stepDownOnRemoval: c.StepDownOnRemoval,
}
lastID := r.raftLog.lastEntryID()
cfg, trk, err := confchange.Restore(confchange.Changer{
Tracker: r.trk,
LastIndex: lastID.index,
}, cs)
if err != nil {
panic(err)
}
assertConfStatesEquivalent(r.logger, cs, r.switchToConfig(cfg, trk))
if !IsEmptyHardState(hs) {
r.loadState(hs)
}
if c.Applied > 0 {
raftlog.appliedTo(c.Applied, 0 /* size */)
}
r.becomeFollower(r.Term, None)
var nodesStrs []string
for _, n := range r.trk.VoterNodes() {
nodesStrs = append(nodesStrs, fmt.Sprintf("%x", n))
}
// TODO(pav-kv): it should be ok to simply print %+v for lastID.
r.logger.Infof("newRaft %x [peers: [%s], term: %d, commit: %d, applied: %d, lastindex: %d, lastterm: %d]",
r.id, strings.Join(nodesStrs, ","), r.Term, r.raftLog.committed, r.raftLog.applied, lastID.index, lastID.term)
return r
}
func (r *raft) hasLeader() bool { return r.lead != None }
func (r *raft) softState() SoftState { return SoftState{Lead: r.lead, RaftState: r.state} }
func (r *raft) hardState() pb.HardState {
return pb.HardState{
Term: r.Term,
Vote: r.Vote,
Commit: r.raftLog.committed,
}
}
// send schedules persisting state to a stable storage and AFTER that
// sending the message (as part of next Ready message processing).
// send调度将状态持久化到稳定存储,并在此之后发送消息(作为下一个Ready消息处理的一部分)。
func (r *raft) send(m pb.Message) {
if m.From == None {
m.From = r.id
}
if m.Type == pb.MsgVote || m.Type == pb.MsgVoteResp || m.Type == pb.MsgPreVote || m.Type == pb.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
// 所有{pre-,}campaign消息在发送时都需要设置term。
// - MsgVote:m.Term是节点正在竞选的任期,当竞选时我们会递增term,因此m.Term是非零的。
// - MsgVoteResp:如果MsgVote被授予,则m.Term是新的r.Term,由于MsgVote的原因,m.Term是非零的。
// - MsgPreVote:m.Term是节点将要竞选的任期,由于我们使用m.Term来指示我们将要竞选的下一个任期,因此m.Term是非零的。
// - MsgPreVoteResp:如果预投票被授予,则m.Term是从原始MsgPreVote消息中收到的任期,由于MsgPreVote的原因,m.Term是非零的。
r.logger.Panicf("term should be set when sending %s", m.Type)
}
} else {
// 因为我们在别的地方创建消息时是不会set term的,所以m.Term在这里时应该为0
// 除了MsgVote、MsgVoteResp、MsgPreVote、MsgPreVoteResp这四种消息,其他消息的term都应该为0
if m.Term != 0 {
r.logger.Panicf("term should not be set when sending %s (was %d)", m.Type, 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.
//
// 不要将term附加到MsgProp、MsgReadIndex提案上是一种转发到leader的方式,MsgProp
// 和MsgReadIndex应该被视为本地消息。MsgReadIndex也被转发到leader。
//
// 换言之,我们只为除了MsgProp和MsgReadIndex之外的消息设置term
// 因为MsgVote、MsgVoteResp、MsgPreVote、MsgPreVoteResp这四种消息是在别的地方创建的,所以它们的term是已经设置好的
if m.Type != pb.MsgProp && m.Type != pb.MsgReadIndex {
m.Term = r.Term
}
}
if m.Type == pb.MsgAppResp || m.Type == pb.MsgVoteResp || m.Type == pb.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.
// 如果启用了异步存储写入,则允许在不稳定状态(例如日志条目写入和选举投票)已经持久地同步到本地磁盘之前,
// 将消息添加到msgs切片中并发送出去。
//
// 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.
// 对于大多数消息类型,这不是问题。然而,与"voting"有关的响应消息,无论是领导者选举还是日志附加
// 都需要在发送之前进行持久化。在一轮选举中,发布投票之前必须将该投票结果同步到本地的稳定存储中。
// 类似地,在将日志附加确认发送给leader之前,必须将该条目同步到本地的稳定存储中。
//
// Per the Raft thesis, section 3.8 Persisted state and server restarts:
// 根据Raft论文第3.8节持久化状态和服务器重启:
//
// > 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
// > Raft服务器必须将足够的信息持久化到稳定存储中,以安全地在服务器重启时生存。
// > 特别是,每个服务器都会持久化其当前任期和投票;这是为了防止服务器在同一任期中投票两次
// > 或用被罢免的领导者的日志条目替换来自新领导者的日志条目。每个服务器还会在将新的日志条目
// > 计入条目的提交之前将其持久化;这可以防止在服务器重启时丢失或“未提交”已提交的条目。
//
// 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.
// 为了强制执行这种持久性要求,一旦当前的不稳定状态集合(响应消息所依赖的状态)已经持久化,
// 这些响应消息就会被排队发送。这种不稳定状态可能已经被传递给了一个正在持久化的Ready结构或者
// 可能正在等待下一个Ready结构开始被写入Storage。这些消息必须等待所有这些状态都持久化后才能发布。
//
// 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.
// 被拒绝的响应(m.Reject == true)提出了一个有趣的情况,其中持久性要求不那么明确。
// 拒绝可能是基于不稳定状态的。例如,一个节点可能会拒绝对一个对等节点的投票,因为它已经开始同步
// 对另一个对等节点的投票。或者它可能会拒绝来自一个对等节点的投票请求,因为它有不稳定的日志条目,
// 这些日志条目表明该对等节点在日志上落后了。在这些情况下,立即发送拒绝响应似乎是安全的,而不会
// 在服务器重启时影响安全性。然而,由于这些拒绝情况很少见,并且因为这种行为的安全性尚未得到正式验证,
// 我们在安全性方面犯了错误,并省略了上面的`&& !m.Reject`条件。
r.msgsAfterAppend = append(r.msgsAfterAppend, m)
} else {
if m.To == r.id {
r.logger.Panicf("message should not be self-addressed when sending %s", m.Type)
}
// 非Response类型的消息,直接添加到msgs切片中,等待发送即可
r.msgs = append(r.msgs, m)
}
}
// sendAppend sends an append RPC with new entries (if any) and the
// current commit index to the given peer.
// sendAppend向给定的peer发送带有新条目(如果有的话)和当前commitIndex的append RPC。
func (r *raft) sendAppend(to uint64) {
r.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).
// 如果有必要的话,maybeSendAppend 发送带有新条目的append RPC到给定的peer。
// 如果发送了消息,则返回true。sendIfEmpty参数控制是否发送没有条目的消息
// (“空”消息对于传达更新的提交索引很有用,但在批量发送多条消息时是不希望的)。
func (r *raft) maybeSendAppend(to uint64, sendIfEmpty bool) bool {
pr := r.trk.Progress[to]
if pr.IsPaused() {
return false
}
prevIndex := pr.Next - 1
prevTerm, err := r.raftLog.term(prevIndex)
if err != nil {
// The log probably got truncated at >= pr.Next, so we can't catch up the
// follower log anymore. Send a snapshot instead.
// 日志可能在>=pr.Next处被截断,因此我们无法再追赶追随者日志。发送快照。
return r.maybeSendSnapshot(to, pr)
}
var ents []pb.Entry
// 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.
// 在受限的StateReplicate状态下,只发送空的MsgApp,以确保进度。
// 否则,如果我们有一个满的Inflights并且所有的inflight消息实际上都被丢弃了,那么复制到该follower将会停滞。
// 相反,一个空的MsgApp最终会到达follower(心跳响应促使leader发送一个append),允许它被确认或拒绝,这两者都会清除Inflights。
if pr.State != tracker.StateReplicate || !pr.Inflights.Full() {
ents, err = r.raftLog.entries(pr.Next, r.maxMsgSize)
}
// 若没有实际的entries,且不发送同步commitIndex的空消息,则不发送消息
if len(ents) == 0 && !sendIfEmpty {
return false
}
// TODO(pav-kv): move this check up to where err is returned.
if err != nil { // send a snapshot if we failed to get the entries
return r.maybeSendSnapshot(to, pr)
}
// Send the actual MsgApp otherwise, and update the progress accordingly.
r.send(pb.Message{
To: to,
Type: pb.MsgApp,
Index: prevIndex,
LogTerm: prevTerm,
Entries: ents,
Commit: r.raftLog.committed,
})
// 更新目标follower对应progress对象的状态
pr.UpdateOnEntriesSend(len(ents), uint64(payloadsSize(ents)))
return true
}
// maybeSendSnapshot fetches a snapshot from Storage, and sends it to the given
// node. Returns true iff the snapshot message has been emitted successfully.
// maybeSendSnapshot从Storage中获取快照,并将其发送到给定的节点。如果成功发送了快照消息,则返回true。
func (r *raft) maybeSendSnapshot(to uint64, pr *tracker.Progress) bool {
if !pr.RecentActive {
// 目标follower不是最近活跃的,不发送快照
r.logger.Debugf("ignore sending snapshot to %x since it is not recently active", to)
return false
}
snapshot, err := r.raftLog.snapshot()
if err != nil {
// 快照暂时不可用,需要等待或者重试
if err == ErrSnapshotTemporarilyUnavailable {
r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
return false
}
// 若获取快照失败,且err != ErrSnapshotTemporarilyUnavailable,则直接panic
// TODO:什么情况下会出现这种情况?
panic(err) // TODO(bdarnell)
}
if IsEmptySnap(snapshot) {
// 若快照为空,则直接panic
panic("need non-empty snapshot")
}
sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
r.id, r.raftLog.firstIndex(), r.raftLog.committed, sindex, sterm, to, pr)
pr.BecomeSnapshot(sindex)
r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
r.send(pb.Message{To: to, Type: pb.MsgSnap, Snapshot: &snapshot})
return true
}
// sendHeartbeat sends a heartbeat RPC to the given peer.
func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
// 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.
// 将commit作为min(to.matched, r.committed)附加。
// 当leader发送心跳消息时,接收者(follower)可能与leader不匹配,或者可能没有所有已提交的条目。
// leader禁止发送大于follower的matchIndex的commitIndex
commit := min(r.trk.Progress[to].Match, r.raftLog.committed)
m := pb.Message{
To: to,
Type: pb.MsgHeartbeat,
Commit: commit,
Context: ctx,
}
r.send(m)
}
// bcastAppend sends RPC, with entries to all peers that are not up-to-date
// according to the progress recorded in r.trk.
func (r *raft) bcastAppend() {
r.trk.Visit(func(id uint64, _ *tracker.Progress) {
if id == r.id {
return
}
r.sendAppend(id)
})
}
// bcastHeartbeat sends RPC, without entries to all the peers.
// bcastHeartbeat向所有对等节点发送RPC,不包含任何entries,
func (r *raft) bcastHeartbeat() {
lastCtx := r.readOnly.lastPendingRequestCtx()
if len(lastCtx) == 0 {
r.bcastHeartbeatWithCtx(nil)
} else { // 若存在,携带最后一个readIndex请求的ctx
r.bcastHeartbeatWithCtx([]byte(lastCtx))
}
}
func (r *raft) bcastHeartbeatWithCtx(ctx []byte) {
r.trk.Visit(func(id uint64, _ *tracker.Progress) {
if id == r.id {
return
}
r.sendHeartbeat(id, ctx)
})
}
func (r *raft) appliedTo(index uint64, size entryEncodingSize) {
oldApplied := r.raftLog.applied
newApplied := max(index, oldApplied)
r.raftLog.appliedTo(newApplied, size)
// 若当前节点是Leader,且设置了AutoLeave选项,且新应用的索引大于等于r.pendingConfIndex
// raft节点的pendingConfIndex是在配置变更时设置的,当新应用的索引大于等于r.pendingConfIndex时,可以自动离开联合配置
if r.trk.Config.AutoLeave && newApplied >= r.pendingConfIndex && r.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).
//
m, err := confChangeToMsg(nil)
if err != nil {
panic(err)
}
// 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.
if err := r.Step(m); err != nil {
r.logger.Debugf("not initiating automatic transition out of joint configuration %s: %v", r.trk.Config, err)
} else {
r.logger.Infof("initiating automatic transition out of joint configuration %s", r.trk.Config)
}
}
}
func (r *raft) appliedSnap(snap *pb.Snapshot) {
index := snap.Metadata.Index
r.raftLog.stableSnapTo(index)
r.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). This can
// only be called in StateLeader.
// maybeCommit尝试推进commitIndex。
// 如果commitIndex更改,则返回true(在这种情况下,调用者应调用r.bcastAppend)。这只能在StateLeader中调用。
// 很显然commitIndex后马上调用r.bcastAppend,是为了让其他节点也能及时更新自己的commitIndex
func (r *raft) maybeCommit() bool {
return r.raftLog.maybeCommit(entryID{term: r.Term, index: r.trk.Committed()})
}
func (r *raft) reset(term uint64) {
if r.Term != term {
r.Term = term
r.Vote = None
}
r.lead = None
r.electionElapsed = 0
r.heartbeatElapsed = 0
r.resetRandomizedElectionTimeout()
r.abortLeaderTransfer()
r.trk.ResetVotes()
r.trk.Visit(func(id uint64, pr *tracker.Progress) {
*pr = tracker.Progress{
Match: 0,
Next: r.raftLog.lastIndex() + 1,
Inflights: tracker.NewInflights(r.trk.MaxInflight, r.trk.MaxInflightBytes),
IsLearner: pr.IsLearner,
}
if id == r.id {
pr.Match = r.raftLog.lastIndex()
}
})
r.pendingConfIndex = 0
r.uncommittedSize = 0
r.readOnly = newReadOnly(r.readOnly.option)
}
func (r *raft) appendEntry(es ...pb.Entry) (accepted bool) {
li := r.raftLog.lastIndex()
for i := range es {
es[i].Term = r.Term
es[i].Index = li + 1 + uint64(i)
}
// Track the size of this uncommitted proposal.
// 跟踪此未提交的提案的大小。
if !r.increaseUncommittedSize(es) {
r.logger.Warningf(
"%x appending new entries to log would exceed uncommitted entry size limit; dropping proposal",
r.id,
)
// Drop the proposal.
return false
}
// use latest "last" index after truncate/append
// 在截断/附加后使用最新的“last”索引
li = r.raftLog.append(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:
// 一旦这些刚刚追加的日志条目被持久化(因为leader不会给自己发送MsgApp),leader需要自我确认这些条目。
// 这个响应消息将被添加到msgsAfterAppend中,并在这些条目被写入稳定存储后传递回这个节点。
// 当处理时,这大致相当于:
//
// r.trk.Progress[r.id].MaybeUpdate(e.Index)
// if r.maybeCommit() {
// r.bcastAppend()
// }
r.send(pb.Message{To: r.id, Type: pb.MsgAppResp, Index: li})
return true
}
// Leader和followers/candidates的具体tick行为是不同的:
// Leader:leader调用的是tickHeartbeat
// followers/candidates:调用的是tickElection
// tickElection is run by followers and candidates after r.electionTimeout.
// tickElection在r.electionTimeout之后由follower和candidate运行。
func (r *raft) tickElection() {
r.electionElapsed++
if r.promotable() && r.pastElectionTimeout() {
r.electionElapsed = 0
if err := r.Step(pb.Message{From: r.id, Type: pb.MsgHup}); err != nil {
r.logger.Debugf("error occurred during election: %v", err)
}
}
}
// tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
// tickHeartbeat由leader运行,以在r.heartbeatTimeout之后发送MsgBeat。
func (r *raft) tickHeartbeat() {
r.heartbeatElapsed++
r.electionElapsed++