node.go 12 KB

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