node.go 14 KB

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