raft.go 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  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. "go.etcd.io/etcd/raft/confchange"
  26. "go.etcd.io/etcd/raft/quorum"
  27. pb "go.etcd.io/etcd/raft/raftpb"
  28. "go.etcd.io/etcd/raft/tracker"
  29. )
  30. // None is a placeholder node ID used when there is no leader.
  31. const None uint64 = 0
  32. const noLimit = math.MaxUint64
  33. // Possible values for StateType.
  34. const (
  35. StateFollower StateType = iota
  36. StateCandidate
  37. StateLeader
  38. StatePreCandidate
  39. numStates
  40. )
  41. type ReadOnlyOption int
  42. const (
  43. // ReadOnlySafe guarantees the linearizability of the read only request by
  44. // communicating with the quorum. It is the default and suggested option.
  45. ReadOnlySafe ReadOnlyOption = iota
  46. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  47. // relying on the leader lease. It can be affected by clock drift.
  48. // If the clock drift is unbounded, leader might keep the lease longer than it
  49. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  50. // in that case.
  51. ReadOnlyLeaseBased
  52. )
  53. // Possible values for CampaignType
  54. const (
  55. // campaignPreElection represents the first phase of a normal election when
  56. // Config.PreVote is true.
  57. campaignPreElection CampaignType = "CampaignPreElection"
  58. // campaignElection represents a normal (time-based) election (the second phase
  59. // of the election when Config.PreVote is true).
  60. campaignElection CampaignType = "CampaignElection"
  61. // campaignTransfer represents the type of leader transfer
  62. campaignTransfer CampaignType = "CampaignTransfer"
  63. )
  64. // ErrProposalDropped is returned when the proposal is ignored by some cases,
  65. // so that the proposer can be notified and fail fast.
  66. var ErrProposalDropped = errors.New("raft proposal dropped")
  67. // lockedRand is a small wrapper around rand.Rand to provide
  68. // synchronization among multiple raft groups. Only the methods needed
  69. // by the code are exposed (e.g. Intn).
  70. type lockedRand struct {
  71. mu sync.Mutex
  72. rand *rand.Rand
  73. }
  74. func (r *lockedRand) Intn(n int) int {
  75. r.mu.Lock()
  76. v := r.rand.Intn(n)
  77. r.mu.Unlock()
  78. return v
  79. }
  80. var globalRand = &lockedRand{
  81. rand: rand.New(rand.NewSource(time.Now().UnixNano())),
  82. }
  83. // CampaignType represents the type of campaigning
  84. // the reason we use the type of string instead of uint64
  85. // is because it's simpler to compare and fill in raft entries
  86. type CampaignType string
  87. // StateType represents the role of a node in a cluster.
  88. type StateType uint64
  89. var stmap = [...]string{
  90. "StateFollower",
  91. "StateCandidate",
  92. "StateLeader",
  93. "StatePreCandidate",
  94. }
  95. func (st StateType) String() string {
  96. return stmap[uint64(st)]
  97. }
  98. // Config contains the parameters to start a raft.
  99. type Config struct {
  100. // ID is the identity of the local raft. ID cannot be 0.
  101. ID uint64
  102. // peers contains the IDs of all nodes (including self) in the raft cluster. It
  103. // should only be set when starting a new raft cluster. Restarting raft from
  104. // previous configuration will panic if peers is set. peer is private and only
  105. // used for testing right now.
  106. peers []uint64
  107. // learners contains the IDs of all learner nodes (including self if the
  108. // local node is a learner) in the raft cluster. learners only receives
  109. // entries from the leader node. It does not vote or promote itself.
  110. learners []uint64
  111. // ElectionTick is the number of Node.Tick invocations that must pass between
  112. // elections. That is, if a follower does not receive any message from the
  113. // leader of current term before ElectionTick has elapsed, it will become
  114. // candidate and start an election. ElectionTick must be greater than
  115. // HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
  116. // unnecessary leader switching.
  117. ElectionTick int
  118. // HeartbeatTick is the number of Node.Tick invocations that must pass between
  119. // heartbeats. That is, a leader sends heartbeat messages to maintain its
  120. // leadership every HeartbeatTick ticks.
  121. HeartbeatTick int
  122. // Storage is the storage for raft. raft generates entries and states to be
  123. // stored in storage. raft reads the persisted entries and states out of
  124. // Storage when it needs. raft reads out the previous state and configuration
  125. // out of storage when restarting.
  126. Storage Storage
  127. // Applied is the last applied index. It should only be set when restarting
  128. // raft. raft will not return entries to the application smaller or equal to
  129. // Applied. If Applied is unset when restarting, raft might return previous
  130. // applied entries. This is a very application dependent configuration.
  131. Applied uint64
  132. // MaxSizePerMsg limits the max byte size of each append message. Smaller
  133. // value lowers the raft recovery cost(initial probing and message lost
  134. // during normal operation). On the other side, it might affect the
  135. // throughput during normal replication. Note: math.MaxUint64 for unlimited,
  136. // 0 for at most one entry per message.
  137. MaxSizePerMsg uint64
  138. // MaxCommittedSizePerReady limits the size of the committed entries which
  139. // can be applied.
  140. MaxCommittedSizePerReady uint64
  141. // MaxUncommittedEntriesSize limits the aggregate byte size of the
  142. // uncommitted entries that may be appended to a leader's log. Once this
  143. // limit is exceeded, proposals will begin to return ErrProposalDropped
  144. // errors. Note: 0 for no limit.
  145. MaxUncommittedEntriesSize uint64
  146. // MaxInflightMsgs limits the max number of in-flight append messages during
  147. // optimistic replication phase. The application transportation layer usually
  148. // has its own sending buffer over TCP/UDP. Setting MaxInflightMsgs to avoid
  149. // overflowing that sending buffer. TODO (xiangli): feedback to application to
  150. // limit the proposal rate?
  151. MaxInflightMsgs int
  152. // CheckQuorum specifies if the leader should check quorum activity. Leader
  153. // steps down when quorum is not active for an electionTimeout.
  154. CheckQuorum bool
  155. // PreVote enables the Pre-Vote algorithm described in raft thesis section
  156. // 9.6. This prevents disruption when a node that has been partitioned away
  157. // rejoins the cluster.
  158. PreVote bool
  159. // ReadOnlyOption specifies how the read only request is processed.
  160. //
  161. // ReadOnlySafe guarantees the linearizability of the read only request by
  162. // communicating with the quorum. It is the default and suggested option.
  163. //
  164. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  165. // relying on the leader lease. It can be affected by clock drift.
  166. // If the clock drift is unbounded, leader might keep the lease longer than it
  167. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  168. // in that case.
  169. // CheckQuorum MUST be enabled if ReadOnlyOption is ReadOnlyLeaseBased.
  170. ReadOnlyOption ReadOnlyOption
  171. // Logger is the logger used for raft log. For multinode which can host
  172. // multiple raft group, each raft group can have its own logger
  173. Logger Logger
  174. // DisableProposalForwarding set to true means that followers will drop
  175. // proposals, rather than forwarding them to the leader. One use case for
  176. // this feature would be in a situation where the Raft leader is used to
  177. // compute the data of a proposal, for example, adding a timestamp from a
  178. // hybrid logical clock to data in a monotonically increasing way. Forwarding
  179. // should be disabled to prevent a follower with an inaccurate hybrid
  180. // logical clock from assigning the timestamp and then forwarding the data
  181. // to the leader.
  182. DisableProposalForwarding bool
  183. }
  184. func (c *Config) validate() error {
  185. if c.ID == None {
  186. return errors.New("cannot use none as id")
  187. }
  188. if c.HeartbeatTick <= 0 {
  189. return errors.New("heartbeat tick must be greater than 0")
  190. }
  191. if c.ElectionTick <= c.HeartbeatTick {
  192. return errors.New("election tick must be greater than heartbeat tick")
  193. }
  194. if c.Storage == nil {
  195. return errors.New("storage cannot be nil")
  196. }
  197. if c.MaxUncommittedEntriesSize == 0 {
  198. c.MaxUncommittedEntriesSize = noLimit
  199. }
  200. // default MaxCommittedSizePerReady to MaxSizePerMsg because they were
  201. // previously the same parameter.
  202. if c.MaxCommittedSizePerReady == 0 {
  203. c.MaxCommittedSizePerReady = c.MaxSizePerMsg
  204. }
  205. if c.MaxInflightMsgs <= 0 {
  206. return errors.New("max inflight messages must be greater than 0")
  207. }
  208. if c.Logger == nil {
  209. c.Logger = raftLogger
  210. }
  211. if c.ReadOnlyOption == ReadOnlyLeaseBased && !c.CheckQuorum {
  212. return errors.New("CheckQuorum must be enabled when ReadOnlyOption is ReadOnlyLeaseBased")
  213. }
  214. return nil
  215. }
  216. type raft struct {
  217. id uint64
  218. Term uint64
  219. Vote uint64
  220. readStates []ReadState
  221. // the log
  222. raftLog *raftLog
  223. maxMsgSize uint64
  224. maxUncommittedSize uint64
  225. // TODO(tbg): rename to trk.
  226. prs tracker.ProgressTracker
  227. state StateType
  228. // isLearner is true if the local raft node is a learner.
  229. isLearner bool
  230. msgs []pb.Message
  231. // the leader id
  232. lead uint64
  233. // leadTransferee is id of the leader transfer target when its value is not zero.
  234. // Follow the procedure defined in raft thesis 3.10.
  235. leadTransferee uint64
  236. // Only one conf change may be pending (in the log, but not yet
  237. // applied) at a time. This is enforced via pendingConfIndex, which
  238. // is set to a value >= the log index of the latest pending
  239. // configuration change (if any). Config changes are only allowed to
  240. // be proposed if the leader's applied index is greater than this
  241. // value.
  242. pendingConfIndex uint64
  243. // an estimate of the size of the uncommitted tail of the Raft log. Used to
  244. // prevent unbounded log growth. Only maintained by the leader. Reset on
  245. // term changes.
  246. uncommittedSize uint64
  247. readOnly *readOnly
  248. // number of ticks since it reached last electionTimeout when it is leader
  249. // or candidate.
  250. // number of ticks since it reached last electionTimeout or received a
  251. // valid message from current leader when it is a follower.
  252. electionElapsed int
  253. // number of ticks since it reached last heartbeatTimeout.
  254. // only leader keeps heartbeatElapsed.
  255. heartbeatElapsed int
  256. checkQuorum bool
  257. preVote bool
  258. heartbeatTimeout int
  259. electionTimeout int
  260. // randomizedElectionTimeout is a random number between
  261. // [electiontimeout, 2 * electiontimeout - 1]. It gets reset
  262. // when raft changes its state to follower or candidate.
  263. randomizedElectionTimeout int
  264. disableProposalForwarding bool
  265. tick func()
  266. step stepFunc
  267. logger Logger
  268. }
  269. func newRaft(c *Config) *raft {
  270. if err := c.validate(); err != nil {
  271. panic(err.Error())
  272. }
  273. raftlog := newLogWithSize(c.Storage, c.Logger, c.MaxCommittedSizePerReady)
  274. hs, cs, err := c.Storage.InitialState()
  275. if err != nil {
  276. panic(err) // TODO(bdarnell)
  277. }
  278. if len(c.peers) > 0 || len(c.learners) > 0 {
  279. if len(cs.Voters) > 0 || len(cs.Learners) > 0 {
  280. // TODO(bdarnell): the peers argument is always nil except in
  281. // tests; the argument should be removed and these tests should be
  282. // updated to specify their nodes through a snapshot.
  283. panic("cannot specify both newRaft(peers, learners) and ConfState.(Voters, Learners)")
  284. }
  285. cs.Voters = c.peers
  286. cs.Learners = c.learners
  287. }
  288. r := &raft{
  289. id: c.ID,
  290. lead: None,
  291. isLearner: false,
  292. raftLog: raftlog,
  293. maxMsgSize: c.MaxSizePerMsg,
  294. maxUncommittedSize: c.MaxUncommittedEntriesSize,
  295. prs: tracker.MakeProgressTracker(c.MaxInflightMsgs),
  296. electionTimeout: c.ElectionTick,
  297. heartbeatTimeout: c.HeartbeatTick,
  298. logger: c.Logger,
  299. checkQuorum: c.CheckQuorum,
  300. preVote: c.PreVote,
  301. readOnly: newReadOnly(c.ReadOnlyOption),
  302. disableProposalForwarding: c.DisableProposalForwarding,
  303. }
  304. cfg, prs, err := confchange.Restore(confchange.Changer{
  305. Tracker: r.prs,
  306. LastIndex: raftlog.lastIndex(),
  307. }, cs)
  308. if err != nil {
  309. panic(err)
  310. }
  311. assertConfStatesEquivalent(r.logger, cs, r.switchToConfig(cfg, prs))
  312. if !IsEmptyHardState(hs) {
  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.Progress[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 StateReplicate
  423. case tracker.StateReplicate:
  424. last := m.Entries[n-1].Index
  425. pr.OptimisticUpdate(last)
  426. pr.Inflights.Add(last)
  427. case tracker.StateProbe:
  428. pr.ProbeSent = true
  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.Progress[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, _ *tracker.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, _ *tracker.Progress) {
  475. if id == r.id {
  476. return
  477. }
  478. r.sendHeartbeat(id, ctx)
  479. })
  480. }
  481. func (r *raft) advance(rd Ready) {
  482. // If entries were applied (or a snapshot), update our cursor for
  483. // the next Ready. Note that if the current HardState contains a
  484. // new Commit index, this does not mean that we're also applying
  485. // all of the new entries due to commit pagination by size.
  486. if index := rd.appliedCursor(); index > 0 {
  487. r.raftLog.appliedTo(index)
  488. if r.prs.Config.AutoLeave && index >= r.pendingConfIndex && r.state == StateLeader {
  489. // If the current (and most recent, at least for this leader's term)
  490. // configuration should be auto-left, initiate that now.
  491. ccdata, err := (&pb.ConfChangeV2{}).Marshal()
  492. if err != nil {
  493. panic(err)
  494. }
  495. ent := pb.Entry{
  496. Type: pb.EntryConfChangeV2,
  497. Data: ccdata,
  498. }
  499. if !r.appendEntry(ent) {
  500. // If we could not append the entry, bump the pending conf index
  501. // so that we'll try again later.
  502. //
  503. // TODO(tbg): test this case.
  504. r.pendingConfIndex = r.raftLog.lastIndex()
  505. } else {
  506. r.logger.Infof("initiating automatic transition out of joint configuration %s", r.prs.Config)
  507. }
  508. }
  509. }
  510. r.reduceUncommittedSize(rd.CommittedEntries)
  511. if len(rd.Entries) > 0 {
  512. e := rd.Entries[len(rd.Entries)-1]
  513. r.raftLog.stableTo(e.Index, e.Term)
  514. }
  515. if !IsEmptySnap(rd.Snapshot) {
  516. r.raftLog.stableSnapTo(rd.Snapshot.Metadata.Index)
  517. }
  518. }
  519. // maybeCommit attempts to advance the commit index. Returns true if
  520. // the commit index changed (in which case the caller should call
  521. // r.bcastAppend).
  522. func (r *raft) maybeCommit() bool {
  523. mci := r.prs.Committed()
  524. return r.raftLog.maybeCommit(mci, r.Term)
  525. }
  526. func (r *raft) reset(term uint64) {
  527. if r.Term != term {
  528. r.Term = term
  529. r.Vote = None
  530. }
  531. r.lead = None
  532. r.electionElapsed = 0
  533. r.heartbeatElapsed = 0
  534. r.resetRandomizedElectionTimeout()
  535. r.abortLeaderTransfer()
  536. r.prs.ResetVotes()
  537. r.prs.Visit(func(id uint64, pr *tracker.Progress) {
  538. *pr = tracker.Progress{
  539. Match: 0,
  540. Next: r.raftLog.lastIndex() + 1,
  541. Inflights: tracker.NewInflights(r.prs.MaxInflight),
  542. IsLearner: pr.IsLearner,
  543. }
  544. if id == r.id {
  545. pr.Match = r.raftLog.lastIndex()
  546. }
  547. })
  548. r.pendingConfIndex = 0
  549. r.uncommittedSize = 0
  550. r.readOnly = newReadOnly(r.readOnly.option)
  551. }
  552. func (r *raft) appendEntry(es ...pb.Entry) (accepted bool) {
  553. li := r.raftLog.lastIndex()
  554. for i := range es {
  555. es[i].Term = r.Term
  556. es[i].Index = li + 1 + uint64(i)
  557. }
  558. // Track the size of this uncommitted proposal.
  559. if !r.increaseUncommittedSize(es) {
  560. r.logger.Debugf(
  561. "%x appending new entries to log would exceed uncommitted entry size limit; dropping proposal",
  562. r.id,
  563. )
  564. // Drop the proposal.
  565. return false
  566. }
  567. // use latest "last" index after truncate/append
  568. li = r.raftLog.append(es...)
  569. r.prs.Progress[r.id].MaybeUpdate(li)
  570. // Regardless of maybeCommit's return, our caller will call bcastAppend.
  571. r.maybeCommit()
  572. return true
  573. }
  574. // tickElection is run by followers and candidates after r.electionTimeout.
  575. func (r *raft) tickElection() {
  576. r.electionElapsed++
  577. if r.promotable() && r.pastElectionTimeout() {
  578. r.electionElapsed = 0
  579. r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
  580. }
  581. }
  582. // tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
  583. func (r *raft) tickHeartbeat() {
  584. r.heartbeatElapsed++
  585. r.electionElapsed++
  586. if r.electionElapsed >= r.electionTimeout {
  587. r.electionElapsed = 0
  588. if r.checkQuorum {
  589. r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
  590. }
  591. // If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
  592. if r.state == StateLeader && r.leadTransferee != None {
  593. r.abortLeaderTransfer()
  594. }
  595. }
  596. if r.state != StateLeader {
  597. return
  598. }
  599. if r.heartbeatElapsed >= r.heartbeatTimeout {
  600. r.heartbeatElapsed = 0
  601. r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
  602. }
  603. }
  604. func (r *raft) becomeFollower(term uint64, lead uint64) {
  605. r.step = stepFollower
  606. r.reset(term)
  607. r.tick = r.tickElection
  608. r.lead = lead
  609. r.state = StateFollower
  610. r.logger.Infof("%x became follower at term %d", r.id, r.Term)
  611. }
  612. func (r *raft) becomeCandidate() {
  613. // TODO(xiangli) remove the panic when the raft implementation is stable
  614. if r.state == StateLeader {
  615. panic("invalid transition [leader -> candidate]")
  616. }
  617. r.step = stepCandidate
  618. r.reset(r.Term + 1)
  619. r.tick = r.tickElection
  620. r.Vote = r.id
  621. r.state = StateCandidate
  622. r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
  623. }
  624. func (r *raft) becomePreCandidate() {
  625. // TODO(xiangli) remove the panic when the raft implementation is stable
  626. if r.state == StateLeader {
  627. panic("invalid transition [leader -> pre-candidate]")
  628. }
  629. // Becoming a pre-candidate changes our step functions and state,
  630. // but doesn't change anything else. In particular it does not increase
  631. // r.Term or change r.Vote.
  632. r.step = stepCandidate
  633. r.prs.ResetVotes()
  634. r.tick = r.tickElection
  635. r.lead = None
  636. r.state = StatePreCandidate
  637. r.logger.Infof("%x became pre-candidate at term %d", r.id, r.Term)
  638. }
  639. func (r *raft) becomeLeader() {
  640. // TODO(xiangli) remove the panic when the raft implementation is stable
  641. if r.state == StateFollower {
  642. panic("invalid transition [follower -> leader]")
  643. }
  644. r.step = stepLeader
  645. r.reset(r.Term)
  646. r.tick = r.tickHeartbeat
  647. r.lead = r.id
  648. r.state = StateLeader
  649. // Followers enter replicate mode when they've been successfully probed
  650. // (perhaps after having received a snapshot as a result). The leader is
  651. // trivially in this state. Note that r.reset() has initialized this
  652. // progress with the last index already.
  653. r.prs.Progress[r.id].BecomeReplicate()
  654. // Conservatively set the pendingConfIndex to the last index in the
  655. // log. There may or may not be a pending config change, but it's
  656. // safe to delay any future proposals until we commit all our
  657. // pending log entries, and scanning the entire tail of the log
  658. // could be expensive.
  659. r.pendingConfIndex = r.raftLog.lastIndex()
  660. emptyEnt := pb.Entry{Data: nil}
  661. if !r.appendEntry(emptyEnt) {
  662. // This won't happen because we just called reset() above.
  663. r.logger.Panic("empty entry was dropped")
  664. }
  665. // As a special case, don't count the initial empty entry towards the
  666. // uncommitted log quota. This is because we want to preserve the
  667. // behavior of allowing one entry larger than quota if the current
  668. // usage is zero.
  669. r.reduceUncommittedSize([]pb.Entry{emptyEnt})
  670. r.logger.Infof("%x became leader at term %d", r.id, r.Term)
  671. }
  672. // campaign transitions the raft instance to candidate state. This must only be
  673. // called after verifying that this is a legitimate transition.
  674. func (r *raft) campaign(t CampaignType) {
  675. if !r.promotable() {
  676. // This path should not be hit (callers are supposed to check), but
  677. // better safe than sorry.
  678. r.logger.Warningf("%x is unpromotable; campaign() should have been called", r.id)
  679. }
  680. var term uint64
  681. var voteMsg pb.MessageType
  682. if t == campaignPreElection {
  683. r.becomePreCandidate()
  684. voteMsg = pb.MsgPreVote
  685. // PreVote RPCs are sent for the next term before we've incremented r.Term.
  686. term = r.Term + 1
  687. } else {
  688. r.becomeCandidate()
  689. voteMsg = pb.MsgVote
  690. term = r.Term
  691. }
  692. if _, _, res := r.poll(r.id, voteRespMsgType(voteMsg), true); res == quorum.VoteWon {
  693. // We won the election after voting for ourselves (which must mean that
  694. // this is a single-node cluster). Advance to the next state.
  695. if t == campaignPreElection {
  696. r.campaign(campaignElection)
  697. } else {
  698. r.becomeLeader()
  699. }
  700. return
  701. }
  702. var ids []uint64
  703. {
  704. idMap := r.prs.Voters.IDs()
  705. ids = make([]uint64, 0, len(idMap))
  706. for id := range idMap {
  707. ids = append(ids, id)
  708. }
  709. sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
  710. }
  711. for _, id := range ids {
  712. if id == r.id {
  713. continue
  714. }
  715. r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
  716. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
  717. var ctx []byte
  718. if t == campaignTransfer {
  719. ctx = []byte(t)
  720. }
  721. r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
  722. }
  723. }
  724. func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int, rejected int, result quorum.VoteResult) {
  725. if v {
  726. r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
  727. } else {
  728. r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
  729. }
  730. r.prs.RecordVote(id, v)
  731. return r.prs.TallyVotes()
  732. }
  733. func (r *raft) Step(m pb.Message) error {
  734. // Handle the message term, which may result in our stepping down to a follower.
  735. switch {
  736. case m.Term == 0:
  737. // local message
  738. case m.Term > r.Term:
  739. if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
  740. force := bytes.Equal(m.Context, []byte(campaignTransfer))
  741. inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
  742. if !force && inLease {
  743. // If a server receives a RequestVote request within the minimum election timeout
  744. // of hearing from a current leader, it does not update its term or grant its vote
  745. 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)",
  746. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
  747. return nil
  748. }
  749. }
  750. switch {
  751. case m.Type == pb.MsgPreVote:
  752. // Never change our term in response to a PreVote
  753. case m.Type == pb.MsgPreVoteResp && !m.Reject:
  754. // We send pre-vote requests with a term in our future. If the
  755. // pre-vote is granted, we will increment our term when we get a
  756. // quorum. If it is not, the term comes from the node that
  757. // rejected our vote so we should become a follower at the new
  758. // term.
  759. default:
  760. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  761. r.id, r.Term, m.Type, m.From, m.Term)
  762. if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap {
  763. r.becomeFollower(m.Term, m.From)
  764. } else {
  765. r.becomeFollower(m.Term, None)
  766. }
  767. }
  768. case m.Term < r.Term:
  769. if (r.checkQuorum || r.preVote) && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
  770. // We have received messages from a leader at a lower term. It is possible
  771. // that these messages were simply delayed in the network, but this could
  772. // also mean that this node has advanced its term number during a network
  773. // partition, and it is now unable to either win an election or to rejoin
  774. // the majority on the old term. If checkQuorum is false, this will be
  775. // handled by incrementing term numbers in response to MsgVote with a
  776. // higher term, but if checkQuorum is true we may not advance the term on
  777. // MsgVote and must generate other messages to advance the term. The net
  778. // result of these two features is to minimize the disruption caused by
  779. // nodes that have been removed from the cluster's configuration: a
  780. // removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
  781. // but it will not receive MsgApp or MsgHeartbeat, so it will not create
  782. // disruptive term increases, by notifying leader of this node's activeness.
  783. // The above comments also true for Pre-Vote
  784. //
  785. // When follower gets isolated, it soon starts an election ending
  786. // up with a higher term than leader, although it won't receive enough
  787. // votes to win the election. When it regains connectivity, this response
  788. // with "pb.MsgAppResp" of higher term would force leader to step down.
  789. // However, this disruption is inevitable to free this stuck node with
  790. // fresh election. This can be prevented with Pre-Vote phase.
  791. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
  792. } else if m.Type == pb.MsgPreVote {
  793. // Before Pre-Vote enable, there may have candidate with higher term,
  794. // but less log. After update to Pre-Vote, the cluster may deadlock if
  795. // we drop messages with a lower term.
  796. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  797. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  798. r.send(pb.Message{To: m.From, Term: r.Term, Type: pb.MsgPreVoteResp, Reject: true})
  799. } else {
  800. // ignore other cases
  801. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  802. r.id, r.Term, m.Type, m.From, m.Term)
  803. }
  804. return nil
  805. }
  806. switch m.Type {
  807. case pb.MsgHup:
  808. if r.state != StateLeader {
  809. if !r.promotable() {
  810. r.logger.Warningf("%x is unpromotable and can not campaign; ignoring MsgHup", r.id)
  811. return nil
  812. }
  813. ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
  814. if err != nil {
  815. r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
  816. }
  817. if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
  818. r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
  819. return nil
  820. }
  821. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  822. if r.preVote {
  823. r.campaign(campaignPreElection)
  824. } else {
  825. r.campaign(campaignElection)
  826. }
  827. } else {
  828. r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
  829. }
  830. case pb.MsgVote, pb.MsgPreVote:
  831. // We can vote if this is a repeat of a vote we've already cast...
  832. canVote := r.Vote == m.From ||
  833. // ...we haven't voted and we don't think there's a leader yet in this term...
  834. (r.Vote == None && r.lead == None) ||
  835. // ...or this is a PreVote for a future term...
  836. (m.Type == pb.MsgPreVote && m.Term > r.Term)
  837. // ...and we believe the candidate is up to date.
  838. if canVote && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  839. // Note: it turns out that that learners must be allowed to cast votes.
  840. // This seems counter- intuitive but is necessary in the situation in which
  841. // a learner has been promoted (i.e. is now a voter) but has not learned
  842. // about this yet.
  843. // For example, consider a group in which id=1 is a learner and id=2 and
  844. // id=3 are voters. A configuration change promoting 1 can be committed on
  845. // the quorum `{2,3}` without the config change being appended to the
  846. // learner's log. If the leader (say 2) fails, there are de facto two
  847. // voters remaining. Only 3 can win an election (due to its log containing
  848. // all committed entries), but to do so it will need 1 to vote. But 1
  849. // considers itself a learner and will continue to do so until 3 has
  850. // stepped up as leader, replicates the conf change to 1, and 1 applies it.
  851. // Ultimately, by receiving a request to vote, the learner realizes that
  852. // the candidate believes it to be a voter, and that it should act
  853. // accordingly. The candidate's config may be stale, too; but in that case
  854. // it won't win the election, at least in the absence of the bug discussed
  855. // in:
  856. // https://github.com/etcd-io/etcd/issues/7625#issuecomment-488798263.
  857. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
  858. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  859. // When responding to Msg{Pre,}Vote messages we include the term
  860. // from the message, not the local term. To see why, consider the
  861. // case where a single node was previously partitioned away and
  862. // it's local term is now out of date. If we include the local term
  863. // (recall that for pre-votes we don't update the local term), the
  864. // (pre-)campaigning node on the other end will proceed to ignore
  865. // the message (it ignores all out of date messages).
  866. // The term in the original message and current local term are the
  867. // same in the case of regular votes, but different for pre-votes.
  868. r.send(pb.Message{To: m.From, Term: m.Term, Type: voteRespMsgType(m.Type)})
  869. if m.Type == pb.MsgVote {
  870. // Only record real votes.
  871. r.electionElapsed = 0
  872. r.Vote = m.From
  873. }
  874. } else {
  875. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  876. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  877. r.send(pb.Message{To: m.From, Term: r.Term, Type: voteRespMsgType(m.Type), Reject: true})
  878. }
  879. default:
  880. err := r.step(r, m)
  881. if err != nil {
  882. return err
  883. }
  884. }
  885. return nil
  886. }
  887. type stepFunc func(r *raft, m pb.Message) error
  888. func stepLeader(r *raft, m pb.Message) error {
  889. // These message types do not require any progress for m.From.
  890. switch m.Type {
  891. case pb.MsgBeat:
  892. r.bcastHeartbeat()
  893. return nil
  894. case pb.MsgCheckQuorum:
  895. // The leader should always see itself as active. As a precaution, handle
  896. // the case in which the leader isn't in the configuration any more (for
  897. // example if it just removed itself).
  898. //
  899. // TODO(tbg): I added a TODO in removeNode, it doesn't seem that the
  900. // leader steps down when removing itself. I might be missing something.
  901. if pr := r.prs.Progress[r.id]; pr != nil {
  902. pr.RecentActive = true
  903. }
  904. if !r.prs.QuorumActive() {
  905. r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
  906. r.becomeFollower(r.Term, None)
  907. }
  908. // Mark everyone (but ourselves) as inactive in preparation for the next
  909. // CheckQuorum.
  910. r.prs.Visit(func(id uint64, pr *tracker.Progress) {
  911. if id != r.id {
  912. pr.RecentActive = false
  913. }
  914. })
  915. return nil
  916. case pb.MsgProp:
  917. if len(m.Entries) == 0 {
  918. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  919. }
  920. if r.prs.Progress[r.id] == nil {
  921. // If we are not currently a member of the range (i.e. this node
  922. // was removed from the configuration while serving as leader),
  923. // drop any new proposals.
  924. return ErrProposalDropped
  925. }
  926. if r.leadTransferee != None {
  927. r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
  928. return ErrProposalDropped
  929. }
  930. for i := range m.Entries {
  931. e := &m.Entries[i]
  932. var cc pb.ConfChangeI
  933. if e.Type == pb.EntryConfChange {
  934. var ccc pb.ConfChange
  935. if err := ccc.Unmarshal(e.Data); err != nil {
  936. panic(err)
  937. }
  938. cc = ccc
  939. } else if e.Type == pb.EntryConfChangeV2 {
  940. var ccc pb.ConfChangeV2
  941. if err := ccc.Unmarshal(e.Data); err != nil {
  942. panic(err)
  943. }
  944. cc = ccc
  945. }
  946. if cc != nil {
  947. alreadyPending := r.pendingConfIndex > r.raftLog.applied
  948. alreadyJoint := len(r.prs.Config.Voters[1]) > 0
  949. wantsLeaveJoint := len(cc.AsV2().Changes) == 0
  950. var refused string
  951. if alreadyPending {
  952. refused = fmt.Sprintf("possible unapplied conf change at index %d (applied to %d)", r.pendingConfIndex, r.raftLog.applied)
  953. } else if alreadyJoint && !wantsLeaveJoint {
  954. refused = "must transition out of joint config first"
  955. } else if !alreadyJoint && wantsLeaveJoint {
  956. refused = "not in joint state; refusing empty conf change"
  957. }
  958. if refused != "" {
  959. r.logger.Infof("%x ignoring conf change %v at config %s: %s", r.id, cc, r.prs.Config, refused)
  960. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  961. } else {
  962. r.pendingConfIndex = r.raftLog.lastIndex() + uint64(i) + 1
  963. }
  964. }
  965. }
  966. if !r.appendEntry(m.Entries...) {
  967. return ErrProposalDropped
  968. }
  969. r.bcastAppend()
  970. return nil
  971. case pb.MsgReadIndex:
  972. // If more than the local vote is needed, go through a full broadcast,
  973. // otherwise optimize.
  974. if !r.prs.IsSingleton() {
  975. if r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(r.raftLog.committed)) != r.Term {
  976. // Reject read only request when this leader has not committed any log entry at its term.
  977. return nil
  978. }
  979. // thinking: use an interally defined context instead of the user given context.
  980. // We can express this in terms of the term and index instead of a user-supplied value.
  981. // This would allow multiple reads to piggyback on the same message.
  982. switch r.readOnly.option {
  983. case ReadOnlySafe:
  984. r.readOnly.addRequest(r.raftLog.committed, m)
  985. // The local node automatically acks the request.
  986. r.readOnly.recvAck(r.id, m.Entries[0].Data)
  987. r.bcastHeartbeatWithCtx(m.Entries[0].Data)
  988. case ReadOnlyLeaseBased:
  989. ri := r.raftLog.committed
  990. if m.From == None || m.From == r.id { // from local member
  991. r.readStates = append(r.readStates, ReadState{Index: ri, RequestCtx: m.Entries[0].Data})
  992. } else {
  993. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  994. }
  995. }
  996. } else { // only one voting member (the leader) in the cluster
  997. if m.From == None || m.From == r.id { // from leader itself
  998. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  999. } else { // from learner member
  1000. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: r.raftLog.committed, Entries: m.Entries})
  1001. }
  1002. }
  1003. return nil
  1004. }
  1005. // All other message types require a progress for m.From (pr).
  1006. pr := r.prs.Progress[m.From]
  1007. if pr == nil {
  1008. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  1009. return nil
  1010. }
  1011. switch m.Type {
  1012. case pb.MsgAppResp:
  1013. pr.RecentActive = true
  1014. if m.Reject {
  1015. r.logger.Debugf("%x received MsgAppResp(MsgApp was rejected, lastindex: %d) from %x for index %d",
  1016. r.id, m.RejectHint, m.From, m.Index)
  1017. if pr.MaybeDecrTo(m.Index, m.RejectHint) {
  1018. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  1019. if pr.State == tracker.StateReplicate {
  1020. pr.BecomeProbe()
  1021. }
  1022. r.sendAppend(m.From)
  1023. }
  1024. } else {
  1025. oldPaused := pr.IsPaused()
  1026. if pr.MaybeUpdate(m.Index) {
  1027. switch {
  1028. case pr.State == tracker.StateProbe:
  1029. pr.BecomeReplicate()
  1030. case pr.State == tracker.StateSnapshot && pr.Match >= pr.PendingSnapshot:
  1031. // TODO(tbg): we should also enter this branch if a snapshot is
  1032. // received that is below pr.PendingSnapshot but which makes it
  1033. // possible to use the log again.
  1034. r.logger.Debugf("%x recovered from needing snapshot, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  1035. // Transition back to replicating state via probing state
  1036. // (which takes the snapshot into account). If we didn't
  1037. // move to replicating state, that would only happen with
  1038. // the next round of appends (but there may not be a next
  1039. // round for a while, exposing an inconsistent RaftStatus).
  1040. pr.BecomeProbe()
  1041. pr.BecomeReplicate()
  1042. case pr.State == tracker.StateReplicate:
  1043. pr.Inflights.FreeLE(m.Index)
  1044. }
  1045. if r.maybeCommit() {
  1046. r.bcastAppend()
  1047. } else if oldPaused {
  1048. // If we were paused before, this node may be missing the
  1049. // latest commit index, so send it.
  1050. r.sendAppend(m.From)
  1051. }
  1052. // We've updated flow control information above, which may
  1053. // allow us to send multiple (size-limited) in-flight messages
  1054. // at once (such as when transitioning from probe to
  1055. // replicate, or when freeTo() covers multiple messages). If
  1056. // we have more entries to send, send as many messages as we
  1057. // can (without sending empty messages for the commit index)
  1058. for r.maybeSendAppend(m.From, false) {
  1059. }
  1060. // Transfer leadership is in progress.
  1061. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  1062. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  1063. r.sendTimeoutNow(m.From)
  1064. }
  1065. }
  1066. }
  1067. case pb.MsgHeartbeatResp:
  1068. pr.RecentActive = true
  1069. pr.ProbeSent = false
  1070. // free one slot for the full inflights window to allow progress.
  1071. if pr.State == tracker.StateReplicate && pr.Inflights.Full() {
  1072. pr.Inflights.FreeFirstOne()
  1073. }
  1074. if pr.Match < r.raftLog.lastIndex() {
  1075. r.sendAppend(m.From)
  1076. }
  1077. if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
  1078. return nil
  1079. }
  1080. if r.prs.Voters.VoteResult(r.readOnly.recvAck(m.From, m.Context)) != quorum.VoteWon {
  1081. return nil
  1082. }
  1083. rss := r.readOnly.advance(m)
  1084. for _, rs := range rss {
  1085. req := rs.req
  1086. if req.From == None || req.From == r.id { // from local member
  1087. r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
  1088. } else {
  1089. r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
  1090. }
  1091. }
  1092. case pb.MsgSnapStatus:
  1093. if pr.State != tracker.StateSnapshot {
  1094. return nil
  1095. }
  1096. // TODO(tbg): this code is very similar to the snapshot handling in
  1097. // MsgAppResp above. In fact, the code there is more correct than the
  1098. // code here and should likely be updated to match (or even better, the
  1099. // logic pulled into a newly created Progress state machine handler).
  1100. if !m.Reject {
  1101. pr.BecomeProbe()
  1102. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  1103. } else {
  1104. // NB: the order here matters or we'll be probing erroneously from
  1105. // the snapshot index, but the snapshot never applied.
  1106. pr.PendingSnapshot = 0
  1107. pr.BecomeProbe()
  1108. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  1109. }
  1110. // If snapshot finish, wait for the MsgAppResp from the remote node before sending
  1111. // out the next MsgApp.
  1112. // If snapshot failure, wait for a heartbeat interval before next try
  1113. pr.ProbeSent = true
  1114. case pb.MsgUnreachable:
  1115. // During optimistic replication, if the remote becomes unreachable,
  1116. // there is huge probability that a MsgApp is lost.
  1117. if pr.State == tracker.StateReplicate {
  1118. pr.BecomeProbe()
  1119. }
  1120. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  1121. case pb.MsgTransferLeader:
  1122. if pr.IsLearner {
  1123. r.logger.Debugf("%x is learner. Ignored transferring leadership", r.id)
  1124. return nil
  1125. }
  1126. leadTransferee := m.From
  1127. lastLeadTransferee := r.leadTransferee
  1128. if lastLeadTransferee != None {
  1129. if lastLeadTransferee == leadTransferee {
  1130. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  1131. r.id, r.Term, leadTransferee, leadTransferee)
  1132. return nil
  1133. }
  1134. r.abortLeaderTransfer()
  1135. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  1136. }
  1137. if leadTransferee == r.id {
  1138. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  1139. return nil
  1140. }
  1141. // Transfer leadership to third party.
  1142. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  1143. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  1144. r.electionElapsed = 0
  1145. r.leadTransferee = leadTransferee
  1146. if pr.Match == r.raftLog.lastIndex() {
  1147. r.sendTimeoutNow(leadTransferee)
  1148. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  1149. } else {
  1150. r.sendAppend(leadTransferee)
  1151. }
  1152. }
  1153. return nil
  1154. }
  1155. // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
  1156. // whether they respond to MsgVoteResp or MsgPreVoteResp.
  1157. func stepCandidate(r *raft, m pb.Message) error {
  1158. // Only handle vote responses corresponding to our candidacy (while in
  1159. // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
  1160. // our pre-candidate state).
  1161. var myVoteRespType pb.MessageType
  1162. if r.state == StatePreCandidate {
  1163. myVoteRespType = pb.MsgPreVoteResp
  1164. } else {
  1165. myVoteRespType = pb.MsgVoteResp
  1166. }
  1167. switch m.Type {
  1168. case pb.MsgProp:
  1169. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1170. return ErrProposalDropped
  1171. case pb.MsgApp:
  1172. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1173. r.handleAppendEntries(m)
  1174. case pb.MsgHeartbeat:
  1175. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1176. r.handleHeartbeat(m)
  1177. case pb.MsgSnap:
  1178. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1179. r.handleSnapshot(m)
  1180. case myVoteRespType:
  1181. gr, rj, res := r.poll(m.From, m.Type, !m.Reject)
  1182. r.logger.Infof("%x has received %d %s votes and %d vote rejections", r.id, gr, m.Type, rj)
  1183. switch res {
  1184. case quorum.VoteWon:
  1185. if r.state == StatePreCandidate {
  1186. r.campaign(campaignElection)
  1187. } else {
  1188. r.becomeLeader()
  1189. r.bcastAppend()
  1190. }
  1191. case quorum.VoteLost:
  1192. // pb.MsgPreVoteResp contains future term of pre-candidate
  1193. // m.Term > r.Term; reuse r.Term
  1194. r.becomeFollower(r.Term, None)
  1195. }
  1196. case pb.MsgTimeoutNow:
  1197. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  1198. }
  1199. return nil
  1200. }
  1201. func stepFollower(r *raft, m pb.Message) error {
  1202. switch m.Type {
  1203. case pb.MsgProp:
  1204. if r.lead == None {
  1205. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1206. return ErrProposalDropped
  1207. } else if r.disableProposalForwarding {
  1208. r.logger.Infof("%x not forwarding to leader %x at term %d; dropping proposal", r.id, r.lead, r.Term)
  1209. return ErrProposalDropped
  1210. }
  1211. m.To = r.lead
  1212. r.send(m)
  1213. case pb.MsgApp:
  1214. r.electionElapsed = 0
  1215. r.lead = m.From
  1216. r.handleAppendEntries(m)
  1217. case pb.MsgHeartbeat:
  1218. r.electionElapsed = 0
  1219. r.lead = m.From
  1220. r.handleHeartbeat(m)
  1221. case pb.MsgSnap:
  1222. r.electionElapsed = 0
  1223. r.lead = m.From
  1224. r.handleSnapshot(m)
  1225. case pb.MsgTransferLeader:
  1226. if r.lead == None {
  1227. r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
  1228. return nil
  1229. }
  1230. m.To = r.lead
  1231. r.send(m)
  1232. case pb.MsgTimeoutNow:
  1233. if r.promotable() {
  1234. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  1235. // Leadership transfers never use pre-vote even if r.preVote is true; we
  1236. // know we are not recovering from a partition so there is no need for the
  1237. // extra round trip.
  1238. r.campaign(campaignTransfer)
  1239. } else {
  1240. r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
  1241. }
  1242. case pb.MsgReadIndex:
  1243. if r.lead == None {
  1244. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  1245. return nil
  1246. }
  1247. m.To = r.lead
  1248. r.send(m)
  1249. case pb.MsgReadIndexResp:
  1250. if len(m.Entries) != 1 {
  1251. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  1252. return nil
  1253. }
  1254. r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
  1255. }
  1256. return nil
  1257. }
  1258. func (r *raft) handleAppendEntries(m pb.Message) {
  1259. if m.Index < r.raftLog.committed {
  1260. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1261. return
  1262. }
  1263. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  1264. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  1265. } else {
  1266. r.logger.Debugf("%x [logterm: %d, index: %d] rejected MsgApp [logterm: %d, index: %d] from %x",
  1267. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  1268. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  1269. }
  1270. }
  1271. func (r *raft) handleHeartbeat(m pb.Message) {
  1272. r.raftLog.commitTo(m.Commit)
  1273. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
  1274. }
  1275. func (r *raft) handleSnapshot(m pb.Message) {
  1276. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  1277. if r.restore(m.Snapshot) {
  1278. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  1279. r.id, r.raftLog.committed, sindex, sterm)
  1280. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  1281. } else {
  1282. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  1283. r.id, r.raftLog.committed, sindex, sterm)
  1284. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1285. }
  1286. }
  1287. // restore recovers the state machine from a snapshot. It restores the log and the
  1288. // configuration of state machine. If this method returns false, the snapshot was
  1289. // ignored, either because it was obsolete or because of an error.
  1290. func (r *raft) restore(s pb.Snapshot) bool {
  1291. if s.Metadata.Index <= r.raftLog.committed {
  1292. return false
  1293. }
  1294. if r.state != StateFollower {
  1295. // This is defense-in-depth: if the leader somehow ended up applying a
  1296. // snapshot, it could move into a new term without moving into a
  1297. // follower state. This should never fire, but if it did, we'd have
  1298. // prevented damage by returning early, so log only a loud warning.
  1299. //
  1300. // At the time of writing, the instance is guaranteed to be in follower
  1301. // state when this method is called.
  1302. r.logger.Warningf("%x attempted to restore snapshot as leader; should never happen", r.id)
  1303. r.becomeFollower(r.Term+1, None)
  1304. return false
  1305. }
  1306. // More defense-in-depth: throw away snapshot if recipient is not in the
  1307. // config. This shouuldn't ever happen (at the time of writing) but lots of
  1308. // code here and there assumes that r.id is in the progress tracker.
  1309. found := false
  1310. cs := s.Metadata.ConfState
  1311. for _, set := range [][]uint64{
  1312. cs.Voters,
  1313. cs.Learners,
  1314. } {
  1315. for _, id := range set {
  1316. if id == r.id {
  1317. found = true
  1318. break
  1319. }
  1320. }
  1321. }
  1322. if !found {
  1323. r.logger.Warningf(
  1324. "%x attempted to restore snapshot but it is not in the ConfState %v; should never happen",
  1325. r.id, cs,
  1326. )
  1327. return false
  1328. }
  1329. // Now go ahead and actually restore.
  1330. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  1331. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  1332. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1333. r.raftLog.commitTo(s.Metadata.Index)
  1334. return false
  1335. }
  1336. r.raftLog.restore(s)
  1337. // Reset the configuration and add the (potentially updated) peers in anew.
  1338. r.prs = tracker.MakeProgressTracker(r.prs.MaxInflight)
  1339. cfg, prs, err := confchange.Restore(confchange.Changer{
  1340. Tracker: r.prs,
  1341. LastIndex: r.raftLog.lastIndex(),
  1342. }, cs)
  1343. if err != nil {
  1344. // This should never happen. Either there's a bug in our config change
  1345. // handling or the client corrupted the conf change.
  1346. panic(fmt.Sprintf("unable to restore config %+v: %s", cs, err))
  1347. }
  1348. assertConfStatesEquivalent(r.logger, cs, r.switchToConfig(cfg, prs))
  1349. pr := r.prs.Progress[r.id]
  1350. pr.MaybeUpdate(pr.Next - 1) // TODO(tbg): this is untested and likely unneeded
  1351. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] restored snapshot [index: %d, term: %d]",
  1352. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1353. return true
  1354. }
  1355. // promotable indicates whether state machine can be promoted to leader,
  1356. // which is true when its own id is in progress list.
  1357. func (r *raft) promotable() bool {
  1358. pr := r.prs.Progress[r.id]
  1359. return pr != nil && !pr.IsLearner
  1360. }
  1361. func (r *raft) applyConfChange(cc pb.ConfChangeV2) pb.ConfState {
  1362. cfg, prs, err := func() (tracker.Config, tracker.ProgressMap, error) {
  1363. changer := confchange.Changer{
  1364. Tracker: r.prs,
  1365. LastIndex: r.raftLog.lastIndex(),
  1366. }
  1367. if cc.LeaveJoint() {
  1368. return changer.LeaveJoint()
  1369. } else if autoLeave, ok := cc.EnterJoint(); ok {
  1370. return changer.EnterJoint(autoLeave, cc.Changes...)
  1371. }
  1372. return changer.Simple(cc.Changes...)
  1373. }()
  1374. if err != nil {
  1375. // TODO(tbg): return the error to the caller.
  1376. panic(err)
  1377. }
  1378. return r.switchToConfig(cfg, prs)
  1379. }
  1380. // switchToConfig reconfigures this node to use the provided configuration. It
  1381. // updates the in-memory state and, when necessary, carries out additional
  1382. // actions such as reacting to the removal of nodes or changed quorum
  1383. // requirements.
  1384. //
  1385. // The inputs usually result from restoring a ConfState or applying a ConfChange.
  1386. func (r *raft) switchToConfig(cfg tracker.Config, prs tracker.ProgressMap) pb.ConfState {
  1387. r.prs.Config = cfg
  1388. r.prs.Progress = prs
  1389. r.logger.Infof("%x switched to configuration %s", r.id, r.prs.Config)
  1390. cs := r.prs.ConfState()
  1391. pr, ok := r.prs.Progress[r.id]
  1392. // Update whether the node itself is a learner, resetting to false when the
  1393. // node is removed.
  1394. r.isLearner = ok && pr.IsLearner
  1395. if (!ok || r.isLearner) && r.state == StateLeader {
  1396. // This node is leader and was removed or demoted. We prevent demotions
  1397. // at the time writing but hypothetically we handle them the same way as
  1398. // removing the leader: stepping down into the next Term.
  1399. //
  1400. // TODO(tbg): step down (for sanity) and ask follower with largest Match
  1401. // to TimeoutNow (to avoid interruption). This might still drop some
  1402. // proposals but it's better than nothing.
  1403. //
  1404. // TODO(tbg): test this branch. It is untested at the time of writing.
  1405. return cs
  1406. }
  1407. // The remaining steps only make sense if this node is the leader and there
  1408. // are other nodes.
  1409. if r.state != StateLeader || len(cs.Voters) == 0 {
  1410. return cs
  1411. }
  1412. if r.maybeCommit() {
  1413. // If the configuration change means that more entries are committed now,
  1414. // broadcast/append to everyone in the updated config.
  1415. r.bcastAppend()
  1416. } else {
  1417. // Otherwise, still probe the newly added replicas; there's no reason to
  1418. // let them wait out a heartbeat interval (or the next incoming
  1419. // proposal).
  1420. r.prs.Visit(func(id uint64, pr *tracker.Progress) {
  1421. r.maybeSendAppend(id, false /* sendIfEmpty */)
  1422. })
  1423. }
  1424. // If the the leadTransferee was removed, abort the leadership transfer.
  1425. if _, tOK := r.prs.Progress[r.leadTransferee]; !tOK && r.leadTransferee != 0 {
  1426. r.abortLeaderTransfer()
  1427. }
  1428. return cs
  1429. }
  1430. func (r *raft) loadState(state pb.HardState) {
  1431. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  1432. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  1433. }
  1434. r.raftLog.committed = state.Commit
  1435. r.Term = state.Term
  1436. r.Vote = state.Vote
  1437. }
  1438. // pastElectionTimeout returns true iff r.electionElapsed is greater
  1439. // than or equal to the randomized election timeout in
  1440. // [electiontimeout, 2 * electiontimeout - 1].
  1441. func (r *raft) pastElectionTimeout() bool {
  1442. return r.electionElapsed >= r.randomizedElectionTimeout
  1443. }
  1444. func (r *raft) resetRandomizedElectionTimeout() {
  1445. r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
  1446. }
  1447. func (r *raft) sendTimeoutNow(to uint64) {
  1448. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  1449. }
  1450. func (r *raft) abortLeaderTransfer() {
  1451. r.leadTransferee = None
  1452. }
  1453. // increaseUncommittedSize computes the size of the proposed entries and
  1454. // determines whether they would push leader over its maxUncommittedSize limit.
  1455. // If the new entries would exceed the limit, the method returns false. If not,
  1456. // the increase in uncommitted entry size is recorded and the method returns
  1457. // true.
  1458. func (r *raft) increaseUncommittedSize(ents []pb.Entry) bool {
  1459. var s uint64
  1460. for _, e := range ents {
  1461. s += uint64(PayloadSize(e))
  1462. }
  1463. if r.uncommittedSize > 0 && r.uncommittedSize+s > r.maxUncommittedSize {
  1464. // If the uncommitted tail of the Raft log is empty, allow any size
  1465. // proposal. Otherwise, limit the size of the uncommitted tail of the
  1466. // log and drop any proposal that would push the size over the limit.
  1467. return false
  1468. }
  1469. r.uncommittedSize += s
  1470. return true
  1471. }
  1472. // reduceUncommittedSize accounts for the newly committed entries by decreasing
  1473. // the uncommitted entry size limit.
  1474. func (r *raft) reduceUncommittedSize(ents []pb.Entry) {
  1475. if r.uncommittedSize == 0 {
  1476. // Fast-path for followers, who do not track or enforce the limit.
  1477. return
  1478. }
  1479. var s uint64
  1480. for _, e := range ents {
  1481. s += uint64(PayloadSize(e))
  1482. }
  1483. if s > r.uncommittedSize {
  1484. // uncommittedSize may underestimate the size of the uncommitted Raft
  1485. // log tail but will never overestimate it. Saturate at 0 instead of
  1486. // allowing overflow.
  1487. r.uncommittedSize = 0
  1488. } else {
  1489. r.uncommittedSize -= s
  1490. }
  1491. }
  1492. func numOfPendingConf(ents []pb.Entry) int {
  1493. n := 0
  1494. for i := range ents {
  1495. if ents[i].Type == pb.EntryConfChange {
  1496. n++
  1497. }
  1498. }
  1499. return n
  1500. }