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