node.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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/golang.org/x/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. func isHardStateEqual(a, b pb.HardState) bool {
  62. return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
  63. }
  64. // IsEmptyHardState returns true if the given HardState is empty.
  65. func IsEmptyHardState(st pb.HardState) bool {
  66. return isHardStateEqual(st, emptyState)
  67. }
  68. // IsEmptySnap returns true if the given Snapshot is empty.
  69. func IsEmptySnap(sp pb.Snapshot) bool {
  70. return sp.Metadata.Index == 0
  71. }
  72. func (rd Ready) containsUpdates() bool {
  73. return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) ||
  74. !IsEmptySnap(rd.Snapshot) || len(rd.Entries) > 0 ||
  75. len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0
  76. }
  77. // Node represents a node in a raft cluster.
  78. type Node interface {
  79. // Tick increments the internal logical clock for the Node by a single tick. Election
  80. // timeouts and heartbeat timeouts are in units of ticks.
  81. Tick()
  82. // Campaign causes the Node to transition to candidate state and start campaigning to become leader.
  83. Campaign(ctx context.Context) error
  84. // Propose proposes that data be appended to the log.
  85. Propose(ctx context.Context, data []byte) error
  86. // ProposeConfChange proposes config change.
  87. // At most one ConfChange can be in the process of going through consensus.
  88. // Application needs to call ApplyConfChange when applying EntryConfChange type entry.
  89. ProposeConfChange(ctx context.Context, cc pb.ConfChange) error
  90. // Step advances the state machine using the given message. ctx.Err() will be returned, if any.
  91. Step(ctx context.Context, msg pb.Message) error
  92. // Ready returns a channel that returns the current point-in-time state
  93. // Users of the Node must call Advance after applying the state returned by Ready
  94. Ready() <-chan Ready
  95. // Advance notifies the Node that the application has applied and saved progress up to the last Ready.
  96. // It prepares the node to return the next available Ready.
  97. Advance()
  98. // ApplyConfChange applies config change to the local node.
  99. // Returns an opaque ConfState protobuf which must be recorded
  100. // in snapshots. Will never return nil; it returns a pointer only
  101. // to match MemoryStorage.Compact.
  102. ApplyConfChange(cc pb.ConfChange) *pb.ConfState
  103. // Stop performs any necessary termination of the Node
  104. Stop()
  105. }
  106. type Peer struct {
  107. ID uint64
  108. Context []byte
  109. }
  110. // StartNode returns a new Node given a unique raft id, a list of raft peers, and
  111. // the election and heartbeat timeouts in units of ticks.
  112. // It appends a ConfChangeAddNode entry for each given peer to the initial log.
  113. func StartNode(id uint64, peers []Peer, election, heartbeat int, storage Storage) Node {
  114. n := newNode()
  115. r := newRaft(id, nil, election, heartbeat, storage)
  116. for _, peer := range peers {
  117. cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context}
  118. d, err := cc.Marshal()
  119. if err != nil {
  120. panic("unexpected marshal error")
  121. }
  122. e := pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: r.raftLog.lastIndex() + 1, Data: d}
  123. r.raftLog.append(r.raftLog.lastIndex(), e)
  124. }
  125. // Mark these initial entries as committed.
  126. // TODO(bdarnell): These entries are still unstable; do we need to preserve
  127. // the invariant that committed < unstable?
  128. r.raftLog.committed = r.raftLog.lastIndex()
  129. go n.run(r)
  130. return &n
  131. }
  132. // RestartNode is identical to StartNode but does not take a list of peers.
  133. // The current membership of the cluster will be restored from the Storage.
  134. func RestartNode(id uint64, election, heartbeat int, storage Storage) Node {
  135. n := newNode()
  136. r := newRaft(id, nil, election, heartbeat, storage)
  137. go n.run(r)
  138. return &n
  139. }
  140. // node is the canonical implementation of the Node interface
  141. type node struct {
  142. propc chan pb.Message
  143. recvc chan pb.Message
  144. confc chan pb.ConfChange
  145. confstatec chan pb.ConfState
  146. readyc chan Ready
  147. advancec chan struct{}
  148. tickc chan struct{}
  149. done chan struct{}
  150. stop chan struct{}
  151. }
  152. func newNode() node {
  153. return node{
  154. propc: make(chan pb.Message),
  155. recvc: make(chan pb.Message),
  156. confc: make(chan pb.ConfChange),
  157. confstatec: make(chan pb.ConfState),
  158. readyc: make(chan Ready),
  159. advancec: make(chan struct{}),
  160. tickc: make(chan struct{}),
  161. done: make(chan struct{}),
  162. stop: make(chan struct{}),
  163. }
  164. }
  165. func (n *node) Stop() {
  166. select {
  167. case n.stop <- struct{}{}:
  168. // Not already stopped, so trigger it
  169. case <-n.done:
  170. // Node has already been stopped - no need to do anything
  171. return
  172. }
  173. // Block until the stop has been acknowledged by run()
  174. <-n.done
  175. }
  176. func (n *node) run(r *raft) {
  177. var propc chan pb.Message
  178. var readyc chan Ready
  179. var advancec chan struct{}
  180. var prevLastUnstablei uint64
  181. var havePrevLastUnstablei bool
  182. var rd Ready
  183. lead := None
  184. prevSoftSt := r.softState()
  185. prevHardSt := r.HardState
  186. for {
  187. if advancec != nil {
  188. readyc = nil
  189. } else {
  190. rd = newReady(r, prevSoftSt, prevHardSt)
  191. if rd.containsUpdates() {
  192. readyc = n.readyc
  193. } else {
  194. readyc = nil
  195. }
  196. if rd.SoftState != nil && lead != rd.SoftState.Lead {
  197. if r.hasLeader() {
  198. if lead == None {
  199. log.Printf("raft: elected leader %x at term %d", rd.SoftState.Lead, r.Term)
  200. } else {
  201. log.Printf("raft: leader changed from %x to %x at term %d", lead, rd.SoftState.Lead, r.Term)
  202. }
  203. propc = n.propc
  204. } else {
  205. log.Printf("raft: lost leader %x at term %d", lead, r.Term)
  206. propc = nil
  207. }
  208. lead = rd.SoftState.Lead
  209. }
  210. }
  211. select {
  212. // TODO: maybe buffer the config propose if there exists one (the way
  213. // described in raft dissertation)
  214. // Currently it is dropped in Step silently.
  215. case m := <-propc:
  216. m.From = r.id
  217. r.Step(m)
  218. case m := <-n.recvc:
  219. r.Step(m) // raft never returns an error
  220. case cc := <-n.confc:
  221. if cc.NodeID == None {
  222. r.resetPendingConf()
  223. select {
  224. case n.confstatec <- pb.ConfState{Nodes: r.nodes()}:
  225. case <-n.done:
  226. }
  227. break
  228. }
  229. switch cc.Type {
  230. case pb.ConfChangeAddNode:
  231. r.addNode(cc.NodeID)
  232. case pb.ConfChangeRemoveNode:
  233. r.removeNode(cc.NodeID)
  234. case pb.ConfChangeUpdateNode:
  235. r.resetPendingConf()
  236. default:
  237. panic("unexpected conf type")
  238. }
  239. select {
  240. case n.confstatec <- pb.ConfState{Nodes: r.nodes()}:
  241. case <-n.done:
  242. }
  243. case <-n.tickc:
  244. r.tick()
  245. case readyc <- rd:
  246. if rd.SoftState != nil {
  247. prevSoftSt = rd.SoftState
  248. }
  249. if len(rd.Entries) > 0 {
  250. prevLastUnstablei = rd.Entries[len(rd.Entries)-1].Index
  251. havePrevLastUnstablei = true
  252. }
  253. if !IsEmptyHardState(rd.HardState) {
  254. prevHardSt = rd.HardState
  255. }
  256. if !IsEmptySnap(rd.Snapshot) {
  257. if rd.Snapshot.Metadata.Index > prevLastUnstablei {
  258. prevLastUnstablei = rd.Snapshot.Metadata.Index
  259. havePrevLastUnstablei = true
  260. }
  261. }
  262. r.msgs = nil
  263. advancec = n.advancec
  264. case <-advancec:
  265. if prevHardSt.Commit != 0 {
  266. r.raftLog.appliedTo(prevHardSt.Commit)
  267. }
  268. if havePrevLastUnstablei {
  269. r.raftLog.stableTo(prevLastUnstablei)
  270. havePrevLastUnstablei = false
  271. }
  272. advancec = nil
  273. case <-n.stop:
  274. close(n.done)
  275. return
  276. }
  277. }
  278. }
  279. // Tick increments the internal logical clock for this Node. Election timeouts
  280. // and heartbeat timeouts are in units of ticks.
  281. func (n *node) Tick() {
  282. select {
  283. case n.tickc <- struct{}{}:
  284. case <-n.done:
  285. }
  286. }
  287. func (n *node) Campaign(ctx context.Context) error {
  288. return n.step(ctx, pb.Message{Type: pb.MsgHup})
  289. }
  290. func (n *node) Propose(ctx context.Context, data []byte) error {
  291. return n.step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  292. }
  293. func (n *node) Step(ctx context.Context, m pb.Message) error {
  294. // ignore unexpected local messages receiving over network
  295. if m.Type == pb.MsgHup || m.Type == pb.MsgBeat {
  296. // TODO: return an error?
  297. return nil
  298. }
  299. return n.step(ctx, m)
  300. }
  301. func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
  302. data, err := cc.Marshal()
  303. if err != nil {
  304. return err
  305. }
  306. return n.Step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
  307. }
  308. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  309. // if any.
  310. func (n *node) step(ctx context.Context, m pb.Message) error {
  311. ch := n.recvc
  312. if m.Type == pb.MsgProp {
  313. ch = n.propc
  314. }
  315. select {
  316. case ch <- m:
  317. return nil
  318. case <-ctx.Done():
  319. return ctx.Err()
  320. case <-n.done:
  321. return ErrStopped
  322. }
  323. }
  324. func (n *node) Ready() <-chan Ready {
  325. return n.readyc
  326. }
  327. func (n *node) Advance() {
  328. select {
  329. case n.advancec <- struct{}{}:
  330. case <-n.done:
  331. }
  332. }
  333. func (n *node) ApplyConfChange(cc pb.ConfChange) *pb.ConfState {
  334. var cs pb.ConfState
  335. select {
  336. case n.confc <- cc:
  337. case <-n.done:
  338. }
  339. select {
  340. case cs = <-n.confstatec:
  341. case <-n.done:
  342. }
  343. return &cs
  344. }
  345. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState) Ready {
  346. rd := Ready{
  347. Entries: r.raftLog.unstableEntries(),
  348. CommittedEntries: r.raftLog.nextEnts(),
  349. Messages: r.msgs,
  350. }
  351. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  352. rd.SoftState = softSt
  353. }
  354. if !isHardStateEqual(r.HardState, prevHardSt) {
  355. rd.HardState = r.HardState
  356. }
  357. if r.snapshot != nil {
  358. rd.Snapshot = *r.snapshot
  359. }
  360. return rd
  361. }