raft.go 51 KB

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