node.go 9.4 KB

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