raft.go 54 KB

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