raft.go 20 KB

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