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. type compact struct {
  62. index uint64
  63. nodes []uint64
  64. data []byte
  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.Index == 0
  76. }
  77. func (rd Ready) containsUpdates() bool {
  78. return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) || !IsEmptySnap(rd.Snapshot) ||
  79. len(rd.Entries) > 0 || len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0
  80. }
  81. // Node represents a node in a raft cluster.
  82. type Node interface {
  83. // Tick increments the internal logical clock for the Node by a single tick. Election
  84. // timeouts and heartbeat timeouts are in units of ticks.
  85. Tick()
  86. // Campaign causes the Node to transition to candidate state and start campaigning to become leader.
  87. Campaign(ctx context.Context) error
  88. // Propose proposes that data be appended to the log.
  89. Propose(ctx context.Context, data []byte) error
  90. // ProposeConfChange proposes config change.
  91. // At most one ConfChange can be in the process of going through consensus.
  92. // Application needs to call ApplyConfChange when applying EntryConfChange type entry.
  93. ProposeConfChange(ctx context.Context, cc pb.ConfChange) error
  94. // Step advances the state machine using the given message. ctx.Err() will be returned, if any.
  95. Step(ctx context.Context, msg pb.Message) error
  96. // Ready returns a channel that returns the current point-in-time state
  97. // Users of the Node must call Advance after applying the state returned by Ready
  98. Ready() <-chan Ready
  99. // Advance notifies the Node that the application has applied and saved progress up to the last Ready.
  100. // It prepares the node to return the next available Ready.
  101. Advance()
  102. // ApplyConfChange applies config change to the local node.
  103. // TODO: reject existing node when add node
  104. // TODO: reject non-existant node when remove node
  105. ApplyConfChange(cc pb.ConfChange)
  106. // Stop performs any necessary termination of the Node
  107. Stop()
  108. // Compact discards the entrire log up to the given index. It also
  109. // generates a raft snapshot containing the given nodes configuration
  110. // and the given snapshot data.
  111. // It is the caller's responsibility to ensure the given configuration
  112. // and snapshot data match the actual point-in-time configuration and snapshot
  113. // at the given index.
  114. Compact(index uint64, nodes []uint64, d []byte)
  115. }
  116. type Peer struct {
  117. ID uint64
  118. Context []byte
  119. }
  120. // StartNode returns a new Node given a unique raft id, a list of raft peers, and
  121. // the election and heartbeat timeouts in units of ticks.
  122. // It appends a ConfChangeAddNode entry for each given peer to the initial log.
  123. func StartNode(id uint64, peers []Peer, election, heartbeat int) Node {
  124. n := newNode()
  125. r := newRaft(id, nil, election, heartbeat)
  126. for _, peer := range peers {
  127. cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context}
  128. d, err := cc.Marshal()
  129. if err != nil {
  130. panic("unexpected marshal error")
  131. }
  132. e := pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: r.raftLog.lastIndex() + 1, Data: d}
  133. r.raftLog.append(r.raftLog.lastIndex(), e)
  134. }
  135. r.raftLog.committed = r.raftLog.lastIndex()
  136. go n.run(r)
  137. return &n
  138. }
  139. // RestartNode is identical to StartNode but takes an initial State and a slice
  140. // of entries. Generally this is used when restarting from a stable storage
  141. // log.
  142. func RestartNode(id uint64, election, heartbeat int, snapshot *pb.Snapshot, st pb.HardState, ents []pb.Entry) Node {
  143. n := newNode()
  144. r := newRaft(id, nil, election, heartbeat)
  145. if snapshot != nil {
  146. r.restore(*snapshot)
  147. r.raftLog.appliedTo(snapshot.Index)
  148. }
  149. if !isHardStateEqual(st, emptyState) {
  150. r.loadState(st)
  151. }
  152. if len(ents) != 0 {
  153. r.loadEnts(ents)
  154. }
  155. go n.run(r)
  156. return &n
  157. }
  158. // node is the canonical implementation of the Node interface
  159. type node struct {
  160. propc chan pb.Message
  161. recvc chan pb.Message
  162. compactc chan compact
  163. confc chan pb.ConfChange
  164. readyc chan Ready
  165. advancec chan struct{}
  166. tickc chan struct{}
  167. done chan struct{}
  168. stop chan struct{}
  169. }
  170. func newNode() node {
  171. return node{
  172. propc: make(chan pb.Message),
  173. recvc: make(chan pb.Message),
  174. compactc: make(chan compact),
  175. confc: make(chan pb.ConfChange),
  176. readyc: make(chan Ready),
  177. advancec: make(chan struct{}),
  178. tickc: make(chan struct{}),
  179. done: make(chan struct{}),
  180. stop: make(chan struct{}),
  181. }
  182. }
  183. func (n *node) Stop() {
  184. select {
  185. case n.stop <- struct{}{}:
  186. // Not already stopped, so trigger it
  187. case <-n.done:
  188. // Node has already been stopped - no need to do anything
  189. return
  190. }
  191. // Block until the stop has been acknowledged by run()
  192. <-n.done
  193. }
  194. func (n *node) run(r *raft) {
  195. var propc chan pb.Message
  196. var readyc chan Ready
  197. var advancec chan struct{}
  198. var prevLastUnstablei uint64
  199. var havePrevLastUnstablei bool
  200. var rd Ready
  201. lead := None
  202. prevSoftSt := r.softState()
  203. prevHardSt := r.HardState
  204. prevSnapi := r.raftLog.snapshot.Index
  205. for {
  206. if advancec != nil {
  207. readyc = nil
  208. } else {
  209. rd = newReady(r, prevSoftSt, prevHardSt, prevSnapi)
  210. if rd.containsUpdates() {
  211. readyc = n.readyc
  212. } else {
  213. readyc = nil
  214. }
  215. if rd.SoftState != nil && lead != rd.SoftState.Lead {
  216. if r.hasLeader() {
  217. if lead == None {
  218. log.Printf("raft: elected leader %x at term %d", rd.SoftState.Lead, r.Term)
  219. } else {
  220. log.Printf("raft: leader changed from %x to %x at term %d", lead, rd.SoftState.Lead, r.Term)
  221. }
  222. propc = n.propc
  223. } else {
  224. log.Printf("raft: lost leader %x at term %d", lead, r.Term)
  225. propc = nil
  226. }
  227. lead = rd.SoftState.Lead
  228. }
  229. }
  230. select {
  231. // TODO: maybe buffer the config propose if there exists one (the way
  232. // described in raft dissertation)
  233. // Currently it is dropped in Step silently.
  234. case m := <-propc:
  235. m.From = r.id
  236. r.Step(m)
  237. case m := <-n.recvc:
  238. r.Step(m) // raft never returns an error
  239. case c := <-n.compactc:
  240. r.compact(c.index, c.nodes, c.data)
  241. case cc := <-n.confc:
  242. if cc.NodeID == None {
  243. r.resetPendingConf()
  244. break
  245. }
  246. switch cc.Type {
  247. case pb.ConfChangeAddNode:
  248. r.addNode(cc.NodeID)
  249. case pb.ConfChangeRemoveNode:
  250. r.removeNode(cc.NodeID)
  251. case pb.ConfChangeUpdateNode:
  252. r.resetPendingConf()
  253. default:
  254. panic("unexpected conf type")
  255. }
  256. case <-n.tickc:
  257. r.tick()
  258. case readyc <- rd:
  259. if rd.SoftState != nil {
  260. prevSoftSt = rd.SoftState
  261. }
  262. if len(rd.Entries) > 0 {
  263. prevLastUnstablei = rd.Entries[len(rd.Entries)-1].Index
  264. havePrevLastUnstablei = true
  265. }
  266. if !IsEmptyHardState(rd.HardState) {
  267. prevHardSt = rd.HardState
  268. }
  269. if !IsEmptySnap(rd.Snapshot) {
  270. prevSnapi = rd.Snapshot.Index
  271. if prevSnapi > prevLastUnstablei {
  272. prevLastUnstablei = prevSnapi
  273. havePrevLastUnstablei = true
  274. }
  275. }
  276. r.msgs = nil
  277. advancec = n.advancec
  278. case <-advancec:
  279. if prevHardSt.Commit != 0 {
  280. r.raftLog.appliedTo(prevHardSt.Commit)
  281. }
  282. if havePrevLastUnstablei {
  283. r.raftLog.stableTo(prevLastUnstablei)
  284. havePrevLastUnstablei = false
  285. }
  286. advancec = nil
  287. case <-n.stop:
  288. close(n.done)
  289. return
  290. }
  291. }
  292. }
  293. // Tick increments the internal logical clock for this Node. Election timeouts
  294. // and heartbeat timeouts are in units of ticks.
  295. func (n *node) Tick() {
  296. select {
  297. case n.tickc <- struct{}{}:
  298. case <-n.done:
  299. }
  300. }
  301. func (n *node) Campaign(ctx context.Context) error {
  302. return n.step(ctx, pb.Message{Type: pb.MsgHup})
  303. }
  304. func (n *node) Propose(ctx context.Context, data []byte) error {
  305. return n.step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  306. }
  307. func (n *node) Step(ctx context.Context, m pb.Message) error {
  308. // ignore unexpected local messages receiving over network
  309. if m.Type == pb.MsgHup || m.Type == pb.MsgBeat {
  310. // TODO: return an error?
  311. return nil
  312. }
  313. return n.step(ctx, m)
  314. }
  315. func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
  316. data, err := cc.Marshal()
  317. if err != nil {
  318. return err
  319. }
  320. return n.Step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
  321. }
  322. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  323. // if any.
  324. func (n *node) step(ctx context.Context, m pb.Message) error {
  325. ch := n.recvc
  326. if m.Type == pb.MsgProp {
  327. ch = n.propc
  328. }
  329. select {
  330. case ch <- m:
  331. return nil
  332. case <-ctx.Done():
  333. return ctx.Err()
  334. case <-n.done:
  335. return ErrStopped
  336. }
  337. }
  338. func (n *node) Ready() <-chan Ready {
  339. return n.readyc
  340. }
  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) {
  348. select {
  349. case n.confc <- cc:
  350. case <-n.done:
  351. }
  352. }
  353. func (n *node) Compact(index uint64, nodes []uint64, d []byte) {
  354. select {
  355. case n.compactc <- compact{index, nodes, d}:
  356. case <-n.done:
  357. }
  358. }
  359. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState, prevSnapi uint64) Ready {
  360. rd := Ready{
  361. Entries: r.raftLog.unstableEnts(),
  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 prevSnapi != r.raftLog.snapshot.Index {
  372. rd.Snapshot = r.raftLog.snapshot
  373. }
  374. return rd
  375. }