node.go 9.2 KB

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