raft.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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 "github.com/coreos/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. // lockedRand is a small wrapper around rand.Rand to provide
  62. // synchronization. Only the methods needed by the code are exposed
  63. // (e.g. Intn).
  64. type lockedRand struct {
  65. mu sync.Mutex
  66. rand *rand.Rand
  67. }
  68. func (r *lockedRand) Intn(n int) int {
  69. r.mu.Lock()
  70. v := r.rand.Intn(n)
  71. r.mu.Unlock()
  72. return v
  73. }
  74. var globalRand = &lockedRand{
  75. rand: rand.New(rand.NewSource(time.Now().UnixNano())),
  76. }
  77. // CampaignType represents the type of campaigning
  78. // the reason we use the type of string instead of uint64
  79. // is because it's simpler to compare and fill in raft entries
  80. type CampaignType string
  81. // StateType represents the role of a node in a cluster.
  82. type StateType uint64
  83. var stmap = [...]string{
  84. "StateFollower",
  85. "StateCandidate",
  86. "StateLeader",
  87. "StatePreCandidate",
  88. }
  89. func (st StateType) String() string {
  90. return stmap[uint64(st)]
  91. }
  92. // Config contains the parameters to start a raft.
  93. type Config struct {
  94. // ID is the identity of the local raft. ID cannot be 0.
  95. ID uint64
  96. // peers contains the IDs of all nodes (including self) in the raft cluster. It
  97. // should only be set when starting a new raft cluster. Restarting raft from
  98. // previous configuration will panic if peers is set. peer is private and only
  99. // used for testing right now.
  100. peers []uint64
  101. // ElectionTick is the number of Node.Tick invocations that must pass between
  102. // elections. That is, if a follower does not receive any message from the
  103. // leader of current term before ElectionTick has elapsed, it will become
  104. // candidate and start an election. ElectionTick must be greater than
  105. // HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
  106. // unnecessary leader switching.
  107. ElectionTick int
  108. // HeartbeatTick is the number of Node.Tick invocations that must pass between
  109. // heartbeats. That is, a leader sends heartbeat messages to maintain its
  110. // leadership every HeartbeatTick ticks.
  111. HeartbeatTick int
  112. // Storage is the storage for raft. raft generates entries and states to be
  113. // stored in storage. raft reads the persisted entries and states out of
  114. // Storage when it needs. raft reads out the previous state and configuration
  115. // out of storage when restarting.
  116. Storage Storage
  117. // Applied is the last applied index. It should only be set when restarting
  118. // raft. raft will not return entries to the application smaller or equal to
  119. // Applied. If Applied is unset when restarting, raft might return previous
  120. // applied entries. This is a very application dependent configuration.
  121. Applied uint64
  122. // MaxSizePerMsg limits the max size of each append message. Smaller value
  123. // lowers the raft recovery cost(initial probing and message lost during normal
  124. // operation). On the other side, it might affect the throughput during normal
  125. // replication. Note: math.MaxUint64 for unlimited, 0 for at most one entry per
  126. // message.
  127. MaxSizePerMsg uint64
  128. // MaxInflightMsgs limits the max number of in-flight append messages during
  129. // optimistic replication phase. The application transportation layer usually
  130. // has its own sending buffer over TCP/UDP. Setting MaxInflightMsgs to avoid
  131. // overflowing that sending buffer. TODO (xiangli): feedback to application to
  132. // limit the proposal rate?
  133. MaxInflightMsgs int
  134. // CheckQuorum specifies if the leader should check quorum activity. Leader
  135. // steps down when quorum is not active for an electionTimeout.
  136. CheckQuorum bool
  137. // PreVote enables the Pre-Vote algorithm described in raft thesis section
  138. // 9.6. This prevents disruption when a node that has been partitioned away
  139. // rejoins the cluster.
  140. PreVote bool
  141. // ReadOnlyOption specifies how the read only request is processed.
  142. //
  143. // ReadOnlySafe guarantees the linearizability of the read only request by
  144. // communicating with the quorum. It is the default and suggested option.
  145. //
  146. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  147. // relying on the leader lease. It can be affected by clock drift.
  148. // If the clock drift is unbounded, leader might keep the lease longer than it
  149. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  150. // in that case.
  151. ReadOnlyOption ReadOnlyOption
  152. // Logger is the logger used for raft log. For multinode which can host
  153. // multiple raft group, each raft group can have its own logger
  154. Logger Logger
  155. }
  156. func (c *Config) validate() error {
  157. if c.ID == None {
  158. return errors.New("cannot use none as id")
  159. }
  160. if c.HeartbeatTick <= 0 {
  161. return errors.New("heartbeat tick must be greater than 0")
  162. }
  163. if c.ElectionTick <= c.HeartbeatTick {
  164. return errors.New("election tick must be greater than heartbeat tick")
  165. }
  166. if c.Storage == nil {
  167. return errors.New("storage cannot be nil")
  168. }
  169. if c.MaxInflightMsgs <= 0 {
  170. return errors.New("max inflight messages must be greater than 0")
  171. }
  172. if c.Logger == nil {
  173. c.Logger = raftLogger
  174. }
  175. return nil
  176. }
  177. type raft struct {
  178. id uint64
  179. Term uint64
  180. Vote uint64
  181. readStates []ReadState
  182. // the log
  183. raftLog *raftLog
  184. maxInflight int
  185. maxMsgSize uint64
  186. prs map[uint64]*Progress
  187. state StateType
  188. votes map[uint64]bool
  189. msgs []pb.Message
  190. // the leader id
  191. lead uint64
  192. // leadTransferee is id of the leader transfer target when its value is not zero.
  193. // Follow the procedure defined in raft thesis 3.10.
  194. leadTransferee uint64
  195. // New configuration is ignored if there exists unapplied configuration.
  196. pendingConf bool
  197. readOnly *readOnly
  198. // number of ticks since it reached last electionTimeout when it is leader
  199. // or candidate.
  200. // number of ticks since it reached last electionTimeout or received a
  201. // valid message from current leader when it is a follower.
  202. electionElapsed int
  203. // number of ticks since it reached last heartbeatTimeout.
  204. // only leader keeps heartbeatElapsed.
  205. heartbeatElapsed int
  206. checkQuorum bool
  207. preVote bool
  208. heartbeatTimeout int
  209. electionTimeout int
  210. // randomizedElectionTimeout is a random number between
  211. // [electiontimeout, 2 * electiontimeout - 1]. It gets reset
  212. // when raft changes its state to follower or candidate.
  213. randomizedElectionTimeout int
  214. tick func()
  215. step stepFunc
  216. logger Logger
  217. }
  218. func newRaft(c *Config) *raft {
  219. if err := c.validate(); err != nil {
  220. panic(err.Error())
  221. }
  222. raftlog := newLog(c.Storage, c.Logger)
  223. hs, cs, err := c.Storage.InitialState()
  224. if err != nil {
  225. panic(err) // TODO(bdarnell)
  226. }
  227. peers := c.peers
  228. if len(cs.Nodes) > 0 {
  229. if len(peers) > 0 {
  230. // TODO(bdarnell): the peers argument is always nil except in
  231. // tests; the argument should be removed and these tests should be
  232. // updated to specify their nodes through a snapshot.
  233. panic("cannot specify both newRaft(peers) and ConfState.Nodes)")
  234. }
  235. peers = cs.Nodes
  236. }
  237. r := &raft{
  238. id: c.ID,
  239. lead: None,
  240. raftLog: raftlog,
  241. maxMsgSize: c.MaxSizePerMsg,
  242. maxInflight: c.MaxInflightMsgs,
  243. prs: make(map[uint64]*Progress),
  244. electionTimeout: c.ElectionTick,
  245. heartbeatTimeout: c.HeartbeatTick,
  246. logger: c.Logger,
  247. checkQuorum: c.CheckQuorum,
  248. preVote: c.PreVote,
  249. readOnly: newReadOnly(c.ReadOnlyOption),
  250. }
  251. for _, p := range peers {
  252. r.prs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight)}
  253. }
  254. if !isHardStateEqual(hs, emptyState) {
  255. r.loadState(hs)
  256. }
  257. if c.Applied > 0 {
  258. raftlog.appliedTo(c.Applied)
  259. }
  260. r.becomeFollower(r.Term, None)
  261. var nodesStrs []string
  262. for _, n := range r.nodes() {
  263. nodesStrs = append(nodesStrs, fmt.Sprintf("%x", n))
  264. }
  265. r.logger.Infof("newRaft %x [peers: [%s], term: %d, commit: %d, applied: %d, lastindex: %d, lastterm: %d]",
  266. r.id, strings.Join(nodesStrs, ","), r.Term, r.raftLog.committed, r.raftLog.applied, r.raftLog.lastIndex(), r.raftLog.lastTerm())
  267. return r
  268. }
  269. func (r *raft) hasLeader() bool { return r.lead != None }
  270. func (r *raft) softState() *SoftState { return &SoftState{Lead: r.lead, RaftState: r.state} }
  271. func (r *raft) hardState() pb.HardState {
  272. return pb.HardState{
  273. Term: r.Term,
  274. Vote: r.Vote,
  275. Commit: r.raftLog.committed,
  276. }
  277. }
  278. func (r *raft) quorum() int { return len(r.prs)/2 + 1 }
  279. func (r *raft) nodes() []uint64 {
  280. nodes := make([]uint64, 0, len(r.prs))
  281. for id := range r.prs {
  282. nodes = append(nodes, id)
  283. }
  284. sort.Sort(uint64Slice(nodes))
  285. return nodes
  286. }
  287. // send persists state to stable storage and then sends to its mailbox.
  288. func (r *raft) send(m pb.Message) {
  289. m.From = r.id
  290. if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
  291. if m.Term == 0 {
  292. // PreVote RPCs are sent at a term other than our actual term, so the code
  293. // that sends these messages is responsible for setting the term.
  294. panic(fmt.Sprintf("term should be set when sending %s", m.Type))
  295. }
  296. } else {
  297. if m.Term != 0 {
  298. panic(fmt.Sprintf("term should not be set when sending %s (was %d)", m.Type, m.Term))
  299. }
  300. // do not attach term to MsgProp, MsgReadIndex
  301. // proposals are a way to forward to the leader and
  302. // should be treated as local message.
  303. // MsgReadIndex is also forwarded to leader.
  304. if m.Type != pb.MsgProp && m.Type != pb.MsgReadIndex {
  305. m.Term = r.Term
  306. }
  307. }
  308. r.msgs = append(r.msgs, m)
  309. }
  310. // sendAppend sends RPC, with entries to the given peer.
  311. func (r *raft) sendAppend(to uint64) {
  312. pr := r.prs[to]
  313. if pr.IsPaused() {
  314. return
  315. }
  316. m := pb.Message{}
  317. m.To = to
  318. term, errt := r.raftLog.term(pr.Next - 1)
  319. ents, erre := r.raftLog.entries(pr.Next, r.maxMsgSize)
  320. if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
  321. if !pr.RecentActive {
  322. r.logger.Debugf("ignore sending snapshot to %x since it is not recently active", to)
  323. return
  324. }
  325. m.Type = pb.MsgSnap
  326. snapshot, err := r.raftLog.snapshot()
  327. if err != nil {
  328. if err == ErrSnapshotTemporarilyUnavailable {
  329. r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
  330. return
  331. }
  332. panic(err) // TODO(bdarnell)
  333. }
  334. if IsEmptySnap(snapshot) {
  335. panic("need non-empty snapshot")
  336. }
  337. m.Snapshot = snapshot
  338. sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
  339. r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
  340. r.id, r.raftLog.firstIndex(), r.raftLog.committed, sindex, sterm, to, pr)
  341. pr.becomeSnapshot(sindex)
  342. r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
  343. } else {
  344. m.Type = pb.MsgApp
  345. m.Index = pr.Next - 1
  346. m.LogTerm = term
  347. m.Entries = ents
  348. m.Commit = r.raftLog.committed
  349. if n := len(m.Entries); n != 0 {
  350. switch pr.State {
  351. // optimistically increase the next when in ProgressStateReplicate
  352. case ProgressStateReplicate:
  353. last := m.Entries[n-1].Index
  354. pr.optimisticUpdate(last)
  355. pr.ins.add(last)
  356. case ProgressStateProbe:
  357. pr.pause()
  358. default:
  359. r.logger.Panicf("%x is sending append in unhandled state %s", r.id, pr.State)
  360. }
  361. }
  362. }
  363. r.send(m)
  364. }
  365. // sendHeartbeat sends an empty MsgApp
  366. func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
  367. // Attach the commit as min(to.matched, r.committed).
  368. // When the leader sends out heartbeat message,
  369. // the receiver(follower) might not be matched with the leader
  370. // or it might not have all the committed entries.
  371. // The leader MUST NOT forward the follower's commit to
  372. // an unmatched index.
  373. commit := min(r.prs[to].Match, r.raftLog.committed)
  374. m := pb.Message{
  375. To: to,
  376. Type: pb.MsgHeartbeat,
  377. Commit: commit,
  378. Context: ctx,
  379. }
  380. r.send(m)
  381. }
  382. // bcastAppend sends RPC, with entries to all peers that are not up-to-date
  383. // according to the progress recorded in r.prs.
  384. func (r *raft) bcastAppend() {
  385. for id := range r.prs {
  386. if id == r.id {
  387. continue
  388. }
  389. r.sendAppend(id)
  390. }
  391. }
  392. // bcastHeartbeat sends RPC, without entries to all the peers.
  393. func (r *raft) bcastHeartbeat() {
  394. lastCtx := r.readOnly.lastPendingRequestCtx()
  395. if len(lastCtx) == 0 {
  396. r.bcastHeartbeatWithCtx(nil)
  397. } else {
  398. r.bcastHeartbeatWithCtx([]byte(lastCtx))
  399. }
  400. }
  401. func (r *raft) bcastHeartbeatWithCtx(ctx []byte) {
  402. for id := range r.prs {
  403. if id == r.id {
  404. continue
  405. }
  406. r.sendHeartbeat(id, ctx)
  407. }
  408. }
  409. // maybeCommit attempts to advance the commit index. Returns true if
  410. // the commit index changed (in which case the caller should call
  411. // r.bcastAppend).
  412. func (r *raft) maybeCommit() bool {
  413. // TODO(bmizerany): optimize.. Currently naive
  414. mis := make(uint64Slice, 0, len(r.prs))
  415. for id := range r.prs {
  416. mis = append(mis, r.prs[id].Match)
  417. }
  418. sort.Sort(sort.Reverse(mis))
  419. mci := mis[r.quorum()-1]
  420. return r.raftLog.maybeCommit(mci, r.Term)
  421. }
  422. func (r *raft) reset(term uint64) {
  423. if r.Term != term {
  424. r.Term = term
  425. r.Vote = None
  426. }
  427. r.lead = None
  428. r.electionElapsed = 0
  429. r.heartbeatElapsed = 0
  430. r.resetRandomizedElectionTimeout()
  431. r.abortLeaderTransfer()
  432. r.votes = make(map[uint64]bool)
  433. for id := range r.prs {
  434. r.prs[id] = &Progress{Next: r.raftLog.lastIndex() + 1, ins: newInflights(r.maxInflight)}
  435. if id == r.id {
  436. r.prs[id].Match = r.raftLog.lastIndex()
  437. }
  438. }
  439. r.pendingConf = false
  440. r.readOnly = newReadOnly(r.readOnly.option)
  441. }
  442. func (r *raft) appendEntry(es ...pb.Entry) {
  443. li := r.raftLog.lastIndex()
  444. for i := range es {
  445. es[i].Term = r.Term
  446. es[i].Index = li + 1 + uint64(i)
  447. }
  448. r.raftLog.append(es...)
  449. r.prs[r.id].maybeUpdate(r.raftLog.lastIndex())
  450. // Regardless of maybeCommit's return, our caller will call bcastAppend.
  451. r.maybeCommit()
  452. }
  453. // tickElection is run by followers and candidates after r.electionTimeout.
  454. func (r *raft) tickElection() {
  455. r.electionElapsed++
  456. if r.promotable() && r.pastElectionTimeout() {
  457. r.electionElapsed = 0
  458. r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
  459. }
  460. }
  461. // tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
  462. func (r *raft) tickHeartbeat() {
  463. r.heartbeatElapsed++
  464. r.electionElapsed++
  465. if r.electionElapsed >= r.electionTimeout {
  466. r.electionElapsed = 0
  467. if r.checkQuorum {
  468. r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
  469. }
  470. // If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
  471. if r.state == StateLeader && r.leadTransferee != None {
  472. r.abortLeaderTransfer()
  473. }
  474. }
  475. if r.state != StateLeader {
  476. return
  477. }
  478. if r.heartbeatElapsed >= r.heartbeatTimeout {
  479. r.heartbeatElapsed = 0
  480. r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
  481. }
  482. }
  483. func (r *raft) becomeFollower(term uint64, lead uint64) {
  484. r.step = stepFollower
  485. r.reset(term)
  486. r.tick = r.tickElection
  487. r.lead = lead
  488. r.state = StateFollower
  489. r.logger.Infof("%x became follower at term %d", r.id, r.Term)
  490. }
  491. func (r *raft) becomeCandidate() {
  492. // TODO(xiangli) remove the panic when the raft implementation is stable
  493. if r.state == StateLeader {
  494. panic("invalid transition [leader -> candidate]")
  495. }
  496. r.step = stepCandidate
  497. r.reset(r.Term + 1)
  498. r.tick = r.tickElection
  499. r.Vote = r.id
  500. r.state = StateCandidate
  501. r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
  502. }
  503. func (r *raft) becomePreCandidate() {
  504. // TODO(xiangli) remove the panic when the raft implementation is stable
  505. if r.state == StateLeader {
  506. panic("invalid transition [leader -> pre-candidate]")
  507. }
  508. // Becoming a pre-candidate changes our step functions and state,
  509. // but doesn't change anything else. In particular it does not increase
  510. // r.Term or change r.Vote.
  511. r.step = stepCandidate
  512. r.tick = r.tickElection
  513. r.state = StatePreCandidate
  514. r.logger.Infof("%x became pre-candidate at term %d", r.id, r.Term)
  515. }
  516. func (r *raft) becomeLeader() {
  517. // TODO(xiangli) remove the panic when the raft implementation is stable
  518. if r.state == StateFollower {
  519. panic("invalid transition [follower -> leader]")
  520. }
  521. r.step = stepLeader
  522. r.reset(r.Term)
  523. r.tick = r.tickHeartbeat
  524. r.lead = r.id
  525. r.state = StateLeader
  526. ents, err := r.raftLog.entries(r.raftLog.committed+1, noLimit)
  527. if err != nil {
  528. r.logger.Panicf("unexpected error getting uncommitted entries (%v)", err)
  529. }
  530. nconf := numOfPendingConf(ents)
  531. if nconf > 1 {
  532. panic("unexpected multiple uncommitted config entry")
  533. }
  534. if nconf == 1 {
  535. r.pendingConf = true
  536. }
  537. r.appendEntry(pb.Entry{Data: nil})
  538. r.logger.Infof("%x became leader at term %d", r.id, r.Term)
  539. }
  540. func (r *raft) campaign(t CampaignType) {
  541. var term uint64
  542. var voteMsg pb.MessageType
  543. if t == campaignPreElection {
  544. r.becomePreCandidate()
  545. voteMsg = pb.MsgPreVote
  546. // PreVote RPCs are sent for the next term before we've incremented r.Term.
  547. term = r.Term + 1
  548. } else {
  549. r.becomeCandidate()
  550. voteMsg = pb.MsgVote
  551. term = r.Term
  552. }
  553. if r.quorum() == r.poll(r.id, voteRespMsgType(voteMsg), true) {
  554. // We won the election after voting for ourselves (which must mean that
  555. // this is a single-node cluster). Advance to the next state.
  556. if t == campaignPreElection {
  557. r.campaign(campaignElection)
  558. } else {
  559. r.becomeLeader()
  560. }
  561. return
  562. }
  563. for id := range r.prs {
  564. if id == r.id {
  565. continue
  566. }
  567. r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
  568. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
  569. var ctx []byte
  570. if t == campaignTransfer {
  571. ctx = []byte(t)
  572. }
  573. r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
  574. }
  575. }
  576. func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int) {
  577. if v {
  578. r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
  579. } else {
  580. r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
  581. }
  582. if _, ok := r.votes[id]; !ok {
  583. r.votes[id] = v
  584. }
  585. for _, vv := range r.votes {
  586. if vv {
  587. granted++
  588. }
  589. }
  590. return granted
  591. }
  592. func (r *raft) Step(m pb.Message) error {
  593. // Handle the message term, which may result in our stepping down to a follower.
  594. switch {
  595. case m.Term == 0:
  596. // local message
  597. case m.Term > r.Term:
  598. lead := m.From
  599. if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
  600. force := bytes.Equal(m.Context, []byte(campaignTransfer))
  601. inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
  602. if !force && inLease {
  603. // If a server receives a RequestVote request within the minimum election timeout
  604. // of hearing from a current leader, it does not update its term or grant its vote
  605. 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)",
  606. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
  607. return nil
  608. }
  609. lead = None
  610. }
  611. switch {
  612. case m.Type == pb.MsgPreVote:
  613. // Never change our term in response to a PreVote
  614. case m.Type == pb.MsgPreVoteResp && !m.Reject:
  615. // We send pre-vote requests with a term in our future. If the
  616. // pre-vote is granted, we will increment our term when we get a
  617. // quorum. If it is not, the term comes from the node that
  618. // rejected our vote so we should become a follower at the new
  619. // term.
  620. default:
  621. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  622. r.id, r.Term, m.Type, m.From, m.Term)
  623. r.becomeFollower(m.Term, lead)
  624. }
  625. case m.Term < r.Term:
  626. if r.checkQuorum && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
  627. // We have received messages from a leader at a lower term. It is possible
  628. // that these messages were simply delayed in the network, but this could
  629. // also mean that this node has advanced its term number during a network
  630. // partition, and it is now unable to either win an election or to rejoin
  631. // the majority on the old term. If checkQuorum is false, this will be
  632. // handled by incrementing term numbers in response to MsgVote with a
  633. // higher term, but if checkQuorum is true we may not advance the term on
  634. // MsgVote and must generate other messages to advance the term. The net
  635. // result of these two features is to minimize the disruption caused by
  636. // nodes that have been removed from the cluster's configuration: a
  637. // removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
  638. // but it will not receive MsgApp or MsgHeartbeat, so it will not create
  639. // disruptive term increases
  640. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
  641. } else {
  642. // ignore other cases
  643. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  644. r.id, r.Term, m.Type, m.From, m.Term)
  645. }
  646. return nil
  647. }
  648. switch m.Type {
  649. case pb.MsgHup:
  650. if r.state != StateLeader {
  651. ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
  652. if err != nil {
  653. r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
  654. }
  655. if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
  656. r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
  657. return nil
  658. }
  659. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  660. if r.preVote {
  661. r.campaign(campaignPreElection)
  662. } else {
  663. r.campaign(campaignElection)
  664. }
  665. } else {
  666. r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
  667. }
  668. case pb.MsgVote, pb.MsgPreVote:
  669. // The m.Term > r.Term clause is for MsgPreVote. For MsgVote m.Term should
  670. // always equal r.Term.
  671. if (r.Vote == None || m.Term > r.Term || r.Vote == m.From) && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  672. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
  673. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  674. r.send(pb.Message{To: m.From, Type: voteRespMsgType(m.Type)})
  675. if m.Type == pb.MsgVote {
  676. // Only record real votes.
  677. r.electionElapsed = 0
  678. r.Vote = m.From
  679. }
  680. } else {
  681. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  682. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  683. r.send(pb.Message{To: m.From, Type: voteRespMsgType(m.Type), Reject: true})
  684. }
  685. default:
  686. r.step(r, m)
  687. }
  688. return nil
  689. }
  690. type stepFunc func(r *raft, m pb.Message)
  691. func stepLeader(r *raft, m pb.Message) {
  692. // These message types do not require any progress for m.From.
  693. switch m.Type {
  694. case pb.MsgBeat:
  695. r.bcastHeartbeat()
  696. return
  697. case pb.MsgCheckQuorum:
  698. if !r.checkQuorumActive() {
  699. r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
  700. r.becomeFollower(r.Term, None)
  701. }
  702. return
  703. case pb.MsgProp:
  704. if len(m.Entries) == 0 {
  705. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  706. }
  707. if _, ok := r.prs[r.id]; !ok {
  708. // If we are not currently a member of the range (i.e. this node
  709. // was removed from the configuration while serving as leader),
  710. // drop any new proposals.
  711. return
  712. }
  713. if r.leadTransferee != None {
  714. r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
  715. return
  716. }
  717. for i, e := range m.Entries {
  718. if e.Type == pb.EntryConfChange {
  719. if r.pendingConf {
  720. r.logger.Infof("propose conf %s ignored since pending unapplied configuration", e.String())
  721. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  722. }
  723. r.pendingConf = true
  724. }
  725. }
  726. r.appendEntry(m.Entries...)
  727. r.bcastAppend()
  728. return
  729. case pb.MsgReadIndex:
  730. if r.quorum() > 1 {
  731. // thinking: use an interally defined context instead of the user given context.
  732. // We can express this in terms of the term and index instead of a user-supplied value.
  733. // This would allow multiple reads to piggyback on the same message.
  734. switch r.readOnly.option {
  735. case ReadOnlySafe:
  736. r.readOnly.addRequest(r.raftLog.committed, m)
  737. r.bcastHeartbeatWithCtx(m.Entries[0].Data)
  738. case ReadOnlyLeaseBased:
  739. var ri uint64
  740. if r.checkQuorum {
  741. ri = r.raftLog.committed
  742. }
  743. if m.From == None || m.From == r.id { // from local member
  744. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  745. } else {
  746. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  747. }
  748. }
  749. } else {
  750. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  751. }
  752. return
  753. }
  754. // All other message types require a progress for m.From (pr).
  755. pr, prOk := r.prs[m.From]
  756. if !prOk {
  757. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  758. return
  759. }
  760. switch m.Type {
  761. case pb.MsgAppResp:
  762. pr.RecentActive = true
  763. if m.Reject {
  764. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  765. r.id, m.RejectHint, m.From, m.Index)
  766. if pr.maybeDecrTo(m.Index, m.RejectHint) {
  767. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  768. if pr.State == ProgressStateReplicate {
  769. pr.becomeProbe()
  770. }
  771. r.sendAppend(m.From)
  772. }
  773. } else {
  774. oldPaused := pr.IsPaused()
  775. if pr.maybeUpdate(m.Index) {
  776. switch {
  777. case pr.State == ProgressStateProbe:
  778. pr.becomeReplicate()
  779. case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
  780. r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  781. pr.becomeProbe()
  782. case pr.State == ProgressStateReplicate:
  783. pr.ins.freeTo(m.Index)
  784. }
  785. if r.maybeCommit() {
  786. r.bcastAppend()
  787. } else if oldPaused {
  788. // update() reset the wait state on this node. If we had delayed sending
  789. // an update before, send it now.
  790. r.sendAppend(m.From)
  791. }
  792. // Transfer leadership is in progress.
  793. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  794. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  795. r.sendTimeoutNow(m.From)
  796. }
  797. }
  798. }
  799. case pb.MsgHeartbeatResp:
  800. pr.RecentActive = true
  801. pr.resume()
  802. // free one slot for the full inflights window to allow progress.
  803. if pr.State == ProgressStateReplicate && pr.ins.full() {
  804. pr.ins.freeFirstOne()
  805. }
  806. if pr.Match < r.raftLog.lastIndex() {
  807. r.sendAppend(m.From)
  808. }
  809. if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
  810. return
  811. }
  812. ackCount := r.readOnly.recvAck(m)
  813. if ackCount < r.quorum() {
  814. return
  815. }
  816. rss := r.readOnly.advance(m)
  817. for _, rs := range rss {
  818. req := rs.req
  819. if req.From == None || req.From == r.id { // from local member
  820. r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
  821. } else {
  822. r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
  823. }
  824. }
  825. case pb.MsgSnapStatus:
  826. if pr.State != ProgressStateSnapshot {
  827. return
  828. }
  829. if !m.Reject {
  830. pr.becomeProbe()
  831. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  832. } else {
  833. pr.snapshotFailure()
  834. pr.becomeProbe()
  835. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  836. }
  837. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  838. // out the next msgApp.
  839. // If snapshot failure, wait for a heartbeat interval before next try
  840. pr.pause()
  841. case pb.MsgUnreachable:
  842. // During optimistic replication, if the remote becomes unreachable,
  843. // there is huge probability that a MsgApp is lost.
  844. if pr.State == ProgressStateReplicate {
  845. pr.becomeProbe()
  846. }
  847. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  848. case pb.MsgTransferLeader:
  849. leadTransferee := m.From
  850. lastLeadTransferee := r.leadTransferee
  851. if lastLeadTransferee != None {
  852. if lastLeadTransferee == leadTransferee {
  853. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  854. r.id, r.Term, leadTransferee, leadTransferee)
  855. return
  856. }
  857. r.abortLeaderTransfer()
  858. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  859. }
  860. if leadTransferee == r.id {
  861. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  862. return
  863. }
  864. // Transfer leadership to third party.
  865. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  866. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  867. r.electionElapsed = 0
  868. r.leadTransferee = leadTransferee
  869. if pr.Match == r.raftLog.lastIndex() {
  870. r.sendTimeoutNow(leadTransferee)
  871. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  872. } else {
  873. r.sendAppend(leadTransferee)
  874. }
  875. }
  876. }
  877. // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
  878. // whether they respond to MsgVoteResp or MsgPreVoteResp.
  879. func stepCandidate(r *raft, m pb.Message) {
  880. // Only handle vote responses corresponding to our candidacy (while in
  881. // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
  882. // our pre-candidate state).
  883. var myVoteRespType pb.MessageType
  884. if r.state == StatePreCandidate {
  885. myVoteRespType = pb.MsgPreVoteResp
  886. } else {
  887. myVoteRespType = pb.MsgVoteResp
  888. }
  889. switch m.Type {
  890. case pb.MsgProp:
  891. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  892. return
  893. case pb.MsgApp:
  894. r.becomeFollower(r.Term, m.From)
  895. r.handleAppendEntries(m)
  896. case pb.MsgHeartbeat:
  897. r.becomeFollower(r.Term, m.From)
  898. r.handleHeartbeat(m)
  899. case pb.MsgSnap:
  900. r.becomeFollower(m.Term, m.From)
  901. r.handleSnapshot(m)
  902. case myVoteRespType:
  903. gr := r.poll(m.From, m.Type, !m.Reject)
  904. 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)
  905. switch r.quorum() {
  906. case gr:
  907. if r.state == StatePreCandidate {
  908. r.campaign(campaignElection)
  909. } else {
  910. r.becomeLeader()
  911. r.bcastAppend()
  912. }
  913. case len(r.votes) - gr:
  914. r.becomeFollower(r.Term, None)
  915. }
  916. case pb.MsgTimeoutNow:
  917. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  918. }
  919. }
  920. func stepFollower(r *raft, m pb.Message) {
  921. switch m.Type {
  922. case pb.MsgProp:
  923. if r.lead == None {
  924. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  925. return
  926. }
  927. m.To = r.lead
  928. r.send(m)
  929. case pb.MsgApp:
  930. r.electionElapsed = 0
  931. r.lead = m.From
  932. r.handleAppendEntries(m)
  933. case pb.MsgHeartbeat:
  934. r.electionElapsed = 0
  935. r.lead = m.From
  936. r.handleHeartbeat(m)
  937. case pb.MsgSnap:
  938. r.electionElapsed = 0
  939. r.lead = m.From
  940. r.handleSnapshot(m)
  941. case pb.MsgTransferLeader:
  942. if r.lead == None {
  943. r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
  944. return
  945. }
  946. m.To = r.lead
  947. r.send(m)
  948. case pb.MsgTimeoutNow:
  949. if r.promotable() {
  950. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  951. // Leadership transfers never use pre-vote even if r.preVote is true; we
  952. // know we are not recovering from a partition so there is no need for the
  953. // extra round trip.
  954. r.campaign(campaignTransfer)
  955. } else {
  956. r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
  957. }
  958. case pb.MsgReadIndex:
  959. if r.lead == None {
  960. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  961. return
  962. }
  963. m.To = r.lead
  964. r.send(m)
  965. case pb.MsgReadIndexResp:
  966. if len(m.Entries) != 1 {
  967. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  968. return
  969. }
  970. r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
  971. }
  972. }
  973. func (r *raft) handleAppendEntries(m pb.Message) {
  974. if m.Index < r.raftLog.committed {
  975. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  976. return
  977. }
  978. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  979. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  980. } else {
  981. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  982. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  983. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  984. }
  985. }
  986. func (r *raft) handleHeartbeat(m pb.Message) {
  987. r.raftLog.commitTo(m.Commit)
  988. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
  989. }
  990. func (r *raft) handleSnapshot(m pb.Message) {
  991. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  992. if r.restore(m.Snapshot) {
  993. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  994. r.id, r.raftLog.committed, sindex, sterm)
  995. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  996. } else {
  997. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  998. r.id, r.raftLog.committed, sindex, sterm)
  999. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1000. }
  1001. }
  1002. // restore recovers the state machine from a snapshot. It restores the log and the
  1003. // configuration of state machine.
  1004. func (r *raft) restore(s pb.Snapshot) bool {
  1005. if s.Metadata.Index <= r.raftLog.committed {
  1006. return false
  1007. }
  1008. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  1009. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  1010. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1011. r.raftLog.commitTo(s.Metadata.Index)
  1012. return false
  1013. }
  1014. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  1015. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1016. r.raftLog.restore(s)
  1017. r.prs = make(map[uint64]*Progress)
  1018. for _, n := range s.Metadata.ConfState.Nodes {
  1019. match, next := uint64(0), r.raftLog.lastIndex()+1
  1020. if n == r.id {
  1021. match = next - 1
  1022. }
  1023. r.setProgress(n, match, next)
  1024. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.prs[n])
  1025. }
  1026. return true
  1027. }
  1028. // promotable indicates whether state machine can be promoted to leader,
  1029. // which is true when its own id is in progress list.
  1030. func (r *raft) promotable() bool {
  1031. _, ok := r.prs[r.id]
  1032. return ok
  1033. }
  1034. func (r *raft) addNode(id uint64) {
  1035. r.pendingConf = false
  1036. if _, ok := r.prs[id]; ok {
  1037. // Ignore any redundant addNode calls (which can happen because the
  1038. // initial bootstrapping entries are applied twice).
  1039. return
  1040. }
  1041. r.setProgress(id, 0, r.raftLog.lastIndex()+1)
  1042. }
  1043. func (r *raft) removeNode(id uint64) {
  1044. r.delProgress(id)
  1045. r.pendingConf = false
  1046. // do not try to commit or abort transferring if there is no nodes in the cluster.
  1047. if len(r.prs) == 0 {
  1048. return
  1049. }
  1050. // The quorum size is now smaller, so see if any pending entries can
  1051. // be committed.
  1052. if r.maybeCommit() {
  1053. r.bcastAppend()
  1054. }
  1055. // If the removed node is the leadTransferee, then abort the leadership transferring.
  1056. if r.state == StateLeader && r.leadTransferee == id {
  1057. r.abortLeaderTransfer()
  1058. }
  1059. }
  1060. func (r *raft) resetPendingConf() { r.pendingConf = false }
  1061. func (r *raft) setProgress(id, match, next uint64) {
  1062. r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
  1063. }
  1064. func (r *raft) delProgress(id uint64) {
  1065. delete(r.prs, id)
  1066. }
  1067. func (r *raft) loadState(state pb.HardState) {
  1068. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  1069. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  1070. }
  1071. r.raftLog.committed = state.Commit
  1072. r.Term = state.Term
  1073. r.Vote = state.Vote
  1074. }
  1075. // pastElectionTimeout returns true iff r.electionElapsed is greater
  1076. // than or equal to the randomized election timeout in
  1077. // [electiontimeout, 2 * electiontimeout - 1].
  1078. func (r *raft) pastElectionTimeout() bool {
  1079. return r.electionElapsed >= r.randomizedElectionTimeout
  1080. }
  1081. func (r *raft) resetRandomizedElectionTimeout() {
  1082. r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
  1083. }
  1084. // checkQuorumActive returns true if the quorum is active from
  1085. // the view of the local raft state machine. Otherwise, it returns
  1086. // false.
  1087. // checkQuorumActive also resets all RecentActive to false.
  1088. func (r *raft) checkQuorumActive() bool {
  1089. var act int
  1090. for id := range r.prs {
  1091. if id == r.id { // self is always active
  1092. act++
  1093. continue
  1094. }
  1095. if r.prs[id].RecentActive {
  1096. act++
  1097. }
  1098. r.prs[id].RecentActive = false
  1099. }
  1100. return act >= r.quorum()
  1101. }
  1102. func (r *raft) sendTimeoutNow(to uint64) {
  1103. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  1104. }
  1105. func (r *raft) abortLeaderTransfer() {
  1106. r.leadTransferee = None
  1107. }
  1108. func numOfPendingConf(ents []pb.Entry) int {
  1109. n := 0
  1110. for i := range ents {
  1111. if ents[i].Type == pb.EntryConfChange {
  1112. n++
  1113. }
  1114. }
  1115. return n
  1116. }