raft.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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. "go.etcd.io/etcd/raft/confchange"
  25. "go.etcd.io/etcd/raft/quorum"
  26. pb "go.etcd.io/etcd/raft/raftpb"
  27. "go.etcd.io/etcd/raft/tracker"
  28. )
  29. // None is a placeholder node ID used when there is no leader.
  30. const None uint64 = 0
  31. const noLimit = math.MaxUint64
  32. // Possible values for StateType.
  33. const (
  34. StateFollower StateType = iota
  35. StateCandidate
  36. StateLeader
  37. StatePreCandidate
  38. numStates
  39. )
  40. type ReadOnlyOption int
  41. const (
  42. // ReadOnlySafe guarantees the linearizability of the read only request by
  43. // communicating with the quorum. It is the default and suggested option.
  44. ReadOnlySafe ReadOnlyOption = iota
  45. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  46. // relying on the leader lease. It can be affected by clock drift.
  47. // If the clock drift is unbounded, leader might keep the lease longer than it
  48. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  49. // in that case.
  50. ReadOnlyLeaseBased
  51. )
  52. // Possible values for CampaignType
  53. const (
  54. // campaignPreElection represents the first phase of a normal election when
  55. // Config.PreVote is true.
  56. campaignPreElection CampaignType = "CampaignPreElection"
  57. // campaignElection represents a normal (time-based) election (the second phase
  58. // of the election when Config.PreVote is true).
  59. campaignElection CampaignType = "CampaignElection"
  60. // campaignTransfer represents the type of leader transfer
  61. campaignTransfer CampaignType = "CampaignTransfer"
  62. )
  63. // ErrProposalDropped is returned when the proposal is ignored by some cases,
  64. // so that the proposer can be notified and fail fast.
  65. var ErrProposalDropped = errors.New("raft proposal dropped")
  66. // lockedRand is a small wrapper around rand.Rand to provide
  67. // synchronization among multiple raft groups. Only the methods needed
  68. // by the code are exposed (e.g. Intn).
  69. type lockedRand struct {
  70. mu sync.Mutex
  71. rand *rand.Rand
  72. }
  73. func (r *lockedRand) Intn(n int) int {
  74. r.mu.Lock()
  75. v := r.rand.Intn(n)
  76. r.mu.Unlock()
  77. return v
  78. }
  79. var globalRand = &lockedRand{
  80. rand: rand.New(rand.NewSource(time.Now().UnixNano())),
  81. }
  82. // CampaignType represents the type of campaigning
  83. // the reason we use the type of string instead of uint64
  84. // is because it's simpler to compare and fill in raft entries
  85. type CampaignType string
  86. // StateType represents the role of a node in a cluster.
  87. type StateType uint64
  88. var stmap = [...]string{
  89. "StateFollower",
  90. "StateCandidate",
  91. "StateLeader",
  92. "StatePreCandidate",
  93. }
  94. func (st StateType) String() string {
  95. return stmap[uint64(st)]
  96. }
  97. // Config contains the parameters to start a raft.
  98. type Config struct {
  99. // ID is the identity of the local raft. ID cannot be 0.
  100. ID uint64
  101. // peers contains the IDs of all nodes (including self) in the raft cluster. It
  102. // should only be set when starting a new raft cluster. Restarting raft from
  103. // previous configuration will panic if peers is set. peer is private and only
  104. // used for testing right now.
  105. peers []uint64
  106. // learners contains the IDs of all learner nodes (including self if the
  107. // local node is a learner) in the raft cluster. learners only receives
  108. // entries from the leader node. It does not vote or promote itself.
  109. learners []uint64
  110. // ElectionTick is the number of Node.Tick invocations that must pass between
  111. // elections. That is, if a follower does not receive any message from the
  112. // leader of current term before ElectionTick has elapsed, it will become
  113. // candidate and start an election. ElectionTick must be greater than
  114. // HeartbeatTick. We suggest ElectionTick = 10 * HeartbeatTick to avoid
  115. // unnecessary leader switching.
  116. ElectionTick int
  117. // HeartbeatTick is the number of Node.Tick invocations that must pass between
  118. // heartbeats. That is, a leader sends heartbeat messages to maintain its
  119. // leadership every HeartbeatTick ticks.
  120. HeartbeatTick int
  121. // Storage is the storage for raft. raft generates entries and states to be
  122. // stored in storage. raft reads the persisted entries and states out of
  123. // Storage when it needs. raft reads out the previous state and configuration
  124. // out of storage when restarting.
  125. Storage Storage
  126. // Applied is the last applied index. It should only be set when restarting
  127. // raft. raft will not return entries to the application smaller or equal to
  128. // Applied. If Applied is unset when restarting, raft might return previous
  129. // applied entries. This is a very application dependent configuration.
  130. Applied uint64
  131. // MaxSizePerMsg limits the max byte size of each append message. Smaller
  132. // value lowers the raft recovery cost(initial probing and message lost
  133. // during normal operation). On the other side, it might affect the
  134. // throughput during normal replication. Note: math.MaxUint64 for unlimited,
  135. // 0 for at most one entry per message.
  136. MaxSizePerMsg uint64
  137. // MaxCommittedSizePerReady limits the size of the committed entries which
  138. // can be applied.
  139. MaxCommittedSizePerReady uint64
  140. // MaxUncommittedEntriesSize limits the aggregate byte size of the
  141. // uncommitted entries that may be appended to a leader's log. Once this
  142. // limit is exceeded, proposals will begin to return ErrProposalDropped
  143. // errors. Note: 0 for no limit.
  144. MaxUncommittedEntriesSize uint64
  145. // MaxInflightMsgs limits the max number of in-flight append messages during
  146. // optimistic replication phase. The application transportation layer usually
  147. // has its own sending buffer over TCP/UDP. Setting MaxInflightMsgs to avoid
  148. // overflowing that sending buffer. TODO (xiangli): feedback to application to
  149. // limit the proposal rate?
  150. MaxInflightMsgs int
  151. // CheckQuorum specifies if the leader should check quorum activity. Leader
  152. // steps down when quorum is not active for an electionTimeout.
  153. CheckQuorum bool
  154. // PreVote enables the Pre-Vote algorithm described in raft thesis section
  155. // 9.6. This prevents disruption when a node that has been partitioned away
  156. // rejoins the cluster.
  157. PreVote bool
  158. // ReadOnlyOption specifies how the read only request is processed.
  159. //
  160. // ReadOnlySafe guarantees the linearizability of the read only request by
  161. // communicating with the quorum. It is the default and suggested option.
  162. //
  163. // ReadOnlyLeaseBased ensures linearizability of the read only request by
  164. // relying on the leader lease. It can be affected by clock drift.
  165. // If the clock drift is unbounded, leader might keep the lease longer than it
  166. // should (clock can move backward/pause without any bound). ReadIndex is not safe
  167. // in that case.
  168. // CheckQuorum MUST be enabled if ReadOnlyOption is ReadOnlyLeaseBased.
  169. ReadOnlyOption ReadOnlyOption
  170. // Logger is the logger used for raft log. For multinode which can host
  171. // multiple raft group, each raft group can have its own logger
  172. Logger Logger
  173. // DisableProposalForwarding set to true means that followers will drop
  174. // proposals, rather than forwarding them to the leader. One use case for
  175. // this feature would be in a situation where the Raft leader is used to
  176. // compute the data of a proposal, for example, adding a timestamp from a
  177. // hybrid logical clock to data in a monotonically increasing way. Forwarding
  178. // should be disabled to prevent a follower with an inaccurate hybrid
  179. // logical clock from assigning the timestamp and then forwarding the data
  180. // to the leader.
  181. DisableProposalForwarding bool
  182. }
  183. func (c *Config) validate() error {
  184. if c.ID == None {
  185. return errors.New("cannot use none as id")
  186. }
  187. if c.HeartbeatTick <= 0 {
  188. return errors.New("heartbeat tick must be greater than 0")
  189. }
  190. if c.ElectionTick <= c.HeartbeatTick {
  191. return errors.New("election tick must be greater than heartbeat tick")
  192. }
  193. if c.Storage == nil {
  194. return errors.New("storage cannot be nil")
  195. }
  196. if c.MaxUncommittedEntriesSize == 0 {
  197. c.MaxUncommittedEntriesSize = noLimit
  198. }
  199. // default MaxCommittedSizePerReady to MaxSizePerMsg because they were
  200. // previously the same parameter.
  201. if c.MaxCommittedSizePerReady == 0 {
  202. c.MaxCommittedSizePerReady = c.MaxSizePerMsg
  203. }
  204. if c.MaxInflightMsgs <= 0 {
  205. return errors.New("max inflight messages must be greater than 0")
  206. }
  207. if c.Logger == nil {
  208. c.Logger = raftLogger
  209. }
  210. if c.ReadOnlyOption == ReadOnlyLeaseBased && !c.CheckQuorum {
  211. return errors.New("CheckQuorum must be enabled when ReadOnlyOption is ReadOnlyLeaseBased")
  212. }
  213. return nil
  214. }
  215. type raft struct {
  216. id uint64
  217. Term uint64
  218. Vote uint64
  219. readStates []ReadState
  220. // the log
  221. raftLog *raftLog
  222. maxMsgSize uint64
  223. maxUncommittedSize uint64
  224. prs tracker.ProgressTracker
  225. state StateType
  226. // isLearner is true if the local raft node is a learner.
  227. isLearner bool
  228. msgs []pb.Message
  229. // the leader id
  230. lead uint64
  231. // leadTransferee is id of the leader transfer target when its value is not zero.
  232. // Follow the procedure defined in raft thesis 3.10.
  233. leadTransferee uint64
  234. // Only one conf change may be pending (in the log, but not yet
  235. // applied) at a time. This is enforced via pendingConfIndex, which
  236. // is set to a value >= the log index of the latest pending
  237. // configuration change (if any). Config changes are only allowed to
  238. // be proposed if the leader's applied index is greater than this
  239. // value.
  240. pendingConfIndex uint64
  241. // an estimate of the size of the uncommitted tail of the Raft log. Used to
  242. // prevent unbounded log growth. Only maintained by the leader. Reset on
  243. // term changes.
  244. uncommittedSize uint64
  245. readOnly *readOnly
  246. // number of ticks since it reached last electionTimeout when it is leader
  247. // or candidate.
  248. // number of ticks since it reached last electionTimeout or received a
  249. // valid message from current leader when it is a follower.
  250. electionElapsed int
  251. // number of ticks since it reached last heartbeatTimeout.
  252. // only leader keeps heartbeatElapsed.
  253. heartbeatElapsed int
  254. checkQuorum bool
  255. preVote bool
  256. heartbeatTimeout int
  257. electionTimeout int
  258. // randomizedElectionTimeout is a random number between
  259. // [electiontimeout, 2 * electiontimeout - 1]. It gets reset
  260. // when raft changes its state to follower or candidate.
  261. randomizedElectionTimeout int
  262. disableProposalForwarding bool
  263. tick func()
  264. step stepFunc
  265. logger Logger
  266. }
  267. func newRaft(c *Config) *raft {
  268. if err := c.validate(); err != nil {
  269. panic(err.Error())
  270. }
  271. raftlog := newLogWithSize(c.Storage, c.Logger, c.MaxCommittedSizePerReady)
  272. hs, cs, err := c.Storage.InitialState()
  273. if err != nil {
  274. panic(err) // TODO(bdarnell)
  275. }
  276. peers := c.peers
  277. learners := c.learners
  278. if len(cs.Nodes) > 0 || len(cs.Learners) > 0 {
  279. if len(peers) > 0 || len(learners) > 0 {
  280. // TODO(bdarnell): the peers argument is always nil except in
  281. // tests; the argument should be removed and these tests should be
  282. // updated to specify their nodes through a snapshot.
  283. panic("cannot specify both newRaft(peers, learners) and ConfState.(Nodes, Learners)")
  284. }
  285. peers = cs.Nodes
  286. learners = cs.Learners
  287. }
  288. r := &raft{
  289. id: c.ID,
  290. lead: None,
  291. isLearner: false,
  292. raftLog: raftlog,
  293. maxMsgSize: c.MaxSizePerMsg,
  294. maxUncommittedSize: c.MaxUncommittedEntriesSize,
  295. prs: tracker.MakeProgressTracker(c.MaxInflightMsgs),
  296. electionTimeout: c.ElectionTick,
  297. heartbeatTimeout: c.HeartbeatTick,
  298. logger: c.Logger,
  299. checkQuorum: c.CheckQuorum,
  300. preVote: c.PreVote,
  301. readOnly: newReadOnly(c.ReadOnlyOption),
  302. disableProposalForwarding: c.DisableProposalForwarding,
  303. }
  304. for _, p := range peers {
  305. // Add node to active config.
  306. r.applyConfChange(pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: p})
  307. }
  308. for _, p := range learners {
  309. // Add learner to active config.
  310. r.applyConfChange(pb.ConfChange{Type: pb.ConfChangeAddLearnerNode, NodeID: p})
  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.Progress[to]
  381. if pr.IsPaused() {
  382. return false
  383. }
  384. m := pb.Message{}
  385. m.To = to
  386. term, errt := r.raftLog.term(pr.Next - 1)
  387. ents, erre := r.raftLog.entries(pr.Next, r.maxMsgSize)
  388. if len(ents) == 0 && !sendIfEmpty {
  389. return false
  390. }
  391. if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
  392. if !pr.RecentActive {
  393. r.logger.Debugf("ignore sending snapshot to %x since it is not recently active", to)
  394. return false
  395. }
  396. m.Type = pb.MsgSnap
  397. snapshot, err := r.raftLog.snapshot()
  398. if err != nil {
  399. if err == ErrSnapshotTemporarilyUnavailable {
  400. r.logger.Debugf("%x failed to send snapshot to %x because snapshot is temporarily unavailable", r.id, to)
  401. return false
  402. }
  403. panic(err) // TODO(bdarnell)
  404. }
  405. if IsEmptySnap(snapshot) {
  406. panic("need non-empty snapshot")
  407. }
  408. m.Snapshot = snapshot
  409. sindex, sterm := snapshot.Metadata.Index, snapshot.Metadata.Term
  410. r.logger.Debugf("%x [firstindex: %d, commit: %d] sent snapshot[index: %d, term: %d] to %x [%s]",
  411. r.id, r.raftLog.firstIndex(), r.raftLog.committed, sindex, sterm, to, pr)
  412. pr.BecomeSnapshot(sindex)
  413. r.logger.Debugf("%x paused sending replication messages to %x [%s]", r.id, to, pr)
  414. } else {
  415. m.Type = pb.MsgApp
  416. m.Index = pr.Next - 1
  417. m.LogTerm = term
  418. m.Entries = ents
  419. m.Commit = r.raftLog.committed
  420. if n := len(m.Entries); n != 0 {
  421. switch pr.State {
  422. // optimistically increase the next when in StateReplicate
  423. case tracker.StateReplicate:
  424. last := m.Entries[n-1].Index
  425. pr.OptimisticUpdate(last)
  426. pr.Inflights.Add(last)
  427. case tracker.StateProbe:
  428. pr.ProbeSent = true
  429. default:
  430. r.logger.Panicf("%x is sending append in unhandled state %s", r.id, pr.State)
  431. }
  432. }
  433. }
  434. r.send(m)
  435. return true
  436. }
  437. // sendHeartbeat sends a heartbeat RPC to the given peer.
  438. func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
  439. // Attach the commit as min(to.matched, r.committed).
  440. // When the leader sends out heartbeat message,
  441. // the receiver(follower) might not be matched with the leader
  442. // or it might not have all the committed entries.
  443. // The leader MUST NOT forward the follower's commit to
  444. // an unmatched index.
  445. commit := min(r.prs.Progress[to].Match, r.raftLog.committed)
  446. m := pb.Message{
  447. To: to,
  448. Type: pb.MsgHeartbeat,
  449. Commit: commit,
  450. Context: ctx,
  451. }
  452. r.send(m)
  453. }
  454. // bcastAppend sends RPC, with entries to all peers that are not up-to-date
  455. // according to the progress recorded in r.prs.
  456. func (r *raft) bcastAppend() {
  457. r.prs.Visit(func(id uint64, _ *tracker.Progress) {
  458. if id == r.id {
  459. return
  460. }
  461. r.sendAppend(id)
  462. })
  463. }
  464. // bcastHeartbeat sends RPC, without entries to all the peers.
  465. func (r *raft) bcastHeartbeat() {
  466. lastCtx := r.readOnly.lastPendingRequestCtx()
  467. if len(lastCtx) == 0 {
  468. r.bcastHeartbeatWithCtx(nil)
  469. } else {
  470. r.bcastHeartbeatWithCtx([]byte(lastCtx))
  471. }
  472. }
  473. func (r *raft) bcastHeartbeatWithCtx(ctx []byte) {
  474. r.prs.Visit(func(id uint64, _ *tracker.Progress) {
  475. if id == r.id {
  476. return
  477. }
  478. r.sendHeartbeat(id, ctx)
  479. })
  480. }
  481. // 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 *tracker.Progress) {
  500. *pr = tracker.Progress{
  501. Match: 0,
  502. Next: r.raftLog.lastIndex() + 1,
  503. Inflights: tracker.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.Progress[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.Progress[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 == quorum.VoteWon {
  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.Voters.IDs() {
  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. func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int, rejected int, result quorum.VoteResult) {
  678. if v {
  679. r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
  680. } else {
  681. r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
  682. }
  683. r.prs.RecordVote(id, v)
  684. return r.prs.TallyVotes()
  685. }
  686. func (r *raft) Step(m pb.Message) error {
  687. // Handle the message term, which may result in our stepping down to a follower.
  688. switch {
  689. case m.Term == 0:
  690. // local message
  691. case m.Term > r.Term:
  692. if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
  693. force := bytes.Equal(m.Context, []byte(campaignTransfer))
  694. inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
  695. if !force && inLease {
  696. // If a server receives a RequestVote request within the minimum election timeout
  697. // of hearing from a current leader, it does not update its term or grant its vote
  698. 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)",
  699. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
  700. return nil
  701. }
  702. }
  703. switch {
  704. case m.Type == pb.MsgPreVote:
  705. // Never change our term in response to a PreVote
  706. case m.Type == pb.MsgPreVoteResp && !m.Reject:
  707. // We send pre-vote requests with a term in our future. If the
  708. // pre-vote is granted, we will increment our term when we get a
  709. // quorum. If it is not, the term comes from the node that
  710. // rejected our vote so we should become a follower at the new
  711. // term.
  712. default:
  713. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  714. r.id, r.Term, m.Type, m.From, m.Term)
  715. if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap {
  716. r.becomeFollower(m.Term, m.From)
  717. } else {
  718. r.becomeFollower(m.Term, None)
  719. }
  720. }
  721. case m.Term < r.Term:
  722. if (r.checkQuorum || r.preVote) && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
  723. // We have received messages from a leader at a lower term. It is possible
  724. // that these messages were simply delayed in the network, but this could
  725. // also mean that this node has advanced its term number during a network
  726. // partition, and it is now unable to either win an election or to rejoin
  727. // the majority on the old term. If checkQuorum is false, this will be
  728. // handled by incrementing term numbers in response to MsgVote with a
  729. // higher term, but if checkQuorum is true we may not advance the term on
  730. // MsgVote and must generate other messages to advance the term. The net
  731. // result of these two features is to minimize the disruption caused by
  732. // nodes that have been removed from the cluster's configuration: a
  733. // removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
  734. // but it will not receive MsgApp or MsgHeartbeat, so it will not create
  735. // disruptive term increases, by notifying leader of this node's activeness.
  736. // The above comments also true for Pre-Vote
  737. //
  738. // When follower gets isolated, it soon starts an election ending
  739. // up with a higher term than leader, although it won't receive enough
  740. // votes to win the election. When it regains connectivity, this response
  741. // with "pb.MsgAppResp" of higher term would force leader to step down.
  742. // However, this disruption is inevitable to free this stuck node with
  743. // fresh election. This can be prevented with Pre-Vote phase.
  744. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
  745. } else if m.Type == pb.MsgPreVote {
  746. // Before Pre-Vote enable, there may have candidate with higher term,
  747. // but less log. After update to Pre-Vote, the cluster may deadlock if
  748. // we drop messages with a lower term.
  749. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  750. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  751. r.send(pb.Message{To: m.From, Term: r.Term, Type: pb.MsgPreVoteResp, Reject: true})
  752. } else {
  753. // ignore other cases
  754. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  755. r.id, r.Term, m.Type, m.From, m.Term)
  756. }
  757. return nil
  758. }
  759. switch m.Type {
  760. case pb.MsgHup:
  761. if r.state != StateLeader {
  762. if !r.promotable() {
  763. r.logger.Warningf("%x is unpromotable and can not campaign; ignoring MsgHup", r.id)
  764. return nil
  765. }
  766. ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
  767. if err != nil {
  768. r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
  769. }
  770. if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
  771. r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
  772. return nil
  773. }
  774. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  775. if r.preVote {
  776. r.campaign(campaignPreElection)
  777. } else {
  778. r.campaign(campaignElection)
  779. }
  780. } else {
  781. r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
  782. }
  783. case pb.MsgVote, pb.MsgPreVote:
  784. if r.isLearner {
  785. // TODO: learner may need to vote, in case of node down when confchange.
  786. 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",
  787. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  788. return nil
  789. }
  790. // We can vote if this is a repeat of a vote we've already cast...
  791. canVote := r.Vote == m.From ||
  792. // ...we haven't voted and we don't think there's a leader yet in this term...
  793. (r.Vote == None && r.lead == None) ||
  794. // ...or this is a PreVote for a future term...
  795. (m.Type == pb.MsgPreVote && m.Term > r.Term)
  796. // ...and we believe the candidate is up to date.
  797. if canVote && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  798. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
  799. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  800. // When responding to Msg{Pre,}Vote messages we include the term
  801. // from the message, not the local term. To see why, consider the
  802. // case where a single node was previously partitioned away and
  803. // it's local term is now out of date. If we include the local term
  804. // (recall that for pre-votes we don't update the local term), the
  805. // (pre-)campaigning node on the other end will proceed to ignore
  806. // the message (it ignores all out of date messages).
  807. // The term in the original message and current local term are the
  808. // same in the case of regular votes, but different for pre-votes.
  809. r.send(pb.Message{To: m.From, Term: m.Term, Type: voteRespMsgType(m.Type)})
  810. if m.Type == pb.MsgVote {
  811. // Only record real votes.
  812. r.electionElapsed = 0
  813. r.Vote = m.From
  814. }
  815. } else {
  816. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  817. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  818. r.send(pb.Message{To: m.From, Term: r.Term, Type: voteRespMsgType(m.Type), Reject: true})
  819. }
  820. default:
  821. err := r.step(r, m)
  822. if err != nil {
  823. return err
  824. }
  825. }
  826. return nil
  827. }
  828. type stepFunc func(r *raft, m pb.Message) error
  829. func stepLeader(r *raft, m pb.Message) error {
  830. // These message types do not require any progress for m.From.
  831. switch m.Type {
  832. case pb.MsgBeat:
  833. r.bcastHeartbeat()
  834. return nil
  835. case pb.MsgCheckQuorum:
  836. // The leader should always see itself as active. As a precaution, handle
  837. // the case in which the leader isn't in the configuration any more (for
  838. // example if it just removed itself).
  839. //
  840. // TODO(tbg): I added a TODO in removeNode, it doesn't seem that the
  841. // leader steps down when removing itself. I might be missing something.
  842. if pr := r.prs.Progress[r.id]; pr != nil {
  843. pr.RecentActive = true
  844. }
  845. if !r.prs.QuorumActive() {
  846. r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
  847. r.becomeFollower(r.Term, None)
  848. }
  849. // Mark everyone (but ourselves) as inactive in preparation for the next
  850. // CheckQuorum.
  851. r.prs.Visit(func(id uint64, pr *tracker.Progress) {
  852. if id != r.id {
  853. pr.RecentActive = false
  854. }
  855. })
  856. return nil
  857. case pb.MsgProp:
  858. if len(m.Entries) == 0 {
  859. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  860. }
  861. if r.prs.Progress[r.id] == nil {
  862. // If we are not currently a member of the range (i.e. this node
  863. // was removed from the configuration while serving as leader),
  864. // drop any new proposals.
  865. return ErrProposalDropped
  866. }
  867. if r.leadTransferee != None {
  868. r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
  869. return ErrProposalDropped
  870. }
  871. for i := range m.Entries {
  872. e := &m.Entries[i]
  873. if e.Type == pb.EntryConfChange {
  874. if r.pendingConfIndex > r.raftLog.applied {
  875. r.logger.Infof("propose conf %s ignored since pending unapplied configuration [index %d, applied %d]",
  876. e, r.pendingConfIndex, r.raftLog.applied)
  877. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  878. } else {
  879. r.pendingConfIndex = r.raftLog.lastIndex() + uint64(i) + 1
  880. }
  881. }
  882. }
  883. if !r.appendEntry(m.Entries...) {
  884. return ErrProposalDropped
  885. }
  886. r.bcastAppend()
  887. return nil
  888. case pb.MsgReadIndex:
  889. // If more than the local vote is needed, go through a full broadcast,
  890. // otherwise optimize.
  891. if !r.prs.IsSingleton() {
  892. if r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(r.raftLog.committed)) != r.Term {
  893. // Reject read only request when this leader has not committed any log entry at its term.
  894. return nil
  895. }
  896. // thinking: use an interally defined context instead of the user given context.
  897. // We can express this in terms of the term and index instead of a user-supplied value.
  898. // This would allow multiple reads to piggyback on the same message.
  899. switch r.readOnly.option {
  900. case ReadOnlySafe:
  901. r.readOnly.addRequest(r.raftLog.committed, m)
  902. // The local node automatically acks the request.
  903. r.readOnly.recvAck(r.id, m.Entries[0].Data)
  904. r.bcastHeartbeatWithCtx(m.Entries[0].Data)
  905. case ReadOnlyLeaseBased:
  906. ri := r.raftLog.committed
  907. if m.From == None || m.From == r.id { // from local member
  908. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  909. } else {
  910. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  911. }
  912. }
  913. } else { // only one voting member (the leader) in the cluster
  914. if m.From == None || m.From == r.id { // from leader itself
  915. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  916. } else { // from learner member
  917. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: r.raftLog.committed, Entries: m.Entries})
  918. }
  919. }
  920. return nil
  921. }
  922. // All other message types require a progress for m.From (pr).
  923. pr := r.prs.Progress[m.From]
  924. if pr == nil {
  925. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  926. return nil
  927. }
  928. switch m.Type {
  929. case pb.MsgAppResp:
  930. pr.RecentActive = true
  931. if m.Reject {
  932. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  933. r.id, m.RejectHint, m.From, m.Index)
  934. if pr.MaybeDecrTo(m.Index, m.RejectHint) {
  935. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  936. if pr.State == tracker.StateReplicate {
  937. pr.BecomeProbe()
  938. }
  939. r.sendAppend(m.From)
  940. }
  941. } else {
  942. oldPaused := pr.IsPaused()
  943. if pr.MaybeUpdate(m.Index) {
  944. switch {
  945. case pr.State == tracker.StateProbe:
  946. pr.BecomeReplicate()
  947. case pr.State == tracker.StateSnapshot && pr.Match >= pr.PendingSnapshot:
  948. r.logger.Debugf("%x recovered from needing snapshot, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  949. // Transition back to replicating state via probing state
  950. // (which takes the snapshot into account). If we didn't
  951. // move to replicating state, that would only happen with
  952. // the next round of appends (but there may not be a next
  953. // round for a while, exposing an inconsistent RaftStatus).
  954. pr.BecomeProbe()
  955. pr.BecomeReplicate()
  956. case pr.State == tracker.StateReplicate:
  957. pr.Inflights.FreeLE(m.Index)
  958. }
  959. if r.maybeCommit() {
  960. r.bcastAppend()
  961. } else if oldPaused {
  962. // If we were paused before, this node may be missing the
  963. // latest commit index, so send it.
  964. r.sendAppend(m.From)
  965. }
  966. // We've updated flow control information above, which may
  967. // allow us to send multiple (size-limited) in-flight messages
  968. // at once (such as when transitioning from probe to
  969. // replicate, or when freeTo() covers multiple messages). If
  970. // we have more entries to send, send as many messages as we
  971. // can (without sending empty messages for the commit index)
  972. for r.maybeSendAppend(m.From, false) {
  973. }
  974. // Transfer leadership is in progress.
  975. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  976. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  977. r.sendTimeoutNow(m.From)
  978. }
  979. }
  980. }
  981. case pb.MsgHeartbeatResp:
  982. pr.RecentActive = true
  983. pr.ProbeSent = false
  984. // free one slot for the full inflights window to allow progress.
  985. if pr.State == tracker.StateReplicate && pr.Inflights.Full() {
  986. pr.Inflights.FreeFirstOne()
  987. }
  988. if pr.Match < r.raftLog.lastIndex() {
  989. r.sendAppend(m.From)
  990. }
  991. if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
  992. return nil
  993. }
  994. if r.prs.Voters.VoteResult(r.readOnly.recvAck(m.From, m.Context)) != quorum.VoteWon {
  995. return nil
  996. }
  997. rss := r.readOnly.advance(m)
  998. for _, rs := range rss {
  999. req := rs.req
  1000. if req.From == None || req.From == r.id { // from local member
  1001. r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
  1002. } else {
  1003. r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
  1004. }
  1005. }
  1006. case pb.MsgSnapStatus:
  1007. if pr.State != tracker.StateSnapshot {
  1008. return nil
  1009. }
  1010. // TODO(tbg): this code is very similar to the snapshot handling in
  1011. // MsgAppResp above. In fact, the code there is more correct than the
  1012. // code here and should likely be updated to match (or even better, the
  1013. // logic pulled into a newly created Progress state machine handler).
  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. // NB: the order here matters or we'll be probing erroneously from
  1019. // the snapshot index, but the snapshot never applied.
  1020. pr.PendingSnapshot = 0
  1021. pr.BecomeProbe()
  1022. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  1023. }
  1024. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  1025. // out the next msgApp.
  1026. // If snapshot failure, wait for a heartbeat interval before next try
  1027. pr.ProbeSent = true
  1028. case pb.MsgUnreachable:
  1029. // During optimistic replication, if the remote becomes unreachable,
  1030. // there is huge probability that a MsgApp is lost.
  1031. if pr.State == tracker.StateReplicate {
  1032. pr.BecomeProbe()
  1033. }
  1034. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  1035. case pb.MsgTransferLeader:
  1036. if pr.IsLearner {
  1037. r.logger.Debugf("%x is learner. Ignored transferring leadership", r.id)
  1038. return nil
  1039. }
  1040. leadTransferee := m.From
  1041. lastLeadTransferee := r.leadTransferee
  1042. if lastLeadTransferee != None {
  1043. if lastLeadTransferee == leadTransferee {
  1044. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  1045. r.id, r.Term, leadTransferee, leadTransferee)
  1046. return nil
  1047. }
  1048. r.abortLeaderTransfer()
  1049. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  1050. }
  1051. if leadTransferee == r.id {
  1052. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  1053. return nil
  1054. }
  1055. // Transfer leadership to third party.
  1056. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  1057. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  1058. r.electionElapsed = 0
  1059. r.leadTransferee = leadTransferee
  1060. if pr.Match == r.raftLog.lastIndex() {
  1061. r.sendTimeoutNow(leadTransferee)
  1062. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  1063. } else {
  1064. r.sendAppend(leadTransferee)
  1065. }
  1066. }
  1067. return nil
  1068. }
  1069. // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
  1070. // whether they respond to MsgVoteResp or MsgPreVoteResp.
  1071. func stepCandidate(r *raft, m pb.Message) error {
  1072. // Only handle vote responses corresponding to our candidacy (while in
  1073. // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
  1074. // our pre-candidate state).
  1075. var myVoteRespType pb.MessageType
  1076. if r.state == StatePreCandidate {
  1077. myVoteRespType = pb.MsgPreVoteResp
  1078. } else {
  1079. myVoteRespType = pb.MsgVoteResp
  1080. }
  1081. switch m.Type {
  1082. case pb.MsgProp:
  1083. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1084. return ErrProposalDropped
  1085. case pb.MsgApp:
  1086. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1087. r.handleAppendEntries(m)
  1088. case pb.MsgHeartbeat:
  1089. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1090. r.handleHeartbeat(m)
  1091. case pb.MsgSnap:
  1092. r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
  1093. r.handleSnapshot(m)
  1094. case myVoteRespType:
  1095. gr, rj, res := r.poll(m.From, m.Type, !m.Reject)
  1096. r.logger.Infof("%x has received %d %s votes and %d vote rejections", r.id, gr, m.Type, rj)
  1097. switch res {
  1098. case quorum.VoteWon:
  1099. if r.state == StatePreCandidate {
  1100. r.campaign(campaignElection)
  1101. } else {
  1102. r.becomeLeader()
  1103. r.bcastAppend()
  1104. }
  1105. case quorum.VoteLost:
  1106. // pb.MsgPreVoteResp contains future term of pre-candidate
  1107. // m.Term > r.Term; reuse r.Term
  1108. r.becomeFollower(r.Term, None)
  1109. }
  1110. case pb.MsgTimeoutNow:
  1111. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  1112. }
  1113. return nil
  1114. }
  1115. func stepFollower(r *raft, m pb.Message) error {
  1116. switch m.Type {
  1117. case pb.MsgProp:
  1118. if r.lead == None {
  1119. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1120. return ErrProposalDropped
  1121. } else if r.disableProposalForwarding {
  1122. r.logger.Infof("%x not forwarding to leader %x at term %d; dropping proposal", r.id, r.lead, r.Term)
  1123. return ErrProposalDropped
  1124. }
  1125. m.To = r.lead
  1126. r.send(m)
  1127. case pb.MsgApp:
  1128. r.electionElapsed = 0
  1129. r.lead = m.From
  1130. r.handleAppendEntries(m)
  1131. case pb.MsgHeartbeat:
  1132. r.electionElapsed = 0
  1133. r.lead = m.From
  1134. r.handleHeartbeat(m)
  1135. case pb.MsgSnap:
  1136. r.electionElapsed = 0
  1137. r.lead = m.From
  1138. r.handleSnapshot(m)
  1139. case pb.MsgTransferLeader:
  1140. if r.lead == None {
  1141. r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
  1142. return nil
  1143. }
  1144. m.To = r.lead
  1145. r.send(m)
  1146. case pb.MsgTimeoutNow:
  1147. if r.promotable() {
  1148. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  1149. // Leadership transfers never use pre-vote even if r.preVote is true; we
  1150. // know we are not recovering from a partition so there is no need for the
  1151. // extra round trip.
  1152. r.campaign(campaignTransfer)
  1153. } else {
  1154. r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
  1155. }
  1156. case pb.MsgReadIndex:
  1157. if r.lead == None {
  1158. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  1159. return nil
  1160. }
  1161. m.To = r.lead
  1162. r.send(m)
  1163. case pb.MsgReadIndexResp:
  1164. if len(m.Entries) != 1 {
  1165. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  1166. return nil
  1167. }
  1168. r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
  1169. }
  1170. return nil
  1171. }
  1172. func (r *raft) handleAppendEntries(m pb.Message) {
  1173. if m.Index < r.raftLog.committed {
  1174. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1175. return
  1176. }
  1177. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  1178. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  1179. } else {
  1180. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  1181. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  1182. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  1183. }
  1184. }
  1185. func (r *raft) handleHeartbeat(m pb.Message) {
  1186. r.raftLog.commitTo(m.Commit)
  1187. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
  1188. }
  1189. func (r *raft) handleSnapshot(m pb.Message) {
  1190. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  1191. if r.restore(m.Snapshot) {
  1192. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  1193. r.id, r.raftLog.committed, sindex, sterm)
  1194. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  1195. } else {
  1196. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  1197. r.id, r.raftLog.committed, sindex, sterm)
  1198. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1199. }
  1200. }
  1201. // restore recovers the state machine from a snapshot. It restores the log and the
  1202. // configuration of state machine. If this method returns false, the snapshot was
  1203. // ignored, either because it was obsolete or because of an error.
  1204. func (r *raft) restore(s pb.Snapshot) bool {
  1205. if s.Metadata.Index <= r.raftLog.committed {
  1206. return false
  1207. }
  1208. if r.state != StateFollower {
  1209. // This is defense-in-depth: if the leader somehow ended up applying a
  1210. // snapshot, it could move into a new term without moving into a
  1211. // follower state. This should never fire, but if it did, we'd have
  1212. // prevented damage by returning early, so log only a loud warning.
  1213. //
  1214. // At the time of writing, the instance is guaranteed to be in follower
  1215. // state when this method is called.
  1216. r.logger.Warningf("%x attempted to restore snapshot as leader; should never happen", r.id)
  1217. r.becomeFollower(r.Term+1, None)
  1218. return false
  1219. }
  1220. // More defense-in-depth: throw away snapshot if recipient is not in the
  1221. // config. This shouuldn't ever happen (at the time of writing) but lots of
  1222. // code here and there assumes that r.id is in the progress tracker.
  1223. found := false
  1224. cs := s.Metadata.ConfState
  1225. for _, set := range [][]uint64{
  1226. cs.Nodes,
  1227. cs.Learners,
  1228. } {
  1229. for _, id := range set {
  1230. if id == r.id {
  1231. found = true
  1232. break
  1233. }
  1234. }
  1235. }
  1236. if !found {
  1237. r.logger.Warningf(
  1238. "%x attempted to restore snapshot but it is not in the ConfState %v; should never happen",
  1239. r.id, cs,
  1240. )
  1241. return false
  1242. }
  1243. // Now go ahead and actually restore.
  1244. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  1245. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  1246. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1247. r.raftLog.commitTo(s.Metadata.Index)
  1248. return false
  1249. }
  1250. r.raftLog.restore(s)
  1251. // Reset the configuration and add the (potentially updated) peers in anew.
  1252. r.prs = tracker.MakeProgressTracker(r.prs.MaxInflight)
  1253. for _, id := range s.Metadata.ConfState.Nodes {
  1254. r.applyConfChange(pb.ConfChange{NodeID: id, Type: pb.ConfChangeAddNode})
  1255. }
  1256. for _, id := range s.Metadata.ConfState.Learners {
  1257. r.applyConfChange(pb.ConfChange{NodeID: id, Type: pb.ConfChangeAddLearnerNode})
  1258. }
  1259. pr := r.prs.Progress[r.id]
  1260. pr.MaybeUpdate(pr.Next - 1) // TODO(tbg): this is untested and likely unneeded
  1261. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] restored snapshot [index: %d, term: %d]",
  1262. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1263. return true
  1264. }
  1265. // promotable indicates whether state machine can be promoted to leader,
  1266. // which is true when its own id is in progress list.
  1267. func (r *raft) promotable() bool {
  1268. pr := r.prs.Progress[r.id]
  1269. return pr != nil && !pr.IsLearner
  1270. }
  1271. func (r *raft) applyConfChange(cc pb.ConfChange) pb.ConfState {
  1272. cfg, prs, err := confchange.Changer{
  1273. Tracker: r.prs,
  1274. LastIndex: r.raftLog.lastIndex(),
  1275. }.Simple(cc)
  1276. if err != nil {
  1277. panic(err)
  1278. }
  1279. r.prs.Config = cfg
  1280. r.prs.Progress = prs
  1281. r.logger.Infof("%x switched to configuration %s", r.id, r.prs.Config)
  1282. // Now that the configuration is updated, handle any side effects.
  1283. cs := pb.ConfState{Nodes: r.prs.VoterNodes(), Learners: r.prs.LearnerNodes()}
  1284. pr, ok := r.prs.Progress[r.id]
  1285. // Update whether the node itself is a learner, resetting to false when the
  1286. // node is removed.
  1287. r.isLearner = ok && pr.IsLearner
  1288. if (!ok || r.isLearner) && r.state == StateLeader {
  1289. // This node is leader and was removed or demoted. We prevent demotions
  1290. // at the time writing but hypothetically we handle them the same way as
  1291. // removing the leader: stepping down into the next Term.
  1292. //
  1293. // TODO(tbg): step down (for sanity) and ask follower with largest Match
  1294. // to TimeoutNow (to avoid interruption). This might still drop some
  1295. // proposals but it's better than nothing.
  1296. //
  1297. // TODO(tbg): test this branch. It is untested at the time of writing.
  1298. return cs
  1299. }
  1300. // The remaining steps only make sense if this node is the leader and there
  1301. // are other nodes.
  1302. if r.state != StateLeader || len(cs.Nodes) == 0 {
  1303. return cs
  1304. }
  1305. if r.maybeCommit() {
  1306. // The quorum size may have been reduced (but not to zero), so see if
  1307. // any pending entries can be committed.
  1308. r.bcastAppend()
  1309. }
  1310. // If the the leadTransferee was removed, abort the leadership transfer.
  1311. if _, tOK := r.prs.Progress[r.leadTransferee]; !tOK && r.leadTransferee != 0 {
  1312. r.abortLeaderTransfer()
  1313. }
  1314. return cs
  1315. }
  1316. func (r *raft) loadState(state pb.HardState) {
  1317. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  1318. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  1319. }
  1320. r.raftLog.committed = state.Commit
  1321. r.Term = state.Term
  1322. r.Vote = state.Vote
  1323. }
  1324. // pastElectionTimeout returns true iff r.electionElapsed is greater
  1325. // than or equal to the randomized election timeout in
  1326. // [electiontimeout, 2 * electiontimeout - 1].
  1327. func (r *raft) pastElectionTimeout() bool {
  1328. return r.electionElapsed >= r.randomizedElectionTimeout
  1329. }
  1330. func (r *raft) resetRandomizedElectionTimeout() {
  1331. r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
  1332. }
  1333. func (r *raft) sendTimeoutNow(to uint64) {
  1334. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  1335. }
  1336. func (r *raft) abortLeaderTransfer() {
  1337. r.leadTransferee = None
  1338. }
  1339. // increaseUncommittedSize computes the size of the proposed entries and
  1340. // determines whether they would push leader over its maxUncommittedSize limit.
  1341. // If the new entries would exceed the limit, the method returns false. If not,
  1342. // the increase in uncommitted entry size is recorded and the method returns
  1343. // true.
  1344. func (r *raft) increaseUncommittedSize(ents []pb.Entry) bool {
  1345. var s uint64
  1346. for _, e := range ents {
  1347. s += uint64(PayloadSize(e))
  1348. }
  1349. if r.uncommittedSize > 0 && r.uncommittedSize+s > r.maxUncommittedSize {
  1350. // If the uncommitted tail of the Raft log is empty, allow any size
  1351. // proposal. Otherwise, limit the size of the uncommitted tail of the
  1352. // log and drop any proposal that would push the size over the limit.
  1353. return false
  1354. }
  1355. r.uncommittedSize += s
  1356. return true
  1357. }
  1358. // reduceUncommittedSize accounts for the newly committed entries by decreasing
  1359. // the uncommitted entry size limit.
  1360. func (r *raft) reduceUncommittedSize(ents []pb.Entry) {
  1361. if r.uncommittedSize == 0 {
  1362. // Fast-path for followers, who do not track or enforce the limit.
  1363. return
  1364. }
  1365. var s uint64
  1366. for _, e := range ents {
  1367. s += uint64(PayloadSize(e))
  1368. }
  1369. if s > r.uncommittedSize {
  1370. // uncommittedSize may underestimate the size of the uncommitted Raft
  1371. // log tail but will never overestimate it. Saturate at 0 instead of
  1372. // allowing overflow.
  1373. r.uncommittedSize = 0
  1374. } else {
  1375. r.uncommittedSize -= s
  1376. }
  1377. }
  1378. func numOfPendingConf(ents []pb.Entry) int {
  1379. n := 0
  1380. for i := range ents {
  1381. if ents[i].Type == pb.EntryConfChange {
  1382. n++
  1383. }
  1384. }
  1385. return n
  1386. }