node.go 10 KB

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