node.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. // CommittedEntries specifies entries to be committed to a
  37. // store/state-machine. These have previously been committed to stable
  38. // store.
  39. CommittedEntries []pb.Entry
  40. // Messages specifies outbound messages to be sent AFTER Entries are
  41. // committed to stable storage.
  42. Messages []pb.Message
  43. }
  44. func isHardStateEqual(a, b pb.HardState) bool {
  45. return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
  46. }
  47. func IsEmptyHardState(st pb.HardState) bool {
  48. return isHardStateEqual(st, emptyState)
  49. }
  50. func (rd Ready) containsUpdates() bool {
  51. return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) || len(rd.Entries) > 0 || len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0
  52. }
  53. type Node struct {
  54. propc chan pb.Message
  55. recvc chan pb.Message
  56. readyc chan Ready
  57. tickc chan struct{}
  58. done chan struct{}
  59. }
  60. // Start returns a new Node given a unique raft id, a list of raft peers, and
  61. // the election and heartbeat timeouts in units of ticks.
  62. func Start(id int64, peers []int64, election, heartbeat int) Node {
  63. n := newNode()
  64. r := newRaft(id, peers, election, heartbeat)
  65. go n.run(r)
  66. return n
  67. }
  68. // Restart is identical to Start but takes an initial State and a slice of
  69. // entries. Generally this is used when restarting from a stable storage
  70. // log.
  71. func Restart(id int64, peers []int64, election, heartbeat int, st pb.HardState, ents []pb.Entry) Node {
  72. n := newNode()
  73. r := newRaft(id, peers, election, heartbeat)
  74. r.loadState(st)
  75. r.loadEnts(ents)
  76. go n.run(r)
  77. return n
  78. }
  79. func newNode() Node {
  80. return Node{
  81. propc: make(chan pb.Message),
  82. recvc: make(chan pb.Message),
  83. readyc: make(chan Ready),
  84. tickc: make(chan struct{}),
  85. done: make(chan struct{}),
  86. }
  87. }
  88. func (n *Node) Stop() {
  89. close(n.done)
  90. }
  91. func (n *Node) run(r *raft) {
  92. var propc chan pb.Message
  93. var readyc chan Ready
  94. lead := None
  95. prevSoftSt := r.softState()
  96. prevHardSt := r.HardState
  97. for {
  98. rd := newReady(r, prevSoftSt, prevHardSt)
  99. if rd.containsUpdates() {
  100. readyc = n.readyc
  101. } else {
  102. readyc = nil
  103. }
  104. if rd.SoftState != nil && lead != rd.SoftState.Lead {
  105. log.Printf("raft: leader changed from %#x to %#x", lead, rd.SoftState.Lead)
  106. lead = rd.SoftState.Lead
  107. if r.hasLeader() {
  108. propc = n.propc
  109. } else {
  110. propc = nil
  111. }
  112. }
  113. select {
  114. case m := <-propc:
  115. m.From = r.id
  116. r.Step(m)
  117. case m := <-n.recvc:
  118. r.Step(m) // raft never returns an error
  119. case <-n.tickc:
  120. r.tick()
  121. case readyc <- rd:
  122. if rd.SoftState != nil {
  123. prevSoftSt = rd.SoftState
  124. }
  125. if !IsEmptyHardState(rd.HardState) {
  126. prevHardSt = rd.HardState
  127. }
  128. r.raftLog.resetNextEnts()
  129. r.raftLog.resetUnstable()
  130. r.msgs = nil
  131. case <-n.done:
  132. return
  133. }
  134. }
  135. }
  136. // Tick increments the internal logical clock for this Node. Election timeouts
  137. // and heartbeat timeouts are in units of ticks.
  138. func (n *Node) Tick() {
  139. select {
  140. case n.tickc <- struct{}{}:
  141. case <-n.done:
  142. }
  143. }
  144. func (n *Node) Campaign(ctx context.Context) error {
  145. return n.Step(ctx, pb.Message{Type: msgHup})
  146. }
  147. // Propose proposes data be appended to the log.
  148. func (n *Node) Propose(ctx context.Context, data []byte) error {
  149. return n.Step(ctx, pb.Message{Type: msgProp, Entries: []pb.Entry{{Data: data}}})
  150. }
  151. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  152. // if any.
  153. func (n *Node) Step(ctx context.Context, m pb.Message) error {
  154. ch := n.recvc
  155. if m.Type == msgProp {
  156. ch = n.propc
  157. }
  158. select {
  159. case ch <- m:
  160. return nil
  161. case <-ctx.Done():
  162. return ctx.Err()
  163. case <-n.done:
  164. return ErrStopped
  165. }
  166. }
  167. // ReadState returns the current point-in-time state.
  168. func (n *Node) Ready() <-chan Ready {
  169. return n.readyc
  170. }
  171. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState) Ready {
  172. rd := Ready{
  173. Entries: r.raftLog.unstableEnts(),
  174. CommittedEntries: r.raftLog.nextEnts(),
  175. Messages: r.msgs,
  176. }
  177. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  178. rd.SoftState = softSt
  179. }
  180. if !isHardStateEqual(r.HardState, prevHardSt) {
  181. rd.HardState = r.HardState
  182. }
  183. return rd
  184. }