doc.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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 provides an implementation of the raft consensus algorithm.
  16. Usage
  17. The primary object in raft is a Node. You either start a Node from scratch
  18. using raft.StartNode or start a Node from some initial state using raft.RestartNode.
  19. storage := raft.NewMemoryStorage()
  20. n := raft.StartNode(0x01, []raft.Peer{{ID: 0x02}, {ID: 0x03}}, 3, 1, storage)
  21. Now that you are holding onto a Node you have a few responsibilities:
  22. First, you must read from the Node.Ready() channel and process the updates
  23. it contains. These steps may be performed in parallel, except as noted in step
  24. 2.
  25. 1. Write HardState, Entries, and Snapshot to persistent storage if they are
  26. not empty. Note that when writing an Entry with Index i, any
  27. previously-persisted entries with Index >= i must be discarded.
  28. 2. Send all Messages to the nodes named in the To field. It is important that
  29. no messages be sent until after the latest HardState has been persisted to disk,
  30. and all Entries written by any previous Ready batch (Messages may be sent while
  31. entries from the same batch are being persisted). If any Message has type MsgSnap,
  32. call Node.ReportSnapshot() after it has been sent (these messages may be large).
  33. 3. Apply Snapshot (if any) and CommittedEntries to the state machine.
  34. If any committed Entry has Type EntryConfChange, call Node.ApplyConfChange()
  35. to apply it to the node. The configuration change may be cancelled at this point
  36. by setting the NodeID field to zero before calling ApplyConfChange
  37. (but ApplyConfChange must be called one way or the other, and the decision to cancel
  38. must be based solely on the state machine and not external information such as
  39. the observed health of the node).
  40. 4. Call Node.Advance() to signal readiness for the next batch of updates.
  41. This may be done at any time after step 1, although all updates must be processed
  42. in the order they were returned by Ready.
  43. Second, all persisted log entries must be made available via an
  44. implementation of the Storage interface. The provided MemoryStorage
  45. type can be used for this (if you repopulate its state upon a
  46. restart), or you can supply your own disk-backed implementation.
  47. Third, when you receive a message from another node, pass it to Node.Step:
  48. func recvRaftRPC(ctx context.Context, m raftpb.Message) {
  49. n.Step(ctx, m)
  50. }
  51. Finally, you need to call Node.Tick() at regular intervals (probably
  52. via a time.Ticker). Raft has two important timeouts: heartbeat and the
  53. election timeout. However, internally to the raft package time is
  54. represented by an abstract "tick".
  55. The total state machine handling loop will look something like this:
  56. for {
  57. select {
  58. case <-s.Ticker:
  59. n.Tick()
  60. case rd := <-s.Node.Ready():
  61. saveToStorage(rd.State, rd.Entries, rd.Snapshot)
  62. send(rd.Messages)
  63. if !raft.IsEmptySnap(rd.Snapshot) {
  64. processSnapshot(rd.Snapshot)
  65. }
  66. for entry := range rd.CommittedEntries {
  67. process(entry)
  68. if entry.Type == raftpb.EntryConfChange:
  69. var cc raftpb.ConfChange
  70. cc.Unmarshal(entry.Data)
  71. s.Node.ApplyConfChange(cc)
  72. }
  73. s.Node.Advance()
  74. case <-s.done:
  75. return
  76. }
  77. }
  78. To propose changes to the state machine from your node take your application
  79. data, serialize it into a byte slice and call:
  80. n.Propose(ctx, data)
  81. If the proposal is committed, data will appear in committed entries with type
  82. raftpb.EntryNormal. There is no guarantee that a proposed command will be
  83. committed; you may have to re-propose after a timeout.
  84. To add or remove node in a cluster, build ConfChange struct 'cc' and call:
  85. n.ProposeConfChange(ctx, cc)
  86. After config change is committed, some committed entry with type
  87. raftpb.EntryConfChange will be returned. You must apply it to node through:
  88. var cc raftpb.ConfChange
  89. cc.Unmarshal(data)
  90. n.ApplyConfChange(cc)
  91. Note: An ID represents a unique node in a cluster for all time. A
  92. given ID MUST be used only once even if the old node has been removed.
  93. This means that for example IP addresses make poor node IDs since they
  94. may be reused. Node IDs must be non-zero.
  95. Implementation notes
  96. This implementation is up to date with the final Raft thesis
  97. (https://ramcloud.stanford.edu/~ongaro/thesis.pdf), although our
  98. implementation of the membership change protocol differs somewhat from
  99. that described in chapter 4. The key invariant that membership changes
  100. happen one node at a time is preserved, but in our implementation the
  101. membership change takes effect when its entry is applied, not when it
  102. is added to the log (so the entry is committed under the old
  103. membership instead of the new). This is equivalent in terms of safety,
  104. since the old and new configurations are guaranteed to overlap.
  105. To ensure that we do not attempt to commit two membership changes at
  106. once by matching log positions (which would be unsafe since they
  107. should have different quorum requirements), we simply disallow any
  108. proposed membership change while any uncommitted change appears in
  109. the leader's log.
  110. This approach introduces a problem when you try to remove a member
  111. from a two-member cluster: If one of the members dies before the
  112. other one receives the commit of the confchange entry, then the member
  113. cannot be removed any more since the cluster cannot make progress.
  114. For this reason it is highly recommened to use three or more nodes in
  115. every cluster.
  116. */
  117. package raft