node.go 13 KB

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