node.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 struct {
  60. propc chan pb.Message
  61. recvc chan pb.Message
  62. compactc chan []byte
  63. readyc chan Ready
  64. tickc chan struct{}
  65. done chan struct{}
  66. }
  67. // Start returns a new Node given a unique raft id, a list of raft peers, and
  68. // the election and heartbeat timeouts in units of ticks.
  69. func Start(id int64, peers []int64, election, heartbeat int) Node {
  70. n := newNode()
  71. r := newRaft(id, peers, election, heartbeat)
  72. go n.run(r)
  73. return n
  74. }
  75. // Restart is identical to Start but takes an initial State and a slice of
  76. // entries. Generally this is used when restarting from a stable storage
  77. // log.
  78. func Restart(id int64, peers []int64, election, heartbeat int, snapshot *pb.Snapshot, st pb.HardState, ents []pb.Entry) Node {
  79. n := newNode()
  80. r := newRaft(id, peers, election, heartbeat)
  81. if snapshot != nil {
  82. r.restore(*snapshot)
  83. }
  84. r.loadState(st)
  85. r.loadEnts(ents)
  86. go n.run(r)
  87. return n
  88. }
  89. func newNode() Node {
  90. return Node{
  91. propc: make(chan pb.Message),
  92. recvc: make(chan pb.Message),
  93. compactc: make(chan []byte),
  94. readyc: make(chan Ready),
  95. tickc: make(chan struct{}),
  96. done: make(chan struct{}),
  97. }
  98. }
  99. func (n *Node) Stop() {
  100. close(n.done)
  101. }
  102. func (n *Node) run(r *raft) {
  103. var propc chan pb.Message
  104. var readyc chan Ready
  105. lead := None
  106. prevSoftSt := r.softState()
  107. prevHardSt := r.HardState
  108. prevSnapi := r.raftLog.snapshot.Index
  109. for {
  110. rd := newReady(r, prevSoftSt, prevHardSt, prevSnapi)
  111. if rd.containsUpdates() {
  112. readyc = n.readyc
  113. } else {
  114. readyc = nil
  115. }
  116. if rd.SoftState != nil && lead != rd.SoftState.Lead {
  117. log.Printf("raft: leader changed from %#x to %#x", lead, rd.SoftState.Lead)
  118. lead = rd.SoftState.Lead
  119. if r.hasLeader() {
  120. propc = n.propc
  121. } else {
  122. propc = nil
  123. }
  124. }
  125. select {
  126. case m := <-propc:
  127. m.From = r.id
  128. r.Step(m)
  129. case m := <-n.recvc:
  130. r.Step(m) // raft never returns an error
  131. case d := <-n.compactc:
  132. r.compact(d)
  133. case <-n.tickc:
  134. r.tick()
  135. case readyc <- rd:
  136. if rd.SoftState != nil {
  137. prevSoftSt = rd.SoftState
  138. }
  139. if !IsEmptyHardState(rd.HardState) {
  140. prevHardSt = rd.HardState
  141. }
  142. if !IsEmptySnap(rd.Snapshot) {
  143. prevSnapi = rd.Snapshot.Index
  144. }
  145. r.raftLog.resetNextEnts()
  146. r.raftLog.resetUnstable()
  147. r.msgs = nil
  148. case <-n.done:
  149. return
  150. }
  151. }
  152. }
  153. // Tick increments the internal logical clock for this Node. Election timeouts
  154. // and heartbeat timeouts are in units of ticks.
  155. func (n *Node) Tick() {
  156. select {
  157. case n.tickc <- struct{}{}:
  158. case <-n.done:
  159. }
  160. }
  161. func (n *Node) Campaign(ctx context.Context) error {
  162. return n.Step(ctx, pb.Message{Type: msgHup})
  163. }
  164. // Propose proposes data be appended to the log.
  165. func (n *Node) Propose(ctx context.Context, data []byte) error {
  166. return n.Step(ctx, pb.Message{Type: msgProp, Entries: []pb.Entry{{Data: data}}})
  167. }
  168. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  169. // if any.
  170. func (n *Node) Step(ctx context.Context, m pb.Message) error {
  171. ch := n.recvc
  172. if m.Type == msgProp {
  173. ch = n.propc
  174. }
  175. select {
  176. case ch <- m:
  177. return nil
  178. case <-ctx.Done():
  179. return ctx.Err()
  180. case <-n.done:
  181. return ErrStopped
  182. }
  183. }
  184. // ReadState returns the current point-in-time state.
  185. func (n *Node) Ready() <-chan Ready {
  186. return n.readyc
  187. }
  188. func (n *Node) Compact(d []byte) {
  189. select {
  190. case n.compactc <- d:
  191. case <-n.done:
  192. }
  193. }
  194. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState, prevSnapi int64) Ready {
  195. rd := Ready{
  196. Entries: r.raftLog.unstableEnts(),
  197. CommittedEntries: r.raftLog.nextEnts(),
  198. Messages: r.msgs,
  199. }
  200. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  201. rd.SoftState = softSt
  202. }
  203. if !isHardStateEqual(r.HardState, prevHardSt) {
  204. rd.HardState = r.HardState
  205. }
  206. if prevSnapi != r.raftLog.snapshot.Index {
  207. rd.Snapshot = r.raftLog.snapshot
  208. }
  209. return rd
  210. }