node.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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.State{}
  10. ErrStopped = errors.New("raft: stopped")
  11. )
  12. // Ready encapsulates the entries and messages that are ready to be saved to
  13. // stable storage, committed or sent to other peers.
  14. type Ready struct {
  15. // The current state of a Node
  16. pb.State
  17. // Entries specifies entries to be saved to stable storage BEFORE
  18. // Messages are sent.
  19. Entries []pb.Entry
  20. // CommittedEntries specifies entries to be committed to a
  21. // store/state-machine. These have previously been committed to stable
  22. // store.
  23. CommittedEntries []pb.Entry
  24. // Messages specifies outbound messages to be sent AFTER Entries are
  25. // committed to stable storage.
  26. Messages []pb.Message
  27. }
  28. func isStateEqual(a, b pb.State) bool {
  29. return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
  30. }
  31. func IsEmptyState(st pb.State) bool {
  32. return isStateEqual(st, emptyState)
  33. }
  34. func (rd Ready) containsUpdates() bool {
  35. return !IsEmptyState(rd.State) || len(rd.Entries) > 0 || len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0
  36. }
  37. type Node struct {
  38. propc chan pb.Message
  39. recvc chan pb.Message
  40. readyc chan Ready
  41. tickc chan struct{}
  42. done chan struct{}
  43. }
  44. // Start returns a new Node given a unique raft id, a list of raft peers, and
  45. // the election and heartbeat timeouts in units of ticks.
  46. func Start(id int64, peers []int64, election, heartbeat int) Node {
  47. n := newNode()
  48. r := newRaft(id, peers, election, heartbeat)
  49. go n.run(r)
  50. return n
  51. }
  52. // Restart is identical to Start but takes an initial State and a slice of
  53. // entries. Generally this is used when restarting from a stable storage
  54. // log.
  55. func Restart(id int64, peers []int64, election, heartbeat int, st pb.State, ents []pb.Entry) Node {
  56. n := newNode()
  57. r := newRaft(id, peers, election, heartbeat)
  58. r.loadState(st)
  59. r.loadEnts(ents)
  60. go n.run(r)
  61. return n
  62. }
  63. func newNode() Node {
  64. return Node{
  65. propc: make(chan pb.Message),
  66. recvc: make(chan pb.Message),
  67. readyc: make(chan Ready),
  68. tickc: make(chan struct{}),
  69. done: make(chan struct{}),
  70. }
  71. }
  72. func (n *Node) Stop() {
  73. close(n.done)
  74. }
  75. func (n *Node) run(r *raft) {
  76. var propc chan pb.Message
  77. var readyc chan Ready
  78. var lead int64
  79. prevSt := r.State
  80. for {
  81. if lead != r.lead {
  82. log.Printf("raft: leader changed from %#x to %#x", lead, r.lead)
  83. lead = r.lead
  84. if r.hasLeader() {
  85. propc = n.propc
  86. } else {
  87. propc = nil
  88. }
  89. }
  90. rd := newReady(r, prevSt)
  91. if rd.containsUpdates() {
  92. readyc = n.readyc
  93. } else {
  94. readyc = nil
  95. }
  96. select {
  97. case m := <-propc:
  98. m.From = r.id
  99. r.Step(m)
  100. case m := <-n.recvc:
  101. r.Step(m) // raft never returns an error
  102. case <-n.tickc:
  103. r.tick()
  104. case readyc <- rd:
  105. r.raftLog.resetNextEnts()
  106. r.raftLog.resetUnstable()
  107. if !IsEmptyState(rd.State) {
  108. prevSt = rd.State
  109. }
  110. r.msgs = nil
  111. case <-n.done:
  112. return
  113. }
  114. }
  115. }
  116. // Tick increments the internal logical clock for this Node. Election timeouts
  117. // and heartbeat timeouts are in units of ticks.
  118. func (n *Node) Tick() {
  119. select {
  120. case n.tickc <- struct{}{}:
  121. case <-n.done:
  122. }
  123. }
  124. func (n *Node) Campaign(ctx context.Context) error {
  125. return n.Step(ctx, pb.Message{Type: msgHup})
  126. }
  127. // Propose proposes data be appended to the log.
  128. func (n *Node) Propose(ctx context.Context, data []byte) error {
  129. return n.Step(ctx, pb.Message{Type: msgProp, Entries: []pb.Entry{{Data: data}}})
  130. }
  131. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  132. // if any.
  133. func (n *Node) Step(ctx context.Context, m pb.Message) error {
  134. ch := n.recvc
  135. if m.Type == msgProp {
  136. ch = n.propc
  137. }
  138. select {
  139. case ch <- m:
  140. return nil
  141. case <-ctx.Done():
  142. return ctx.Err()
  143. case <-n.done:
  144. return ErrStopped
  145. }
  146. }
  147. // ReadState returns the current point-in-time state.
  148. func (n *Node) Ready() <-chan Ready {
  149. return n.readyc
  150. }
  151. func newReady(r *raft, prev pb.State) Ready {
  152. rd := Ready{
  153. Entries: r.raftLog.unstableEnts(),
  154. CommittedEntries: r.raftLog.nextEnts(),
  155. Messages: r.msgs,
  156. }
  157. if !isStateEqual(r.State, prev) {
  158. rd.State = r.State
  159. }
  160. return rd
  161. }