raft.go 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package raft
  15. import (
  16. "bytes"
  17. "errors"
  18. "fmt"
  19. "math"
  20. "math/rand"
  21. "sort"
  22. "strings"
  23. "sync"
  24. "time"
  25. pb "go.etcd.io/etcd/raft/raftpb"
  26. )
  27. // None is a placeholder node ID used when there is no leader.
  28. const None uint64 = 0
  29. const noLimit = math.MaxUint64
  30. // Possible values for StateType.
  31. const (
  32. StateFollower StateType = iota
  33. StateCandidate
  34. StateLeader
  35. StatePreCandidate
  36. numStates
  37. )
  38. type ReadOnlyOption int
  39. const (
  40. // ReadOnlySafe guarantees the linearizability of the read only request by
  41. // communicating with the quorum. It is the default and suggested option.
  42. ReadOnlySafe ReadOnlyOption = iota
  43. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  44. // relying on the leader lease. It can be affected by clock drift.
  45. // If the clock drift is unbounded, leader might keep the lease longer than it
  46. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  47. // in that case.
  48. ReadOnlyLeaseBased
  49. )
  50. // Possible values for CampaignType
  51. const (
  52. // campaignPreElection represents the first phase of a normal election when
  53. // Config.PreVote is true.
  54. campaignPreElection CampaignType = "CampaignPreElection"
  55. // campaignElection represents a normal (time-based) election (the second phase
  56. // of the election when Config.PreVote is true).
  57. campaignElection CampaignType = "CampaignElection"
  58. // campaignTransfer represents the type of leader transfer
  59. campaignTransfer CampaignType = "CampaignTransfer"
  60. )
  61. // ErrProposalDropped is returned when the proposal is ignored by some cases,
  62. // so that the proposer can be notified and fail fast.
  63. var ErrProposalDropped = errors.New("raft proposal dropped")
  64. // lockedRand is a small wrapper around rand.Rand to provide
  65. // synchronization among multiple raft groups. Only the methods needed
  66. // by the code are exposed (e.g. Intn).
  67. type lockedRand struct {
  68. mu sync.Mutex
  69. rand *rand.Rand
  70. }
  71. func (r *lockedRand) Intn(n int) int {
  72. r.mu.Lock()
  73. v := r.rand.Intn(n)
  74. r.mu.Unlock()
  75. return v
  76. }
  77. var globalRand = &lockedRand{
  78. rand: rand.New(rand.NewSource(time.Now().UnixNano())),
  79. }
  80. // CampaignType represents the type of campaigning
  81. // the reason we use the type of string instead of uint64
  82. // is because it's simpler to compare and fill in raft entries
  83. type CampaignType string
  84. // StateType represents the role of a node in a cluster.
  85. type StateType uint64
  86. var stmap = [...]string{
  87. "StateFollower",
  88. "StateCandidate",
  89. "StateLeader",
  90. "StatePreCandidate",
  91. }
  92. func (st StateType) String() string {
  93. return stmap[uint64(st)]
  94. }
  95. // Config contains the parameters to start a raft.
  96. type Config struct {
  97. // ID is the identity of the local raft. ID cannot be 0.
  98. ID uint64
  99. // peers contains the IDs of all nodes (including self) in the raft cluster. It
  100. // should only be set when starting a new raft cluster. Restarting raft from
  101. // previous configuration will panic if peers is set. peer is private and only
  102. // used for testing right now.
  103. peers []uint64
  104. // learners contains the IDs of all learner nodes (including self if the
  105. // local node is a learner) in the raft cluster. learners only receives
  106. // entries from the leader node. It does not vote or promote itself.
  107. learners []uint64
  108. // ElectionTick is the number of Node.Tick invocations that must pass between
  109. // elections. That is, if a follower does not receive any message from the
  110. // leader of current term before ElectionTick has elapsed, it will become
  111. // candidate and start an election. ElectionTick must be greater than
  112. // HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
  113. // unnecessary leader switching.
  114. ElectionTick int
  115. // HeartbeatTick is the number of Node.Tick invocations that must pass between
  116. // heartbeats. That is, a leader sends heartbeat messages to maintain its
  117. // leadership every HeartbeatTick ticks.
  118. HeartbeatTick int
  119. // Storage is the storage for raft. raft generates entries and states to be
  120. // stored in storage. raft reads the persisted entries and states out of
  121. // Storage when it needs. raft reads out the previous state and configuration
  122. // out of storage when restarting.
  123. Storage Storage
  124. // Applied is the last applied index. It should only be set when restarting
  125. // raft. raft will not return entries to the application smaller or equal to
  126. // Applied. If Applied is unset when restarting, raft might return previous
  127. // applied entries. This is a very application dependent configuration.
  128. Applied uint64
  129. // MaxSizePerMsg limits the max size of each append message. Smaller value
  130. // lowers the raft recovery cost(initial probing and message lost during normal
  131. // operation). On the other side, it might affect the throughput during normal
  132. // replication. Note: math.MaxUint64 for unlimited, 0 for at most one entry per
  133. // message.
  134. MaxSizePerMsg uint64
  135. // MaxInflightMsgs limits the max number of in-flight append messages during
  136. // optimistic replication phase. The application transportation layer usually
  137. // has its own sending buffer over TCP/UDP. Setting MaxInflightMsgs to avoid
  138. // overflowing that sending buffer. TODO (xiangli): feedback to application to
  139. // limit the proposal rate?
  140. MaxInflightMsgs int
  141. // CheckQuorum specifies if the leader should check quorum activity. Leader
  142. // steps down when quorum is not active for an electionTimeout.
  143. CheckQuorum bool
  144. // PreVote enables the Pre-Vote algorithm described in raft thesis section
  145. // 9.6. This prevents disruption when a node that has been partitioned away
  146. // rejoins the cluster.
  147. PreVote bool
  148. // ReadOnlyOption specifies how the read only request is processed.
  149. //
  150. // ReadOnlySafe guarantees the linearizability of the read only request by
  151. // communicating with the quorum. It is the default and suggested option.
  152. //
  153. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  154. // relying on the leader lease. It can be affected by clock drift.
  155. // If the clock drift is unbounded, leader might keep the lease longer than it
  156. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  157. // in that case.
  158. // CheckQuorum MUST be enabled if ReadOnlyOption is ReadOnlyLeaseBased.
  159. ReadOnlyOption ReadOnlyOption
  160. // Logger is the logger used for raft log. For multinode which can host
  161. // multiple raft group, each raft group can have its own logger
  162. Logger Logger
  163. // DisableProposalForwarding set to true means that followers will drop
  164. // proposals, rather than forwarding them to the leader. One use case for
  165. // this feature would be in a situation where the Raft leader is used to
  166. // compute the data of a proposal, for example, adding a timestamp from a
  167. // hybrid logical clock to data in a monotonically increasing way. Forwarding
  168. // should be disabled to prevent a follower with an inaccurate hybrid
  169. // logical clock from assigning the timestamp and then forwarding the data
  170. // to the leader.
  171. DisableProposalForwarding bool
  172. }
  173. func (c *Config) validate() error {
  174. if c.ID == None {
  175. return errors.New("cannot use none as id")
  176. }
  177. if c.HeartbeatTick <= 0 {
  178. return errors.New("heartbeat tick must be greater than 0")
  179. }
  180. if c.ElectionTick <= c.HeartbeatTick {
  181. return errors.New("election tick must be greater than heartbeat tick")
  182. }
  183. if c.Storage == nil {
  184. return errors.New("storage cannot be nil")
  185. }
  186. if c.MaxInflightMsgs <= 0 {
  187. return errors.New("max inflight messages must be greater than 0")
  188. }
  189. if c.Logger == nil {
  190. c.Logger = raftLogger
  191. }
  192. if c.ReadOnlyOption == ReadOnlyLeaseBased && !c.CheckQuorum {
  193. return errors.New("CheckQuorum must be enabled when ReadOnlyOption is ReadOnlyLeaseBased")
  194. }
  195. return nil
  196. }
  197. type raft struct {
  198. id uint64
  199. Term uint64
  200. Vote uint64
  201. readStates []ReadState
  202. // the log
  203. raftLog *raftLog
  204. maxInflight int
  205. maxMsgSize uint64
  206. prs map[uint64]*Progress
  207. learnerPrs map[uint64]*Progress
  208. matchBuf uint64Slice
  209. state StateType
  210. // isLearner is true if the local raft node is a learner.
  211. isLearner bool
  212. votes map[uint64]bool
  213. msgs []pb.Message
  214. // the leader id
  215. lead uint64
  216. // leadTransferee is id of the leader transfer target when its value is not zero.
  217. // Follow the procedure defined in raft thesis 3.10.
  218. leadTransferee uint64
  219. // Only one conf change may be pending (in the log, but not yet
  220. // applied) at a time. This is enforced via pendingConfIndex, which
  221. // is set to a value >= the log index of the latest pending
  222. // configuration change (if any). Config changes are only allowed to
  223. // be proposed if the leader's applied index is greater than this
  224. // value.
  225. pendingConfIndex uint64
  226. readOnly *readOnly
  227. // number of ticks since it reached last electionTimeout when it is leader
  228. // or candidate.
  229. // number of ticks since it reached last electionTimeout or received a
  230. // valid message from current leader when it is a follower.
  231. electionElapsed int
  232. // number of ticks since it reached last heartbeatTimeout.
  233. // only leader keeps heartbeatElapsed.
  234. heartbeatElapsed int
  235. checkQuorum bool
  236. preVote bool
  237. heartbeatTimeout int
  238. electionTimeout int
  239. // randomizedElectionTimeout is a random number between
  240. // [electiontimeout, 2 * electiontimeout - 1]. It gets reset
  241. // when raft changes its state to follower or candidate.
  242. randomizedElectionTimeout int
  243. disableProposalForwarding bool
  244. tick func()
  245. step stepFunc
  246. logger Logger
  247. }
  248. func newRaft(c *Config) *raft {
  249. if err := c.validate(); err != nil {
  250. panic(err.Error())
  251. }
  252. raftlog := newLogWithSize(c.Storage, c.Logger, c.MaxSizePerMsg)
  253. hs, cs, err := c.Storage.InitialState()
  254. if err != nil {
  255. panic(err) // TODO(bdarnell)
  256. }
  257. peers := c.peers
  258. learners := c.learners
  259. if len(cs.Nodes) > 0 || len(cs.Learners) > 0 {
  260. if len(peers) > 0 || len(learners) > 0 {
  261. // TODO(bdarnell): the peers argument is always nil except in
  262. // tests; the argument should be removed and these tests should be
  263. // updated to specify their nodes through a snapshot.
  264. panic("cannot specify both newRaft(peers, learners) and ConfState.(Nodes, Learners)")
  265. }
  266. peers = cs.Nodes
  267. learners = cs.Learners
  268. }
  269. r := &raft{
  270. id: c.ID,
  271. lead: None,
  272. isLearner: false,
  273. raftLog: raftlog,
  274. maxMsgSize: c.MaxSizePerMsg,
  275. maxInflight: c.MaxInflightMsgs,
  276. prs: make(map[uint64]*Progress),
  277. learnerPrs: make(map[uint64]*Progress),
  278. electionTimeout: c.ElectionTick,
  279. heartbeatTimeout: c.HeartbeatTick,
  280. logger: c.Logger,
  281. checkQuorum: c.CheckQuorum,
  282. preVote: c.PreVote,
  283. readOnly: newReadOnly(c.ReadOnlyOption),
  284. disableProposalForwarding: c.DisableProposalForwarding,
  285. }
  286. for _, p := range peers {
  287. r.prs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight)}
  288. }
  289. for _, p := range learners {
  290. if _, ok := r.prs[p]; ok {
  291. panic(fmt.Sprintf("node %x is in both learner and peer list", p))
  292. }
  293. r.learnerPrs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight), IsLearner: true}
  294. if r.id == p {
  295. r.isLearner = true
  296. }
  297. }
  298. if !isHardStateEqual(hs, emptyState) {
  299. r.loadState(hs)
  300. }
  301. if c.Applied > 0 {
  302. raftlog.appliedTo(c.Applied)
  303. }
  304. r.becomeFollower(r.Term, None)
  305. var nodesStrs []string
  306. for _, n := range r.nodes() {
  307. nodesStrs = append(nodesStrs, fmt.Sprintf("%x", n))
  308. }
  309. r.logger.Infof("newRaft %x [peers: [%s], term: %d, commit: %d, applied: %d, lastindex: %d, lastterm: %d]",
  310. r.id, strings.Join(nodesStrs, ","), r.Term, r.raftLog.committed, r.raftLog.applied, r.raftLog.lastIndex(), r.raftLog.lastTerm())
  311. return r
  312. }
  313. func (r *raft) hasLeader() bool { return r.lead != None }
  314. func (r *raft) softState() *SoftState { return &SoftState{Lead: r.lead, RaftState: r.state} }
  315. func (r *raft) hardState() pb.HardState {
  316. return pb.HardState{
  317. Term: r.Term,
  318. Vote: r.Vote,
  319. Commit: r.raftLog.committed,
  320. }
  321. }
  322. func (r *raft) quorum() int { return len(r.prs)/2 + 1 }
  323. func (r *raft) nodes() []uint64 {
  324. nodes := make([]uint64, 0, len(r.prs))
  325. for id := range r.prs {
  326. nodes = append(nodes, id)
  327. }
  328. sort.Sort(uint64Slice(nodes))
  329. return nodes
  330. }
  331. func (r *raft) learnerNodes() []uint64 {
  332. nodes := make([]uint64, 0, len(r.learnerPrs))
  333. for id := range r.learnerPrs {
  334. nodes = append(nodes, id)
  335. }
  336. sort.Sort(uint64Slice(nodes))
  337. return nodes
  338. }
  339. // send persists state to stable storage and then sends to its mailbox.
  340. func (r *raft) send(m pb.Message) {
  341. m.From = r.id
  342. if m.Type == pb.MsgVote || m.Type == pb.MsgVoteResp || m.Type == pb.MsgPreVote || m.Type == pb.MsgPreVoteResp {
  343. if m.Term == 0 {
  344. // All {pre-,}campaign messages need to have the term set when
  345. // sending.
  346. // - MsgVote: m.Term is the term the node is campaigning for,
  347. // non-zero as we increment the term when campaigning.
  348. // - MsgVoteResp: m.Term is the new r.Term if the MsgVote was
  349. // granted, non-zero for the same reason MsgVote is
  350. // - MsgPreVote: m.Term is the term the node will campaign,
  351. // non-zero as we use m.Term to indicate the next term we'll be
  352. // campaigning for
  353. // - MsgPreVoteResp: m.Term is the term received in the original
  354. // MsgPreVote if the pre-vote was granted, non-zero for the
  355. // same reasons MsgPreVote is
  356. panic(fmt.Sprintf("term should be set when sending %s", m.Type))
  357. }
  358. } else {
  359. if m.Term != 0 {
  360. panic(fmt.Sprintf("term should not be set when sending %s (was %d)", m.Type, m.Term))
  361. }
  362. // do not attach term to MsgProp, MsgReadIndex
  363. // proposals are a way to forward to the leader and
  364. // should be treated as local message.
  365. // MsgReadIndex is also forwarded to leader.
  366. if m.Type != pb.MsgProp && m.Type != pb.MsgReadIndex {
  367. m.Term = r.Term
  368. }
  369. }
  370. r.msgs = append(r.msgs, m)
  371. }
  372. func (r *raft) getProgress(id uint64) *Progress {
  373. if pr, ok := r.prs[id]; ok {
  374. return pr
  375. }
  376. return r.learnerPrs[id]
  377. }
  378. // sendAppend sends an append RPC with new entries (if any) and the
  379. // current commit index to the given peer.
  380. func (r *raft) sendAppend(to uint64) {
  381. r.maybeSendAppend(to, true)
  382. }
  383. // maybeSendAppend sends an append RPC with new entries to the given peer,
  384. // if necessary. Returns true if a message was sent. The sendIfEmpty
  385. // argument controls whether messages with no entries will be sent
  386. // ("empty" messages are useful to convey updated Commit indexes, but
  387. // are undesirable when we're sending multiple messages in a batch).
  388. func (r *raft) maybeSendAppend(to uint64, sendIfEmpty bool) bool {
  389. pr := r.getProgress(to)
  390. if pr.IsPaused() {
  391. return false
  392. }
  393. m := pb.Message{}
  394. m.To = to
  395. term, errt := r.raftLog.term(pr.Next - 1)
  396. ents, erre := r.raftLog.entries(pr.Next, r.maxMsgSize)
  397. if len(ents) == 0 && !sendIfEmpty {
  398. return false
  399. }
  400. if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
  401. if !pr.RecentActive {
  402. r.logger.Debugf("ignore sending snapshot to %x since it is not recently active", to)
  403. return false
  404. }
  405. m.Type = pb.MsgSnap
  406. snapshot, err := r.raftLog.snapshot()
  407. if err != nil {
  408. if err == ErrSnapshotTemporarilyUnavailable {
  409. r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
  410. return false
  411. }
  412. panic(err) // TODO(bdarnell)
  413. }
  414. if IsEmptySnap(snapshot) {
  415. panic("need non-empty snapshot")
  416. }
  417. m.Snapshot = snapshot
  418. sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
  419. r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
  420. r.id, r.raftLog.firstIndex(), r.raftLog.committed, sindex, sterm, to, pr)
  421. pr.becomeSnapshot(sindex)
  422. r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
  423. } else {
  424. m.Type = pb.MsgApp
  425. m.Index = pr.Next - 1
  426. m.LogTerm = term
  427. m.Entries = ents
  428. m.Commit = r.raftLog.committed
  429. if n := len(m.Entries); n != 0 {
  430. switch pr.State {
  431. // optimistically increase the next when in ProgressStateReplicate
  432. case ProgressStateReplicate:
  433. last := m.Entries[n-1].Index
  434. pr.optimisticUpdate(last)
  435. pr.ins.add(last)
  436. case ProgressStateProbe:
  437. pr.pause()
  438. default:
  439. r.logger.Panicf("%x is sending append in unhandled state %s", r.id, pr.State)
  440. }
  441. }
  442. }
  443. r.send(m)
  444. return true
  445. }
  446. // sendHeartbeat sends an empty MsgApp
  447. func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
  448. // Attach the commit as min(to.matched, r.committed).
  449. // When the leader sends out heartbeat message,
  450. // the receiver(follower) might not be matched with the leader
  451. // or it might not have all the committed entries.
  452. // The leader MUST NOT forward the follower's commit to
  453. // an unmatched index.
  454. commit := min(r.getProgress(to).Match, r.raftLog.committed)
  455. m := pb.Message{
  456. To: to,
  457. Type: pb.MsgHeartbeat,
  458. Commit: commit,
  459. Context: ctx,
  460. }
  461. r.send(m)
  462. }
  463. func (r *raft) forEachProgress(f func(id uint64, pr *Progress)) {
  464. for id, pr := range r.prs {
  465. f(id, pr)
  466. }
  467. for id, pr := range r.learnerPrs {
  468. f(id, pr)
  469. }
  470. }
  471. // bcastAppend sends RPC, with entries to all peers that are not up-to-date
  472. // according to the progress recorded in r.prs.
  473. func (r *raft) bcastAppend() {
  474. r.forEachProgress(func(id uint64, _ *Progress) {
  475. if id == r.id {
  476. return
  477. }
  478. r.sendAppend(id)
  479. })
  480. }
  481. // bcastHeartbeat sends RPC, without entries to all the peers.
  482. func (r *raft) bcastHeartbeat() {
  483. lastCtx := r.readOnly.lastPendingRequestCtx()
  484. if len(lastCtx) == 0 {
  485. r.bcastHeartbeatWithCtx(nil)
  486. } else {
  487. r.bcastHeartbeatWithCtx([]byte(lastCtx))
  488. }
  489. }
  490. func (r *raft) bcastHeartbeatWithCtx(ctx []byte) {
  491. r.forEachProgress(func(id uint64, _ *Progress) {
  492. if id == r.id {
  493. return
  494. }
  495. r.sendHeartbeat(id, ctx)
  496. })
  497. }
  498. // maybeCommit attempts to advance the commit index. Returns true if
  499. // the commit index changed (in which case the caller should call
  500. // r.bcastAppend).
  501. func (r *raft) maybeCommit() bool {
  502. // Preserving matchBuf across calls is an optimization
  503. // used to avoid allocating a new slice on each call.
  504. if cap(r.matchBuf) < len(r.prs) {
  505. r.matchBuf = make(uint64Slice, len(r.prs))
  506. }
  507. mis := r.matchBuf[:len(r.prs)]
  508. idx := 0
  509. for _, p := range r.prs {
  510. mis[idx] = p.Match
  511. idx++
  512. }
  513. sort.Sort(mis)
  514. mci := mis[len(mis)-r.quorum()]
  515. return r.raftLog.maybeCommit(mci, r.Term)
  516. }
  517. func (r *raft) reset(term uint64) {
  518. if r.Term != term {
  519. r.Term = term
  520. r.Vote = None
  521. }
  522. r.lead = None
  523. r.electionElapsed = 0
  524. r.heartbeatElapsed = 0
  525. r.resetRandomizedElectionTimeout()
  526. r.abortLeaderTransfer()
  527. r.votes = make(map[uint64]bool)
  528. r.forEachProgress(func(id uint64, pr *Progress) {
  529. *pr = Progress{Next: r.raftLog.lastIndex() + 1, ins: newInflights(r.maxInflight), IsLearner: pr.IsLearner}
  530. if id == r.id {
  531. pr.Match = r.raftLog.lastIndex()
  532. }
  533. })
  534. r.pendingConfIndex = 0
  535. r.readOnly = newReadOnly(r.readOnly.option)
  536. }
  537. func (r *raft) appendEntry(es ...pb.Entry) {
  538. li := r.raftLog.lastIndex()
  539. for i := range es {
  540. es[i].Term = r.Term
  541. es[i].Index = li + 1 + uint64(i)
  542. }
  543. // use latest "last" index after truncate/append
  544. li = r.raftLog.append(es...)
  545. r.getProgress(r.id).maybeUpdate(li)
  546. // Regardless of maybeCommit's return, our caller will call bcastAppend.
  547. r.maybeCommit()
  548. }
  549. // tickElection is run by followers and candidates after r.electionTimeout.
  550. func (r *raft) tickElection() {
  551. r.electionElapsed++
  552. if r.promotable() && r.pastElectionTimeout() {
  553. r.electionElapsed = 0
  554. r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
  555. }
  556. }
  557. // tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
  558. func (r *raft) tickHeartbeat() {
  559. r.heartbeatElapsed++
  560. r.electionElapsed++
  561. if r.electionElapsed >= r.electionTimeout {
  562. r.electionElapsed = 0
  563. if r.checkQuorum {
  564. r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
  565. }
  566. // If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
  567. if r.state == StateLeader && r.leadTransferee != None {
  568. r.abortLeaderTransfer()
  569. }
  570. }
  571. if r.state != StateLeader {
  572. return
  573. }
  574. if r.heartbeatElapsed >= r.heartbeatTimeout {
  575. r.heartbeatElapsed = 0
  576. r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
  577. }
  578. }
  579. func (r *raft) becomeFollower(term uint64, lead uint64) {
  580. r.step = stepFollower
  581. r.reset(term)
  582. r.tick = r.tickElection
  583. r.lead = lead
  584. r.state = StateFollower
  585. r.logger.Infof("%x became follower at term %d", r.id, r.Term)
  586. }
  587. func (r *raft) becomeCandidate() {
  588. // TODO(xiangli) remove the panic when the raft implementation is stable
  589. if r.state == StateLeader {
  590. panic("invalid transition [leader -> candidate]")
  591. }
  592. r.step = stepCandidate
  593. r.reset(r.Term + 1)
  594. r.tick = r.tickElection
  595. r.Vote = r.id
  596. r.state = StateCandidate
  597. r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
  598. }
  599. func (r *raft) becomePreCandidate() {
  600. // TODO(xiangli) remove the panic when the raft implementation is stable
  601. if r.state == StateLeader {
  602. panic("invalid transition [leader -> pre-candidate]")
  603. }
  604. // Becoming a pre-candidate changes our step functions and state,
  605. // but doesn't change anything else. In particular it does not increase
  606. // r.Term or change r.Vote.
  607. r.step = stepCandidate
  608. r.votes = make(map[uint64]bool)
  609. r.tick = r.tickElection
  610. r.state = StatePreCandidate
  611. r.logger.Infof("%x became pre-candidate at term %d", r.id, r.Term)
  612. }
  613. func (r *raft) becomeLeader() {
  614. // TODO(xiangli) remove the panic when the raft implementation is stable
  615. if r.state == StateFollower {
  616. panic("invalid transition [follower -> leader]")
  617. }
  618. r.step = stepLeader
  619. r.reset(r.Term)
  620. r.tick = r.tickHeartbeat
  621. r.lead = r.id
  622. r.state = StateLeader
  623. // Conservatively set the pendingConfIndex to the last index in the
  624. // log. There may or may not be a pending config change, but it's
  625. // safe to delay any future proposals until we commit all our
  626. // pending log entries, and scanning the entire tail of the log
  627. // could be expensive.
  628. r.pendingConfIndex = r.raftLog.lastIndex()
  629. r.appendEntry(pb.Entry{Data: nil})
  630. r.logger.Infof("%x became leader at term %d", r.id, r.Term)
  631. }
  632. func (r *raft) campaign(t CampaignType) {
  633. var term uint64
  634. var voteMsg pb.MessageType
  635. if t == campaignPreElection {
  636. r.becomePreCandidate()
  637. voteMsg = pb.MsgPreVote
  638. // PreVote RPCs are sent for the next term before we've incremented r.Term.
  639. term = r.Term + 1
  640. } else {
  641. r.becomeCandidate()
  642. voteMsg = pb.MsgVote
  643. term = r.Term
  644. }
  645. if r.quorum() == r.poll(r.id, voteRespMsgType(voteMsg), true) {
  646. // We won the election after voting for ourselves (which must mean that
  647. // this is a single-node cluster). Advance to the next state.
  648. if t == campaignPreElection {
  649. r.campaign(campaignElection)
  650. } else {
  651. r.becomeLeader()
  652. }
  653. return
  654. }
  655. for id := range r.prs {
  656. if id == r.id {
  657. continue
  658. }
  659. r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
  660. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
  661. var ctx []byte
  662. if t == campaignTransfer {
  663. ctx = []byte(t)
  664. }
  665. r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
  666. }
  667. }
  668. func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int) {
  669. if v {
  670. r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
  671. } else {
  672. r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
  673. }
  674. if _, ok := r.votes[id]; !ok {
  675. r.votes[id] = v
  676. }
  677. for _, vv := range r.votes {
  678. if vv {
  679. granted++
  680. }
  681. }
  682. return granted
  683. }
  684. func (r *raft) Step(m pb.Message) error {
  685. // Handle the message term, which may result in our stepping down to a follower.
  686. switch {
  687. case m.Term == 0:
  688. // local message
  689. case m.Term > r.Term:
  690. if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
  691. force := bytes.Equal(m.Context, []byte(campaignTransfer))
  692. inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
  693. if !force && inLease {
  694. // If a server receives a RequestVote request within the minimum election timeout
  695. // of hearing from a current leader, it does not update its term or grant its vote
  696. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored %s from %x [logterm: %d, index: %d] at term %d: lease is not expired (remaining ticks: %d)",
  697. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
  698. return nil
  699. }
  700. }
  701. switch {
  702. case m.Type == pb.MsgPreVote:
  703. // Never change our term in response to a PreVote
  704. case m.Type == pb.MsgPreVoteResp && !m.Reject:
  705. // We send pre-vote requests with a term in our future. If the
  706. // pre-vote is granted, we will increment our term when we get a
  707. // quorum. If it is not, the term comes from the node that
  708. // rejected our vote so we should become a follower at the new
  709. // term.
  710. default:
  711. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  712. r.id, r.Term, m.Type, m.From, m.Term)
  713. if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap {
  714. r.becomeFollower(m.Term, m.From)
  715. } else {
  716. r.becomeFollower(m.Term, None)
  717. }
  718. }
  719. case m.Term < r.Term:
  720. if (r.checkQuorum || r.preVote) && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
  721. // We have received messages from a leader at a lower term. It is possible
  722. // that these messages were simply delayed in the network, but this could
  723. // also mean that this node has advanced its term number during a network
  724. // partition, and it is now unable to either win an election or to rejoin
  725. // the majority on the old term. If checkQuorum is false, this will be
  726. // handled by incrementing term numbers in response to MsgVote with a
  727. // higher term, but if checkQuorum is true we may not advance the term on
  728. // MsgVote and must generate other messages to advance the term. The net
  729. // result of these two features is to minimize the disruption caused by
  730. // nodes that have been removed from the cluster's configuration: a
  731. // removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
  732. // but it will not receive MsgApp or MsgHeartbeat, so it will not create
  733. // disruptive term increases, by notifying leader of this node's activeness.
  734. // The above comments also true for Pre-Vote
  735. //
  736. // When follower gets isolated, it soon starts an election ending
  737. // up with a higher term than leader, although it won't receive enough
  738. // votes to win the election. When it regains connectivity, this response
  739. // with "pb.MsgAppResp" of higher term would force leader to step down.
  740. // However, this disruption is inevitable to free this stuck node with
  741. // fresh election. This can be prevented with Pre-Vote phase.
  742. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
  743. } else if m.Type == pb.MsgPreVote {
  744. // Before Pre-Vote enable, there may have candidate with higher term,
  745. // but less log. After update to Pre-Vote, the cluster may deadlock if
  746. // we drop messages with a lower term.
  747. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  748. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  749. r.send(pb.Message{To: m.From, Term: r.Term, Type: pb.MsgPreVoteResp, Reject: true})
  750. } else {
  751. // ignore other cases
  752. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  753. r.id, r.Term, m.Type, m.From, m.Term)
  754. }
  755. return nil
  756. }
  757. switch m.Type {
  758. case pb.MsgHup:
  759. if r.state != StateLeader {
  760. ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
  761. if err != nil {
  762. r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
  763. }
  764. if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
  765. r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
  766. return nil
  767. }
  768. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  769. if r.preVote {
  770. r.campaign(campaignPreElection)
  771. } else {
  772. r.campaign(campaignElection)
  773. }
  774. } else {
  775. r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
  776. }
  777. case pb.MsgVote, pb.MsgPreVote:
  778. if r.isLearner {
  779. // TODO: learner may need to vote, in case of node down when confchange.
  780. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored %s from %x [logterm: %d, index: %d] at term %d: learner can not vote",
  781. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  782. return nil
  783. }
  784. // We can vote if this is a repeat of a vote we've already cast...
  785. canVote := r.Vote == m.From ||
  786. // ...we haven't voted and we don't think there's a leader yet in this term...
  787. (r.Vote == None && r.lead == None) ||
  788. // ...or this is a PreVote for a future term...
  789. (m.Type == pb.MsgPreVote && m.Term > r.Term)
  790. // ...and we believe the candidate is up to date.
  791. if canVote && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  792. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
  793. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  794. // When responding to Msg{Pre,}Vote messages we include the term
  795. // from the message, not the local term. To see why consider the
  796. // case where a single node was previously partitioned away and
  797. // it's local term is now of date. If we include the local term
  798. // (recall that for pre-votes we don't update the local term), the
  799. // (pre-)campaigning node on the other end will proceed to ignore
  800. // the message (it ignores all out of date messages).
  801. // The term in the original message and current local term are the
  802. // same in the case of regular votes, but different for pre-votes.
  803. r.send(pb.Message{To: m.From, Term: m.Term, Type: voteRespMsgType(m.Type)})
  804. if m.Type == pb.MsgVote {
  805. // Only record real votes.
  806. r.electionElapsed = 0
  807. r.Vote = m.From
  808. }
  809. } else {
  810. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  811. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  812. r.send(pb.Message{To: m.From, Term: r.Term, Type: voteRespMsgType(m.Type), Reject: true})
  813. }
  814. default:
  815. err := r.step(r, m)
  816. if err != nil {
  817. return err
  818. }
  819. }
  820. return nil
  821. }
  822. type stepFunc func(r *raft, m pb.Message) error
  823. func stepLeader(r *raft, m pb.Message) error {
  824. // These message types do not require any progress for m.From.
  825. switch m.Type {
  826. case pb.MsgBeat:
  827. r.bcastHeartbeat()
  828. return nil
  829. case pb.MsgCheckQuorum:
  830. if !r.checkQuorumActive() {
  831. r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
  832. r.becomeFollower(r.Term, None)
  833. }
  834. return nil
  835. case pb.MsgProp:
  836. if len(m.Entries) == 0 {
  837. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  838. }
  839. if _, ok := r.prs[r.id]; !ok {
  840. // If we are not currently a member of the range (i.e. this node
  841. // was removed from the configuration while serving as leader),
  842. // drop any new proposals.
  843. return ErrProposalDropped
  844. }
  845. if r.leadTransferee != None {
  846. r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
  847. return ErrProposalDropped
  848. }
  849. for i, e := range m.Entries {
  850. if e.Type == pb.EntryConfChange {
  851. if r.pendingConfIndex > r.raftLog.applied {
  852. r.logger.Infof("propose conf %s ignored since pending unapplied configuration [index %d, applied %d]",
  853. e.String(), r.pendingConfIndex, r.raftLog.applied)
  854. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  855. } else {
  856. r.pendingConfIndex = r.raftLog.lastIndex() + uint64(i) + 1
  857. }
  858. }
  859. }
  860. r.appendEntry(m.Entries...)
  861. r.bcastAppend()
  862. return nil
  863. case pb.MsgReadIndex:
  864. if r.quorum() > 1 {
  865. if r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(r.raftLog.committed)) != r.Term {
  866. // Reject read only request when this leader has not committed any log entry at its term.
  867. return nil
  868. }
  869. // thinking: use an interally defined context instead of the user given context.
  870. // We can express this in terms of the term and index instead of a user-supplied value.
  871. // This would allow multiple reads to piggyback on the same message.
  872. switch r.readOnly.option {
  873. case ReadOnlySafe:
  874. r.readOnly.addRequest(r.raftLog.committed, m)
  875. r.bcastHeartbeatWithCtx(m.Entries[0].Data)
  876. case ReadOnlyLeaseBased:
  877. ri := r.raftLog.committed
  878. if m.From == None || m.From == r.id { // from local member
  879. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  880. } else {
  881. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  882. }
  883. }
  884. } else {
  885. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  886. }
  887. return nil
  888. }
  889. // All other message types require a progress for m.From (pr).
  890. pr := r.getProgress(m.From)
  891. if pr == nil {
  892. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  893. return nil
  894. }
  895. switch m.Type {
  896. case pb.MsgAppResp:
  897. pr.RecentActive = true
  898. if m.Reject {
  899. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  900. r.id, m.RejectHint, m.From, m.Index)
  901. if pr.maybeDecrTo(m.Index, m.RejectHint) {
  902. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  903. if pr.State == ProgressStateReplicate {
  904. pr.becomeProbe()
  905. }
  906. r.sendAppend(m.From)
  907. }
  908. } else {
  909. oldPaused := pr.IsPaused()
  910. if pr.maybeUpdate(m.Index) {
  911. switch {
  912. case pr.State == ProgressStateProbe:
  913. pr.becomeReplicate()
  914. case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
  915. r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  916. pr.becomeProbe()
  917. case pr.State == ProgressStateReplicate:
  918. pr.ins.freeTo(m.Index)
  919. }
  920. if r.maybeCommit() {
  921. r.bcastAppend()
  922. } else if oldPaused {
  923. // If we were paused before, this node may be missing the
  924. // latest commit index, so send it.
  925. r.sendAppend(m.From)
  926. }
  927. // We've updated flow control information above, which may
  928. // allow us to send multiple (size-limited) in-flight messages
  929. // at once (such as when transitioning from probe to
  930. // replicate, or when freeTo() covers multiple messages). If
  931. // we have more entries to send, send as many messages as we
  932. // can (without sending empty messages for the commit index)
  933. for r.maybeSendAppend(m.From, false) {
  934. }
  935. // Transfer leadership is in progress.
  936. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  937. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  938. r.sendTimeoutNow(m.From)
  939. }
  940. }
  941. }
  942. case pb.MsgHeartbeatResp:
  943. pr.RecentActive = true
  944. pr.resume()
  945. // free one slot for the full inflights window to allow progress.
  946. if pr.State == ProgressStateReplicate && pr.ins.full() {
  947. pr.ins.freeFirstOne()
  948. }
  949. if pr.Match < r.raftLog.lastIndex() {
  950. r.sendAppend(m.From)
  951. }
  952. if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
  953. return nil
  954. }
  955. ackCount := r.readOnly.recvAck(m)
  956. if ackCount < r.quorum() {
  957. return nil
  958. }
  959. rss := r.readOnly.advance(m)
  960. for _, rs := range rss {
  961. req := rs.req
  962. if req.From == None || req.From == r.id { // from local member
  963. r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
  964. } else {
  965. r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
  966. }
  967. }
  968. case pb.MsgSnapStatus:
  969. if pr.State != ProgressStateSnapshot {
  970. return nil
  971. }
  972. if !m.Reject {
  973. pr.becomeProbe()
  974. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  975. } else {
  976. pr.snapshotFailure()
  977. pr.becomeProbe()
  978. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  979. }
  980. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  981. // out the next msgApp.
  982. // If snapshot failure, wait for a heartbeat interval before next try
  983. pr.pause()
  984. case pb.MsgUnreachable:
  985. // During optimistic replication, if the remote becomes unreachable,
  986. // there is huge probability that a MsgApp is lost.
  987. if pr.State == ProgressStateReplicate {
  988. pr.becomeProbe()
  989. }
  990. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  991. case pb.MsgTransferLeader:
  992. if pr.IsLearner {
  993. r.logger.Debugf("%x is learner. Ignored transferring leadership", r.id)
  994. return nil
  995. }
  996. leadTransferee := m.From
  997. lastLeadTransferee := r.leadTransferee
  998. if lastLeadTransferee != None {
  999. if lastLeadTransferee == leadTransferee {
  1000. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  1001. r.id, r.Term, leadTransferee, leadTransferee)
  1002. return nil
  1003. }
  1004. r.abortLeaderTransfer()
  1005. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  1006. }
  1007. if leadTransferee == r.id {
  1008. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  1009. return nil
  1010. }
  1011. // Transfer leadership to third party.
  1012. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  1013. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  1014. r.electionElapsed = 0
  1015. r.leadTransferee = leadTransferee
  1016. if pr.Match == r.raftLog.lastIndex() {
  1017. r.sendTimeoutNow(leadTransferee)
  1018. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  1019. } else {
  1020. r.sendAppend(leadTransferee)
  1021. }
  1022. }
  1023. return nil
  1024. }
  1025. // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
  1026. // whether they respond to MsgVoteResp or MsgPreVoteResp.
  1027. func stepCandidate(r *raft, m pb.Message) error {
  1028. // Only handle vote responses corresponding to our candidacy (while in
  1029. // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
  1030. // our pre-candidate state).
  1031. var myVoteRespType pb.MessageType
  1032. if r.state == StatePreCandidate {
  1033. myVoteRespType = pb.MsgPreVoteResp
  1034. } else {
  1035. myVoteRespType = pb.MsgVoteResp
  1036. }
  1037. switch m.Type {
  1038. case pb.MsgProp:
  1039. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1040. return ErrProposalDropped
  1041. case pb.MsgApp:
  1042. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1043. r.handleAppendEntries(m)
  1044. case pb.MsgHeartbeat:
  1045. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1046. r.handleHeartbeat(m)
  1047. case pb.MsgSnap:
  1048. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1049. r.handleSnapshot(m)
  1050. case myVoteRespType:
  1051. gr := r.poll(m.From, m.Type, !m.Reject)
  1052. r.logger.Infof("%x [quorum:%d] has received %d %s votes and %d vote rejections", r.id, r.quorum(), gr, m.Type, len(r.votes)-gr)
  1053. switch r.quorum() {
  1054. case gr:
  1055. if r.state == StatePreCandidate {
  1056. r.campaign(campaignElection)
  1057. } else {
  1058. r.becomeLeader()
  1059. r.bcastAppend()
  1060. }
  1061. case len(r.votes) - gr:
  1062. // pb.MsgPreVoteResp contains future term of pre-candidate
  1063. // m.Term > r.Term; reuse r.Term
  1064. r.becomeFollower(r.Term, None)
  1065. }
  1066. case pb.MsgTimeoutNow:
  1067. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  1068. }
  1069. return nil
  1070. }
  1071. func stepFollower(r *raft, m pb.Message) error {
  1072. switch m.Type {
  1073. case pb.MsgProp:
  1074. if r.lead == None {
  1075. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1076. return ErrProposalDropped
  1077. } else if r.disableProposalForwarding {
  1078. r.logger.Infof("%x not forwarding to leader %x at term %d; dropping proposal", r.id, r.lead, r.Term)
  1079. return ErrProposalDropped
  1080. }
  1081. m.To = r.lead
  1082. r.send(m)
  1083. case pb.MsgApp:
  1084. r.electionElapsed = 0
  1085. r.lead = m.From
  1086. r.handleAppendEntries(m)
  1087. case pb.MsgHeartbeat:
  1088. r.electionElapsed = 0
  1089. r.lead = m.From
  1090. r.handleHeartbeat(m)
  1091. case pb.MsgSnap:
  1092. r.electionElapsed = 0
  1093. r.lead = m.From
  1094. r.handleSnapshot(m)
  1095. case pb.MsgTransferLeader:
  1096. if r.lead == None {
  1097. r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
  1098. return nil
  1099. }
  1100. m.To = r.lead
  1101. r.send(m)
  1102. case pb.MsgTimeoutNow:
  1103. if r.promotable() {
  1104. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  1105. // Leadership transfers never use pre-vote even if r.preVote is true; we
  1106. // know we are not recovering from a partition so there is no need for the
  1107. // extra round trip.
  1108. r.campaign(campaignTransfer)
  1109. } else {
  1110. r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
  1111. }
  1112. case pb.MsgReadIndex:
  1113. if r.lead == None {
  1114. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  1115. return nil
  1116. }
  1117. m.To = r.lead
  1118. r.send(m)
  1119. case pb.MsgReadIndexResp:
  1120. if len(m.Entries) != 1 {
  1121. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  1122. return nil
  1123. }
  1124. r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
  1125. }
  1126. return nil
  1127. }
  1128. func (r *raft) handleAppendEntries(m pb.Message) {
  1129. if m.Index < r.raftLog.committed {
  1130. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1131. return
  1132. }
  1133. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  1134. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  1135. } else {
  1136. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  1137. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  1138. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  1139. }
  1140. }
  1141. func (r *raft) handleHeartbeat(m pb.Message) {
  1142. r.raftLog.commitTo(m.Commit)
  1143. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
  1144. }
  1145. func (r *raft) handleSnapshot(m pb.Message) {
  1146. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  1147. if r.restore(m.Snapshot) {
  1148. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  1149. r.id, r.raftLog.committed, sindex, sterm)
  1150. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  1151. } else {
  1152. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  1153. r.id, r.raftLog.committed, sindex, sterm)
  1154. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1155. }
  1156. }
  1157. // restore recovers the state machine from a snapshot. It restores the log and the
  1158. // configuration of state machine.
  1159. func (r *raft) restore(s pb.Snapshot) bool {
  1160. if s.Metadata.Index <= r.raftLog.committed {
  1161. return false
  1162. }
  1163. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  1164. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  1165. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1166. r.raftLog.commitTo(s.Metadata.Index)
  1167. return false
  1168. }
  1169. // The normal peer can't become learner.
  1170. if !r.isLearner {
  1171. for _, id := range s.Metadata.ConfState.Learners {
  1172. if id == r.id {
  1173. r.logger.Errorf("%x can't become learner when restores snapshot [index: %d, term: %d]", r.id, s.Metadata.Index, s.Metadata.Term)
  1174. return false
  1175. }
  1176. }
  1177. }
  1178. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  1179. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1180. r.raftLog.restore(s)
  1181. r.prs = make(map[uint64]*Progress)
  1182. r.learnerPrs = make(map[uint64]*Progress)
  1183. r.restoreNode(s.Metadata.ConfState.Nodes, false)
  1184. r.restoreNode(s.Metadata.ConfState.Learners, true)
  1185. return true
  1186. }
  1187. func (r *raft) restoreNode(nodes []uint64, isLearner bool) {
  1188. for _, n := range nodes {
  1189. match, next := uint64(0), r.raftLog.lastIndex()+1
  1190. if n == r.id {
  1191. match = next - 1
  1192. r.isLearner = isLearner
  1193. }
  1194. r.setProgress(n, match, next, isLearner)
  1195. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.getProgress(n))
  1196. }
  1197. }
  1198. // promotable indicates whether state machine can be promoted to leader,
  1199. // which is true when its own id is in progress list.
  1200. func (r *raft) promotable() bool {
  1201. _, ok := r.prs[r.id]
  1202. return ok
  1203. }
  1204. func (r *raft) addNode(id uint64) {
  1205. r.addNodeOrLearnerNode(id, false)
  1206. }
  1207. func (r *raft) addLearner(id uint64) {
  1208. r.addNodeOrLearnerNode(id, true)
  1209. }
  1210. func (r *raft) addNodeOrLearnerNode(id uint64, isLearner bool) {
  1211. pr := r.getProgress(id)
  1212. if pr == nil {
  1213. r.setProgress(id, 0, r.raftLog.lastIndex()+1, isLearner)
  1214. } else {
  1215. if isLearner && !pr.IsLearner {
  1216. // can only change Learner to Voter
  1217. r.logger.Infof("%x ignored addLearner: do not support changing %x from raft peer to learner.", r.id, id)
  1218. return
  1219. }
  1220. if isLearner == pr.IsLearner {
  1221. // Ignore any redundant addNode calls (which can happen because the
  1222. // initial bootstrapping entries are applied twice).
  1223. return
  1224. }
  1225. // change Learner to Voter, use origin Learner progress
  1226. delete(r.learnerPrs, id)
  1227. pr.IsLearner = false
  1228. r.prs[id] = pr
  1229. }
  1230. if r.id == id {
  1231. r.isLearner = isLearner
  1232. }
  1233. // When a node is first added, we should mark it as recently active.
  1234. // Otherwise, CheckQuorum may cause us to step down if it is invoked
  1235. // before the added node has a chance to communicate with us.
  1236. pr = r.getProgress(id)
  1237. pr.RecentActive = true
  1238. }
  1239. func (r *raft) removeNode(id uint64) {
  1240. r.delProgress(id)
  1241. // do not try to commit or abort transferring if there is no nodes in the cluster.
  1242. if len(r.prs) == 0 && len(r.learnerPrs) == 0 {
  1243. return
  1244. }
  1245. // The quorum size is now smaller, so see if any pending entries can
  1246. // be committed.
  1247. if r.maybeCommit() {
  1248. r.bcastAppend()
  1249. }
  1250. // If the removed node is the leadTransferee, then abort the leadership transferring.
  1251. if r.state == StateLeader && r.leadTransferee == id {
  1252. r.abortLeaderTransfer()
  1253. }
  1254. }
  1255. func (r *raft) setProgress(id, match, next uint64, isLearner bool) {
  1256. if !isLearner {
  1257. delete(r.learnerPrs, id)
  1258. r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
  1259. return
  1260. }
  1261. if _, ok := r.prs[id]; ok {
  1262. panic(fmt.Sprintf("%x unexpected changing from voter to learner for %x", r.id, id))
  1263. }
  1264. r.learnerPrs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight), IsLearner: true}
  1265. }
  1266. func (r *raft) delProgress(id uint64) {
  1267. delete(r.prs, id)
  1268. delete(r.learnerPrs, id)
  1269. }
  1270. func (r *raft) loadState(state pb.HardState) {
  1271. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  1272. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  1273. }
  1274. r.raftLog.committed = state.Commit
  1275. r.Term = state.Term
  1276. r.Vote = state.Vote
  1277. }
  1278. // pastElectionTimeout returns true iff r.electionElapsed is greater
  1279. // than or equal to the randomized election timeout in
  1280. // [electiontimeout, 2 * electiontimeout - 1].
  1281. func (r *raft) pastElectionTimeout() bool {
  1282. return r.electionElapsed >= r.randomizedElectionTimeout
  1283. }
  1284. func (r *raft) resetRandomizedElectionTimeout() {
  1285. r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
  1286. }
  1287. // checkQuorumActive returns true if the quorum is active from
  1288. // the view of the local raft state machine. Otherwise, it returns
  1289. // false.
  1290. // checkQuorumActive also resets all RecentActive to false.
  1291. func (r *raft) checkQuorumActive() bool {
  1292. var act int
  1293. r.forEachProgress(func(id uint64, pr *Progress) {
  1294. if id == r.id { // self is always active
  1295. act++
  1296. return
  1297. }
  1298. if pr.RecentActive && !pr.IsLearner {
  1299. act++
  1300. }
  1301. pr.RecentActive = false
  1302. })
  1303. return act >= r.quorum()
  1304. }
  1305. func (r *raft) sendTimeoutNow(to uint64) {
  1306. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  1307. }
  1308. func (r *raft) abortLeaderTransfer() {
  1309. r.leadTransferee = None
  1310. }
  1311. func numOfPendingConf(ents []pb.Entry) int {
  1312. n := 0
  1313. for i := range ents {
  1314. if ents[i].Type == pb.EntryConfChange {
  1315. n++
  1316. }
  1317. }
  1318. return n
  1319. }