raft.go 51 KB

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