rawnode.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // Copyright 2015 The etcd Authors
  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. pb "go.etcd.io/etcd/raft/raftpb"
  18. "go.etcd.io/etcd/raft/tracker"
  19. )
  20. // ErrStepLocalMsg is returned when try to step a local raft message
  21. var ErrStepLocalMsg = errors.New("raft: cannot step raft local message")
  22. // ErrStepPeerNotFound is returned when try to step a response message
  23. // but there is no peer found in raft.prs for that node.
  24. var ErrStepPeerNotFound = errors.New("raft: cannot step as peer not found")
  25. // RawNode is a thread-unsafe Node.
  26. // The methods of this struct correspond to the methods of Node and are described
  27. // more fully there.
  28. type RawNode struct {
  29. raft *raft
  30. prevSoftSt *SoftState
  31. prevHardSt pb.HardState
  32. }
  33. // NewRawNode instantiates a RawNode from the given configuration.
  34. //
  35. // See Bootstrap() for bootstrapping an initial state; this replaces the former
  36. // 'peers' argument to this method (with identical behavior). However, It is
  37. // recommended that instead of calling Bootstrap, applications bootstrap their
  38. // state manually by setting up a Storage that has a first index > 1 and which
  39. // stores the desired ConfState as its InitialState.
  40. func NewRawNode(config *Config) (*RawNode, error) {
  41. r := newRaft(config)
  42. rn := &RawNode{
  43. raft: r,
  44. }
  45. rn.prevSoftSt = r.softState()
  46. rn.prevHardSt = r.hardState()
  47. return rn, nil
  48. }
  49. // Tick advances the internal logical clock by a single tick.
  50. func (rn *RawNode) Tick() {
  51. rn.raft.tick()
  52. }
  53. // TickQuiesced advances the internal logical clock by a single tick without
  54. // performing any other state machine processing. It allows the caller to avoid
  55. // periodic heartbeats and elections when all of the peers in a Raft group are
  56. // known to be at the same state. Expected usage is to periodically invoke Tick
  57. // or TickQuiesced depending on whether the group is "active" or "quiesced".
  58. //
  59. // WARNING: Be very careful about using this method as it subverts the Raft
  60. // state machine. You should probably be using Tick instead.
  61. func (rn *RawNode) TickQuiesced() {
  62. rn.raft.electionElapsed++
  63. }
  64. // Campaign causes this RawNode to transition to candidate state.
  65. func (rn *RawNode) Campaign() error {
  66. return rn.raft.Step(pb.Message{
  67. Type: pb.MsgHup,
  68. })
  69. }
  70. // Propose proposes data be appended to the raft log.
  71. func (rn *RawNode) Propose(data []byte) error {
  72. return rn.raft.Step(pb.Message{
  73. Type: pb.MsgProp,
  74. From: rn.raft.id,
  75. Entries: []pb.Entry{
  76. {Data: data},
  77. }})
  78. }
  79. // ProposeConfChange proposes a config change. See (Node).ProposeConfChange for
  80. // details.
  81. func (rn *RawNode) ProposeConfChange(cc pb.ConfChangeI) error {
  82. m, err := confChangeToMsg(cc)
  83. if err != nil {
  84. return err
  85. }
  86. return rn.raft.Step(m)
  87. }
  88. // ApplyConfChange applies a config change to the local node.
  89. func (rn *RawNode) ApplyConfChange(cc pb.ConfChangeI) *pb.ConfState {
  90. cs := rn.raft.applyConfChange(cc.AsV2())
  91. return &cs
  92. }
  93. // Step advances the state machine using the given message.
  94. func (rn *RawNode) Step(m pb.Message) error {
  95. // ignore unexpected local messages receiving over network
  96. if IsLocalMsg(m.Type) {
  97. return ErrStepLocalMsg
  98. }
  99. if pr := rn.raft.prs.Progress[m.From]; pr != nil || !IsResponseMsg(m.Type) {
  100. return rn.raft.Step(m)
  101. }
  102. return ErrStepPeerNotFound
  103. }
  104. // Ready returns the outstanding work that the application needs to handle. This
  105. // includes appending and applying entries or a snapshot, updating the HardState,
  106. // and sending messages. The returned Ready() *must* be handled and subsequently
  107. // passed back via Advance().
  108. func (rn *RawNode) Ready() Ready {
  109. rd := rn.readyWithoutAccept()
  110. rn.acceptReady(rd)
  111. return rd
  112. }
  113. // readyWithoutAccept returns a Ready. This is a read-only operation, i.e. there
  114. // is no obligation that the Ready must be handled.
  115. func (rn *RawNode) readyWithoutAccept() Ready {
  116. return newReady(rn.raft, rn.prevSoftSt, rn.prevHardSt)
  117. }
  118. // acceptReady is called when the consumer of the RawNode has decided to go
  119. // ahead and handle a Ready. Nothing must alter the state of the RawNode between
  120. // this call and the prior call to Ready().
  121. func (rn *RawNode) acceptReady(rd Ready) {
  122. if rd.SoftState != nil {
  123. rn.prevSoftSt = rd.SoftState
  124. }
  125. if len(rd.ReadStates) != 0 {
  126. rn.raft.readStates = nil
  127. }
  128. rn.raft.msgs = nil
  129. }
  130. // HasReady called when RawNode user need to check if any Ready pending.
  131. // Checking logic in this method should be consistent with Ready.containsUpdates().
  132. func (rn *RawNode) HasReady() bool {
  133. r := rn.raft
  134. if !r.softState().equal(rn.prevSoftSt) {
  135. return true
  136. }
  137. if hardSt := r.hardState(); !IsEmptyHardState(hardSt) && !isHardStateEqual(hardSt, rn.prevHardSt) {
  138. return true
  139. }
  140. if r.raftLog.unstable.snapshot != nil && !IsEmptySnap(*r.raftLog.unstable.snapshot) {
  141. return true
  142. }
  143. if len(r.msgs) > 0 || len(r.raftLog.unstableEntries()) > 0 || r.raftLog.hasNextEnts() {
  144. return true
  145. }
  146. if len(r.readStates) != 0 {
  147. return true
  148. }
  149. return false
  150. }
  151. // Advance notifies the RawNode that the application has applied and saved progress in the
  152. // last Ready results.
  153. func (rn *RawNode) Advance(rd Ready) {
  154. if !IsEmptyHardState(rd.HardState) {
  155. rn.prevHardSt = rd.HardState
  156. }
  157. rn.raft.advance(rd)
  158. }
  159. // Status returns the current status of the given group. This allocates, see
  160. // BasicStatus and WithProgress for allocation-friendlier choices.
  161. func (rn *RawNode) Status() Status {
  162. status := getStatus(rn.raft)
  163. return status
  164. }
  165. // BasicStatus returns a BasicStatus. Notably this does not contain the
  166. // Progress map; see WithProgress for an allocation-free way to inspect it.
  167. func (rn *RawNode) BasicStatus() BasicStatus {
  168. return getBasicStatus(rn.raft)
  169. }
  170. // ProgressType indicates the type of replica a Progress corresponds to.
  171. type ProgressType byte
  172. const (
  173. // ProgressTypePeer accompanies a Progress for a regular peer replica.
  174. ProgressTypePeer ProgressType = iota
  175. // ProgressTypeLearner accompanies a Progress for a learner replica.
  176. ProgressTypeLearner
  177. )
  178. // WithProgress is a helper to introspect the Progress for this node and its
  179. // peers.
  180. func (rn *RawNode) WithProgress(visitor func(id uint64, typ ProgressType, pr tracker.Progress)) {
  181. rn.raft.prs.Visit(func(id uint64, pr *tracker.Progress) {
  182. typ := ProgressTypePeer
  183. if pr.IsLearner {
  184. typ = ProgressTypeLearner
  185. }
  186. p := *pr
  187. p.Inflights = nil
  188. visitor(id, typ, p)
  189. })
  190. }
  191. // ReportUnreachable reports the given node is not reachable for the last send.
  192. func (rn *RawNode) ReportUnreachable(id uint64) {
  193. _ = rn.raft.Step(pb.Message{Type: pb.MsgUnreachable, From: id})
  194. }
  195. // ReportSnapshot reports the status of the sent snapshot.
  196. func (rn *RawNode) ReportSnapshot(id uint64, status SnapshotStatus) {
  197. rej := status == SnapshotFailure
  198. _ = rn.raft.Step(pb.Message{Type: pb.MsgSnapStatus, From: id, Reject: rej})
  199. }
  200. // TransferLeader tries to transfer leadership to the given transferee.
  201. func (rn *RawNode) TransferLeader(transferee uint64) {
  202. _ = rn.raft.Step(pb.Message{Type: pb.MsgTransferLeader, From: transferee})
  203. }
  204. // ReadIndex requests a read state. The read state will be set in ready.
  205. // Read State has a read index. Once the application advances further than the read
  206. // index, any linearizable read requests issued before the read request can be
  207. // processed safely. The read state will have the same rctx attached.
  208. func (rn *RawNode) ReadIndex(rctx []byte) {
  209. _ = rn.raft.Step(pb.Message{Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: rctx}}})
  210. }