raft.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  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/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. // campaign transitions the raft instance to candidate state. This must only be
  635. // called after verifying that this is a legitimate transition.
  636. func (r *raft) campaign(t CampaignType) {
  637. if !r.promotable() {
  638. // This path should not be hit (callers are supposed to check), but
  639. // better safe than sorry.
  640. r.logger.Warningf("%x is unpromotable; campaign() should have been called", r.id)
  641. }
  642. var term uint64
  643. var voteMsg pb.MessageType
  644. if t == campaignPreElection {
  645. r.becomePreCandidate()
  646. voteMsg = pb.MsgPreVote
  647. // PreVote RPCs are sent for the next term before we've incremented r.Term.
  648. term = r.Term + 1
  649. } else {
  650. r.becomeCandidate()
  651. voteMsg = pb.MsgVote
  652. term = r.Term
  653. }
  654. if _, _, res := r.poll(r.id, voteRespMsgType(voteMsg), true); res == electionWon {
  655. // We won the election after voting for ourselves (which must mean that
  656. // this is a single-node cluster). Advance to the next state.
  657. if t == campaignPreElection {
  658. r.campaign(campaignElection)
  659. } else {
  660. r.becomeLeader()
  661. }
  662. return
  663. }
  664. for id := range r.prs.nodes {
  665. if id == r.id {
  666. continue
  667. }
  668. r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
  669. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
  670. var ctx []byte
  671. if t == campaignTransfer {
  672. ctx = []byte(t)
  673. }
  674. r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
  675. }
  676. }
  677. type electionResult byte
  678. const (
  679. electionIndeterminate electionResult = iota
  680. electionLost
  681. electionWon
  682. )
  683. func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int, rejected int, result electionResult) {
  684. if v {
  685. r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
  686. } else {
  687. r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
  688. }
  689. r.prs.recordVote(id, v)
  690. return r.prs.tallyVotes()
  691. }
  692. func (r *raft) Step(m pb.Message) error {
  693. // Handle the message term, which may result in our stepping down to a follower.
  694. switch {
  695. case m.Term == 0:
  696. // local message
  697. case m.Term > r.Term:
  698. if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
  699. force := bytes.Equal(m.Context, []byte(campaignTransfer))
  700. inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
  701. if !force && inLease {
  702. // If a server receives a RequestVote request within the minimum election timeout
  703. // of hearing from a current leader, it does not update its term or grant its vote
  704. 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)",
  705. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
  706. return nil
  707. }
  708. }
  709. switch {
  710. case m.Type == pb.MsgPreVote:
  711. // Never change our term in response to a PreVote
  712. case m.Type == pb.MsgPreVoteResp && !m.Reject:
  713. // We send pre-vote requests with a term in our future. If the
  714. // pre-vote is granted, we will increment our term when we get a
  715. // quorum. If it is not, the term comes from the node that
  716. // rejected our vote so we should become a follower at the new
  717. // term.
  718. default:
  719. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  720. r.id, r.Term, m.Type, m.From, m.Term)
  721. if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap {
  722. r.becomeFollower(m.Term, m.From)
  723. } else {
  724. r.becomeFollower(m.Term, None)
  725. }
  726. }
  727. case m.Term < r.Term:
  728. if (r.checkQuorum || r.preVote) && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
  729. // We have received messages from a leader at a lower term. It is possible
  730. // that these messages were simply delayed in the network, but this could
  731. // also mean that this node has advanced its term number during a network
  732. // partition, and it is now unable to either win an election or to rejoin
  733. // the majority on the old term. If checkQuorum is false, this will be
  734. // handled by incrementing term numbers in response to MsgVote with a
  735. // higher term, but if checkQuorum is true we may not advance the term on
  736. // MsgVote and must generate other messages to advance the term. The net
  737. // result of these two features is to minimize the disruption caused by
  738. // nodes that have been removed from the cluster's configuration: a
  739. // removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
  740. // but it will not receive MsgApp or MsgHeartbeat, so it will not create
  741. // disruptive term increases, by notifying leader of this node's activeness.
  742. // The above comments also true for Pre-Vote
  743. //
  744. // When follower gets isolated, it soon starts an election ending
  745. // up with a higher term than leader, although it won't receive enough
  746. // votes to win the election. When it regains connectivity, this response
  747. // with "pb.MsgAppResp" of higher term would force leader to step down.
  748. // However, this disruption is inevitable to free this stuck node with
  749. // fresh election. This can be prevented with Pre-Vote phase.
  750. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
  751. } else if m.Type == pb.MsgPreVote {
  752. // Before Pre-Vote enable, there may have candidate with higher term,
  753. // but less log. After update to Pre-Vote, the cluster may deadlock if
  754. // we drop messages with a lower term.
  755. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  756. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  757. r.send(pb.Message{To: m.From, Term: r.Term, Type: pb.MsgPreVoteResp, Reject: true})
  758. } else {
  759. // ignore other cases
  760. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  761. r.id, r.Term, m.Type, m.From, m.Term)
  762. }
  763. return nil
  764. }
  765. switch m.Type {
  766. case pb.MsgHup:
  767. if r.state != StateLeader {
  768. if !r.promotable() {
  769. r.logger.Warningf("%x is unpromotable and can not campaign; ignoring MsgHup", r.id)
  770. return nil
  771. }
  772. ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
  773. if err != nil {
  774. r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
  775. }
  776. if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
  777. r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
  778. return nil
  779. }
  780. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  781. if r.preVote {
  782. r.campaign(campaignPreElection)
  783. } else {
  784. r.campaign(campaignElection)
  785. }
  786. } else {
  787. r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
  788. }
  789. case pb.MsgVote, pb.MsgPreVote:
  790. if r.isLearner {
  791. // TODO: learner may need to vote, in case of node down when confchange.
  792. 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",
  793. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  794. return nil
  795. }
  796. // We can vote if this is a repeat of a vote we've already cast...
  797. canVote := r.Vote == m.From ||
  798. // ...we haven't voted and we don't think there's a leader yet in this term...
  799. (r.Vote == None && r.lead == None) ||
  800. // ...or this is a PreVote for a future term...
  801. (m.Type == pb.MsgPreVote && m.Term > r.Term)
  802. // ...and we believe the candidate is up to date.
  803. if canVote && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  804. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
  805. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  806. // When responding to Msg{Pre,}Vote messages we include the term
  807. // from the message, not the local term. To see why, consider the
  808. // case where a single node was previously partitioned away and
  809. // it's local term is now out of date. If we include the local term
  810. // (recall that for pre-votes we don't update the local term), the
  811. // (pre-)campaigning node on the other end will proceed to ignore
  812. // the message (it ignores all out of date messages).
  813. // The term in the original message and current local term are the
  814. // same in the case of regular votes, but different for pre-votes.
  815. r.send(pb.Message{To: m.From, Term: m.Term, Type: voteRespMsgType(m.Type)})
  816. if m.Type == pb.MsgVote {
  817. // Only record real votes.
  818. r.electionElapsed = 0
  819. r.Vote = m.From
  820. }
  821. } else {
  822. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  823. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  824. r.send(pb.Message{To: m.From, Term: r.Term, Type: voteRespMsgType(m.Type), Reject: true})
  825. }
  826. default:
  827. err := r.step(r, m)
  828. if err != nil {
  829. return err
  830. }
  831. }
  832. return nil
  833. }
  834. type stepFunc func(r *raft, m pb.Message) error
  835. func stepLeader(r *raft, m pb.Message) error {
  836. // These message types do not require any progress for m.From.
  837. switch m.Type {
  838. case pb.MsgBeat:
  839. r.bcastHeartbeat()
  840. return nil
  841. case pb.MsgCheckQuorum:
  842. // The leader should always see itself as active. As a precaution, handle
  843. // the case in which the leader isn't in the configuration any more (for
  844. // example if it just removed itself).
  845. //
  846. // TODO(tbg): I added a TODO in removeNode, it doesn't seem that the
  847. // leader steps down when removing itself. I might be missing something.
  848. if pr := r.prs.getProgress(r.id); pr != nil {
  849. pr.RecentActive = true
  850. }
  851. if !r.prs.quorumActive() {
  852. r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
  853. r.becomeFollower(r.Term, None)
  854. }
  855. // Mark everyone (but ourselves) as inactive in preparation for the next
  856. // CheckQuorum.
  857. r.prs.visit(func(id uint64, pr *Progress) {
  858. if id != r.id {
  859. pr.RecentActive = false
  860. }
  861. })
  862. return nil
  863. case pb.MsgProp:
  864. if len(m.Entries) == 0 {
  865. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  866. }
  867. if r.prs.getProgress(r.id) == nil {
  868. // If we are not currently a member of the range (i.e. this node
  869. // was removed from the configuration while serving as leader),
  870. // drop any new proposals.
  871. return ErrProposalDropped
  872. }
  873. if r.leadTransferee != None {
  874. r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
  875. return ErrProposalDropped
  876. }
  877. for i := range m.Entries {
  878. e := &m.Entries[i]
  879. if e.Type == pb.EntryConfChange {
  880. if r.pendingConfIndex > r.raftLog.applied {
  881. r.logger.Infof("propose conf %s ignored since pending unapplied configuration [index %d, applied %d]",
  882. e, r.pendingConfIndex, r.raftLog.applied)
  883. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  884. } else {
  885. r.pendingConfIndex = r.raftLog.lastIndex() + uint64(i) + 1
  886. }
  887. }
  888. }
  889. if !r.appendEntry(m.Entries...) {
  890. return ErrProposalDropped
  891. }
  892. r.bcastAppend()
  893. return nil
  894. case pb.MsgReadIndex:
  895. if !r.prs.isSingleton() { // more than one voting member in cluster
  896. if r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(r.raftLog.committed)) != r.Term {
  897. // Reject read only request when this leader has not committed any log entry at its term.
  898. return nil
  899. }
  900. // thinking: use an interally defined context instead of the user given context.
  901. // We can express this in terms of the term and index instead of a user-supplied value.
  902. // This would allow multiple reads to piggyback on the same message.
  903. switch r.readOnly.option {
  904. case ReadOnlySafe:
  905. r.readOnly.addRequest(r.raftLog.committed, m)
  906. // The local node automatically acks the request.
  907. r.readOnly.recvAck(r.id, m.Entries[0].Data)
  908. r.bcastHeartbeatWithCtx(m.Entries[0].Data)
  909. case ReadOnlyLeaseBased:
  910. ri := r.raftLog.committed
  911. if m.From == None || m.From == r.id { // from local member
  912. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  913. } else {
  914. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  915. }
  916. }
  917. } else { // only one voting member (the leader) in the cluster
  918. if m.From == None || m.From == r.id { // from leader itself
  919. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  920. } else { // from learner member
  921. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: r.raftLog.committed, Entries: m.Entries})
  922. }
  923. }
  924. return nil
  925. }
  926. // All other message types require a progress for m.From (pr).
  927. pr := r.prs.getProgress(m.From)
  928. if pr == nil {
  929. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  930. return nil
  931. }
  932. switch m.Type {
  933. case pb.MsgAppResp:
  934. pr.RecentActive = true
  935. if m.Reject {
  936. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  937. r.id, m.RejectHint, m.From, m.Index)
  938. if pr.maybeDecrTo(m.Index, m.RejectHint) {
  939. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  940. if pr.State == ProgressStateReplicate {
  941. pr.becomeProbe()
  942. }
  943. r.sendAppend(m.From)
  944. }
  945. } else {
  946. oldPaused := pr.IsPaused()
  947. if pr.maybeUpdate(m.Index) {
  948. switch {
  949. case pr.State == ProgressStateProbe:
  950. pr.becomeReplicate()
  951. case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
  952. r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  953. // Transition back to replicating state via probing state
  954. // (which takes the snapshot into account). If we didn't
  955. // move to replicating state, that would only happen with
  956. // the next round of appends (but there may not be a next
  957. // round for a while, exposing an inconsistent RaftStatus).
  958. pr.becomeProbe()
  959. pr.becomeReplicate()
  960. case pr.State == ProgressStateReplicate:
  961. pr.ins.freeTo(m.Index)
  962. }
  963. if r.maybeCommit() {
  964. r.bcastAppend()
  965. } else if oldPaused {
  966. // If we were paused before, this node may be missing the
  967. // latest commit index, so send it.
  968. r.sendAppend(m.From)
  969. }
  970. // We've updated flow control information above, which may
  971. // allow us to send multiple (size-limited) in-flight messages
  972. // at once (such as when transitioning from probe to
  973. // replicate, or when freeTo() covers multiple messages). If
  974. // we have more entries to send, send as many messages as we
  975. // can (without sending empty messages for the commit index)
  976. for r.maybeSendAppend(m.From, false) {
  977. }
  978. // Transfer leadership is in progress.
  979. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  980. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  981. r.sendTimeoutNow(m.From)
  982. }
  983. }
  984. }
  985. case pb.MsgHeartbeatResp:
  986. pr.RecentActive = true
  987. pr.resume()
  988. // free one slot for the full inflights window to allow progress.
  989. if pr.State == ProgressStateReplicate && pr.ins.full() {
  990. pr.ins.freeFirstOne()
  991. }
  992. if pr.Match < r.raftLog.lastIndex() {
  993. r.sendAppend(m.From)
  994. }
  995. if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
  996. return nil
  997. }
  998. if !r.prs.hasQuorum(r.readOnly.recvAck(m.From, m.Context)) {
  999. return nil
  1000. }
  1001. rss := r.readOnly.advance(m)
  1002. for _, rs := range rss {
  1003. req := rs.req
  1004. if req.From == None || req.From == r.id { // from local member
  1005. r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
  1006. } else {
  1007. r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
  1008. }
  1009. }
  1010. case pb.MsgSnapStatus:
  1011. if pr.State != ProgressStateSnapshot {
  1012. return nil
  1013. }
  1014. if !m.Reject {
  1015. pr.becomeProbe()
  1016. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  1017. } else {
  1018. pr.snapshotFailure()
  1019. pr.becomeProbe()
  1020. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  1021. }
  1022. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  1023. // out the next msgApp.
  1024. // If snapshot failure, wait for a heartbeat interval before next try
  1025. pr.pause()
  1026. case pb.MsgUnreachable:
  1027. // During optimistic replication, if the remote becomes unreachable,
  1028. // there is huge probability that a MsgApp is lost.
  1029. if pr.State == ProgressStateReplicate {
  1030. pr.becomeProbe()
  1031. }
  1032. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  1033. case pb.MsgTransferLeader:
  1034. if pr.IsLearner {
  1035. r.logger.Debugf("%x is learner. Ignored transferring leadership", r.id)
  1036. return nil
  1037. }
  1038. leadTransferee := m.From
  1039. lastLeadTransferee := r.leadTransferee
  1040. if lastLeadTransferee != None {
  1041. if lastLeadTransferee == leadTransferee {
  1042. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  1043. r.id, r.Term, leadTransferee, leadTransferee)
  1044. return nil
  1045. }
  1046. r.abortLeaderTransfer()
  1047. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  1048. }
  1049. if leadTransferee == r.id {
  1050. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  1051. return nil
  1052. }
  1053. // Transfer leadership to third party.
  1054. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  1055. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  1056. r.electionElapsed = 0
  1057. r.leadTransferee = leadTransferee
  1058. if pr.Match == r.raftLog.lastIndex() {
  1059. r.sendTimeoutNow(leadTransferee)
  1060. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  1061. } else {
  1062. r.sendAppend(leadTransferee)
  1063. }
  1064. }
  1065. return nil
  1066. }
  1067. // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
  1068. // whether they respond to MsgVoteResp or MsgPreVoteResp.
  1069. func stepCandidate(r *raft, m pb.Message) error {
  1070. // Only handle vote responses corresponding to our candidacy (while in
  1071. // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
  1072. // our pre-candidate state).
  1073. var myVoteRespType pb.MessageType
  1074. if r.state == StatePreCandidate {
  1075. myVoteRespType = pb.MsgPreVoteResp
  1076. } else {
  1077. myVoteRespType = pb.MsgVoteResp
  1078. }
  1079. switch m.Type {
  1080. case pb.MsgProp:
  1081. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1082. return ErrProposalDropped
  1083. case pb.MsgApp:
  1084. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1085. r.handleAppendEntries(m)
  1086. case pb.MsgHeartbeat:
  1087. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1088. r.handleHeartbeat(m)
  1089. case pb.MsgSnap:
  1090. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1091. r.handleSnapshot(m)
  1092. case myVoteRespType:
  1093. gr, rj, res := r.poll(m.From, m.Type, !m.Reject)
  1094. r.logger.Infof("%x has received %d %s votes and %d vote rejections", r.id, gr, m.Type, rj)
  1095. switch res {
  1096. case electionWon:
  1097. if r.state == StatePreCandidate {
  1098. r.campaign(campaignElection)
  1099. } else {
  1100. r.becomeLeader()
  1101. r.bcastAppend()
  1102. }
  1103. case electionLost:
  1104. // pb.MsgPreVoteResp contains future term of pre-candidate
  1105. // m.Term > r.Term; reuse r.Term
  1106. r.becomeFollower(r.Term, None)
  1107. }
  1108. case pb.MsgTimeoutNow:
  1109. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  1110. }
  1111. return nil
  1112. }
  1113. func stepFollower(r *raft, m pb.Message) error {
  1114. switch m.Type {
  1115. case pb.MsgProp:
  1116. if r.lead == None {
  1117. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1118. return ErrProposalDropped
  1119. } else if r.disableProposalForwarding {
  1120. r.logger.Infof("%x not forwarding to leader %x at term %d; dropping proposal", r.id, r.lead, r.Term)
  1121. return ErrProposalDropped
  1122. }
  1123. m.To = r.lead
  1124. r.send(m)
  1125. case pb.MsgApp:
  1126. r.electionElapsed = 0
  1127. r.lead = m.From
  1128. r.handleAppendEntries(m)
  1129. case pb.MsgHeartbeat:
  1130. r.electionElapsed = 0
  1131. r.lead = m.From
  1132. r.handleHeartbeat(m)
  1133. case pb.MsgSnap:
  1134. r.electionElapsed = 0
  1135. r.lead = m.From
  1136. r.handleSnapshot(m)
  1137. case pb.MsgTransferLeader:
  1138. if r.lead == None {
  1139. r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
  1140. return nil
  1141. }
  1142. m.To = r.lead
  1143. r.send(m)
  1144. case pb.MsgTimeoutNow:
  1145. if r.promotable() {
  1146. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  1147. // Leadership transfers never use pre-vote even if r.preVote is true; we
  1148. // know we are not recovering from a partition so there is no need for the
  1149. // extra round trip.
  1150. r.campaign(campaignTransfer)
  1151. } else {
  1152. r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
  1153. }
  1154. case pb.MsgReadIndex:
  1155. if r.lead == None {
  1156. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  1157. return nil
  1158. }
  1159. m.To = r.lead
  1160. r.send(m)
  1161. case pb.MsgReadIndexResp:
  1162. if len(m.Entries) != 1 {
  1163. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  1164. return nil
  1165. }
  1166. r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
  1167. }
  1168. return nil
  1169. }
  1170. func (r *raft) handleAppendEntries(m pb.Message) {
  1171. if m.Index < r.raftLog.committed {
  1172. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1173. return
  1174. }
  1175. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  1176. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  1177. } else {
  1178. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  1179. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  1180. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  1181. }
  1182. }
  1183. func (r *raft) handleHeartbeat(m pb.Message) {
  1184. r.raftLog.commitTo(m.Commit)
  1185. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
  1186. }
  1187. func (r *raft) handleSnapshot(m pb.Message) {
  1188. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  1189. if r.restore(m.Snapshot) {
  1190. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  1191. r.id, r.raftLog.committed, sindex, sterm)
  1192. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  1193. } else {
  1194. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  1195. r.id, r.raftLog.committed, sindex, sterm)
  1196. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1197. }
  1198. }
  1199. // restore recovers the state machine from a snapshot. It restores the log and the
  1200. // configuration of state machine.
  1201. func (r *raft) restore(s pb.Snapshot) bool {
  1202. if s.Metadata.Index <= r.raftLog.committed {
  1203. return false
  1204. }
  1205. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  1206. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  1207. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1208. r.raftLog.commitTo(s.Metadata.Index)
  1209. return false
  1210. }
  1211. // The normal peer can't become learner.
  1212. if !r.isLearner {
  1213. for _, id := range s.Metadata.ConfState.Learners {
  1214. if id == r.id {
  1215. r.logger.Errorf("%x can't become learner when restores snapshot [index: %d, term: %d]", r.id, s.Metadata.Index, s.Metadata.Term)
  1216. return false
  1217. }
  1218. }
  1219. }
  1220. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  1221. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1222. r.raftLog.restore(s)
  1223. r.prs = makePRS(r.prs.maxInflight)
  1224. r.restoreNode(s.Metadata.ConfState.Nodes, false)
  1225. r.restoreNode(s.Metadata.ConfState.Learners, true)
  1226. return true
  1227. }
  1228. func (r *raft) restoreNode(nodes []uint64, isLearner bool) {
  1229. for _, n := range nodes {
  1230. match, next := uint64(0), r.raftLog.lastIndex()+1
  1231. if n == r.id {
  1232. match = next - 1
  1233. r.isLearner = isLearner
  1234. }
  1235. r.prs.initProgress(n, match, next, isLearner)
  1236. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.prs.getProgress(n))
  1237. }
  1238. }
  1239. // promotable indicates whether state machine can be promoted to leader,
  1240. // which is true when its own id is in progress list.
  1241. func (r *raft) promotable() bool {
  1242. pr := r.prs.getProgress(r.id)
  1243. return pr != nil && !pr.IsLearner
  1244. }
  1245. func (r *raft) addNode(id uint64) {
  1246. r.addNodeOrLearnerNode(id, false)
  1247. }
  1248. func (r *raft) addLearner(id uint64) {
  1249. r.addNodeOrLearnerNode(id, true)
  1250. }
  1251. func (r *raft) addNodeOrLearnerNode(id uint64, isLearner bool) {
  1252. pr := r.prs.getProgress(id)
  1253. if pr == nil {
  1254. r.prs.initProgress(id, 0, r.raftLog.lastIndex()+1, isLearner)
  1255. } else {
  1256. if isLearner && !pr.IsLearner {
  1257. // Can only change Learner to Voter.
  1258. r.logger.Infof("%x ignored addLearner: do not support changing %x from raft peer to learner.", r.id, id)
  1259. return
  1260. }
  1261. if isLearner == pr.IsLearner {
  1262. // Ignore any redundant addNode calls (which can happen because the
  1263. // initial bootstrapping entries are applied twice).
  1264. return
  1265. }
  1266. // Change Learner to Voter, use origin Learner progress.
  1267. r.prs.removeAny(id)
  1268. r.prs.initProgress(id, 0 /* match */, 1 /* next */, false /* isLearner */)
  1269. pr.IsLearner = false
  1270. *r.prs.getProgress(id) = *pr
  1271. }
  1272. if r.id == id {
  1273. r.isLearner = isLearner
  1274. }
  1275. // When a node is first added, we should mark it as recently active.
  1276. // Otherwise, CheckQuorum may cause us to step down if it is invoked
  1277. // before the added node has a chance to communicate with us.
  1278. r.prs.getProgress(id).RecentActive = true
  1279. }
  1280. func (r *raft) removeNode(id uint64) {
  1281. r.prs.removeAny(id)
  1282. // Do not try to commit or abort transferring if the cluster is now empty.
  1283. if len(r.prs.nodes) == 0 && len(r.prs.learners) == 0 {
  1284. return
  1285. }
  1286. // TODO(tbg): won't bad (or at least unfortunate) things happen if the
  1287. // leader just removed itself?
  1288. // The quorum size is now smaller, so see if any pending entries can
  1289. // be committed.
  1290. if r.maybeCommit() {
  1291. r.bcastAppend()
  1292. }
  1293. // If the removed node is the leadTransferee, then abort the leadership transferring.
  1294. if r.state == StateLeader && r.leadTransferee == id {
  1295. r.abortLeaderTransfer()
  1296. }
  1297. }
  1298. func (r *raft) loadState(state pb.HardState) {
  1299. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  1300. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  1301. }
  1302. r.raftLog.committed = state.Commit
  1303. r.Term = state.Term
  1304. r.Vote = state.Vote
  1305. }
  1306. // pastElectionTimeout returns true iff r.electionElapsed is greater
  1307. // than or equal to the randomized election timeout in
  1308. // [electiontimeout, 2 * electiontimeout - 1].
  1309. func (r *raft) pastElectionTimeout() bool {
  1310. return r.electionElapsed >= r.randomizedElectionTimeout
  1311. }
  1312. func (r *raft) resetRandomizedElectionTimeout() {
  1313. r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
  1314. }
  1315. func (r *raft) sendTimeoutNow(to uint64) {
  1316. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  1317. }
  1318. func (r *raft) abortLeaderTransfer() {
  1319. r.leadTransferee = None
  1320. }
  1321. // increaseUncommittedSize computes the size of the proposed entries and
  1322. // determines whether they would push leader over its maxUncommittedSize limit.
  1323. // If the new entries would exceed the limit, the method returns false. If not,
  1324. // the increase in uncommitted entry size is recorded and the method returns
  1325. // true.
  1326. func (r *raft) increaseUncommittedSize(ents []pb.Entry) bool {
  1327. var s uint64
  1328. for _, e := range ents {
  1329. s += uint64(PayloadSize(e))
  1330. }
  1331. if r.uncommittedSize > 0 && r.uncommittedSize+s > r.maxUncommittedSize {
  1332. // If the uncommitted tail of the Raft log is empty, allow any size
  1333. // proposal. Otherwise, limit the size of the uncommitted tail of the
  1334. // log and drop any proposal that would push the size over the limit.
  1335. return false
  1336. }
  1337. r.uncommittedSize += s
  1338. return true
  1339. }
  1340. // reduceUncommittedSize accounts for the newly committed entries by decreasing
  1341. // the uncommitted entry size limit.
  1342. func (r *raft) reduceUncommittedSize(ents []pb.Entry) {
  1343. if r.uncommittedSize == 0 {
  1344. // Fast-path for followers, who do not track or enforce the limit.
  1345. return
  1346. }
  1347. var s uint64
  1348. for _, e := range ents {
  1349. s += uint64(PayloadSize(e))
  1350. }
  1351. if s > r.uncommittedSize {
  1352. // uncommittedSize may underestimate the size of the uncommitted Raft
  1353. // log tail but will never overestimate it. Saturate at 0 instead of
  1354. // allowing overflow.
  1355. r.uncommittedSize = 0
  1356. } else {
  1357. r.uncommittedSize -= s
  1358. }
  1359. }
  1360. func numOfPendingConf(ents []pb.Entry) int {
  1361. n := 0
  1362. for i := range ents {
  1363. if ents[i].Type == pb.EntryConfChange {
  1364. n++
  1365. }
  1366. }
  1367. return n
  1368. }