raft.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  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. r.raftLog.append(es...)
  524. r.getProgress(r.id).maybeUpdate(r.raftLog.lastIndex())
  525. // Regardless of maybeCommit's return, our caller will call bcastAppend.
  526. r.maybeCommit()
  527. }
  528. // tickElection is run by followers and candidates after r.electionTimeout.
  529. func (r *raft) tickElection() {
  530. r.electionElapsed++
  531. if r.promotable() && r.pastElectionTimeout() {
  532. r.electionElapsed = 0
  533. r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
  534. }
  535. }
  536. // tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout.
  537. func (r *raft) tickHeartbeat() {
  538. r.heartbeatElapsed++
  539. r.electionElapsed++
  540. if r.electionElapsed >= r.electionTimeout {
  541. r.electionElapsed = 0
  542. if r.checkQuorum {
  543. r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
  544. }
  545. // If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
  546. if r.state == StateLeader && r.leadTransferee != None {
  547. r.abortLeaderTransfer()
  548. }
  549. }
  550. if r.state != StateLeader {
  551. return
  552. }
  553. if r.heartbeatElapsed >= r.heartbeatTimeout {
  554. r.heartbeatElapsed = 0
  555. r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
  556. }
  557. }
  558. func (r *raft) becomeFollower(term uint64, lead uint64) {
  559. r.step = stepFollower
  560. r.reset(term)
  561. r.tick = r.tickElection
  562. r.lead = lead
  563. r.state = StateFollower
  564. r.logger.Infof("%x became follower at term %d", r.id, r.Term)
  565. }
  566. func (r *raft) becomeCandidate() {
  567. // TODO(xiangli) remove the panic when the raft implementation is stable
  568. if r.state == StateLeader {
  569. panic("invalid transition [leader -> candidate]")
  570. }
  571. r.step = stepCandidate
  572. r.reset(r.Term + 1)
  573. r.tick = r.tickElection
  574. r.Vote = r.id
  575. r.state = StateCandidate
  576. r.logger.Infof("%x became candidate at term %d", r.id, r.Term)
  577. }
  578. func (r *raft) becomePreCandidate() {
  579. // TODO(xiangli) remove the panic when the raft implementation is stable
  580. if r.state == StateLeader {
  581. panic("invalid transition [leader -> pre-candidate]")
  582. }
  583. // Becoming a pre-candidate changes our step functions and state,
  584. // but doesn't change anything else. In particular it does not increase
  585. // r.Term or change r.Vote.
  586. r.step = stepCandidate
  587. r.votes = make(map[uint64]bool)
  588. r.tick = r.tickElection
  589. r.state = StatePreCandidate
  590. r.logger.Infof("%x became pre-candidate at term %d", r.id, r.Term)
  591. }
  592. func (r *raft) becomeLeader() {
  593. // TODO(xiangli) remove the panic when the raft implementation is stable
  594. if r.state == StateFollower {
  595. panic("invalid transition [follower -> leader]")
  596. }
  597. r.step = stepLeader
  598. r.reset(r.Term)
  599. r.tick = r.tickHeartbeat
  600. r.lead = r.id
  601. r.state = StateLeader
  602. ents, err := r.raftLog.entries(r.raftLog.committed+1, noLimit)
  603. if err != nil {
  604. r.logger.Panicf("unexpected error getting uncommitted entries (%v)", err)
  605. }
  606. // Conservatively set the pendingConfIndex to the last index in the
  607. // log. There may or may not be a pending config change, but it's
  608. // safe to delay any future proposals until we commit all our
  609. // pending log entries, and scanning the entire tail of the log
  610. // could be expensive.
  611. if len(ents) > 0 {
  612. r.pendingConfIndex = ents[len(ents)-1].Index
  613. }
  614. r.appendEntry(pb.Entry{Data: nil})
  615. r.logger.Infof("%x became leader at term %d", r.id, r.Term)
  616. }
  617. func (r *raft) campaign(t CampaignType) {
  618. var term uint64
  619. var voteMsg pb.MessageType
  620. if t == campaignPreElection {
  621. r.becomePreCandidate()
  622. voteMsg = pb.MsgPreVote
  623. // PreVote RPCs are sent for the next term before we've incremented r.Term.
  624. term = r.Term + 1
  625. } else {
  626. r.becomeCandidate()
  627. voteMsg = pb.MsgVote
  628. term = r.Term
  629. }
  630. if r.quorum() == r.poll(r.id, voteRespMsgType(voteMsg), true) {
  631. // We won the election after voting for ourselves (which must mean that
  632. // this is a single-node cluster). Advance to the next state.
  633. if t == campaignPreElection {
  634. r.campaign(campaignElection)
  635. } else {
  636. r.becomeLeader()
  637. }
  638. return
  639. }
  640. for id := range r.prs {
  641. if id == r.id {
  642. continue
  643. }
  644. r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d",
  645. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
  646. var ctx []byte
  647. if t == campaignTransfer {
  648. ctx = []byte(t)
  649. }
  650. r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
  651. }
  652. }
  653. func (r *raft) poll(id uint64, t pb.MessageType, v bool) (granted int) {
  654. if v {
  655. r.logger.Infof("%x received %s from %x at term %d", r.id, t, id, r.Term)
  656. } else {
  657. r.logger.Infof("%x received %s rejection from %x at term %d", r.id, t, id, r.Term)
  658. }
  659. if _, ok := r.votes[id]; !ok {
  660. r.votes[id] = v
  661. }
  662. for _, vv := range r.votes {
  663. if vv {
  664. granted++
  665. }
  666. }
  667. return granted
  668. }
  669. func (r *raft) Step(m pb.Message) error {
  670. // Handle the message term, which may result in our stepping down to a follower.
  671. switch {
  672. case m.Term == 0:
  673. // local message
  674. case m.Term > r.Term:
  675. if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote {
  676. force := bytes.Equal(m.Context, []byte(campaignTransfer))
  677. inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout
  678. if !force && inLease {
  679. // If a server receives a RequestVote request within the minimum election timeout
  680. // of hearing from a current leader, it does not update its term or grant its vote
  681. 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)",
  682. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed)
  683. return nil
  684. }
  685. }
  686. switch {
  687. case m.Type == pb.MsgPreVote:
  688. // Never change our term in response to a PreVote
  689. case m.Type == pb.MsgPreVoteResp && !m.Reject:
  690. // We send pre-vote requests with a term in our future. If the
  691. // pre-vote is granted, we will increment our term when we get a
  692. // quorum. If it is not, the term comes from the node that
  693. // rejected our vote so we should become a follower at the new
  694. // term.
  695. default:
  696. r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]",
  697. r.id, r.Term, m.Type, m.From, m.Term)
  698. if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap {
  699. r.becomeFollower(m.Term, m.From)
  700. } else {
  701. r.becomeFollower(m.Term, None)
  702. }
  703. }
  704. case m.Term < r.Term:
  705. if (r.checkQuorum || r.preVote) && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) {
  706. // We have received messages from a leader at a lower term. It is possible
  707. // that these messages were simply delayed in the network, but this could
  708. // also mean that this node has advanced its term number during a network
  709. // partition, and it is now unable to either win an election or to rejoin
  710. // the majority on the old term. If checkQuorum is false, this will be
  711. // handled by incrementing term numbers in response to MsgVote with a
  712. // higher term, but if checkQuorum is true we may not advance the term on
  713. // MsgVote and must generate other messages to advance the term. The net
  714. // result of these two features is to minimize the disruption caused by
  715. // nodes that have been removed from the cluster's configuration: a
  716. // removed node will send MsgVotes (or MsgPreVotes) which will be ignored,
  717. // but it will not receive MsgApp or MsgHeartbeat, so it will not create
  718. // disruptive term increases
  719. // The above comments also true for Pre-Vote
  720. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp})
  721. } else if m.Type == pb.MsgPreVote {
  722. // Before Pre-Vote enable, there may have candidate with higher term,
  723. // but less log. After update to Pre-Vote, the cluster may deadlock if
  724. // we drop messages with a lower term.
  725. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  726. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  727. r.send(pb.Message{To: m.From, Term: r.Term, Type: pb.MsgPreVoteResp, Reject: true})
  728. } else {
  729. // ignore other cases
  730. r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]",
  731. r.id, r.Term, m.Type, m.From, m.Term)
  732. }
  733. return nil
  734. }
  735. switch m.Type {
  736. case pb.MsgHup:
  737. if r.state != StateLeader {
  738. ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit)
  739. if err != nil {
  740. r.logger.Panicf("unexpected error getting unapplied entries (%v)", err)
  741. }
  742. if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied {
  743. r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n)
  744. return nil
  745. }
  746. r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
  747. if r.preVote {
  748. r.campaign(campaignPreElection)
  749. } else {
  750. r.campaign(campaignElection)
  751. }
  752. } else {
  753. r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
  754. }
  755. case pb.MsgVote, pb.MsgPreVote:
  756. if r.isLearner {
  757. // TODO: learner may need to vote, in case of node down when confchange.
  758. 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",
  759. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  760. return nil
  761. }
  762. // We can vote if this is a repeat of a vote we've already cast...
  763. canVote := r.Vote == m.From ||
  764. // ...we haven't voted and we don't think there's a leader yet in this term...
  765. (r.Vote == None && r.lead == None) ||
  766. // ...or this is a PreVote for a future term...
  767. (m.Type == pb.MsgPreVote && m.Term > r.Term)
  768. // ...and we believe the candidate is up to date.
  769. if canVote && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
  770. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %x [logterm: %d, index: %d] at term %d",
  771. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  772. // When responding to Msg{Pre,}Vote messages we include the term
  773. // from the message, not the local term. To see why consider the
  774. // case where a single node was previously partitioned away and
  775. // it's local term is now of date. If we include the local term
  776. // (recall that for pre-votes we don't update the local term), the
  777. // (pre-)campaigning node on the other end will proceed to ignore
  778. // the message (it ignores all out of date messages).
  779. // The term in the original message and current local term are the
  780. // same in the case of regular votes, but different for pre-votes.
  781. r.send(pb.Message{To: m.From, Term: m.Term, Type: voteRespMsgType(m.Type)})
  782. if m.Type == pb.MsgVote {
  783. // Only record real votes.
  784. r.electionElapsed = 0
  785. r.Vote = m.From
  786. }
  787. } else {
  788. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d",
  789. r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
  790. r.send(pb.Message{To: m.From, Term: r.Term, Type: voteRespMsgType(m.Type), Reject: true})
  791. }
  792. default:
  793. err := r.step(r, m)
  794. if err != nil {
  795. return err
  796. }
  797. }
  798. return nil
  799. }
  800. type stepFunc func(r *raft, m pb.Message) error
  801. func stepLeader(r *raft, m pb.Message) error {
  802. // These message types do not require any progress for m.From.
  803. switch m.Type {
  804. case pb.MsgBeat:
  805. r.bcastHeartbeat()
  806. return nil
  807. case pb.MsgCheckQuorum:
  808. if !r.checkQuorumActive() {
  809. r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id)
  810. r.becomeFollower(r.Term, None)
  811. }
  812. return nil
  813. case pb.MsgProp:
  814. if len(m.Entries) == 0 {
  815. r.logger.Panicf("%x stepped empty MsgProp", r.id)
  816. }
  817. if _, ok := r.prs[r.id]; !ok {
  818. // If we are not currently a member of the range (i.e. this node
  819. // was removed from the configuration while serving as leader),
  820. // drop any new proposals.
  821. return ErrProposalDropped
  822. }
  823. if r.leadTransferee != None {
  824. r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee)
  825. return ErrProposalDropped
  826. }
  827. for i, e := range m.Entries {
  828. if e.Type == pb.EntryConfChange {
  829. if r.pendingConfIndex > r.raftLog.applied {
  830. r.logger.Infof("propose conf %s ignored since pending unapplied configuration [index %d, applied %d]",
  831. e.String(), r.pendingConfIndex, r.raftLog.applied)
  832. m.Entries[i] = pb.Entry{Type: pb.EntryNormal}
  833. } else {
  834. r.pendingConfIndex = r.raftLog.lastIndex() + uint64(i) + 1
  835. }
  836. }
  837. }
  838. r.appendEntry(m.Entries...)
  839. r.bcastAppend()
  840. return nil
  841. case pb.MsgReadIndex:
  842. if r.quorum() > 1 {
  843. if r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(r.raftLog.committed)) != r.Term {
  844. // Reject read only request when this leader has not committed any log entry at its term.
  845. return nil
  846. }
  847. // thinking: use an interally defined context instead of the user given context.
  848. // We can express this in terms of the term and index instead of a user-supplied value.
  849. // This would allow multiple reads to piggyback on the same message.
  850. switch r.readOnly.option {
  851. case ReadOnlySafe:
  852. r.readOnly.addRequest(r.raftLog.committed, m)
  853. r.bcastHeartbeatWithCtx(m.Entries[0].Data)
  854. case ReadOnlyLeaseBased:
  855. ri := r.raftLog.committed
  856. if m.From == None || m.From == r.id { // from local member
  857. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  858. } else {
  859. r.send(pb.Message{To: m.From, Type: pb.MsgReadIndexResp, Index: ri, Entries: m.Entries})
  860. }
  861. }
  862. } else {
  863. r.readStates = append(r.readStates, ReadState{Index: r.raftLog.committed, RequestCtx: m.Entries[0].Data})
  864. }
  865. return nil
  866. }
  867. // All other message types require a progress for m.From (pr).
  868. pr := r.getProgress(m.From)
  869. if pr == nil {
  870. r.logger.Debugf("%x no progress available for %x", r.id, m.From)
  871. return nil
  872. }
  873. switch m.Type {
  874. case pb.MsgAppResp:
  875. pr.RecentActive = true
  876. if m.Reject {
  877. r.logger.Debugf("%x received msgApp rejection(lastindex: %d) from %x for index %d",
  878. r.id, m.RejectHint, m.From, m.Index)
  879. if pr.maybeDecrTo(m.Index, m.RejectHint) {
  880. r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr)
  881. if pr.State == ProgressStateReplicate {
  882. pr.becomeProbe()
  883. }
  884. r.sendAppend(m.From)
  885. }
  886. } else {
  887. oldPaused := pr.IsPaused()
  888. if pr.maybeUpdate(m.Index) {
  889. switch {
  890. case pr.State == ProgressStateProbe:
  891. pr.becomeReplicate()
  892. case pr.State == ProgressStateSnapshot && pr.needSnapshotAbort():
  893. r.logger.Debugf("%x snapshot aborted, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  894. pr.becomeProbe()
  895. case pr.State == ProgressStateReplicate:
  896. pr.ins.freeTo(m.Index)
  897. }
  898. if r.maybeCommit() {
  899. r.bcastAppend()
  900. } else if oldPaused {
  901. // update() reset the wait state on this node. If we had delayed sending
  902. // an update before, send it now.
  903. r.sendAppend(m.From)
  904. }
  905. // Transfer leadership is in progress.
  906. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() {
  907. r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From)
  908. r.sendTimeoutNow(m.From)
  909. }
  910. }
  911. }
  912. case pb.MsgHeartbeatResp:
  913. pr.RecentActive = true
  914. pr.resume()
  915. // free one slot for the full inflights window to allow progress.
  916. if pr.State == ProgressStateReplicate && pr.ins.full() {
  917. pr.ins.freeFirstOne()
  918. }
  919. if pr.Match < r.raftLog.lastIndex() {
  920. r.sendAppend(m.From)
  921. }
  922. if r.readOnly.option != ReadOnlySafe || len(m.Context) == 0 {
  923. return nil
  924. }
  925. ackCount := r.readOnly.recvAck(m)
  926. if ackCount < r.quorum() {
  927. return nil
  928. }
  929. rss := r.readOnly.advance(m)
  930. for _, rs := range rss {
  931. req := rs.req
  932. if req.From == None || req.From == r.id { // from local member
  933. r.readStates = append(r.readStates, ReadState{Index: rs.index, RequestCtx: req.Entries[0].Data})
  934. } else {
  935. r.send(pb.Message{To: req.From, Type: pb.MsgReadIndexResp, Index: rs.index, Entries: req.Entries})
  936. }
  937. }
  938. case pb.MsgSnapStatus:
  939. if pr.State != ProgressStateSnapshot {
  940. return nil
  941. }
  942. if !m.Reject {
  943. pr.becomeProbe()
  944. r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  945. } else {
  946. pr.snapshotFailure()
  947. pr.becomeProbe()
  948. r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr)
  949. }
  950. // If snapshot finish, wait for the msgAppResp from the remote node before sending
  951. // out the next msgApp.
  952. // If snapshot failure, wait for a heartbeat interval before next try
  953. pr.pause()
  954. case pb.MsgUnreachable:
  955. // During optimistic replication, if the remote becomes unreachable,
  956. // there is huge probability that a MsgApp is lost.
  957. if pr.State == ProgressStateReplicate {
  958. pr.becomeProbe()
  959. }
  960. r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr)
  961. case pb.MsgTransferLeader:
  962. if pr.IsLearner {
  963. r.logger.Debugf("%x is learner. Ignored transferring leadership", r.id)
  964. return nil
  965. }
  966. leadTransferee := m.From
  967. lastLeadTransferee := r.leadTransferee
  968. if lastLeadTransferee != None {
  969. if lastLeadTransferee == leadTransferee {
  970. r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x",
  971. r.id, r.Term, leadTransferee, leadTransferee)
  972. return nil
  973. }
  974. r.abortLeaderTransfer()
  975. r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee)
  976. }
  977. if leadTransferee == r.id {
  978. r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id)
  979. return nil
  980. }
  981. // Transfer leadership to third party.
  982. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee)
  983. // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed.
  984. r.electionElapsed = 0
  985. r.leadTransferee = leadTransferee
  986. if pr.Match == r.raftLog.lastIndex() {
  987. r.sendTimeoutNow(leadTransferee)
  988. r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee)
  989. } else {
  990. r.sendAppend(leadTransferee)
  991. }
  992. }
  993. return nil
  994. }
  995. // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
  996. // whether they respond to MsgVoteResp or MsgPreVoteResp.
  997. func stepCandidate(r *raft, m pb.Message) error {
  998. // Only handle vote responses corresponding to our candidacy (while in
  999. // StateCandidate, we may get stale MsgPreVoteResp messages in this term from
  1000. // our pre-candidate state).
  1001. var myVoteRespType pb.MessageType
  1002. if r.state == StatePreCandidate {
  1003. myVoteRespType = pb.MsgPreVoteResp
  1004. } else {
  1005. myVoteRespType = pb.MsgVoteResp
  1006. }
  1007. switch m.Type {
  1008. case pb.MsgProp:
  1009. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1010. return ErrProposalDropped
  1011. case pb.MsgApp:
  1012. r.becomeFollower(r.Term, m.From)
  1013. r.handleAppendEntries(m)
  1014. case pb.MsgHeartbeat:
  1015. r.becomeFollower(r.Term, m.From)
  1016. r.handleHeartbeat(m)
  1017. case pb.MsgSnap:
  1018. r.becomeFollower(m.Term, m.From)
  1019. r.handleSnapshot(m)
  1020. case myVoteRespType:
  1021. gr := r.poll(m.From, m.Type, !m.Reject)
  1022. 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)
  1023. switch r.quorum() {
  1024. case gr:
  1025. if r.state == StatePreCandidate {
  1026. r.campaign(campaignElection)
  1027. } else {
  1028. r.becomeLeader()
  1029. r.bcastAppend()
  1030. }
  1031. case len(r.votes) - gr:
  1032. r.becomeFollower(r.Term, None)
  1033. }
  1034. case pb.MsgTimeoutNow:
  1035. r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
  1036. }
  1037. return nil
  1038. }
  1039. func stepFollower(r *raft, m pb.Message) error {
  1040. switch m.Type {
  1041. case pb.MsgProp:
  1042. if r.lead == None {
  1043. r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
  1044. return ErrProposalDropped
  1045. } else if r.disableProposalForwarding {
  1046. r.logger.Infof("%x not forwarding to leader %x at term %d; dropping proposal", r.id, r.lead, r.Term)
  1047. return ErrProposalDropped
  1048. }
  1049. m.To = r.lead
  1050. r.send(m)
  1051. case pb.MsgApp:
  1052. r.electionElapsed = 0
  1053. r.lead = m.From
  1054. r.handleAppendEntries(m)
  1055. case pb.MsgHeartbeat:
  1056. r.electionElapsed = 0
  1057. r.lead = m.From
  1058. r.handleHeartbeat(m)
  1059. case pb.MsgSnap:
  1060. r.electionElapsed = 0
  1061. r.lead = m.From
  1062. r.handleSnapshot(m)
  1063. case pb.MsgTransferLeader:
  1064. if r.lead == None {
  1065. r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term)
  1066. return nil
  1067. }
  1068. m.To = r.lead
  1069. r.send(m)
  1070. case pb.MsgTimeoutNow:
  1071. if r.promotable() {
  1072. r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From)
  1073. // Leadership transfers never use pre-vote even if r.preVote is true; we
  1074. // know we are not recovering from a partition so there is no need for the
  1075. // extra round trip.
  1076. r.campaign(campaignTransfer)
  1077. } else {
  1078. r.logger.Infof("%x received MsgTimeoutNow from %x but is not promotable", r.id, m.From)
  1079. }
  1080. case pb.MsgReadIndex:
  1081. if r.lead == None {
  1082. r.logger.Infof("%x no leader at term %d; dropping index reading msg", r.id, r.Term)
  1083. return nil
  1084. }
  1085. m.To = r.lead
  1086. r.send(m)
  1087. case pb.MsgReadIndexResp:
  1088. if len(m.Entries) != 1 {
  1089. r.logger.Errorf("%x invalid format of MsgReadIndexResp from %x, entries count: %d", r.id, m.From, len(m.Entries))
  1090. return nil
  1091. }
  1092. r.readStates = append(r.readStates, ReadState{Index: m.Index, RequestCtx: m.Entries[0].Data})
  1093. }
  1094. return nil
  1095. }
  1096. func (r *raft) handleAppendEntries(m pb.Message) {
  1097. if m.Index < r.raftLog.committed {
  1098. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1099. return
  1100. }
  1101. if mlastIndex, ok := r.raftLog.maybeAppend(m.Index, m.LogTerm, m.Commit, m.Entries...); ok {
  1102. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: mlastIndex})
  1103. } else {
  1104. r.logger.Debugf("%x [logterm: %d, index: %d] rejected msgApp [logterm: %d, index: %d] from %x",
  1105. r.id, r.raftLog.zeroTermOnErrCompacted(r.raftLog.term(m.Index)), m.Index, m.LogTerm, m.Index, m.From)
  1106. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: m.Index, Reject: true, RejectHint: r.raftLog.lastIndex()})
  1107. }
  1108. }
  1109. func (r *raft) handleHeartbeat(m pb.Message) {
  1110. r.raftLog.commitTo(m.Commit)
  1111. r.send(pb.Message{To: m.From, Type: pb.MsgHeartbeatResp, Context: m.Context})
  1112. }
  1113. func (r *raft) handleSnapshot(m pb.Message) {
  1114. sindex, sterm := m.Snapshot.Metadata.Index, m.Snapshot.Metadata.Term
  1115. if r.restore(m.Snapshot) {
  1116. r.logger.Infof("%x [commit: %d] restored snapshot [index: %d, term: %d]",
  1117. r.id, r.raftLog.committed, sindex, sterm)
  1118. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.lastIndex()})
  1119. } else {
  1120. r.logger.Infof("%x [commit: %d] ignored snapshot [index: %d, term: %d]",
  1121. r.id, r.raftLog.committed, sindex, sterm)
  1122. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp, Index: r.raftLog.committed})
  1123. }
  1124. }
  1125. // restore recovers the state machine from a snapshot. It restores the log and the
  1126. // configuration of state machine.
  1127. func (r *raft) restore(s pb.Snapshot) bool {
  1128. if s.Metadata.Index <= r.raftLog.committed {
  1129. return false
  1130. }
  1131. if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
  1132. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
  1133. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1134. r.raftLog.commitTo(s.Metadata.Index)
  1135. return false
  1136. }
  1137. // The normal peer can't become learner.
  1138. if !r.isLearner {
  1139. for _, id := range s.Metadata.ConfState.Learners {
  1140. if id == r.id {
  1141. r.logger.Errorf("%x can't become learner when restores snapshot [index: %d, term: %d]", r.id, s.Metadata.Index, s.Metadata.Term)
  1142. return false
  1143. }
  1144. }
  1145. }
  1146. r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
  1147. r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
  1148. r.raftLog.restore(s)
  1149. r.prs = make(map[uint64]*Progress)
  1150. r.learnerPrs = make(map[uint64]*Progress)
  1151. r.restoreNode(s.Metadata.ConfState.Nodes, false)
  1152. r.restoreNode(s.Metadata.ConfState.Learners, true)
  1153. return true
  1154. }
  1155. func (r *raft) restoreNode(nodes []uint64, isLearner bool) {
  1156. for _, n := range nodes {
  1157. match, next := uint64(0), r.raftLog.lastIndex()+1
  1158. if n == r.id {
  1159. match = next - 1
  1160. r.isLearner = isLearner
  1161. }
  1162. r.setProgress(n, match, next, isLearner)
  1163. r.logger.Infof("%x restored progress of %x [%s]", r.id, n, r.getProgress(n))
  1164. }
  1165. }
  1166. // promotable indicates whether state machine can be promoted to leader,
  1167. // which is true when its own id is in progress list.
  1168. func (r *raft) promotable() bool {
  1169. _, ok := r.prs[r.id]
  1170. return ok
  1171. }
  1172. func (r *raft) addNode(id uint64) {
  1173. r.addNodeOrLearnerNode(id, false)
  1174. }
  1175. func (r *raft) addLearner(id uint64) {
  1176. r.addNodeOrLearnerNode(id, true)
  1177. }
  1178. func (r *raft) addNodeOrLearnerNode(id uint64, isLearner bool) {
  1179. pr := r.getProgress(id)
  1180. if pr == nil {
  1181. r.setProgress(id, 0, r.raftLog.lastIndex()+1, isLearner)
  1182. } else {
  1183. if isLearner && !pr.IsLearner {
  1184. // can only change Learner to Voter
  1185. r.logger.Infof("%x ignored addLearner: do not support changing %x from raft peer to learner.", r.id, id)
  1186. return
  1187. }
  1188. if isLearner == pr.IsLearner {
  1189. // Ignore any redundant addNode calls (which can happen because the
  1190. // initial bootstrapping entries are applied twice).
  1191. return
  1192. }
  1193. // change Learner to Voter, use origin Learner progress
  1194. delete(r.learnerPrs, id)
  1195. pr.IsLearner = false
  1196. r.prs[id] = pr
  1197. }
  1198. if r.id == id {
  1199. r.isLearner = isLearner
  1200. }
  1201. // When a node is first added, we should mark it as recently active.
  1202. // Otherwise, CheckQuorum may cause us to step down if it is invoked
  1203. // before the added node has a chance to communicate with us.
  1204. pr = r.getProgress(id)
  1205. pr.RecentActive = true
  1206. }
  1207. func (r *raft) removeNode(id uint64) {
  1208. r.delProgress(id)
  1209. // do not try to commit or abort transferring if there is no nodes in the cluster.
  1210. if len(r.prs) == 0 && len(r.learnerPrs) == 0 {
  1211. return
  1212. }
  1213. // The quorum size is now smaller, so see if any pending entries can
  1214. // be committed.
  1215. if r.maybeCommit() {
  1216. r.bcastAppend()
  1217. }
  1218. // If the removed node is the leadTransferee, then abort the leadership transferring.
  1219. if r.state == StateLeader && r.leadTransferee == id {
  1220. r.abortLeaderTransfer()
  1221. }
  1222. }
  1223. func (r *raft) setProgress(id, match, next uint64, isLearner bool) {
  1224. if !isLearner {
  1225. delete(r.learnerPrs, id)
  1226. r.prs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight)}
  1227. return
  1228. }
  1229. if _, ok := r.prs[id]; ok {
  1230. panic(fmt.Sprintf("%x unexpected changing from voter to learner for %x", r.id, id))
  1231. }
  1232. r.learnerPrs[id] = &Progress{Next: next, Match: match, ins: newInflights(r.maxInflight), IsLearner: true}
  1233. }
  1234. func (r *raft) delProgress(id uint64) {
  1235. delete(r.prs, id)
  1236. delete(r.learnerPrs, id)
  1237. }
  1238. func (r *raft) loadState(state pb.HardState) {
  1239. if state.Commit < r.raftLog.committed || state.Commit > r.raftLog.lastIndex() {
  1240. r.logger.Panicf("%x state.commit %d is out of range [%d, %d]", r.id, state.Commit, r.raftLog.committed, r.raftLog.lastIndex())
  1241. }
  1242. r.raftLog.committed = state.Commit
  1243. r.Term = state.Term
  1244. r.Vote = state.Vote
  1245. }
  1246. // pastElectionTimeout returns true iff r.electionElapsed is greater
  1247. // than or equal to the randomized election timeout in
  1248. // [electiontimeout, 2 * electiontimeout - 1].
  1249. func (r *raft) pastElectionTimeout() bool {
  1250. return r.electionElapsed >= r.randomizedElectionTimeout
  1251. }
  1252. func (r *raft) resetRandomizedElectionTimeout() {
  1253. r.randomizedElectionTimeout = r.electionTimeout + globalRand.Intn(r.electionTimeout)
  1254. }
  1255. // checkQuorumActive returns true if the quorum is active from
  1256. // the view of the local raft state machine. Otherwise, it returns
  1257. // false.
  1258. // checkQuorumActive also resets all RecentActive to false.
  1259. func (r *raft) checkQuorumActive() bool {
  1260. var act int
  1261. r.forEachProgress(func(id uint64, pr *Progress) {
  1262. if id == r.id { // self is always active
  1263. act++
  1264. return
  1265. }
  1266. if pr.RecentActive && !pr.IsLearner {
  1267. act++
  1268. }
  1269. pr.RecentActive = false
  1270. })
  1271. return act >= r.quorum()
  1272. }
  1273. func (r *raft) sendTimeoutNow(to uint64) {
  1274. r.send(pb.Message{To: to, Type: pb.MsgTimeoutNow})
  1275. }
  1276. func (r *raft) abortLeaderTransfer() {
  1277. r.leadTransferee = None
  1278. }
  1279. func numOfPendingConf(ents []pb.Entry) int {
  1280. n := 0
  1281. for i := range ents {
  1282. if ents[i].Type == pb.EntryConfChange {
  1283. n++
  1284. }
  1285. }
  1286. return n
  1287. }