node.go 8.7 KB

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