node.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. // Configure proposes config change. Only one config can be in the process of going through consensus at a time.
  68. Configure(ctx context.Context, data []byte) error
  69. // Step advances the state machine using the given message. ctx.Err() will be returned, if any.
  70. Step(ctx context.Context, msg pb.Message) error
  71. // Ready returns a channel that returns the current point-in-time state
  72. Ready() <-chan Ready
  73. // Stop performs any necessary termination of the Node
  74. Stop()
  75. // Compact
  76. Compact(d []byte)
  77. // AddNode adds a node with given id into peer list.
  78. // TODO: reject existed node
  79. AddNode(id int64)
  80. // RemoveNode removes a node with give id from peer list.
  81. // TODO: reject unexisted node
  82. RemoveNode(id int64)
  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. const (
  107. confAdd = iota
  108. confRemove
  109. )
  110. type conf struct {
  111. typ int
  112. id int64
  113. }
  114. // node is the canonical implementation of the Node interface
  115. type node struct {
  116. propc chan pb.Message
  117. recvc chan pb.Message
  118. compactc chan []byte
  119. confc chan conf
  120. readyc chan Ready
  121. tickc chan struct{}
  122. done chan struct{}
  123. }
  124. func newNode() node {
  125. return node{
  126. propc: make(chan pb.Message),
  127. recvc: make(chan pb.Message),
  128. compactc: make(chan []byte),
  129. confc: make(chan conf),
  130. readyc: make(chan Ready),
  131. tickc: make(chan struct{}),
  132. done: make(chan struct{}),
  133. }
  134. }
  135. func (n *node) Stop() {
  136. close(n.done)
  137. }
  138. func (n *node) run(r *raft) {
  139. var propc chan pb.Message
  140. var readyc chan Ready
  141. lead := None
  142. prevSoftSt := r.softState()
  143. prevHardSt := r.HardState
  144. prevSnapi := r.raftLog.snapshot.Index
  145. for {
  146. rd := newReady(r, prevSoftSt, prevHardSt, prevSnapi)
  147. if rd.containsUpdates() {
  148. readyc = n.readyc
  149. } else {
  150. readyc = nil
  151. }
  152. if rd.SoftState != nil && lead != rd.SoftState.Lead {
  153. log.Printf("raft: leader changed from %#x to %#x", lead, rd.SoftState.Lead)
  154. lead = rd.SoftState.Lead
  155. if r.hasLeader() {
  156. propc = n.propc
  157. } else {
  158. propc = nil
  159. }
  160. }
  161. select {
  162. // TODO: buffer the config propose if there exists one
  163. case m := <-propc:
  164. m.From = r.id
  165. r.Step(m)
  166. case m := <-n.recvc:
  167. r.Step(m) // raft never returns an error
  168. case d := <-n.compactc:
  169. r.compact(d)
  170. case c := <-n.confc:
  171. switch c.typ {
  172. case confAdd:
  173. r.addNode(c.id)
  174. case confRemove:
  175. r.removeNode(c.id)
  176. default:
  177. panic("unexpected conf type")
  178. }
  179. case <-n.tickc:
  180. r.tick()
  181. case readyc <- rd:
  182. if rd.SoftState != nil {
  183. prevSoftSt = rd.SoftState
  184. }
  185. if !IsEmptyHardState(rd.HardState) {
  186. prevHardSt = rd.HardState
  187. }
  188. if !IsEmptySnap(rd.Snapshot) {
  189. prevSnapi = rd.Snapshot.Index
  190. }
  191. // TODO(yichengq): we assume that all committed config
  192. // entries will be applied to make things easy for now.
  193. // TODO(yichengq): it may have race because applied is set
  194. // before entries are applied.
  195. r.raftLog.resetNextEnts()
  196. r.raftLog.resetUnstable()
  197. r.msgs = nil
  198. case <-n.done:
  199. return
  200. }
  201. }
  202. }
  203. // Tick increments the internal logical clock for this Node. Election timeouts
  204. // and heartbeat timeouts are in units of ticks.
  205. func (n *node) Tick() {
  206. select {
  207. case n.tickc <- struct{}{}:
  208. case <-n.done:
  209. }
  210. }
  211. func (n *node) Campaign(ctx context.Context) error {
  212. return n.Step(ctx, pb.Message{Type: msgHup})
  213. }
  214. func (n *node) Propose(ctx context.Context, data []byte) error {
  215. return n.Step(ctx, pb.Message{Type: msgProp, Entries: []pb.Entry{{Data: data}}})
  216. }
  217. func (n *node) Configure(ctx context.Context, data []byte) error {
  218. return n.Step(ctx, pb.Message{Type: msgProp, Entries: []pb.Entry{{Type: pb.EntryConfig, Data: data}}})
  219. }
  220. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  221. // if any.
  222. func (n *node) Step(ctx context.Context, m pb.Message) error {
  223. ch := n.recvc
  224. if m.Type == msgProp {
  225. ch = n.propc
  226. }
  227. select {
  228. case ch <- m:
  229. return nil
  230. case <-ctx.Done():
  231. return ctx.Err()
  232. case <-n.done:
  233. return ErrStopped
  234. }
  235. }
  236. func (n *node) Ready() <-chan Ready {
  237. return n.readyc
  238. }
  239. func (n *node) Compact(d []byte) {
  240. select {
  241. case n.compactc <- d:
  242. case <-n.done:
  243. }
  244. }
  245. func (n *node) AddNode(id int64) {
  246. select {
  247. case n.confc <- conf{typ: confAdd, id: id}:
  248. case <-n.done:
  249. }
  250. }
  251. func (n *node) RemoveNode(id int64) {
  252. select {
  253. case n.confc <- conf{typ: confRemove, id: id}:
  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. }