node.go 4.2 KB

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