raft.go 46 KB

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