node.go 8.2 KB

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