raft.go 19 KB

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