raft.go 22 KB

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