node.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package raft
  2. import (
  3. "errors"
  4. "log"
  5. pb "github.com/coreos/etcd/raft/raftpb"
  6. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  7. )
  8. var (
  9. emptyState = pb.HardState{}
  10. ErrStopped = errors.New("raft: stopped")
  11. )
  12. // SoftState provides state that is useful for logging and debugging.
  13. // The state is volatile and does not need to be persisted to the WAL.
  14. type SoftState struct {
  15. Lead int64
  16. RaftState StateType
  17. }
  18. func (a *SoftState) equal(b *SoftState) bool {
  19. return a.Lead == b.Lead && a.RaftState == b.RaftState
  20. }
  21. // Ready encapsulates the entries and messages that are ready to read,
  22. // be saved to stable storage, committed or sent to other peers.
  23. // All fields in Ready are read-only.
  24. type Ready struct {
  25. // The current volatile state of a Node.
  26. // SoftState will be nil if there is no update.
  27. // It is not required to consume or store SoftState.
  28. *SoftState
  29. // The current state of a Node to be saved to stable storage BEFORE
  30. // Messages are sent.
  31. // HardState will be equal to empty state if there is no update.
  32. pb.HardState
  33. // Entries specifies entries to be saved to stable storage BEFORE
  34. // Messages are sent.
  35. Entries []pb.Entry
  36. // Snapshot specifies the snapshot to be saved to stable storage.
  37. Snapshot pb.Snapshot
  38. // CommittedEntries specifies entries to be committed to a
  39. // store/state-machine. These have previously been committed to stable
  40. // store.
  41. CommittedEntries []pb.Entry
  42. // Messages specifies outbound messages to be sent AFTER Entries are
  43. // committed to stable storage.
  44. Messages []pb.Message
  45. }
  46. func isHardStateEqual(a, b pb.HardState) bool {
  47. return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
  48. }
  49. func IsEmptyHardState(st pb.HardState) bool {
  50. return isHardStateEqual(st, emptyState)
  51. }
  52. func IsEmptySnap(sp pb.Snapshot) bool {
  53. return sp.Index == 0
  54. }
  55. func (rd Ready) containsUpdates() bool {
  56. return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) || !IsEmptySnap(rd.Snapshot) ||
  57. len(rd.Entries) > 0 || len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0
  58. }
  59. type Node interface {
  60. // Tick increments the internal logical clock for the Node by a single tick. Election
  61. // timeouts and heartbeat timeouts are in units of ticks.
  62. Tick()
  63. // Campaign causes the Node to transition to candidate state and start campaigning to become leader
  64. Campaign(ctx context.Context) error
  65. // Propose proposes that data be appended to the log.
  66. Propose(ctx context.Context, data []byte) error
  67. // Step advances the state machine using the given message. ctx.Err() will be returned, if any.
  68. Step(ctx context.Context, msg pb.Message) error
  69. // Ready returns a channel that returns the current point-in-time state
  70. Ready() <-chan Ready
  71. // Stop performs any necessary termination of the Node
  72. Stop()
  73. // Compact
  74. Compact(d []byte)
  75. }
  76. // StartNode returns a new Node given a unique raft id, a list of raft peers, and
  77. // the election and heartbeat timeouts in units of ticks.
  78. func StartNode(id int64, peers []int64, election, heartbeat int) Node {
  79. n := newNode()
  80. r := newRaft(id, peers, election, heartbeat)
  81. go n.run(r)
  82. return &n
  83. }
  84. // RestartNode is identical to StartNode but takes an initial State and a slice
  85. // of entries. Generally this is used when restarting from a stable storage
  86. // log.
  87. func RestartNode(id int64, peers []int64, election, heartbeat int, snapshot *pb.Snapshot, st pb.HardState, ents []pb.Entry) Node {
  88. n := newNode()
  89. r := newRaft(id, peers, election, heartbeat)
  90. if snapshot != nil {
  91. r.restore(*snapshot)
  92. }
  93. r.loadState(st)
  94. r.loadEnts(ents)
  95. go n.run(r)
  96. return &n
  97. }
  98. // node is the canonical implementation of the Node interface
  99. type node struct {
  100. propc chan pb.Message
  101. recvc chan pb.Message
  102. compactc chan []byte
  103. readyc chan Ready
  104. tickc chan struct{}
  105. done chan struct{}
  106. }
  107. func newNode() node {
  108. return node{
  109. propc: make(chan pb.Message),
  110. recvc: make(chan pb.Message),
  111. compactc: make(chan []byte),
  112. readyc: make(chan Ready),
  113. tickc: make(chan struct{}),
  114. done: make(chan struct{}),
  115. }
  116. }
  117. func (n *node) Stop() {
  118. close(n.done)
  119. }
  120. func (n *node) run(r *raft) {
  121. var propc chan pb.Message
  122. var readyc chan Ready
  123. lead := None
  124. prevSoftSt := r.softState()
  125. prevHardSt := r.HardState
  126. prevSnapi := r.raftLog.snapshot.Index
  127. for {
  128. rd := newReady(r, prevSoftSt, prevHardSt, prevSnapi)
  129. if rd.containsUpdates() {
  130. readyc = n.readyc
  131. } else {
  132. readyc = nil
  133. }
  134. if rd.SoftState != nil && lead != rd.SoftState.Lead {
  135. log.Printf("raft: leader changed from %#x to %#x", lead, rd.SoftState.Lead)
  136. lead = rd.SoftState.Lead
  137. if r.hasLeader() {
  138. propc = n.propc
  139. } else {
  140. propc = nil
  141. }
  142. }
  143. select {
  144. case m := <-propc:
  145. m.From = r.id
  146. r.Step(m)
  147. case m := <-n.recvc:
  148. r.Step(m) // raft never returns an error
  149. case d := <-n.compactc:
  150. r.compact(d)
  151. case <-n.tickc:
  152. r.tick()
  153. case readyc <- rd:
  154. if rd.SoftState != nil {
  155. prevSoftSt = rd.SoftState
  156. }
  157. if !IsEmptyHardState(rd.HardState) {
  158. prevHardSt = rd.HardState
  159. }
  160. if !IsEmptySnap(rd.Snapshot) {
  161. prevSnapi = rd.Snapshot.Index
  162. }
  163. r.raftLog.resetNextEnts()
  164. r.raftLog.resetUnstable()
  165. r.msgs = nil
  166. case <-n.done:
  167. return
  168. }
  169. }
  170. }
  171. // Tick increments the internal logical clock for this Node. Election timeouts
  172. // and heartbeat timeouts are in units of ticks.
  173. func (n *node) Tick() {
  174. select {
  175. case n.tickc <- struct{}{}:
  176. case <-n.done:
  177. }
  178. }
  179. func (n *node) Campaign(ctx context.Context) error {
  180. return n.Step(ctx, pb.Message{Type: msgHup})
  181. }
  182. func (n *node) Propose(ctx context.Context, data []byte) error {
  183. return n.Step(ctx, pb.Message{Type: msgProp, Entries: []pb.Entry{{Data: data}}})
  184. }
  185. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  186. // if any.
  187. func (n *node) Step(ctx context.Context, m pb.Message) error {
  188. ch := n.recvc
  189. if m.Type == msgProp {
  190. ch = n.propc
  191. }
  192. select {
  193. case ch <- m:
  194. return nil
  195. case <-ctx.Done():
  196. return ctx.Err()
  197. case <-n.done:
  198. return ErrStopped
  199. }
  200. }
  201. func (n *node) Ready() <-chan Ready {
  202. return n.readyc
  203. }
  204. func (n *node) Compact(d []byte) {
  205. select {
  206. case n.compactc <- d:
  207. case <-n.done:
  208. }
  209. }
  210. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState, prevSnapi int64) Ready {
  211. rd := Ready{
  212. Entries: r.raftLog.unstableEnts(),
  213. CommittedEntries: r.raftLog.nextEnts(),
  214. Messages: r.msgs,
  215. }
  216. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  217. rd.SoftState = softSt
  218. }
  219. if !isHardStateEqual(r.HardState, prevHardSt) {
  220. rd.HardState = r.HardState
  221. }
  222. if prevSnapi != r.raftLog.snapshot.Index {
  223. rd.Snapshot = r.raftLog.snapshot
  224. }
  225. return rd
  226. }