raft.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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.lead = m.From
  747. r.handleSnapshot(m)
  748. case pb.MsgVote:
  749. if (r.Vote == None || r.Vote == m.From) && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  750. r.electionElapsed = 0
  751. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] voted for %x [logterm: %d, index: %d] at term %d",
  752. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  753. r.Vote = m.From
  754. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp})
  755. } else {
  756. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected vote from %x [logterm: %d, index: %d] at term %d",
  757. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  758. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp, Reject: true})
  759. }
  760. case pb.MsgTimeoutNow:
  761. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  762. r.campaign()
  763. case pb.MsgReadIndex:
  764. if r.lead == None {
  765. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  766. return
  767. }
  768. m.To = r.lead
  769. r.send(m)
  770. case pb.MsgReadIndexResp:
  771. if len(m.Entries) != 1 {
  772. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  773. return
  774. }
  775. r.readState.Index = m.Index
  776. r.readState.RequestCtx = m.Entries[0].Data
  777. }
  778. }
  779. func (r *raft) handleAppendEntries(m pb.Message) {
  780. if m.Index < r.raftLog.committed {
  781. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  782. return
  783. }
  784. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  785. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  786. } else {
  787. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  788. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  789. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  790. }
  791. }
  792. func (r *raft) handleHeartbeat(m pb.Message) {
  793. r.raftLog.commitTo(m.Commit)
  794. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp})
  795. }
  796. func (r *raft) handleSnapshot(m pb.Message) {
  797. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  798. if r.restore(m.Snapshot) {
  799. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  800. r.id, r.raftLog.committed, sindex, sterm)
  801. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  802. } else {
  803. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  804. r.id, r.raftLog.committed, sindex, sterm)
  805. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  806. }
  807. }
  808. // restore recovers the state machine from a snapshot. It restores the log and the
  809. // configuration of state machine.
  810. func (r *raft) restore(s pb.Snapshot) bool {
  811. if s.Metadata.Index <= r.raftLog.committed {
  812. return false
  813. }
  814. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  815. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  816. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  817. r.raftLog.commitTo(s.Metadata.Index)
  818. return false
  819. }
  820. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  821. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  822. r.raftLog.restore(s)
  823. r.prs = make(map[uint64]*Progress)
  824. for _, n := range s.Metadata.ConfState.Nodes {
  825. match, next := uint64(0), r.raftLog.lastIndex()+1
  826. if n == r.id {
  827. match = next - 1
  828. }
  829. r.setProgress(n, match, next)
  830. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.prs[n])
  831. }
  832. return true
  833. }
  834. // promotable indicates whether state machine can be promoted to leader,
  835. // which is true when its own id is in progress list.
  836. func (r *raft) promotable() bool {
  837. _, ok := r.prs[r.id]
  838. return ok
  839. }
  840. func (r *raft) addNode(id uint64) {
  841. if _, ok := r.prs[id]; ok {
  842. // Ignore any redundant addNode calls (which can happen because the
  843. // initial bootstrapping entries are applied twice).
  844. return
  845. }
  846. r.setProgress(id, 0, r.raftLog.lastIndex()+1)
  847. r.pendingConf = false
  848. }
  849. func (r *raft) removeNode(id uint64) {
  850. r.delProgress(id)
  851. r.pendingConf = false
  852. // do not try to commit or abort transferring if there is no nodes in the cluster.
  853. if len(r.prs) == 0 {
  854. return
  855. }
  856. // The quorum size is now smaller, so see if any pending entries can
  857. // be committed.
  858. if r.maybeCommit() {
  859. r.bcastAppend()
  860. }
  861. // If the removed node is the leadTransferee, then abort the leadership transferring.
  862. if r.state == StateLeader && r.leadTransferee == id {
  863. r.abortLeaderTransfer()
  864. }
  865. }
  866. func (r *raft) resetPendingConf() { r.pendingConf = false }
  867. func (r *raft) setProgress(id, match, next uint64) {
  868. r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
  869. }
  870. func (r *raft) delProgress(id uint64) {
  871. delete(r.prs, id)
  872. }
  873. func (r *raft) loadState(state pb.HardState) {
  874. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  875. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  876. }
  877. r.raftLog.committed = state.Commit
  878. r.Term = state.Term
  879. r.Vote = state.Vote
  880. }
  881. // pastElectionTimeout returns true iff r.electionElapsed is greater
  882. // than or equal to the randomized election timeout in
  883. // [electiontimeout, 2 * electiontimeout - 1].
  884. func (r *raft) pastElectionTimeout() bool {
  885. return r.electionElapsed >= r.randomizedElectionTimeout
  886. }
  887. func (r *raft) resetRandomizedElectionTimeout() {
  888. r.randomizedElectionTimeout = r.electionTimeout + r.rand.Intn(r.electionTimeout)
  889. }
  890. // checkQuorumActive returns true if the quorum is active from
  891. // the view of the local raft state machine. Otherwise, it returns
  892. // false.
  893. // checkQuorumActive also resets all RecentActive to false.
  894. func (r *raft) checkQuorumActive() bool {
  895. var act int
  896. for id := range r.prs {
  897. if id == r.id { // self is always active
  898. act++
  899. continue
  900. }
  901. if r.prs[id].RecentActive {
  902. act++
  903. }
  904. r.prs[id].RecentActive = false
  905. }
  906. return act >= r.quorum()
  907. }
  908. func (r *raft) sendTimeoutNow(to uint64) {
  909. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  910. }
  911. func (r *raft) abortLeaderTransfer() {
  912. r.leadTransferee = None
  913. }