node.go 13 KB

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