node.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. // ProposeConfChange proposes config change.
  68. // At most one ConfChange can be in the process of going through consensus.
  69. // Application needs to call ApplyConfChange when applying EntryConfChange type entry.
  70. ProposeConfChange(ctx context.Context, cc pb.ConfChange) error
  71. // Step advances the state machine using the given message. ctx.Err() will be returned, if any.
  72. Step(ctx context.Context, msg pb.Message) error
  73. // Ready returns a channel that returns the current point-in-time state
  74. Ready() <-chan Ready
  75. // ApplyConfChange applies config change to the local node.
  76. // TODO: reject existing node when add node
  77. // TODO: reject non-existant node when remove node
  78. ApplyConfChange(cc pb.ConfChange)
  79. // Stop performs any necessary termination of the Node
  80. Stop()
  81. // Compact
  82. Compact(d []byte)
  83. }
  84. // StartNode returns a new Node given a unique raft id, a list of raft peers, and
  85. // the election and heartbeat timeouts in units of ticks.
  86. func StartNode(id int64, peers []int64, election, heartbeat int) Node {
  87. n := newNode()
  88. r := newRaft(id, peers, election, heartbeat)
  89. go n.run(r)
  90. return &n
  91. }
  92. // RestartNode is identical to StartNode but takes an initial State and a slice
  93. // of entries. Generally this is used when restarting from a stable storage
  94. // log.
  95. func RestartNode(id int64, peers []int64, election, heartbeat int, snapshot *pb.Snapshot, st pb.HardState, ents []pb.Entry) Node {
  96. n := newNode()
  97. r := newRaft(id, peers, election, heartbeat)
  98. if snapshot != nil {
  99. r.restore(*snapshot)
  100. }
  101. r.loadState(st)
  102. r.loadEnts(ents)
  103. go n.run(r)
  104. return &n
  105. }
  106. // node is the canonical implementation of the Node interface
  107. type node struct {
  108. propc chan pb.Message
  109. recvc chan pb.Message
  110. compactc chan []byte
  111. confc chan pb.ConfChange
  112. readyc chan Ready
  113. tickc chan struct{}
  114. done chan struct{}
  115. }
  116. func newNode() node {
  117. return node{
  118. propc: make(chan pb.Message),
  119. recvc: make(chan pb.Message),
  120. compactc: make(chan []byte),
  121. confc: make(chan pb.ConfChange),
  122. readyc: make(chan Ready),
  123. tickc: make(chan struct{}),
  124. done: make(chan struct{}),
  125. }
  126. }
  127. func (n *node) Stop() {
  128. close(n.done)
  129. }
  130. func (n *node) run(r *raft) {
  131. var propc chan pb.Message
  132. var readyc chan Ready
  133. lead := None
  134. prevSoftSt := r.softState()
  135. prevHardSt := r.HardState
  136. prevSnapi := r.raftLog.snapshot.Index
  137. for {
  138. rd := newReady(r, prevSoftSt, prevHardSt, prevSnapi)
  139. if rd.containsUpdates() {
  140. readyc = n.readyc
  141. } else {
  142. readyc = nil
  143. }
  144. if rd.SoftState != nil && lead != rd.SoftState.Lead {
  145. log.Printf("raft: leader changed from %#x to %#x", lead, rd.SoftState.Lead)
  146. lead = rd.SoftState.Lead
  147. if r.hasLeader() {
  148. propc = n.propc
  149. } else {
  150. propc = nil
  151. }
  152. }
  153. select {
  154. // TODO: maybe buffer the config propose if there exists one (the way
  155. // described in raft dissertation)
  156. // Currently it is dropped in Step silently.
  157. case m := <-propc:
  158. m.From = r.id
  159. r.Step(m)
  160. case m := <-n.recvc:
  161. r.Step(m) // raft never returns an error
  162. case d := <-n.compactc:
  163. r.compact(d)
  164. case cc := <-n.confc:
  165. switch cc.Type {
  166. case pb.ConfChangeAddNode:
  167. r.addNode(cc.NodeID)
  168. case pb.ConfChangeRemoveNode:
  169. r.removeNode(cc.NodeID)
  170. default:
  171. panic("unexpected conf type")
  172. }
  173. case <-n.tickc:
  174. r.tick()
  175. case readyc <- rd:
  176. if rd.SoftState != nil {
  177. prevSoftSt = rd.SoftState
  178. }
  179. if !IsEmptyHardState(rd.HardState) {
  180. prevHardSt = rd.HardState
  181. }
  182. if !IsEmptySnap(rd.Snapshot) {
  183. prevSnapi = rd.Snapshot.Index
  184. }
  185. // TODO(yichengq): we assume that all committed config
  186. // entries will be applied to make things easy for now.
  187. // TODO(yichengq): it may have race because applied is set
  188. // before entries are applied.
  189. r.raftLog.resetNextEnts()
  190. r.raftLog.resetUnstable()
  191. r.msgs = nil
  192. case <-n.done:
  193. return
  194. }
  195. }
  196. }
  197. // Tick increments the internal logical clock for this Node. Election timeouts
  198. // and heartbeat timeouts are in units of ticks.
  199. func (n *node) Tick() {
  200. select {
  201. case n.tickc <- struct{}{}:
  202. case <-n.done:
  203. }
  204. }
  205. func (n *node) Campaign(ctx context.Context) error {
  206. return n.step(ctx, pb.Message{Type: msgHup})
  207. }
  208. func (n *node) Propose(ctx context.Context, data []byte) error {
  209. return n.step(ctx, pb.Message{Type: msgProp, Entries: []pb.Entry{{Data: data}}})
  210. }
  211. func (n *node) Step(ctx context.Context, m pb.Message) error {
  212. // ignore unexpected local messages receiving over network
  213. if m.Type == msgHup || m.Type == msgBeat {
  214. // TODO: return an error?
  215. return nil
  216. }
  217. return n.step(ctx, m)
  218. }
  219. func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
  220. data, err := cc.Marshal()
  221. if err != nil {
  222. return err
  223. }
  224. return n.Step(ctx, pb.Message{Type: msgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
  225. }
  226. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  227. // if any.
  228. func (n *node) step(ctx context.Context, m pb.Message) error {
  229. ch := n.recvc
  230. if m.Type == msgProp {
  231. ch = n.propc
  232. }
  233. select {
  234. case ch <- m:
  235. return nil
  236. case <-ctx.Done():
  237. return ctx.Err()
  238. case <-n.done:
  239. return ErrStopped
  240. }
  241. }
  242. func (n *node) Ready() <-chan Ready {
  243. return n.readyc
  244. }
  245. func (n *node) ApplyConfChange(cc pb.ConfChange) {
  246. select {
  247. case n.confc <- cc:
  248. case <-n.done:
  249. }
  250. }
  251. func (n *node) Compact(d []byte) {
  252. select {
  253. case n.compactc <- d:
  254. case <-n.done:
  255. }
  256. }
  257. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState, prevSnapi int64) Ready {
  258. rd := Ready{
  259. Entries: r.raftLog.unstableEnts(),
  260. CommittedEntries: r.raftLog.nextEnts(),
  261. Messages: r.msgs,
  262. }
  263. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  264. rd.SoftState = softSt
  265. }
  266. if !isHardStateEqual(r.HardState, prevHardSt) {
  267. rd.HardState = r.HardState
  268. }
  269. if prevSnapi != r.raftLog.snapshot.Index {
  270. rd.Snapshot = r.raftLog.snapshot
  271. }
  272. return rd
  273. }