doc.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. /*
  15. Package raft sends and receives messages in the Protocol Buffer format
  16. defined in the raftpb package.
  17. Raft is a protocol with which a cluster of nodes can maintain a replicated state machine.
  18. The state machine is kept in sync through the use of a replicated log.
  19. For more details on Raft, see "In Search of an Understandable Consensus Algorithm"
  20. (https://ramcloud.stanford.edu/raft.pdf) by Diego Ongaro and John Ousterhout.
  21. A simple example application, _raftexample_, is also available to help illustrate
  22. how to use this package in practice:
  23. https://github.com/coreos/etcd/tree/master/contrib/raftexample
  24. Usage
  25. The primary object in raft is a Node. You either start a Node from scratch
  26. using raft.StartNode or start a Node from some initial state using raft.RestartNode.
  27. To start a node from scratch:
  28. storage := raft.NewMemoryStorage()
  29. c := &Config{
  30. ID: 0x01,
  31. ElectionTick: 10,
  32. HeartbeatTick: 1,
  33. Storage: storage,
  34. MaxSizePerMsg: 4096,
  35. MaxInflightMsgs: 256,
  36. }
  37. n := raft.StartNode(c, []raft.Peer{{ID: 0x02}, {ID: 0x03}})
  38. To restart a node from previous state:
  39. storage := raft.NewMemoryStorage()
  40. // recover the in-memory storage from persistent
  41. // snapshot, state and entries.
  42. storage.ApplySnapshot(snapshot)
  43. storage.SetHardState(state)
  44. storage.Append(entries)
  45. c := &Config{
  46. ID: 0x01,
  47. ElectionTick: 10,
  48. HeartbeatTick: 1,
  49. Storage: storage,
  50. MaxSizePerMsg: 4096,
  51. MaxInflightMsgs: 256,
  52. }
  53. // restart raft without peer information.
  54. // peer information is already included in the storage.
  55. n := raft.RestartNode(c)
  56. Now that you are holding onto a Node you have a few responsibilities:
  57. First, you must read from the Node.Ready() channel and process the updates
  58. it contains. These steps may be performed in parallel, except as noted in step
  59. 2.
  60. 1. Write HardState, Entries, and Snapshot to persistent storage if they are
  61. not empty. Note that when writing an Entry with Index i, any
  62. previously-persisted entries with Index >= i must be discarded.
  63. 2. Send all Messages to the nodes named in the To field. It is important that
  64. no messages be sent until after the latest HardState has been persisted to disk,
  65. and all Entries written by any previous Ready batch (Messages may be sent while
  66. entries from the same batch are being persisted). If any Message has type MsgSnap,
  67. call Node.ReportSnapshot() after it has been sent (these messages may be large).
  68. 3. Apply Snapshot (if any) and CommittedEntries to the state machine.
  69. If any committed Entry has Type EntryConfChange, call Node.ApplyConfChange()
  70. to apply it to the node. The configuration change may be cancelled at this point
  71. by setting the NodeID field to zero before calling ApplyConfChange
  72. (but ApplyConfChange must be called one way or the other, and the decision to cancel
  73. must be based solely on the state machine and not external information such as
  74. the observed health of the node).
  75. 4. Call Node.Advance() to signal readiness for the next batch of updates.
  76. This may be done at any time after step 1, although all updates must be processed
  77. in the order they were returned by Ready.
  78. Second, all persisted log entries must be made available via an
  79. implementation of the Storage interface. The provided MemoryStorage
  80. type can be used for this (if you repopulate its state upon a
  81. restart), or you can supply your own disk-backed implementation.
  82. Third, when you receive a message from another node, pass it to Node.Step:
  83. func recvRaftRPC(ctx context.Context, m raftpb.Message) {
  84. n.Step(ctx, m)
  85. }
  86. Finally, you need to call Node.Tick() at regular intervals (probably
  87. via a time.Ticker). Raft has two important timeouts: heartbeat and the
  88. election timeout. However, internally to the raft package time is
  89. represented by an abstract "tick".
  90. The total state machine handling loop will look something like this:
  91. for {
  92. select {
  93. case <-s.Ticker:
  94. n.Tick()
  95. case rd := <-s.Node.Ready():
  96. saveToStorage(rd.State, rd.Entries, rd.Snapshot)
  97. send(rd.Messages)
  98. if !raft.IsEmptySnap(rd.Snapshot) {
  99. processSnapshot(rd.Snapshot)
  100. }
  101. for _, entry := range rd.CommittedEntries {
  102. process(entry)
  103. if entry.Type == raftpb.EntryConfChange {
  104. var cc raftpb.ConfChange
  105. cc.Unmarshal(entry.Data)
  106. s.Node.ApplyConfChange(cc)
  107. }
  108. s.Node.Advance()
  109. case <-s.done:
  110. return
  111. }
  112. }
  113. To propose changes to the state machine from your node take your application
  114. data, serialize it into a byte slice and call:
  115. n.Propose(ctx, data)
  116. If the proposal is committed, data will appear in committed entries with type
  117. raftpb.EntryNormal. There is no guarantee that a proposed command will be
  118. committed; you may have to re-propose after a timeout.
  119. To add or remove node in a cluster, build ConfChange struct 'cc' and call:
  120. n.ProposeConfChange(ctx, cc)
  121. After config change is committed, some committed entry with type
  122. raftpb.EntryConfChange will be returned. You must apply it to node through:
  123. var cc raftpb.ConfChange
  124. cc.Unmarshal(data)
  125. n.ApplyConfChange(cc)
  126. Note: An ID represents a unique node in a cluster for all time. A
  127. given ID MUST be used only once even if the old node has been removed.
  128. This means that for example IP addresses make poor node IDs since they
  129. may be reused. Node IDs must be non-zero.
  130. Implementation notes
  131. This implementation is up to date with the final Raft thesis
  132. (https://ramcloud.stanford.edu/~ongaro/thesis.pdf), although our
  133. implementation of the membership change protocol differs somewhat from
  134. that described in chapter 4. The key invariant that membership changes
  135. happen one node at a time is preserved, but in our implementation the
  136. membership change takes effect when its entry is applied, not when it
  137. is added to the log (so the entry is committed under the old
  138. membership instead of the new). This is equivalent in terms of safety,
  139. since the old and new configurations are guaranteed to overlap.
  140. To ensure that we do not attempt to commit two membership changes at
  141. once by matching log positions (which would be unsafe since they
  142. should have different quorum requirements), we simply disallow any
  143. proposed membership change while any uncommitted change appears in
  144. the leader's log.
  145. This approach introduces a problem when you try to remove a member
  146. from a two-member cluster: If one of the members dies before the
  147. other one receives the commit of the confchange entry, then the member
  148. cannot be removed any more since the cluster cannot make progress.
  149. For this reason it is highly recommended to use three or more nodes in
  150. every cluster.
  151. MessageType
  152. Package raft sends and receives message in Protocol Buffer format (defined
  153. in raftpb package). Each state (follower, candidate, leader) implements its
  154. own 'step' method ('stepFollower', 'stepCandidate', 'stepLeader') when
  155. advancing with the given raftpb.Message. Each step is determined by its
  156. raftpb.MessageType. Note that every step is checked by one common method
  157. 'Step' that safety-checks the terms of node and incoming message to prevent
  158. stale log entries:
  159. 'MsgHup' is used for election. If a node is a follower or candidate, the
  160. 'tick' function in 'raft' struct is set as 'tickElection'. If a follower or
  161. candidate has not received any heartbeat before the election timeout, it
  162. passes 'MsgHup' to its Step method and becomes (or remains) a candidate to
  163. start a new election.
  164. 'MsgBeat' is an internal type that signals leaders to send a heartbeat of
  165. the 'MsgHeartbeat' type. If a node is a leader, the 'tick' function in
  166. the 'raft' struct is set as 'tickHeartbeat', and sends periodic heartbeat
  167. messages of the 'MsgBeat' type to its followers.
  168. 'MsgProp' proposes to append data to its log entries. This is a special
  169. type to redirect proposals to leader. Therefore, send method overwrites
  170. raftpb.Message's term with its HardState's term to avoid attaching its
  171. local term to 'MsgProp'. When 'MsgProp' is passed to the leader's 'Step'
  172. method, the leader first calls the 'appendEntry' method to append entries
  173. to its log, and then calls 'bcastAppend' method to send those entries to
  174. its peers. When passed to candidate, 'MsgProp' is dropped. When passed to
  175. follower, 'MsgProp' is stored in follower's mailbox(msgs) by the send
  176. method. It is stored with sender's ID and later forwarded to leader by
  177. rafthttp package.
  178. 'MsgApp' contains log entries to replicate. A leader calls bcastAppend,
  179. which calls sendAppend, which sends soon-to-be-replicated logs in 'MsgApp'
  180. type. When 'MsgApp' is passed to candidate's Step method, candidate reverts
  181. back to follower, because it indicates that there is a valid leader sending
  182. 'MsgApp' messages. Candidate and follower respond to this message in
  183. 'MsgAppResp' type.
  184. 'MsgAppResp' is response to log replication request('MsgApp'). When
  185. 'MsgApp' is passed to candidate or follower's Step method, it responds by
  186. calling 'handleAppendEntries' method, which sends 'MsgAppResp' to raft
  187. mailbox.
  188. 'MsgVote' requests votes for election. When a node is a follower or
  189. candidate and 'MsgHup' is passed to its Step method, then the node calls
  190. 'campaign' method to campaign itself to become a leader. Once 'campaign'
  191. method is called, the node becomes candidate and sends 'MsgVote' to peers
  192. in cluster to request votes. When passed to leader or candidate's Step
  193. method and the message's Term is lower than leader's or candidate's,
  194. 'MsgVote' will be rejected ('MsgVoteResp' is returned with Reject true).
  195. If leader or candidate receives 'MsgVote' with higher term, it will revert
  196. back to follower. When 'MsgVote' is passed to follower, it votes for the
  197. sender only when sender's last term is greater than MsgVote's term or
  198. sender's last term is equal to MsgVote's term but sender's last committed
  199. index is greater than or equal to follower's.
  200. 'MsgVoteResp' contains responses from voting request. When 'MsgVoteResp' is
  201. passed to candidate, the candidate calculates how many votes it has won. If
  202. it's more than majority (quorum), it becomes leader and calls 'bcastAppend'.
  203. If candidate receives majority of votes of denials, it reverts back to
  204. follower.
  205. 'MsgSnap' requests to install a snapshot message. When a node has just
  206. become a leader or the leader receives 'MsgProp' message, it calls
  207. 'bcastAppend' method, which then calls 'sendAppend' method to each
  208. follower. In 'sendAppend', if a leader fails to get term or entries,
  209. the leader requests snapshot by sending 'MsgSnap' type message.
  210. 'MsgSnapStatus' tells the result of snapshot install message. When a
  211. follower rejected 'MsgSnap', it indicates the snapshot request with
  212. 'MsgSnap' had failed from network issues which causes the network layer
  213. to fail to send out snapshots to its followers. Then leader considers
  214. follower's progress as probe. When 'MsgSnap' were not rejected, it
  215. indicates that the snapshot succeeded and the leader sets follower's
  216. progress to probe and resumes its log replication.
  217. 'MsgHeartbeat' sends heartbeat from leader. When 'MsgHeartbeat' is passed
  218. to candidate and message's term is higher than candidate's, the candidate
  219. reverts back to follower and updates its committed index from the one in
  220. this heartbeat. And it sends the message to its mailbox. When
  221. 'MsgHeartbeat' is passed to follower's Step method and message's term is
  222. higher than follower's, the follower updates its leaderID with the ID
  223. from the message.
  224. 'MsgHeartbeatResp' is a response to 'MsgHeartbeat'. When 'MsgHeartbeatResp'
  225. is passed to leader's Step method, the leader knows which follower
  226. responded. And only when the leader's last committed index is greater than
  227. follower's Match index, the leader runs 'sendAppend` method.
  228. 'MsgUnreachable' tells that request(message) wasn't delivered. When
  229. 'MsgUnreachable' is passed to leader's Step method, the leader discovers
  230. that the follower that sent this 'MsgUnreachable' is not reachable, often
  231. indicating 'MsgApp' is lost. When follower's progress state is replicate,
  232. the leader sets it back to probe.
  233. */
  234. package raft