node.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. "errors"
  17. pb "github.com/coreos/etcd/raft/raftpb"
  18. "golang.org/x/net/context"
  19. )
  20. type SnapshotStatus int
  21. const (
  22. SnapshotFinish SnapshotStatus = 1
  23. SnapshotFailure SnapshotStatus = 2
  24. )
  25. var (
  26. emptyState = pb.HardState{}
  27. // ErrStopped is returned by methods on Nodes that have been stopped.
  28. ErrStopped = errors.New("raft: stopped")
  29. )
  30. // SoftState provides state that is useful for logging and debugging.
  31. // The state is volatile and does not need to be persisted to the WAL.
  32. type SoftState struct {
  33. Lead uint64 // must use atomic operations to access; keep 64-bit aligned.
  34. RaftState StateType
  35. }
  36. func (a *SoftState) equal(b *SoftState) bool {
  37. return a.Lead == b.Lead && a.RaftState == b.RaftState
  38. }
  39. // Ready encapsulates the entries and messages that are ready to read,
  40. // be saved to stable storage, committed or sent to other peers.
  41. // All fields in Ready are read-only.
  42. type Ready struct {
  43. // The current volatile state of a Node.
  44. // SoftState will be nil if there is no update.
  45. // It is not required to consume or store SoftState.
  46. *SoftState
  47. // The current state of a Node to be saved to stable storage BEFORE
  48. // Messages are sent.
  49. // HardState will be equal to empty state if there is no update.
  50. pb.HardState
  51. // ReadState can be used for node to serve linearizable read requests locally
  52. // when its applied index is greater than the index in ReadState.
  53. // Note that the readState will be returned when raft receives msgReadIndex.
  54. // The returned is only valid for the request that requested to read.
  55. ReadState
  56. // Entries specifies entries to be saved to stable storage BEFORE
  57. // Messages are sent.
  58. Entries []pb.Entry
  59. // Snapshot specifies the snapshot to be saved to stable storage.
  60. Snapshot pb.Snapshot
  61. // CommittedEntries specifies entries to be committed to a
  62. // store/state-machine. These have previously been committed to stable
  63. // store.
  64. CommittedEntries []pb.Entry
  65. // Messages specifies outbound messages to be sent AFTER Entries are
  66. // committed to stable storage.
  67. // If it contains a MsgSnap message, the application MUST report back to raft
  68. // when the snapshot has been received or has failed by calling ReportSnapshot.
  69. Messages []pb.Message
  70. }
  71. func isHardStateEqual(a, b pb.HardState) bool {
  72. return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
  73. }
  74. // IsEmptyHardState returns true if the given HardState is empty.
  75. func IsEmptyHardState(st pb.HardState) bool {
  76. return isHardStateEqual(st, emptyState)
  77. }
  78. // IsEmptySnap returns true if the given Snapshot is empty.
  79. func IsEmptySnap(sp pb.Snapshot) bool {
  80. return sp.Metadata.Index == 0
  81. }
  82. func (rd Ready) containsUpdates() bool {
  83. return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) ||
  84. !IsEmptySnap(rd.Snapshot) || len(rd.Entries) > 0 ||
  85. len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0 || rd.Index != None
  86. }
  87. // Node represents a node in a raft cluster.
  88. type Node interface {
  89. // Tick increments the internal logical clock for the Node by a single tick. Election
  90. // timeouts and heartbeat timeouts are in units of ticks.
  91. Tick()
  92. // Campaign causes the Node to transition to candidate state and start campaigning to become leader.
  93. Campaign(ctx context.Context) error
  94. // Propose proposes that data be appended to the log.
  95. Propose(ctx context.Context, data []byte) error
  96. // ProposeConfChange proposes config change.
  97. // At most one ConfChange can be in the process of going through consensus.
  98. // Application needs to call ApplyConfChange when applying EntryConfChange type entry.
  99. ProposeConfChange(ctx context.Context, cc pb.ConfChange) error
  100. // Step advances the state machine using the given message. ctx.Err() will be returned, if any.
  101. Step(ctx context.Context, msg pb.Message) error
  102. // Ready returns a channel that returns the current point-in-time state.
  103. // Users of the Node must call Advance after retrieving the state returned by Ready.
  104. //
  105. // NOTE: No committed entries from the next Ready may be applied until all committed entries
  106. // and snapshots from the previous one have finished.
  107. Ready() <-chan Ready
  108. // Advance notifies the Node that the application has saved progress up to the last Ready.
  109. // It prepares the node to return the next available Ready.
  110. //
  111. // The application should generally call Advance after it applies the entries in last Ready.
  112. //
  113. // However, as an optimization, the application may call Advance while it is applying the
  114. // commands. For example. when the last Ready contains a snapshot, the application might take
  115. // a long time to apply the snapshot data. To continue receiving Ready without blocking raft
  116. // progress, it can call Advance before finishing applying the last ready. To make this optimization
  117. // work safely, when the application receives a Ready with softState.RaftState equal to Candidate
  118. // it MUST apply all pending configuration changes if there is any.
  119. //
  120. // Here is a simple solution that waiting for ALL pending entries to get applied.
  121. // ```
  122. // ...
  123. // rd := <-n.Ready()
  124. // go apply(rd.CommittedEntries) // optimization to apply asynchronously in FIFO order.
  125. // if rd.SoftState.RaftState == StateCandidate {
  126. // waitAllApplied()
  127. // }
  128. // n.Advance()
  129. // ...
  130. //```
  131. Advance()
  132. // ApplyConfChange applies config change to the local node.
  133. // Returns an opaque ConfState protobuf which must be recorded
  134. // in snapshots. Will never return nil; it returns a pointer only
  135. // to match MemoryStorage.Compact.
  136. ApplyConfChange(cc pb.ConfChange) *pb.ConfState
  137. // ReadIndex request a read state. The read state will be set in the ready.
  138. // Read state has a read index. Once the application advances further than the read
  139. // index, any linearizable read requests issued before the read request can be
  140. // processed safely. The read state will have the same rctx attached.
  141. //
  142. // Note: the current implementation depends on the leader lease. If the clock drift is unbounded,
  143. // leader might keep the lease longer than it should (clock can move backward/pause without any bound).
  144. // ReadIndex is not safe in that case.
  145. // TODO: add clock drift bound into raft configuration.
  146. ReadIndex(ctx context.Context, rctx []byte) error
  147. // Status returns the current status of the raft state machine.
  148. Status() Status
  149. // ReportUnreachable reports the given node is not reachable for the last send.
  150. ReportUnreachable(id uint64)
  151. // ReportSnapshot reports the status of the sent snapshot.
  152. ReportSnapshot(id uint64, status SnapshotStatus)
  153. // Stop performs any necessary termination of the Node.
  154. Stop()
  155. }
  156. type Peer struct {
  157. ID uint64
  158. Context []byte
  159. }
  160. // StartNode returns a new Node given configuration and a list of raft peers.
  161. // It appends a ConfChangeAddNode entry for each given peer to the initial log.
  162. func StartNode(c *Config, peers []Peer) Node {
  163. r := newRaft(c)
  164. // become the follower at term 1 and apply initial configuration
  165. // entries of term 1
  166. r.becomeFollower(1, None)
  167. for _, peer := range peers {
  168. cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context}
  169. d, err := cc.Marshal()
  170. if err != nil {
  171. panic("unexpected marshal error")
  172. }
  173. e := pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: r.raftLog.lastIndex() + 1, Data: d}
  174. r.raftLog.append(e)
  175. }
  176. // Mark these initial entries as committed.
  177. // TODO(bdarnell): These entries are still unstable; do we need to preserve
  178. // the invariant that committed < unstable?
  179. r.raftLog.committed = r.raftLog.lastIndex()
  180. // Now apply them, mainly so that the application can call Campaign
  181. // immediately after StartNode in tests. Note that these nodes will
  182. // be added to raft twice: here and when the application's Ready
  183. // loop calls ApplyConfChange. The calls to addNode must come after
  184. // all calls to raftLog.append so progress.next is set after these
  185. // bootstrapping entries (it is an error if we try to append these
  186. // entries since they have already been committed).
  187. // We do not set raftLog.applied so the application will be able
  188. // to observe all conf changes via Ready.CommittedEntries.
  189. for _, peer := range peers {
  190. r.addNode(peer.ID)
  191. }
  192. n := newNode()
  193. n.logger = c.Logger
  194. go n.run(r)
  195. return &n
  196. }
  197. // RestartNode is similar to StartNode but does not take a list of peers.
  198. // The current membership of the cluster will be restored from the Storage.
  199. // If the caller has an existing state machine, pass in the last log index that
  200. // has been applied to it; otherwise use zero.
  201. func RestartNode(c *Config) Node {
  202. r := newRaft(c)
  203. n := newNode()
  204. n.logger = c.Logger
  205. go n.run(r)
  206. return &n
  207. }
  208. // node is the canonical implementation of the Node interface
  209. type node struct {
  210. propc chan pb.Message
  211. recvc chan pb.Message
  212. confc chan pb.ConfChange
  213. confstatec chan pb.ConfState
  214. readyc chan Ready
  215. advancec chan struct{}
  216. tickc chan struct{}
  217. done chan struct{}
  218. stop chan struct{}
  219. status chan chan Status
  220. logger Logger
  221. }
  222. func newNode() node {
  223. return node{
  224. propc: make(chan pb.Message),
  225. recvc: make(chan pb.Message),
  226. confc: make(chan pb.ConfChange),
  227. confstatec: make(chan pb.ConfState),
  228. readyc: make(chan Ready),
  229. advancec: make(chan struct{}),
  230. // make tickc a buffered chan, so raft node can buffer some ticks when the node
  231. // is busy processing raft messages. Raft node will resume process buffered
  232. // ticks when it becomes idle.
  233. tickc: make(chan struct{}, 128),
  234. done: make(chan struct{}),
  235. stop: make(chan struct{}),
  236. status: make(chan chan Status),
  237. }
  238. }
  239. func (n *node) Stop() {
  240. select {
  241. case n.stop <- struct{}{}:
  242. // Not already stopped, so trigger it
  243. case <-n.done:
  244. // Node has already been stopped - no need to do anything
  245. return
  246. }
  247. // Block until the stop has been acknowledged by run()
  248. <-n.done
  249. }
  250. func (n *node) run(r *raft) {
  251. var propc chan pb.Message
  252. var readyc chan Ready
  253. var advancec chan struct{}
  254. var prevLastUnstablei, prevLastUnstablet uint64
  255. var havePrevLastUnstablei bool
  256. var prevSnapi uint64
  257. var rd Ready
  258. lead := None
  259. prevSoftSt := r.softState()
  260. prevHardSt := emptyState
  261. for {
  262. if advancec != nil {
  263. readyc = nil
  264. } else {
  265. rd = newReady(r, prevSoftSt, prevHardSt)
  266. if rd.containsUpdates() {
  267. readyc = n.readyc
  268. } else {
  269. readyc = nil
  270. }
  271. }
  272. if lead != r.lead {
  273. if r.hasLeader() {
  274. if lead == None {
  275. r.logger.Infof("raft.node: %x elected leader %x at term %d", r.id, r.lead, r.Term)
  276. } else {
  277. r.logger.Infof("raft.node: %x changed leader from %x to %x at term %d", r.id, lead, r.lead, r.Term)
  278. }
  279. propc = n.propc
  280. } else {
  281. r.logger.Infof("raft.node: %x lost leader %x at term %d", r.id, lead, r.Term)
  282. propc = nil
  283. }
  284. lead = r.lead
  285. }
  286. select {
  287. // TODO: maybe buffer the config propose if there exists one (the way
  288. // described in raft dissertation)
  289. // Currently it is dropped in Step silently.
  290. case m := <-propc:
  291. m.From = r.id
  292. r.Step(m)
  293. case m := <-n.recvc:
  294. // filter out response message from unknown From.
  295. if _, ok := r.prs[m.From]; ok || !IsResponseMsg(m.Type) {
  296. r.Step(m) // raft never returns an error
  297. }
  298. case cc := <-n.confc:
  299. if cc.NodeID == None {
  300. r.resetPendingConf()
  301. select {
  302. case n.confstatec <- pb.ConfState{Nodes: r.nodes()}:
  303. case <-n.done:
  304. }
  305. break
  306. }
  307. switch cc.Type {
  308. case pb.ConfChangeAddNode:
  309. r.addNode(cc.NodeID)
  310. case pb.ConfChangeRemoveNode:
  311. // block incoming proposal when local node is
  312. // removed
  313. if cc.NodeID == r.id {
  314. propc = nil
  315. }
  316. r.removeNode(cc.NodeID)
  317. case pb.ConfChangeUpdateNode:
  318. r.resetPendingConf()
  319. default:
  320. panic("unexpected conf type")
  321. }
  322. select {
  323. case n.confstatec <- pb.ConfState{Nodes: r.nodes()}:
  324. case <-n.done:
  325. }
  326. case <-n.tickc:
  327. r.tick()
  328. case readyc <- rd:
  329. if rd.SoftState != nil {
  330. prevSoftSt = rd.SoftState
  331. }
  332. if len(rd.Entries) > 0 {
  333. prevLastUnstablei = rd.Entries[len(rd.Entries)-1].Index
  334. prevLastUnstablet = rd.Entries[len(rd.Entries)-1].Term
  335. havePrevLastUnstablei = true
  336. }
  337. if !IsEmptyHardState(rd.HardState) {
  338. prevHardSt = rd.HardState
  339. }
  340. if !IsEmptySnap(rd.Snapshot) {
  341. prevSnapi = rd.Snapshot.Metadata.Index
  342. }
  343. r.msgs = nil
  344. r.readState.Index = None
  345. r.readState.RequestCtx = nil
  346. advancec = n.advancec
  347. case <-advancec:
  348. if prevHardSt.Commit != 0 {
  349. r.raftLog.appliedTo(prevHardSt.Commit)
  350. }
  351. if havePrevLastUnstablei {
  352. r.raftLog.stableTo(prevLastUnstablei, prevLastUnstablet)
  353. havePrevLastUnstablei = false
  354. }
  355. r.raftLog.stableSnapTo(prevSnapi)
  356. advancec = nil
  357. case c := <-n.status:
  358. c <- getStatus(r)
  359. case <-n.stop:
  360. close(n.done)
  361. return
  362. }
  363. }
  364. }
  365. // Tick increments the internal logical clock for this Node. Election timeouts
  366. // and heartbeat timeouts are in units of ticks.
  367. func (n *node) Tick() {
  368. select {
  369. case n.tickc <- struct{}{}:
  370. case <-n.done:
  371. default:
  372. n.logger.Warningf("A tick missed to fire. Node blocks too long!")
  373. }
  374. }
  375. func (n *node) Campaign(ctx context.Context) error { return n.step(ctx, pb.Message{Type: pb.MsgHup}) }
  376. func (n *node) Propose(ctx context.Context, data []byte) error {
  377. return n.step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  378. }
  379. func (n *node) Step(ctx context.Context, m pb.Message) error {
  380. // ignore unexpected local messages receiving over network
  381. if IsLocalMsg(m.Type) {
  382. // TODO: return an error?
  383. return nil
  384. }
  385. return n.step(ctx, m)
  386. }
  387. func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
  388. data, err := cc.Marshal()
  389. if err != nil {
  390. return err
  391. }
  392. return n.Step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
  393. }
  394. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  395. // if any.
  396. func (n *node) step(ctx context.Context, m pb.Message) error {
  397. ch := n.recvc
  398. if m.Type == pb.MsgProp {
  399. ch = n.propc
  400. }
  401. select {
  402. case ch <- m:
  403. return nil
  404. case <-ctx.Done():
  405. return ctx.Err()
  406. case <-n.done:
  407. return ErrStopped
  408. }
  409. }
  410. func (n *node) Ready() <-chan Ready { return n.readyc }
  411. func (n *node) Advance() {
  412. select {
  413. case n.advancec <- struct{}{}:
  414. case <-n.done:
  415. }
  416. }
  417. func (n *node) ApplyConfChange(cc pb.ConfChange) *pb.ConfState {
  418. var cs pb.ConfState
  419. select {
  420. case n.confc <- cc:
  421. case <-n.done:
  422. }
  423. select {
  424. case cs = <-n.confstatec:
  425. case <-n.done:
  426. }
  427. return &cs
  428. }
  429. func (n *node) Status() Status {
  430. c := make(chan Status)
  431. n.status <- c
  432. return <-c
  433. }
  434. func (n *node) ReportUnreachable(id uint64) {
  435. select {
  436. case n.recvc <- pb.Message{Type: pb.MsgUnreachable, From: id}:
  437. case <-n.done:
  438. }
  439. }
  440. func (n *node) ReportSnapshot(id uint64, status SnapshotStatus) {
  441. rej := status == SnapshotFailure
  442. select {
  443. case n.recvc <- pb.Message{Type: pb.MsgSnapStatus, From: id, Reject: rej}:
  444. case <-n.done:
  445. }
  446. }
  447. func (n *node) ReadIndex(ctx context.Context, rctx []byte) error {
  448. return n.step(ctx, pb.Message{Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: rctx}}})
  449. }
  450. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState) Ready {
  451. rd := Ready{
  452. Entries: r.raftLog.unstableEntries(),
  453. CommittedEntries: r.raftLog.nextEnts(),
  454. Messages: r.msgs,
  455. }
  456. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  457. rd.SoftState = softSt
  458. }
  459. if hardSt := r.hardState(); !isHardStateEqual(hardSt, prevHardSt) {
  460. rd.HardState = hardSt
  461. }
  462. if r.raftLog.unstable.snapshot != nil {
  463. rd.Snapshot = *r.raftLog.unstable.snapshot
  464. }
  465. if r.readState.Index != None {
  466. c := make([]byte, len(r.readState.RequestCtx))
  467. copy(c, r.readState.RequestCtx)
  468. rd.Index = r.readState.Index
  469. rd.RequestCtx = c
  470. }
  471. return rd
  472. }