raft.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  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. if r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(r.raftLog.committed)) != r.Term {
  732. // Reject read only request when this leader has not committed any log entry at its term.
  733. return
  734. }
  735. // thinking: use an interally defined context instead of the user given context.
  736. // We can express this in terms of the term and index instead of a user-supplied value.
  737. // This would allow multiple reads to piggyback on the same message.
  738. switch r.readOnly.option {
  739. case ReadOnlySafe:
  740. r.readOnly.addRequest(r.raftLog.committed, m)
  741. r.bcastHeartbeatWithCtx(m.Entries[0].Data)
  742. case ReadOnlyLeaseBased:
  743. var ri uint64
  744. if r.checkQuorum {
  745. ri = r.raftLog.committed
  746. }
  747. if m.From == None || m.From == r.id { // from local member
  748. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  749. } else {
  750. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  751. }
  752. }
  753. } else {
  754. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  755. }
  756. return
  757. }
  758. // All other message types require a progress for m.From (pr).
  759. pr, prOk := r.prs[m.From]
  760. if !prOk {
  761. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  762. return
  763. }
  764. switch m.Type {
  765. case pb.MsgAppResp:
  766. pr.RecentActive = true
  767. if m.Reject {
  768. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  769. r.id, m.RejectHint, m.From, m.Index)
  770. if pr.maybeDecrTo(m.Index, m.RejectHint) {
  771. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  772. if pr.State == ProgressStateReplicate {
  773. pr.becomeProbe()
  774. }
  775. r.sendAppend(m.From)
  776. }
  777. } else {
  778. oldPaused := pr.IsPaused()
  779. if pr.maybeUpdate(m.Index) {
  780. switch {
  781. case pr.State == ProgressStateProbe:
  782. pr.becomeReplicate()
  783. case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
  784. r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  785. pr.becomeProbe()
  786. case pr.State == ProgressStateReplicate:
  787. pr.ins.freeTo(m.Index)
  788. }
  789. if r.maybeCommit() {
  790. r.bcastAppend()
  791. } else if oldPaused {
  792. // update() reset the wait state on this node. If we had delayed sending
  793. // an update before, send it now.
  794. r.sendAppend(m.From)
  795. }
  796. // Transfer leadership is in progress.
  797. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  798. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  799. r.sendTimeoutNow(m.From)
  800. }
  801. }
  802. }
  803. case pb.MsgHeartbeatResp:
  804. pr.RecentActive = true
  805. pr.resume()
  806. // free one slot for the full inflights window to allow progress.
  807. if pr.State == ProgressStateReplicate && pr.ins.full() {
  808. pr.ins.freeFirstOne()
  809. }
  810. if pr.Match < r.raftLog.lastIndex() {
  811. r.sendAppend(m.From)
  812. }
  813. if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
  814. return
  815. }
  816. ackCount := r.readOnly.recvAck(m)
  817. if ackCount < r.quorum() {
  818. return
  819. }
  820. rss := r.readOnly.advance(m)
  821. for _, rs := range rss {
  822. req := rs.req
  823. if req.From == None || req.From == r.id { // from local member
  824. r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
  825. } else {
  826. r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
  827. }
  828. }
  829. case pb.MsgSnapStatus:
  830. if pr.State != ProgressStateSnapshot {
  831. return
  832. }
  833. if !m.Reject {
  834. pr.becomeProbe()
  835. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  836. } else {
  837. pr.snapshotFailure()
  838. pr.becomeProbe()
  839. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  840. }
  841. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  842. // out the next msgApp.
  843. // If snapshot failure, wait for a heartbeat interval before next try
  844. pr.pause()
  845. case pb.MsgUnreachable:
  846. // During optimistic replication, if the remote becomes unreachable,
  847. // there is huge probability that a MsgApp is lost.
  848. if pr.State == ProgressStateReplicate {
  849. pr.becomeProbe()
  850. }
  851. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  852. case pb.MsgTransferLeader:
  853. leadTransferee := m.From
  854. lastLeadTransferee := r.leadTransferee
  855. if lastLeadTransferee != None {
  856. if lastLeadTransferee == leadTransferee {
  857. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  858. r.id, r.Term, leadTransferee, leadTransferee)
  859. return
  860. }
  861. r.abortLeaderTransfer()
  862. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  863. }
  864. if leadTransferee == r.id {
  865. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  866. return
  867. }
  868. // Transfer leadership to third party.
  869. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  870. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  871. r.electionElapsed = 0
  872. r.leadTransferee = leadTransferee
  873. if pr.Match == r.raftLog.lastIndex() {
  874. r.sendTimeoutNow(leadTransferee)
  875. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  876. } else {
  877. r.sendAppend(leadTransferee)
  878. }
  879. }
  880. }
  881. // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
  882. // whether they respond to MsgVoteResp or MsgPreVoteResp.
  883. func stepCandidate(r *raft, m pb.Message) {
  884. // Only handle vote responses corresponding to our candidacy (while in
  885. // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
  886. // our pre-candidate state).
  887. var myVoteRespType pb.MessageType
  888. if r.state == StatePreCandidate {
  889. myVoteRespType = pb.MsgPreVoteResp
  890. } else {
  891. myVoteRespType = pb.MsgVoteResp
  892. }
  893. switch m.Type {
  894. case pb.MsgProp:
  895. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  896. return
  897. case pb.MsgApp:
  898. r.becomeFollower(r.Term, m.From)
  899. r.handleAppendEntries(m)
  900. case pb.MsgHeartbeat:
  901. r.becomeFollower(r.Term, m.From)
  902. r.handleHeartbeat(m)
  903. case pb.MsgSnap:
  904. r.becomeFollower(m.Term, m.From)
  905. r.handleSnapshot(m)
  906. case myVoteRespType:
  907. gr := r.poll(m.From, m.Type, !m.Reject)
  908. 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)
  909. switch r.quorum() {
  910. case gr:
  911. if r.state == StatePreCandidate {
  912. r.campaign(campaignElection)
  913. } else {
  914. r.becomeLeader()
  915. r.bcastAppend()
  916. }
  917. case len(r.votes) - gr:
  918. r.becomeFollower(r.Term, None)
  919. }
  920. case pb.MsgTimeoutNow:
  921. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  922. }
  923. }
  924. func stepFollower(r *raft, m pb.Message) {
  925. switch m.Type {
  926. case pb.MsgProp:
  927. if r.lead == None {
  928. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  929. return
  930. }
  931. m.To = r.lead
  932. r.send(m)
  933. case pb.MsgApp:
  934. r.electionElapsed = 0
  935. r.lead = m.From
  936. r.handleAppendEntries(m)
  937. case pb.MsgHeartbeat:
  938. r.electionElapsed = 0
  939. r.lead = m.From
  940. r.handleHeartbeat(m)
  941. case pb.MsgSnap:
  942. r.electionElapsed = 0
  943. r.lead = m.From
  944. r.handleSnapshot(m)
  945. case pb.MsgTransferLeader:
  946. if r.lead == None {
  947. r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
  948. return
  949. }
  950. m.To = r.lead
  951. r.send(m)
  952. case pb.MsgTimeoutNow:
  953. if r.promotable() {
  954. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  955. // Leadership transfers never use pre-vote even if r.preVote is true; we
  956. // know we are not recovering from a partition so there is no need for the
  957. // extra round trip.
  958. r.campaign(campaignTransfer)
  959. } else {
  960. r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
  961. }
  962. case pb.MsgReadIndex:
  963. if r.lead == None {
  964. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  965. return
  966. }
  967. m.To = r.lead
  968. r.send(m)
  969. case pb.MsgReadIndexResp:
  970. if len(m.Entries) != 1 {
  971. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  972. return
  973. }
  974. r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
  975. }
  976. }
  977. func (r *raft) handleAppendEntries(m pb.Message) {
  978. if m.Index < r.raftLog.committed {
  979. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  980. return
  981. }
  982. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  983. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  984. } else {
  985. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  986. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  987. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  988. }
  989. }
  990. func (r *raft) handleHeartbeat(m pb.Message) {
  991. r.raftLog.commitTo(m.Commit)
  992. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
  993. }
  994. func (r *raft) handleSnapshot(m pb.Message) {
  995. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  996. if r.restore(m.Snapshot) {
  997. r.logger.Infof("%x [commit: %d] restored 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.lastIndex()})
  1000. } else {
  1001. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  1002. r.id, r.raftLog.committed, sindex, sterm)
  1003. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1004. }
  1005. }
  1006. // restore recovers the state machine from a snapshot. It restores the log and the
  1007. // configuration of state machine.
  1008. func (r *raft) restore(s pb.Snapshot) bool {
  1009. if s.Metadata.Index <= r.raftLog.committed {
  1010. return false
  1011. }
  1012. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  1013. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  1014. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1015. r.raftLog.commitTo(s.Metadata.Index)
  1016. return false
  1017. }
  1018. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  1019. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1020. r.raftLog.restore(s)
  1021. r.prs = make(map[uint64]*Progress)
  1022. for _, n := range s.Metadata.ConfState.Nodes {
  1023. match, next := uint64(0), r.raftLog.lastIndex()+1
  1024. if n == r.id {
  1025. match = next - 1
  1026. }
  1027. r.setProgress(n, match, next)
  1028. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.prs[n])
  1029. }
  1030. return true
  1031. }
  1032. // promotable indicates whether state machine can be promoted to leader,
  1033. // which is true when its own id is in progress list.
  1034. func (r *raft) promotable() bool {
  1035. _, ok := r.prs[r.id]
  1036. return ok
  1037. }
  1038. func (r *raft) addNode(id uint64) {
  1039. r.pendingConf = false
  1040. if _, ok := r.prs[id]; ok {
  1041. // Ignore any redundant addNode calls (which can happen because the
  1042. // initial bootstrapping entries are applied twice).
  1043. return
  1044. }
  1045. r.setProgress(id, 0, r.raftLog.lastIndex()+1)
  1046. }
  1047. func (r *raft) removeNode(id uint64) {
  1048. r.delProgress(id)
  1049. r.pendingConf = false
  1050. // do not try to commit or abort transferring if there is no nodes in the cluster.
  1051. if len(r.prs) == 0 {
  1052. return
  1053. }
  1054. // The quorum size is now smaller, so see if any pending entries can
  1055. // be committed.
  1056. if r.maybeCommit() {
  1057. r.bcastAppend()
  1058. }
  1059. // If the removed node is the leadTransferee, then abort the leadership transferring.
  1060. if r.state == StateLeader && r.leadTransferee == id {
  1061. r.abortLeaderTransfer()
  1062. }
  1063. }
  1064. func (r *raft) resetPendingConf() { r.pendingConf = false }
  1065. func (r *raft) setProgress(id, match, next uint64) {
  1066. r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
  1067. }
  1068. func (r *raft) delProgress(id uint64) {
  1069. delete(r.prs, id)
  1070. }
  1071. func (r *raft) loadState(state pb.HardState) {
  1072. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  1073. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  1074. }
  1075. r.raftLog.committed = state.Commit
  1076. r.Term = state.Term
  1077. r.Vote = state.Vote
  1078. }
  1079. // pastElectionTimeout returns true iff r.electionElapsed is greater
  1080. // than or equal to the randomized election timeout in
  1081. // [electiontimeout, 2 * electiontimeout - 1].
  1082. func (r *raft) pastElectionTimeout() bool {
  1083. return r.electionElapsed >= r.randomizedElectionTimeout
  1084. }
  1085. func (r *raft) resetRandomizedElectionTimeout() {
  1086. r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
  1087. }
  1088. // checkQuorumActive returns true if the quorum is active from
  1089. // the view of the local raft state machine. Otherwise, it returns
  1090. // false.
  1091. // checkQuorumActive also resets all RecentActive to false.
  1092. func (r *raft) checkQuorumActive() bool {
  1093. var act int
  1094. for id := range r.prs {
  1095. if id == r.id { // self is always active
  1096. act++
  1097. continue
  1098. }
  1099. if r.prs[id].RecentActive {
  1100. act++
  1101. }
  1102. r.prs[id].RecentActive = false
  1103. }
  1104. return act >= r.quorum()
  1105. }
  1106. func (r *raft) sendTimeoutNow(to uint64) {
  1107. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  1108. }
  1109. func (r *raft) abortLeaderTransfer() {
  1110. r.leadTransferee = None
  1111. }
  1112. func numOfPendingConf(ents []pb.Entry) int {
  1113. n := 0
  1114. for i := range ents {
  1115. if ents[i].Type == pb.EntryConfChange {
  1116. n++
  1117. }
  1118. }
  1119. return n
  1120. }