raft.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package raft
  15. import (
  16. "bytes"
  17. "errors"
  18. "fmt"
  19. "math"
  20. "math/rand"
  21. "sort"
  22. "strings"
  23. "sync"
  24. "time"
  25. pb "github.com/coreos/etcd/raft/raftpb"
  26. )
  27. // None is a placeholder node ID used when there is no leader.
  28. const None uint64 = 0
  29. const noLimit = math.MaxUint64
  30. // Possible values for StateType.
  31. const (
  32. StateFollower StateType = iota
  33. StateCandidate
  34. StateLeader
  35. StatePreCandidate
  36. numStates
  37. )
  38. type ReadOnlyOption int
  39. const (
  40. // ReadOnlySafe guarantees the linearizability of the read only request by
  41. // communicating with the quorum. It is the default and suggested option.
  42. ReadOnlySafe ReadOnlyOption = iota
  43. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  44. // relying on the leader lease. It can be affected by clock drift.
  45. // If the clock drift is unbounded, leader might keep the lease longer than it
  46. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  47. // in that case.
  48. ReadOnlyLeaseBased
  49. )
  50. // Possible values for CampaignType
  51. const (
  52. // campaignPreElection represents the first phase of a normal election when
  53. // Config.PreVote is true.
  54. campaignPreElection CampaignType = "CampaignPreElection"
  55. // campaignElection represents a normal (time-based) election (the second phase
  56. // of the election when Config.PreVote is true).
  57. campaignElection CampaignType = "CampaignElection"
  58. // campaignTransfer represents the type of leader transfer
  59. campaignTransfer CampaignType = "CampaignTransfer"
  60. )
  61. // ErrProposalDropped is returned when the proposal is ignored by some cases,
  62. // so that the proposer can be notified and fail fast.
  63. var ErrProposalDropped = errors.New("raft proposal dropped")
  64. // lockedRand is a small wrapper around rand.Rand to provide
  65. // synchronization. Only the methods needed by the code are exposed
  66. // (e.g. Intn).
  67. type lockedRand struct {
  68. mu sync.Mutex
  69. rand *rand.Rand
  70. }
  71. func (r *lockedRand) Intn(n int) int {
  72. r.mu.Lock()
  73. v := r.rand.Intn(n)
  74. r.mu.Unlock()
  75. return v
  76. }
  77. var globalRand = &lockedRand{
  78. rand: rand.New(rand.NewSource(time.Now().UnixNano())),
  79. }
  80. // CampaignType represents the type of campaigning
  81. // the reason we use the type of string instead of uint64
  82. // is because it's simpler to compare and fill in raft entries
  83. type CampaignType string
  84. // StateType represents the role of a node in a cluster.
  85. type StateType uint64
  86. var stmap = [...]string{
  87. "StateFollower",
  88. "StateCandidate",
  89. "StateLeader",
  90. "StatePreCandidate",
  91. }
  92. func (st StateType) String() string {
  93. return stmap[uint64(st)]
  94. }
  95. // Config contains the parameters to start a raft.
  96. type Config struct {
  97. // ID is the identity of the local raft. ID cannot be 0.
  98. ID uint64
  99. // peers contains the IDs of all nodes (including self) in the raft cluster. It
  100. // should only be set when starting a new raft cluster. Restarting raft from
  101. // previous configuration will panic if peers is set. peer is private and only
  102. // used for testing right now.
  103. peers []uint64
  104. // learners contains the IDs of all learner nodes (including self if the
  105. // local node is a learner) in the raft cluster. learners only receives
  106. // entries from the leader node. It does not vote or promote itself.
  107. learners []uint64
  108. // ElectionTick is the number of Node.Tick invocations that must pass between
  109. // elections. That is, if a follower does not receive any message from the
  110. // leader of current term before ElectionTick has elapsed, it will become
  111. // candidate and start an election. ElectionTick must be greater than
  112. // HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
  113. // unnecessary leader switching.
  114. ElectionTick int
  115. // HeartbeatTick is the number of Node.Tick invocations that must pass between
  116. // heartbeats. That is, a leader sends heartbeat messages to maintain its
  117. // leadership every HeartbeatTick ticks.
  118. HeartbeatTick int
  119. // Storage is the storage for raft. raft generates entries and states to be
  120. // stored in storage. raft reads the persisted entries and states out of
  121. // Storage when it needs. raft reads out the previous state and configuration
  122. // out of storage when restarting.
  123. Storage Storage
  124. // Applied is the last applied index. It should only be set when restarting
  125. // raft. raft will not return entries to the application smaller or equal to
  126. // Applied. If Applied is unset when restarting, raft might return previous
  127. // applied entries. This is a very application dependent configuration.
  128. Applied uint64
  129. // MaxSizePerMsg limits the max size of each append message. Smaller value
  130. // lowers the raft recovery cost(initial probing and message lost during normal
  131. // operation). On the other side, it might affect the throughput during normal
  132. // replication. Note: math.MaxUint64 for unlimited, 0 for at most one entry per
  133. // message.
  134. MaxSizePerMsg uint64
  135. // MaxInflightMsgs limits the max number of in-flight append messages during
  136. // optimistic replication phase. The application transportation layer usually
  137. // has its own sending buffer over TCP/UDP. Setting MaxInflightMsgs to avoid
  138. // overflowing that sending buffer. TODO (xiangli): feedback to application to
  139. // limit the proposal rate?
  140. MaxInflightMsgs int
  141. // CheckQuorum specifies if the leader should check quorum activity. Leader
  142. // steps down when quorum is not active for an electionTimeout.
  143. CheckQuorum bool
  144. // PreVote enables the Pre-Vote algorithm described in raft thesis section
  145. // 9.6. This prevents disruption when a node that has been partitioned away
  146. // rejoins the cluster.
  147. PreVote bool
  148. // ReadOnlyOption specifies how the read only request is processed.
  149. //
  150. // ReadOnlySafe guarantees the linearizability of the read only request by
  151. // communicating with the quorum. It is the default and suggested option.
  152. //
  153. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  154. // relying on the leader lease. It can be affected by clock drift.
  155. // If the clock drift is unbounded, leader might keep the lease longer than it
  156. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  157. // in that case.
  158. // CheckQuorum MUST be enabled if ReadOnlyOption is ReadOnlyLeaseBased.
  159. ReadOnlyOption ReadOnlyOption
  160. // Logger is the logger used for raft log. For multinode which can host
  161. // multiple raft group, each raft group can have its own logger
  162. Logger Logger
  163. // DisableProposalForwarding set to true means that followers will drop
  164. // proposals, rather than forwarding them to the leader. One use case for
  165. // this feature would be in a situation where the Raft leader is used to
  166. // compute the data of a proposal, for example, adding a timestamp from a
  167. // hybrid logical clock to data in a monotonically increasing way. Forwarding
  168. // should be disabled to prevent a follower with an innaccurate hybrid
  169. // logical clock from assigning the timestamp and then forwarding the data
  170. // to the leader.
  171. DisableProposalForwarding bool
  172. }
  173. func (c *Config) validate() error {
  174. if c.ID == None {
  175. return errors.New("cannot use none as id")
  176. }
  177. if c.HeartbeatTick <= 0 {
  178. return errors.New("heartbeat tick must be greater than 0")
  179. }
  180. if c.ElectionTick <= c.HeartbeatTick {
  181. return errors.New("election tick must be greater than heartbeat tick")
  182. }
  183. if c.Storage == nil {
  184. return errors.New("storage cannot be nil")
  185. }
  186. if c.MaxInflightMsgs <= 0 {
  187. return errors.New("max inflight messages must be greater than 0")
  188. }
  189. if c.Logger == nil {
  190. c.Logger = raftLogger
  191. }
  192. if c.ReadOnlyOption == ReadOnlyLeaseBased && !c.CheckQuorum {
  193. return errors.New("CheckQuorum must be enabled when ReadOnlyOption is ReadOnlyLeaseBased")
  194. }
  195. return nil
  196. }
  197. type raft struct {
  198. id uint64
  199. Term uint64
  200. Vote uint64
  201. readStates []ReadState
  202. // the log
  203. raftLog *raftLog
  204. maxInflight int
  205. maxMsgSize uint64
  206. prs map[uint64]*Progress
  207. learnerPrs map[uint64]*Progress
  208. state StateType
  209. // isLearner is true if the local raft node is a learner.
  210. isLearner bool
  211. votes map[uint64]bool
  212. msgs []pb.Message
  213. // the leader id
  214. lead uint64
  215. // leadTransferee is id of the leader transfer target when its value is not zero.
  216. // Follow the procedure defined in raft thesis 3.10.
  217. leadTransferee uint64
  218. // Only one conf change may be pending (in the log, but not yet
  219. // applied) at a time. This is enforced via pendingConfIndex, which
  220. // is set to a value >= the log index of the latest pending
  221. // configuration change (if any). Config changes are only allowed to
  222. // be proposed if the leader's applied index is greater than this
  223. // value.
  224. pendingConfIndex uint64
  225. readOnly *readOnly
  226. // number of ticks since it reached last electionTimeout when it is leader
  227. // or candidate.
  228. // number of ticks since it reached last electionTimeout or received a
  229. // valid message from current leader when it is a follower.
  230. electionElapsed int
  231. // number of ticks since it reached last heartbeatTimeout.
  232. // only leader keeps heartbeatElapsed.
  233. heartbeatElapsed int
  234. checkQuorum bool
  235. preVote bool
  236. heartbeatTimeout int
  237. electionTimeout int
  238. // randomizedElectionTimeout is a random number between
  239. // [electiontimeout, 2 * electiontimeout - 1]. It gets reset
  240. // when raft changes its state to follower or candidate.
  241. randomizedElectionTimeout int
  242. disableProposalForwarding bool
  243. tick func()
  244. step stepFunc
  245. logger Logger
  246. }
  247. func newRaft(c *Config) *raft {
  248. if err := c.validate(); err != nil {
  249. panic(err.Error())
  250. }
  251. raftlog := newLog(c.Storage, c.Logger)
  252. hs, cs, err := c.Storage.InitialState()
  253. if err != nil {
  254. panic(err) // TODO(bdarnell)
  255. }
  256. peers := c.peers
  257. learners := c.learners
  258. if len(cs.Nodes) > 0 || len(cs.Learners) > 0 {
  259. if len(peers) > 0 || len(learners) > 0 {
  260. // TODO(bdarnell): the peers argument is always nil except in
  261. // tests; the argument should be removed and these tests should be
  262. // updated to specify their nodes through a snapshot.
  263. panic("cannot specify both newRaft(peers, learners) and ConfState.(Nodes, Learners)")
  264. }
  265. peers = cs.Nodes
  266. learners = cs.Learners
  267. }
  268. r := &raft{
  269. id: c.ID,
  270. lead: None,
  271. isLearner: false,
  272. raftLog: raftlog,
  273. maxMsgSize: c.MaxSizePerMsg,
  274. maxInflight: c.MaxInflightMsgs,
  275. prs: make(map[uint64]*Progress),
  276. learnerPrs: make(map[uint64]*Progress),
  277. electionTimeout: c.ElectionTick,
  278. heartbeatTimeout: c.HeartbeatTick,
  279. logger: c.Logger,
  280. checkQuorum: c.CheckQuorum,
  281. preVote: c.PreVote,
  282. readOnly: newReadOnly(c.ReadOnlyOption),
  283. disableProposalForwarding: c.DisableProposalForwarding,
  284. }
  285. for _, p := range peers {
  286. r.prs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight)}
  287. }
  288. for _, p := range learners {
  289. if _, ok := r.prs[p]; ok {
  290. panic(fmt.Sprintf("node %x is in both learner and peer list", p))
  291. }
  292. r.learnerPrs[p] = &Progress{Next: 1, ins: newInflights(r.maxInflight), IsLearner: true}
  293. if r.id == p {
  294. r.isLearner = true
  295. }
  296. }
  297. if !isHardStateEqual(hs, emptyState) {
  298. r.loadState(hs)
  299. }
  300. if c.Applied > 0 {
  301. raftlog.appliedTo(c.Applied)
  302. }
  303. r.becomeFollower(r.Term, None)
  304. var nodesStrs []string
  305. for _, n := range r.nodes() {
  306. nodesStrs = append(nodesStrs, fmt.Sprintf("%x", n))
  307. }
  308. r.logger.Infof("newRaft %x [peers: [%s], term: %d, commit: %d, applied: %d, lastindex: %d, lastterm: %d]",
  309. r.id, strings.Join(nodesStrs, ","), r.Term, r.raftLog.committed, r.raftLog.applied, r.raftLog.lastIndex(), r.raftLog.lastTerm())
  310. return r
  311. }
  312. func (r *raft) hasLeader() bool { return r.lead != None }
  313. func (r *raft) softState() *SoftState { return &SoftState{Lead: r.lead, RaftState: r.state} }
  314. func (r *raft) hardState() pb.HardState {
  315. return pb.HardState{
  316. Term: r.Term,
  317. Vote: r.Vote,
  318. Commit: r.raftLog.committed,
  319. }
  320. }
  321. func (r *raft) quorum() int { return len(r.prs)/2 + 1 }
  322. func (r *raft) nodes() []uint64 {
  323. nodes := make([]uint64, 0, len(r.prs))
  324. for id := range r.prs {
  325. nodes = append(nodes, id)
  326. }
  327. sort.Sort(uint64Slice(nodes))
  328. return nodes
  329. }
  330. func (r *raft) learnerNodes() []uint64 {
  331. nodes := make([]uint64, 0, len(r.learnerPrs))
  332. for id := range r.learnerPrs {
  333. nodes = append(nodes, id)
  334. }
  335. sort.Sort(uint64Slice(nodes))
  336. return nodes
  337. }
  338. // send persists state to stable storage and then sends to its mailbox.
  339. func (r *raft) send(m pb.Message) {
  340. m.From = r.id
  341. if m.Type == pb.MsgVote || m.Type == pb.MsgVoteResp || m.Type == pb.MsgPreVote || m.Type == pb.MsgPreVoteResp {
  342. if m.Term == 0 {
  343. // All {pre-,}campaign messages need to have the term set when
  344. // sending.
  345. // - MsgVote: m.Term is the term the node is campaigning for,
  346. // non-zero as we increment the term when campaigning.
  347. // - MsgVoteResp: m.Term is the new r.Term if the MsgVote was
  348. // granted, non-zero for the same reason MsgVote is
  349. // - MsgPreVote: m.Term is the term the node will campaign,
  350. // non-zero as we use m.Term to indicate the next term we'll be
  351. // campaigning for
  352. // - MsgPreVoteResp: m.Term is the term received in the original
  353. // MsgPreVote if the pre-vote was granted, non-zero for the
  354. // same reasons MsgPreVote is
  355. panic(fmt.Sprintf("term should be set when sending %s", m.Type))
  356. }
  357. } else {
  358. if m.Term != 0 {
  359. panic(fmt.Sprintf("term should not be set when sending %s (was %d)", m.Type, m.Term))
  360. }
  361. // do not attach term to MsgProp, MsgReadIndex
  362. // proposals are a way to forward to the leader and
  363. // should be treated as local message.
  364. // MsgReadIndex is also forwarded to leader.
  365. if m.Type != pb.MsgProp && m.Type != pb.MsgReadIndex {
  366. m.Term = r.Term
  367. }
  368. }
  369. r.msgs = append(r.msgs, m)
  370. }
  371. func (r *raft) getProgress(id uint64) *Progress {
  372. if pr, ok := r.prs[id]; ok {
  373. return pr
  374. }
  375. return r.learnerPrs[id]
  376. }
  377. // sendAppend sends RPC, with entries to the given peer.
  378. func (r *raft) sendAppend(to uint64) {
  379. pr := r.getProgress(to)
  380. if pr.IsPaused() {
  381. return
  382. }
  383. m := pb.Message{}
  384. m.To = to
  385. term, errt := r.raftLog.term(pr.Next - 1)
  386. ents, erre := r.raftLog.entries(pr.Next, r.maxMsgSize)
  387. if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
  388. if !pr.RecentActive {
  389. r.logger.Debugf("ignore sending snapshot to %x since it is not recently active", to)
  390. return
  391. }
  392. m.Type = pb.MsgSnap
  393. snapshot, err := r.raftLog.snapshot()
  394. if err != nil {
  395. if err == ErrSnapshotTemporarilyUnavailable {
  396. r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
  397. return
  398. }
  399. panic(err) // TODO(bdarnell)
  400. }
  401. if IsEmptySnap(snapshot) {
  402. panic("need non-empty snapshot")
  403. }
  404. m.Snapshot = snapshot
  405. sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
  406. r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
  407. r.id, r.raftLog.firstIndex(), r.raftLog.committed, sindex, sterm, to, pr)
  408. pr.becomeSnapshot(sindex)
  409. r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
  410. } else {
  411. m.Type = pb.MsgApp
  412. m.Index = pr.Next - 1
  413. m.LogTerm = term
  414. m.Entries = ents
  415. m.Commit = r.raftLog.committed
  416. if n := len(m.Entries); n != 0 {
  417. switch pr.State {
  418. // optimistically increase the next when in ProgressStateReplicate
  419. case ProgressStateReplicate:
  420. last := m.Entries[n-1].Index
  421. pr.optimisticUpdate(last)
  422. pr.ins.add(last)
  423. case ProgressStateProbe:
  424. pr.pause()
  425. default:
  426. r.logger.Panicf("%x is sending append in unhandled state %s", r.id, pr.State)
  427. }
  428. }
  429. }
  430. r.send(m)
  431. }
  432. // sendHeartbeat sends an empty MsgApp
  433. func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
  434. // Attach the commit as min(to.matched, r.committed).
  435. // When the leader sends out heartbeat message,
  436. // the receiver(follower) might not be matched with the leader
  437. // or it might not have all the committed entries.
  438. // The leader MUST NOT forward the follower's commit to
  439. // an unmatched index.
  440. commit := min(r.getProgress(to).Match, r.raftLog.committed)
  441. m := pb.Message{
  442. To: to,
  443. Type: pb.MsgHeartbeat,
  444. Commit: commit,
  445. Context: ctx,
  446. }
  447. r.send(m)
  448. }
  449. func (r *raft) forEachProgress(f func(id uint64, pr *Progress)) {
  450. for id, pr := range r.prs {
  451. f(id, pr)
  452. }
  453. for id, pr := range r.learnerPrs {
  454. f(id, pr)
  455. }
  456. }
  457. // bcastAppend sends RPC, with entries to all peers that are not up-to-date
  458. // according to the progress recorded in r.prs.
  459. func (r *raft) bcastAppend() {
  460. r.forEachProgress(func(id uint64, _ *Progress) {
  461. if id == r.id {
  462. return
  463. }
  464. r.sendAppend(id)
  465. })
  466. }
  467. // bcastHeartbeat sends RPC, without entries to all the peers.
  468. func (r *raft) bcastHeartbeat() {
  469. lastCtx := r.readOnly.lastPendingRequestCtx()
  470. if len(lastCtx) == 0 {
  471. r.bcastHeartbeatWithCtx(nil)
  472. } else {
  473. r.bcastHeartbeatWithCtx([]byte(lastCtx))
  474. }
  475. }
  476. func (r *raft) bcastHeartbeatWithCtx(ctx []byte) {
  477. r.forEachProgress(func(id uint64, _ *Progress) {
  478. if id == r.id {
  479. return
  480. }
  481. r.sendHeartbeat(id, ctx)
  482. })
  483. }
  484. // maybeCommit attempts to advance the commit index. Returns true if
  485. // the commit index changed (in which case the caller should call
  486. // r.bcastAppend).
  487. func (r *raft) maybeCommit() bool {
  488. // TODO(bmizerany): optimize.. Currently naive
  489. mis := make(uint64Slice, 0, len(r.prs))
  490. for _, p := range r.prs {
  491. mis = append(mis, p.Match)
  492. }
  493. sort.Sort(sort.Reverse(mis))
  494. mci := mis[r.quorum()-1]
  495. return r.raftLog.maybeCommit(mci, r.Term)
  496. }
  497. func (r *raft) reset(term uint64) {
  498. if r.Term != term {
  499. r.Term = term
  500. r.Vote = None
  501. }
  502. r.lead = None
  503. r.electionElapsed = 0
  504. r.heartbeatElapsed = 0
  505. r.resetRandomizedElectionTimeout()
  506. r.abortLeaderTransfer()
  507. r.votes = make(map[uint64]bool)
  508. r.forEachProgress(func(id uint64, pr *Progress) {
  509. *pr = Progress{Next: r.raftLog.lastIndex() + 1, ins: newInflights(r.maxInflight), IsLearner: pr.IsLearner}
  510. if id == r.id {
  511. pr.Match = r.raftLog.lastIndex()
  512. }
  513. })
  514. r.pendingConfIndex = 0
  515. r.readOnly = newReadOnly(r.readOnly.option)
  516. }
  517. func (r *raft) appendEntry(es ...pb.Entry) {
  518. li := r.raftLog.lastIndex()
  519. for i := range es {
  520. es[i].Term = r.Term
  521. es[i].Index = li + 1 + uint64(i)
  522. }
  523. r.raftLog.append(es...)
  524. r.getProgress(r.id).maybeUpdate(r.raftLog.lastIndex())
  525. // Regardless of maybeCommit's return, our caller will call bcastAppend.
  526. r.maybeCommit()
  527. }
  528. // tickElection is run by followers and candidates after r.electionTimeout.
  529. func (r *raft) tickElection() {
  530. r.electionElapsed++
  531. if r.promotable() && r.pastElectionTimeout() {
  532. r.electionElapsed = 0
  533. r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
  534. }
  535. }
  536. // tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
  537. func (r *raft) tickHeartbeat() {
  538. r.heartbeatElapsed++
  539. r.electionElapsed++
  540. if r.electionElapsed >= r.electionTimeout {
  541. r.electionElapsed = 0
  542. if r.checkQuorum {
  543. r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
  544. }
  545. // If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
  546. if r.state == StateLeader && r.leadTransferee != None {
  547. r.abortLeaderTransfer()
  548. }
  549. }
  550. if r.state != StateLeader {
  551. return
  552. }
  553. if r.heartbeatElapsed >= r.heartbeatTimeout {
  554. r.heartbeatElapsed = 0
  555. r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
  556. }
  557. }
  558. func (r *raft) becomeFollower(term uint64, lead uint64) {
  559. r.step = stepFollower
  560. r.reset(term)
  561. r.tick = r.tickElection
  562. r.lead = lead
  563. r.state = StateFollower
  564. r.logger.Infof("%x became follower at term %d", r.id, r.Term)
  565. }
  566. func (r *raft) becomeCandidate() {
  567. // TODO(xiangli) remove the panic when the raft implementation is stable
  568. if r.state == StateLeader {
  569. panic("invalid transition [leader -> candidate]")
  570. }
  571. r.step = stepCandidate
  572. r.reset(r.Term + 1)
  573. r.tick = r.tickElection
  574. r.Vote = r.id
  575. r.state = StateCandidate
  576. r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
  577. }
  578. func (r *raft) becomePreCandidate() {
  579. // TODO(xiangli) remove the panic when the raft implementation is stable
  580. if r.state == StateLeader {
  581. panic("invalid transition [leader -> pre-candidate]")
  582. }
  583. // Becoming a pre-candidate changes our step functions and state,
  584. // but doesn't change anything else. In particular it does not increase
  585. // r.Term or change r.Vote.
  586. r.step = stepCandidate
  587. r.votes = make(map[uint64]bool)
  588. r.tick = r.tickElection
  589. r.state = StatePreCandidate
  590. r.logger.Infof("%x became pre-candidate at term %d", r.id, r.Term)
  591. }
  592. func (r *raft) becomeLeader() {
  593. // TODO(xiangli) remove the panic when the raft implementation is stable
  594. if r.state == StateFollower {
  595. panic("invalid transition [follower -> leader]")
  596. }
  597. r.step = stepLeader
  598. r.reset(r.Term)
  599. r.tick = r.tickHeartbeat
  600. r.lead = r.id
  601. r.state = StateLeader
  602. ents, err := r.raftLog.entries(r.raftLog.committed+1, noLimit)
  603. if err != nil {
  604. r.logger.Panicf("unexpected error getting uncommitted entries (%v)", err)
  605. }
  606. // Conservatively set the pendingConfIndex to the last index in the
  607. // log. There may or may not be a pending config change, but it's
  608. // safe to delay any future proposals until we commit all our
  609. // pending log entries, and scanning the entire tail of the log
  610. // could be expensive.
  611. if len(ents) > 0 {
  612. r.pendingConfIndex = ents[len(ents)-1].Index
  613. }
  614. r.appendEntry(pb.Entry{Data: nil})
  615. r.logger.Infof("%x became leader at term %d", r.id, r.Term)
  616. }
  617. func (r *raft) campaign(t CampaignType) {
  618. var term uint64
  619. var voteMsg pb.MessageType
  620. if t == campaignPreElection {
  621. r.becomePreCandidate()
  622. voteMsg = pb.MsgPreVote
  623. // PreVote RPCs are sent for the next term before we've incremented r.Term.
  624. term = r.Term + 1
  625. } else {
  626. r.becomeCandidate()
  627. voteMsg = pb.MsgVote
  628. term = r.Term
  629. }
  630. if r.quorum() == r.poll(r.id, voteRespMsgType(voteMsg), true) {
  631. // We won the election after voting for ourselves (which must mean that
  632. // this is a single-node cluster). Advance to the next state.
  633. if t == campaignPreElection {
  634. r.campaign(campaignElection)
  635. } else {
  636. r.becomeLeader()
  637. }
  638. return
  639. }
  640. for id := range r.prs {
  641. if id == r.id {
  642. continue
  643. }
  644. r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
  645. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
  646. var ctx []byte
  647. if t == campaignTransfer {
  648. ctx = []byte(t)
  649. }
  650. r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
  651. }
  652. }
  653. func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int) {
  654. if v {
  655. r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
  656. } else {
  657. r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
  658. }
  659. if _, ok := r.votes[id]; !ok {
  660. r.votes[id] = v
  661. }
  662. for _, vv := range r.votes {
  663. if vv {
  664. granted++
  665. }
  666. }
  667. return granted
  668. }
  669. func (r *raft) Step(m pb.Message) error {
  670. // Handle the message term, which may result in our stepping down to a follower.
  671. switch {
  672. case m.Term == 0:
  673. // local message
  674. case m.Term > r.Term:
  675. if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
  676. force := bytes.Equal(m.Context, []byte(campaignTransfer))
  677. inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
  678. if !force && inLease {
  679. // If a server receives a RequestVote request within the minimum election timeout
  680. // of hearing from a current leader, it does not update its term or grant its vote
  681. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored %s from %x [logterm: %d, index: %d] at term %d: lease is not expired (remaining ticks: %d)",
  682. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
  683. return nil
  684. }
  685. }
  686. switch {
  687. case m.Type == pb.MsgPreVote:
  688. // Never change our term in response to a PreVote
  689. case m.Type == pb.MsgPreVoteResp && !m.Reject:
  690. // We send pre-vote requests with a term in our future. If the
  691. // pre-vote is granted, we will increment our term when we get a
  692. // quorum. If it is not, the term comes from the node that
  693. // rejected our vote so we should become a follower at the new
  694. // term.
  695. default:
  696. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  697. r.id, r.Term, m.Type, m.From, m.Term)
  698. if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap {
  699. r.becomeFollower(m.Term, m.From)
  700. } else {
  701. r.becomeFollower(m.Term, None)
  702. }
  703. }
  704. case m.Term < r.Term:
  705. if r.checkQuorum && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
  706. // We have received messages from a leader at a lower term. It is possible
  707. // that these messages were simply delayed in the network, but this could
  708. // also mean that this node has advanced its term number during a network
  709. // partition, and it is now unable to either win an election or to rejoin
  710. // the majority on the old term. If checkQuorum is false, this will be
  711. // handled by incrementing term numbers in response to MsgVote with a
  712. // higher term, but if checkQuorum is true we may not advance the term on
  713. // MsgVote and must generate other messages to advance the term. The net
  714. // result of these two features is to minimize the disruption caused by
  715. // nodes that have been removed from the cluster's configuration: a
  716. // removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
  717. // but it will not receive MsgApp or MsgHeartbeat, so it will not create
  718. // disruptive term increases
  719. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
  720. } else {
  721. // ignore other cases
  722. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  723. r.id, r.Term, m.Type, m.From, m.Term)
  724. }
  725. return nil
  726. }
  727. switch m.Type {
  728. case pb.MsgHup:
  729. if r.state != StateLeader {
  730. ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
  731. if err != nil {
  732. r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
  733. }
  734. if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
  735. r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
  736. return nil
  737. }
  738. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  739. if r.preVote {
  740. r.campaign(campaignPreElection)
  741. } else {
  742. r.campaign(campaignElection)
  743. }
  744. } else {
  745. r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
  746. }
  747. case pb.MsgVote, pb.MsgPreVote:
  748. if r.isLearner {
  749. // TODO: learner may need to vote, in case of node down when confchange.
  750. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored %s from %x [logterm: %d, index: %d] at term %d: learner can not vote",
  751. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  752. return nil
  753. }
  754. // The m.Term > r.Term clause is for MsgPreVote. For MsgVote m.Term should
  755. // always equal r.Term.
  756. if (r.Vote == None || m.Term > r.Term || r.Vote == m.From) && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  757. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
  758. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  759. // When responding to Msg{Pre,}Vote messages we include the term
  760. // from the message, not the local term. To see why consider the
  761. // case where a single node was previously partitioned away and
  762. // it's local term is now of date. If we include the local term
  763. // (recall that for pre-votes we don't update the local term), the
  764. // (pre-)campaigning node on the other end will proceed to ignore
  765. // the message (it ignores all out of date messages).
  766. // The term in the original message and current local term are the
  767. // same in the case of regular votes, but different for pre-votes.
  768. r.send(pb.Message{To: m.From, Term: m.Term, Type: voteRespMsgType(m.Type)})
  769. if m.Type == pb.MsgVote {
  770. // Only record real votes.
  771. r.electionElapsed = 0
  772. r.Vote = m.From
  773. }
  774. } else {
  775. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  776. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  777. r.send(pb.Message{To: m.From, Term: r.Term, Type: voteRespMsgType(m.Type), Reject: true})
  778. }
  779. default:
  780. err := r.step(r, m)
  781. if err != nil {
  782. return err
  783. }
  784. }
  785. return nil
  786. }
  787. type stepFunc func(r *raft, m pb.Message) error
  788. func stepLeader(r *raft, m pb.Message) error {
  789. // These message types do not require any progress for m.From.
  790. switch m.Type {
  791. case pb.MsgBeat:
  792. r.bcastHeartbeat()
  793. return nil
  794. case pb.MsgCheckQuorum:
  795. if !r.checkQuorumActive() {
  796. r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
  797. r.becomeFollower(r.Term, None)
  798. }
  799. return nil
  800. case pb.MsgProp:
  801. if len(m.Entries) == 0 {
  802. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  803. }
  804. if _, ok := r.prs[r.id]; !ok {
  805. // If we are not currently a member of the range (i.e. this node
  806. // was removed from the configuration while serving as leader),
  807. // drop any new proposals.
  808. return ErrProposalDropped
  809. }
  810. if r.leadTransferee != None {
  811. r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
  812. return ErrProposalDropped
  813. }
  814. for i, e := range m.Entries {
  815. if e.Type == pb.EntryConfChange {
  816. if r.pendingConfIndex > r.raftLog.applied {
  817. r.logger.Infof("propose conf %s ignored since pending unapplied configuration [index %d, applied %d]",
  818. e.String(), r.pendingConfIndex, r.raftLog.applied)
  819. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  820. } else {
  821. r.pendingConfIndex = r.raftLog.lastIndex() + uint64(i) + 1
  822. }
  823. }
  824. }
  825. r.appendEntry(m.Entries...)
  826. r.bcastAppend()
  827. return nil
  828. case pb.MsgReadIndex:
  829. if r.quorum() > 1 {
  830. if r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(r.raftLog.committed)) != r.Term {
  831. // Reject read only request when this leader has not committed any log entry at its term.
  832. return nil
  833. }
  834. // thinking: use an interally defined context instead of the user given context.
  835. // We can express this in terms of the term and index instead of a user-supplied value.
  836. // This would allow multiple reads to piggyback on the same message.
  837. switch r.readOnly.option {
  838. case ReadOnlySafe:
  839. r.readOnly.addRequest(r.raftLog.committed, m)
  840. r.bcastHeartbeatWithCtx(m.Entries[0].Data)
  841. case ReadOnlyLeaseBased:
  842. ri := r.raftLog.committed
  843. if m.From == None || m.From == r.id { // from local member
  844. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  845. } else {
  846. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  847. }
  848. }
  849. } else {
  850. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  851. }
  852. return nil
  853. }
  854. // All other message types require a progress for m.From (pr).
  855. pr := r.getProgress(m.From)
  856. if pr == nil {
  857. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  858. return nil
  859. }
  860. switch m.Type {
  861. case pb.MsgAppResp:
  862. pr.RecentActive = true
  863. if m.Reject {
  864. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  865. r.id, m.RejectHint, m.From, m.Index)
  866. if pr.maybeDecrTo(m.Index, m.RejectHint) {
  867. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  868. if pr.State == ProgressStateReplicate {
  869. pr.becomeProbe()
  870. }
  871. r.sendAppend(m.From)
  872. }
  873. } else {
  874. oldPaused := pr.IsPaused()
  875. if pr.maybeUpdate(m.Index) {
  876. switch {
  877. case pr.State == ProgressStateProbe:
  878. pr.becomeReplicate()
  879. case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
  880. r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  881. pr.becomeProbe()
  882. case pr.State == ProgressStateReplicate:
  883. pr.ins.freeTo(m.Index)
  884. }
  885. if r.maybeCommit() {
  886. r.bcastAppend()
  887. } else if oldPaused {
  888. // update() reset the wait state on this node. If we had delayed sending
  889. // an update before, send it now.
  890. r.sendAppend(m.From)
  891. }
  892. // Transfer leadership is in progress.
  893. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  894. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  895. r.sendTimeoutNow(m.From)
  896. }
  897. }
  898. }
  899. case pb.MsgHeartbeatResp:
  900. pr.RecentActive = true
  901. pr.resume()
  902. // free one slot for the full inflights window to allow progress.
  903. if pr.State == ProgressStateReplicate && pr.ins.full() {
  904. pr.ins.freeFirstOne()
  905. }
  906. if pr.Match < r.raftLog.lastIndex() {
  907. r.sendAppend(m.From)
  908. }
  909. if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
  910. return nil
  911. }
  912. ackCount := r.readOnly.recvAck(m)
  913. if ackCount < r.quorum() {
  914. return nil
  915. }
  916. rss := r.readOnly.advance(m)
  917. for _, rs := range rss {
  918. req := rs.req
  919. if req.From == None || req.From == r.id { // from local member
  920. r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
  921. } else {
  922. r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
  923. }
  924. }
  925. case pb.MsgSnapStatus:
  926. if pr.State != ProgressStateSnapshot {
  927. return nil
  928. }
  929. if !m.Reject {
  930. pr.becomeProbe()
  931. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  932. } else {
  933. pr.snapshotFailure()
  934. pr.becomeProbe()
  935. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  936. }
  937. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  938. // out the next msgApp.
  939. // If snapshot failure, wait for a heartbeat interval before next try
  940. pr.pause()
  941. case pb.MsgUnreachable:
  942. // During optimistic replication, if the remote becomes unreachable,
  943. // there is huge probability that a MsgApp is lost.
  944. if pr.State == ProgressStateReplicate {
  945. pr.becomeProbe()
  946. }
  947. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  948. case pb.MsgTransferLeader:
  949. if pr.IsLearner {
  950. r.logger.Debugf("%x is learner. Ignored transferring leadership", r.id)
  951. return nil
  952. }
  953. leadTransferee := m.From
  954. lastLeadTransferee := r.leadTransferee
  955. if lastLeadTransferee != None {
  956. if lastLeadTransferee == leadTransferee {
  957. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  958. r.id, r.Term, leadTransferee, leadTransferee)
  959. return nil
  960. }
  961. r.abortLeaderTransfer()
  962. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  963. }
  964. if leadTransferee == r.id {
  965. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  966. return nil
  967. }
  968. // Transfer leadership to third party.
  969. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  970. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  971. r.electionElapsed = 0
  972. r.leadTransferee = leadTransferee
  973. if pr.Match == r.raftLog.lastIndex() {
  974. r.sendTimeoutNow(leadTransferee)
  975. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  976. } else {
  977. r.sendAppend(leadTransferee)
  978. }
  979. }
  980. return nil
  981. }
  982. // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
  983. // whether they respond to MsgVoteResp or MsgPreVoteResp.
  984. func stepCandidate(r *raft, m pb.Message) error {
  985. // Only handle vote responses corresponding to our candidacy (while in
  986. // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
  987. // our pre-candidate state).
  988. var myVoteRespType pb.MessageType
  989. if r.state == StatePreCandidate {
  990. myVoteRespType = pb.MsgPreVoteResp
  991. } else {
  992. myVoteRespType = pb.MsgVoteResp
  993. }
  994. switch m.Type {
  995. case pb.MsgProp:
  996. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  997. return ErrProposalDropped
  998. case pb.MsgApp:
  999. r.becomeFollower(r.Term, m.From)
  1000. r.handleAppendEntries(m)
  1001. case pb.MsgHeartbeat:
  1002. r.becomeFollower(r.Term, m.From)
  1003. r.handleHeartbeat(m)
  1004. case pb.MsgSnap:
  1005. r.becomeFollower(m.Term, m.From)
  1006. r.handleSnapshot(m)
  1007. case myVoteRespType:
  1008. gr := r.poll(m.From, m.Type, !m.Reject)
  1009. r.logger.Infof("%x [quorum:%d] has received %d %s votes and %d vote rejections", r.id, r.quorum(), gr, m.Type, len(r.votes)-gr)
  1010. switch r.quorum() {
  1011. case gr:
  1012. if r.state == StatePreCandidate {
  1013. r.campaign(campaignElection)
  1014. } else {
  1015. r.becomeLeader()
  1016. r.bcastAppend()
  1017. }
  1018. case len(r.votes) - gr:
  1019. r.becomeFollower(r.Term, None)
  1020. }
  1021. case pb.MsgTimeoutNow:
  1022. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  1023. }
  1024. return nil
  1025. }
  1026. func stepFollower(r *raft, m pb.Message) error {
  1027. switch m.Type {
  1028. case pb.MsgProp:
  1029. if r.lead == None {
  1030. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1031. return ErrProposalDropped
  1032. } else if r.disableProposalForwarding {
  1033. r.logger.Infof("%x not forwarding to leader %x at term %d; dropping proposal", r.id, r.lead, r.Term)
  1034. return ErrProposalDropped
  1035. }
  1036. m.To = r.lead
  1037. r.send(m)
  1038. case pb.MsgApp:
  1039. r.electionElapsed = 0
  1040. r.lead = m.From
  1041. r.handleAppendEntries(m)
  1042. case pb.MsgHeartbeat:
  1043. r.electionElapsed = 0
  1044. r.lead = m.From
  1045. r.handleHeartbeat(m)
  1046. case pb.MsgSnap:
  1047. r.electionElapsed = 0
  1048. r.lead = m.From
  1049. r.handleSnapshot(m)
  1050. case pb.MsgTransferLeader:
  1051. if r.lead == None {
  1052. r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
  1053. return nil
  1054. }
  1055. m.To = r.lead
  1056. r.send(m)
  1057. case pb.MsgTimeoutNow:
  1058. if r.promotable() {
  1059. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  1060. // Leadership transfers never use pre-vote even if r.preVote is true; we
  1061. // know we are not recovering from a partition so there is no need for the
  1062. // extra round trip.
  1063. r.campaign(campaignTransfer)
  1064. } else {
  1065. r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
  1066. }
  1067. case pb.MsgReadIndex:
  1068. if r.lead == None {
  1069. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  1070. return nil
  1071. }
  1072. m.To = r.lead
  1073. r.send(m)
  1074. case pb.MsgReadIndexResp:
  1075. if len(m.Entries) != 1 {
  1076. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  1077. return nil
  1078. }
  1079. r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
  1080. }
  1081. return nil
  1082. }
  1083. func (r *raft) handleAppendEntries(m pb.Message) {
  1084. if m.Index < r.raftLog.committed {
  1085. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1086. return
  1087. }
  1088. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  1089. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  1090. } else {
  1091. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  1092. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  1093. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  1094. }
  1095. }
  1096. func (r *raft) handleHeartbeat(m pb.Message) {
  1097. r.raftLog.commitTo(m.Commit)
  1098. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
  1099. }
  1100. func (r *raft) handleSnapshot(m pb.Message) {
  1101. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  1102. if r.restore(m.Snapshot) {
  1103. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  1104. r.id, r.raftLog.committed, sindex, sterm)
  1105. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  1106. } else {
  1107. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  1108. r.id, r.raftLog.committed, sindex, sterm)
  1109. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1110. }
  1111. }
  1112. // restore recovers the state machine from a snapshot. It restores the log and the
  1113. // configuration of state machine.
  1114. func (r *raft) restore(s pb.Snapshot) bool {
  1115. if s.Metadata.Index <= r.raftLog.committed {
  1116. return false
  1117. }
  1118. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  1119. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  1120. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1121. r.raftLog.commitTo(s.Metadata.Index)
  1122. return false
  1123. }
  1124. // The normal peer can't become learner.
  1125. if !r.isLearner {
  1126. for _, id := range s.Metadata.ConfState.Learners {
  1127. if id == r.id {
  1128. r.logger.Errorf("%x can't become learner when restores snapshot [index: %d, term: %d]", r.id, s.Metadata.Index, s.Metadata.Term)
  1129. return false
  1130. }
  1131. }
  1132. }
  1133. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  1134. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1135. r.raftLog.restore(s)
  1136. r.prs = make(map[uint64]*Progress)
  1137. r.learnerPrs = make(map[uint64]*Progress)
  1138. r.restoreNode(s.Metadata.ConfState.Nodes, false)
  1139. r.restoreNode(s.Metadata.ConfState.Learners, true)
  1140. return true
  1141. }
  1142. func (r *raft) restoreNode(nodes []uint64, isLearner bool) {
  1143. for _, n := range nodes {
  1144. match, next := uint64(0), r.raftLog.lastIndex()+1
  1145. if n == r.id {
  1146. match = next - 1
  1147. r.isLearner = isLearner
  1148. }
  1149. r.setProgress(n, match, next, isLearner)
  1150. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.getProgress(n))
  1151. }
  1152. }
  1153. // promotable indicates whether state machine can be promoted to leader,
  1154. // which is true when its own id is in progress list.
  1155. func (r *raft) promotable() bool {
  1156. _, ok := r.prs[r.id]
  1157. return ok
  1158. }
  1159. func (r *raft) addNode(id uint64) {
  1160. r.addNodeOrLearnerNode(id, false)
  1161. }
  1162. func (r *raft) addLearner(id uint64) {
  1163. r.addNodeOrLearnerNode(id, true)
  1164. }
  1165. func (r *raft) addNodeOrLearnerNode(id uint64, isLearner bool) {
  1166. pr := r.getProgress(id)
  1167. if pr == nil {
  1168. r.setProgress(id, 0, r.raftLog.lastIndex()+1, isLearner)
  1169. } else {
  1170. if isLearner && !pr.IsLearner {
  1171. // can only change Learner to Voter
  1172. r.logger.Infof("%x ignored addLearner: do not support changing %x from raft peer to learner.", r.id, id)
  1173. return
  1174. }
  1175. if isLearner == pr.IsLearner {
  1176. // Ignore any redundant addNode calls (which can happen because the
  1177. // initial bootstrapping entries are applied twice).
  1178. return
  1179. }
  1180. // change Learner to Voter, use origin Learner progress
  1181. delete(r.learnerPrs, id)
  1182. pr.IsLearner = false
  1183. r.prs[id] = pr
  1184. }
  1185. if r.id == id {
  1186. r.isLearner = isLearner
  1187. }
  1188. // When a node is first added, we should mark it as recently active.
  1189. // Otherwise, CheckQuorum may cause us to step down if it is invoked
  1190. // before the added node has a chance to communicate with us.
  1191. pr = r.getProgress(id)
  1192. pr.RecentActive = true
  1193. }
  1194. func (r *raft) removeNode(id uint64) {
  1195. r.delProgress(id)
  1196. // do not try to commit or abort transferring if there is no nodes in the cluster.
  1197. if len(r.prs) == 0 && len(r.learnerPrs) == 0 {
  1198. return
  1199. }
  1200. // The quorum size is now smaller, so see if any pending entries can
  1201. // be committed.
  1202. if r.maybeCommit() {
  1203. r.bcastAppend()
  1204. }
  1205. // If the removed node is the leadTransferee, then abort the leadership transferring.
  1206. if r.state == StateLeader && r.leadTransferee == id {
  1207. r.abortLeaderTransfer()
  1208. }
  1209. }
  1210. func (r *raft) setProgress(id, match, next uint64, isLearner bool) {
  1211. if !isLearner {
  1212. delete(r.learnerPrs, id)
  1213. r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
  1214. return
  1215. }
  1216. if _, ok := r.prs[id]; ok {
  1217. panic(fmt.Sprintf("%x unexpected changing from voter to learner for %x", r.id, id))
  1218. }
  1219. r.learnerPrs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight), IsLearner: true}
  1220. }
  1221. func (r *raft) delProgress(id uint64) {
  1222. delete(r.prs, id)
  1223. delete(r.learnerPrs, id)
  1224. }
  1225. func (r *raft) loadState(state pb.HardState) {
  1226. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  1227. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  1228. }
  1229. r.raftLog.committed = state.Commit
  1230. r.Term = state.Term
  1231. r.Vote = state.Vote
  1232. }
  1233. // pastElectionTimeout returns true iff r.electionElapsed is greater
  1234. // than or equal to the randomized election timeout in
  1235. // [electiontimeout, 2 * electiontimeout - 1].
  1236. func (r *raft) pastElectionTimeout() bool {
  1237. return r.electionElapsed >= r.randomizedElectionTimeout
  1238. }
  1239. func (r *raft) resetRandomizedElectionTimeout() {
  1240. r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
  1241. }
  1242. // checkQuorumActive returns true if the quorum is active from
  1243. // the view of the local raft state machine. Otherwise, it returns
  1244. // false.
  1245. // checkQuorumActive also resets all RecentActive to false.
  1246. func (r *raft) checkQuorumActive() bool {
  1247. var act int
  1248. r.forEachProgress(func(id uint64, pr *Progress) {
  1249. if id == r.id { // self is always active
  1250. act++
  1251. return
  1252. }
  1253. if pr.RecentActive && !pr.IsLearner {
  1254. act++
  1255. }
  1256. pr.RecentActive = false
  1257. })
  1258. return act >= r.quorum()
  1259. }
  1260. func (r *raft) sendTimeoutNow(to uint64) {
  1261. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  1262. }
  1263. func (r *raft) abortLeaderTransfer() {
  1264. r.leadTransferee = None
  1265. }
  1266. func numOfPendingConf(ents []pb.Entry) int {
  1267. n := 0
  1268. for i := range ents {
  1269. if ents[i].Type == pb.EntryConfChange {
  1270. n++
  1271. }
  1272. }
  1273. return n
  1274. }