node.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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/code.google.com/p/go.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 also builds ConfChangeAddNode entry for each peer and puts them at the head of the 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. }
  148. if !isHardStateEqual(st, emptyState) {
  149. r.loadState(st)
  150. }
  151. if len(ents) != 0 {
  152. r.loadEnts(ents)
  153. }
  154. go n.run(r)
  155. return &n
  156. }
  157. // node is the canonical implementation of the Node interface
  158. type node struct {
  159. propc chan pb.Message
  160. recvc chan pb.Message
  161. compactc chan compact
  162. confc chan pb.ConfChange
  163. readyc chan Ready
  164. advancec chan struct{}
  165. tickc chan struct{}
  166. done chan struct{}
  167. }
  168. func newNode() node {
  169. return node{
  170. propc: make(chan pb.Message),
  171. recvc: make(chan pb.Message),
  172. compactc: make(chan compact),
  173. confc: make(chan pb.ConfChange),
  174. readyc: make(chan Ready),
  175. advancec: make(chan struct{}),
  176. tickc: make(chan struct{}),
  177. done: make(chan struct{}),
  178. }
  179. }
  180. func (n *node) Stop() {
  181. close(n.done)
  182. }
  183. func (n *node) run(r *raft) {
  184. var propc chan pb.Message
  185. var readyc chan Ready
  186. var advancec chan struct{}
  187. var prevLastUnstablei uint64
  188. var rd Ready
  189. lead := None
  190. prevSoftSt := r.softState()
  191. prevHardSt := r.HardState
  192. prevSnapi := r.raftLog.snapshot.Index
  193. for {
  194. if advancec != nil {
  195. readyc = nil
  196. } else {
  197. rd = newReady(r, prevSoftSt, prevHardSt, prevSnapi)
  198. if rd.containsUpdates() {
  199. readyc = n.readyc
  200. } else {
  201. readyc = nil
  202. }
  203. if rd.SoftState != nil && lead != rd.SoftState.Lead {
  204. if r.hasLeader() {
  205. if lead == None {
  206. log.Printf("raft: elected leader %x at term %d", rd.SoftState.Lead, r.Term)
  207. } else {
  208. log.Printf("raft: leader changed from %x to %x at term %d", lead, rd.SoftState.Lead, r.Term)
  209. }
  210. propc = n.propc
  211. } else {
  212. log.Printf("raft: lost leader %x at term %d", lead, r.Term)
  213. propc = nil
  214. }
  215. lead = rd.SoftState.Lead
  216. }
  217. }
  218. select {
  219. // TODO: maybe buffer the config propose if there exists one (the way
  220. // described in raft dissertation)
  221. // Currently it is dropped in Step silently.
  222. case m := <-propc:
  223. m.From = r.id
  224. r.Step(m)
  225. case m := <-n.recvc:
  226. r.Step(m) // raft never returns an error
  227. case c := <-n.compactc:
  228. r.compact(c.index, c.nodes, c.data)
  229. case cc := <-n.confc:
  230. if cc.NodeID == None {
  231. r.resetPendingConf()
  232. break
  233. }
  234. switch cc.Type {
  235. case pb.ConfChangeAddNode:
  236. r.addNode(cc.NodeID)
  237. case pb.ConfChangeRemoveNode:
  238. r.removeNode(cc.NodeID)
  239. default:
  240. panic("unexpected conf type")
  241. }
  242. case <-n.tickc:
  243. r.tick()
  244. case readyc <- rd:
  245. if rd.SoftState != nil {
  246. prevSoftSt = rd.SoftState
  247. }
  248. if len(rd.Entries) > 0 {
  249. prevLastUnstablei = rd.Entries[len(rd.Entries)-1].Index
  250. }
  251. if !IsEmptyHardState(rd.HardState) {
  252. prevHardSt = rd.HardState
  253. }
  254. if !IsEmptySnap(rd.Snapshot) {
  255. prevSnapi = rd.Snapshot.Index
  256. if prevSnapi > prevLastUnstablei {
  257. prevLastUnstablei = prevSnapi
  258. }
  259. }
  260. r.msgs = nil
  261. advancec = n.advancec
  262. case <-advancec:
  263. if prevHardSt.Commit != 0 {
  264. r.raftLog.appliedTo(prevHardSt.Commit)
  265. }
  266. if prevLastUnstablei != 0 {
  267. r.raftLog.stableTo(prevLastUnstablei)
  268. }
  269. advancec = nil
  270. case <-n.done:
  271. return
  272. }
  273. }
  274. }
  275. // Tick increments the internal logical clock for this Node. Election timeouts
  276. // and heartbeat timeouts are in units of ticks.
  277. func (n *node) Tick() {
  278. select {
  279. case n.tickc <- struct{}{}:
  280. case <-n.done:
  281. }
  282. }
  283. func (n *node) Campaign(ctx context.Context) error {
  284. return n.step(ctx, pb.Message{Type: pb.MsgHup})
  285. }
  286. func (n *node) Propose(ctx context.Context, data []byte) error {
  287. return n.step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  288. }
  289. func (n *node) Step(ctx context.Context, m pb.Message) error {
  290. // ignore unexpected local messages receiving over network
  291. if m.Type == pb.MsgHup || m.Type == pb.MsgBeat {
  292. // TODO: return an error?
  293. return nil
  294. }
  295. return n.step(ctx, m)
  296. }
  297. func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
  298. data, err := cc.Marshal()
  299. if err != nil {
  300. return err
  301. }
  302. return n.Step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
  303. }
  304. // Step advances the state machine using msgs. The ctx.Err() will be returned,
  305. // if any.
  306. func (n *node) step(ctx context.Context, m pb.Message) error {
  307. ch := n.recvc
  308. if m.Type == pb.MsgProp {
  309. ch = n.propc
  310. }
  311. select {
  312. case ch <- m:
  313. return nil
  314. case <-ctx.Done():
  315. return ctx.Err()
  316. case <-n.done:
  317. return ErrStopped
  318. }
  319. }
  320. func (n *node) Ready() <-chan Ready {
  321. return n.readyc
  322. }
  323. func (n *node) Advance() {
  324. select {
  325. case n.advancec <- struct{}{}:
  326. case <-n.done:
  327. }
  328. }
  329. func (n *node) ApplyConfChange(cc pb.ConfChange) {
  330. select {
  331. case n.confc <- cc:
  332. case <-n.done:
  333. }
  334. }
  335. func (n *node) Compact(index uint64, nodes []uint64, d []byte) {
  336. select {
  337. case n.compactc <- compact{index, nodes, d}:
  338. case <-n.done:
  339. }
  340. }
  341. func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState, prevSnapi uint64) Ready {
  342. rd := Ready{
  343. Entries: r.raftLog.unstableEnts(),
  344. CommittedEntries: r.raftLog.nextEnts(),
  345. Messages: r.msgs,
  346. }
  347. if softSt := r.softState(); !softSt.equal(prevSoftSt) {
  348. rd.SoftState = softSt
  349. }
  350. if !isHardStateEqual(r.HardState, prevHardSt) {
  351. rd.HardState = r.HardState
  352. }
  353. if prevSnapi != r.raftLog.snapshot.Index {
  354. rd.Snapshot = r.raftLog.snapshot
  355. }
  356. return rd
  357. }