node.go 14 KB

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