raft.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. "errors"
  17. "fmt"
  18. "math"
  19. "math/rand"
  20. "sort"
  21. "strings"
  22. pb "github.com/coreos/etcd/raft/raftpb"
  23. )
  24. // None is a placeholder node ID used when there is no leader.
  25. const None uint64 = 0
  26. const noLimit = math.MaxUint64
  27. // Possible values for StateType.
  28. const (
  29. StateFollower StateType = iota
  30. StateCandidate
  31. StateLeader
  32. )
  33. // StateType represents the role of a node in a cluster.
  34. type StateType uint64
  35. var stmap = [...]string{
  36. "StateFollower",
  37. "StateCandidate",
  38. "StateLeader",
  39. }
  40. func (st StateType) String() string {
  41. return stmap[uint64(st)]
  42. }
  43. // Config contains the parameters to start a raft.
  44. type Config struct {
  45. // ID is the identity of the local raft. ID cannot be 0.
  46. ID uint64
  47. // peers contains the IDs of all nodes (including self) in the raft cluster. It
  48. // should only be set when starting a new raft cluster. Restarting raft from
  49. // previous configuration will panic if peers is set. peer is private and only
  50. // used for testing right now.
  51. peers []uint64
  52. // ElectionTick is the number of Node.Tick invocations that must pass between
  53. // elections. That is, if a follower does not receive any message from the
  54. // leader of current term before ElectionTick has elapsed, it will become
  55. // candidate and start an election. ElectionTick must be greater than
  56. // HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
  57. // unnecessary leader switching.
  58. ElectionTick int
  59. // HeartbeatTick is the number of Node.Tick invocations that must pass between
  60. // heartbeats. That is, a leader sends heartbeat messages to maintain its
  61. // leadership every HeartbeatTick ticks.
  62. HeartbeatTick int
  63. // Storage is the storage for raft. raft generates entries and states to be
  64. // stored in storage. raft reads the persisted entries and states out of
  65. // Storage when it needs. raft reads out the previous state and configuration
  66. // out of storage when restarting.
  67. Storage Storage
  68. // Applied is the last applied index. It should only be set when restarting
  69. // raft. raft will not return entries to the application smaller or equal to
  70. // Applied. If Applied is unset when restarting, raft might return previous
  71. // applied entries. This is a very application dependent configuration.
  72. Applied uint64
  73. // MaxSizePerMsg limits the max size of each append message. Smaller value
  74. // lowers the raft recovery cost(initial probing and message lost during normal
  75. // operation). On the other side, it might affect the throughput during normal
  76. // replication. Note: math.MaxUint64 for unlimited, 0 for at most one entry per
  77. // message.
  78. MaxSizePerMsg uint64
  79. // MaxInflightMsgs limits the max number of in-flight append messages during
  80. // optimistic replication phase. The application transportation layer usually
  81. // has its own sending buffer over TCP/UDP. Setting MaxInflightMsgs to avoid
  82. // overflowing that sending buffer. TODO (xiangli): feedback to application to
  83. // limit the proposal rate?
  84. MaxInflightMsgs int
  85. // CheckQuorum specifies if the leader should check quorum activity. Leader
  86. // steps down when quorum is not active for an electionTimeout.
  87. CheckQuorum bool
  88. // Logger is the logger used for raft log. For multinode which can host
  89. // multiple raft group, each raft group can have its own logger
  90. Logger Logger
  91. }
  92. func (c *Config) validate() error {
  93. if c.ID == None {
  94. return errors.New("cannot use none as id")
  95. }
  96. if c.HeartbeatTick <= 0 {
  97. return errors.New("heartbeat tick must be greater than 0")
  98. }
  99. if c.ElectionTick <= c.HeartbeatTick {
  100. return errors.New("election tick must be greater than heartbeat tick")
  101. }
  102. if c.Storage == nil {
  103. return errors.New("storage cannot be nil")
  104. }
  105. if c.MaxInflightMsgs <= 0 {
  106. return errors.New("max inflight messages must be greater than 0")
  107. }
  108. if c.Logger == nil {
  109. c.Logger = raftLogger
  110. }
  111. return nil
  112. }
  113. // ReadState provides state for read only query.
  114. // It's caller's responsibility to send MsgReadIndex first before getting
  115. // this state from ready, It's also caller's duty to differentiate if this
  116. // state is what it requests through RequestCtx, eg. given a unique id as
  117. // RequestCtx
  118. type ReadState struct {
  119. Index uint64
  120. RequestCtx []byte
  121. }
  122. type raft struct {
  123. id uint64
  124. Term uint64
  125. Vote uint64
  126. readState ReadState
  127. // the log
  128. raftLog *raftLog
  129. maxInflight int
  130. maxMsgSize uint64
  131. prs map[uint64]*Progress
  132. state StateType
  133. votes map[uint64]bool
  134. msgs []pb.Message
  135. // the leader id
  136. lead uint64
  137. // leadTransferee is id of the leader transfer target when its value is not zero.
  138. // Follow the procedure defined in raft thesis 3.10.
  139. leadTransferee uint64
  140. // New configuration is ignored if there exists unapplied configuration.
  141. pendingConf bool
  142. // number of ticks since it reached last electionTimeout when it is leader
  143. // or candidate.
  144. // number of ticks since it reached last electionTimeout or received a
  145. // valid message from current leader when it is a follower.
  146. electionElapsed int
  147. // number of ticks since it reached last heartbeatTimeout.
  148. // only leader keeps heartbeatElapsed.
  149. heartbeatElapsed int
  150. checkQuorum bool
  151. heartbeatTimeout int
  152. electionTimeout int
  153. // randomizedElectionTimeout is a random number between
  154. // [electiontimeout, 2 * electiontimeout - 1]. It gets reset
  155. // when raft changes its state to follower or candidate.
  156. randomizedElectionTimeout int
  157. rand *rand.Rand
  158. tick func()
  159. step stepFunc
  160. logger Logger
  161. }
  162. func newRaft(c *Config) *raft {
  163. if err := c.validate(); err != nil {
  164. panic(err.Error())
  165. }
  166. raftlog := newLog(c.Storage, c.Logger)
  167. hs, cs, err := c.Storage.InitialState()
  168. if err != nil {
  169. panic(err) // TODO(bdarnell)
  170. }
  171. peers := c.peers
  172. if len(cs.Nodes) > 0 {
  173. if len(peers) > 0 {
  174. // TODO(bdarnell): the peers argument is always nil except in
  175. // tests; the argument should be removed and these tests should be
  176. // updated to specify their nodes through a snapshot.
  177. panic("cannot specify both newRaft(peers) and ConfState.Nodes)")
  178. }
  179. peers = cs.Nodes
  180. }
  181. r := &raft{
  182. id: c.ID,
  183. lead: None,
  184. readState: ReadState{Index: None, RequestCtx: nil},
  185. raftLog: raftlog,
  186. maxMsgSize: c.MaxSizePerMsg,
  187. maxInflight: c.MaxInflightMsgs,
  188. prs: make(map[uint64]*Progress),
  189. electionTimeout: c.ElectionTick,
  190. heartbeatTimeout: c.HeartbeatTick,
  191. logger: c.Logger,
  192. checkQuorum: c.CheckQuorum,
  193. }
  194. r.rand = rand.New(rand.NewSource(int64(c.ID)))
  195. for _, p := range peers {
  196. r.prs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight)}
  197. }
  198. if !isHardStateEqual(hs, emptyState) {
  199. r.loadState(hs)
  200. }
  201. if c.Applied > 0 {
  202. raftlog.appliedTo(c.Applied)
  203. }
  204. r.becomeFollower(r.Term, None)
  205. var nodesStrs []string
  206. for _, n := range r.nodes() {
  207. nodesStrs = append(nodesStrs, fmt.Sprintf("%x", n))
  208. }
  209. r.logger.Infof("newRaft %x [peers: [%s], term: %d, commit: %d, applied: %d, lastindex: %d, lastterm: %d]",
  210. r.id, strings.Join(nodesStrs, ","), r.Term, r.raftLog.committed, r.raftLog.applied, r.raftLog.lastIndex(), r.raftLog.lastTerm())
  211. return r
  212. }
  213. func (r *raft) hasLeader() bool { return r.lead != None }
  214. func (r *raft) softState() *SoftState { return &SoftState{Lead: r.lead, RaftState: r.state} }
  215. func (r *raft) hardState() pb.HardState {
  216. return pb.HardState{
  217. Term: r.Term,
  218. Vote: r.Vote,
  219. Commit: r.raftLog.committed,
  220. }
  221. }
  222. func (r *raft) quorum() int { return len(r.prs)/2 + 1 }
  223. func (r *raft) nodes() []uint64 {
  224. nodes := make([]uint64, 0, len(r.prs))
  225. for id := range r.prs {
  226. nodes = append(nodes, id)
  227. }
  228. sort.Sort(uint64Slice(nodes))
  229. return nodes
  230. }
  231. // send persists state to stable storage and then sends to its mailbox.
  232. func (r *raft) send(m pb.Message) {
  233. m.From = r.id
  234. // do not attach term to MsgProp
  235. // proposals are a way to forward to the leader and
  236. // should be treated as local message.
  237. if m.Type != pb.MsgProp {
  238. m.Term = r.Term
  239. }
  240. r.msgs = append(r.msgs, m)
  241. }
  242. // sendAppend sends RPC, with entries to the given peer.
  243. func (r *raft) sendAppend(to uint64) {
  244. pr := r.prs[to]
  245. if pr.isPaused() {
  246. return
  247. }
  248. m := pb.Message{}
  249. m.To = to
  250. term, errt := r.raftLog.term(pr.Next - 1)
  251. ents, erre := r.raftLog.entries(pr.Next, r.maxMsgSize)
  252. if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
  253. if !pr.RecentActive {
  254. r.logger.Debugf("ignore sending snapshot to %x since it is not recently active", to)
  255. return
  256. }
  257. m.Type = pb.MsgSnap
  258. snapshot, err := r.raftLog.snapshot()
  259. if err != nil {
  260. if err == ErrSnapshotTemporarilyUnavailable {
  261. r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
  262. return
  263. }
  264. panic(err) // TODO(bdarnell)
  265. }
  266. if IsEmptySnap(snapshot) {
  267. panic("need non-empty snapshot")
  268. }
  269. m.Snapshot = snapshot
  270. sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
  271. r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
  272. r.id, r.raftLog.firstIndex(), r.raftLog.committed, sindex, sterm, to, pr)
  273. pr.becomeSnapshot(sindex)
  274. r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
  275. } else {
  276. m.Type = pb.MsgApp
  277. m.Index = pr.Next - 1
  278. m.LogTerm = term
  279. m.Entries = ents
  280. m.Commit = r.raftLog.committed
  281. if n := len(m.Entries); n != 0 {
  282. switch pr.State {
  283. // optimistically increase the next when in ProgressStateReplicate
  284. case ProgressStateReplicate:
  285. last := m.Entries[n-1].Index
  286. pr.optimisticUpdate(last)
  287. pr.ins.add(last)
  288. case ProgressStateProbe:
  289. pr.pause()
  290. default:
  291. r.logger.Panicf("%x is sending append in unhandled state %s", r.id, pr.State)
  292. }
  293. }
  294. }
  295. r.send(m)
  296. }
  297. // sendHeartbeat sends an empty MsgApp
  298. func (r *raft) sendHeartbeat(to uint64) {
  299. // Attach the commit as min(to.matched, r.committed).
  300. // When the leader sends out heartbeat message,
  301. // the receiver(follower) might not be matched with the leader
  302. // or it might not have all the committed entries.
  303. // The leader MUST NOT forward the follower's commit to
  304. // an unmatched index.
  305. commit := min(r.prs[to].Match, r.raftLog.committed)
  306. m := pb.Message{
  307. To: to,
  308. Type: pb.MsgHeartbeat,
  309. Commit: commit,
  310. }
  311. r.send(m)
  312. }
  313. // bcastAppend sends RPC, with entries to all peers that are not up-to-date
  314. // according to the progress recorded in r.prs.
  315. func (r *raft) bcastAppend() {
  316. for id := range r.prs {
  317. if id == r.id {
  318. continue
  319. }
  320. r.sendAppend(id)
  321. }
  322. }
  323. // bcastHeartbeat sends RPC, without entries to all the peers.
  324. func (r *raft) bcastHeartbeat() {
  325. for id := range r.prs {
  326. if id == r.id {
  327. continue
  328. }
  329. r.sendHeartbeat(id)
  330. r.prs[id].resume()
  331. }
  332. }
  333. // maybeCommit attempts to advance the commit index. Returns true if
  334. // the commit index changed (in which case the caller should call
  335. // r.bcastAppend).
  336. func (r *raft) maybeCommit() bool {
  337. // TODO(bmizerany): optimize.. Currently naive
  338. mis := make(uint64Slice, 0, len(r.prs))
  339. for id := range r.prs {
  340. mis = append(mis, r.prs[id].Match)
  341. }
  342. sort.Sort(sort.Reverse(mis))
  343. mci := mis[r.quorum()-1]
  344. return r.raftLog.maybeCommit(mci, r.Term)
  345. }
  346. func (r *raft) reset(term uint64) {
  347. if r.Term != term {
  348. r.Term = term
  349. r.Vote = None
  350. }
  351. r.lead = None
  352. r.electionElapsed = 0
  353. r.heartbeatElapsed = 0
  354. r.resetRandomizedElectionTimeout()
  355. r.abortLeaderTransfer()
  356. r.votes = make(map[uint64]bool)
  357. for id := range r.prs {
  358. r.prs[id] = &Progress{Next: r.raftLog.lastIndex() + 1, ins: newInflights(r.maxInflight)}
  359. if id == r.id {
  360. r.prs[id].Match = r.raftLog.lastIndex()
  361. }
  362. }
  363. r.pendingConf = false
  364. }
  365. func (r *raft) appendEntry(es ...pb.Entry) {
  366. li := r.raftLog.lastIndex()
  367. for i := range es {
  368. es[i].Term = r.Term
  369. es[i].Index = li + 1 + uint64(i)
  370. }
  371. r.raftLog.append(es...)
  372. r.prs[r.id].maybeUpdate(r.raftLog.lastIndex())
  373. // Regardless of maybeCommit's return, our caller will call bcastAppend.
  374. r.maybeCommit()
  375. }
  376. // tickElection is run by followers and candidates after r.electionTimeout.
  377. func (r *raft) tickElection() {
  378. r.electionElapsed++
  379. if r.promotable() && r.pastElectionTimeout() {
  380. r.electionElapsed = 0
  381. r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
  382. }
  383. }
  384. // tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
  385. func (r *raft) tickHeartbeat() {
  386. r.heartbeatElapsed++
  387. r.electionElapsed++
  388. if r.electionElapsed >= r.electionTimeout {
  389. r.electionElapsed = 0
  390. if r.checkQuorum {
  391. r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
  392. }
  393. // If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
  394. if r.state == StateLeader && r.leadTransferee != None {
  395. r.abortLeaderTransfer()
  396. }
  397. }
  398. if r.state != StateLeader {
  399. return
  400. }
  401. if r.heartbeatElapsed >= r.heartbeatTimeout {
  402. r.heartbeatElapsed = 0
  403. r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
  404. }
  405. }
  406. func (r *raft) becomeFollower(term uint64, lead uint64) {
  407. r.step = stepFollower
  408. r.reset(term)
  409. r.tick = r.tickElection
  410. r.lead = lead
  411. r.state = StateFollower
  412. r.logger.Infof("%x became follower at term %d", r.id, r.Term)
  413. }
  414. func (r *raft) becomeCandidate() {
  415. // TODO(xiangli) remove the panic when the raft implementation is stable
  416. if r.state == StateLeader {
  417. panic("invalid transition [leader -> candidate]")
  418. }
  419. r.step = stepCandidate
  420. r.reset(r.Term + 1)
  421. r.tick = r.tickElection
  422. r.Vote = r.id
  423. r.state = StateCandidate
  424. r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
  425. }
  426. func (r *raft) becomeLeader() {
  427. // TODO(xiangli) remove the panic when the raft implementation is stable
  428. if r.state == StateFollower {
  429. panic("invalid transition [follower -> leader]")
  430. }
  431. r.step = stepLeader
  432. r.reset(r.Term)
  433. r.tick = r.tickHeartbeat
  434. r.lead = r.id
  435. r.state = StateLeader
  436. ents, err := r.raftLog.entries(r.raftLog.committed+1, noLimit)
  437. if err != nil {
  438. r.logger.Panicf("unexpected error getting uncommitted entries (%v)", err)
  439. }
  440. for _, e := range ents {
  441. if e.Type != pb.EntryConfChange {
  442. continue
  443. }
  444. if r.pendingConf {
  445. panic("unexpected double uncommitted config entry")
  446. }
  447. r.pendingConf = true
  448. }
  449. r.appendEntry(pb.Entry{Data: nil})
  450. r.logger.Infof("%x became leader at term %d", r.id, r.Term)
  451. }
  452. func (r *raft) campaign() {
  453. r.becomeCandidate()
  454. if r.quorum() == r.poll(r.id, true) {
  455. r.becomeLeader()
  456. return
  457. }
  458. for id := range r.prs {
  459. if id == r.id {
  460. continue
  461. }
  462. r.logger.Infof("%x [logterm: %d, index: %d] sent vote request to %x at term %d",
  463. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), id, r.Term)
  464. r.send(pb.Message{To: id, Type: pb.MsgVote, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm()})
  465. }
  466. }
  467. func (r *raft) poll(id uint64, v bool) (granted int) {
  468. if v {
  469. r.logger.Infof("%x received vote from %x at term %d", r.id, id, r.Term)
  470. } else {
  471. r.logger.Infof("%x received vote rejection from %x at term %d", r.id, id, r.Term)
  472. }
  473. if _, ok := r.votes[id]; !ok {
  474. r.votes[id] = v
  475. }
  476. for _, vv := range r.votes {
  477. if vv {
  478. granted++
  479. }
  480. }
  481. return granted
  482. }
  483. func (r *raft) Step(m pb.Message) error {
  484. if m.Type == pb.MsgHup {
  485. if r.state != StateLeader {
  486. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  487. r.campaign()
  488. } else {
  489. r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
  490. }
  491. return nil
  492. }
  493. if m.Type == pb.MsgTransferLeader {
  494. if r.state != StateLeader {
  495. r.logger.Debugf("%x [term %d state %v] ignoring MsgTransferLeader to %x", r.id, r.Term, r.state, m.From)
  496. }
  497. }
  498. switch {
  499. case m.Term == 0:
  500. // local message
  501. case m.Term > r.Term:
  502. lead := m.From
  503. if m.Type == pb.MsgVote {
  504. if r.checkQuorum && r.state != StateCandidate && r.electionElapsed < r.electionTimeout {
  505. // If a server receives a RequestVote request within the minimum election timeout
  506. // of hearing from a current leader, it does not update its term or grant its vote
  507. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored vote from %x [logterm: %d, index: %d] at term %d: lease is not expired (remaining ticks: %d)",
  508. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
  509. return nil
  510. }
  511. lead = None
  512. }
  513. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  514. r.id, r.Term, m.Type, m.From, m.Term)
  515. r.becomeFollower(m.Term, lead)
  516. case m.Term < r.Term:
  517. if r.checkQuorum && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
  518. // We have received messages from a leader at a lower term. It is possible that these messages were
  519. // simply delayed in the network, but this could also mean that this node has advanced its term number
  520. // during a network partition, and it is now unable to either win an election or to rejoin the majority
  521. // on the old term. If checkQuorum is false, this will be handled by incrementing term numbers in response
  522. // to MsgVote with a higher term, but if checkQuorum is true we may not advance the term on MsgVote and
  523. // must generate other messages to advance the term. The net result of these two features is to minimize
  524. // the disruption caused by nodes that have been removed from the cluster's configuration: a removed node
  525. // will send MsgVotes which will be ignored, but it will not receive MsgApp or MsgHeartbeat, so it will not
  526. // create disruptive term increases
  527. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
  528. } else {
  529. // ignore other cases
  530. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  531. r.id, r.Term, m.Type, m.From, m.Term)
  532. }
  533. return nil
  534. }
  535. r.step(r, m)
  536. return nil
  537. }
  538. type stepFunc func(r *raft, m pb.Message)
  539. func stepLeader(r *raft, m pb.Message) {
  540. // These message types do not require any progress for m.From.
  541. switch m.Type {
  542. case pb.MsgBeat:
  543. r.bcastHeartbeat()
  544. return
  545. case pb.MsgCheckQuorum:
  546. if !r.checkQuorumActive() {
  547. r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
  548. r.becomeFollower(r.Term, None)
  549. }
  550. return
  551. case pb.MsgProp:
  552. if len(m.Entries) == 0 {
  553. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  554. }
  555. if _, ok := r.prs[r.id]; !ok {
  556. // If we are not currently a member of the range (i.e. this node
  557. // was removed from the configuration while serving as leader),
  558. // drop any new proposals.
  559. return
  560. }
  561. if r.leadTransferee != None {
  562. r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
  563. return
  564. }
  565. for i, e := range m.Entries {
  566. if e.Type == pb.EntryConfChange {
  567. if r.pendingConf {
  568. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  569. }
  570. r.pendingConf = true
  571. }
  572. }
  573. r.appendEntry(m.Entries...)
  574. r.bcastAppend()
  575. return
  576. case pb.MsgVote:
  577. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected vote from %x [logterm: %d, index: %d] at term %d",
  578. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  579. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp, Reject: true})
  580. return
  581. case pb.MsgReadIndex:
  582. ri := None
  583. if r.checkQuorum {
  584. ri = r.raftLog.committed
  585. }
  586. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  587. return
  588. }
  589. // All other message types require a progress for m.From (pr).
  590. pr, prOk := r.prs[m.From]
  591. if !prOk {
  592. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  593. return
  594. }
  595. switch m.Type {
  596. case pb.MsgAppResp:
  597. pr.RecentActive = true
  598. if m.Reject {
  599. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  600. r.id, m.RejectHint, m.From, m.Index)
  601. if pr.maybeDecrTo(m.Index, m.RejectHint) {
  602. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  603. if pr.State == ProgressStateReplicate {
  604. pr.becomeProbe()
  605. }
  606. r.sendAppend(m.From)
  607. }
  608. } else {
  609. oldPaused := pr.isPaused()
  610. if pr.maybeUpdate(m.Index) {
  611. switch {
  612. case pr.State == ProgressStateProbe:
  613. pr.becomeReplicate()
  614. case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
  615. r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  616. pr.becomeProbe()
  617. case pr.State == ProgressStateReplicate:
  618. pr.ins.freeTo(m.Index)
  619. }
  620. if r.maybeCommit() {
  621. r.bcastAppend()
  622. } else if oldPaused {
  623. // update() reset the wait state on this node. If we had delayed sending
  624. // an update before, send it now.
  625. r.sendAppend(m.From)
  626. }
  627. // Transfer leadership is in progress.
  628. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  629. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  630. r.sendTimeoutNow(m.From)
  631. }
  632. }
  633. }
  634. case pb.MsgHeartbeatResp:
  635. pr.RecentActive = true
  636. // free one slot for the full inflights window to allow progress.
  637. if pr.State == ProgressStateReplicate && pr.ins.full() {
  638. pr.ins.freeFirstOne()
  639. }
  640. if pr.Match < r.raftLog.lastIndex() {
  641. r.sendAppend(m.From)
  642. }
  643. case pb.MsgSnapStatus:
  644. if pr.State != ProgressStateSnapshot {
  645. return
  646. }
  647. if !m.Reject {
  648. pr.becomeProbe()
  649. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  650. } else {
  651. pr.snapshotFailure()
  652. pr.becomeProbe()
  653. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  654. }
  655. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  656. // out the next msgApp.
  657. // If snapshot failure, wait for a heartbeat interval before next try
  658. pr.pause()
  659. case pb.MsgUnreachable:
  660. // During optimistic replication, if the remote becomes unreachable,
  661. // there is huge probability that a MsgApp is lost.
  662. if pr.State == ProgressStateReplicate {
  663. pr.becomeProbe()
  664. }
  665. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  666. case pb.MsgTransferLeader:
  667. leadTransferee := m.From
  668. lastLeadTransferee := r.leadTransferee
  669. if lastLeadTransferee != None {
  670. if lastLeadTransferee == leadTransferee {
  671. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  672. r.id, r.Term, leadTransferee, leadTransferee)
  673. return
  674. }
  675. r.abortLeaderTransfer()
  676. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  677. }
  678. if leadTransferee == r.id {
  679. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  680. return
  681. }
  682. // Transfer leadership to third party.
  683. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  684. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  685. r.electionElapsed = 0
  686. r.leadTransferee = leadTransferee
  687. if pr.Match == r.raftLog.lastIndex() {
  688. r.sendTimeoutNow(leadTransferee)
  689. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  690. } else {
  691. r.sendAppend(leadTransferee)
  692. }
  693. }
  694. }
  695. func stepCandidate(r *raft, m pb.Message) {
  696. switch m.Type {
  697. case pb.MsgProp:
  698. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  699. return
  700. case pb.MsgApp:
  701. r.becomeFollower(r.Term, m.From)
  702. r.handleAppendEntries(m)
  703. case pb.MsgHeartbeat:
  704. r.becomeFollower(r.Term, m.From)
  705. r.handleHeartbeat(m)
  706. case pb.MsgSnap:
  707. r.becomeFollower(m.Term, m.From)
  708. r.handleSnapshot(m)
  709. case pb.MsgVote:
  710. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected vote from %x [logterm: %d, index: %d] at term %d",
  711. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  712. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp, Reject: true})
  713. case pb.MsgVoteResp:
  714. gr := r.poll(m.From, !m.Reject)
  715. r.logger.Infof("%x [quorum:%d] has received %d votes and %d vote rejections", r.id, r.quorum(), gr, len(r.votes)-gr)
  716. switch r.quorum() {
  717. case gr:
  718. r.becomeLeader()
  719. r.bcastAppend()
  720. case len(r.votes) - gr:
  721. r.becomeFollower(r.Term, None)
  722. }
  723. case pb.MsgTimeoutNow:
  724. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  725. }
  726. }
  727. func stepFollower(r *raft, m pb.Message) {
  728. switch m.Type {
  729. case pb.MsgProp:
  730. if r.lead == None {
  731. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  732. return
  733. }
  734. m.To = r.lead
  735. r.send(m)
  736. case pb.MsgApp:
  737. r.electionElapsed = 0
  738. r.lead = m.From
  739. r.handleAppendEntries(m)
  740. case pb.MsgHeartbeat:
  741. r.electionElapsed = 0
  742. r.lead = m.From
  743. r.handleHeartbeat(m)
  744. case pb.MsgSnap:
  745. r.electionElapsed = 0
  746. r.handleSnapshot(m)
  747. case pb.MsgVote:
  748. if (r.Vote == None || r.Vote == m.From) && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  749. r.electionElapsed = 0
  750. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] voted for %x [logterm: %d, index: %d] at term %d",
  751. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  752. r.Vote = m.From
  753. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp})
  754. } else {
  755. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected vote from %x [logterm: %d, index: %d] at term %d",
  756. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  757. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp, Reject: true})
  758. }
  759. case pb.MsgTimeoutNow:
  760. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  761. r.campaign()
  762. case pb.MsgReadIndex:
  763. if r.lead == None {
  764. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  765. return
  766. }
  767. m.To = r.lead
  768. r.send(m)
  769. case pb.MsgReadIndexResp:
  770. if len(m.Entries) != 1 {
  771. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  772. return
  773. }
  774. r.readState.Index = m.Index
  775. r.readState.RequestCtx = m.Entries[0].Data
  776. }
  777. }
  778. func (r *raft) handleAppendEntries(m pb.Message) {
  779. if m.Index < r.raftLog.committed {
  780. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  781. return
  782. }
  783. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  784. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  785. } else {
  786. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  787. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  788. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  789. }
  790. }
  791. func (r *raft) handleHeartbeat(m pb.Message) {
  792. r.raftLog.commitTo(m.Commit)
  793. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp})
  794. }
  795. func (r *raft) handleSnapshot(m pb.Message) {
  796. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  797. if r.restore(m.Snapshot) {
  798. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  799. r.id, r.raftLog.committed, sindex, sterm)
  800. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  801. } else {
  802. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  803. r.id, r.raftLog.committed, sindex, sterm)
  804. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  805. }
  806. }
  807. // restore recovers the state machine from a snapshot. It restores the log and the
  808. // configuration of state machine.
  809. func (r *raft) restore(s pb.Snapshot) bool {
  810. if s.Metadata.Index <= r.raftLog.committed {
  811. return false
  812. }
  813. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  814. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  815. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  816. r.raftLog.commitTo(s.Metadata.Index)
  817. return false
  818. }
  819. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  820. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  821. r.raftLog.restore(s)
  822. r.prs = make(map[uint64]*Progress)
  823. for _, n := range s.Metadata.ConfState.Nodes {
  824. match, next := uint64(0), uint64(r.raftLog.lastIndex())+1
  825. if n == r.id {
  826. match = next - 1
  827. } else {
  828. match = 0
  829. }
  830. r.setProgress(n, match, next)
  831. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.prs[n])
  832. }
  833. return true
  834. }
  835. // promotable indicates whether state machine can be promoted to leader,
  836. // which is true when its own id is in progress list.
  837. func (r *raft) promotable() bool {
  838. _, ok := r.prs[r.id]
  839. return ok
  840. }
  841. func (r *raft) addNode(id uint64) {
  842. if _, ok := r.prs[id]; ok {
  843. // Ignore any redundant addNode calls (which can happen because the
  844. // initial bootstrapping entries are applied twice).
  845. return
  846. }
  847. r.setProgress(id, 0, r.raftLog.lastIndex()+1)
  848. r.pendingConf = false
  849. }
  850. func (r *raft) removeNode(id uint64) {
  851. r.delProgress(id)
  852. r.pendingConf = false
  853. // do not try to commit or abort transferring if there is no nodes in the cluster.
  854. if len(r.prs) == 0 {
  855. return
  856. }
  857. // The quorum size is now smaller, so see if any pending entries can
  858. // be committed.
  859. if r.maybeCommit() {
  860. r.bcastAppend()
  861. }
  862. // If the removed node is the leadTransferee, then abort the leadership transferring.
  863. if r.state == StateLeader && r.leadTransferee == id {
  864. r.abortLeaderTransfer()
  865. }
  866. }
  867. func (r *raft) resetPendingConf() { r.pendingConf = false }
  868. func (r *raft) setProgress(id, match, next uint64) {
  869. r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
  870. }
  871. func (r *raft) delProgress(id uint64) {
  872. delete(r.prs, id)
  873. }
  874. func (r *raft) loadState(state pb.HardState) {
  875. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  876. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  877. }
  878. r.raftLog.committed = state.Commit
  879. r.Term = state.Term
  880. r.Vote = state.Vote
  881. }
  882. // pastElectionTimeout returns true iff r.electionElapsed is greater
  883. // than or equal to the randomized election timeout in
  884. // [electiontimeout, 2 * electiontimeout - 1].
  885. func (r *raft) pastElectionTimeout() bool {
  886. return r.electionElapsed >= r.randomizedElectionTimeout
  887. }
  888. func (r *raft) resetRandomizedElectionTimeout() {
  889. r.randomizedElectionTimeout = r.electionTimeout + r.rand.Intn(r.electionTimeout)
  890. }
  891. // checkQuorumActive returns true if the quorum is active from
  892. // the view of the local raft state machine. Otherwise, it returns
  893. // false.
  894. // checkQuorumActive also resets all RecentActive to false.
  895. func (r *raft) checkQuorumActive() bool {
  896. var act int
  897. for id := range r.prs {
  898. if id == r.id { // self is always active
  899. act++
  900. continue
  901. }
  902. if r.prs[id].RecentActive {
  903. act++
  904. }
  905. r.prs[id].RecentActive = false
  906. }
  907. return act >= r.quorum()
  908. }
  909. func (r *raft) sendTimeoutNow(to uint64) {
  910. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  911. }
  912. func (r *raft) abortLeaderTransfer() {
  913. r.leadTransferee = None
  914. }