node.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. // become the follower at term 1 and apply initial configuration
  117. // entires of term 1
  118. r.becomeFollower(1, None)
  119. for _, peer := range peers {
  120. cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context}
  121. d, err := cc.Marshal()
  122. if err != nil {
  123. panic("unexpected marshal error")
  124. }
  125. e := pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: r.raftLog.lastIndex() + 1, Data: d}
  126. r.raftLog.append(e)
  127. }
  128. // Mark these initial entries as committed.
  129. // TODO(bdarnell): These entries are still unstable; do we need to preserve
  130. // the invariant that committed < unstable?
  131. r.raftLog.committed = r.raftLog.lastIndex()
  132. // Now apply them, mainly so that the application can call Campaign
  133. // immediately after StartNode in tests. Note that these nodes will
  134. // be added to raft twice: here and when the application's Ready
  135. // loop calls ApplyConfChange. The calls to addNode must come after
  136. // all calls to raftLog.append so progress.next is set after these
  137. // bootstrapping entries (it is an error if we try to append these
  138. // entries since they have already been committed).
  139. // We do not set raftLog.applied so the application will be able
  140. // to observe all conf changes via Ready.CommittedEntries.
  141. for _, peer := range peers {
  142. r.addNode(peer.ID)
  143. }
  144. go n.run(r)
  145. return &n
  146. }
  147. // RestartNode is identical to StartNode but does not take a list of peers.
  148. // The current membership of the cluster will be restored from the Storage.
  149. func RestartNode(id uint64, election, heartbeat int, storage Storage) Node {
  150. n := newNode()
  151. r := newRaft(id, nil, election, heartbeat, storage)
  152. go n.run(r)
  153. return &n
  154. }
  155. // node is the canonical implementation of the Node interface
  156. type node struct {
  157. propc chan pb.Message
  158. recvc chan pb.Message
  159. confc chan pb.ConfChange
  160. confstatec chan pb.ConfState
  161. readyc chan Ready
  162. advancec chan struct{}
  163. tickc chan struct{}
  164. done chan struct{}
  165. stop chan struct{}
  166. }
  167. func newNode() node {
  168. return node{
  169. propc: make(chan pb.Message),
  170. recvc: make(chan pb.Message),
  171. confc: make(chan pb.ConfChange),
  172. confstatec: make(chan pb.ConfState),
  173. readyc: make(chan Ready),
  174. advancec: make(chan struct{}),
  175. tickc: make(chan struct{}),
  176. done: make(chan struct{}),
  177. stop: make(chan struct{}),
  178. }
  179. }
  180. func (n *node) Stop() {
  181. select {
  182. case n.stop <- struct{}{}:
  183. // Not already stopped, so trigger it
  184. case <-n.done:
  185. // Node has already been stopped - no need to do anything
  186. return
  187. }
  188. // Block until the stop has been acknowledged by run()
  189. <-n.done
  190. }
  191. func (n *node) run(r *raft) {
  192. var propc chan pb.Message
  193. var readyc chan Ready
  194. var advancec chan struct{}
  195. var prevLastUnstablei uint64
  196. var prevLastUnstablet uint64
  197. var havePrevLastUnstablei bool
  198. var prevSnapi uint64
  199. var rd Ready
  200. lead := None
  201. prevSoftSt := r.softState()
  202. prevHardSt := r.HardState
  203. for {
  204. if advancec != nil {
  205. readyc = nil
  206. } else {
  207. rd = newReady(r, prevSoftSt, prevHardSt)
  208. if rd.containsUpdates() {
  209. readyc = n.readyc
  210. } else {
  211. readyc = nil
  212. }
  213. }
  214. if lead != r.leader() {
  215. if r.hasLeader() {
  216. if lead == None {
  217. log.Printf("raft.node: %x elected leader %x at term %d", r.id, r.leader(), r.Term)
  218. } else {
  219. log.Printf("raft.node: %x changed leader from %x to %x at term %d", r.id, lead, r.leader(), r.Term)
  220. }
  221. propc = n.propc
  222. } else {
  223. log.Printf("raft.node: %x lost leader %x at term %d", r.id, lead, r.Term)
  224. propc = nil
  225. }
  226. lead = r.leader()
  227. }
  228. select {
  229. // TODO: maybe buffer the config propose if there exists one (the way
  230. // described in raft dissertation)
  231. // Currently it is dropped in Step silently.
  232. case m := <-propc:
  233. m.From = r.id
  234. r.Step(m)
  235. case m := <-n.recvc:
  236. // filter out response message from unknow From.
  237. if _, ok := r.prs[m.From]; ok || !IsResponseMsg(m) {
  238. r.Step(m) // raft never returns an error
  239. }
  240. case cc := <-n.confc:
  241. if cc.NodeID == None {
  242. r.resetPendingConf()
  243. select {
  244. case n.confstatec <- pb.ConfState{Nodes: r.nodes()}:
  245. case <-n.done:
  246. }
  247. break
  248. }
  249. switch cc.Type {
  250. case pb.ConfChangeAddNode:
  251. r.addNode(cc.NodeID)
  252. case pb.ConfChangeRemoveNode:
  253. r.removeNode(cc.NodeID)
  254. case pb.ConfChangeUpdateNode:
  255. r.resetPendingConf()
  256. default:
  257. panic("unexpected conf type")
  258. }
  259. select {
  260. case n.confstatec <- pb.ConfState{Nodes: r.nodes()}:
  261. case <-n.done:
  262. }
  263. case <-n.tickc:
  264. r.tick()
  265. case readyc <- rd:
  266. if rd.SoftState != nil {
  267. prevSoftSt = rd.SoftState
  268. }
  269. if len(rd.Entries) > 0 {
  270. prevLastUnstablei = rd.Entries[len(rd.Entries)-1].Index
  271. prevLastUnstablet = rd.Entries[len(rd.Entries)-1].Term
  272. havePrevLastUnstablei = true
  273. }
  274. if !IsEmptyHardState(rd.HardState) {
  275. prevHardSt = rd.HardState
  276. }
  277. if !IsEmptySnap(rd.Snapshot) {
  278. prevSnapi = rd.Snapshot.Metadata.Index
  279. }
  280. r.msgs = nil
  281. advancec = n.advancec
  282. case <-advancec:
  283. if prevHardSt.Commit != 0 {
  284. r.raftLog.appliedTo(prevHardSt.Commit)
  285. }
  286. if havePrevLastUnstablei {
  287. r.raftLog.stableTo(prevLastUnstablei, prevLastUnstablet)
  288. havePrevLastUnstablei = false
  289. }
  290. r.raftLog.stableSnapTo(prevSnapi)
  291. advancec = nil
  292. case <-n.stop:
  293. close(n.done)
  294. return
  295. }
  296. }
  297. }
  298. // Tick increments the internal logical clock for this Node. Election timeouts
  299. // and heartbeat timeouts are in units of ticks.
  300. func (n *node) Tick() {
  301. select {
  302. case n.tickc <- struct{}{}:
  303. case <-n.done:
  304. }
  305. }
  306. func (n *node) Campaign(ctx context.Context) error { return n.step(ctx, pb.Message{Type: pb.MsgHup}) }
  307. func (n *node) Propose(ctx context.Context, data []byte) error {
  308. return n.step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  309. }
  310. func (n *node) Step(ctx context.Context, m pb.Message) error {
  311. // ignore unexpected local messages receiving over network
  312. if IsLocalMsg(m) {
  313. // TODO: return an error?
  314. return nil
  315. }
  316. return n.step(ctx, m)
  317. }
  318. func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
  319. data, err := cc.Marshal()
  320. if err != nil {
  321. return err
  322. }
  323. return n.Step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
  324. }
  325. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  326. // if any.
  327. func (n *node) step(ctx context.Context, m pb.Message) error {
  328. ch := n.recvc
  329. if m.Type == pb.MsgProp {
  330. ch = n.propc
  331. }
  332. select {
  333. case ch <- m:
  334. return nil
  335. case <-ctx.Done():
  336. return ctx.Err()
  337. case <-n.done:
  338. return ErrStopped
  339. }
  340. }
  341. func (n *node) Ready() <-chan Ready { return n.readyc }
  342. func (n *node) Advance() {
  343. select {
  344. case n.advancec <- struct{}{}:
  345. case <-n.done:
  346. }
  347. }
  348. func (n *node) ApplyConfChange(cc pb.ConfChange) *pb.ConfState {
  349. var cs pb.ConfState
  350. select {
  351. case n.confc <- cc:
  352. case <-n.done:
  353. }
  354. select {
  355. case cs = <-n.confstatec:
  356. case <-n.done:
  357. }
  358. return &cs
  359. }
  360. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState) Ready {
  361. rd := Ready{
  362. Entries: r.raftLog.unstableEntries(),
  363. CommittedEntries: r.raftLog.nextEnts(),
  364. Messages: r.msgs,
  365. }
  366. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  367. rd.SoftState = softSt
  368. }
  369. if !isHardStateEqual(r.HardState, prevHardSt) {
  370. rd.HardState = r.HardState
  371. }
  372. if r.raftLog.unstable.snapshot != nil {
  373. rd.Snapshot = *r.raftLog.unstable.snapshot
  374. }
  375. return rd
  376. }