node.go 13 KB

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