raft.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. // Copyright 2015 CoreOS, Inc.
  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. var errNoLeader = errors.New("no leader")
  28. var ErrSnapshotTemporarilyUnavailable = errors.New("snapshot is temporarily unavailable")
  29. // Possible values for StateType.
  30. const (
  31. StateFollower StateType = iota
  32. StateCandidate
  33. StateLeader
  34. )
  35. // StateType represents the role of a node in a cluster.
  36. type StateType uint64
  37. var stmap = [...]string{
  38. "StateFollower",
  39. "StateCandidate",
  40. "StateLeader",
  41. }
  42. func (st StateType) String() string {
  43. return stmap[uint64(st)]
  44. }
  45. // Config contains the parameters to start a raft.
  46. type Config struct {
  47. // ID is the identity of the local raft. ID cannot be 0.
  48. ID uint64
  49. // peers contains the IDs of all nodes (including self) in
  50. // the raft cluster. It should only be set when starting a new
  51. // raft cluster.
  52. // Restarting raft from previous configuration will panic if
  53. // peers is set.
  54. // peer is private and only used for testing right now.
  55. peers []uint64
  56. // ElectionTick is the election timeout. If a follower does not
  57. // receive any message from the leader of current term during
  58. // ElectionTick, it will become candidate and start an election.
  59. // ElectionTick must be greater than HeartbeatTick. We suggest
  60. // to use ElectionTick = 10 * HeartbeatTick to avoid unnecessary
  61. // leader switching.
  62. ElectionTick int
  63. // HeartbeatTick is the heartbeat interval. A leader sends heartbeat
  64. // message to maintain the leadership every heartbeat interval.
  65. HeartbeatTick int
  66. // Storage is the storage for raft. raft generates entires and
  67. // states to be stored in storage. raft reads the persisted entires
  68. // and states out of Storage when it needs. raft reads out the previous
  69. // state and configuration out of storage when restarting.
  70. Storage Storage
  71. // Applied is the last applied index. It should only be set when restarting
  72. // raft. raft will not return entries to the application smaller or equal to Applied.
  73. // If Applied is unset when restarting, raft might return previous applied entries.
  74. // This is a very application dependent configuration.
  75. Applied uint64
  76. // MaxSizePerMsg limits the max size of each append message. Smaller value lowers
  77. // the raft recovery cost(initial probing and message lost during normal operation).
  78. // On the other side, it might affect the throughput during normal replication.
  79. // Note: math.MaxUint64 for unlimited, 0 for at most one entry per message.
  80. MaxSizePerMsg uint64
  81. // MaxInflightMsgs limits the max number of in-flight append messages during optimistic
  82. // replication phase. The application transportation layer usually has its own sending
  83. // buffer over TCP/UDP. Setting MaxInflightMsgs to avoid overflowing that sending buffer.
  84. // TODO (xiangli): feedback to application to limit the proposal rate?
  85. MaxInflightMsgs int
  86. // logger is the logger used for raft log. For multinode which
  87. // can host multiple raft group, each raft group can have its
  88. // own logger
  89. Logger Logger
  90. }
  91. func (c *Config) validate() error {
  92. if c.ID == None {
  93. return errors.New("cannot use none as id")
  94. }
  95. if c.HeartbeatTick <= 0 {
  96. return errors.New("heartbeat tick must be greater than 0")
  97. }
  98. if c.ElectionTick <= c.HeartbeatTick {
  99. return errors.New("election tick must be greater than heartbeat tick")
  100. }
  101. if c.Storage == nil {
  102. return errors.New("storage cannot be nil")
  103. }
  104. if c.MaxInflightMsgs <= 0 {
  105. return errors.New("max inflight messages must be greater than 0")
  106. }
  107. if c.Logger == nil {
  108. c.Logger = raftLogger
  109. }
  110. return nil
  111. }
  112. type raft struct {
  113. pb.HardState
  114. id uint64
  115. // the log
  116. raftLog *raftLog
  117. maxInflight int
  118. maxMsgSize uint64
  119. prs map[uint64]*Progress
  120. state StateType
  121. votes map[uint64]bool
  122. msgs []pb.Message
  123. // the leader id
  124. lead uint64
  125. // New configuration is ignored if there exists unapplied configuration.
  126. pendingConf bool
  127. elapsed int // number of ticks since the last msg
  128. heartbeatTimeout int
  129. electionTimeout int
  130. rand *rand.Rand
  131. tick func()
  132. step stepFunc
  133. logger Logger
  134. }
  135. func newRaft(c *Config) *raft {
  136. if err := c.validate(); err != nil {
  137. panic(err.Error())
  138. }
  139. raftlog := newLog(c.Storage, c.Logger)
  140. hs, cs, err := c.Storage.InitialState()
  141. if err != nil {
  142. panic(err) // TODO(bdarnell)
  143. }
  144. peers := c.peers
  145. if len(cs.Nodes) > 0 {
  146. if len(peers) > 0 {
  147. // TODO(bdarnell): the peers argument is always nil except in
  148. // tests; the argument should be removed and these tests should be
  149. // updated to specify their nodes through a snapshot.
  150. panic("cannot specify both newRaft(peers) and ConfState.Nodes)")
  151. }
  152. peers = cs.Nodes
  153. }
  154. r := &raft{
  155. id: c.ID,
  156. lead: None,
  157. raftLog: raftlog,
  158. maxMsgSize: c.MaxSizePerMsg,
  159. maxInflight: c.MaxInflightMsgs,
  160. prs: make(map[uint64]*Progress),
  161. electionTimeout: c.ElectionTick,
  162. heartbeatTimeout: c.HeartbeatTick,
  163. logger: c.Logger,
  164. }
  165. r.rand = rand.New(rand.NewSource(int64(c.ID)))
  166. for _, p := range peers {
  167. r.prs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight)}
  168. }
  169. if !isHardStateEqual(hs, emptyState) {
  170. r.loadState(hs)
  171. }
  172. if c.Applied > 0 {
  173. raftlog.appliedTo(c.Applied)
  174. }
  175. r.becomeFollower(r.Term, None)
  176. nodesStrs := make([]string, 0)
  177. for _, n := range r.nodes() {
  178. nodesStrs = append(nodesStrs, fmt.Sprintf("%x", n))
  179. }
  180. r.logger.Infof("newRaft %x [peers: [%s], term: %d, commit: %d, applied: %d, lastindex: %d, lastterm: %d]",
  181. r.id, strings.Join(nodesStrs, ","), r.Term, r.raftLog.committed, r.raftLog.applied, r.raftLog.lastIndex(), r.raftLog.lastTerm())
  182. return r
  183. }
  184. func (r *raft) hasLeader() bool { return r.lead != None }
  185. func (r *raft) softState() *SoftState { return &SoftState{Lead: r.lead, RaftState: r.state} }
  186. func (r *raft) q() int { return len(r.prs)/2 + 1 }
  187. func (r *raft) nodes() []uint64 {
  188. nodes := make([]uint64, 0, len(r.prs))
  189. for k := range r.prs {
  190. nodes = append(nodes, k)
  191. }
  192. sort.Sort(uint64Slice(nodes))
  193. return nodes
  194. }
  195. // send persists state to stable storage and then sends to its mailbox.
  196. func (r *raft) send(m pb.Message) {
  197. m.From = r.id
  198. // do not attach term to MsgProp
  199. // proposals are a way to forward to the leader and
  200. // should be treated as local message.
  201. if m.Type != pb.MsgProp {
  202. m.Term = r.Term
  203. }
  204. r.msgs = append(r.msgs, m)
  205. }
  206. // sendAppend sends RRPC, with entries to the given peer.
  207. func (r *raft) sendAppend(to uint64) {
  208. pr := r.prs[to]
  209. if pr.isPaused() {
  210. return
  211. }
  212. m := pb.Message{}
  213. m.To = to
  214. term, errt := r.raftLog.term(pr.Next - 1)
  215. ents, erre := r.raftLog.entries(pr.Next, r.maxMsgSize)
  216. if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
  217. m.Type = pb.MsgSnap
  218. snapshot, err := r.raftLog.snapshot()
  219. if err != nil {
  220. if err == ErrSnapshotTemporarilyUnavailable {
  221. r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
  222. return
  223. }
  224. panic(err) // TODO(bdarnell)
  225. }
  226. if IsEmptySnap(snapshot) {
  227. panic("need non-empty snapshot")
  228. }
  229. m.Snapshot = snapshot
  230. sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
  231. r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
  232. r.id, r.raftLog.firstIndex(), r.Commit, sindex, sterm, to, pr)
  233. pr.becomeSnapshot(sindex)
  234. r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
  235. } else {
  236. m.Type = pb.MsgApp
  237. m.Index = pr.Next - 1
  238. m.LogTerm = term
  239. m.Entries = ents
  240. m.Commit = r.raftLog.committed
  241. if n := len(m.Entries); n != 0 {
  242. switch pr.State {
  243. // optimistically increase the next when in ProgressStateReplicate
  244. case ProgressStateReplicate:
  245. last := m.Entries[n-1].Index
  246. pr.optimisticUpdate(last)
  247. pr.ins.add(last)
  248. case ProgressStateProbe:
  249. pr.pause()
  250. default:
  251. r.logger.Panicf("%x is sending append in unhandled state %s", r.id, pr.State)
  252. }
  253. }
  254. }
  255. r.send(m)
  256. }
  257. // sendHeartbeat sends an empty MsgApp
  258. func (r *raft) sendHeartbeat(to uint64) {
  259. // Attach the commit as min(to.matched, r.committed).
  260. // When the leader sends out heartbeat message,
  261. // the receiver(follower) might not be matched with the leader
  262. // or it might not have all the committed entries.
  263. // The leader MUST NOT forward the follower's commit to
  264. // an unmatched index.
  265. commit := min(r.prs[to].Match, r.raftLog.committed)
  266. m := pb.Message{
  267. To: to,
  268. Type: pb.MsgHeartbeat,
  269. Commit: commit,
  270. }
  271. r.send(m)
  272. }
  273. // bcastAppend sends RRPC, with entries to all peers that are not up-to-date
  274. // according to the progress recorded in r.prs.
  275. func (r *raft) bcastAppend() {
  276. for i := range r.prs {
  277. if i == r.id {
  278. continue
  279. }
  280. r.sendAppend(i)
  281. }
  282. }
  283. // bcastHeartbeat sends RRPC, without entries to all the peers.
  284. func (r *raft) bcastHeartbeat() {
  285. for i := range r.prs {
  286. if i == r.id {
  287. continue
  288. }
  289. r.sendHeartbeat(i)
  290. r.prs[i].resume()
  291. }
  292. }
  293. func (r *raft) maybeCommit() bool {
  294. // TODO(bmizerany): optimize.. Currently naive
  295. mis := make(uint64Slice, 0, len(r.prs))
  296. for i := range r.prs {
  297. mis = append(mis, r.prs[i].Match)
  298. }
  299. sort.Sort(sort.Reverse(mis))
  300. mci := mis[r.q()-1]
  301. return r.raftLog.maybeCommit(mci, r.Term)
  302. }
  303. func (r *raft) reset(term uint64) {
  304. if r.Term != term {
  305. r.Term = term
  306. r.Vote = None
  307. }
  308. r.lead = None
  309. r.elapsed = 0
  310. r.votes = make(map[uint64]bool)
  311. for i := range r.prs {
  312. r.prs[i] = &Progress{Next: r.raftLog.lastIndex() + 1, ins: newInflights(r.maxInflight)}
  313. if i == r.id {
  314. r.prs[i].Match = r.raftLog.lastIndex()
  315. }
  316. }
  317. r.pendingConf = false
  318. }
  319. func (r *raft) appendEntry(es ...pb.Entry) {
  320. li := r.raftLog.lastIndex()
  321. for i := range es {
  322. es[i].Term = r.Term
  323. es[i].Index = li + 1 + uint64(i)
  324. }
  325. r.raftLog.append(es...)
  326. r.prs[r.id].maybeUpdate(r.raftLog.lastIndex())
  327. r.maybeCommit()
  328. }
  329. // tickElection is run by followers and candidates after r.electionTimeout.
  330. func (r *raft) tickElection() {
  331. if !r.promotable() {
  332. r.elapsed = 0
  333. return
  334. }
  335. r.elapsed++
  336. if r.isElectionTimeout() {
  337. r.elapsed = 0
  338. r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
  339. }
  340. }
  341. // tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
  342. func (r *raft) tickHeartbeat() {
  343. r.elapsed++
  344. if r.elapsed >= r.heartbeatTimeout {
  345. r.elapsed = 0
  346. r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
  347. }
  348. }
  349. func (r *raft) becomeFollower(term uint64, lead uint64) {
  350. r.step = stepFollower
  351. r.reset(term)
  352. r.tick = r.tickElection
  353. r.lead = lead
  354. r.state = StateFollower
  355. r.logger.Infof("%x became follower at term %d", r.id, r.Term)
  356. }
  357. func (r *raft) becomeCandidate() {
  358. // TODO(xiangli) remove the panic when the raft implementation is stable
  359. if r.state == StateLeader {
  360. panic("invalid transition [leader -> candidate]")
  361. }
  362. r.step = stepCandidate
  363. r.reset(r.Term + 1)
  364. r.tick = r.tickElection
  365. r.Vote = r.id
  366. r.state = StateCandidate
  367. r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
  368. }
  369. func (r *raft) becomeLeader() {
  370. // TODO(xiangli) remove the panic when the raft implementation is stable
  371. if r.state == StateFollower {
  372. panic("invalid transition [follower -> leader]")
  373. }
  374. r.step = stepLeader
  375. r.reset(r.Term)
  376. r.tick = r.tickHeartbeat
  377. r.lead = r.id
  378. r.state = StateLeader
  379. ents, err := r.raftLog.entries(r.raftLog.committed+1, noLimit)
  380. if err != nil {
  381. r.logger.Panicf("unexpected error getting uncommitted entries (%v)", err)
  382. }
  383. for _, e := range ents {
  384. if e.Type != pb.EntryConfChange {
  385. continue
  386. }
  387. if r.pendingConf {
  388. panic("unexpected double uncommitted config entry")
  389. }
  390. r.pendingConf = true
  391. }
  392. r.appendEntry(pb.Entry{Data: nil})
  393. r.logger.Infof("%x became leader at term %d", r.id, r.Term)
  394. }
  395. func (r *raft) campaign() {
  396. r.becomeCandidate()
  397. if r.q() == r.poll(r.id, true) {
  398. r.becomeLeader()
  399. return
  400. }
  401. for i := range r.prs {
  402. if i == r.id {
  403. continue
  404. }
  405. r.logger.Infof("%x [logterm: %d, index: %d] sent vote request to %x at term %d",
  406. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), i, r.Term)
  407. r.send(pb.Message{To: i, Type: pb.MsgVote, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm()})
  408. }
  409. }
  410. func (r *raft) poll(id uint64, v bool) (granted int) {
  411. if v {
  412. r.logger.Infof("%x received vote from %x at term %d", r.id, id, r.Term)
  413. } else {
  414. r.logger.Infof("%x received vote rejection from %x at term %d", r.id, id, r.Term)
  415. }
  416. if _, ok := r.votes[id]; !ok {
  417. r.votes[id] = v
  418. }
  419. for _, vv := range r.votes {
  420. if vv {
  421. granted++
  422. }
  423. }
  424. return granted
  425. }
  426. func (r *raft) Step(m pb.Message) error {
  427. if m.Type == pb.MsgHup {
  428. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  429. r.campaign()
  430. r.Commit = r.raftLog.committed
  431. return nil
  432. }
  433. switch {
  434. case m.Term == 0:
  435. // local message
  436. case m.Term > r.Term:
  437. lead := m.From
  438. if m.Type == pb.MsgVote {
  439. lead = None
  440. }
  441. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  442. r.id, r.Term, m.Type, m.From, m.Term)
  443. r.becomeFollower(m.Term, lead)
  444. case m.Term < r.Term:
  445. // ignore
  446. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  447. r.id, r.Term, m.Type, m.From, m.Term)
  448. return nil
  449. }
  450. r.step(r, m)
  451. r.Commit = r.raftLog.committed
  452. return nil
  453. }
  454. type stepFunc func(r *raft, m pb.Message)
  455. func stepLeader(r *raft, m pb.Message) {
  456. pr := r.prs[m.From]
  457. switch m.Type {
  458. case pb.MsgBeat:
  459. r.bcastHeartbeat()
  460. case pb.MsgProp:
  461. if len(m.Entries) == 0 {
  462. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  463. }
  464. if _, ok := r.prs[r.id]; !ok {
  465. // If we are not currently a member of the range (i.e. this node
  466. // was removed from the configuration while serving as leader),
  467. // drop any new proposals.
  468. return
  469. }
  470. for i, e := range m.Entries {
  471. if e.Type == pb.EntryConfChange {
  472. if r.pendingConf {
  473. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  474. }
  475. r.pendingConf = true
  476. }
  477. }
  478. r.appendEntry(m.Entries...)
  479. r.bcastAppend()
  480. case pb.MsgAppResp:
  481. if m.Reject {
  482. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  483. r.id, m.RejectHint, m.From, m.Index)
  484. if pr.maybeDecrTo(m.Index, m.RejectHint) {
  485. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  486. if pr.State == ProgressStateReplicate {
  487. pr.becomeProbe()
  488. }
  489. r.sendAppend(m.From)
  490. }
  491. } else {
  492. oldPaused := pr.isPaused()
  493. if pr.maybeUpdate(m.Index) {
  494. switch {
  495. case pr.State == ProgressStateProbe:
  496. pr.becomeReplicate()
  497. case pr.State == ProgressStateSnapshot && pr.maybeSnapshotAbort():
  498. r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  499. pr.becomeProbe()
  500. case pr.State == ProgressStateReplicate:
  501. pr.ins.freeTo(m.Index)
  502. }
  503. if r.maybeCommit() {
  504. r.bcastAppend()
  505. } else if oldPaused {
  506. // update() reset the wait state on this node. If we had delayed sending
  507. // an update before, send it now.
  508. r.sendAppend(m.From)
  509. }
  510. }
  511. }
  512. case pb.MsgHeartbeatResp:
  513. // free one slot for the full inflights window to allow progress.
  514. if pr.State == ProgressStateReplicate && pr.ins.full() {
  515. pr.ins.freeFirstOne()
  516. }
  517. if pr.Match < r.raftLog.lastIndex() {
  518. r.sendAppend(m.From)
  519. }
  520. case pb.MsgVote:
  521. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected vote from %x [logterm: %d, index: %d] at term %d",
  522. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  523. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp, Reject: true})
  524. case pb.MsgSnapStatus:
  525. if pr.State != ProgressStateSnapshot {
  526. return
  527. }
  528. if !m.Reject {
  529. pr.becomeProbe()
  530. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  531. } else {
  532. pr.snapshotFailure()
  533. pr.becomeProbe()
  534. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  535. }
  536. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  537. // out the next msgApp.
  538. // If snapshot failure, wait for a heartbeat interval before next try
  539. pr.pause()
  540. case pb.MsgUnreachable:
  541. // During optimistic replication, if the remote becomes unreachable,
  542. // there is huge probability that a MsgApp is lost.
  543. if pr.State == ProgressStateReplicate {
  544. pr.becomeProbe()
  545. }
  546. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  547. }
  548. }
  549. func stepCandidate(r *raft, m pb.Message) {
  550. switch m.Type {
  551. case pb.MsgProp:
  552. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  553. return
  554. case pb.MsgApp:
  555. r.becomeFollower(r.Term, m.From)
  556. r.handleAppendEntries(m)
  557. case pb.MsgHeartbeat:
  558. r.becomeFollower(r.Term, m.From)
  559. r.handleHeartbeat(m)
  560. case pb.MsgSnap:
  561. r.becomeFollower(m.Term, m.From)
  562. r.handleSnapshot(m)
  563. case pb.MsgVote:
  564. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected vote from %x [logterm: %d, index: %d] at term %x",
  565. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  566. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp, Reject: true})
  567. case pb.MsgVoteResp:
  568. gr := r.poll(m.From, !m.Reject)
  569. r.logger.Infof("%x [q:%d] has received %d votes and %d vote rejections", r.id, r.q(), gr, len(r.votes)-gr)
  570. switch r.q() {
  571. case gr:
  572. r.becomeLeader()
  573. r.bcastAppend()
  574. case len(r.votes) - gr:
  575. r.becomeFollower(r.Term, None)
  576. }
  577. }
  578. }
  579. func stepFollower(r *raft, m pb.Message) {
  580. switch m.Type {
  581. case pb.MsgProp:
  582. if r.lead == None {
  583. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  584. return
  585. }
  586. m.To = r.lead
  587. r.send(m)
  588. case pb.MsgApp:
  589. r.elapsed = 0
  590. r.lead = m.From
  591. r.handleAppendEntries(m)
  592. case pb.MsgHeartbeat:
  593. r.elapsed = 0
  594. r.lead = m.From
  595. r.handleHeartbeat(m)
  596. case pb.MsgSnap:
  597. r.elapsed = 0
  598. r.handleSnapshot(m)
  599. case pb.MsgVote:
  600. if (r.Vote == None || r.Vote == m.From) && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  601. r.elapsed = 0
  602. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] voted for %x [logterm: %d, index: %d] at term %d",
  603. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  604. r.Vote = m.From
  605. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp})
  606. } else {
  607. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected vote from %x [logterm: %d, index: %d] at term %d",
  608. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.From, m.LogTerm, m.Index, r.Term)
  609. r.send(pb.Message{To: m.From, Type: pb.MsgVoteResp, Reject: true})
  610. }
  611. }
  612. }
  613. func (r *raft) handleAppendEntries(m pb.Message) {
  614. if m.Index < r.Commit {
  615. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.Commit})
  616. return
  617. }
  618. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  619. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  620. } else {
  621. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  622. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  623. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  624. }
  625. }
  626. func (r *raft) handleHeartbeat(m pb.Message) {
  627. r.raftLog.commitTo(m.Commit)
  628. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp})
  629. }
  630. func (r *raft) handleSnapshot(m pb.Message) {
  631. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  632. if r.restore(m.Snapshot) {
  633. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  634. r.id, r.Commit, sindex, sterm)
  635. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  636. } else {
  637. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  638. r.id, r.Commit, sindex, sterm)
  639. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  640. }
  641. }
  642. // restore recovers the state machine from a snapshot. It restores the log and the
  643. // configuration of state machine.
  644. func (r *raft) restore(s pb.Snapshot) bool {
  645. if s.Metadata.Index <= r.raftLog.committed {
  646. return false
  647. }
  648. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  649. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  650. r.id, r.Commit, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  651. r.raftLog.commitTo(s.Metadata.Index)
  652. return false
  653. }
  654. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  655. r.id, r.Commit, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  656. r.raftLog.restore(s)
  657. r.prs = make(map[uint64]*Progress)
  658. for _, n := range s.Metadata.ConfState.Nodes {
  659. match, next := uint64(0), uint64(r.raftLog.lastIndex())+1
  660. if n == r.id {
  661. match = next - 1
  662. } else {
  663. match = 0
  664. }
  665. r.setProgress(n, match, next)
  666. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.prs[n])
  667. }
  668. return true
  669. }
  670. // promotable indicates whether state machine can be promoted to leader,
  671. // which is true when its own id is in progress list.
  672. func (r *raft) promotable() bool {
  673. _, ok := r.prs[r.id]
  674. return ok
  675. }
  676. func (r *raft) addNode(id uint64) {
  677. if _, ok := r.prs[id]; ok {
  678. // Ignore any redundant addNode calls (which can happen because the
  679. // initial bootstrapping entries are applied twice).
  680. return
  681. }
  682. r.setProgress(id, 0, r.raftLog.lastIndex()+1)
  683. r.pendingConf = false
  684. }
  685. func (r *raft) removeNode(id uint64) {
  686. r.delProgress(id)
  687. r.pendingConf = false
  688. }
  689. func (r *raft) resetPendingConf() { r.pendingConf = false }
  690. func (r *raft) setProgress(id, match, next uint64) {
  691. r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
  692. }
  693. func (r *raft) delProgress(id uint64) {
  694. delete(r.prs, id)
  695. }
  696. func (r *raft) loadState(state pb.HardState) {
  697. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  698. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  699. }
  700. r.raftLog.committed = state.Commit
  701. r.Term = state.Term
  702. r.Vote = state.Vote
  703. r.Commit = state.Commit
  704. }
  705. // isElectionTimeout returns true if r.elapsed is greater than the
  706. // randomized election timeout in (electiontimeout, 2 * electiontimeout - 1).
  707. // Otherwise, it returns false.
  708. func (r *raft) isElectionTimeout() bool {
  709. d := r.elapsed - r.electionTimeout
  710. if d < 0 {
  711. return false
  712. }
  713. return d > r.rand.Int()%r.electionTimeout
  714. }