| 1 |
// Copyright 2020-2026 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"crypto/sha256" |
| 19 |
"encoding/binary" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"iter" |
| 23 |
"math" |
| 24 |
"math/rand" |
| 25 |
"os" |
| 26 |
"path/filepath" |
| 27 |
"runtime" |
| 28 |
"strings" |
| 29 |
"sync" |
| 30 |
"sync/atomic" |
| 31 |
"time" |
| 32 |
|
| 33 |
"github.com/antithesishq/antithesis-sdk-go/assert" |
| 34 |
"github.com/nats-io/nats-server/v2/internal/fastrand" |
| 35 |
|
| 36 |
"github.com/minio/highwayhash" |
| 37 |
) |
| 38 |
|
| 39 |
type RaftNode interface { |
| 40 |
Propose(term uint64, entry []byte) error |
| 41 |
ProposeMulti(term uint64, entries []*Entry) error |
| 42 |
ForwardProposal(entry []byte) error |
| 43 |
InstallSnapshot(snap []byte, force bool) error |
| 44 |
CreateSnapshotCheckpoint(force bool) (RaftNodeCheckpoint, error) |
| 45 |
SendSnapshot(snap []byte) error |
| 46 |
NeedSnapshot() bool |
| 47 |
Applied(index uint64) (entries uint64, bytes uint64) |
| 48 |
Processed(index uint64, applied uint64) (entries uint64, bytes uint64) |
| 49 |
State() RaftState |
| 50 |
Size() (entries, bytes uint64) |
| 51 |
Progress() (index, commit, applied uint64) |
| 52 |
Leader() bool |
| 53 |
LeaderSince() *time.Time |
| 54 |
Quorum() bool |
| 55 |
Current() bool |
| 56 |
Healthy() bool |
| 57 |
Term() uint64 |
| 58 |
Leaderless() bool |
| 59 |
GroupLeader() string |
| 60 |
HadPreviousLeader() bool |
| 61 |
StepDown(preferred ...string) error |
| 62 |
SetObserver(isObserver bool) |
| 63 |
IsObserver() bool |
| 64 |
Campaign() error |
| 65 |
CampaignImmediately() error |
| 66 |
ID() string |
| 67 |
Group() string |
| 68 |
Peers() []*Peer |
| 69 |
ProposeKnownPeers(knownPeers []string) |
| 70 |
UpdateKnownPeers(knownPeers []string) |
| 71 |
ProposeAddPeer(peer string) error |
| 72 |
ProposeRemovePeer(peer string) error |
| 73 |
MembershipChangeInProgress() bool |
| 74 |
AdjustClusterSize(csz int) error |
| 75 |
AdjustBootClusterSize(csz int) error |
| 76 |
ClusterSize() int |
| 77 |
ApplyQ() *ipQueue[*CommittedEntry] |
| 78 |
PauseApply() error |
| 79 |
ResumeApply() |
| 80 |
DrainAndReplaySnapshot() bool |
| 81 |
LeadChangeC() <-chan leadChange |
| 82 |
QuitC() <-chan struct{} |
| 83 |
Created() time.Time |
| 84 |
Stop() |
| 85 |
WaitForStop() |
| 86 |
Delete() |
| 87 |
IsDeleted() bool |
| 88 |
Reset() |
| 89 |
RecreateInternalSubs() error |
| 90 |
IsSystemAccount() bool |
| 91 |
GetTrafficAccountName() string |
| 92 |
GetWriteErr() error |
| 93 |
} |
| 94 |
|
| 95 |
// RaftNodeCheckpoint is used as an alternative to a direct InstallSnapshot. |
| 96 |
// A checkpoint is created from CreateSnapshotCheckpoint and allows installing snapshots asynchronously, |
| 97 |
// as well as loading the last snapshot or entries between the last snapshot and the one we're about to create. |
| 98 |
// Abort can be called to cancel the snapshot installation at any time, or InstallSnapshot to install it. |
| 99 |
type RaftNodeCheckpoint interface { |
| 100 |
LoadLastSnapshot() (snap []byte, err error) |
| 101 |
AppendEntriesSeq() iter.Seq2[*appendEntry, error] |
| 102 |
Abort() |
| 103 |
InstallSnapshot(data []byte) (uint64, error) |
| 104 |
} |
| 105 |
|
| 106 |
type WAL interface { |
| 107 |
Type() StorageType |
| 108 |
StoreMsg(subj string, hdr, msg []byte, ttl int64) (uint64, int64, error) |
| 109 |
LoadMsg(index uint64, sm *StoreMsg) (*StoreMsg, error) |
| 110 |
RemoveMsg(index uint64) (bool, error) |
| 111 |
Compact(index uint64) (uint64, error) |
| 112 |
Purge() (uint64, error) |
| 113 |
PurgeEx(subject string, seq, keep uint64) (uint64, error) |
| 114 |
Truncate(seq uint64) error |
| 115 |
State() StreamState |
| 116 |
FastState(*StreamState) |
| 117 |
Stop() error |
| 118 |
Delete(inline bool) error |
| 119 |
} |
| 120 |
|
| 121 |
type Peer struct { |
| 122 |
ID string |
| 123 |
Current bool |
| 124 |
Last time.Time |
| 125 |
Lag uint64 |
| 126 |
} |
| 127 |
|
| 128 |
type RaftState uint8 |
| 129 |
|
| 130 |
// Allowable states for a NATS Consensus Group. |
| 131 |
const ( |
| 132 |
Follower RaftState = iota |
| 133 |
Leader |
| 134 |
Candidate |
| 135 |
Closed |
| 136 |
) |
| 137 |
|
| 138 |
func (state RaftState) String() string { |
| 139 |
switch state { |
| 140 |
case Follower: |
| 141 |
return "FOLLOWER" |
| 142 |
case Candidate: |
| 143 |
return "CANDIDATE" |
| 144 |
case Leader: |
| 145 |
return "LEADER" |
| 146 |
case Closed: |
| 147 |
return "CLOSED" |
| 148 |
} |
| 149 |
return "UNKNOWN" |
| 150 |
} |
| 151 |
|
| 152 |
type raft struct { |
| 153 |
sync.RWMutex |
| 154 |
// Serializes writing snapshot files, since async snapshots are written with the Raft lock released. |
| 155 |
// MUST be acquired while already holding the Raft lock. But the Raft lock may then be released. |
| 156 |
snapLock sync.Mutex |
| 157 |
|
| 158 |
created time.Time // Time that the group was created |
| 159 |
accName string // Account name of the asset this raft group is for |
| 160 |
group string // Raft group |
| 161 |
sd string // Store directory |
| 162 |
id string // Node ID |
| 163 |
wg sync.WaitGroup // Wait for running goroutines to exit on shutdown |
| 164 |
|
| 165 |
dios *diskIOSemaphore |
| 166 |
wal WAL // WAL store (filestore or memstore) |
| 167 |
wtype StorageType // WAL type, e.g. FileStorage or MemoryStorage |
| 168 |
bytes uint64 // Total amount of bytes stored in the WAL. (Saves us from needing to call wal.FastState very often) |
| 169 |
werr error // Last write error |
| 170 |
|
| 171 |
state atomic.Int32 // RaftState |
| 172 |
leaderState atomic.Bool // Is in (complete) leader state. |
| 173 |
leaderSince atomic.Pointer[time.Time] // How long since becoming leader. |
| 174 |
hh *highwayhash.Digest64 // Highwayhash, used for snapshots |
| 175 |
snapfile string // Snapshot filename |
| 176 |
|
| 177 |
csz int // Cluster size |
| 178 |
qn int // Number of nodes needed to establish quorum |
| 179 |
peers map[string]*lps // Other peers in the Raft group |
| 180 |
|
| 181 |
removed map[string]time.Time // Peers that were removed from the group |
| 182 |
acks map[uint64]map[string]struct{} // Append entry responses/acks, map of entry index -> peer ID |
| 183 |
pae map[uint64]*appendEntry // Pending append entries |
| 184 |
paeBytes uint64 // Total byte size of the pending append entries in pae |
| 185 |
|
| 186 |
elect *time.Timer // Election timer, normally accessed via electTimer |
| 187 |
etlr time.Time // Election timer last reset time, for unit tests only |
| 188 |
active time.Time // Last activity time, i.e. for heartbeats |
| 189 |
llqrt time.Time // Last quorum lost time |
| 190 |
lsut time.Time // Last scale-up time |
| 191 |
|
| 192 |
term uint64 // The current vote term |
| 193 |
pterm uint64 // Previous term from the last snapshot |
| 194 |
pindex uint64 // Previous index from the last snapshot |
| 195 |
commit uint64 // Index of the most recent commit |
| 196 |
processed uint64 // Index of the most recently processed commit |
| 197 |
applied uint64 // Index of the most recently applied commit |
| 198 |
papplied uint64 // First sequence of our log, matches when we last installed a snapshot. |
| 199 |
|
| 200 |
membChange *membChange // Uncommitted membership change entry at a specific log index. |
| 201 |
|
| 202 |
aflr uint64 // Index when to signal initial messages have been applied after becoming leader. 0 means signaling is disabled. |
| 203 |
|
| 204 |
leader string // The ID of the leader |
| 205 |
vote string // Our current vote state |
| 206 |
|
| 207 |
s *Server // Reference to top-level server |
| 208 |
js *jetStream // JetStream, if running, to see if we are out of resources |
| 209 |
|
| 210 |
hasleader atomic.Bool // Is there a group leader right now? |
| 211 |
pleader atomic.Bool // Has the group ever had a leader? |
| 212 |
isSysAcc atomic.Bool // Are we utilizing the system account? |
| 213 |
|
| 214 |
extSt extensionState // Extension state |
| 215 |
|
| 216 |
track bool // Whether out of resources checking is enabled. |
| 217 |
dflag bool // Debug flag |
| 218 |
|
| 219 |
psubj string // Proposals subject |
| 220 |
rpsubj string // Remove peers subject |
| 221 |
vsubj string // Vote requests subject |
| 222 |
vreply string // Vote responses subject |
| 223 |
asubj string // Append entries subject |
| 224 |
areply string // Append entries responses subject |
| 225 |
|
| 226 |
t raftTransport // Transport that handles Raft messaging |
| 227 |
aesub *subscription // Subscription for handleAppendEntry callbacks |
| 228 |
|
| 229 |
wtv []byte // Term and vote to be written |
| 230 |
wps []byte // Peer state to be written |
| 231 |
|
| 232 |
catchup *catchupState // For when we need to catch up as a follower. |
| 233 |
progress map[string]*ipQueue[uint64] // For leader or server catching up a follower. |
| 234 |
|
| 235 |
hcommit uint64 // The commit at the time that applies were paused |
| 236 |
|
| 237 |
prop *ipQueue[*proposedEntry] // Proposals |
| 238 |
entry *ipQueue[*appendEntry] // Append entries |
| 239 |
resp *ipQueue[*appendEntryResponse] // Append entries responses |
| 240 |
apply *ipQueue[*CommittedEntry] // Apply queue (committed entries to be passed to upper layer) |
| 241 |
reqs *ipQueue[*voteRequest] // Vote requests |
| 242 |
votes *ipQueue[*voteResponse] // Vote responses |
| 243 |
leadc chan leadChange // Leader changes |
| 244 |
quit chan struct{} // Raft group shutdown |
| 245 |
|
| 246 |
lxfer bool // Are we doing a leadership transfer? |
| 247 |
hcbehind bool // Were we falling behind at the last health check? (see: isCurrent) |
| 248 |
maybeLeader bool // The group had a preferred leader. And is maybe already acting as leader prior to scale up. |
| 249 |
paused bool // Whether or not applies are paused |
| 250 |
observer bool // The node is observing, i.e. not able to become leader |
| 251 |
initializing bool // The node is new, and "empty log" checks can be temporarily relaxed. |
| 252 |
scaleUp bool // The node is part of a scale up, puts us in observer mode until the log contains data. |
| 253 |
deleted bool // If the node was deleted. |
| 254 |
snapshotting bool // Snapshot is in progress. |
| 255 |
quorumPaused bool // Pause replication and quorum participation to prevent log growth during slow applies. |
| 256 |
|
| 257 |
overrunCount uint64 // Counter of how many times we were overrun, either as follower or as leader. |
| 258 |
} |
| 259 |
|
| 260 |
type proposedEntry struct { |
| 261 |
*Entry |
| 262 |
reply string // Optional, to respond once proposal handled |
| 263 |
} |
| 264 |
|
| 265 |
// catchupState structure that holds our subscription, and catchup term and index |
| 266 |
// as well as starting term and index and how many updates we have seen. |
| 267 |
type catchupState struct { |
| 268 |
sub *subscription // Subscription that catchup messages will arrive on |
| 269 |
cterm uint64 // Catchup term |
| 270 |
cindex uint64 // Catchup index |
| 271 |
pterm uint64 // Starting term |
| 272 |
pindex uint64 // Starting index |
| 273 |
active time.Time // Last time we received a message for this catchup |
| 274 |
signal bool // Whether the EntryCatchup signal was sent. |
| 275 |
} |
| 276 |
|
| 277 |
// lps holds peer state of last time and last index replicated. |
| 278 |
type lps struct { |
| 279 |
ts time.Time // Last timestamp |
| 280 |
li uint64 // Last index replicated |
| 281 |
} |
| 282 |
|
| 283 |
type membChange struct { |
| 284 |
index uint64 // Which entry in the log is the membership change. |
| 285 |
peer string // The peer whose membership is being changed. |
| 286 |
prev *lps // The previous membership state if removing, unset if adding. |
| 287 |
} |
| 288 |
|
| 289 |
const ( |
| 290 |
minElectionTimeoutDefault = 4 * time.Second |
| 291 |
maxElectionTimeoutDefault = 9 * time.Second |
| 292 |
minCampaignTimeoutDefault = 100 * time.Millisecond |
| 293 |
maxCampaignTimeoutDefault = 8 * minCampaignTimeoutDefault |
| 294 |
hbIntervalDefault = 1 * time.Second |
| 295 |
lostQuorumIntervalDefault = hbIntervalDefault * 10 // 10 seconds |
| 296 |
lostQuorumCheckIntervalDefault = hbIntervalDefault * 10 // 10 seconds |
| 297 |
observerModeIntervalDefault = 48 * time.Hour |
| 298 |
peerRemoveTimeoutDefault = 5 * time.Minute |
| 299 |
) |
| 300 |
|
| 301 |
var ( |
| 302 |
minElectionTimeout = minElectionTimeoutDefault |
| 303 |
maxElectionTimeout = maxElectionTimeoutDefault |
| 304 |
minCampaignTimeout = minCampaignTimeoutDefault |
| 305 |
maxCampaignTimeout = maxCampaignTimeoutDefault |
| 306 |
hbInterval = hbIntervalDefault |
| 307 |
lostQuorumInterval = lostQuorumIntervalDefault |
| 308 |
lostQuorumCheck = lostQuorumCheckIntervalDefault |
| 309 |
observerModeInterval = observerModeIntervalDefault |
| 310 |
peerRemoveTimeout = peerRemoveTimeoutDefault |
| 311 |
) |
| 312 |
|
| 313 |
type RaftConfig struct { |
| 314 |
Name string |
| 315 |
Store string |
| 316 |
Log WAL |
| 317 |
Track bool |
| 318 |
Observer bool |
| 319 |
|
| 320 |
// Recovering must be set for a Raft group that's recovering after a restart, or if it's |
| 321 |
// first seen after a catchup from another server. If a server recovers with an empty log, |
| 322 |
// we know to protect against data loss. |
| 323 |
Recovering bool |
| 324 |
|
| 325 |
// ScaleUp identifies the Raft peer set is being scaled up. |
| 326 |
// We need to protect against losing state due to the new peers starting with an empty log. |
| 327 |
// Therefore, these empty servers can't try to become leader until they at least have _some_ state. |
| 328 |
ScaleUp bool |
| 329 |
|
| 330 |
// NewTransport creates the transport used for Raft node communication. |
| 331 |
// This is mainly for tests to inject a custom transport. |
| 332 |
// If nil, the default transport is used. |
| 333 |
NewTransport newTransportFunc |
| 334 |
} |
| 335 |
|
| 336 |
var ( |
| 337 |
errNotLeader = errors.New("raft: not leader") |
| 338 |
errAlreadyLeader = errors.New("raft: already leader") |
| 339 |
errNilCfg = errors.New("raft: no config given") |
| 340 |
errCorruptPeers = errors.New("raft: corrupt peer state") |
| 341 |
errEntryLoadFailed = errors.New("raft: could not load entry from WAL") |
| 342 |
errEntryStoreFailed = errors.New("raft: could not store entry to WAL") |
| 343 |
errNodeClosed = errors.New("raft: node is closed") |
| 344 |
errNodeRemoved = errors.New("raft: peer was removed") |
| 345 |
errBadSnapName = errors.New("raft: snapshot name could not be parsed") |
| 346 |
errNoSnapAvailable = errors.New("raft: no snapshot available") |
| 347 |
errSnapInProgress = errors.New("raft: snapshot is already in progress") |
| 348 |
errSnapAborted = errors.New("raft: snapshot was aborted") |
| 349 |
errCatchupsRunning = errors.New("raft: snapshot can not be installed while catchups running") |
| 350 |
errSnapshotCorrupt = errors.New("raft: snapshot corrupt") |
| 351 |
errTooManyPrefs = errors.New("raft: stepdown requires at most one preferred new leader") |
| 352 |
errNoPeerState = errors.New("raft: no peerstate") |
| 353 |
errAdjustBootCluster = errors.New("raft: can not adjust boot peer size on established group") |
| 354 |
errLeaderLen = fmt.Errorf("raft: leader should be exactly %d bytes", idLen) |
| 355 |
errTooManyEntries = errors.New("raft: append entry can contain a max of 64k entries") |
| 356 |
errBadAppendEntry = errors.New("raft: append entry corrupt") |
| 357 |
errNoInternalClient = errors.New("raft: no internal client") |
| 358 |
errMembershipChange = errors.New("raft: membership change in progress") |
| 359 |
errRemoveLastNode = errors.New("raft: cannot remove the last peer") |
| 360 |
errPeerNotFound = errors.New("raft: peer not found") |
| 361 |
) |
| 362 |
|
| 363 |
// This will bootstrap a raftNode by writing its config into the store directory. |
| 364 |
func (s *Server) bootstrapRaftNode(cfg *RaftConfig, knownPeers []string, allPeersKnown bool) error { |
| 365 |
if cfg == nil { |
| 366 |
return errNilCfg |
| 367 |
} |
| 368 |
// Check validity of peers if presented. |
| 369 |
for _, p := range knownPeers { |
| 370 |
if len(p) != idLen { |
| 371 |
return fmt.Errorf("raft: illegal peer: %q", p) |
| 372 |
} |
| 373 |
} |
| 374 |
expected := len(knownPeers) |
| 375 |
// We need to adjust this is all peers are not known. |
| 376 |
if !allPeersKnown { |
| 377 |
s.Debugf("Determining expected peer size for JetStream meta group") |
| 378 |
if expected < 2 { |
| 379 |
expected = 2 |
| 380 |
} |
| 381 |
opts := s.getOpts() |
| 382 |
nrs := len(opts.Routes) |
| 383 |
|
| 384 |
cn := s.ClusterName() |
| 385 |
ngwps := 0 |
| 386 |
for _, gw := range opts.Gateway.Gateways { |
| 387 |
// Ignore our own cluster if specified. |
| 388 |
if gw.Name == cn { |
| 389 |
continue |
| 390 |
} |
| 391 |
// Each configured gateway URL represents one remote endpoint, so |
| 392 |
// count it as a single peer. We must not resolve the host and add |
| 393 |
// one per returned address: a hostname on a dual-stack host (e.g. |
| 394 |
// "localhost" -> 127.0.0.1 + ::1) would then count the same server |
| 395 |
// multiple times, inflating the expected meta-group size above the |
| 396 |
// real node count and preventing meta leader election. |
| 397 |
ngwps += len(gw.URLs) |
| 398 |
} |
| 399 |
|
| 400 |
if expected < nrs+ngwps { |
| 401 |
expected = nrs + ngwps |
| 402 |
s.Debugf("Adjusting expected peer set size to %d with %d known", expected, len(knownPeers)) |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
// Check the store directory. If we have a memory based WAL we need to make sure the directory is setup. |
| 407 |
if stat, err := os.Stat(cfg.Store); os.IsNotExist(err) { |
| 408 |
if err := os.MkdirAll(cfg.Store, defaultDirPerms); err != nil { |
| 409 |
return fmt.Errorf("raft: could not create storage directory - %v", err) |
| 410 |
} |
| 411 |
} else if stat == nil || !stat.IsDir() { |
| 412 |
return fmt.Errorf("raft: storage directory is not a directory") |
| 413 |
} |
| 414 |
tmpfile, err := os.CreateTemp(cfg.Store, "_test_") |
| 415 |
if err != nil { |
| 416 |
return fmt.Errorf("raft: storage directory is not writable") |
| 417 |
} |
| 418 |
tmpfile.Close() |
| 419 |
os.Remove(tmpfile.Name()) |
| 420 |
|
| 421 |
return writePeerState(s.diskIOSemaphore(), cfg.Store, &peerState{knownPeers, expected, extUndetermined}) |
| 422 |
} |
| 423 |
|
| 424 |
// initRaftNode will initialize the raft node, to be used by startRaftNode or when testing to not run the Go routine. |
| 425 |
func (s *Server) initRaftNode(accName string, cfg *RaftConfig, labels pprofLabels) (*raft, error) { |
| 426 |
restorePeerState := func(n *raft) error { |
| 427 |
ps, err := readPeerState(s.diskIOSemaphore(), cfg.Store) |
| 428 |
if err != nil { |
| 429 |
return err |
| 430 |
} |
| 431 |
if ps == nil { |
| 432 |
return errNoPeerState |
| 433 |
} |
| 434 |
n.processPeerState(ps) |
| 435 |
n.extSt = ps.domainExt |
| 436 |
return nil |
| 437 |
} |
| 438 |
|
| 439 |
if cfg == nil { |
| 440 |
return nil, errNilCfg |
| 441 |
} |
| 442 |
s.mu.RLock() |
| 443 |
if s.sys == nil { |
| 444 |
s.mu.RUnlock() |
| 445 |
return nil, ErrNoSysAccount |
| 446 |
} |
| 447 |
hash := s.sys.shash |
| 448 |
s.mu.RUnlock() |
| 449 |
|
| 450 |
qpfx := fmt.Sprintf("[ACC:%s] RAFT '%s' ", accName, cfg.Name) |
| 451 |
n := &raft{ |
| 452 |
created: time.Now(), |
| 453 |
id: hash[:idLen], |
| 454 |
group: cfg.Name, |
| 455 |
sd: cfg.Store, |
| 456 |
wal: cfg.Log, |
| 457 |
wtype: cfg.Log.Type(), |
| 458 |
dios: s.diskIOSemaphore(), |
| 459 |
track: cfg.Track, |
| 460 |
peers: make(map[string]*lps), |
| 461 |
acks: make(map[uint64]map[string]struct{}), |
| 462 |
pae: make(map[uint64]*appendEntry), |
| 463 |
s: s, |
| 464 |
js: s.getJetStream(), |
| 465 |
quit: make(chan struct{}), |
| 466 |
reqs: newIPQueue[*voteRequest](s, qpfx+"vreq"), |
| 467 |
votes: newIPQueue[*voteResponse](s, qpfx+"vresp"), |
| 468 |
prop: newIPQueue[*proposedEntry](s, qpfx+"entry"), |
| 469 |
entry: newIPQueue[*appendEntry](s, qpfx+"appendEntry"), |
| 470 |
resp: newIPQueue[*appendEntryResponse](s, qpfx+"appendEntryResponse"), |
| 471 |
apply: newIPQueue[*CommittedEntry](s, qpfx+"committedEntry"), |
| 472 |
accName: accName, |
| 473 |
leadc: make(chan leadChange, 1), |
| 474 |
observer: cfg.Observer, |
| 475 |
} |
| 476 |
|
| 477 |
if cfg.NewTransport != nil { |
| 478 |
n.t = cfg.NewTransport(s, n) |
| 479 |
} else { |
| 480 |
n.t = defaultRaftTransport(s, n) |
| 481 |
} |
| 482 |
|
| 483 |
// Setup our internal subscriptions for proposals, votes and append entries. |
| 484 |
// If we fail to do this for some reason then this is fatal — we cannot |
| 485 |
// continue setting up or the Raft node may be partially/totally isolated. |
| 486 |
if err := n.RecreateInternalSubs(); err != nil { |
| 487 |
n.shutdown() |
| 488 |
return nil, err |
| 489 |
} |
| 490 |
|
| 491 |
if atomic.LoadInt32(&s.logging.debug) > 0 { |
| 492 |
n.dflag = true |
| 493 |
} |
| 494 |
|
| 495 |
// Set up the highwayhash for the snapshots. |
| 496 |
key := sha256.Sum256([]byte(n.group)) |
| 497 |
n.hh, _ = highwayhash.NewDigest64(key[:]) |
| 498 |
|
| 499 |
// If we have a term and vote file (tav.idx on the filesystem) then read in |
| 500 |
// what we think the term and vote was. It's possible these are out of date |
| 501 |
// so a catch-up may be required. |
| 502 |
if term, vote, err := n.readTermVote(); err == nil && term > 0 { |
| 503 |
n.term = term |
| 504 |
n.vote = vote |
| 505 |
} |
| 506 |
|
| 507 |
// Can't recover snapshots if memory based since wal will be reset. |
| 508 |
// We will inherit from the current leader. |
| 509 |
n.papplied = 0 |
| 510 |
if _, ok := n.wal.(*memStore); ok { |
| 511 |
_ = os.RemoveAll(filepath.Join(n.sd, snapshotsDir)) |
| 512 |
} else if err := n.setupLastSnapshot(); err != nil && err != errNoSnapAvailable { |
| 513 |
// If we failed to recover from the snapshot, then we should surface |
| 514 |
// the error upwards, otherwise we can complete recovery but have only |
| 515 |
// a partial view of the world. |
| 516 |
n.shutdown() |
| 517 |
return nil, err |
| 518 |
} |
| 519 |
|
| 520 |
// We may have restored the peer state from the |
| 521 |
// snapshot above. If not, we restore peers from |
| 522 |
// the peer state file. |
| 523 |
if len(n.peers) == 0 { |
| 524 |
if err := restorePeerState(n); err != nil { |
| 525 |
return nil, err |
| 526 |
} |
| 527 |
} |
| 528 |
|
| 529 |
// Make sure that the snapshots directory exists. |
| 530 |
if err := os.MkdirAll(filepath.Join(n.sd, snapshotsDir), defaultDirPerms); err != nil { |
| 531 |
n.shutdown() |
| 532 |
return nil, fmt.Errorf("could not create snapshots directory - %v", err) |
| 533 |
} |
| 534 |
|
| 535 |
truncateAndErr := func(index uint64) { |
| 536 |
if err := n.wal.Truncate(index); err != nil { |
| 537 |
n.setWriteErr(err) |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
// Retrieve the stream state from the WAL. If there are pending append |
| 542 |
// entries that were committed but not applied before we last shut down, |
| 543 |
// we will try to replay them and process them here. |
| 544 |
var state StreamState |
| 545 |
n.wal.FastState(&state) |
| 546 |
n.bytes = state.Bytes |
| 547 |
|
| 548 |
if state.Msgs > 0 { |
| 549 |
n.debug("Replaying state of %d entries", state.Msgs) |
| 550 |
|
| 551 |
// This process will queue up entries on our applied queue but prior to the upper |
| 552 |
// state machine running. So we will monitor how much we have queued and if we |
| 553 |
// reach a limit will pause the apply queue and resume inside of run() go routine. |
| 554 |
const maxQsz = 32 * 1024 * 1024 // 32MB max |
| 555 |
|
| 556 |
// It looks like there are entries we have committed but not applied |
| 557 |
// yet. Replay them. |
| 558 |
for index, qsz := state.FirstSeq, 0; index <= state.LastSeq; index++ { |
| 559 |
ae, err := n.loadEntry(index) |
| 560 |
// The first entry in our WAL initializes state but must align with our snapshot if we had one. |
| 561 |
// Importantly, check this first, as we might need to truncate the WAL further than the index. |
| 562 |
if index == state.FirstSeq { |
| 563 |
// If the entry is missing, corrupt, or doesn't align with the snapshot, truncate the WAL. |
| 564 |
if err != nil || ae == nil || ae.pindex != index-1 || n.pindex != ae.pindex { |
| 565 |
if err != nil { |
| 566 |
n.warn("Could not load %d from WAL [%+v]: %v", index, state, err) |
| 567 |
} else { |
| 568 |
n.warn("Misaligned WAL, will truncate") |
| 569 |
} |
| 570 |
// Truncate to the snapshot or beginning if there is none. |
| 571 |
truncateAndErr(n.pindex) |
| 572 |
break |
| 573 |
} |
| 574 |
n.pterm, n.pindex = ae.pterm, ae.pindex |
| 575 |
if ae.commit > 0 && ae.commit > n.commit { |
| 576 |
n.commit = ae.commit |
| 577 |
} |
| 578 |
} |
| 579 |
if err != nil { |
| 580 |
n.warn("Could not load %d from WAL [%+v]: %v", index, state, err) |
| 581 |
// Truncate to the previous correct entry. |
| 582 |
truncateAndErr(index - 1) |
| 583 |
break |
| 584 |
} |
| 585 |
if ae.pindex != index-1 { |
| 586 |
n.warn("Corrupt WAL, will truncate") |
| 587 |
// Truncate to the previous correct entry. |
| 588 |
truncateAndErr(index - 1) |
| 589 |
break |
| 590 |
} |
| 591 |
n.processAppendEntry(ae, nil) |
| 592 |
// Check how much we have queued up so far to determine if we should pause. |
| 593 |
for _, e := range ae.entries { |
| 594 |
qsz += len(e.Data) |
| 595 |
if qsz > maxQsz && !n.paused { |
| 596 |
n.PauseApply() |
| 597 |
} |
| 598 |
} |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
n.debug("Started (cluster size %d, quorum %d)", n.csz, n.qn) |
| 603 |
|
| 604 |
// Check if we need to start in observer mode due to lame duck status. |
| 605 |
// This will stop us from taking on the leader role when we're about to |
| 606 |
// shutdown anyway. |
| 607 |
if s.isLameDuckMode() { |
| 608 |
n.debug("Will start in observer mode due to lame duck status") |
| 609 |
n.SetObserver(true) |
| 610 |
} |
| 611 |
|
| 612 |
// Set the election timer and lost quorum timers to now, so that we |
| 613 |
// won't accidentally trigger either state without knowing the real state |
| 614 |
// of the other nodes. |
| 615 |
n.Lock() |
| 616 |
n.resetElectionTimeout() |
| 617 |
n.llqrt = time.Now() |
| 618 |
|
| 619 |
// If our log is empty, and we're initializing, relax the "empty log" checks temporarily. |
| 620 |
if !cfg.Recovering && n.pindex == 0 { |
| 621 |
n.initializing = true |
| 622 |
// If we're scaling up and our log is empty, must put ourselves into observer |
| 623 |
// and wait for data from the leader. |
| 624 |
if !cfg.Observer && cfg.ScaleUp { |
| 625 |
n.scaleUp = true |
| 626 |
n.setObserverLocked(true, extUndetermined) |
| 627 |
} |
| 628 |
} |
| 629 |
n.Unlock() |
| 630 |
|
| 631 |
// Register the Raft group. |
| 632 |
labels["group"] = n.group |
| 633 |
s.registerRaftNode(n.group, n) |
| 634 |
|
| 635 |
return n, nil |
| 636 |
} |
| 637 |
|
| 638 |
// startRaftNode will start the raft node. |
| 639 |
func (s *Server) startRaftNode(accName string, cfg *RaftConfig, labels pprofLabels) (RaftNode, error) { |
| 640 |
n, err := s.initRaftNode(accName, cfg, labels) |
| 641 |
if err != nil { |
| 642 |
return nil, err |
| 643 |
} |
| 644 |
|
| 645 |
// Start the run goroutine for the Raft state machine. |
| 646 |
n.wg.Add(1) |
| 647 |
s.startGoRoutine(n.run, labels) |
| 648 |
|
| 649 |
return n, nil |
| 650 |
} |
| 651 |
|
| 652 |
// Returns whether peers within this group claim to support |
| 653 |
// moving NRG traffic into the asset account. |
| 654 |
// Lock must be held. |
| 655 |
func (n *raft) checkAccountNRGStatus() bool { |
| 656 |
if !n.s.accountNRGAllowed.Load() { |
| 657 |
return false |
| 658 |
} |
| 659 |
enabled := true |
| 660 |
for pn := range n.peers { |
| 661 |
if si, ok := n.s.nodeToInfo.Load(pn); ok && si != nil { |
| 662 |
enabled = enabled && si.(nodeInfo).accountNRG |
| 663 |
} |
| 664 |
} |
| 665 |
return enabled |
| 666 |
} |
| 667 |
|
| 668 |
// Whether we are using the system account or not. |
| 669 |
func (n *raft) IsSystemAccount() bool { |
| 670 |
return n.isSysAcc.Load() |
| 671 |
} |
| 672 |
|
| 673 |
// GetTrafficAccountName returns the account name of the account used for replication traffic. |
| 674 |
func (n *raft) GetTrafficAccountName() string { |
| 675 |
n.RLock() |
| 676 |
defer n.RUnlock() |
| 677 |
if n.t == nil { |
| 678 |
return (*Account)(nil).GetName() |
| 679 |
} |
| 680 |
return n.t.Account().GetName() |
| 681 |
} |
| 682 |
|
| 683 |
func (n *raft) RecreateInternalSubs() error { |
| 684 |
n.Lock() |
| 685 |
defer n.Unlock() |
| 686 |
return n.recreateInternalSubsLocked() |
| 687 |
} |
| 688 |
|
| 689 |
func (n *raft) recreateInternalSubsLocked() error { |
| 690 |
// Sanity check for system account, as it can disappear when |
| 691 |
// the system is shutting down. |
| 692 |
if n.s == nil { |
| 693 |
return fmt.Errorf("server not found") |
| 694 |
} |
| 695 |
n.s.mu.RLock() |
| 696 |
sys := n.s.sys |
| 697 |
n.s.mu.RUnlock() |
| 698 |
if sys == nil { |
| 699 |
return fmt.Errorf("system account not found") |
| 700 |
} |
| 701 |
|
| 702 |
// Default is the system account. |
| 703 |
nrgAcc := sys.account |
| 704 |
n.isSysAcc.Store(true) |
| 705 |
|
| 706 |
// Is account NRG enabled in this account and do all group |
| 707 |
// peers claim to also support account NRG? |
| 708 |
if n.checkAccountNRGStatus() { |
| 709 |
// Check whether the account that the asset belongs to |
| 710 |
// has volunteered a different NRG account. |
| 711 |
target := nrgAcc.Name |
| 712 |
if a, _ := n.s.lookupAccount(n.accName); a != nil { |
| 713 |
a.mu.RLock() |
| 714 |
if a.js != nil { |
| 715 |
target = a.nrgAccount |
| 716 |
} |
| 717 |
a.mu.RUnlock() |
| 718 |
} |
| 719 |
|
| 720 |
// If the target account exists, then we'll use that. |
| 721 |
if target != _EMPTY_ { |
| 722 |
if a, _ := n.s.lookupAccount(target); a != nil { |
| 723 |
nrgAcc = a |
| 724 |
if a != sys.account { |
| 725 |
n.isSysAcc.Store(false) |
| 726 |
} |
| 727 |
} |
| 728 |
} |
| 729 |
} |
| 730 |
if n.aesub != nil && n.t.Account() == nrgAcc { |
| 731 |
// Subscriptions already exist and the account NRG state |
| 732 |
// hasn't changed. |
| 733 |
return nil |
| 734 |
} |
| 735 |
|
| 736 |
// Need to cancel any in-progress catch-ups, otherwise the |
| 737 |
// inboxes are about to be pulled out from underneath it in |
| 738 |
// the next step... |
| 739 |
n.cancelCatchup() |
| 740 |
|
| 741 |
if n.t.Account() != nrgAcc { |
| 742 |
n.debug("Subscribing in '%s'", nrgAcc.GetName()) |
| 743 |
} |
| 744 |
|
| 745 |
n.t.Reset(nrgAcc) |
| 746 |
|
| 747 |
// Recreate any internal subscriptions for voting, append |
| 748 |
// entries etc in the new account. |
| 749 |
return n.createInternalSubs() |
| 750 |
} |
| 751 |
|
| 752 |
// outOfResources checks to see if we are out of resources. |
| 753 |
func (n *raft) outOfResources() bool { |
| 754 |
js := n.js |
| 755 |
if !n.track || js == nil { |
| 756 |
return false |
| 757 |
} |
| 758 |
return js.limitsExceeded(n.wtype) |
| 759 |
} |
| 760 |
|
| 761 |
// Maps node names back to server names. |
| 762 |
func (s *Server) serverNameForNode(node string) string { |
| 763 |
if si, ok := s.nodeToInfo.Load(node); ok && si != nil { |
| 764 |
return si.(nodeInfo).name |
| 765 |
} |
| 766 |
return _EMPTY_ |
| 767 |
} |
| 768 |
|
| 769 |
// Maps node names back to cluster names. |
| 770 |
func (s *Server) clusterNameForNode(node string) string { |
| 771 |
if si, ok := s.nodeToInfo.Load(node); ok && si != nil { |
| 772 |
return si.(nodeInfo).cluster |
| 773 |
} |
| 774 |
return _EMPTY_ |
| 775 |
} |
| 776 |
|
| 777 |
// Registers the Raft node with the server, as it will track all of the Raft |
| 778 |
// nodes. |
| 779 |
func (s *Server) registerRaftNode(group string, n RaftNode) { |
| 780 |
s.rnMu.Lock() |
| 781 |
defer s.rnMu.Unlock() |
| 782 |
if s.raftNodes == nil { |
| 783 |
s.raftNodes = make(map[string]RaftNode) |
| 784 |
} |
| 785 |
s.raftNodes[group] = n |
| 786 |
} |
| 787 |
|
| 788 |
// Unregisters the Raft node from the server, i.e. at shutdown. |
| 789 |
func (s *Server) unregisterRaftNode(group string) { |
| 790 |
s.rnMu.Lock() |
| 791 |
defer s.rnMu.Unlock() |
| 792 |
if s.raftNodes != nil { |
| 793 |
delete(s.raftNodes, group) |
| 794 |
} |
| 795 |
} |
| 796 |
|
| 797 |
// Returns how many Raft nodes are running in this server instance. |
| 798 |
func (s *Server) numRaftNodes() int { |
| 799 |
s.rnMu.RLock() |
| 800 |
defer s.rnMu.RUnlock() |
| 801 |
return len(s.raftNodes) |
| 802 |
} |
| 803 |
|
| 804 |
// Finds the Raft node for a given Raft group, if any. If there is no Raft node |
| 805 |
// running for this group then it can return nil. |
| 806 |
func (s *Server) lookupRaftNode(group string) RaftNode { |
| 807 |
s.rnMu.RLock() |
| 808 |
defer s.rnMu.RUnlock() |
| 809 |
var n RaftNode |
| 810 |
if s.raftNodes != nil { |
| 811 |
n = s.raftNodes[group] |
| 812 |
} |
| 813 |
return n |
| 814 |
} |
| 815 |
|
| 816 |
// Reloads the debug state for all running Raft nodes. This is necessary when |
| 817 |
// the configuration has been reloaded and the debug log level has changed. |
| 818 |
func (s *Server) reloadDebugRaftNodes(debug bool) { |
| 819 |
if s == nil { |
| 820 |
return |
| 821 |
} |
| 822 |
s.rnMu.RLock() |
| 823 |
for _, ni := range s.raftNodes { |
| 824 |
n := ni.(*raft) |
| 825 |
n.Lock() |
| 826 |
n.dflag = debug |
| 827 |
n.Unlock() |
| 828 |
} |
| 829 |
s.rnMu.RUnlock() |
| 830 |
} |
| 831 |
|
| 832 |
// Requests that all Raft nodes on this server step down and place them into |
| 833 |
// observer mode. This is called when the server is shutting down. |
| 834 |
func (s *Server) stepdownRaftNodes() { |
| 835 |
if s == nil { |
| 836 |
return |
| 837 |
} |
| 838 |
s.rnMu.RLock() |
| 839 |
if len(s.raftNodes) == 0 { |
| 840 |
s.rnMu.RUnlock() |
| 841 |
return |
| 842 |
} |
| 843 |
s.Debugf("Stepping down all leader raft nodes") |
| 844 |
nodes := make([]RaftNode, 0, len(s.raftNodes)) |
| 845 |
for _, n := range s.raftNodes { |
| 846 |
nodes = append(nodes, n) |
| 847 |
} |
| 848 |
s.rnMu.RUnlock() |
| 849 |
|
| 850 |
for _, node := range nodes { |
| 851 |
node.StepDown() |
| 852 |
node.SetObserver(true) |
| 853 |
} |
| 854 |
} |
| 855 |
|
| 856 |
// Shuts down all Raft nodes on this server. This is called either when the |
| 857 |
// server is either entering lame duck mode, shutting down or when JetStream |
| 858 |
// has been disabled. |
| 859 |
func (s *Server) shutdownRaftNodes() { |
| 860 |
if s == nil { |
| 861 |
return |
| 862 |
} |
| 863 |
s.rnMu.RLock() |
| 864 |
if len(s.raftNodes) == 0 { |
| 865 |
s.rnMu.RUnlock() |
| 866 |
return |
| 867 |
} |
| 868 |
nodes := make([]RaftNode, 0, len(s.raftNodes)) |
| 869 |
s.Debugf("Shutting down all raft nodes") |
| 870 |
for _, n := range s.raftNodes { |
| 871 |
nodes = append(nodes, n) |
| 872 |
} |
| 873 |
s.rnMu.RUnlock() |
| 874 |
|
| 875 |
for _, node := range nodes { |
| 876 |
node.Stop() |
| 877 |
} |
| 878 |
} |
| 879 |
|
| 880 |
// Used in lameduck mode to move off the leaders. |
| 881 |
// We also put all nodes in observer mode so new leaders |
| 882 |
// can not be placed on this server. |
| 883 |
func (s *Server) transferRaftLeaders() bool { |
| 884 |
if s == nil { |
| 885 |
return false |
| 886 |
} |
| 887 |
s.rnMu.RLock() |
| 888 |
if len(s.raftNodes) == 0 { |
| 889 |
s.rnMu.RUnlock() |
| 890 |
return false |
| 891 |
} |
| 892 |
nodes := make([]RaftNode, 0, len(s.raftNodes)) |
| 893 |
for _, n := range s.raftNodes { |
| 894 |
nodes = append(nodes, n) |
| 895 |
} |
| 896 |
s.rnMu.RUnlock() |
| 897 |
|
| 898 |
var didTransfer bool |
| 899 |
for _, node := range nodes { |
| 900 |
if err := node.StepDown(); err == nil { |
| 901 |
didTransfer = true |
| 902 |
} |
| 903 |
node.SetObserver(true) |
| 904 |
} |
| 905 |
return didTransfer |
| 906 |
} |
| 907 |
|
| 908 |
// Formal API |
| 909 |
|
| 910 |
// Propose will propose a new entry to the group. |
| 911 |
// This should only be called on the leader. |
| 912 |
func (n *raft) Propose(term uint64, data []byte) error { |
| 913 |
n.Lock() |
| 914 |
defer n.Unlock() |
| 915 |
return n.proposeLocked(term, data) |
| 916 |
} |
| 917 |
|
| 918 |
func (n *raft) proposeLocked(term uint64, data []byte) error { |
| 919 |
// Check state under lock, we might not be leader anymore. |
| 920 |
if state := n.State(); state != Leader || term != n.term { |
| 921 |
n.debug("Proposal ignored, not leader (state: %v, cterm: %d, term: %d)", state, term, n.term) |
| 922 |
return errNotLeader |
| 923 |
} |
| 924 |
|
| 925 |
// Error if we had a previous write error. |
| 926 |
if werr := n.werr; werr != nil { |
| 927 |
return werr |
| 928 |
} |
| 929 |
|
| 930 |
if n.isLeaderOverrun() { |
| 931 |
var state StreamState |
| 932 |
n.wal.FastState(&state) |
| 933 |
n.warn("Leader falling behind, stepping down: pindex %d, commit %d, applied %d, WAL size %s", n.pindex, n.commit, n.applied, friendlyBytes(state.Bytes)) |
| 934 |
// Stepdown without leader transfer, likely all replicas will be overrun, and we need time to recover. |
| 935 |
n.stepdownLocked(noLeader) |
| 936 |
n.overrunCount++ |
| 937 |
return errNotLeader |
| 938 |
} |
| 939 |
n.prop.push(newProposedEntry(newEntry(EntryNormal, data), _EMPTY_)) |
| 940 |
return nil |
| 941 |
} |
| 942 |
|
| 943 |
// ProposeMulti will propose multiple entries at once. |
| 944 |
// This should only be called on the leader. |
| 945 |
func (n *raft) ProposeMulti(term uint64, entries []*Entry) error { |
| 946 |
n.Lock() |
| 947 |
defer n.Unlock() |
| 948 |
// Check state under lock, we might not be leader anymore. |
| 949 |
if state := n.State(); state != Leader || term != n.term { |
| 950 |
n.debug("Multi proposal ignored, not leader (state: %v, cterm: %d, term: %d)", state, term, n.term) |
| 951 |
return errNotLeader |
| 952 |
} |
| 953 |
|
| 954 |
// Error if we had a previous write error. |
| 955 |
if werr := n.werr; werr != nil { |
| 956 |
return werr |
| 957 |
} |
| 958 |
|
| 959 |
if n.isLeaderOverrun() { |
| 960 |
var state StreamState |
| 961 |
n.wal.FastState(&state) |
| 962 |
n.warn("Leader falling behind, stepping down: pindex %d, commit %d, applied %d, WAL size %s", n.pindex, n.commit, n.applied, friendlyBytes(state.Bytes)) |
| 963 |
// Stepdown without leader transfer, likely all replicas will be overrun, and we need time to recover. |
| 964 |
n.stepdownLocked(noLeader) |
| 965 |
n.overrunCount++ |
| 966 |
return errNotLeader |
| 967 |
} |
| 968 |
for _, e := range entries { |
| 969 |
n.prop.push(newProposedEntry(e, _EMPTY_)) |
| 970 |
} |
| 971 |
return nil |
| 972 |
} |
| 973 |
|
| 974 |
// isLeaderOverrun returns whether we are overrun and should step down due to continuously increasing |
| 975 |
// uncommitted or unapplied entries. If triggered, this means we're being severely overrun by |
| 976 |
// incoming proposals or the system is degraded such that it's too slow (or unable) to process them. |
| 977 |
// Stepping down means the system gets to "breathe" for a bit, until a new leader can be elected. |
| 978 |
// Lock should be held. |
| 979 |
func (n *raft) isLeaderOverrun() bool { |
| 980 |
applied := max(n.applied, n.papplied) |
| 981 |
commit := max(n.commit, n.papplied) |
| 982 |
// We only do this past a high threshold to protect ourselves. |
| 983 |
// Worst-case we'll have 2x the threshold, once in uncommitted and once in unapplied entries. |
| 984 |
// Either the number of uncommitted entries is over the threshold: we're not getting quorum from our followers. |
| 985 |
uncommittedThreshold := n.pindex > commit && n.overrun(n.pindex-commit, pauseQuorumThreshold, pauseQuorumBytes) |
| 986 |
// Or, the number of in-memory committed but not yet applied entries is over the threshold: we're slow to apply. |
| 987 |
unappliedThreshold := commit > applied && n.overrun(commit-applied, pauseQuorumThreshold, pauseQuorumBytes) |
| 988 |
return uncommittedThreshold || unappliedThreshold |
| 989 |
} |
| 990 |
|
| 991 |
// entryBytes estimates the byte size of the given number of entries, based on the |
| 992 |
// average size of the entries we are currently holding in our WAL. |
| 993 |
// Lock should be held. |
| 994 |
func (n *raft) entryBytes(entries uint64) uint64 { |
| 995 |
msgs := n.pindex - n.papplied |
| 996 |
if msgs == 0 || n.bytes == 0 { |
| 997 |
return 0 |
| 998 |
} |
| 999 |
return entries * n.bytes / msgs |
| 1000 |
} |
| 1001 |
|
| 1002 |
// overrun returns whether the given number of entries is over either the entry count |
| 1003 |
// threshold or the estimated byte threshold. |
| 1004 |
// Lock should be held. |
| 1005 |
func (n *raft) overrun(entries, maxEntries, maxBytes uint64) bool { |
| 1006 |
return entries > maxEntries || n.entryBytes(entries) > maxBytes |
| 1007 |
} |
| 1008 |
|
| 1009 |
// ForwardProposal will forward the proposal to the leader if known. |
| 1010 |
// If we are the leader this is the same as calling propose. |
| 1011 |
func (n *raft) ForwardProposal(entry []byte) error { |
| 1012 |
if n.State() == Leader { |
| 1013 |
n.Lock() |
| 1014 |
defer n.Unlock() |
| 1015 |
// We pass the node's term so the proposal goes through. This is unavoidable with forwarded |
| 1016 |
// proposals, normally the passed term MUST be that of the process triggering the proposals. |
| 1017 |
// So a stale process that is still running isn't allowed to make new proposals past its term. |
| 1018 |
return n.proposeLocked(n.term, entry) |
| 1019 |
} |
| 1020 |
|
| 1021 |
// TODO: Currently we do not set a reply subject, even though we are |
| 1022 |
// now capable of responding. Do this once enough time has passed, |
| 1023 |
// i.e. maybe in 2.12. |
| 1024 |
n.sendRPC(n.psubj, _EMPTY_, entry) |
| 1025 |
return nil |
| 1026 |
} |
| 1027 |
|
| 1028 |
// ProposeAddPeer is called to add a peer to the group. |
| 1029 |
func (n *raft) ProposeAddPeer(peer string) error { |
| 1030 |
n.RLock() |
| 1031 |
// Check state under lock, we might not be leader anymore. |
| 1032 |
if n.State() != Leader { |
| 1033 |
n.RUnlock() |
| 1034 |
return errNotLeader |
| 1035 |
} |
| 1036 |
// Error if we had a previous write error. |
| 1037 |
if werr := n.werr; werr != nil { |
| 1038 |
n.RUnlock() |
| 1039 |
return werr |
| 1040 |
} |
| 1041 |
if n.membChange != nil { |
| 1042 |
n.RUnlock() |
| 1043 |
return errMembershipChange |
| 1044 |
} |
| 1045 |
prop := n.prop |
| 1046 |
n.RUnlock() |
| 1047 |
|
| 1048 |
prop.push(newProposedEntry(newEntry(EntryAddPeer, []byte(peer)), _EMPTY_)) |
| 1049 |
return nil |
| 1050 |
} |
| 1051 |
|
| 1052 |
// ProposeRemovePeer is called to remove a peer from the group. |
| 1053 |
func (n *raft) ProposeRemovePeer(peer string) error { |
| 1054 |
n.RLock() |
| 1055 |
|
| 1056 |
// Error if we had a previous write error. |
| 1057 |
if werr := n.werr; werr != nil { |
| 1058 |
n.RUnlock() |
| 1059 |
return werr |
| 1060 |
} |
| 1061 |
|
| 1062 |
if n.State() != Leader { |
| 1063 |
subj := n.rpsubj |
| 1064 |
n.RUnlock() |
| 1065 |
|
| 1066 |
// Forward the proposal to the leader |
| 1067 |
n.sendRPC(subj, _EMPTY_, []byte(peer)) |
| 1068 |
return nil |
| 1069 |
} |
| 1070 |
|
| 1071 |
if n.membChange != nil { |
| 1072 |
n.RUnlock() |
| 1073 |
return errMembershipChange |
| 1074 |
} |
| 1075 |
if _, ok := n.peers[peer]; !ok { |
| 1076 |
n.RUnlock() |
| 1077 |
return errPeerNotFound |
| 1078 |
} |
| 1079 |
if len(n.peers) <= 1 { |
| 1080 |
n.RUnlock() |
| 1081 |
return errRemoveLastNode |
| 1082 |
} |
| 1083 |
|
| 1084 |
prop := n.prop |
| 1085 |
n.RUnlock() |
| 1086 |
|
| 1087 |
prop.push(newProposedEntry(newEntry(EntryRemovePeer, []byte(peer)), _EMPTY_)) |
| 1088 |
return nil |
| 1089 |
} |
| 1090 |
|
| 1091 |
func (n *raft) MembershipChangeInProgress() bool { |
| 1092 |
n.RLock() |
| 1093 |
defer n.RUnlock() |
| 1094 |
return n.membChange != nil |
| 1095 |
} |
| 1096 |
|
| 1097 |
// ClusterSize reports back the total cluster size. |
| 1098 |
// This effects quorum etc. |
| 1099 |
func (n *raft) ClusterSize() int { |
| 1100 |
n.Lock() |
| 1101 |
defer n.Unlock() |
| 1102 |
return n.csz |
| 1103 |
} |
| 1104 |
|
| 1105 |
// AdjustBootClusterSize can be called to adjust the boot cluster size. |
| 1106 |
// Will error if called on a group with a leader or a previous leader. |
| 1107 |
// This can be helpful in mixed mode. |
| 1108 |
func (n *raft) AdjustBootClusterSize(csz int) error { |
| 1109 |
n.Lock() |
| 1110 |
defer n.Unlock() |
| 1111 |
|
| 1112 |
if n.leader != noLeader || n.pleader.Load() { |
| 1113 |
return errAdjustBootCluster |
| 1114 |
} |
| 1115 |
// Same floor as bootstrap. |
| 1116 |
if csz < 2 { |
| 1117 |
csz = 2 |
| 1118 |
} |
| 1119 |
// Adjust the cluster size and the number of nodes needed to establish |
| 1120 |
// a quorum. |
| 1121 |
n.csz = csz |
| 1122 |
n.qn = n.csz/2 + 1 |
| 1123 |
|
| 1124 |
return nil |
| 1125 |
} |
| 1126 |
|
| 1127 |
// AdjustClusterSize will change the cluster set size. |
| 1128 |
// Must be the leader. |
| 1129 |
func (n *raft) AdjustClusterSize(csz int) error { |
| 1130 |
n.Lock() |
| 1131 |
defer n.Unlock() |
| 1132 |
|
| 1133 |
// Check state under lock, we might not be leader anymore. |
| 1134 |
if n.State() != Leader { |
| 1135 |
return errNotLeader |
| 1136 |
} |
| 1137 |
// Same floor as bootstrap. |
| 1138 |
if csz < 2 { |
| 1139 |
csz = 2 |
| 1140 |
} |
| 1141 |
|
| 1142 |
// Adjust the cluster size and the number of nodes needed to establish |
| 1143 |
// a quorum. |
| 1144 |
n.csz = csz |
| 1145 |
n.qn = n.csz/2 + 1 |
| 1146 |
|
| 1147 |
n.sendPeerState() |
| 1148 |
return nil |
| 1149 |
} |
| 1150 |
|
| 1151 |
// PauseApply will allow us to pause processing of append entries onto our |
| 1152 |
// external apply queue. In effect this means that the upper layer will no longer |
| 1153 |
// receive any new entries from the Raft group. |
| 1154 |
func (n *raft) PauseApply() error { |
| 1155 |
if n.State() == Leader { |
| 1156 |
return errAlreadyLeader |
| 1157 |
} |
| 1158 |
n.Lock() |
| 1159 |
defer n.Unlock() |
| 1160 |
n.pauseApplyLocked() |
| 1161 |
return nil |
| 1162 |
} |
| 1163 |
|
| 1164 |
func (n *raft) pauseApplyLocked() { |
| 1165 |
// If we are currently not a follower, make sure we step down. |
| 1166 |
if n.State() != Follower { |
| 1167 |
n.stepdownLocked(noLeader) |
| 1168 |
} |
| 1169 |
|
| 1170 |
n.debug("Pausing our apply channel") |
| 1171 |
n.paused = true |
| 1172 |
if n.hcommit < n.commit { |
| 1173 |
n.hcommit = n.commit |
| 1174 |
} |
| 1175 |
// Also prevent us from trying to become a leader while paused and catching up. |
| 1176 |
n.resetElect(observerModeInterval) |
| 1177 |
} |
| 1178 |
|
| 1179 |
// ResumeApply will resume sending applies to the external apply queue. This |
| 1180 |
// means that we will start sending new entries to the upper layer. |
| 1181 |
func (n *raft) ResumeApply() { |
| 1182 |
n.Lock() |
| 1183 |
defer n.Unlock() |
| 1184 |
|
| 1185 |
if !n.paused { |
| 1186 |
return |
| 1187 |
} |
| 1188 |
|
| 1189 |
n.debug("Resuming our apply channel") |
| 1190 |
|
| 1191 |
// Reset before we start. |
| 1192 |
n.resetElectionTimeout() |
| 1193 |
|
| 1194 |
// Run catchup.. |
| 1195 |
if n.hcommit > n.commit { |
| 1196 |
n.debug("Resuming %d replays", n.hcommit+1-n.commit) |
| 1197 |
for index := n.commit + 1; index <= n.hcommit; index++ { |
| 1198 |
if err := n.applyCommit(index); err != nil { |
| 1199 |
n.warn("Got error on apply commit during replay: %v", err) |
| 1200 |
break |
| 1201 |
} |
| 1202 |
// We want to unlock here to allow the upper layers to call Applied() without blocking. |
| 1203 |
n.Unlock() |
| 1204 |
// Give hint to let other Go routines run. |
| 1205 |
// Might not be necessary but seems to make it more fine grained interleaving. |
| 1206 |
runtime.Gosched() |
| 1207 |
// Simply re-acquire |
| 1208 |
n.Lock() |
| 1209 |
// Need to check if we got closed. |
| 1210 |
if n.State() == Closed { |
| 1211 |
return |
| 1212 |
} |
| 1213 |
} |
| 1214 |
} |
| 1215 |
|
| 1216 |
// Clear our paused state after we apply. |
| 1217 |
n.paused = false |
| 1218 |
n.hcommit = 0 |
| 1219 |
|
| 1220 |
// If we had been selected to be the next leader campaign here now that we have resumed. |
| 1221 |
if n.lxfer { |
| 1222 |
n.xferCampaign() |
| 1223 |
} else { |
| 1224 |
n.resetElectionTimeout() |
| 1225 |
} |
| 1226 |
} |
| 1227 |
|
| 1228 |
// DrainAndReplaySnapshot will drain the apply queue and replay the snapshot. |
| 1229 |
// Our highest known commit will be preserved by pausing applies. The caller |
| 1230 |
// should make sure to call ResumeApply() when handling the snapshot from the |
| 1231 |
// queue, which will populate the rest of the committed entries in the queue. |
| 1232 |
func (n *raft) DrainAndReplaySnapshot() bool { |
| 1233 |
n.Lock() |
| 1234 |
defer n.Unlock() |
| 1235 |
// If the node was deleted, we can't replay the snapshot. |
| 1236 |
if n.deleted { |
| 1237 |
return false |
| 1238 |
} |
| 1239 |
snap, err := n.loadLastSnapshot() |
| 1240 |
if err != nil { |
| 1241 |
return false |
| 1242 |
} |
| 1243 |
n.warn("Draining and replaying snapshot") |
| 1244 |
n.pauseApplyLocked() |
| 1245 |
n.apply.drain() |
| 1246 |
// Cancel after draining, we might have sent EntryCatchup and need to get them the nil entry. |
| 1247 |
n.cancelCatchup() |
| 1248 |
n.commit = snap.lastIndex |
| 1249 |
n.apply.push(newCommittedEntry(n.commit, []*Entry{{EntrySnapshot, snap.data}})) |
| 1250 |
return true |
| 1251 |
} |
| 1252 |
|
| 1253 |
// Applied is a callback that must be called by the upper layer when it |
| 1254 |
// has successfully applied the committed entries that it received from the |
| 1255 |
// apply queue. It will return the number of entries and an estimation of the |
| 1256 |
// byte size that could be removed with a snapshot/compact. |
| 1257 |
func (n *raft) Applied(index uint64) (entries uint64, bytes uint64) { |
| 1258 |
return n.Processed(index, index) |
| 1259 |
} |
| 1260 |
|
| 1261 |
// Processed is a callback that must be called by the upper layer when it |
| 1262 |
// has processed the committed entries that it received from the apply queue, |
| 1263 |
// but it (maybe) hasn't applied all the processed entries yet. |
| 1264 |
// Used to indicate a commit was processed, even if it wasn't applied yet and |
| 1265 |
// can't be compacted away by a snapshot just yet. Which allows us to try to |
| 1266 |
// become leader if we've processed all commits, even if they're not all applied. |
| 1267 |
func (n *raft) Processed(index uint64, applied uint64) (entries uint64, bytes uint64) { |
| 1268 |
n.Lock() |
| 1269 |
defer n.Unlock() |
| 1270 |
|
| 1271 |
// Ignore if not applicable. This can happen during a reset. |
| 1272 |
if index > n.commit { |
| 1273 |
return 0, 0 |
| 1274 |
} |
| 1275 |
|
| 1276 |
// Ignore if already processed. |
| 1277 |
if index > n.processed { |
| 1278 |
n.processed = index |
| 1279 |
} |
| 1280 |
|
| 1281 |
// Ignore if already applied. |
| 1282 |
if applied > index { |
| 1283 |
applied = index |
| 1284 |
} |
| 1285 |
if applied > n.applied { |
| 1286 |
n.applied = applied |
| 1287 |
} |
| 1288 |
|
| 1289 |
// If it was set, and we reached the minimum processed index, reset and send signal to upper layer. |
| 1290 |
// We're not waiting for processed AND applied, because applying could take longer. |
| 1291 |
if n.aflr > 0 && n.processed >= n.aflr { |
| 1292 |
n.aflr = 0 |
| 1293 |
// Quick sanity-check to confirm we're still leader. |
| 1294 |
// In which case we must signal, since switchToLeader would not have done so already. |
| 1295 |
if n.State() == Leader { |
| 1296 |
if !n.leaderState.Swap(true) { |
| 1297 |
// Only update timestamp if leader state actually changed. |
| 1298 |
nowts := time.Now().UTC() |
| 1299 |
n.leaderSince.Store(&nowts) |
| 1300 |
} |
| 1301 |
n.updateLeadChange(true) |
| 1302 |
} |
| 1303 |
} |
| 1304 |
|
| 1305 |
// Calculate the number of entries and estimate the byte size that |
| 1306 |
// we can now remove with a compaction/snapshot. |
| 1307 |
if n.applied > n.papplied { |
| 1308 |
entries = n.applied - n.papplied |
| 1309 |
} |
| 1310 |
if msgs := n.pindex - n.papplied; msgs > 0 { |
| 1311 |
bytes = entries * n.bytes / msgs |
| 1312 |
} |
| 1313 |
return entries, bytes |
| 1314 |
} |
| 1315 |
|
| 1316 |
// For capturing data needed by snapshot. |
| 1317 |
type snapshot struct { |
| 1318 |
lastTerm uint64 |
| 1319 |
lastIndex uint64 |
| 1320 |
peerstate []byte |
| 1321 |
data []byte |
| 1322 |
} |
| 1323 |
|
| 1324 |
const minSnapshotLen = 28 |
| 1325 |
|
| 1326 |
// Encodes a snapshot into a buffer for storage. |
| 1327 |
// Lock should be held. |
| 1328 |
func (n *raft) encodeSnapshot(snap *snapshot) []byte { |
| 1329 |
if snap == nil { |
| 1330 |
return nil |
| 1331 |
} |
| 1332 |
var le = binary.LittleEndian |
| 1333 |
buf := make([]byte, minSnapshotLen+len(snap.peerstate)+len(snap.data)) |
| 1334 |
le.PutUint64(buf[0:], snap.lastTerm) |
| 1335 |
le.PutUint64(buf[8:], snap.lastIndex) |
| 1336 |
// Peer state |
| 1337 |
le.PutUint32(buf[16:], uint32(len(snap.peerstate))) |
| 1338 |
wi := 20 |
| 1339 |
copy(buf[wi:], snap.peerstate) |
| 1340 |
wi += len(snap.peerstate) |
| 1341 |
// data itself. |
| 1342 |
copy(buf[wi:], snap.data) |
| 1343 |
wi += len(snap.data) |
| 1344 |
|
| 1345 |
// Now do the hash for the end. |
| 1346 |
n.hh.Reset() |
| 1347 |
n.hh.Write(buf[:wi]) |
| 1348 |
var hb [highwayhash.Size64]byte |
| 1349 |
checksum := n.hh.Sum(hb[:0]) |
| 1350 |
copy(buf[wi:], checksum) |
| 1351 |
wi += len(checksum) |
| 1352 |
return buf[:wi] |
| 1353 |
} |
| 1354 |
|
| 1355 |
// SendSnapshot will send the latest snapshot as a normal AE. |
| 1356 |
// Should only be used when the upper layers know this is most recent. |
| 1357 |
// Used when restoring streams, moving a stream from R1 to R>1, etc. |
| 1358 |
func (n *raft) SendSnapshot(data []byte) error { |
| 1359 |
n.Lock() |
| 1360 |
defer n.Unlock() |
| 1361 |
// Don't check if we're leader before sending and storing, this is used on scaleup. |
| 1362 |
n.sendAppendEntryLocked([]*Entry{{EntrySnapshot, data}}, false) |
| 1363 |
return nil |
| 1364 |
} |
| 1365 |
|
| 1366 |
// Used to install a snapshot for the given term and applied index. This will release |
| 1367 |
// all of the log entries up to and including index. This should not be called with |
| 1368 |
// entries that have been applied to the FSM but have not been applied to the raft state. |
| 1369 |
func (n *raft) InstallSnapshot(data []byte, force bool) error { |
| 1370 |
n.Lock() |
| 1371 |
defer n.Unlock() |
| 1372 |
|
| 1373 |
c, err := n.createSnapshotCheckpointLocked(force) |
| 1374 |
if err != nil { |
| 1375 |
return err |
| 1376 |
} |
| 1377 |
c.n.debug("Installing snapshot of %d bytes [%d:%d]", len(data), c.term, c.applied) |
| 1378 |
snap := &snapshot{ |
| 1379 |
lastTerm: c.term, |
| 1380 |
lastIndex: c.applied, |
| 1381 |
peerstate: c.peerstate, |
| 1382 |
data: data, |
| 1383 |
} |
| 1384 |
return c.n.installSnapshot(snap) |
| 1385 |
} |
| 1386 |
|
| 1387 |
// Install the snapshot. |
| 1388 |
// Lock should be held. |
| 1389 |
func (n *raft) installSnapshot(snap *snapshot) error { |
| 1390 |
// Always reset, regardless of success or error. |
| 1391 |
// This is done even though this doesn't come from a checkpoint. We do this so we can |
| 1392 |
// interrupt/abort an asynchronously running snapshot (if it exists). Ensures the upper layer |
| 1393 |
// can't overwrite a snapshot that we installed here with an old asynchronously created one. |
| 1394 |
defer func() { |
| 1395 |
n.snapshotting = false |
| 1396 |
}() |
| 1397 |
|
| 1398 |
snapDir := filepath.Join(n.sd, snapshotsDir) |
| 1399 |
sn := fmt.Sprintf(snapFileT, snap.lastTerm, snap.lastIndex) |
| 1400 |
sfile := filepath.Join(snapDir, sn) |
| 1401 |
|
| 1402 |
n.snapLock.Lock() |
| 1403 |
err := writeFileWithSync(n.dios, sfile, n.encodeSnapshot(snap), defaultFilePerms) |
| 1404 |
n.snapLock.Unlock() |
| 1405 |
if err != nil { |
| 1406 |
// We could set write err here, but if this is a temporary situation, too many open files etc. |
| 1407 |
// we want to retry and snapshots are not fatal. |
| 1408 |
return err |
| 1409 |
} |
| 1410 |
|
| 1411 |
// Delete our previous snapshot file if it exists. |
| 1412 |
if n.snapfile != _EMPTY_ && n.snapfile != sfile { |
| 1413 |
os.Remove(n.snapfile) |
| 1414 |
} |
| 1415 |
// Remember our latest snapshot file. |
| 1416 |
n.snapfile = sfile |
| 1417 |
if _, err := n.wal.Compact(snap.lastIndex + 1); err != nil { |
| 1418 |
n.setWriteErrLocked(err) |
| 1419 |
return err |
| 1420 |
} |
| 1421 |
|
| 1422 |
// If installing a snapshot past our commits, clear the cache. |
| 1423 |
if snap.lastIndex > n.commit { |
| 1424 |
n.resetPendingEntries() |
| 1425 |
} |
| 1426 |
|
| 1427 |
var state StreamState |
| 1428 |
n.wal.FastState(&state) |
| 1429 |
n.papplied = snap.lastIndex |
| 1430 |
n.bytes = state.Bytes |
| 1431 |
return nil |
| 1432 |
} |
| 1433 |
|
| 1434 |
// CreateSnapshotCheckpoint creates a checkpoint to allow installing a snapshot asynchronously. |
| 1435 |
// Caller MUST make sure it only ever has one checkpoint handle at most, and either installs or |
| 1436 |
// aborts the checkpoint. |
| 1437 |
// See also: RaftNodeCheckpoint |
| 1438 |
func (n *raft) CreateSnapshotCheckpoint(force bool) (RaftNodeCheckpoint, error) { |
| 1439 |
n.Lock() |
| 1440 |
defer n.Unlock() |
| 1441 |
return n.createSnapshotCheckpointLocked(force) |
| 1442 |
} |
| 1443 |
|
| 1444 |
func (n *raft) createSnapshotCheckpointLocked(force bool) (*checkpoint, error) { |
| 1445 |
if n.State() == Closed { |
| 1446 |
return nil, errNodeClosed |
| 1447 |
} |
| 1448 |
if !force && n.snapshotting { |
| 1449 |
return nil, errSnapInProgress |
| 1450 |
} |
| 1451 |
|
| 1452 |
// If a write error has occurred already then stop here. |
| 1453 |
if werr := n.werr; werr != nil { |
| 1454 |
return nil, werr |
| 1455 |
} |
| 1456 |
|
| 1457 |
// Check that a catchup isn't already taking place. If it is then we won't |
| 1458 |
// allow installing snapshots until it is done. |
| 1459 |
// Unless we're forced to snapshot. We might have been catching up a peer for |
| 1460 |
// a long period, and this protects our log size from growing indefinitely. |
| 1461 |
if !force && len(n.progress) > 0 { |
| 1462 |
return nil, errCatchupsRunning |
| 1463 |
} |
| 1464 |
|
| 1465 |
if n.applied == 0 { |
| 1466 |
n.debug("Not snapshotting as there are no applied entries") |
| 1467 |
return nil, errNoSnapAvailable |
| 1468 |
} |
| 1469 |
|
| 1470 |
var term uint64 |
| 1471 |
if ae, _ := n.loadEntry(n.applied); ae != nil { |
| 1472 |
term = ae.term |
| 1473 |
ae.returnToPool() |
| 1474 |
} else { |
| 1475 |
n.debug("Not snapshotting as entry %d is not available", n.applied) |
| 1476 |
return nil, errNoSnapAvailable |
| 1477 |
} |
| 1478 |
|
| 1479 |
// Snapshot the committed peer state for the current applied index, we'll need it in the snapshot. |
| 1480 |
peerstate := encodePeerState(n.committedPeerStateLocked(n.applied)) |
| 1481 |
snapDir := filepath.Join(n.sd, snapshotsDir) |
| 1482 |
snapFile := filepath.Join(snapDir, fmt.Sprintf(snapFileT, term, n.applied)) |
| 1483 |
|
| 1484 |
n.snapshotting = true |
| 1485 |
c := &checkpoint{ |
| 1486 |
n: n, |
| 1487 |
term: term, |
| 1488 |
applied: n.applied, |
| 1489 |
papplied: n.papplied, |
| 1490 |
snapFile: snapFile, |
| 1491 |
peerstate: peerstate, |
| 1492 |
} |
| 1493 |
return c, nil |
| 1494 |
} |
| 1495 |
|
| 1496 |
type checkpoint struct { |
| 1497 |
n *raft // Reference to the RaftNode. |
| 1498 |
term uint64 // The term of the entry at applied. |
| 1499 |
applied uint64 // What applied value the snapshot will represent and what the log can be compacted to. |
| 1500 |
papplied uint64 // Previous applied value of the previous snapshot. |
| 1501 |
snapFile string // Where the snapshot should be installed. |
| 1502 |
peerstate []byte // Encoded peerstate generated when creating this checkpoint. |
| 1503 |
} |
| 1504 |
|
| 1505 |
// LoadLastSnapshot loads the last snapshot from disk when using a RaftNodeCheckpoint. |
| 1506 |
func (c *checkpoint) LoadLastSnapshot() ([]byte, error) { |
| 1507 |
c.n.Lock() |
| 1508 |
defer c.n.Unlock() |
| 1509 |
if c.n.State() == Closed { |
| 1510 |
return nil, errNodeClosed |
| 1511 |
} |
| 1512 |
if !c.n.snapshotting { |
| 1513 |
// The checkpoint can be aborted at any time, don't continue if that happened. |
| 1514 |
return nil, errSnapAborted |
| 1515 |
} |
| 1516 |
snap, err := c.n.loadLastSnapshot() |
| 1517 |
if err != nil { |
| 1518 |
return nil, err |
| 1519 |
} |
| 1520 |
if snap.lastIndex != c.papplied { |
| 1521 |
// Another snapshot was installed in the meantime. This invalidates our checkpoint. |
| 1522 |
return nil, errors.New("snapshot index mismatch") |
| 1523 |
} |
| 1524 |
return snap.data, nil |
| 1525 |
} |
| 1526 |
|
| 1527 |
// AppendEntriesSeq allows iterating over entries that can be compacted as part of a snapshot. |
| 1528 |
func (c *checkpoint) AppendEntriesSeq() iter.Seq2[*appendEntry, error] { |
| 1529 |
return func(yield func(*appendEntry, error) bool) { |
| 1530 |
for index := c.papplied + 1; index <= c.applied; index++ { |
| 1531 |
c.n.Lock() |
| 1532 |
if c.n.State() == Closed { |
| 1533 |
c.n.Unlock() |
| 1534 |
yield(nil, errNodeClosed) |
| 1535 |
return |
| 1536 |
} |
| 1537 |
if !c.n.snapshotting { |
| 1538 |
c.n.Unlock() |
| 1539 |
// The checkpoint can be aborted at any time, don't continue if that happened. |
| 1540 |
yield(nil, errSnapAborted) |
| 1541 |
return |
| 1542 |
} |
| 1543 |
// Load entry and yield to the caller while unlocked. |
| 1544 |
ae, err := c.n.loadEntry(index) |
| 1545 |
c.n.Unlock() |
| 1546 |
if err != nil { |
| 1547 |
yield(nil, err) |
| 1548 |
return |
| 1549 |
} |
| 1550 |
hasMore := yield(ae, nil) |
| 1551 |
ae.returnToPool() |
| 1552 |
if !hasMore { |
| 1553 |
return |
| 1554 |
} |
| 1555 |
} |
| 1556 |
} |
| 1557 |
} |
| 1558 |
|
| 1559 |
// Abort can be called to cancel the snapshot installation at any time. |
| 1560 |
func (c *checkpoint) Abort() { |
| 1561 |
c.n.Lock() |
| 1562 |
defer c.n.Unlock() |
| 1563 |
c.n.snapshotting = false |
| 1564 |
} |
| 1565 |
|
| 1566 |
// InstallSnapshot allows asynchronous installation of a snapshot by unlocking when |
| 1567 |
// performing operations that don't strictly need to be locked. When the lock is re-acquired |
| 1568 |
// it's checked that the node is not closed and n.snapshotting is still set to ensure we're |
| 1569 |
// still meant to install the snapshot. |
| 1570 |
// Async snapshots can only be used when using CreateSnapshotCheckpoint. |
| 1571 |
// Lock should be held. |
| 1572 |
func (c *checkpoint) InstallSnapshot(data []byte) (uint64, error) { |
| 1573 |
n := c.n |
| 1574 |
n.Lock() |
| 1575 |
defer n.Unlock() |
| 1576 |
if n.State() == Closed { |
| 1577 |
return 0, errNodeClosed |
| 1578 |
} |
| 1579 |
if !n.snapshotting { |
| 1580 |
// The checkpoint can be aborted at any time, don't continue if that happened. |
| 1581 |
return 0, errSnapAborted |
| 1582 |
} |
| 1583 |
|
| 1584 |
// Always reset, regardless of success or error. |
| 1585 |
defer func() { |
| 1586 |
n.snapshotting = false |
| 1587 |
}() |
| 1588 |
|
| 1589 |
n.debug("Installing snapshot of %d bytes [%d:%d]", len(data), c.term, c.applied) |
| 1590 |
snap := &snapshot{ |
| 1591 |
lastTerm: c.term, |
| 1592 |
lastIndex: c.applied, |
| 1593 |
peerstate: c.peerstate, |
| 1594 |
data: data, |
| 1595 |
} |
| 1596 |
encoded := n.encodeSnapshot(snap) |
| 1597 |
|
| 1598 |
// Before releasing the Raft lock, we acquire the snapshot lock to make |
| 1599 |
// sure snapshot writes remain serial. |
| 1600 |
n.snapLock.Lock() |
| 1601 |
// Unlock while writing. |
| 1602 |
n.Unlock() |
| 1603 |
err := writeFileWithSync(n.dios, c.snapFile, encoded, defaultFilePerms) |
| 1604 |
n.snapLock.Unlock() |
| 1605 |
n.Lock() |
| 1606 |
// On any failure path, drop the file we just wrote so it doesn't get |
| 1607 |
// picked up by setupLastSnapshot on restart. Skip the remove if it's the |
| 1608 |
// snapshot already adopted into n.snapfile for this term/applied, a direct |
| 1609 |
// install that was serialized after our write will have overwritten it. |
| 1610 |
if closed := n.State() == Closed; closed || !n.snapshotting || err != nil { |
| 1611 |
if c.snapFile != n.snapfile { |
| 1612 |
os.Remove(c.snapFile) |
| 1613 |
} |
| 1614 |
// If the node was closed/deleted while we were writing, the write error |
| 1615 |
// is just a consequence of that, report the close instead. |
| 1616 |
if closed { |
| 1617 |
return 0, errNodeClosed |
| 1618 |
} else if !n.snapshotting { |
| 1619 |
return 0, errSnapAborted |
| 1620 |
} |
| 1621 |
|
| 1622 |
// We could set write err here, but if this is a temporary situation, too many open files etc. |
| 1623 |
// we want to retry and snapshots are not fatal. |
| 1624 |
return 0, err |
| 1625 |
} |
| 1626 |
|
| 1627 |
// Delete our previous snapshot file if it exists. |
| 1628 |
if n.snapfile != _EMPTY_ && n.snapfile != c.snapFile { |
| 1629 |
os.Remove(n.snapfile) |
| 1630 |
} |
| 1631 |
// Remember our latest snapshot file. |
| 1632 |
n.snapfile = c.snapFile |
| 1633 |
|
| 1634 |
// Unlock while compacting. |
| 1635 |
n.Unlock() |
| 1636 |
_, err = n.wal.Compact(snap.lastIndex + 1) |
| 1637 |
n.Lock() |
| 1638 |
if n.State() == Closed { |
| 1639 |
return 0, errNodeClosed |
| 1640 |
} else if !n.snapshotting { |
| 1641 |
// The checkpoint can be aborted at any time, don't continue if that happened. |
| 1642 |
return 0, errSnapAborted |
| 1643 |
} else if err != nil { |
| 1644 |
n.setWriteErrLocked(err) |
| 1645 |
return 0, err |
| 1646 |
} |
| 1647 |
|
| 1648 |
compacted := n.bytes |
| 1649 |
var state StreamState |
| 1650 |
n.wal.FastState(&state) |
| 1651 |
n.papplied = snap.lastIndex |
| 1652 |
n.bytes = state.Bytes |
| 1653 |
|
| 1654 |
// Expose compacted size. |
| 1655 |
if n.bytes > compacted { |
| 1656 |
compacted = 0 |
| 1657 |
} else { |
| 1658 |
compacted -= n.bytes |
| 1659 |
} |
| 1660 |
return compacted, nil |
| 1661 |
} |
| 1662 |
|
| 1663 |
// NeedSnapshot returns true if it is necessary to try to install a snapshot, i.e. |
| 1664 |
// after we have finished recovering/replaying at startup, on a regular interval or |
| 1665 |
// as a part of cleaning up when shutting down. |
| 1666 |
func (n *raft) NeedSnapshot() bool { |
| 1667 |
n.RLock() |
| 1668 |
defer n.RUnlock() |
| 1669 |
return n.snapfile == _EMPTY_ && n.applied > 1 |
| 1670 |
} |
| 1671 |
|
| 1672 |
const ( |
| 1673 |
snapshotsDir = "snapshots" |
| 1674 |
snapFileT = "snap.%d.%d" |
| 1675 |
) |
| 1676 |
|
| 1677 |
// termAndIndexFromSnapfile tries to load the snapshot file and returns the term |
| 1678 |
// and index from that snapshot. |
| 1679 |
func termAndIndexFromSnapFile(sn string) (term, index uint64, err error) { |
| 1680 |
if sn == _EMPTY_ { |
| 1681 |
return 0, 0, errBadSnapName |
| 1682 |
} |
| 1683 |
fn := filepath.Base(sn) |
| 1684 |
if n, err := fmt.Sscanf(fn, snapFileT, &term, &index); err != nil || n != 2 { |
| 1685 |
return 0, 0, errBadSnapName |
| 1686 |
} |
| 1687 |
if fn != fmt.Sprintf(snapFileT, term, index) { |
| 1688 |
return 0, 0, errBadSnapName |
| 1689 |
} |
| 1690 |
return term, index, nil |
| 1691 |
} |
| 1692 |
|
| 1693 |
// setupLastSnapshot is called at startup to try and recover the last snapshot from |
| 1694 |
// the disk if possible. We will try to recover the term, index and commit/applied |
| 1695 |
// indices and then notify the upper layer what we found. Compacts the WAL if needed. |
| 1696 |
func (n *raft) setupLastSnapshot() error { |
| 1697 |
snapDir := filepath.Join(n.sd, snapshotsDir) |
| 1698 |
psnaps, err := os.ReadDir(snapDir) |
| 1699 |
if err != nil { |
| 1700 |
if os.IsNotExist(err) { |
| 1701 |
return errNoSnapAvailable |
| 1702 |
} |
| 1703 |
return err |
| 1704 |
} |
| 1705 |
|
| 1706 |
var lterm, lindex uint64 |
| 1707 |
var latest string |
| 1708 |
for _, sf := range psnaps { |
| 1709 |
sfile := filepath.Join(snapDir, sf.Name()) |
| 1710 |
var term, index uint64 |
| 1711 |
term, index, err := termAndIndexFromSnapFile(sf.Name()) |
| 1712 |
if err == nil { |
| 1713 |
if term > lterm { |
| 1714 |
lterm, lindex = term, index |
| 1715 |
latest = sfile |
| 1716 |
} else if term == lterm && index > lindex { |
| 1717 |
lindex = index |
| 1718 |
latest = sfile |
| 1719 |
} |
| 1720 |
} else { |
| 1721 |
// Clean this up, can't parse the name. |
| 1722 |
// TODO(dlc) - We could read in and check actual contents. |
| 1723 |
n.debug("Removing snapshot, can't parse name: %q", sf.Name()) |
| 1724 |
os.Remove(sfile) |
| 1725 |
} |
| 1726 |
} |
| 1727 |
if latest == _EMPTY_ { |
| 1728 |
return nil |
| 1729 |
} |
| 1730 |
|
| 1731 |
// Set latest snapshot we have. |
| 1732 |
n.Lock() |
| 1733 |
defer n.Unlock() |
| 1734 |
|
| 1735 |
n.snapfile = latest |
| 1736 |
snap, err := n.loadLastSnapshot() |
| 1737 |
if err != nil { |
| 1738 |
return err |
| 1739 |
} |
| 1740 |
|
| 1741 |
// We successfully recovered the last snapshot from the disk. |
| 1742 |
// Recover state from the snapshot and then notify the upper layer. |
| 1743 |
// Compact the WAL when we're done if needed. |
| 1744 |
n.pindex = snap.lastIndex |
| 1745 |
n.pterm = snap.lastTerm |
| 1746 |
// Explicitly only set commit, and not applied. |
| 1747 |
// Applied will move up when the snapshot is actually applied. |
| 1748 |
n.commit = snap.lastIndex |
| 1749 |
n.papplied = snap.lastIndex |
| 1750 |
// Restore the peerState |
| 1751 |
ps, err := decodePeerState(snap.peerstate) |
| 1752 |
if err != nil { |
| 1753 |
return err |
| 1754 |
} |
| 1755 |
n.processPeerState(ps) |
| 1756 |
n.extSt = ps.domainExt |
| 1757 |
|
| 1758 |
n.apply.push(newCommittedEntry(n.commit, []*Entry{{EntrySnapshot, snap.data}})) |
| 1759 |
if _, err := n.wal.Compact(snap.lastIndex + 1); err != nil { |
| 1760 |
n.setWriteErrLocked(err) |
| 1761 |
return err |
| 1762 |
} |
| 1763 |
|
| 1764 |
// Now cleanup any old entries. We only do this once we know that the |
| 1765 |
// latest snapshot was OK. |
| 1766 |
for _, sf := range psnaps { |
| 1767 |
if sfile := filepath.Join(snapDir, sf.Name()); sfile != latest { |
| 1768 |
n.debug("Removing old snapshot: %q", sfile) |
| 1769 |
os.Remove(sfile) |
| 1770 |
} |
| 1771 |
} |
| 1772 |
|
| 1773 |
return nil |
| 1774 |
} |
| 1775 |
|
| 1776 |
// loadLastSnapshot will load and return our last snapshot. |
| 1777 |
// Lock should be held. |
| 1778 |
func (n *raft) loadLastSnapshot() (*snapshot, error) { |
| 1779 |
if n.snapfile == _EMPTY_ { |
| 1780 |
return nil, errNoSnapAvailable |
| 1781 |
} |
| 1782 |
|
| 1783 |
n.dios.acquire() |
| 1784 |
buf, err := os.ReadFile(n.snapfile) |
| 1785 |
n.dios.release() |
| 1786 |
|
| 1787 |
if err != nil { |
| 1788 |
n.warn("Error reading snapshot: %v", err) |
| 1789 |
return nil, err |
| 1790 |
} |
| 1791 |
if len(buf) < minSnapshotLen { |
| 1792 |
n.warn("Snapshot corrupt, too short") |
| 1793 |
return nil, errSnapshotCorrupt |
| 1794 |
} |
| 1795 |
|
| 1796 |
// Check to make sure hash is consistent. |
| 1797 |
hoff := len(buf) - 8 |
| 1798 |
lchk := buf[hoff:] |
| 1799 |
n.hh.Reset() |
| 1800 |
n.hh.Write(buf[:hoff]) |
| 1801 |
var hb [highwayhash.Size64]byte |
| 1802 |
if !bytes.Equal(lchk[:], n.hh.Sum(hb[:0])) { |
| 1803 |
n.warn("Snapshot corrupt, checksums did not match") |
| 1804 |
return nil, errSnapshotCorrupt |
| 1805 |
} |
| 1806 |
|
| 1807 |
var le = binary.LittleEndian |
| 1808 |
lps := le.Uint32(buf[16:]) |
| 1809 |
snap := &snapshot{ |
| 1810 |
lastTerm: le.Uint64(buf[0:]), |
| 1811 |
lastIndex: le.Uint64(buf[8:]), |
| 1812 |
peerstate: buf[20 : 20+lps], |
| 1813 |
data: buf[20+lps : hoff], |
| 1814 |
} |
| 1815 |
|
| 1816 |
// We had a bug in 2.9.12 that would allow snapshots on last index of 0. |
| 1817 |
// Detect that and continue anyway, nothing else we can do about it. |
| 1818 |
if snap.lastIndex == 0 { |
| 1819 |
n.warn("Snapshot with last index 0 is invalid, cleaning up") |
| 1820 |
os.Remove(n.snapfile) |
| 1821 |
n.snapfile = _EMPTY_ |
| 1822 |
return nil, errNoSnapAvailable |
| 1823 |
} |
| 1824 |
|
| 1825 |
return snap, nil |
| 1826 |
} |
| 1827 |
|
| 1828 |
// Leader returns if we are the leader for our group. |
| 1829 |
// We use an atomic here now vs acquiring the read lock. |
| 1830 |
func (n *raft) Leader() bool { |
| 1831 |
if n == nil { |
| 1832 |
return false |
| 1833 |
} |
| 1834 |
return n.leaderState.Load() |
| 1835 |
} |
| 1836 |
|
| 1837 |
// LeaderSince returns how long we have been leader for, |
| 1838 |
// if applicable. |
| 1839 |
func (n *raft) LeaderSince() *time.Time { |
| 1840 |
if n == nil { |
| 1841 |
return nil |
| 1842 |
} |
| 1843 |
return n.leaderSince.Load() |
| 1844 |
} |
| 1845 |
|
| 1846 |
// stepdown immediately steps down the Raft node to the |
| 1847 |
// follower state. This will take the lock itself. |
| 1848 |
func (n *raft) stepdown(newLeader string) { |
| 1849 |
n.Lock() |
| 1850 |
defer n.Unlock() |
| 1851 |
n.stepdownLocked(newLeader) |
| 1852 |
} |
| 1853 |
|
| 1854 |
// stepdownLocked immediately steps down the Raft node to the |
| 1855 |
// follower state. This requires the lock is already held. |
| 1856 |
func (n *raft) stepdownLocked(newLeader string) { |
| 1857 |
n.debug("Stepping down") |
| 1858 |
n.switchToFollowerLocked(newLeader) |
| 1859 |
} |
| 1860 |
|
| 1861 |
// isCatchingUp returns true if a catchup is currently taking place. |
| 1862 |
func (n *raft) isCatchingUp() bool { |
| 1863 |
n.RLock() |
| 1864 |
defer n.RUnlock() |
| 1865 |
return n.catchup != nil |
| 1866 |
} |
| 1867 |
|
| 1868 |
// isCurrent is called from the healthchecks and returns true if we believe |
| 1869 |
// that the upper layer is current with the Raft layer, i.e. that it has applied |
| 1870 |
// all of the commits that we have given it. |
| 1871 |
// Optionally we can also check whether or not we're making forward progress if we |
| 1872 |
// aren't current, in which case this function may block for up to ~10ms to find out. |
| 1873 |
// Lock should be held. |
| 1874 |
func (n *raft) isCurrent(includeForwardProgress bool) bool { |
| 1875 |
// Check if we are closed. |
| 1876 |
if n.State() == Closed { |
| 1877 |
n.debug("Not current, node is closed") |
| 1878 |
return false |
| 1879 |
} |
| 1880 |
|
| 1881 |
// Check whether we've made progress on any state, 0 is invalid so not healthy. |
| 1882 |
if n.commit == 0 { |
| 1883 |
n.debug("Not current, no commits") |
| 1884 |
return false |
| 1885 |
} |
| 1886 |
|
| 1887 |
// If we were previously logging about falling behind, also log when the problem |
| 1888 |
// was cleared. |
| 1889 |
clearBehindState := func() { |
| 1890 |
if n.hcbehind { |
| 1891 |
n.warn("Health check OK, no longer falling behind") |
| 1892 |
n.hcbehind = false |
| 1893 |
} |
| 1894 |
} |
| 1895 |
|
| 1896 |
// Make sure we are the leader or we know we have heard from the leader recently. |
| 1897 |
if n.State() == Leader { |
| 1898 |
clearBehindState() |
| 1899 |
return true |
| 1900 |
} |
| 1901 |
|
| 1902 |
// Check to see that we have heard from the current leader lately. |
| 1903 |
if n.leader != noLeader && n.leader != n.id && n.catchup == nil { |
| 1904 |
okInterval := hbInterval * 2 |
| 1905 |
if ps := n.peers[n.leader]; ps == nil || time.Since(ps.ts) > okInterval { |
| 1906 |
n.debug("Not current, no recent leader contact") |
| 1907 |
return false |
| 1908 |
} |
| 1909 |
} |
| 1910 |
if cs := n.catchup; cs != nil { |
| 1911 |
// We're actively catching up, can't mark current even if commit==applied. |
| 1912 |
n.debug("Not current, still catching up pindex=%d, cindex=%d", n.pindex, cs.cindex) |
| 1913 |
return false |
| 1914 |
} |
| 1915 |
|
| 1916 |
if n.paused && n.hcommit > n.commit { |
| 1917 |
// We're currently paused, waiting to be resumed to apply pending commits. |
| 1918 |
n.debug("Not current, waiting to resume applies commit=%d, hcommit=%d", n.commit, n.hcommit) |
| 1919 |
return false |
| 1920 |
} |
| 1921 |
|
| 1922 |
if n.commit == n.applied { |
| 1923 |
// At this point if we are current, we can return saying so. |
| 1924 |
clearBehindState() |
| 1925 |
return true |
| 1926 |
} else if !includeForwardProgress { |
| 1927 |
// Otherwise, if we aren't allowed to include forward progress |
| 1928 |
// (i.e. we are checking "current" instead of "healthy") then |
| 1929 |
// give up now. |
| 1930 |
return false |
| 1931 |
} |
| 1932 |
|
| 1933 |
// Otherwise, wait for a short period of time and see if we are making any |
| 1934 |
// forward progress. |
| 1935 |
if startDelta := n.commit - n.applied; startDelta > 0 { |
| 1936 |
for i := 0; i < 10; i++ { // 10ms, in 1ms increments |
| 1937 |
n.Unlock() |
| 1938 |
time.Sleep(time.Millisecond) |
| 1939 |
n.Lock() |
| 1940 |
if n.State() == Closed { |
| 1941 |
n.debug("Node closed during health check, returning not current") |
| 1942 |
return false |
| 1943 |
} |
| 1944 |
if n.commit-n.applied < startDelta { |
| 1945 |
// The gap is getting smaller, so we're making forward progress. |
| 1946 |
clearBehindState() |
| 1947 |
return true |
| 1948 |
} |
| 1949 |
} |
| 1950 |
} |
| 1951 |
|
| 1952 |
n.hcbehind = true |
| 1953 |
n.warn("Falling behind in health check, commit %d != applied %d", n.commit, n.applied) |
| 1954 |
return false |
| 1955 |
} |
| 1956 |
|
| 1957 |
// Current returns if we are the leader for our group or an up to date follower. |
| 1958 |
func (n *raft) Current() bool { |
| 1959 |
if n == nil { |
| 1960 |
return false |
| 1961 |
} |
| 1962 |
n.Lock() |
| 1963 |
defer n.Unlock() |
| 1964 |
return n.isCurrent(false) |
| 1965 |
} |
| 1966 |
|
| 1967 |
// Healthy returns if we are the leader for our group and nearly up-to-date. |
| 1968 |
func (n *raft) Healthy() bool { |
| 1969 |
if n == nil { |
| 1970 |
return false |
| 1971 |
} |
| 1972 |
n.Lock() |
| 1973 |
defer n.Unlock() |
| 1974 |
return n.isCurrent(true) |
| 1975 |
} |
| 1976 |
|
| 1977 |
// HadPreviousLeader indicates if this group ever had a leader. |
| 1978 |
func (n *raft) HadPreviousLeader() bool { |
| 1979 |
return n.pleader.Load() |
| 1980 |
} |
| 1981 |
|
| 1982 |
// GroupLeader returns the current leader of the group. |
| 1983 |
func (n *raft) GroupLeader() string { |
| 1984 |
if n == nil { |
| 1985 |
return noLeader |
| 1986 |
} |
| 1987 |
n.RLock() |
| 1988 |
defer n.RUnlock() |
| 1989 |
return n.leader |
| 1990 |
} |
| 1991 |
|
| 1992 |
// Leaderless is a lockless way of finding out if the group has a |
| 1993 |
// leader or not. Use instead of GroupLeader in hot paths. |
| 1994 |
func (n *raft) Leaderless() bool { |
| 1995 |
if n == nil { |
| 1996 |
return true |
| 1997 |
} |
| 1998 |
// Negated because we want the default state of hasLeader to be |
| 1999 |
// false until the first setLeader() call. |
| 2000 |
return !n.hasleader.Load() |
| 2001 |
} |
| 2002 |
|
| 2003 |
// Guess the best next leader. Stepdown will check more thoroughly. |
| 2004 |
// Lock should be held. |
| 2005 |
func (n *raft) selectNextLeader() string { |
| 2006 |
nextLeader, hli := noLeader, uint64(0) |
| 2007 |
for peer, ps := range n.peers { |
| 2008 |
if peer == n.id || ps.li <= hli { |
| 2009 |
continue |
| 2010 |
} |
| 2011 |
hli = ps.li |
| 2012 |
nextLeader = peer |
| 2013 |
} |
| 2014 |
return nextLeader |
| 2015 |
} |
| 2016 |
|
| 2017 |
// StepDown will have a leader stepdown and optionally do a leader transfer. |
| 2018 |
func (n *raft) StepDown(preferred ...string) error { |
| 2019 |
n.Lock() |
| 2020 |
// Check state under lock, we might not be leader anymore. |
| 2021 |
if n.State() != Leader { |
| 2022 |
n.Unlock() |
| 2023 |
return errNotLeader |
| 2024 |
} |
| 2025 |
if len(preferred) > 1 { |
| 2026 |
n.Unlock() |
| 2027 |
return errTooManyPrefs |
| 2028 |
} |
| 2029 |
|
| 2030 |
n.debug("Being asked to stepdown") |
| 2031 |
|
| 2032 |
// See if we have up to date followers. |
| 2033 |
maybeLeader := noLeader |
| 2034 |
if len(preferred) > 0 { |
| 2035 |
if preferred[0] != _EMPTY_ { |
| 2036 |
maybeLeader = preferred[0] |
| 2037 |
} else { |
| 2038 |
preferred = nil |
| 2039 |
} |
| 2040 |
} |
| 2041 |
|
| 2042 |
// Can't pick ourselves. |
| 2043 |
if maybeLeader == n.id { |
| 2044 |
maybeLeader = noLeader |
| 2045 |
preferred = nil |
| 2046 |
} |
| 2047 |
|
| 2048 |
// If we have a preferred check it first. |
| 2049 |
if maybeLeader != noLeader { |
| 2050 |
var isHealthy bool |
| 2051 |
if ps, ok := n.peers[maybeLeader]; ok { |
| 2052 |
si, ok := n.s.nodeToInfo.Load(maybeLeader) |
| 2053 |
isHealthy = ok && !si.(nodeInfo).offline && time.Since(ps.ts) < hbInterval*3 |
| 2054 |
} |
| 2055 |
if !isHealthy { |
| 2056 |
maybeLeader = noLeader |
| 2057 |
} |
| 2058 |
} |
| 2059 |
|
| 2060 |
// If we do not have a preferred at this point pick the first healthy one. |
| 2061 |
// Make sure not ourselves. |
| 2062 |
if maybeLeader == noLeader { |
| 2063 |
for peer, ps := range n.peers { |
| 2064 |
if peer == n.id { |
| 2065 |
continue |
| 2066 |
} |
| 2067 |
si, ok := n.s.nodeToInfo.Load(peer) |
| 2068 |
isHealthy := ok && !si.(nodeInfo).offline && time.Since(ps.ts) < hbInterval*3 |
| 2069 |
if isHealthy { |
| 2070 |
maybeLeader = peer |
| 2071 |
break |
| 2072 |
} |
| 2073 |
} |
| 2074 |
} |
| 2075 |
n.Unlock() |
| 2076 |
|
| 2077 |
if len(preferred) > 0 && maybeLeader == noLeader { |
| 2078 |
n.debug("Can not transfer to preferred peer %q", preferred[0]) |
| 2079 |
} |
| 2080 |
|
| 2081 |
// If we have a new leader selected, transfer over to them. |
| 2082 |
// Send the append entry directly rather than via the proposals queue, |
| 2083 |
// as we will switch to follower state immediately and will blow away |
| 2084 |
// the contents of the proposal queue in the process. |
| 2085 |
if maybeLeader != noLeader { |
| 2086 |
n.debug("Selected %q for new leader, stepping down due to leadership transfer", maybeLeader) |
| 2087 |
ae := newEntry(EntryLeaderTransfer, []byte(maybeLeader)) |
| 2088 |
n.sendAppendEntry([]*Entry{ae}) |
| 2089 |
} |
| 2090 |
|
| 2091 |
// Force us to stepdown here. |
| 2092 |
n.stepdown(noLeader) |
| 2093 |
|
| 2094 |
return nil |
| 2095 |
} |
| 2096 |
|
| 2097 |
// Campaign will have our node start a leadership vote. |
| 2098 |
func (n *raft) Campaign() error { |
| 2099 |
n.Lock() |
| 2100 |
defer n.Unlock() |
| 2101 |
return n.campaign(randCampaignTimeout()) |
| 2102 |
} |
| 2103 |
|
| 2104 |
// CampaignImmediately will have our node start a leadership vote after minimal delay. |
| 2105 |
func (n *raft) CampaignImmediately() error { |
| 2106 |
n.Lock() |
| 2107 |
defer n.Unlock() |
| 2108 |
n.maybeLeader = true |
| 2109 |
n.resetInitializing() |
| 2110 |
return n.campaign(minCampaignTimeout / 2) |
| 2111 |
} |
| 2112 |
|
| 2113 |
func randCampaignTimeout() time.Duration { |
| 2114 |
delta := rand.Int63n(int64(maxCampaignTimeout - minCampaignTimeout)) |
| 2115 |
return (minCampaignTimeout + time.Duration(delta)) |
| 2116 |
} |
| 2117 |
|
| 2118 |
// Campaign will have our node start a leadership vote. |
| 2119 |
// Lock should be held. |
| 2120 |
func (n *raft) campaign(et time.Duration) error { |
| 2121 |
n.debug("Starting campaign") |
| 2122 |
if n.State() == Leader { |
| 2123 |
return errAlreadyLeader |
| 2124 |
} |
| 2125 |
n.resetElect(et) |
| 2126 |
return nil |
| 2127 |
} |
| 2128 |
|
| 2129 |
// xferCampaign will have our node start an immediate leadership vote. |
| 2130 |
// Lock should be held. |
| 2131 |
func (n *raft) xferCampaign() error { |
| 2132 |
n.debug("Starting transfer campaign") |
| 2133 |
if n.State() == Leader { |
| 2134 |
n.lxfer = false |
| 2135 |
return errAlreadyLeader |
| 2136 |
} |
| 2137 |
n.resetElect(10 * time.Millisecond) |
| 2138 |
return nil |
| 2139 |
} |
| 2140 |
|
| 2141 |
// State returns the current state for this node. |
| 2142 |
// Upper layers should not check State to check if we're Leader, use n.Leader() instead. |
| 2143 |
func (n *raft) State() RaftState { |
| 2144 |
return RaftState(n.state.Load()) |
| 2145 |
} |
| 2146 |
|
| 2147 |
// Progress returns the current index, commit and applied values. |
| 2148 |
func (n *raft) Progress() (index, commit, applied uint64) { |
| 2149 |
n.RLock() |
| 2150 |
defer n.RUnlock() |
| 2151 |
return n.pindex, n.commit, n.applied |
| 2152 |
} |
| 2153 |
|
| 2154 |
// Size returns number of entries and total bytes for our WAL. |
| 2155 |
func (n *raft) Size() (entries uint64, bytes uint64) { |
| 2156 |
n.RLock() |
| 2157 |
entries = n.pindex - n.papplied |
| 2158 |
bytes = n.bytes |
| 2159 |
n.RUnlock() |
| 2160 |
return entries, bytes |
| 2161 |
} |
| 2162 |
|
| 2163 |
func (n *raft) ID() string { |
| 2164 |
if n == nil { |
| 2165 |
return _EMPTY_ |
| 2166 |
} |
| 2167 |
// Lock not needed as n.id is never changed after creation. |
| 2168 |
return n.id |
| 2169 |
} |
| 2170 |
|
| 2171 |
func (n *raft) Group() string { |
| 2172 |
// Lock not needed as n.group is never changed after creation. |
| 2173 |
return n.group |
| 2174 |
} |
| 2175 |
|
| 2176 |
func (n *raft) Peers() []*Peer { |
| 2177 |
n.RLock() |
| 2178 |
defer n.RUnlock() |
| 2179 |
|
| 2180 |
var peers []*Peer |
| 2181 |
for id, ps := range n.peers { |
| 2182 |
var current bool |
| 2183 |
var lag uint64 |
| 2184 |
if id == n.id { |
| 2185 |
// We are current and have no lag when compared with ourselves. |
| 2186 |
current = true |
| 2187 |
} else if n.id == n.leader { |
| 2188 |
// We are the leader, we know how many entries this replica has persisted. |
| 2189 |
// Lag is determined by how many entries we have quorum on in our log that haven't yet |
| 2190 |
// been persisted on the replica. They are current if there's no lag. |
| 2191 |
// This will show all peers that are part of quorum as "current". |
| 2192 |
if n.commit > ps.li { |
| 2193 |
lag = n.commit - ps.li |
| 2194 |
} |
| 2195 |
current = lag == 0 |
| 2196 |
} else if id == n.leader { |
| 2197 |
// This peer is the leader, we don't know our lag, but we can report |
| 2198 |
// on whether we've seen the leader recently. |
| 2199 |
okInterval := hbInterval * 2 |
| 2200 |
current = time.Since(ps.ts) <= okInterval |
| 2201 |
} else { |
| 2202 |
// The remaining condition is another follower that we're not in contact with. |
| 2203 |
// We intentionally leave current and lag as empty. |
| 2204 |
current, lag = false, 0 |
| 2205 |
} |
| 2206 |
|
| 2207 |
p := &Peer{ |
| 2208 |
ID: id, |
| 2209 |
Current: current, |
| 2210 |
Last: ps.ts, |
| 2211 |
Lag: lag, |
| 2212 |
} |
| 2213 |
peers = append(peers, p) |
| 2214 |
} |
| 2215 |
return peers |
| 2216 |
} |
| 2217 |
|
| 2218 |
// Update and propose our known set of peers. |
| 2219 |
func (n *raft) ProposeKnownPeers(knownPeers []string) { |
| 2220 |
n.Lock() |
| 2221 |
defer n.Unlock() |
| 2222 |
// If we are the leader update and send this update out. |
| 2223 |
if n.State() != Leader { |
| 2224 |
return |
| 2225 |
} |
| 2226 |
n.updateKnownPeersLocked(knownPeers) |
| 2227 |
n.sendPeerState() |
| 2228 |
} |
| 2229 |
|
| 2230 |
// Update our known set of peers. |
| 2231 |
func (n *raft) UpdateKnownPeers(knownPeers []string) { |
| 2232 |
n.Lock() |
| 2233 |
n.updateKnownPeersLocked(knownPeers) |
| 2234 |
n.Unlock() |
| 2235 |
} |
| 2236 |
|
| 2237 |
func (n *raft) updateKnownPeersLocked(knownPeers []string) { |
| 2238 |
// Process like peer state update. |
| 2239 |
ps := &peerState{knownPeers, len(knownPeers), n.extSt} |
| 2240 |
n.processPeerState(ps) |
| 2241 |
} |
| 2242 |
|
| 2243 |
// ApplyQ returns the apply queue that new commits will be sent to for the |
| 2244 |
// upper layer to apply. |
| 2245 |
func (n *raft) ApplyQ() *ipQueue[*CommittedEntry] { return n.apply } |
| 2246 |
|
| 2247 |
// LeadChangeC returns the leader change channel, notifying when the Raft |
| 2248 |
// leader role has moved. |
| 2249 |
func (n *raft) LeadChangeC() <-chan leadChange { return n.leadc } |
| 2250 |
|
| 2251 |
// QuitC returns the quit channel, notifying when the Raft group has shut down. |
| 2252 |
func (n *raft) QuitC() <-chan struct{} { return n.quit } |
| 2253 |
|
| 2254 |
func (n *raft) Created() time.Time { |
| 2255 |
// Lock not needed as n.created is never changed after creation. |
| 2256 |
return n.created |
| 2257 |
} |
| 2258 |
|
| 2259 |
func (n *raft) Stop() { |
| 2260 |
n.shutdown() |
| 2261 |
} |
| 2262 |
|
| 2263 |
func (n *raft) WaitForStop() { |
| 2264 |
if n.state.Load() == int32(Closed) { |
| 2265 |
n.wg.Wait() |
| 2266 |
} |
| 2267 |
} |
| 2268 |
|
| 2269 |
func (n *raft) Delete() { |
| 2270 |
n.shutdown() |
| 2271 |
n.wg.Wait() |
| 2272 |
|
| 2273 |
n.Lock() |
| 2274 |
defer n.Unlock() |
| 2275 |
|
| 2276 |
n.deleted = true |
| 2277 |
if wal := n.wal; wal != nil { |
| 2278 |
wal.Delete(false) |
| 2279 |
} |
| 2280 |
os.RemoveAll(n.sd) |
| 2281 |
n.snapfile = _EMPTY_ |
| 2282 |
n.debug("Deleted") |
| 2283 |
} |
| 2284 |
|
| 2285 |
func (n *raft) IsDeleted() bool { |
| 2286 |
n.RLock() |
| 2287 |
defer n.RUnlock() |
| 2288 |
return n.deleted |
| 2289 |
} |
| 2290 |
|
| 2291 |
func (n *raft) shutdown() { |
| 2292 |
// First call to Stop or Delete should close the quit chan |
| 2293 |
// to notify the runAs goroutines to stop what they're doing. |
| 2294 |
if n.state.Swap(int32(Closed)) != int32(Closed) { |
| 2295 |
n.leaderState.Store(false) |
| 2296 |
n.leaderSince.Store(nil) |
| 2297 |
close(n.quit) |
| 2298 |
} |
| 2299 |
} |
| 2300 |
|
| 2301 |
// Reset discards this node's local raft state (log, snapshots, peer set, |
| 2302 |
// term/vote) so it can be caught up cleanly by another group with the same |
| 2303 |
// name. The caller is responsible for parking the node first (typically via |
| 2304 |
// SetObserver) if it should not compete for leadership immediately after; |
| 2305 |
// Reset itself steps the node down but does not flip observer mode. |
| 2306 |
func (n *raft) Reset() { |
| 2307 |
n.Lock() |
| 2308 |
defer n.Unlock() |
| 2309 |
|
| 2310 |
n.debug("Resetting Raft state") |
| 2311 |
|
| 2312 |
n.stepdownLocked(_EMPTY_) |
| 2313 |
|
| 2314 |
// Cancel any in-flight catchup so it does not race the reset. |
| 2315 |
n.cancelCatchup() |
| 2316 |
|
| 2317 |
// Drop proposals and inbound entries; they are no longer meaningful |
| 2318 |
// against whatever log this node ends up following. |
| 2319 |
n.prop.drain() |
| 2320 |
n.entry.drain() |
| 2321 |
n.resp.drain() |
| 2322 |
n.apply.drain() |
| 2323 |
n.reqs.drain() |
| 2324 |
n.votes.drain() |
| 2325 |
|
| 2326 |
// Remove every snapshot under our snapshots dir, not just the one referenced |
| 2327 |
// by n.snapfile. Orphans (e.g. from a crash between install and the previous |
| 2328 |
// file's removal) would otherwise be picked up by setupLastSnapshot on the |
| 2329 |
// next restart and reseed the state we are discarding here. |
| 2330 |
snapDir := filepath.Join(n.sd, snapshotsDir) |
| 2331 |
if err := os.RemoveAll(snapDir); err != nil { |
| 2332 |
n.warn("Error removing snapshots directory during reset: %v", err) |
| 2333 |
} |
| 2334 |
if err := os.MkdirAll(snapDir, defaultDirPerms); err != nil { |
| 2335 |
n.warn("Error recreating snapshots directory during reset: %v", err) |
| 2336 |
} |
| 2337 |
n.snapfile = _EMPTY_ |
| 2338 |
|
| 2339 |
// Abort any inflight async snapshot checkpoint. |
| 2340 |
n.snapshotting = false |
| 2341 |
|
| 2342 |
// Reset the WAL, but reset these first to not trip the assertion. |
| 2343 |
n.commit, n.hcommit, n.applied, n.processed, n.papplied = 0, 0, 0, 0, 0 |
| 2344 |
n.resetWAL() |
| 2345 |
|
| 2346 |
// Reset peer set to just ourselves; a new leader will fold us back into |
| 2347 |
// the cluster's membership view via processPeerState. |
| 2348 |
n.peers = map[string]*lps{n.id: {time.Time{}, 0}} |
| 2349 |
n.removed = nil |
| 2350 |
n.adjustClusterSizeAndQuorum() |
| 2351 |
|
| 2352 |
n.term, n.vote = 0, _EMPTY_ |
| 2353 |
n.writeTermVote() |
| 2354 |
|
| 2355 |
// Persist the cleared peer state so a restart picks up the reset. |
| 2356 |
n.writePeerState(n.currentPeerStateLocked()) |
| 2357 |
} |
| 2358 |
|
| 2359 |
const ( |
| 2360 |
raftAllSubj = "$NRG.>" |
| 2361 |
raftVoteSubj = "$NRG.V.%s" |
| 2362 |
raftAppendSubj = "$NRG.AE.%s" |
| 2363 |
raftPropSubj = "$NRG.P.%s" |
| 2364 |
raftRemovePeerSubj = "$NRG.RP.%s" |
| 2365 |
raftReply = "$NRG.R.%s" |
| 2366 |
raftCatchupReply = "$NRG.CR.%s" |
| 2367 |
// Catchup progress replies happen in their own subject space for |
| 2368 |
// flow control to the leader, but not counting toward quorum. |
| 2369 |
raftCatchupProgressReply = "$NRG.CP.%s" |
| 2370 |
raftCatchupProgressPre = "$NRG.CP." |
| 2371 |
) |
| 2372 |
|
| 2373 |
// Lock should be held (due to use of random generator) |
| 2374 |
func (n *raft) newCatchupInbox() string { |
| 2375 |
var b [replySuffixLen]byte |
| 2376 |
rn := fastrand.Uint64() |
| 2377 |
for i, l := 0, rn; i < len(b); i++ { |
| 2378 |
b[i] = digits[l%base] |
| 2379 |
l /= base |
| 2380 |
} |
| 2381 |
return fmt.Sprintf(raftCatchupReply, b[:]) |
| 2382 |
} |
| 2383 |
|
| 2384 |
// Lock should be held (due to use of random generator) |
| 2385 |
func (n *raft) newCatchupProgressInbox() string { |
| 2386 |
var b [replySuffixLen]byte |
| 2387 |
rn := fastrand.Uint64() |
| 2388 |
for i, l := 0, rn; i < len(b); i++ { |
| 2389 |
b[i] = digits[l%base] |
| 2390 |
l /= base |
| 2391 |
} |
| 2392 |
return fmt.Sprintf(raftCatchupProgressReply, b[:]) |
| 2393 |
} |
| 2394 |
|
| 2395 |
func (n *raft) newInbox() string { |
| 2396 |
var b [replySuffixLen]byte |
| 2397 |
rn := fastrand.Uint64() |
| 2398 |
for i, l := 0, rn; i < len(b); i++ { |
| 2399 |
b[i] = digits[l%base] |
| 2400 |
l /= base |
| 2401 |
} |
| 2402 |
return fmt.Sprintf(raftReply, b[:]) |
| 2403 |
} |
| 2404 |
|
| 2405 |
// Our internal subscribe. |
| 2406 |
// Lock should be held. |
| 2407 |
func (n *raft) subscribe(subject string, cb msgHandler) (*subscription, error) { |
| 2408 |
return n.t.Subscribe(subject, cb) |
| 2409 |
} |
| 2410 |
|
| 2411 |
// Lock should be held. |
| 2412 |
func (n *raft) unsubscribe(sub *subscription) { |
| 2413 |
n.t.Unsubscribe(sub) |
| 2414 |
} |
| 2415 |
|
| 2416 |
// Lock should be held. |
| 2417 |
func (n *raft) createInternalSubs() error { |
| 2418 |
n.vsubj, n.vreply = fmt.Sprintf(raftVoteSubj, n.group), n.newInbox() |
| 2419 |
n.asubj, n.areply = fmt.Sprintf(raftAppendSubj, n.group), n.newInbox() |
| 2420 |
n.psubj = fmt.Sprintf(raftPropSubj, n.group) |
| 2421 |
n.rpsubj = fmt.Sprintf(raftRemovePeerSubj, n.group) |
| 2422 |
|
| 2423 |
// Votes |
| 2424 |
if _, err := n.subscribe(n.vreply, n.handleVoteResponse); err != nil { |
| 2425 |
return err |
| 2426 |
} |
| 2427 |
if _, err := n.subscribe(n.vsubj, n.handleVoteRequest); err != nil { |
| 2428 |
return err |
| 2429 |
} |
| 2430 |
// AppendEntry |
| 2431 |
if _, err := n.subscribe(n.areply, n.handleAppendEntryResponse); err != nil { |
| 2432 |
return err |
| 2433 |
} |
| 2434 |
if sub, err := n.subscribe(n.asubj, n.handleAppendEntry); err != nil { |
| 2435 |
return err |
| 2436 |
} else { |
| 2437 |
n.aesub = sub |
| 2438 |
} |
| 2439 |
|
| 2440 |
return nil |
| 2441 |
} |
| 2442 |
|
| 2443 |
func randElectionTimeout() time.Duration { |
| 2444 |
delta := rand.Int63n(int64(maxElectionTimeout - minElectionTimeout)) |
| 2445 |
return (minElectionTimeout + time.Duration(delta)) |
| 2446 |
} |
| 2447 |
|
| 2448 |
// Lock should be held. |
| 2449 |
func (n *raft) resetElectionTimeout() { |
| 2450 |
n.resetElect(randElectionTimeout()) |
| 2451 |
} |
| 2452 |
|
| 2453 |
func (n *raft) resetElectionTimeoutWithLock() { |
| 2454 |
n.resetElectWithLock(randElectionTimeout()) |
| 2455 |
} |
| 2456 |
|
| 2457 |
// Lock should be held. |
| 2458 |
func (n *raft) resetElect(et time.Duration) { |
| 2459 |
n.etlr = time.Now() |
| 2460 |
if n.elect == nil { |
| 2461 |
n.elect = time.NewTimer(et) |
| 2462 |
} else { |
| 2463 |
if !n.elect.Stop() { |
| 2464 |
select { |
| 2465 |
case <-n.elect.C: |
| 2466 |
default: |
| 2467 |
} |
| 2468 |
} |
| 2469 |
n.elect.Reset(et) |
| 2470 |
} |
| 2471 |
} |
| 2472 |
|
| 2473 |
func (n *raft) resetElectWithLock(et time.Duration) { |
| 2474 |
n.Lock() |
| 2475 |
n.resetElect(et) |
| 2476 |
n.Unlock() |
| 2477 |
} |
| 2478 |
|
| 2479 |
// run is the top-level runner for the Raft state machine. Depending on the |
| 2480 |
// state of the node (leader, follower, candidate, observer), this will call |
| 2481 |
// through to other functions. It is expected that this function will run for |
| 2482 |
// the entire life of the Raft node once started. |
| 2483 |
func (n *raft) run() { |
| 2484 |
s := n.s |
| 2485 |
defer s.grWG.Done() |
| 2486 |
defer n.wg.Done() |
| 2487 |
|
| 2488 |
// We want to wait for some routing to be enabled, so we will wait for |
| 2489 |
// at least a route, leaf or gateway connection to be established before |
| 2490 |
// starting the run loop. |
| 2491 |
for gw := s.gateway; ; { |
| 2492 |
s.mu.RLock() |
| 2493 |
ready, gwEnabled := s.numRemotes()+len(s.leafs) > 0, gw.enabled |
| 2494 |
s.mu.RUnlock() |
| 2495 |
if !ready && gwEnabled { |
| 2496 |
gw.RLock() |
| 2497 |
ready = len(gw.out)+len(gw.in) > 0 |
| 2498 |
gw.RUnlock() |
| 2499 |
} |
| 2500 |
if !ready { |
| 2501 |
select { |
| 2502 |
case <-s.quitCh: |
| 2503 |
return |
| 2504 |
case <-time.After(100 * time.Millisecond): |
| 2505 |
s.RateLimitWarnf("Waiting for routing to be established...") |
| 2506 |
} |
| 2507 |
} else { |
| 2508 |
break |
| 2509 |
} |
| 2510 |
} |
| 2511 |
|
| 2512 |
// We may have paused adding entries to apply queue, resume here. |
| 2513 |
// No-op if not paused. |
| 2514 |
n.ResumeApply() |
| 2515 |
|
| 2516 |
// Send nil entry to signal the upper layers we are done doing replay/restore. |
| 2517 |
n.apply.push(nil) |
| 2518 |
|
| 2519 |
runner: |
| 2520 |
for { |
| 2521 |
switch n.State() { |
| 2522 |
case Follower: |
| 2523 |
n.runAsFollower() |
| 2524 |
case Candidate: |
| 2525 |
n.runAsCandidate() |
| 2526 |
case Leader: |
| 2527 |
n.runAsLeader() |
| 2528 |
case Closed: |
| 2529 |
break runner |
| 2530 |
} |
| 2531 |
} |
| 2532 |
|
| 2533 |
// If we've reached this point then we're shutting down, either because |
| 2534 |
// the server is stopping or because the Raft group is closing/closed. |
| 2535 |
n.Lock() |
| 2536 |
defer n.Unlock() |
| 2537 |
|
| 2538 |
n.t.Close() |
| 2539 |
|
| 2540 |
// Unregistering ipQueues do not prevent them from push/pop |
| 2541 |
// just will remove them from the central monitoring map |
| 2542 |
queues := []interface { |
| 2543 |
unregister() |
| 2544 |
drain() int |
| 2545 |
}{n.reqs, n.votes, n.prop, n.entry, n.resp, n.apply} |
| 2546 |
for _, q := range queues { |
| 2547 |
q.drain() |
| 2548 |
q.unregister() |
| 2549 |
} |
| 2550 |
|
| 2551 |
n.s.unregisterRaftNode(n.group) |
| 2552 |
|
| 2553 |
if wal := n.wal; wal != nil { |
| 2554 |
wal.Stop() |
| 2555 |
} |
| 2556 |
|
| 2557 |
n.debug("Shutdown") |
| 2558 |
} |
| 2559 |
|
| 2560 |
func (n *raft) debug(format string, args ...any) { |
| 2561 |
if n.dflag { |
| 2562 |
nf := fmt.Sprintf("RAFT [%s - %s] %s", n.id, n.group, format) |
| 2563 |
n.s.Debugf(nf, args...) |
| 2564 |
} |
| 2565 |
} |
| 2566 |
|
| 2567 |
func (n *raft) warn(format string, args ...any) { |
| 2568 |
nf := fmt.Sprintf("RAFT [%s - %s] %s", n.id, n.group, format) |
| 2569 |
n.s.RateLimitWarnf(nf, args...) |
| 2570 |
} |
| 2571 |
|
| 2572 |
func (n *raft) error(format string, args ...any) { |
| 2573 |
nf := fmt.Sprintf("RAFT [%s - %s] %s", n.id, n.group, format) |
| 2574 |
n.s.Errorf(nf, args...) |
| 2575 |
} |
| 2576 |
|
| 2577 |
func (n *raft) electTimer() *time.Timer { |
| 2578 |
n.RLock() |
| 2579 |
defer n.RUnlock() |
| 2580 |
return n.elect |
| 2581 |
} |
| 2582 |
|
| 2583 |
func (n *raft) IsObserver() bool { |
| 2584 |
n.RLock() |
| 2585 |
defer n.RUnlock() |
| 2586 |
return n.observer |
| 2587 |
} |
| 2588 |
|
| 2589 |
// Sets the state to observer only. |
| 2590 |
func (n *raft) SetObserver(isObserver bool) { |
| 2591 |
n.setObserver(isObserver, extUndetermined) |
| 2592 |
} |
| 2593 |
|
| 2594 |
func (n *raft) setObserver(isObserver bool, extSt extensionState) { |
| 2595 |
n.Lock() |
| 2596 |
defer n.Unlock() |
| 2597 |
n.setObserverLocked(isObserver, extSt) |
| 2598 |
} |
| 2599 |
|
| 2600 |
func (n *raft) setObserverLocked(isObserver bool, extSt extensionState) { |
| 2601 |
wasObserver := n.observer |
| 2602 |
n.observer = isObserver |
| 2603 |
n.extSt = extSt |
| 2604 |
|
| 2605 |
// If we're leaving observer state then reset the election timer or |
| 2606 |
// we might end up waiting for up to the observerModeInterval. |
| 2607 |
if wasObserver && !isObserver { |
| 2608 |
n.resetElect(randElectionTimeout()) |
| 2609 |
} |
| 2610 |
} |
| 2611 |
|
| 2612 |
// processAppendEntries is called by the Raft state machine when there are |
| 2613 |
// new append entries to be committed and sent to the upper state machine. |
| 2614 |
func (n *raft) processAppendEntries() { |
| 2615 |
canProcess := true |
| 2616 |
if n.isClosed() { |
| 2617 |
n.debug("AppendEntry not processing inbound, closed") |
| 2618 |
canProcess = false |
| 2619 |
} |
| 2620 |
if n.outOfResources() { |
| 2621 |
n.debug("AppendEntry not processing inbound, no resources") |
| 2622 |
canProcess = false |
| 2623 |
} |
| 2624 |
// Always pop the entries, but check if we can process them. If we can't |
| 2625 |
// then the entries are effectively dropped. |
| 2626 |
aes := n.entry.pop() |
| 2627 |
if canProcess { |
| 2628 |
for _, ae := range aes { |
| 2629 |
n.processAppendEntry(ae, ae.sub) |
| 2630 |
} |
| 2631 |
} |
| 2632 |
n.entry.recycle(&aes) |
| 2633 |
} |
| 2634 |
|
| 2635 |
// runAsFollower is called by run and will block for as long as the node is |
| 2636 |
// running in the follower state. |
| 2637 |
func (n *raft) runAsFollower() { |
| 2638 |
for n.State() == Follower { |
| 2639 |
elect := n.electTimer() |
| 2640 |
|
| 2641 |
select { |
| 2642 |
case <-n.entry.ch: |
| 2643 |
// New append entries have arrived over the network. |
| 2644 |
n.processAppendEntries() |
| 2645 |
case <-n.s.quitCh: |
| 2646 |
// The server is shutting down. |
| 2647 |
return |
| 2648 |
case <-n.quit: |
| 2649 |
// The Raft node is shutting down. |
| 2650 |
return |
| 2651 |
case <-elect.C: |
| 2652 |
// The election timer has fired so we think it's time to call an election. |
| 2653 |
// If we are out of resources we just want to stay in this state for the moment. |
| 2654 |
if n.outOfResources() { |
| 2655 |
n.resetElectionTimeoutWithLock() |
| 2656 |
n.debug("Not switching to candidate, no resources") |
| 2657 |
} else if n.IsObserver() { |
| 2658 |
n.resetElectWithLock(observerModeInterval) |
| 2659 |
n.debug("Not switching to candidate, observer only") |
| 2660 |
} else if n.isCatchingUp() { |
| 2661 |
n.debug("Not switching to candidate, catching up") |
| 2662 |
// Check to see if our catchup has stalled. |
| 2663 |
n.Lock() |
| 2664 |
if n.catchupStalled() { |
| 2665 |
n.cancelCatchup() |
| 2666 |
} |
| 2667 |
n.resetElectionTimeout() |
| 2668 |
n.Unlock() |
| 2669 |
} else { |
| 2670 |
n.switchToCandidate() |
| 2671 |
return |
| 2672 |
} |
| 2673 |
case <-n.votes.ch: |
| 2674 |
// We're receiving votes from the network, probably because we have only |
| 2675 |
// just stepped down and they were already in flight. Ignore them. |
| 2676 |
n.debug("Ignoring old vote response, we have stepped down") |
| 2677 |
n.votes.popOne() |
| 2678 |
case <-n.resp.ch: |
| 2679 |
// Ignore append entry responses received from before the state change. |
| 2680 |
n.resp.drain() |
| 2681 |
case <-n.prop.ch: |
| 2682 |
// Ignore proposals received from before the state change. |
| 2683 |
n.prop.drain() |
| 2684 |
case <-n.reqs.ch: |
| 2685 |
// We've just received a vote request from the network. |
| 2686 |
// Because of drain() it is possible that we get nil from popOne(). |
| 2687 |
if voteReq, ok := n.reqs.popOne(); ok { |
| 2688 |
n.processVoteRequest(voteReq) |
| 2689 |
} |
| 2690 |
} |
| 2691 |
} |
| 2692 |
} |
| 2693 |
|
| 2694 |
// Pool for CommittedEntry re-use. |
| 2695 |
var cePool = sync.Pool{ |
| 2696 |
New: func() any { |
| 2697 |
return &CommittedEntry{} |
| 2698 |
}, |
| 2699 |
} |
| 2700 |
|
| 2701 |
// CommittedEntry is handed back to the user to apply a commit to their upper layer. |
| 2702 |
type CommittedEntry struct { |
| 2703 |
Index uint64 |
| 2704 |
Entries []*Entry |
| 2705 |
} |
| 2706 |
|
| 2707 |
// Create a new CommittedEntry. When the returned entry is no longer needed, it |
| 2708 |
// should be returned to the pool by calling ReturnToPool. |
| 2709 |
func newCommittedEntry(index uint64, entries []*Entry) *CommittedEntry { |
| 2710 |
ce := cePool.Get().(*CommittedEntry) |
| 2711 |
ce.Index, ce.Entries = index, entries |
| 2712 |
return ce |
| 2713 |
} |
| 2714 |
|
| 2715 |
// ReturnToPool returns the CommittedEntry to the pool, after which point it is |
| 2716 |
// no longer safe to reuse. |
| 2717 |
func (ce *CommittedEntry) ReturnToPool() { |
| 2718 |
if ce == nil { |
| 2719 |
return |
| 2720 |
} |
| 2721 |
if len(ce.Entries) > 0 { |
| 2722 |
for _, e := range ce.Entries { |
| 2723 |
entryPool.Put(e) |
| 2724 |
} |
| 2725 |
} |
| 2726 |
ce.Index, ce.Entries = 0, nil |
| 2727 |
cePool.Put(ce) |
| 2728 |
} |
| 2729 |
|
| 2730 |
// Pool for Entry re-use. |
| 2731 |
var entryPool = sync.Pool{ |
| 2732 |
New: func() any { |
| 2733 |
return &Entry{} |
| 2734 |
}, |
| 2735 |
} |
| 2736 |
|
| 2737 |
// Helper to create new entries. When the returned entry is no longer needed, it |
| 2738 |
// should be returned to the entryPool pool. |
| 2739 |
func newEntry(t EntryType, data []byte) *Entry { |
| 2740 |
entry := entryPool.Get().(*Entry) |
| 2741 |
entry.Type, entry.Data = t, data |
| 2742 |
return entry |
| 2743 |
} |
| 2744 |
|
| 2745 |
// Pool for appendEntry re-use. |
| 2746 |
var aePool = sync.Pool{ |
| 2747 |
New: func() any { |
| 2748 |
return &appendEntry{} |
| 2749 |
}, |
| 2750 |
} |
| 2751 |
|
| 2752 |
// appendEntry is the main struct that is used to sync raft peers. |
| 2753 |
type appendEntry struct { |
| 2754 |
leader string // The leader that this append entry came from. |
| 2755 |
term uint64 // The term when this entry was stored. |
| 2756 |
commit uint64 // The commit index of the leader when this append entry was sent. |
| 2757 |
pterm uint64 // The previous term, for checking consistency. |
| 2758 |
pindex uint64 // The previous commit index, for checking consistency. |
| 2759 |
entries []*Entry // Entries to process. |
| 2760 |
// Below fields are for internal use only: |
| 2761 |
lterm uint64 // The highest term for catchups only, as the leader understands it. (If lterm=0, use term instead) |
| 2762 |
reply string // Reply subject to respond to once committed. |
| 2763 |
sub *subscription // The subscription that the append entry came in on. |
| 2764 |
buf []byte |
| 2765 |
} |
| 2766 |
|
| 2767 |
// Create a new appendEntry. |
| 2768 |
func newAppendEntry(leader string, term, commit, pterm, pindex uint64, entries []*Entry) *appendEntry { |
| 2769 |
ae := aePool.Get().(*appendEntry) |
| 2770 |
ae.leader, ae.term, ae.commit, ae.pterm, ae.pindex, ae.entries = leader, term, commit, pterm, pindex, entries |
| 2771 |
ae.lterm, ae.reply, ae.sub, ae.buf = 0, _EMPTY_, nil, nil |
| 2772 |
return ae |
| 2773 |
} |
| 2774 |
|
| 2775 |
// Will return this append entry, and its interior entries to their respective pools. |
| 2776 |
func (ae *appendEntry) returnToPool() { |
| 2777 |
ae.entries, ae.buf, ae.sub, ae.reply = nil, nil, nil, _EMPTY_ |
| 2778 |
aePool.Put(ae) |
| 2779 |
} |
| 2780 |
|
| 2781 |
// Pool for proposedEntry re-use. |
| 2782 |
var pePool = sync.Pool{ |
| 2783 |
New: func() any { |
| 2784 |
return &proposedEntry{} |
| 2785 |
}, |
| 2786 |
} |
| 2787 |
|
| 2788 |
// Create a new proposedEntry. |
| 2789 |
func newProposedEntry(entry *Entry, reply string) *proposedEntry { |
| 2790 |
pe := pePool.Get().(*proposedEntry) |
| 2791 |
pe.Entry, pe.reply = entry, reply |
| 2792 |
return pe |
| 2793 |
} |
| 2794 |
|
| 2795 |
// Will return this proosed entry. |
| 2796 |
func (pe *proposedEntry) returnToPool() { |
| 2797 |
pe.Entry, pe.reply = nil, _EMPTY_ |
| 2798 |
pePool.Put(pe) |
| 2799 |
} |
| 2800 |
|
| 2801 |
type EntryType uint8 |
| 2802 |
|
| 2803 |
const ( |
| 2804 |
EntryNormal EntryType = iota |
| 2805 |
EntryOldSnapshot |
| 2806 |
EntryPeerState |
| 2807 |
EntryAddPeer |
| 2808 |
EntryRemovePeer |
| 2809 |
EntryLeaderTransfer |
| 2810 |
EntrySnapshot |
| 2811 |
// EntryCatchup signals an internal type used to signal a Raft-level catchup has started. |
| 2812 |
// After the catchup completes (or is canceled), a nil entry will be sent to signal this. |
| 2813 |
// This type of entry is purely internal and not transmitted between peers or stored in the log. |
| 2814 |
EntryCatchup |
| 2815 |
) |
| 2816 |
|
| 2817 |
func (t EntryType) String() string { |
| 2818 |
switch t { |
| 2819 |
case EntryNormal: |
| 2820 |
return "Normal" |
| 2821 |
case EntryOldSnapshot: |
| 2822 |
return "OldSnapshot" |
| 2823 |
case EntryPeerState: |
| 2824 |
return "PeerState" |
| 2825 |
case EntryAddPeer: |
| 2826 |
return "AddPeer" |
| 2827 |
case EntryRemovePeer: |
| 2828 |
return "RemovePeer" |
| 2829 |
case EntryLeaderTransfer: |
| 2830 |
return "LeaderTransfer" |
| 2831 |
case EntrySnapshot: |
| 2832 |
return "Snapshot" |
| 2833 |
} |
| 2834 |
return fmt.Sprintf("Unknown [%d]", uint8(t)) |
| 2835 |
} |
| 2836 |
|
| 2837 |
type Entry struct { |
| 2838 |
Type EntryType |
| 2839 |
Data []byte |
| 2840 |
} |
| 2841 |
|
| 2842 |
func (e *Entry) ChangesMembership() bool { |
| 2843 |
switch e.Type { |
| 2844 |
case EntryAddPeer, EntryRemovePeer: |
| 2845 |
return true |
| 2846 |
default: |
| 2847 |
return false |
| 2848 |
} |
| 2849 |
} |
| 2850 |
|
| 2851 |
func (ae *appendEntry) String() string { |
| 2852 |
return fmt.Sprintf("&{leader:%s term:%d commit:%d pterm:%d pindex:%d entries: %d}", |
| 2853 |
ae.leader, ae.term, ae.commit, ae.pterm, ae.pindex, len(ae.entries)) |
| 2854 |
} |
| 2855 |
|
| 2856 |
const appendEntryBaseLen = idLen + 4*8 + 2 |
| 2857 |
|
| 2858 |
func (ae *appendEntry) encode(b []byte) ([]byte, error) { |
| 2859 |
if ll := len(ae.leader); ll != idLen && ll != 0 { |
| 2860 |
return nil, errLeaderLen |
| 2861 |
} |
| 2862 |
if len(ae.entries) > math.MaxUint16 { |
| 2863 |
return nil, errTooManyEntries |
| 2864 |
} |
| 2865 |
|
| 2866 |
var elen uint64 |
| 2867 |
for _, e := range ae.entries { |
| 2868 |
// MaxInt32 instead of MaxUint32 deliberate here to stop int |
| 2869 |
// overflow on 32-bit platforms, still gives us ~2GB limit. |
| 2870 |
ulen := uint64(len(e.Data)) |
| 2871 |
if ulen > math.MaxInt32 { |
| 2872 |
return nil, errBadAppendEntry |
| 2873 |
} |
| 2874 |
elen += ulen + 1 + 4 // 1 is type, 4 is for size. |
| 2875 |
} |
| 2876 |
// Uvarint for lterm can be a maximum 10 bytes for a uint64. |
| 2877 |
var _lterm [10]byte |
| 2878 |
lterm := _lterm[:binary.PutUvarint(_lterm[:], ae.lterm)] |
| 2879 |
tlen := appendEntryBaseLen + elen + uint64(len(lterm)) |
| 2880 |
|
| 2881 |
var buf []byte |
| 2882 |
if uint64(cap(b)) >= tlen { |
| 2883 |
buf = b[:idLen] |
| 2884 |
} else { |
| 2885 |
buf = make([]byte, idLen, tlen) |
| 2886 |
} |
| 2887 |
|
| 2888 |
var le = binary.LittleEndian |
| 2889 |
copy(buf[:idLen], ae.leader) |
| 2890 |
buf = le.AppendUint64(buf, ae.term) |
| 2891 |
buf = le.AppendUint64(buf, ae.commit) |
| 2892 |
buf = le.AppendUint64(buf, ae.pterm) |
| 2893 |
buf = le.AppendUint64(buf, ae.pindex) |
| 2894 |
buf = le.AppendUint16(buf, uint16(len(ae.entries))) |
| 2895 |
for _, e := range ae.entries { |
| 2896 |
// The +1 is safe here as we've already checked len(e.Data) |
| 2897 |
// is not greater than MaxInt32, which is less than MaxUint32. |
| 2898 |
buf = le.AppendUint32(buf, uint32(1+len(e.Data))) |
| 2899 |
buf = append(buf, byte(e.Type)) |
| 2900 |
buf = append(buf, e.Data...) |
| 2901 |
} |
| 2902 |
// This is safe because old nodes will ignore bytes after the |
| 2903 |
// encoded messages. Nodes that are aware of this will decode |
| 2904 |
// it correctly. |
| 2905 |
buf = append(buf, lterm...) |
| 2906 |
return buf, nil |
| 2907 |
} |
| 2908 |
|
| 2909 |
// This can not be used post the wire level callback since we do not copy. |
| 2910 |
func decodeAppendEntry(msg []byte, sub *subscription, reply string) (*appendEntry, error) { |
| 2911 |
if len(msg) < appendEntryBaseLen { |
| 2912 |
return nil, errBadAppendEntry |
| 2913 |
} |
| 2914 |
|
| 2915 |
var le = binary.LittleEndian |
| 2916 |
|
| 2917 |
ae := newAppendEntry(string(msg[:idLen]), le.Uint64(msg[8:]), le.Uint64(msg[16:]), le.Uint64(msg[24:]), le.Uint64(msg[32:]), nil) |
| 2918 |
ae.reply, ae.sub = reply, sub |
| 2919 |
|
| 2920 |
// Decode Entries. |
| 2921 |
ne, ri := int(le.Uint16(msg[40:])), uint64(appendEntryBaseLen) |
| 2922 |
for i, max := 0, uint64(len(msg)); i < ne; i++ { |
| 2923 |
if max-ri < 4 { |
| 2924 |
return nil, errBadAppendEntry |
| 2925 |
} |
| 2926 |
ml := uint64(le.Uint32(msg[ri:])) |
| 2927 |
ri += 4 |
| 2928 |
if ml <= 0 || ri+ml > max { |
| 2929 |
return nil, errBadAppendEntry |
| 2930 |
} |
| 2931 |
entry := newEntry(EntryType(msg[ri]), msg[ri+1:ri+ml]) |
| 2932 |
ae.entries = append(ae.entries, entry) |
| 2933 |
ri += ml |
| 2934 |
} |
| 2935 |
if len(msg[ri:]) > 0 { |
| 2936 |
if lterm, n := binary.Uvarint(msg[ri:]); n > 0 { |
| 2937 |
ae.lterm = lterm |
| 2938 |
} |
| 2939 |
} |
| 2940 |
ae.buf = msg |
| 2941 |
return ae, nil |
| 2942 |
} |
| 2943 |
|
| 2944 |
// Pool for appendEntryResponse re-use. |
| 2945 |
var arPool = sync.Pool{ |
| 2946 |
New: func() any { |
| 2947 |
return &appendEntryResponse{} |
| 2948 |
}, |
| 2949 |
} |
| 2950 |
|
| 2951 |
// We want to make sure this does not change from system changing length of syshash. |
| 2952 |
const idLen = 8 |
| 2953 |
const appendEntryResponseLen = 24 + 1 |
| 2954 |
|
| 2955 |
// appendEntryResponse is our response to a received appendEntry. |
| 2956 |
type appendEntryResponse struct { |
| 2957 |
term uint64 |
| 2958 |
index uint64 |
| 2959 |
peer string |
| 2960 |
reply string // internal usage. |
| 2961 |
success bool |
| 2962 |
} |
| 2963 |
|
| 2964 |
// Create a new appendEntryResponse. |
| 2965 |
func newAppendEntryResponse(term, index uint64, peer string, success bool) *appendEntryResponse { |
| 2966 |
ar := arPool.Get().(*appendEntryResponse) |
| 2967 |
ar.term, ar.index, ar.peer, ar.success = term, index, peer, success |
| 2968 |
// Always empty out. |
| 2969 |
ar.reply = _EMPTY_ |
| 2970 |
return ar |
| 2971 |
} |
| 2972 |
|
| 2973 |
func (ar *appendEntryResponse) encode(b []byte) []byte { |
| 2974 |
var buf []byte |
| 2975 |
if cap(b) >= appendEntryResponseLen { |
| 2976 |
buf = b[:appendEntryResponseLen] |
| 2977 |
} else { |
| 2978 |
buf = make([]byte, appendEntryResponseLen) |
| 2979 |
} |
| 2980 |
var le = binary.LittleEndian |
| 2981 |
le.PutUint64(buf[0:], ar.term) |
| 2982 |
le.PutUint64(buf[8:], ar.index) |
| 2983 |
copy(buf[16:16+idLen], ar.peer) |
| 2984 |
if ar.success { |
| 2985 |
buf[24] = 1 |
| 2986 |
} else { |
| 2987 |
buf[24] = 0 |
| 2988 |
} |
| 2989 |
return buf[:appendEntryResponseLen] |
| 2990 |
} |
| 2991 |
|
| 2992 |
// Track all peers we may have ever seen to use an string interns for appendEntryResponse decoding. |
| 2993 |
var peers sync.Map |
| 2994 |
|
| 2995 |
func decodeAppendEntryResponse(msg []byte) *appendEntryResponse { |
| 2996 |
if len(msg) != appendEntryResponseLen { |
| 2997 |
return nil |
| 2998 |
} |
| 2999 |
var le = binary.LittleEndian |
| 3000 |
ar := arPool.Get().(*appendEntryResponse) |
| 3001 |
ar.term = le.Uint64(msg[0:]) |
| 3002 |
ar.index = le.Uint64(msg[8:]) |
| 3003 |
|
| 3004 |
peer, ok := peers.Load(string(msg[16 : 16+idLen])) |
| 3005 |
if !ok { |
| 3006 |
// We missed so store inline here. |
| 3007 |
peer = string(msg[16 : 16+idLen]) |
| 3008 |
peers.Store(peer, peer) |
| 3009 |
} |
| 3010 |
ar.peer = peer.(string) |
| 3011 |
ar.success = msg[24] == 1 |
| 3012 |
return ar |
| 3013 |
} |
| 3014 |
|
| 3015 |
// Called when a remove peer proposal has been forwarded |
| 3016 |
func (n *raft) handleForwardedRemovePeerProposal(sub *subscription, c *client, _ *Account, _, reply string, msg []byte) { |
| 3017 |
n.debug("Received forwarded remove peer proposal: %q", msg) |
| 3018 |
|
| 3019 |
if len(msg) != idLen { |
| 3020 |
n.warn("Received invalid peer name for remove proposal: %q", msg) |
| 3021 |
return |
| 3022 |
} |
| 3023 |
|
| 3024 |
n.RLock() |
| 3025 |
// Check state under lock, we might not be leader anymore. |
| 3026 |
if n.State() != Leader || !n.leaderState.Load() { |
| 3027 |
n.debug("Ignoring forwarded peer removal proposal, not leader") |
| 3028 |
n.RUnlock() |
| 3029 |
return |
| 3030 |
} |
| 3031 |
// Error if we had a previous write error. |
| 3032 |
if werr := n.werr; werr != nil { |
| 3033 |
n.RUnlock() |
| 3034 |
return |
| 3035 |
} |
| 3036 |
if n.membChange != nil { |
| 3037 |
n.debug("Ignoring forwarded peer removal proposal, membership changing") |
| 3038 |
n.RUnlock() |
| 3039 |
return |
| 3040 |
} |
| 3041 |
if _, ok := n.peers[string(msg)]; !ok { |
| 3042 |
n.debug("Ignoring forwarded peer removal proposal, peer not found") |
| 3043 |
n.RUnlock() |
| 3044 |
return |
| 3045 |
} |
| 3046 |
if len(n.peers) <= 1 { |
| 3047 |
n.debug("Ignoring forwarded peer removal proposal, remove last node") |
| 3048 |
n.RUnlock() |
| 3049 |
return |
| 3050 |
} |
| 3051 |
prop := n.prop |
| 3052 |
n.RUnlock() |
| 3053 |
|
| 3054 |
// Need to copy since this is underlying client/route buffer. |
| 3055 |
peer := copyBytes(msg) |
| 3056 |
prop.push(newProposedEntry(newEntry(EntryRemovePeer, peer), reply)) |
| 3057 |
} |
| 3058 |
|
| 3059 |
// Called when a peer has forwarded a proposal. |
| 3060 |
func (n *raft) handleForwardedProposal(sub *subscription, c *client, _ *Account, _, reply string, msg []byte) { |
| 3061 |
// Need to copy since this is underlying client/route buffer. |
| 3062 |
msg = copyBytes(msg) |
| 3063 |
|
| 3064 |
n.RLock() |
| 3065 |
prop := n.prop |
| 3066 |
// Check state under lock, we might not be leader anymore. |
| 3067 |
if n.State() != Leader || !n.leaderState.Load() { |
| 3068 |
n.debug("Ignoring forwarded proposal, not leader") |
| 3069 |
n.RUnlock() |
| 3070 |
return |
| 3071 |
} |
| 3072 |
|
| 3073 |
// Ignore if we have had a write error previous. |
| 3074 |
if n.werr != nil { |
| 3075 |
n.RUnlock() |
| 3076 |
return |
| 3077 |
} |
| 3078 |
|
| 3079 |
if n.isLeaderOverrun() { |
| 3080 |
n.RUnlock() |
| 3081 |
n.Lock() |
| 3082 |
defer n.Unlock() |
| 3083 |
// Now that we've reacquired as write lock, we need to make sure that everything we |
| 3084 |
// believed before is still true. Otherwise we've either stepped down already from |
| 3085 |
// another goroutine or we've stopped being overrun and shouldn't drop the entry. |
| 3086 |
if n.State() != Leader || !n.leaderState.Load() { |
| 3087 |
return |
| 3088 |
} else if !n.isLeaderOverrun() { |
| 3089 |
prop.push(newProposedEntry(newEntry(EntryNormal, msg), reply)) |
| 3090 |
return |
| 3091 |
} |
| 3092 |
var state StreamState |
| 3093 |
n.wal.FastState(&state) |
| 3094 |
n.warn("Leader falling behind, stepping down: pindex %d, commit %d, applied %d, WAL size %s", n.pindex, n.commit, n.applied, friendlyBytes(state.Bytes)) |
| 3095 |
// Stepdown without leader transfer, likely all replicas will be overrun, and we need time to recover. |
| 3096 |
n.stepdownLocked(noLeader) |
| 3097 |
n.overrunCount++ |
| 3098 |
return |
| 3099 |
} |
| 3100 |
// Possible that we could fall through to here from multiple connections but if |
| 3101 |
// one does end up stepping down then the proposal queue gets drained anyway. |
| 3102 |
n.RUnlock() |
| 3103 |
prop.push(newProposedEntry(newEntry(EntryNormal, msg), reply)) |
| 3104 |
} |
| 3105 |
|
| 3106 |
// Adds peer with the given id to our membership, |
| 3107 |
// and adjusts cluster size and quorum accordingly. |
| 3108 |
// Lock should be held. |
| 3109 |
func (n *raft) addPeer(peer string) { |
| 3110 |
// If we were on the removed list reverse that here. |
| 3111 |
if n.removed != nil { |
| 3112 |
delete(n.removed, peer) |
| 3113 |
if len(n.removed) == 0 { |
| 3114 |
n.removed = nil |
| 3115 |
} |
| 3116 |
} |
| 3117 |
|
| 3118 |
if _, ok := n.peers[peer]; !ok { |
| 3119 |
// We are not tracking this one automatically so we need |
| 3120 |
// to bump cluster size. |
| 3121 |
n.peers[peer] = &lps{time.Time{}, 0} |
| 3122 |
} |
| 3123 |
// Adjust cluster size and quorum if needed. |
| 3124 |
n.adjustClusterSizeAndQuorum() |
| 3125 |
// Write out our new state. |
| 3126 |
n.writePeerState(&peerState{n.peerNames(), n.csz, n.extSt}) |
| 3127 |
} |
| 3128 |
|
| 3129 |
// Remove the peer with the given id from our membership, |
| 3130 |
// and adjusts cluster size and quorum accordingly. |
| 3131 |
// Lock should be held. |
| 3132 |
func (n *raft) removePeer(peer string) { |
| 3133 |
if n.removed == nil { |
| 3134 |
n.removed = map[string]time.Time{} |
| 3135 |
} |
| 3136 |
n.removed[peer] = time.Now() |
| 3137 |
|
| 3138 |
delete(n.peers, peer) |
| 3139 |
n.adjustClusterSizeAndQuorum() |
| 3140 |
n.writePeerState(&peerState{n.peerNames(), n.csz, n.extSt}) |
| 3141 |
} |
| 3142 |
|
| 3143 |
// Build and send appendEntry request for the given entry that changes |
| 3144 |
// membership (EntryAddPeer / EntryRemovePeer). |
| 3145 |
// Returns true if the entry made it to the WAL and was sent to the followers |
| 3146 |
func (n *raft) sendMembershipChange(e *Entry) bool { |
| 3147 |
n.Lock() |
| 3148 |
defer n.Unlock() |
| 3149 |
|
| 3150 |
// Only makes sense to call this with entries that change membership. |
| 3151 |
// Also, ignore if we're already changing membership. |
| 3152 |
if !e.ChangesMembership() || n.membChange != nil { |
| 3153 |
return false |
| 3154 |
} |
| 3155 |
|
| 3156 |
// Set to the index where we will store the membership change. |
| 3157 |
// It needs to be before we send, since if we're cluster size 1 we try to commit immediately. |
| 3158 |
peer := string(e.Data) |
| 3159 |
n.membChange = &membChange{index: n.pindex + 1, peer: peer} |
| 3160 |
ps := n.peers[peer] |
| 3161 |
// Ignore if the peer already exists (add) or is not found (remove). |
| 3162 |
if (e.Type == EntryAddPeer && ps != nil) || (e.Type == EntryRemovePeer && ps == nil) { |
| 3163 |
n.membChange = nil |
| 3164 |
return false |
| 3165 |
} |
| 3166 |
if e.Type == EntryRemovePeer { |
| 3167 |
n.membChange.prev = ps |
| 3168 |
} |
| 3169 |
err := n.sendAppendEntryLocked([]*Entry{e}, true) |
| 3170 |
if err != nil { |
| 3171 |
n.membChange = nil |
| 3172 |
return false |
| 3173 |
} |
| 3174 |
|
| 3175 |
if e.Type == EntryAddPeer { |
| 3176 |
// Track directly, but wait for commit to be official |
| 3177 |
if _, ok := n.peers[peer]; !ok { |
| 3178 |
n.peers[peer] = &lps{time.Time{}, 0} |
| 3179 |
n.adjustClusterSizeAndQuorum() |
| 3180 |
} |
| 3181 |
} |
| 3182 |
|
| 3183 |
if e.Type == EntryRemovePeer { |
| 3184 |
// Track directly, but wait for commit to be official |
| 3185 |
if _, ok := n.peers[peer]; ok { |
| 3186 |
delete(n.peers, peer) |
| 3187 |
n.adjustClusterSizeAndQuorum() |
| 3188 |
} |
| 3189 |
if n.csz == 1 { |
| 3190 |
n.tryCommit(n.pindex) |
| 3191 |
return true |
| 3192 |
} |
| 3193 |
} |
| 3194 |
return true |
| 3195 |
} |
| 3196 |
|
| 3197 |
func (n *raft) runAsLeader() { |
| 3198 |
if n.State() == Closed { |
| 3199 |
return |
| 3200 |
} |
| 3201 |
|
| 3202 |
n.Lock() |
| 3203 |
psubj, rpsubj := n.psubj, n.rpsubj |
| 3204 |
|
| 3205 |
// For forwarded proposals, both normal and remove peer proposals. |
| 3206 |
fsub, err := n.subscribe(psubj, n.handleForwardedProposal) |
| 3207 |
if err != nil { |
| 3208 |
n.warn("Error subscribing to forwarded proposals: %v", err) |
| 3209 |
n.stepdownLocked(noLeader) |
| 3210 |
n.Unlock() |
| 3211 |
return |
| 3212 |
} |
| 3213 |
rpsub, err := n.subscribe(rpsubj, n.handleForwardedRemovePeerProposal) |
| 3214 |
if err != nil { |
| 3215 |
n.warn("Error subscribing to forwarded remove peer proposals: %v", err) |
| 3216 |
n.unsubscribe(fsub) |
| 3217 |
n.stepdownLocked(noLeader) |
| 3218 |
n.Unlock() |
| 3219 |
return |
| 3220 |
} |
| 3221 |
|
| 3222 |
// Cleanup our subscription when we leave. |
| 3223 |
defer func() { |
| 3224 |
n.Lock() |
| 3225 |
n.unsubscribe(fsub) |
| 3226 |
n.unsubscribe(rpsub) |
| 3227 |
n.Unlock() |
| 3228 |
}() |
| 3229 |
n.Unlock() |
| 3230 |
|
| 3231 |
hb := time.NewTicker(hbInterval) |
| 3232 |
defer hb.Stop() |
| 3233 |
|
| 3234 |
lq := time.NewTicker(lostQuorumCheck) |
| 3235 |
defer lq.Stop() |
| 3236 |
|
| 3237 |
for n.State() == Leader { |
| 3238 |
select { |
| 3239 |
case <-n.s.quitCh: |
| 3240 |
return |
| 3241 |
case <-n.quit: |
| 3242 |
return |
| 3243 |
case <-n.resp.ch: |
| 3244 |
ars := n.resp.pop() |
| 3245 |
for _, ar := range ars { |
| 3246 |
n.processAppendEntryResponse(ar) |
| 3247 |
} |
| 3248 |
n.resp.recycle(&ars) |
| 3249 |
case <-n.prop.ch: |
| 3250 |
const maxBatch = 256 * 1024 |
| 3251 |
const maxEntries = 512 |
| 3252 |
var entries []*Entry |
| 3253 |
|
| 3254 |
es, sz := n.prop.pop(), 0 |
| 3255 |
for _, b := range es { |
| 3256 |
if b.ChangesMembership() { |
| 3257 |
n.sendMembershipChange(b.Entry) |
| 3258 |
continue |
| 3259 |
} |
| 3260 |
entries = append(entries, b.Entry) |
| 3261 |
// Increment size. |
| 3262 |
sz += len(b.Data) + 1 |
| 3263 |
// If below thresholds go ahead and send. |
| 3264 |
if sz < maxBatch && len(entries) < maxEntries { |
| 3265 |
continue |
| 3266 |
} |
| 3267 |
n.sendAppendEntry(entries) |
| 3268 |
// Reset our sz and entries. |
| 3269 |
// We need to re-create `entries` because there is a reference |
| 3270 |
// to it in the node's pae map. |
| 3271 |
sz, entries = 0, nil |
| 3272 |
} |
| 3273 |
if len(entries) > 0 { |
| 3274 |
n.sendAppendEntry(entries) |
| 3275 |
} |
| 3276 |
// Respond to any proposals waiting for a confirmation. |
| 3277 |
for _, pe := range es { |
| 3278 |
if pe.reply != _EMPTY_ { |
| 3279 |
n.sendReply(pe.reply, nil) |
| 3280 |
} |
| 3281 |
pe.returnToPool() |
| 3282 |
} |
| 3283 |
n.prop.recycle(&es) |
| 3284 |
|
| 3285 |
case <-hb.C: |
| 3286 |
if n.notActive() { |
| 3287 |
n.sendHeartbeat() |
| 3288 |
} |
| 3289 |
case <-lq.C: |
| 3290 |
if n.lostQuorum() { |
| 3291 |
n.stepdown(noLeader) |
| 3292 |
return |
| 3293 |
} |
| 3294 |
case <-n.votes.ch: |
| 3295 |
// Because of drain() it is possible that we get nil from popOne(). |
| 3296 |
vresp, ok := n.votes.popOne() |
| 3297 |
if !ok { |
| 3298 |
continue |
| 3299 |
} |
| 3300 |
if vresp.term > n.Term() { |
| 3301 |
n.stepdown(noLeader) |
| 3302 |
return |
| 3303 |
} |
| 3304 |
case <-n.reqs.ch: |
| 3305 |
// Because of drain() it is possible that we get nil from popOne(). |
| 3306 |
if voteReq, ok := n.reqs.popOne(); ok { |
| 3307 |
n.processVoteRequest(voteReq) |
| 3308 |
} |
| 3309 |
case <-n.entry.ch: |
| 3310 |
n.processAppendEntries() |
| 3311 |
} |
| 3312 |
} |
| 3313 |
} |
| 3314 |
|
| 3315 |
// Quorum reports the quorum status. Will be called on former leaders. |
| 3316 |
func (n *raft) Quorum() bool { |
| 3317 |
n.RLock() |
| 3318 |
defer n.RUnlock() |
| 3319 |
|
| 3320 |
nc := 0 |
| 3321 |
for id, peer := range n.peers { |
| 3322 |
if id == n.id || time.Since(peer.ts) < lostQuorumInterval { |
| 3323 |
if nc++; nc >= n.qn { |
| 3324 |
return true |
| 3325 |
} |
| 3326 |
} |
| 3327 |
} |
| 3328 |
return false |
| 3329 |
} |
| 3330 |
|
| 3331 |
func (n *raft) lostQuorum() bool { |
| 3332 |
n.RLock() |
| 3333 |
defer n.RUnlock() |
| 3334 |
return n.lostQuorumLocked() |
| 3335 |
} |
| 3336 |
|
| 3337 |
func (n *raft) lostQuorumLocked() bool { |
| 3338 |
// In order to avoid false positives that can happen in heavily loaded systems |
| 3339 |
// make sure nothing is queued up that we have not processed yet. |
| 3340 |
// Also make sure we let any scale up actions settle before deciding. |
| 3341 |
if n.resp.len() != 0 || (!n.lsut.IsZero() && time.Since(n.lsut) < lostQuorumInterval) { |
| 3342 |
return false |
| 3343 |
} |
| 3344 |
|
| 3345 |
nc := 0 |
| 3346 |
for id, peer := range n.peers { |
| 3347 |
if id == n.id || time.Since(peer.ts) < lostQuorumInterval { |
| 3348 |
if nc++; nc >= n.qn { |
| 3349 |
return false |
| 3350 |
} |
| 3351 |
} |
| 3352 |
} |
| 3353 |
return true |
| 3354 |
} |
| 3355 |
|
| 3356 |
// Check for being not active in terms of sending entries. |
| 3357 |
// Used in determining if we need to send a heartbeat. |
| 3358 |
func (n *raft) notActive() bool { |
| 3359 |
n.RLock() |
| 3360 |
defer n.RUnlock() |
| 3361 |
return time.Since(n.active) > hbInterval |
| 3362 |
} |
| 3363 |
|
| 3364 |
// Return our current term. |
| 3365 |
func (n *raft) Term() uint64 { |
| 3366 |
n.RLock() |
| 3367 |
defer n.RUnlock() |
| 3368 |
return n.term |
| 3369 |
} |
| 3370 |
|
| 3371 |
// Lock should be held. |
| 3372 |
func (n *raft) loadFirstEntry() (ae *appendEntry, err error) { |
| 3373 |
var state StreamState |
| 3374 |
n.wal.FastState(&state) |
| 3375 |
return n.loadEntry(state.FirstSeq) |
| 3376 |
} |
| 3377 |
|
| 3378 |
func (n *raft) runCatchup(ar *appendEntryResponse, indexUpdatesQ *ipQueue[uint64]) { |
| 3379 |
n.Lock() |
| 3380 |
s := n.s |
| 3381 |
peer, subj, term, pterm, last := ar.peer, ar.reply, n.term, n.pterm, n.pindex |
| 3382 |
leader := n.State() == Leader // Grab while holding lock, to not race. |
| 3383 |
// Catchup progress responses for flow control happen on its own subscription, |
| 3384 |
// not counting toward quorum. |
| 3385 |
reply := n.newCatchupProgressInbox() |
| 3386 |
psub, err := n.subscribe(reply, func(_ *subscription, _ *client, _ *Account, _, _ string, msg []byte) { |
| 3387 |
if pr := decodeAppendEntryResponse(msg); pr != nil { |
| 3388 |
n.trackPeer(pr.peer) |
| 3389 |
if pr.success && pr.peer == peer { |
| 3390 |
indexUpdatesQ.push(pr.index) |
| 3391 |
} |
| 3392 |
arPool.Put(pr) |
| 3393 |
} |
| 3394 |
}) |
| 3395 |
n.Unlock() |
| 3396 |
|
| 3397 |
defer s.grWG.Done() |
| 3398 |
defer arPool.Put(ar) |
| 3399 |
|
| 3400 |
defer func() { |
| 3401 |
n.Lock() |
| 3402 |
if psub != nil { |
| 3403 |
n.unsubscribe(psub) |
| 3404 |
} |
| 3405 |
// Only remove our own progress entry. |
| 3406 |
if q, ok := n.progress[peer]; ok && q == indexUpdatesQ { |
| 3407 |
delete(n.progress, peer) |
| 3408 |
if len(n.progress) == 0 { |
| 3409 |
n.progress = nil |
| 3410 |
} |
| 3411 |
} |
| 3412 |
// Check if this is a new peer and if so go ahead and propose adding them. |
| 3413 |
_, exists := n.peers[peer] |
| 3414 |
n.Unlock() |
| 3415 |
if !exists { |
| 3416 |
n.debug("Catchup done for %q, will add into peers", peer) |
| 3417 |
n.ProposeAddPeer(peer) |
| 3418 |
} |
| 3419 |
indexUpdatesQ.unregister() |
| 3420 |
}() |
| 3421 |
|
| 3422 |
if err != nil { |
| 3423 |
// Without the progress subscription, there's no flow control, so catchup would stall. |
| 3424 |
n.warn("Canceling catchup for %q, could not subscribe to progress inbox: %v", peer, err) |
| 3425 |
return |
| 3426 |
} |
| 3427 |
if !leader { |
| 3428 |
n.debug("Canceling catchup for %q, not leader anymore", peer) |
| 3429 |
return |
| 3430 |
} |
| 3431 |
n.debug("Running catchup for %q [%d:%d] to [%d:%d]", peer, ar.term, ar.index, pterm, last) |
| 3432 |
|
| 3433 |
const maxOutstanding = 2 * 1024 * 1024 // 2MB for now. |
| 3434 |
next, total, om := uint64(0), 0, make(map[uint64]int) |
| 3435 |
|
| 3436 |
sendNext := func() bool { |
| 3437 |
for total <= maxOutstanding { |
| 3438 |
next++ |
| 3439 |
if next > last { |
| 3440 |
return true |
| 3441 |
} |
| 3442 |
ae, err := n.loadEntry(next) |
| 3443 |
if err != nil { |
| 3444 |
if err != ErrStoreEOF { |
| 3445 |
n.warn("Got an error loading %d index: %v", next, err) |
| 3446 |
} |
| 3447 |
return true |
| 3448 |
} |
| 3449 |
// Re-encode with the lterm if needed |
| 3450 |
if ae.lterm != term { |
| 3451 |
ae.lterm = term |
| 3452 |
if ae.buf, err = ae.encode(ae.buf[:0]); err != nil { |
| 3453 |
n.warn("Got an error re-encoding append entry: %v", err) |
| 3454 |
return true |
| 3455 |
} |
| 3456 |
} |
| 3457 |
// Update our tracking total. |
| 3458 |
om[next] = len(ae.buf) |
| 3459 |
total += len(ae.buf) |
| 3460 |
n.sendRPC(subj, reply, ae.buf) |
| 3461 |
} |
| 3462 |
return false |
| 3463 |
} |
| 3464 |
|
| 3465 |
const activityInterval = 2 * time.Second |
| 3466 |
timeout := time.NewTimer(activityInterval) |
| 3467 |
defer timeout.Stop() |
| 3468 |
|
| 3469 |
stepCheck := time.NewTicker(100 * time.Millisecond) |
| 3470 |
defer stepCheck.Stop() |
| 3471 |
|
| 3472 |
// Run as long as we are leader and still not caught up. |
| 3473 |
for n.State() == Leader { |
| 3474 |
select { |
| 3475 |
case <-n.s.quitCh: |
| 3476 |
return |
| 3477 |
case <-n.quit: |
| 3478 |
return |
| 3479 |
case <-stepCheck.C: |
| 3480 |
if n.State() != Leader { |
| 3481 |
n.debug("Catching up canceled, no longer leader") |
| 3482 |
return |
| 3483 |
} |
| 3484 |
case <-timeout.C: |
| 3485 |
n.debug("Catching up for %q stalled", peer) |
| 3486 |
return |
| 3487 |
case <-indexUpdatesQ.ch: |
| 3488 |
if index, ok := indexUpdatesQ.popOne(); ok { |
| 3489 |
// Update our activity timer. |
| 3490 |
timeout.Reset(activityInterval) |
| 3491 |
// Update outstanding total. |
| 3492 |
total -= om[index] |
| 3493 |
delete(om, index) |
| 3494 |
if next == 0 { |
| 3495 |
next = index |
| 3496 |
} |
| 3497 |
// Check if we are done. |
| 3498 |
if index > last || sendNext() { |
| 3499 |
n.debug("Finished catching up") |
| 3500 |
return |
| 3501 |
} |
| 3502 |
} |
| 3503 |
} |
| 3504 |
} |
| 3505 |
} |
| 3506 |
|
| 3507 |
// Lock should be held. |
| 3508 |
func (n *raft) sendSnapshotToFollower(subject string) (uint64, error) { |
| 3509 |
snap, err := n.loadLastSnapshot() |
| 3510 |
if err != nil { |
| 3511 |
// We need to stepdown here when this happens. |
| 3512 |
n.stepdownLocked(noLeader) |
| 3513 |
return 0, err |
| 3514 |
} |
| 3515 |
// Go ahead and send the snapshot and peerstate here as first append entry to the catchup follower. |
| 3516 |
ae := n.buildAppendEntry([]*Entry{{EntrySnapshot, snap.data}, {EntryPeerState, snap.peerstate}}) |
| 3517 |
ae.pterm, ae.pindex = snap.lastTerm, snap.lastIndex |
| 3518 |
var state StreamState |
| 3519 |
n.wal.FastState(&state) |
| 3520 |
|
| 3521 |
fpIndex := state.FirstSeq - 1 |
| 3522 |
if snap.lastIndex < fpIndex && state.FirstSeq != 0 { |
| 3523 |
snap.lastIndex = fpIndex |
| 3524 |
ae.pindex = fpIndex |
| 3525 |
} |
| 3526 |
|
| 3527 |
encoding, err := ae.encode(nil) |
| 3528 |
if err != nil { |
| 3529 |
return 0, err |
| 3530 |
} |
| 3531 |
n.sendRPC(subject, n.areply, encoding) |
| 3532 |
return snap.lastIndex, nil |
| 3533 |
} |
| 3534 |
|
| 3535 |
func (n *raft) catchupFollower(ar *appendEntryResponse) { |
| 3536 |
n.debug("Being asked to catch up follower: %q", ar.peer) |
| 3537 |
n.Lock() |
| 3538 |
if n.progress == nil { |
| 3539 |
n.progress = make(map[string]*ipQueue[uint64]) |
| 3540 |
} else if q, ok := n.progress[ar.peer]; ok { |
| 3541 |
n.debug("Will cancel existing entry for catching up %q", ar.peer) |
| 3542 |
delete(n.progress, ar.peer) |
| 3543 |
q.push(n.pindex) |
| 3544 |
} |
| 3545 |
|
| 3546 |
// Check to make sure we have this entry. |
| 3547 |
start := ar.index + 1 |
| 3548 |
var state StreamState |
| 3549 |
n.wal.FastState(&state) |
| 3550 |
|
| 3551 |
if start < state.FirstSeq || (state.Msgs == 0 && start <= state.LastSeq) { |
| 3552 |
n.debug("Need to send snapshot to follower") |
| 3553 |
if lastIndex, err := n.sendSnapshotToFollower(ar.reply); err != nil { |
| 3554 |
n.error("Error sending snapshot to follower [%s]: %v", ar.peer, err) |
| 3555 |
n.Unlock() |
| 3556 |
arPool.Put(ar) |
| 3557 |
return |
| 3558 |
} else { |
| 3559 |
start = lastIndex + 1 |
| 3560 |
// If no other entries, we can just return here. |
| 3561 |
if state.Msgs == 0 || start > state.LastSeq { |
| 3562 |
n.debug("Finished catching up") |
| 3563 |
n.Unlock() |
| 3564 |
arPool.Put(ar) |
| 3565 |
return |
| 3566 |
} |
| 3567 |
n.debug("Snapshot sent, reset first catchup entry to %d", lastIndex) |
| 3568 |
} |
| 3569 |
} |
| 3570 |
|
| 3571 |
ae, err := n.loadEntry(start) |
| 3572 |
if err != nil { |
| 3573 |
n.warn("Request from follower for entry at index [%d] errored for state %+v - %v", start, state, err) |
| 3574 |
if err == ErrStoreEOF { |
| 3575 |
// If we are here we are seeing a request for an item beyond our state, meaning we should stepdown. |
| 3576 |
n.stepdownLocked(noLeader) |
| 3577 |
n.Unlock() |
| 3578 |
arPool.Put(ar) |
| 3579 |
return |
| 3580 |
} |
| 3581 |
ae, err = n.loadFirstEntry() |
| 3582 |
} |
| 3583 |
if err != nil || ae == nil { |
| 3584 |
n.warn("Could not find a starting entry for catchup request: %v", err) |
| 3585 |
// If we are here we are seeing a request for an item we do not have, meaning we should stepdown. |
| 3586 |
// This is possible on a reset of our WAL but the other side has a snapshot already. |
| 3587 |
// If we do not stepdown this can cycle. |
| 3588 |
n.stepdownLocked(noLeader) |
| 3589 |
n.Unlock() |
| 3590 |
arPool.Put(ar) |
| 3591 |
return |
| 3592 |
} |
| 3593 |
if ae.pindex != ar.index || ae.pterm != ar.term { |
| 3594 |
n.debug("Our first entry [%d:%d] does not match request from follower [%d:%d]", ae.pterm, ae.pindex, ar.term, ar.index) |
| 3595 |
} |
| 3596 |
// Create a queue for delivering updates from responses. |
| 3597 |
indexUpdates := newIPQueue[uint64](n.s, fmt.Sprintf("[ACC:%s] RAFT '%s' indexUpdates", n.accName, n.group)) |
| 3598 |
indexUpdates.push(ae.pindex) |
| 3599 |
n.progress[ar.peer] = indexUpdates |
| 3600 |
n.wg.Add(1) |
| 3601 |
n.Unlock() |
| 3602 |
started := n.s.startGoRoutine(func() { |
| 3603 |
defer n.wg.Done() |
| 3604 |
n.runCatchup(ar, indexUpdates) |
| 3605 |
}) |
| 3606 |
if !started { |
| 3607 |
n.wg.Done() |
| 3608 |
n.Lock() |
| 3609 |
if n.progress != nil && n.progress[ar.peer] == indexUpdates { |
| 3610 |
delete(n.progress, ar.peer) |
| 3611 |
} |
| 3612 |
n.Unlock() |
| 3613 |
indexUpdates.unregister() |
| 3614 |
arPool.Put(ar) |
| 3615 |
} |
| 3616 |
} |
| 3617 |
|
| 3618 |
func (n *raft) loadEntry(index uint64) (*appendEntry, error) { |
| 3619 |
var smp StoreMsg |
| 3620 |
sm, err := n.wal.LoadMsg(index, &smp) |
| 3621 |
if err != nil { |
| 3622 |
return nil, err |
| 3623 |
} |
| 3624 |
return decodeAppendEntry(sm.msg, nil, _EMPTY_) |
| 3625 |
} |
| 3626 |
|
| 3627 |
// applyCommit will update our commit index and apply the entry to the apply queue. |
| 3628 |
// lock should be held. |
| 3629 |
func (n *raft) applyCommit(index uint64) error { |
| 3630 |
if n.State() == Closed { |
| 3631 |
return errNodeClosed |
| 3632 |
} |
| 3633 |
if index <= n.commit { |
| 3634 |
n.debug("Ignoring apply commit for %d, already processed", index) |
| 3635 |
return nil |
| 3636 |
} |
| 3637 |
|
| 3638 |
if n.State() == Leader { |
| 3639 |
delete(n.acks, index) |
| 3640 |
} |
| 3641 |
|
| 3642 |
if index <= n.papplied { |
| 3643 |
return nil |
| 3644 |
} |
| 3645 |
|
| 3646 |
ae := n.pae[index] |
| 3647 |
if ae == nil { |
| 3648 |
var err error |
| 3649 |
if ae, err = n.loadEntry(index); err != nil { |
| 3650 |
if err != ErrStoreClosed && err != ErrStoreEOF { |
| 3651 |
n.warn("Got an error loading %d index: %v - will reset", index, err) |
| 3652 |
if n.State() == Leader { |
| 3653 |
n.stepdownLocked(n.selectNextLeader()) |
| 3654 |
} |
| 3655 |
// Reset and cancel any catchup. |
| 3656 |
n.resetWAL() |
| 3657 |
n.cancelCatchup() |
| 3658 |
} |
| 3659 |
return errEntryLoadFailed |
| 3660 |
} |
| 3661 |
} else { |
| 3662 |
// Size it now, the buffer is cleared below. |
| 3663 |
sz := n.entryStoreSize(ae) |
| 3664 |
defer func() { |
| 3665 |
if _, ok := n.pae[index]; ok { |
| 3666 |
n.paeBytes -= sz |
| 3667 |
delete(n.pae, index) |
| 3668 |
} |
| 3669 |
}() |
| 3670 |
} |
| 3671 |
|
| 3672 |
n.commit = index |
| 3673 |
ae.buf = nil |
| 3674 |
var committed []*Entry |
| 3675 |
|
| 3676 |
defer func() { |
| 3677 |
// Pass to the upper layers if we have normal entries. It is |
| 3678 |
// entirely possible that 'committed' might be an empty slice here, |
| 3679 |
// which will happen if we've processed updates inline (like peer |
| 3680 |
// states). In which case the upper layer will just call down with |
| 3681 |
// Applied() with no further action. |
| 3682 |
n.apply.push(newCommittedEntry(index, committed)) |
| 3683 |
// Place back in the pool. |
| 3684 |
ae.returnToPool() |
| 3685 |
}() |
| 3686 |
|
| 3687 |
for _, e := range ae.entries { |
| 3688 |
switch e.Type { |
| 3689 |
case EntryNormal: |
| 3690 |
committed = append(committed, e) |
| 3691 |
case EntryOldSnapshot: |
| 3692 |
// For old snapshots in our WAL. |
| 3693 |
committed = append(committed, newEntry(EntrySnapshot, e.Data)) |
| 3694 |
case EntrySnapshot: |
| 3695 |
committed = append(committed, e) |
| 3696 |
// If we have no snapshot, install the leader's snapshot as our own. |
| 3697 |
if len(ae.entries) == 1 && n.snapfile == _EMPTY_ && ae.commit > 0 { |
| 3698 |
n.installSnapshot(&snapshot{ |
| 3699 |
lastTerm: ae.pterm, |
| 3700 |
lastIndex: ae.commit, |
| 3701 |
peerstate: encodePeerState(n.committedPeerStateLocked(ae.commit)), |
| 3702 |
data: e.Data, |
| 3703 |
}) |
| 3704 |
} |
| 3705 |
case EntryPeerState: |
| 3706 |
if n.State() != Leader { |
| 3707 |
if ps, err := decodePeerState(e.Data); err == nil { |
| 3708 |
n.processPeerState(ps) |
| 3709 |
} |
| 3710 |
} |
| 3711 |
case EntryAddPeer: |
| 3712 |
newPeer := string(e.Data) |
| 3713 |
n.debug("Added peer %q", newPeer) |
| 3714 |
|
| 3715 |
// Store our peer in our global peer map for all peers. |
| 3716 |
peers.LoadOrStore(newPeer, newPeer) |
| 3717 |
|
| 3718 |
n.addPeer(newPeer) |
| 3719 |
|
| 3720 |
// We pass these up as well. |
| 3721 |
committed = append(committed, e) |
| 3722 |
|
| 3723 |
// We are done with this membership change |
| 3724 |
n.membChange = nil |
| 3725 |
|
| 3726 |
case EntryRemovePeer: |
| 3727 |
peer := string(e.Data) |
| 3728 |
n.debug("Removing peer %q", peer) |
| 3729 |
|
| 3730 |
n.removePeer(peer) |
| 3731 |
|
| 3732 |
// Remove from string intern map. |
| 3733 |
peers.Delete(peer) |
| 3734 |
|
| 3735 |
// We pass these up as well. |
| 3736 |
committed = append(committed, e) |
| 3737 |
|
| 3738 |
// We are done with this membership change |
| 3739 |
n.membChange = nil |
| 3740 |
|
| 3741 |
// If this is us and we are the leader signal the caller |
| 3742 |
// to attempt to stepdown. |
| 3743 |
if peer == n.id && n.State() == Leader { |
| 3744 |
return errNodeRemoved |
| 3745 |
} |
| 3746 |
} |
| 3747 |
} |
| 3748 |
return nil |
| 3749 |
} |
| 3750 |
|
| 3751 |
// Check if there is a quorum for the given index, and if |
| 3752 |
// so, commit the corresponding entry. |
| 3753 |
// Return true if the index was committed, false otherwise. |
| 3754 |
// Lock should be held. |
| 3755 |
func (n *raft) tryCommit(index uint64) (bool, error) { |
| 3756 |
acks := len(n.acks[index]) |
| 3757 |
// Count the leader if it's still part of membership |
| 3758 |
if n.peers[n.ID()] != nil { |
| 3759 |
acks += 1 |
| 3760 |
} |
| 3761 |
if acks < n.qn { |
| 3762 |
return false, nil |
| 3763 |
} |
| 3764 |
// We have a quorum |
| 3765 |
for i := n.commit + 1; i <= index; i++ { |
| 3766 |
if err := n.applyCommit(i); err != nil { |
| 3767 |
if err != errNodeClosed && err != errNodeRemoved { |
| 3768 |
n.error("Got an error applying commit for %d: %v", i, err) |
| 3769 |
} |
| 3770 |
return false, err |
| 3771 |
} |
| 3772 |
} |
| 3773 |
return true, nil |
| 3774 |
} |
| 3775 |
|
| 3776 |
// Used to track a success response. Returns true if the |
| 3777 |
// response was tracked, false if the response was ignored |
| 3778 |
// (the response is old, the index is already committed, ...) |
| 3779 |
// Lock should be held. |
| 3780 |
func (n *raft) trackResponse(ar *appendEntryResponse) bool { |
| 3781 |
// Check state under lock, we might not be leader anymore. |
| 3782 |
if n.State() != Leader { |
| 3783 |
return false |
| 3784 |
} |
| 3785 |
|
| 3786 |
ps := n.peers[ar.peer] |
| 3787 |
|
| 3788 |
// Update peer's last index. |
| 3789 |
if ps != nil && ar.index > ps.li { |
| 3790 |
ps.li = ar.index |
| 3791 |
} |
| 3792 |
|
| 3793 |
// Ignore items already committed, or skip if this is not about an entry that matches our current term. |
| 3794 |
if ar.index <= n.commit || ar.term != n.term { |
| 3795 |
assert.AlwaysOrUnreachable(ar.term <= n.term, "Raft response term mismatch", map[string]any{ |
| 3796 |
"n.accName": n.accName, |
| 3797 |
"n.group": n.group, |
| 3798 |
"n.id": n.id, |
| 3799 |
"n.term": n.term, |
| 3800 |
"ar.term": ar.term, |
| 3801 |
}) |
| 3802 |
return false |
| 3803 |
} |
| 3804 |
|
| 3805 |
// Not a peer, can't count this message towards quorum |
| 3806 |
if ps == nil { |
| 3807 |
return false |
| 3808 |
} |
| 3809 |
|
| 3810 |
// Keep track of the response |
| 3811 |
results := n.acks[ar.index] |
| 3812 |
if results == nil { |
| 3813 |
results = make(map[string]struct{}) |
| 3814 |
n.acks[ar.index] = results |
| 3815 |
} |
| 3816 |
results[ar.peer] = struct{}{} |
| 3817 |
|
| 3818 |
return true |
| 3819 |
} |
| 3820 |
|
| 3821 |
// Used to adjust cluster size and peer count based on added official peers. |
| 3822 |
// lock should be held. |
| 3823 |
func (n *raft) adjustClusterSizeAndQuorum() { |
| 3824 |
pcsz, ncsz := n.csz, len(n.peers) |
| 3825 |
n.csz = ncsz |
| 3826 |
n.qn = n.csz/2 + 1 |
| 3827 |
|
| 3828 |
if ncsz > pcsz { |
| 3829 |
n.debug("Expanding our clustersize: %d -> %d", pcsz, ncsz) |
| 3830 |
n.lsut = time.Now() |
| 3831 |
} else if ncsz < pcsz { |
| 3832 |
n.debug("Decreasing our clustersize: %d -> %d", pcsz, ncsz) |
| 3833 |
if n.State() == Leader { |
| 3834 |
go n.sendHeartbeat() |
| 3835 |
} |
| 3836 |
} |
| 3837 |
if ncsz != pcsz { |
| 3838 |
n.recreateInternalSubsLocked() |
| 3839 |
} |
| 3840 |
} |
| 3841 |
|
| 3842 |
// Returns true if we should count vote responses from this peer. |
| 3843 |
// Lock should be held. |
| 3844 |
func (n *raft) shouldCountVoteFromPeer(peer string) bool { |
| 3845 |
if _, ok := n.peers[peer]; ok { |
| 3846 |
return true |
| 3847 |
} |
| 3848 |
// During bootstrap, we may know fewer peer ids |
| 3849 |
// than the declared cluster size. Initially, we |
| 3850 |
// may need to accept votes from peers that are |
| 3851 |
// not yet in the peer set. |
| 3852 |
return len(n.peers) < n.csz |
| 3853 |
} |
| 3854 |
|
| 3855 |
// Track interactions with this peer. |
| 3856 |
func (n *raft) trackPeer(peer string) error { |
| 3857 |
n.Lock() |
| 3858 |
var needPeerAdd, isRemoved bool |
| 3859 |
var rts time.Time |
| 3860 |
if n.removed != nil { |
| 3861 |
rts, isRemoved = n.removed[peer] |
| 3862 |
// Removed peers can rejoin after timeout. |
| 3863 |
if isRemoved && time.Since(rts) >= peerRemoveTimeout { |
| 3864 |
isRemoved = false |
| 3865 |
} |
| 3866 |
} |
| 3867 |
if n.State() == Leader { |
| 3868 |
if _, ok := n.peers[peer]; !ok { |
| 3869 |
// Check if this peer had been removed previously. |
| 3870 |
needPeerAdd = !isRemoved |
| 3871 |
} |
| 3872 |
} |
| 3873 |
if ps := n.peers[peer]; ps != nil { |
| 3874 |
ps.ts = time.Now() |
| 3875 |
} |
| 3876 |
n.Unlock() |
| 3877 |
|
| 3878 |
if needPeerAdd { |
| 3879 |
n.ProposeAddPeer(peer) |
| 3880 |
} |
| 3881 |
return nil |
| 3882 |
} |
| 3883 |
|
| 3884 |
func (n *raft) runAsCandidate() { |
| 3885 |
n.Lock() |
| 3886 |
// Drain old responses. |
| 3887 |
n.votes.drain() |
| 3888 |
n.Unlock() |
| 3889 |
|
| 3890 |
// Send out our request for votes. |
| 3891 |
n.requestVote() |
| 3892 |
|
| 3893 |
// We vote for ourselves. |
| 3894 |
n.votes.push(&voteResponse{term: n.term, peer: n.ID(), granted: true}) |
| 3895 |
|
| 3896 |
votes := map[string]struct{}{} |
| 3897 |
emptyVotes := map[string]struct{}{} |
| 3898 |
|
| 3899 |
for n.State() == Candidate { |
| 3900 |
elect := n.electTimer() |
| 3901 |
select { |
| 3902 |
case <-n.entry.ch: |
| 3903 |
n.processAppendEntries() |
| 3904 |
case <-n.resp.ch: |
| 3905 |
// Ignore append entry responses received from before the state change. |
| 3906 |
n.resp.drain() |
| 3907 |
case <-n.prop.ch: |
| 3908 |
// Ignore proposals received from before the state change. |
| 3909 |
n.prop.drain() |
| 3910 |
case <-n.s.quitCh: |
| 3911 |
return |
| 3912 |
case <-n.quit: |
| 3913 |
return |
| 3914 |
case <-elect.C: |
| 3915 |
n.switchToCandidate() |
| 3916 |
return |
| 3917 |
case <-n.votes.ch: |
| 3918 |
// Because of drain() it is possible that we get nil from popOne(). |
| 3919 |
vresp, ok := n.votes.popOne() |
| 3920 |
if !ok { |
| 3921 |
continue |
| 3922 |
} |
| 3923 |
n.RLock() |
| 3924 |
nterm := n.term |
| 3925 |
csz := n.csz |
| 3926 |
countVote := n.shouldCountVoteFromPeer(vresp.peer) |
| 3927 |
n.RUnlock() |
| 3928 |
|
| 3929 |
if vresp.granted && nterm == vresp.term { |
| 3930 |
// only track peers that would be our followers |
| 3931 |
n.trackPeer(vresp.peer) |
| 3932 |
if countVote { |
| 3933 |
if !vresp.empty { |
| 3934 |
votes[vresp.peer] = struct{}{} |
| 3935 |
} else { |
| 3936 |
emptyVotes[vresp.peer] = struct{}{} |
| 3937 |
} |
| 3938 |
} |
| 3939 |
if n.wonElection(len(votes)) { |
| 3940 |
// Become LEADER if we have won and gotten a quorum with everyone we should hear from. |
| 3941 |
n.switchToLeader() |
| 3942 |
return |
| 3943 |
} else if len(votes)+len(emptyVotes) == csz { |
| 3944 |
// Become LEADER if we've got voted in by ALL servers. |
| 3945 |
// We couldn't get quorum based on just our normal votes. |
| 3946 |
// But, we have heard from the full cluster, and some servers came up empty. |
| 3947 |
// We know for sure we have the most up-to-date log. |
| 3948 |
n.switchToLeader() |
| 3949 |
return |
| 3950 |
} |
| 3951 |
} else if vresp.term > nterm { |
| 3952 |
// if we observe a bigger term, we should start over again or risk forming a quorum fully knowing |
| 3953 |
// someone with a better term exists. This is even the right thing to do if won == true. |
| 3954 |
n.Lock() |
| 3955 |
n.debug("Stepping down from candidate, detected higher term: %d vs %d", vresp.term, n.term) |
| 3956 |
n.term = vresp.term |
| 3957 |
n.vote = noVote |
| 3958 |
n.writeTermVote() |
| 3959 |
n.lxfer = false |
| 3960 |
n.stepdownLocked(noLeader) |
| 3961 |
n.Unlock() |
| 3962 |
} |
| 3963 |
case <-n.reqs.ch: |
| 3964 |
// Because of drain() it is possible that we get nil from popOne(). |
| 3965 |
if voteReq, ok := n.reqs.popOne(); ok { |
| 3966 |
n.processVoteRequest(voteReq) |
| 3967 |
} |
| 3968 |
} |
| 3969 |
} |
| 3970 |
} |
| 3971 |
|
| 3972 |
// handleAppendEntry handles an append entry from the wire. This function |
| 3973 |
// is an internal callback from the "asubj" append entry subscription. |
| 3974 |
func (n *raft) handleAppendEntry(sub *subscription, c *client, _ *Account, _, reply string, msg []byte) { |
| 3975 |
msg = copyBytes(msg) |
| 3976 |
if ae, err := decodeAppendEntry(msg, sub, reply); err == nil { |
| 3977 |
// Push to the new entry channel. From here one of the worker |
| 3978 |
// goroutines (runAsLeader, runAsFollower, runAsCandidate) will |
| 3979 |
// pick it up. |
| 3980 |
n.entry.push(ae) |
| 3981 |
} else { |
| 3982 |
n.warn("AppendEntry failed to be placed on internal channel: corrupt entry") |
| 3983 |
} |
| 3984 |
} |
| 3985 |
|
| 3986 |
// cancelCatchup will stop an in-flight catchup by unsubscribing from the |
| 3987 |
// catchup subscription. |
| 3988 |
// Lock should be held. |
| 3989 |
func (n *raft) cancelCatchup() { |
| 3990 |
n.debug("Canceling catchup subscription since we are now up to date") |
| 3991 |
|
| 3992 |
if n.catchup != nil && n.catchup.sub != nil { |
| 3993 |
n.unsubscribe(n.catchup.sub) |
| 3994 |
} |
| 3995 |
n.cancelCatchupSignal() |
| 3996 |
n.catchup = nil |
| 3997 |
} |
| 3998 |
|
| 3999 |
// catchupStalled will try to determine if we are stalled. This is called |
| 4000 |
// on a new entry from our leader. |
| 4001 |
// Lock should be held. |
| 4002 |
func (n *raft) catchupStalled() bool { |
| 4003 |
if n.catchup == nil { |
| 4004 |
return false |
| 4005 |
} |
| 4006 |
if n.catchup.pindex == n.pindex { |
| 4007 |
return time.Since(n.catchup.active) > 2*time.Second |
| 4008 |
} |
| 4009 |
n.catchup.pindex = n.pindex |
| 4010 |
n.catchup.active = time.Now() |
| 4011 |
return false |
| 4012 |
} |
| 4013 |
|
| 4014 |
// createCatchup will create the state needed to track a catchup as it |
| 4015 |
// runs. It then creates a unique inbox for this catchup and subscribes |
| 4016 |
// to it. The remote side will stream entries to that subject. |
| 4017 |
// Lock should be held. |
| 4018 |
func (n *raft) createCatchup(ae *appendEntry) string { |
| 4019 |
// Cleanup any old ones. |
| 4020 |
if n.catchup != nil && n.catchup.sub != nil { |
| 4021 |
n.unsubscribe(n.catchup.sub) |
| 4022 |
} |
| 4023 |
// Snapshot term and index. |
| 4024 |
n.catchup = &catchupState{ |
| 4025 |
cterm: ae.pterm, |
| 4026 |
cindex: ae.pindex, |
| 4027 |
pterm: n.pterm, |
| 4028 |
pindex: n.pindex, |
| 4029 |
active: time.Now(), |
| 4030 |
} |
| 4031 |
inbox := n.newCatchupInbox() |
| 4032 |
sub, _ := n.subscribe(inbox, n.handleAppendEntry) |
| 4033 |
n.catchup.sub = sub |
| 4034 |
return inbox |
| 4035 |
} |
| 4036 |
|
| 4037 |
// Lock should be held. |
| 4038 |
func (n *raft) sendCatchupSignal() { |
| 4039 |
if n.catchup == nil || n.catchup.signal { |
| 4040 |
return |
| 4041 |
} |
| 4042 |
n.catchup.signal = true |
| 4043 |
// Signal to the upper layer that the following entries are catchup entries, up until the nil guard. |
| 4044 |
n.apply.push(newCommittedEntry(0, []*Entry{{EntryCatchup, nil}})) |
| 4045 |
} |
| 4046 |
|
| 4047 |
// Lock should be held. |
| 4048 |
func (n *raft) cancelCatchupSignal() { |
| 4049 |
if n.catchup == nil || !n.catchup.signal { |
| 4050 |
return |
| 4051 |
} |
| 4052 |
// Send nil entry to signal the upper layers we are done catching up. |
| 4053 |
n.apply.push(nil) |
| 4054 |
} |
| 4055 |
|
| 4056 |
// Truncate our WAL and reset. |
| 4057 |
// Lock should be held. |
| 4058 |
func (n *raft) truncateWAL(term, index uint64) { |
| 4059 |
n.debug("Truncating and repairing WAL to Term %d Index %d", term, index) |
| 4060 |
|
| 4061 |
if term == 0 && index == 0 { |
| 4062 |
if n.commit > 0 { |
| 4063 |
n.warn("Resetting WAL state") |
| 4064 |
} else { |
| 4065 |
n.debug("Clearing WAL state (no commits)") |
| 4066 |
} |
| 4067 |
} |
| 4068 |
if index < n.commit { |
| 4069 |
assert.Unreachable("WAL truncate lost commits", map[string]any{ |
| 4070 |
"n.accName": n.accName, |
| 4071 |
"n.group": n.group, |
| 4072 |
"n.id": n.id, |
| 4073 |
"term": term, |
| 4074 |
"index": index, |
| 4075 |
"commit": n.commit, |
| 4076 |
"applied": n.applied, |
| 4077 |
}) |
| 4078 |
} |
| 4079 |
|
| 4080 |
defer func() { |
| 4081 |
// Check to see if we invalidated any snapshots that might have held state |
| 4082 |
// from the entries we are truncating. |
| 4083 |
if snap, _ := n.loadLastSnapshot(); snap != nil && snap.lastIndex > index { |
| 4084 |
os.Remove(n.snapfile) |
| 4085 |
n.snapfile = _EMPTY_ |
| 4086 |
} |
| 4087 |
// Make sure to reset commit and applied if above |
| 4088 |
if n.commit > n.pindex { |
| 4089 |
n.commit = n.pindex |
| 4090 |
} |
| 4091 |
if n.processed > n.commit { |
| 4092 |
n.processed = n.commit |
| 4093 |
} |
| 4094 |
if n.applied > n.processed { |
| 4095 |
n.applied = n.processed |
| 4096 |
} |
| 4097 |
// Refresh bytes count after truncate. |
| 4098 |
var state StreamState |
| 4099 |
n.wal.FastState(&state) |
| 4100 |
n.bytes = state.Bytes |
| 4101 |
}() |
| 4102 |
|
| 4103 |
if err := n.wal.Truncate(index); err != nil { |
| 4104 |
n.warn("Error truncating WAL: %v", err) |
| 4105 |
n.setWriteErrLocked(err) |
| 4106 |
return |
| 4107 |
} |
| 4108 |
// Set after we know we have truncated properly. |
| 4109 |
n.pterm, n.pindex = term, index |
| 4110 |
|
| 4111 |
// Invalidate cached entries the WAL no longer has. |
| 4112 |
if index == 0 { |
| 4113 |
n.resetPendingEntries() |
| 4114 |
} else { |
| 4115 |
for k, ae := range n.pae { |
| 4116 |
if k > index { |
| 4117 |
n.paeBytes -= n.entryStoreSize(ae) |
| 4118 |
delete(n.pae, k) |
| 4119 |
} |
| 4120 |
} |
| 4121 |
} |
| 4122 |
|
| 4123 |
// Check if we're truncating an uncommitted membership change. |
| 4124 |
if n.membChange != nil && n.membChange.index > index { |
| 4125 |
peer := n.membChange.peer |
| 4126 |
if ps := n.membChange.prev; ps != nil { |
| 4127 |
// This was a removal, add it back. |
| 4128 |
n.peers[peer] = ps |
| 4129 |
// If we were on the removed list, reverse that here. |
| 4130 |
if n.removed != nil { |
| 4131 |
delete(n.removed, peer) |
| 4132 |
if len(n.removed) == 0 { |
| 4133 |
n.removed = nil |
| 4134 |
} |
| 4135 |
} |
| 4136 |
} else { |
| 4137 |
// This was an addition, remove it. |
| 4138 |
delete(n.peers, peer) |
| 4139 |
} |
| 4140 |
n.adjustClusterSizeAndQuorum() |
| 4141 |
n.writePeerState(&peerState{n.peerNames(), n.csz, n.extSt}) |
| 4142 |
n.membChange = nil |
| 4143 |
} |
| 4144 |
} |
| 4145 |
|
| 4146 |
// Reset our WAL. This is equivalent to truncating all data from the log. |
| 4147 |
// Lock should be held. |
| 4148 |
func (n *raft) resetWAL() { |
| 4149 |
n.truncateWAL(0, 0) |
| 4150 |
} |
| 4151 |
|
| 4152 |
// Lock should be held |
| 4153 |
func (n *raft) updateLeader(newLeader string) { |
| 4154 |
wasLeader := n.leader == n.id |
| 4155 |
n.leader = newLeader |
| 4156 |
n.hasleader.Store(newLeader != _EMPTY_) |
| 4157 |
if !n.pleader.Load() && newLeader != noLeader { |
| 4158 |
n.pleader.Store(true) |
| 4159 |
// If we were preferred to become the first leader, but didn't end up successful. |
| 4160 |
// Ensure to call lead change. When scaling from R1 to R3 we've optimized for a scale up |
| 4161 |
// not flipping leader/non-leader/leader status if the leader remains the same. But we need to |
| 4162 |
// correct that if the first leader turns out to be different. |
| 4163 |
if n.maybeLeader { |
| 4164 |
n.maybeLeader = false |
| 4165 |
if n.id != newLeader { |
| 4166 |
n.updateLeadChange(false) |
| 4167 |
} |
| 4168 |
} |
| 4169 |
} |
| 4170 |
// Reset last seen timestamps and indices. |
| 4171 |
// If we are (or were) the leader we track(ed) everyone, and don't reset. |
| 4172 |
// But if we're a follower we only track the leader, and reset all others. |
| 4173 |
if newLeader != n.id && !wasLeader { |
| 4174 |
for peer, ps := range n.peers { |
| 4175 |
// Always reset last replicated index. |
| 4176 |
ps.li = 0 |
| 4177 |
if peer == newLeader { |
| 4178 |
continue |
| 4179 |
} |
| 4180 |
// Only reset the last seen timestamp if this peer is not the leader. |
| 4181 |
ps.ts = time.Time{} |
| 4182 |
} |
| 4183 |
} |
| 4184 |
} |
| 4185 |
|
| 4186 |
// processAppendEntry will process an appendEntry. This is called either |
| 4187 |
// during recovery or from processAppendEntries when there are new entries |
| 4188 |
// to be committed. |
| 4189 |
func (n *raft) processAppendEntry(ae *appendEntry, sub *subscription) { |
| 4190 |
n.Lock() |
| 4191 |
// Don't reset here if we have been asked to assume leader position. |
| 4192 |
if !n.lxfer { |
| 4193 |
n.resetElectionTimeout() |
| 4194 |
} |
| 4195 |
|
| 4196 |
// Just return if closed or we had previous write error. |
| 4197 |
if n.State() == Closed || n.werr != nil { |
| 4198 |
n.Unlock() |
| 4199 |
return |
| 4200 |
} |
| 4201 |
|
| 4202 |
// Scratch buffer for responses. |
| 4203 |
var scratch [appendEntryResponseLen]byte |
| 4204 |
arbuf := scratch[:] |
| 4205 |
|
| 4206 |
// Grab term from append entry. But if leader explicitly defined its term, use that instead. |
| 4207 |
// This is required during catchup if the leader catches us up on older items from previous terms. |
| 4208 |
// While still allowing us to confirm they're matching our highest known term. |
| 4209 |
lterm := ae.term |
| 4210 |
if ae.lterm != 0 { |
| 4211 |
lterm = ae.lterm |
| 4212 |
} |
| 4213 |
|
| 4214 |
// Are we receiving from another leader. |
| 4215 |
if n.State() == Leader { |
| 4216 |
if lterm >= n.term { |
| 4217 |
// If the append entry term is newer than the current term, erase our |
| 4218 |
// vote. |
| 4219 |
if lterm > n.term { |
| 4220 |
n.term = lterm |
| 4221 |
n.vote = noVote |
| 4222 |
n.writeTermVote() |
| 4223 |
} else { |
| 4224 |
assert.Unreachable( |
| 4225 |
"Two leaders using the same term", |
| 4226 |
map[string]any{ |
| 4227 |
"n.accName": n.accName, |
| 4228 |
"n.group": n.group, |
| 4229 |
"n.id": n.id, |
| 4230 |
"n.term": n.term, |
| 4231 |
"ae.leader": ae.leader, |
| 4232 |
"ae.term": ae.term, |
| 4233 |
"ae.lterm": ae.lterm, |
| 4234 |
}) |
| 4235 |
} |
| 4236 |
n.debug("Received append entry from another leader, stepping down to %q", ae.leader) |
| 4237 |
n.stepdownLocked(ae.leader) |
| 4238 |
} else { |
| 4239 |
// Let them know we are the leader. |
| 4240 |
ar := newAppendEntryResponse(n.term, n.pindex, n.id, false) |
| 4241 |
n.debug("AppendEntry ignoring old term from another leader") |
| 4242 |
n.sendRPC(ae.reply, _EMPTY_, ar.encode(arbuf)) |
| 4243 |
arPool.Put(ar) |
| 4244 |
n.Unlock() |
| 4245 |
return |
| 4246 |
} |
| 4247 |
} |
| 4248 |
|
| 4249 |
// If we received an append entry as a candidate then it would appear that |
| 4250 |
// another node has taken on the leader role already, so we should convert |
| 4251 |
// to a follower of that node instead. |
| 4252 |
if n.State() == Candidate { |
| 4253 |
// If we have a leader in the current term or higher, we should stepdown, |
| 4254 |
// write the term and vote if the term of the request is higher. |
| 4255 |
if lterm >= n.term { |
| 4256 |
// If the append entry term is newer than the current term, erase our |
| 4257 |
// vote. |
| 4258 |
if lterm > n.term { |
| 4259 |
n.term = lterm |
| 4260 |
n.vote = noVote |
| 4261 |
n.writeTermVote() |
| 4262 |
} |
| 4263 |
n.debug("Received append entry in candidate state from %q, converting to follower", ae.leader) |
| 4264 |
n.stepdownLocked(ae.leader) |
| 4265 |
n.updateLeadChange(false) |
| 4266 |
} |
| 4267 |
} |
| 4268 |
|
| 4269 |
// Catching up state. |
| 4270 |
catchingUp := n.catchup != nil |
| 4271 |
// Is this a new entry? New entries will be delivered on the append entry |
| 4272 |
// sub, rather than a catch-up sub. |
| 4273 |
isNew := sub != nil && sub == n.aesub |
| 4274 |
// Entries arriving on any other subscription are catchup entries being streamed |
| 4275 |
// to our dedicated catchup inbox. |
| 4276 |
isCatchup := sub != nil && !isNew |
| 4277 |
|
| 4278 |
// If we are/were catching up ignore old catchup subs, but only if catching up from an older server |
| 4279 |
// that doesn't send the leader term when catching up or if we would truncate as a result. |
| 4280 |
// We can reject old catchups from newer subs later, just by checking the append entry is on the correct term. |
| 4281 |
if !isNew && sub != nil && (ae.lterm == 0 || ae.pindex < n.pindex) && (!catchingUp || sub != n.catchup.sub) { |
| 4282 |
n.Unlock() |
| 4283 |
n.debug("AppendEntry ignoring old entry from previous catchup") |
| 4284 |
return |
| 4285 |
} |
| 4286 |
|
| 4287 |
// If this term is greater than ours. |
| 4288 |
if lterm > n.term { |
| 4289 |
n.term = lterm |
| 4290 |
n.vote = noVote |
| 4291 |
if isNew { |
| 4292 |
n.writeTermVote() |
| 4293 |
} |
| 4294 |
if n.State() != Follower { |
| 4295 |
n.debug("Term higher than ours and we are not a follower: %v, stepping down to %q", n.State(), ae.leader) |
| 4296 |
n.stepdownLocked(ae.leader) |
| 4297 |
} |
| 4298 |
} else if lterm < n.term && sub != nil && (isNew || ae.lterm != 0) { |
| 4299 |
// Anything that's below our expected highest term needs to be rejected. |
| 4300 |
// Unless we're replaying (sub=nil), in which case we'll always continue. |
| 4301 |
// For backward-compatibility we shouldn't reject if we're being caught up by an old server. |
| 4302 |
if !isNew { |
| 4303 |
n.debug("AppendEntry ignoring old entry from previous catchup") |
| 4304 |
n.Unlock() |
| 4305 |
return |
| 4306 |
} |
| 4307 |
n.debug("Rejected AppendEntry from a leader (%s) with term %d which is less than ours", ae.leader, lterm) |
| 4308 |
ar := newAppendEntryResponse(n.term, n.pindex, n.id, false) |
| 4309 |
n.Unlock() |
| 4310 |
n.sendRPC(ae.reply, _EMPTY_, ar.encode(arbuf)) |
| 4311 |
arPool.Put(ar) |
| 4312 |
return |
| 4313 |
} |
| 4314 |
|
| 4315 |
// Check state if we are catching up. |
| 4316 |
if catchingUp { |
| 4317 |
if cs := n.catchup; cs != nil && n.pterm >= cs.cterm && n.pindex >= cs.cindex { |
| 4318 |
// If we are here we are good, so if we have a catchup pending we can cancel. |
| 4319 |
n.cancelCatchup() |
| 4320 |
// Reset our notion of catching up. |
| 4321 |
catchingUp = false |
| 4322 |
} else if isNew { |
| 4323 |
var ar *appendEntryResponse |
| 4324 |
var inbox string |
| 4325 |
// Check to see if we are stalled. If so recreate our catchup state and resend response. |
| 4326 |
if n.catchupStalled() { |
| 4327 |
n.debug("Catchup may be stalled, will request again") |
| 4328 |
inbox = n.createCatchup(ae) |
| 4329 |
ar = newAppendEntryResponse(n.pterm, n.pindex, n.id, false) |
| 4330 |
} |
| 4331 |
n.Unlock() |
| 4332 |
if ar != nil { |
| 4333 |
n.sendRPC(ae.reply, inbox, ar.encode(arbuf)) |
| 4334 |
arPool.Put(ar) |
| 4335 |
} |
| 4336 |
// Ignore new while catching up or replaying. |
| 4337 |
return |
| 4338 |
} |
| 4339 |
} |
| 4340 |
|
| 4341 |
if isNew && n.leader != ae.leader && n.State() == Follower { |
| 4342 |
n.debug("AppendEntry updating leader to %q", ae.leader) |
| 4343 |
n.updateLeader(ae.leader) |
| 4344 |
n.writeTermVote() |
| 4345 |
n.resetElectionTimeout() |
| 4346 |
n.updateLeadChange(false) |
| 4347 |
} |
| 4348 |
|
| 4349 |
// Track leader directly |
| 4350 |
// But, do so after all consistency checks so we don't track an old leader. |
| 4351 |
if isNew && ae.leader != noLeader && ae.leader == n.leader { |
| 4352 |
if ps := n.peers[ae.leader]; ps != nil { |
| 4353 |
ps.ts = time.Now() |
| 4354 |
} |
| 4355 |
} |
| 4356 |
|
| 4357 |
// If commits are outpacing our applies, temporarily stop accepting new entries to avoid falling further behind. |
| 4358 |
// This encourages the leader to sync us via a snapshot instead. We use max(applied, papplied) to avoid |
| 4359 |
// incorrectly triggering this pause immediately after receiving a snapshot. |
| 4360 |
applied := max(n.applied, n.papplied) |
| 4361 |
commit := max(n.commit, n.papplied) |
| 4362 |
if sub != nil && (commit > applied || n.quorumPaused) { |
| 4363 |
diff := commit - applied |
| 4364 |
if n.quorumPaused { |
| 4365 |
if n.overrun(diff, paeWarnThreshold, paeWarnBytes) { |
| 4366 |
if catchingUp { |
| 4367 |
n.cancelCatchup() |
| 4368 |
} |
| 4369 |
n.Unlock() |
| 4370 |
return |
| 4371 |
} |
| 4372 |
// Once we're sufficiently below the threshold, we continue again. We'll likely receive a snapshot |
| 4373 |
// from the leader. |
| 4374 |
n.quorumPaused = false |
| 4375 |
var state StreamState |
| 4376 |
n.wal.FastState(&state) |
| 4377 |
n.warn("Quorum resumed: commit %d, applied %d, WAL size %s", commit, applied, friendlyBytes(state.Bytes)) |
| 4378 |
} else if n.overrun(diff, pauseQuorumThreshold, pauseQuorumBytes) { |
| 4379 |
// It takes a while until we reach the pause threshold, but once we do we enter a "cooldown period". |
| 4380 |
n.quorumPaused = true |
| 4381 |
n.overrunCount++ |
| 4382 |
var state StreamState |
| 4383 |
n.wal.FastState(&state) |
| 4384 |
n.warn("Quorum paused, falling behind: commit %d != applied %d, WAL size %s", commit, applied, friendlyBytes(state.Bytes)) |
| 4385 |
if catchingUp { |
| 4386 |
n.cancelCatchup() |
| 4387 |
} |
| 4388 |
n.Unlock() |
| 4389 |
return |
| 4390 |
} |
| 4391 |
} |
| 4392 |
|
| 4393 |
if ae.pterm != n.pterm || ae.pindex != n.pindex { |
| 4394 |
// Check if this is a lower or equal index than what we were expecting. |
| 4395 |
if ae.pindex <= n.pindex { |
| 4396 |
n.debug("AppendEntry detected pindex less than/equal to ours: [%d:%d] vs [%d:%d]", ae.pterm, ae.pindex, n.pterm, n.pindex) |
| 4397 |
var success bool |
| 4398 |
|
| 4399 |
if ae.pindex < n.commit { |
| 4400 |
// If we have already committed this entry, just mark success. |
| 4401 |
success = true |
| 4402 |
n.debug("AppendEntry pindex %d below commit %d, marking success", ae.pindex, n.commit) |
| 4403 |
} else if eae, _ := n.loadEntry(ae.pindex); eae == nil { |
| 4404 |
// If terms are equal, and we are not catching up, we have simply already processed this message. |
| 4405 |
// This can happen on server restarts based on timings of snapshots. |
| 4406 |
if ae.pterm == n.pterm && isNew { |
| 4407 |
success = true |
| 4408 |
n.debug("AppendEntry pindex %d already processed, marking success", ae.pindex) |
| 4409 |
} else if ae.pindex == n.pindex { |
| 4410 |
// Check if only our terms do not match here. |
| 4411 |
// Make sure pterms match and we take on the leader's. |
| 4412 |
// This prevents constant spinning. |
| 4413 |
n.truncateWAL(ae.pterm, ae.pindex) |
| 4414 |
} else { |
| 4415 |
snap, err := n.loadLastSnapshot() |
| 4416 |
if err == nil && snap.lastIndex == ae.pindex && snap.lastTerm == ae.pterm { |
| 4417 |
// Entry can't be found, this is normal because we have a snapshot at this index. |
| 4418 |
// Truncate back to where we've created the snapshot. |
| 4419 |
n.truncateWAL(snap.lastTerm, snap.lastIndex) |
| 4420 |
// Only continue if truncation was successful, and we ended up such that we can safely continue. |
| 4421 |
if ae.pterm == n.pterm && ae.pindex == n.pindex { |
| 4422 |
goto CONTINUE |
| 4423 |
} |
| 4424 |
} else { |
| 4425 |
// Otherwise, something has gone very wrong and we need to reset. |
| 4426 |
n.resetWAL() |
| 4427 |
} |
| 4428 |
} |
| 4429 |
} else if eae.term == ae.pterm { |
| 4430 |
// If terms match we can delete all entries past this one, and then continue storing the current entry. |
| 4431 |
n.truncateWAL(ae.pterm, ae.pindex) |
| 4432 |
// Only continue if truncation was successful, and we ended up such that we can safely continue. |
| 4433 |
if ae.pterm == n.pterm && ae.pindex == n.pindex { |
| 4434 |
goto CONTINUE |
| 4435 |
} |
| 4436 |
} else { |
| 4437 |
// If terms mismatched, delete that entry and all others past it. |
| 4438 |
// But only if we haven't already committed past this point. |
| 4439 |
if eae.pindex < n.commit { |
| 4440 |
success = true |
| 4441 |
assert.Unreachable("Truncate to earlier entry would lose commits", map[string]any{ |
| 4442 |
"n.accName": n.accName, |
| 4443 |
"n.group": n.group, |
| 4444 |
"n.id": n.id, |
| 4445 |
"n.term": n.term, |
| 4446 |
"n.pindex": n.pindex, |
| 4447 |
"n.commit": n.commit, |
| 4448 |
"n.applied": n.applied, |
| 4449 |
"ae.pindex": ae.pindex, |
| 4450 |
"ae.pterm": ae.pterm, |
| 4451 |
"ae.commit": ae.commit, |
| 4452 |
"eae.pterm": eae.pterm, |
| 4453 |
"eae.pindex": eae.pindex, |
| 4454 |
}) |
| 4455 |
} else { |
| 4456 |
n.truncateWAL(eae.pterm, eae.pindex) |
| 4457 |
} |
| 4458 |
} |
| 4459 |
// Cancel regardless if unsuccessful. |
| 4460 |
if !success { |
| 4461 |
n.cancelCatchup() |
| 4462 |
} |
| 4463 |
// Intentionally not responding. Otherwise, we could erroneously report "success". Reporting |
| 4464 |
// non-success is not needed either, and would only be wasting messages. |
| 4465 |
// For example, if we got partial catchup, and then the "real-time" messages came in very delayed. |
| 4466 |
// If we reported "success" on those "real-time" messages, we'd wrongfully be providing |
| 4467 |
// quorum while not having an up-to-date log. |
| 4468 |
n.Unlock() |
| 4469 |
return |
| 4470 |
} |
| 4471 |
|
| 4472 |
// Check if we are catching up. If we are here we know the leader did not have all of the entries |
| 4473 |
// so make sure this is a snapshot entry. If it is not start the catchup process again since it |
| 4474 |
// means we may have missed additional messages. |
| 4475 |
if catchingUp { |
| 4476 |
// This means we already entered into a catchup state but what the leader sent us did not match what we expected. |
| 4477 |
// Snapshots and peerstate will always be together when a leader is catching us up in this fashion. |
| 4478 |
if len(ae.entries) != 2 || ae.entries[0].Type != EntrySnapshot || ae.entries[1].Type != EntryPeerState { |
| 4479 |
n.warn("Expected first catchup entry to be a snapshot and peerstate, will retry") |
| 4480 |
n.cancelCatchup() |
| 4481 |
n.Unlock() |
| 4482 |
return |
| 4483 |
} |
| 4484 |
|
| 4485 |
if ps, err := decodePeerState(ae.entries[1].Data); err == nil { |
| 4486 |
n.processPeerState(ps) |
| 4487 |
// Also need to copy from client's buffer. |
| 4488 |
ae.entries[0].Data = copyBytes(ae.entries[0].Data) |
| 4489 |
} else { |
| 4490 |
n.warn("Could not parse snapshot peerstate correctly") |
| 4491 |
n.cancelCatchup() |
| 4492 |
n.Unlock() |
| 4493 |
return |
| 4494 |
} |
| 4495 |
|
| 4496 |
// Inherit state from appendEntry with the leader's snapshot. |
| 4497 |
hadPreviousSnapshot := n.snapfile != _EMPTY_ |
| 4498 |
|
| 4499 |
snap := &snapshot{ |
| 4500 |
lastTerm: ae.pterm, |
| 4501 |
lastIndex: ae.pindex, |
| 4502 |
peerstate: encodePeerState(&peerState{n.peerNames(), n.csz, n.extSt}), |
| 4503 |
data: ae.entries[0].Data, |
| 4504 |
} |
| 4505 |
// Install the leader's snapshot as our own. |
| 4506 |
if err := n.installSnapshot(snap); err != nil { |
| 4507 |
n.setWriteErrLocked(err) |
| 4508 |
n.Unlock() |
| 4509 |
return |
| 4510 |
} |
| 4511 |
n.pindex = ae.pindex |
| 4512 |
n.pterm = ae.pterm |
| 4513 |
n.commit = ae.pindex |
| 4514 |
n.resetInitializing() |
| 4515 |
|
| 4516 |
if !hadPreviousSnapshot { |
| 4517 |
// If the first snapshot we install is received from another server, then we immediately signal |
| 4518 |
// to the upper-layer it can coalesce catchup entries. |
| 4519 |
n.sendCatchupSignal() |
| 4520 |
} |
| 4521 |
// Now send snapshot to upper levels. Only send the snapshot, not the peerstate entry. |
| 4522 |
n.apply.push(newCommittedEntry(n.commit, ae.entries[:1])) |
| 4523 |
if hadPreviousSnapshot { |
| 4524 |
// Signal catchup only after we've sent the snapshot. That ensures the upper-layer processes the snapshot |
| 4525 |
// as-is and can only coalesce other catchup entries after this one. |
| 4526 |
n.sendCatchupSignal() |
| 4527 |
} |
| 4528 |
n.Unlock() |
| 4529 |
return |
| 4530 |
} |
| 4531 |
|
| 4532 |
// Setup our state for catching up. |
| 4533 |
n.debug("AppendEntry did not match [%d:%d] with [%d:%d]", ae.pterm, ae.pindex, n.pterm, n.pindex) |
| 4534 |
inbox := n.createCatchup(ae) |
| 4535 |
ar := newAppendEntryResponse(n.pterm, n.pindex, n.id, false) |
| 4536 |
n.Unlock() |
| 4537 |
n.sendRPC(ae.reply, inbox, ar.encode(arbuf)) |
| 4538 |
arPool.Put(ar) |
| 4539 |
return |
| 4540 |
} |
| 4541 |
|
| 4542 |
CONTINUE: |
| 4543 |
// Save to our WAL if we have entries. |
| 4544 |
if ae.shouldStore() { |
| 4545 |
// Only store if an original which will have sub != nil |
| 4546 |
if sub != nil { |
| 4547 |
if err := n.storeToWAL(ae); err != nil { |
| 4548 |
if err != ErrStoreClosed { |
| 4549 |
n.warn("Error storing entry to WAL: %v", err) |
| 4550 |
} |
| 4551 |
n.Unlock() |
| 4552 |
return |
| 4553 |
} |
| 4554 |
n.cachePendingEntry(ae) |
| 4555 |
n.resetInitializing() |
| 4556 |
} else { |
| 4557 |
// This is a replay on startup so just take the appendEntry version. |
| 4558 |
n.pterm = ae.term |
| 4559 |
n.pindex = ae.pindex + 1 |
| 4560 |
} |
| 4561 |
} |
| 4562 |
|
| 4563 |
// Check to see if we have any related entries to process here. |
| 4564 |
for _, e := range ae.entries { |
| 4565 |
switch e.Type { |
| 4566 |
case EntryLeaderTransfer: |
| 4567 |
// Only process these if they are new, so no replays or catchups. |
| 4568 |
if isNew { |
| 4569 |
maybeLeader := string(e.Data) |
| 4570 |
// This is us. We need to check if we can become the leader. |
| 4571 |
if maybeLeader == n.id { |
| 4572 |
// If not an observer and not paused we are good to go. |
| 4573 |
if !n.observer && !n.paused { |
| 4574 |
n.lxfer = true |
| 4575 |
n.xferCampaign() |
| 4576 |
} else if n.paused { |
| 4577 |
// Here we can become a leader but need to wait for resume of the apply queue. |
| 4578 |
n.lxfer = true |
| 4579 |
} |
| 4580 |
} |
| 4581 |
} |
| 4582 |
case EntryAddPeer: |
| 4583 |
// When receiving or restoring, mark membership as changing. |
| 4584 |
// Set to the index where this entry was stored (pindex is now this entry's index) |
| 4585 |
if newPeer := string(e.Data); len(newPeer) == idLen { |
| 4586 |
// Track directly, but wait for commit to be official |
| 4587 |
n.membChange = &membChange{index: n.pindex, peer: newPeer} |
| 4588 |
if _, ok := n.peers[newPeer]; !ok { |
| 4589 |
n.peers[newPeer] = &lps{time.Time{}, 0} |
| 4590 |
} |
| 4591 |
n.adjustClusterSizeAndQuorum() |
| 4592 |
// Store our peer in our global peer map for all peers. |
| 4593 |
peers.LoadOrStore(newPeer, newPeer) |
| 4594 |
} |
| 4595 |
case EntryRemovePeer: |
| 4596 |
// When receiving or restoring, mark membership as changing. |
| 4597 |
// Set to the index where this entry was stored (pindex is now this entry's index) |
| 4598 |
if oldPeer := string(e.Data); len(oldPeer) == idLen { |
| 4599 |
// Track directly, but wait for commit to be official |
| 4600 |
ps, ok := n.peers[oldPeer] |
| 4601 |
if !ok { |
| 4602 |
ps = &lps{time.Time{}, 0} |
| 4603 |
|
| 4604 |
} |
| 4605 |
n.membChange = &membChange{index: n.pindex, peer: oldPeer, prev: ps} |
| 4606 |
delete(n.peers, oldPeer) |
| 4607 |
n.adjustClusterSizeAndQuorum() |
| 4608 |
} |
| 4609 |
} |
| 4610 |
} |
| 4611 |
|
| 4612 |
// Make a copy of these values, as the AppendEntry might be cached and returned to the pool in applyCommit. |
| 4613 |
aeCommit := ae.commit |
| 4614 |
aeReply := ae.reply |
| 4615 |
|
| 4616 |
// Apply anything we need here. |
| 4617 |
if aeCommit > n.commit { |
| 4618 |
// If we're catching up, we might need to signal that it's okay to potentially coalesce entries from here. |
| 4619 |
if catchingUp { |
| 4620 |
n.sendCatchupSignal() |
| 4621 |
} |
| 4622 |
if n.paused { |
| 4623 |
n.hcommit = aeCommit |
| 4624 |
n.debug("Paused, not applying %d", aeCommit) |
| 4625 |
} else { |
| 4626 |
for index := n.commit + 1; index <= aeCommit; index++ { |
| 4627 |
if err := n.applyCommit(index); err != nil { |
| 4628 |
break |
| 4629 |
} |
| 4630 |
} |
| 4631 |
} |
| 4632 |
} |
| 4633 |
|
| 4634 |
// The only way for the leader to receive "success" MUST be through this path. |
| 4635 |
// Only new entries are allowed to provide quorum, since providing quorum based |
| 4636 |
// on catchup is unsafe. Catchup entries are acked through here, but only on a |
| 4637 |
// dedicated progress inbox. |
| 4638 |
var ar *appendEntryResponse |
| 4639 |
if isNew || (isCatchup && strings.HasPrefix(aeReply, raftCatchupProgressPre)) { |
| 4640 |
ar = newAppendEntryResponse(n.pterm, n.pindex, n.id, true) |
| 4641 |
} |
| 4642 |
n.Unlock() |
| 4643 |
|
| 4644 |
// Success. Send our response. |
| 4645 |
if ar != nil { |
| 4646 |
n.sendRPC(aeReply, _EMPTY_, ar.encode(arbuf)) |
| 4647 |
arPool.Put(ar) |
| 4648 |
} |
| 4649 |
} |
| 4650 |
|
| 4651 |
// resetInitializing resets the notion of initializing. |
| 4652 |
// If we were scaling up, also leaves observer mode. |
| 4653 |
// Lock should be held. |
| 4654 |
func (n *raft) resetInitializing() { |
| 4655 |
n.initializing = false |
| 4656 |
if n.scaleUp { |
| 4657 |
n.scaleUp = false |
| 4658 |
n.setObserverLocked(false, extUndetermined) |
| 4659 |
} |
| 4660 |
} |
| 4661 |
|
| 4662 |
// processPeerState is called when a peer state entry is received |
| 4663 |
// over the wire or when we're updating known peers. |
| 4664 |
// Lock should be held. |
| 4665 |
func (n *raft) processPeerState(ps *peerState) { |
| 4666 |
// Update our version of peers to that of the leader. Calculate |
| 4667 |
// the number of nodes needed to establish a quorum. |
| 4668 |
n.csz = ps.clusterSize |
| 4669 |
n.qn = n.csz/2 + 1 |
| 4670 |
|
| 4671 |
old := n.peers |
| 4672 |
n.peers = make(map[string]*lps) |
| 4673 |
for _, peer := range ps.knownPeers { |
| 4674 |
if lp := old[peer]; lp != nil { |
| 4675 |
n.peers[peer] = lp |
| 4676 |
delete(old, peer) |
| 4677 |
} else { |
| 4678 |
n.peers[peer] = &lps{time.Time{}, 0} |
| 4679 |
} |
| 4680 |
// If we were on the removed list reverse that here. |
| 4681 |
if n.removed != nil { |
| 4682 |
delete(n.removed, peer) |
| 4683 |
if len(n.removed) == 0 { |
| 4684 |
n.removed = nil |
| 4685 |
} |
| 4686 |
} |
| 4687 |
} |
| 4688 |
// Any remaining old nodes are marked as removed, so they can't be |
| 4689 |
// re-added via automatic peer tracking. |
| 4690 |
if len(old) > 0 { |
| 4691 |
if n.removed == nil { |
| 4692 |
n.removed = map[string]time.Time{} |
| 4693 |
} |
| 4694 |
now := time.Now() |
| 4695 |
for peer := range old { |
| 4696 |
n.removed[peer] = now |
| 4697 |
} |
| 4698 |
} |
| 4699 |
n.debug("Update peers from leader to %+v", n.peers) |
| 4700 |
n.writePeerState(ps) |
| 4701 |
} |
| 4702 |
|
| 4703 |
// processAppendEntryResponse is called when we receive an append entry |
| 4704 |
// response from another node. They will send a confirmation to tell us |
| 4705 |
// whether they successfully committed the entry or not. |
| 4706 |
func (n *raft) processAppendEntryResponse(ar *appendEntryResponse) { |
| 4707 |
n.trackPeer(ar.peer) |
| 4708 |
|
| 4709 |
if ar.success { |
| 4710 |
// The remote node successfully committed the append entry. |
| 4711 |
// They agree with our leadership and are happy with the state of the log. |
| 4712 |
// In this case ar.term was populated with the remote's pterm. If this matches |
| 4713 |
// our term, we can use it to check for quorum and up our commit. |
| 4714 |
var err error |
| 4715 |
var committed bool |
| 4716 |
|
| 4717 |
n.Lock() |
| 4718 |
if n.trackResponse(ar) { |
| 4719 |
committed, err = n.tryCommit(ar.index) |
| 4720 |
} |
| 4721 |
n.Unlock() |
| 4722 |
|
| 4723 |
// Leader was peer-removed. Attempt a step-down to |
| 4724 |
// a new leader before shutting down. |
| 4725 |
if err == errNodeRemoved { |
| 4726 |
n.StepDown() |
| 4727 |
n.Stop() |
| 4728 |
} |
| 4729 |
|
| 4730 |
// Send a heartbeat if there is no other message lined |
| 4731 |
// up, so that followers can apply without waiting for |
| 4732 |
// the next message. |
| 4733 |
if committed && n.prop.len() == 0 { |
| 4734 |
n.sendHeartbeat() |
| 4735 |
} |
| 4736 |
|
| 4737 |
arPool.Put(ar) |
| 4738 |
} else if ar.reply != _EMPTY_ { |
| 4739 |
// The remote node didn't commit the append entry, and they believe they |
| 4740 |
// are behind and have specified a reply subject, so let's try to catch them up. |
| 4741 |
// In this case ar.term was populated with the remote's pterm. |
| 4742 |
n.catchupFollower(ar) |
| 4743 |
} else { |
| 4744 |
n.Lock() |
| 4745 |
if ar.term > n.term { |
| 4746 |
// The remote node didn't commit the append entry, it looks like |
| 4747 |
// they are on a newer term than we are. Step down. |
| 4748 |
// In this case ar.term was populated with the remote's term. |
| 4749 |
n.term = ar.term |
| 4750 |
n.vote = noVote |
| 4751 |
n.writeTermVote() |
| 4752 |
n.warn("Detected another leader with higher term, will stepdown") |
| 4753 |
n.stepdownLocked(noLeader) |
| 4754 |
} |
| 4755 |
n.Unlock() |
| 4756 |
// Either way, return back to pool. |
| 4757 |
arPool.Put(ar) |
| 4758 |
} |
| 4759 |
} |
| 4760 |
|
| 4761 |
// handleAppendEntryResponse processes responses to append entries. |
| 4762 |
func (n *raft) handleAppendEntryResponse(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) { |
| 4763 |
ar := decodeAppendEntryResponse(msg) |
| 4764 |
if ar == nil { |
| 4765 |
n.error("Received malformed append entry response") |
| 4766 |
return |
| 4767 |
} |
| 4768 |
ar.reply = reply |
| 4769 |
n.resp.push(ar) |
| 4770 |
} |
| 4771 |
|
| 4772 |
func (n *raft) buildAppendEntry(entries []*Entry) *appendEntry { |
| 4773 |
return newAppendEntry(n.id, n.term, n.commit, n.pterm, n.pindex, entries) |
| 4774 |
} |
| 4775 |
|
| 4776 |
// Determine if we should store an entry. This stops us from storing |
| 4777 |
// heartbeat messages. |
| 4778 |
func (ae *appendEntry) shouldStore() bool { |
| 4779 |
return ae != nil && len(ae.entries) > 0 |
| 4780 |
} |
| 4781 |
|
| 4782 |
// Store our append entry to our WAL. |
| 4783 |
// lock should be held. |
| 4784 |
func (n *raft) storeToWAL(ae *appendEntry) error { |
| 4785 |
if ae == nil { |
| 4786 |
return fmt.Errorf("raft: Missing append entry for storage") |
| 4787 |
} |
| 4788 |
if n.werr != nil { |
| 4789 |
return n.werr |
| 4790 |
} |
| 4791 |
|
| 4792 |
seq, _, err := n.wal.StoreMsg(_EMPTY_, nil, ae.buf, 0) |
| 4793 |
if err != nil { |
| 4794 |
n.setWriteErrLocked(err) |
| 4795 |
return err |
| 4796 |
} |
| 4797 |
|
| 4798 |
// Sanity checking for now. |
| 4799 |
if index := ae.pindex + 1; index != seq { |
| 4800 |
n.warn("Wrong index, ae is %+v, index stored was %d, n.pindex is %d, will reset", ae, seq, n.pindex) |
| 4801 |
if n.State() == Leader { |
| 4802 |
n.stepdownLocked(n.selectNextLeader()) |
| 4803 |
} |
| 4804 |
// Reset and cancel any catchup. |
| 4805 |
n.resetWAL() |
| 4806 |
n.cancelCatchup() |
| 4807 |
return errEntryStoreFailed |
| 4808 |
} |
| 4809 |
|
| 4810 |
n.bytes += n.entryStoreSize(ae) |
| 4811 |
n.pterm = ae.term |
| 4812 |
n.pindex = seq |
| 4813 |
return nil |
| 4814 |
} |
| 4815 |
|
| 4816 |
const ( |
| 4817 |
pauseQuorumThreshold = 100_000 |
| 4818 |
pauseQuorumBytes = 1 * 1024 * 1024 * 1024 // 1GB |
| 4819 |
|
| 4820 |
paeDropThreshold = 20_000 |
| 4821 |
paeDropBytes = 256 * 1024 * 1024 // 256MB |
| 4822 |
|
| 4823 |
paeWarnThreshold = 10_000 |
| 4824 |
paeWarnModulo = 5_000 |
| 4825 |
paeWarnBytes = 128 * 1024 * 1024 // 128MB |
| 4826 |
paeWarnBytesModulo = 32 * 1024 * 1024 // 32MB |
| 4827 |
) |
| 4828 |
|
| 4829 |
func (n *raft) sendAppendEntry(entries []*Entry) { |
| 4830 |
n.Lock() |
| 4831 |
defer n.Unlock() |
| 4832 |
n.sendAppendEntryLocked(entries, true) |
| 4833 |
} |
| 4834 |
|
| 4835 |
// Returns nil if an appendEntry was appended to our WAL and sent to followers, |
| 4836 |
// an error otherwise. |
| 4837 |
func (n *raft) sendAppendEntryLocked(entries []*Entry, checkLeader bool) error { |
| 4838 |
// Safeguard against sending an append entry right after a stepdown from a different goroutine. |
| 4839 |
// Specifically done while holding the lock to not race. |
| 4840 |
if checkLeader && n.State() != Leader { |
| 4841 |
n.debug("Not sending append entry, not leader") |
| 4842 |
return errNotLeader |
| 4843 |
} |
| 4844 |
ae := n.buildAppendEntry(entries) |
| 4845 |
|
| 4846 |
var err error |
| 4847 |
var scratch [1024]byte |
| 4848 |
ae.buf, err = ae.encode(scratch[:]) |
| 4849 |
if err != nil { |
| 4850 |
return err |
| 4851 |
} |
| 4852 |
|
| 4853 |
// If we have entries store this in our wal. |
| 4854 |
shouldStore := ae.shouldStore() |
| 4855 |
if shouldStore { |
| 4856 |
if err := n.storeToWAL(ae); err != nil { |
| 4857 |
return err |
| 4858 |
} |
| 4859 |
n.active = time.Now() |
| 4860 |
n.cachePendingEntry(ae) |
| 4861 |
} |
| 4862 |
n.sendRPC(n.asubj, n.areply, ae.buf) |
| 4863 |
if !shouldStore { |
| 4864 |
ae.returnToPool() |
| 4865 |
} |
| 4866 |
if n.csz == 1 { |
| 4867 |
n.tryCommit(n.pindex) |
| 4868 |
} |
| 4869 |
return nil |
| 4870 |
} |
| 4871 |
|
| 4872 |
// cachePendingEntry saves append entries in memory for faster processing during applyCommit. |
| 4873 |
// Only save so many however to avoid memory bloat. |
| 4874 |
func (n *raft) cachePendingEntry(ae *appendEntry) { |
| 4875 |
// Invalidate any cache entry at this index, we might have |
| 4876 |
// stored it previously with a different value. |
| 4877 |
if pae, ok := n.pae[n.pindex]; ok { |
| 4878 |
n.paeBytes -= n.entryStoreSize(pae) |
| 4879 |
delete(n.pae, n.pindex) |
| 4880 |
} |
| 4881 |
if l := uint64(len(n.pae)); l < paeDropThreshold && n.paeBytes < paeDropBytes { |
| 4882 |
prev := n.paeBytes |
| 4883 |
n.pae[n.pindex], l = ae, l+1 |
| 4884 |
n.paeBytes += n.entryStoreSize(ae) |
| 4885 |
if l >= paeWarnThreshold && l%paeWarnModulo == 0 { |
| 4886 |
n.warn("%d append entries pending", len(n.pae)) |
| 4887 |
} else if b := n.paeBytes; b >= paeWarnBytes { |
| 4888 |
// Only log on transition past another paeWarnBytesModulo. |
| 4889 |
if b/paeWarnBytesModulo != prev/paeWarnBytesModulo { |
| 4890 |
n.warn("%d append entries pending, %s", l, friendlyBytes(b)) |
| 4891 |
} |
| 4892 |
} |
| 4893 |
} |
| 4894 |
} |
| 4895 |
|
| 4896 |
// entryStoreSize returns the byte size of the given append entry as stored in our WAL. |
| 4897 |
// Lock should be held. |
| 4898 |
func (n *raft) entryStoreSize(ae *appendEntry) uint64 { |
| 4899 |
if ae == nil || ae.buf == nil { |
| 4900 |
return 0 |
| 4901 |
} |
| 4902 |
if n.wtype == FileStorage { |
| 4903 |
return fileStoreMsgSize(_EMPTY_, nil, ae.buf) |
| 4904 |
} |
| 4905 |
return memStoreMsgSize(_EMPTY_, nil, ae.buf) |
| 4906 |
} |
| 4907 |
|
| 4908 |
// resetPendingEntries clears our append entry cache. |
| 4909 |
// Lock should be held. |
| 4910 |
func (n *raft) resetPendingEntries() { |
| 4911 |
if len(n.pae) > 0 { |
| 4912 |
n.pae = make(map[uint64]*appendEntry) |
| 4913 |
} |
| 4914 |
n.paeBytes = 0 |
| 4915 |
} |
| 4916 |
|
| 4917 |
type extensionState uint16 |
| 4918 |
|
| 4919 |
const ( |
| 4920 |
extUndetermined = extensionState(iota) |
| 4921 |
extExtended |
| 4922 |
extNotExtended |
| 4923 |
) |
| 4924 |
|
| 4925 |
type peerState struct { |
| 4926 |
knownPeers []string |
| 4927 |
clusterSize int |
| 4928 |
domainExt extensionState |
| 4929 |
} |
| 4930 |
|
| 4931 |
func peerStateBufSize(ps *peerState) int { |
| 4932 |
return 4 + 4 + (idLen * len(ps.knownPeers)) + 2 |
| 4933 |
} |
| 4934 |
|
| 4935 |
func encodePeerState(ps *peerState) []byte { |
| 4936 |
var le = binary.LittleEndian |
| 4937 |
buf := make([]byte, peerStateBufSize(ps)) |
| 4938 |
le.PutUint32(buf[0:], uint32(ps.clusterSize)) |
| 4939 |
le.PutUint32(buf[4:], uint32(len(ps.knownPeers))) |
| 4940 |
wi := 8 |
| 4941 |
for _, peer := range ps.knownPeers { |
| 4942 |
copy(buf[wi:], peer) |
| 4943 |
wi += idLen |
| 4944 |
} |
| 4945 |
le.PutUint16(buf[wi:], uint16(ps.domainExt)) |
| 4946 |
return buf |
| 4947 |
} |
| 4948 |
|
| 4949 |
func decodePeerState(buf []byte) (*peerState, error) { |
| 4950 |
if len(buf) < 8 { |
| 4951 |
return nil, errCorruptPeers |
| 4952 |
} |
| 4953 |
var le = binary.LittleEndian |
| 4954 |
ps := &peerState{clusterSize: int(le.Uint32(buf[0:]))} |
| 4955 |
expectedPeers := int(le.Uint32(buf[4:])) |
| 4956 |
buf = buf[8:] |
| 4957 |
ri := 0 |
| 4958 |
for i, n := 0, expectedPeers; i < n && ri+idLen <= len(buf); i++ { |
| 4959 |
ps.knownPeers = append(ps.knownPeers, string(buf[ri:ri+idLen])) |
| 4960 |
ri += idLen |
| 4961 |
} |
| 4962 |
if len(ps.knownPeers) != expectedPeers { |
| 4963 |
return nil, errCorruptPeers |
| 4964 |
} |
| 4965 |
if len(buf[ri:]) >= 2 { |
| 4966 |
ps.domainExt = extensionState(le.Uint16(buf[ri:])) |
| 4967 |
} |
| 4968 |
return ps, nil |
| 4969 |
} |
| 4970 |
|
| 4971 |
// Lock should be held. |
| 4972 |
func (n *raft) peerNames() []string { |
| 4973 |
peers := make([]string, 0, len(n.peers)) |
| 4974 |
for name := range n.peers { |
| 4975 |
peers = append(peers, name) |
| 4976 |
} |
| 4977 |
return peers |
| 4978 |
} |
| 4979 |
|
| 4980 |
func (n *raft) currentPeerState() *peerState { |
| 4981 |
n.RLock() |
| 4982 |
ps := n.currentPeerStateLocked() |
| 4983 |
n.RUnlock() |
| 4984 |
return ps |
| 4985 |
} |
| 4986 |
|
| 4987 |
func (n *raft) currentPeerStateLocked() *peerState { |
| 4988 |
return &peerState{n.peerNames(), n.csz, n.extSt} |
| 4989 |
} |
| 4990 |
|
| 4991 |
// committedPeerStateLocked builds peer state from the committed membership as of the given index. |
| 4992 |
// Lock should be held. |
| 4993 |
func (n *raft) committedPeerStateLocked(index uint64) *peerState { |
| 4994 |
// No pending change or index already covers the pending change. |
| 4995 |
if n.membChange == nil || n.membChange.index <= index { |
| 4996 |
return &peerState{n.peerNames(), n.csz, n.extSt} |
| 4997 |
} |
| 4998 |
|
| 4999 |
// Reconstruct the committed peer set by reverting the speculative change. |
| 5000 |
peer := n.membChange.peer |
| 5001 |
if n.membChange.prev != nil { |
| 5002 |
// This was a removal; the peer is still a committed member, add it back. |
| 5003 |
names := make([]string, 0, len(n.peers)+1) |
| 5004 |
for name := range n.peers { |
| 5005 |
names = append(names, name) |
| 5006 |
} |
| 5007 |
if _, ok := n.peers[peer]; !ok { |
| 5008 |
names = append(names, peer) |
| 5009 |
} |
| 5010 |
return &peerState{names, len(names), n.extSt} |
| 5011 |
} |
| 5012 |
|
| 5013 |
// This was an addition; exclude the not-yet-committed peer. |
| 5014 |
names := make([]string, 0, len(n.peers)) |
| 5015 |
for name := range n.peers { |
| 5016 |
if name == peer { |
| 5017 |
continue |
| 5018 |
} |
| 5019 |
names = append(names, name) |
| 5020 |
} |
| 5021 |
return &peerState{names, len(names), n.extSt} |
| 5022 |
} |
| 5023 |
|
| 5024 |
// sendPeerState will send our current peer state to the cluster. |
| 5025 |
// Lock should be held. |
| 5026 |
func (n *raft) sendPeerState() { |
| 5027 |
n.sendAppendEntryLocked([]*Entry{{EntryPeerState, encodePeerState(n.currentPeerStateLocked())}}, true) |
| 5028 |
} |
| 5029 |
|
| 5030 |
// Send a heartbeat. |
| 5031 |
func (n *raft) sendHeartbeat() { |
| 5032 |
n.sendAppendEntry(nil) |
| 5033 |
} |
| 5034 |
|
| 5035 |
type voteRequest struct { |
| 5036 |
term uint64 |
| 5037 |
lastTerm uint64 |
| 5038 |
lastIndex uint64 |
| 5039 |
candidate string |
| 5040 |
// internal only. |
| 5041 |
reply string |
| 5042 |
} |
| 5043 |
|
| 5044 |
const voteRequestLen = 24 + idLen |
| 5045 |
|
| 5046 |
func (vr *voteRequest) encode() []byte { |
| 5047 |
var buf [voteRequestLen]byte |
| 5048 |
var le = binary.LittleEndian |
| 5049 |
le.PutUint64(buf[0:], vr.term) |
| 5050 |
le.PutUint64(buf[8:], vr.lastTerm) |
| 5051 |
le.PutUint64(buf[16:], vr.lastIndex) |
| 5052 |
copy(buf[24:24+idLen], vr.candidate) |
| 5053 |
|
| 5054 |
return buf[:voteRequestLen] |
| 5055 |
} |
| 5056 |
|
| 5057 |
func decodeVoteRequest(msg []byte, reply string) *voteRequest { |
| 5058 |
if len(msg) != voteRequestLen { |
| 5059 |
return nil |
| 5060 |
} |
| 5061 |
|
| 5062 |
var le = binary.LittleEndian |
| 5063 |
return &voteRequest{ |
| 5064 |
term: le.Uint64(msg[0:]), |
| 5065 |
lastTerm: le.Uint64(msg[8:]), |
| 5066 |
lastIndex: le.Uint64(msg[16:]), |
| 5067 |
candidate: string(copyBytes(msg[24 : 24+idLen])), |
| 5068 |
reply: reply, |
| 5069 |
} |
| 5070 |
} |
| 5071 |
|
| 5072 |
const peerStateFile = "peers.idx" |
| 5073 |
|
| 5074 |
// Lock should be held. |
| 5075 |
func (n *raft) writePeerState(ps *peerState) { |
| 5076 |
pse := encodePeerState(ps) |
| 5077 |
if bytes.Equal(n.wps, pse) { |
| 5078 |
return |
| 5079 |
} |
| 5080 |
// Stamp latest and write the peer state file. |
| 5081 |
n.wps = pse |
| 5082 |
if err := writePeerState(n.dios, n.sd, ps); err != nil && !n.isClosed() { |
| 5083 |
n.setWriteErrLocked(err) |
| 5084 |
n.warn("Error writing peer state file for %q: %v", n.group, err) |
| 5085 |
} |
| 5086 |
} |
| 5087 |
|
| 5088 |
// Writes out our peer state outside of a specific raft context. |
| 5089 |
func writePeerState(dios *diskIOSemaphore, sd string, ps *peerState) error { |
| 5090 |
psf := filepath.Join(sd, peerStateFile) |
| 5091 |
if _, err := os.Stat(psf); err != nil && !os.IsNotExist(err) { |
| 5092 |
return err |
| 5093 |
} |
| 5094 |
return writeFileWithSync(dios, psf, encodePeerState(ps), defaultFilePerms) |
| 5095 |
} |
| 5096 |
|
| 5097 |
func readPeerState(dios *diskIOSemaphore, sd string) (ps *peerState, err error) { |
| 5098 |
dios.acquire() |
| 5099 |
buf, err := os.ReadFile(filepath.Join(sd, peerStateFile)) |
| 5100 |
dios.release() |
| 5101 |
|
| 5102 |
if err != nil { |
| 5103 |
return nil, err |
| 5104 |
} |
| 5105 |
return decodePeerState(buf) |
| 5106 |
} |
| 5107 |
|
| 5108 |
const termVoteFile = "tav.idx" |
| 5109 |
const termLen = 8 // uint64 |
| 5110 |
const termVoteLen = idLen + termLen |
| 5111 |
|
| 5112 |
// Writes out our term & vote outside of a specific raft context. |
| 5113 |
func writeTermVote(dios *diskIOSemaphore, sd string, wtv []byte) error { |
| 5114 |
psf := filepath.Join(sd, termVoteFile) |
| 5115 |
if _, err := os.Stat(psf); err != nil && !os.IsNotExist(err) { |
| 5116 |
return err |
| 5117 |
} |
| 5118 |
return writeFileWithSync(dios, psf, wtv, defaultFilePerms) |
| 5119 |
} |
| 5120 |
|
| 5121 |
// readTermVote will read the largest term and who we voted from to stable storage. |
| 5122 |
// Lock should be held. |
| 5123 |
func (n *raft) readTermVote() (term uint64, voted string, err error) { |
| 5124 |
n.dios.acquire() |
| 5125 |
buf, err := os.ReadFile(filepath.Join(n.sd, termVoteFile)) |
| 5126 |
n.dios.release() |
| 5127 |
|
| 5128 |
if err != nil { |
| 5129 |
return 0, noVote, err |
| 5130 |
} |
| 5131 |
if len(buf) < termLen { |
| 5132 |
// Not enough bytes for the uint64 below, so avoid a panic. |
| 5133 |
return 0, noVote, nil |
| 5134 |
} |
| 5135 |
var le = binary.LittleEndian |
| 5136 |
term = le.Uint64(buf[0:]) |
| 5137 |
if len(buf) < termVoteLen { |
| 5138 |
return term, noVote, nil |
| 5139 |
} |
| 5140 |
voted = string(buf[8:]) |
| 5141 |
return term, voted, nil |
| 5142 |
} |
| 5143 |
|
| 5144 |
// Lock should be held. |
| 5145 |
func (n *raft) setWriteErrLocked(err error) { |
| 5146 |
// Check if we are closed already. |
| 5147 |
if n.State() == Closed { |
| 5148 |
return |
| 5149 |
} |
| 5150 |
// Ignore if already set. |
| 5151 |
if n.werr == err || err == nil { |
| 5152 |
return |
| 5153 |
} |
| 5154 |
// Ignore non-write errors. |
| 5155 |
if err == ErrStoreClosed || |
| 5156 |
err == ErrStoreEOF || |
| 5157 |
err == ErrStoreMsgNotFound || |
| 5158 |
err == errNoPending || |
| 5159 |
err == errPartialCache { |
| 5160 |
return |
| 5161 |
} |
| 5162 |
// If this is a not found report but do not disable. |
| 5163 |
if os.IsNotExist(err) { |
| 5164 |
n.warn("Resource not found: %v", err) |
| 5165 |
return |
| 5166 |
} |
| 5167 |
n.error("Critical write error: %v", err) |
| 5168 |
n.werr = err |
| 5169 |
// Abort any inflight async snapshot checkpoint. |
| 5170 |
n.snapshotting = false |
| 5171 |
n.shutdown() |
| 5172 |
assert.Unreachable("Raft encountered write error", map[string]any{ |
| 5173 |
"n.accName": n.accName, |
| 5174 |
"n.group": n.group, |
| 5175 |
"n.id": n.id, |
| 5176 |
"err": err, |
| 5177 |
}) |
| 5178 |
|
| 5179 |
if isPermissionError(err) { |
| 5180 |
go n.s.handleWritePermissionError() |
| 5181 |
} |
| 5182 |
|
| 5183 |
if isOutOfSpaceErr(err) { |
| 5184 |
// For now since this can be happening all under the covers, we will call up and disable JetStream. |
| 5185 |
go n.s.handleOutOfSpace(nil) |
| 5186 |
} |
| 5187 |
} |
| 5188 |
|
| 5189 |
// Helper to check if we are closed when we do not hold a lock already. |
| 5190 |
func (n *raft) isClosed() bool { |
| 5191 |
return n.State() == Closed |
| 5192 |
} |
| 5193 |
|
| 5194 |
// GetWriteErr returns the write error (if any). |
| 5195 |
func (n *raft) GetWriteErr() error { |
| 5196 |
n.RLock() |
| 5197 |
defer n.RUnlock() |
| 5198 |
return n.werr |
| 5199 |
} |
| 5200 |
|
| 5201 |
// Capture our write error if any and hold. |
| 5202 |
func (n *raft) setWriteErr(err error) { |
| 5203 |
n.Lock() |
| 5204 |
defer n.Unlock() |
| 5205 |
n.setWriteErrLocked(err) |
| 5206 |
} |
| 5207 |
|
| 5208 |
// writeTermVote will record the largest term and who we voted for to stable |
| 5209 |
// storage. It returns the write error, if any, so that callers which need the |
| 5210 |
// term/vote to be durable before acting on it (e.g. granting or requesting a |
| 5211 |
// vote) can avoid doing so when the persist fails. |
| 5212 |
// Lock should be held. |
| 5213 |
func (n *raft) writeTermVote() error { |
| 5214 |
if n.werr != nil { |
| 5215 |
return n.werr |
| 5216 |
} |
| 5217 |
|
| 5218 |
var buf [termVoteLen]byte |
| 5219 |
var le = binary.LittleEndian |
| 5220 |
le.PutUint64(buf[0:], n.term) |
| 5221 |
copy(buf[8:], n.vote) |
| 5222 |
b := buf[:8+len(n.vote)] |
| 5223 |
|
| 5224 |
// If the term and vote hasn't changed then don't rewrite to disk. |
| 5225 |
if bytes.Equal(n.wtv, b) { |
| 5226 |
return nil |
| 5227 |
} |
| 5228 |
// Stamp latest and write the term & vote file. |
| 5229 |
n.wtv = b |
| 5230 |
if err := writeTermVote(n.dios, n.sd, n.wtv); err != nil && !n.isClosed() { |
| 5231 |
// Clear wtv since we failed. |
| 5232 |
n.wtv = nil |
| 5233 |
n.setWriteErrLocked(err) |
| 5234 |
n.warn("Error writing term and vote file for %q: %v", n.group, err) |
| 5235 |
return err |
| 5236 |
} |
| 5237 |
return nil |
| 5238 |
} |
| 5239 |
|
| 5240 |
// voteResponse is a response to a vote request. |
| 5241 |
type voteResponse struct { |
| 5242 |
term uint64 |
| 5243 |
peer string |
| 5244 |
granted bool |
| 5245 |
empty bool // "Empty vote", whether this peer's log is empty. |
| 5246 |
} |
| 5247 |
|
| 5248 |
const voteResponseLen = 8 + 8 + 1 |
| 5249 |
|
| 5250 |
func (vr *voteResponse) encode() []byte { |
| 5251 |
var buf [voteResponseLen]byte |
| 5252 |
var le = binary.LittleEndian |
| 5253 |
le.PutUint64(buf[0:], vr.term) |
| 5254 |
copy(buf[8:], vr.peer) |
| 5255 |
if vr.granted { |
| 5256 |
buf[16] |= 1 |
| 5257 |
} |
| 5258 |
if vr.empty { |
| 5259 |
buf[16] |= 2 |
| 5260 |
} |
| 5261 |
return buf[:voteResponseLen] |
| 5262 |
} |
| 5263 |
|
| 5264 |
func decodeVoteResponse(msg []byte) *voteResponse { |
| 5265 |
if len(msg) != voteResponseLen { |
| 5266 |
return nil |
| 5267 |
} |
| 5268 |
var le = binary.LittleEndian |
| 5269 |
vr := &voteResponse{term: le.Uint64(msg[0:]), peer: string(msg[8:16])} |
| 5270 |
vr.granted = msg[16]&1 != 0 |
| 5271 |
vr.empty = msg[16]&2 != 0 |
| 5272 |
return vr |
| 5273 |
} |
| 5274 |
|
| 5275 |
func (n *raft) handleVoteResponse(sub *subscription, c *client, _ *Account, _, reply string, msg []byte) { |
| 5276 |
vr := decodeVoteResponse(msg) |
| 5277 |
n.debug("Received a voteResponse %+v", vr) |
| 5278 |
if vr == nil { |
| 5279 |
n.error("Received malformed vote response for %q", n.group) |
| 5280 |
return |
| 5281 |
} |
| 5282 |
|
| 5283 |
if state := n.State(); state != Candidate && state != Leader { |
| 5284 |
n.debug("Ignoring old vote response, we have stepped down") |
| 5285 |
return |
| 5286 |
} |
| 5287 |
|
| 5288 |
n.votes.push(vr) |
| 5289 |
} |
| 5290 |
|
| 5291 |
func (n *raft) processVoteRequest(vr *voteRequest) error { |
| 5292 |
// To simplify calling code, we can possibly pass `nil` to this function. |
| 5293 |
// If that is the case, does not consider it an error. |
| 5294 |
if vr == nil { |
| 5295 |
return nil |
| 5296 |
} |
| 5297 |
n.debug("Received a voteRequest %+v", vr) |
| 5298 |
|
| 5299 |
n.Lock() |
| 5300 |
|
| 5301 |
vresp := &voteResponse{n.term, n.id, false, n.pindex == 0} |
| 5302 |
defer n.debug("Sending a voteResponse %+v -> %q", vresp, vr.reply) |
| 5303 |
|
| 5304 |
// Ignore if we are newer. This is important so that we don't accidentally process |
| 5305 |
// votes from a previous term if they were still in flight somewhere. |
| 5306 |
if vr.term < n.term { |
| 5307 |
n.Unlock() |
| 5308 |
n.sendReply(vr.reply, vresp.encode()) |
| 5309 |
return nil |
| 5310 |
} |
| 5311 |
|
| 5312 |
// If this is a higher term go ahead and stepdown. |
| 5313 |
if vr.term > n.term { |
| 5314 |
if n.State() != Follower { |
| 5315 |
n.debug("Stepping down from %s, detected higher term: %d vs %d", |
| 5316 |
strings.ToLower(n.State().String()), vr.term, n.term) |
| 5317 |
n.stepdownLocked(noLeader) |
| 5318 |
} |
| 5319 |
n.cancelCatchup() |
| 5320 |
n.term = vr.term |
| 5321 |
n.vote = noVote |
| 5322 |
n.writeTermVote() |
| 5323 |
} |
| 5324 |
|
| 5325 |
// Only way we get to yes is through here. |
| 5326 |
voteOk := n.vote == noVote || n.vote == vr.candidate |
| 5327 |
|
| 5328 |
// If we have an empty log, but are initializing. |
| 5329 |
if voteOk && vresp.empty && n.initializing { |
| 5330 |
// Reset notion of having an empty log if we're voting during initialization/scale up. |
| 5331 |
// Ensures they only need quorum, and not need to hear from all servers. |
| 5332 |
vresp.empty = false |
| 5333 |
} |
| 5334 |
|
| 5335 |
// Other server's log needs to be equal or more up-to-date than ours. |
| 5336 |
if voteOk && (vr.lastTerm > n.pterm || vr.lastTerm == n.pterm && vr.lastIndex >= n.pindex) { |
| 5337 |
// Persist our vote before granting it. Raft requires the vote to be durable before |
| 5338 |
// we respond, otherwise a restart could forget the vote and let us grant a second |
| 5339 |
// vote in the same term, which would break election safety. |
| 5340 |
n.term = vr.term |
| 5341 |
n.vote = vr.candidate |
| 5342 |
if err := n.writeTermVote(); err != nil { |
| 5343 |
n.vote = noVote |
| 5344 |
n.warn("Not granting vote for %q, could not persist term and vote: %v", n.group, err) |
| 5345 |
} else { |
| 5346 |
vresp.granted = true |
| 5347 |
n.resetElectionTimeout() |
| 5348 |
} |
| 5349 |
} else if n.vote == noVote && n.State() != Candidate { |
| 5350 |
// We have a more up-to-date log, and haven't voted yet. |
| 5351 |
// Start campaigning earlier, but only if not candidate already, as that would short-circuit us. |
| 5352 |
n.resetElect(randCampaignTimeout()) |
| 5353 |
} |
| 5354 |
|
| 5355 |
// Term might have changed, make sure response has the most current |
| 5356 |
vresp.term = n.term |
| 5357 |
|
| 5358 |
n.Unlock() |
| 5359 |
|
| 5360 |
n.sendReply(vr.reply, vresp.encode()) |
| 5361 |
|
| 5362 |
return nil |
| 5363 |
} |
| 5364 |
|
| 5365 |
func (n *raft) handleVoteRequest(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) { |
| 5366 |
vr := decodeVoteRequest(msg, reply) |
| 5367 |
if vr == nil { |
| 5368 |
n.error("Received malformed vote request for %q", n.group) |
| 5369 |
return |
| 5370 |
} |
| 5371 |
n.reqs.push(vr) |
| 5372 |
} |
| 5373 |
|
| 5374 |
func (n *raft) requestVote() { |
| 5375 |
n.Lock() |
| 5376 |
if n.State() != Candidate { |
| 5377 |
n.Unlock() |
| 5378 |
return |
| 5379 |
} |
| 5380 |
n.vote = n.id |
| 5381 |
if err := n.writeTermVote(); err != nil { |
| 5382 |
// Make sure that our self-vote is persisted durably before campaigning, otherwise |
| 5383 |
// we could vote for someone else in the same term after a restart. |
| 5384 |
n.vote = noVote |
| 5385 |
n.Unlock() |
| 5386 |
n.warn("Not requesting votes for %q, could not persist term and vote: %v", n.group, err) |
| 5387 |
return |
| 5388 |
} |
| 5389 |
vr := voteRequest{n.term, n.pterm, n.pindex, n.id, _EMPTY_} |
| 5390 |
subj, reply := n.vsubj, n.vreply |
| 5391 |
n.Unlock() |
| 5392 |
|
| 5393 |
n.debug("Sending out voteRequest %+v", vr) |
| 5394 |
|
| 5395 |
// Now send it out. |
| 5396 |
n.sendRPC(subj, reply, vr.encode()) |
| 5397 |
} |
| 5398 |
|
| 5399 |
func (n *raft) sendRPC(subject, reply string, msg []byte) { |
| 5400 |
n.t.Publish(subject, reply, msg) |
| 5401 |
} |
| 5402 |
|
| 5403 |
func (n *raft) sendReply(subject string, msg []byte) { |
| 5404 |
n.t.Publish(subject, _EMPTY_, msg) |
| 5405 |
} |
| 5406 |
|
| 5407 |
func (n *raft) wonElection(votes int) bool { |
| 5408 |
return votes >= n.quorumNeeded() |
| 5409 |
} |
| 5410 |
|
| 5411 |
// Return the quorum size for a given cluster config. |
| 5412 |
func (n *raft) quorumNeeded() int { |
| 5413 |
n.RLock() |
| 5414 |
qn := n.qn |
| 5415 |
n.RUnlock() |
| 5416 |
return qn |
| 5417 |
} |
| 5418 |
|
| 5419 |
// leadChange signals a leadership change to the upper layer. The term |
| 5420 |
// identifies the leadership epoch the signal belongs to. |
| 5421 |
type leadChange struct { |
| 5422 |
isLeader bool |
| 5423 |
term uint64 |
| 5424 |
} |
| 5425 |
|
| 5426 |
// Lock should be held. |
| 5427 |
func (n *raft) updateLeadChange(isLeader bool) { |
| 5428 |
lc := leadChange{isLeader: isLeader, term: n.term} |
| 5429 |
// We don't care about values that have not been consumed (transitory states), |
| 5430 |
// so we dequeue any state that is pending and push the new one. |
| 5431 |
for { |
| 5432 |
select { |
| 5433 |
case n.leadc <- lc: |
| 5434 |
return |
| 5435 |
default: |
| 5436 |
select { |
| 5437 |
case <-n.leadc: |
| 5438 |
default: |
| 5439 |
// May have been consumed by the "reader" go routine, so go back |
| 5440 |
// to the top of the loop and try to send again. |
| 5441 |
} |
| 5442 |
} |
| 5443 |
} |
| 5444 |
} |
| 5445 |
|
| 5446 |
// Lock should be held. |
| 5447 |
func (n *raft) switchState(state RaftState) bool { |
| 5448 |
retry: |
| 5449 |
pstate := n.State() |
| 5450 |
if pstate == Closed { |
| 5451 |
return false |
| 5452 |
} |
| 5453 |
|
| 5454 |
// Set our state. If something else has changed our state |
| 5455 |
// then retry, this will either be a Stop or Delete call. |
| 5456 |
if !n.state.CompareAndSwap(int32(pstate), int32(state)) { |
| 5457 |
goto retry |
| 5458 |
} |
| 5459 |
|
| 5460 |
// Reset the election timer. |
| 5461 |
n.resetElectionTimeout() |
| 5462 |
|
| 5463 |
var leadChanged bool |
| 5464 |
if pstate == Leader && state != Leader { |
| 5465 |
leadChanged = true |
| 5466 |
n.updateLeadChange(false) |
| 5467 |
// Drain the append entry response and proposal queues. |
| 5468 |
n.resp.drain() |
| 5469 |
n.prop.drain() |
| 5470 |
} else if state == Leader && pstate != Leader { |
| 5471 |
// Don't updateLeadChange here, it will be done in switchToLeader or after initial messages are applied. |
| 5472 |
leadChanged = true |
| 5473 |
n.resetPendingEntries() |
| 5474 |
} |
| 5475 |
|
| 5476 |
n.writeTermVote() |
| 5477 |
return leadChanged |
| 5478 |
} |
| 5479 |
|
| 5480 |
const ( |
| 5481 |
noLeader = _EMPTY_ |
| 5482 |
noVote = _EMPTY_ |
| 5483 |
) |
| 5484 |
|
| 5485 |
func (n *raft) switchToFollower(leader string) { |
| 5486 |
n.Lock() |
| 5487 |
defer n.Unlock() |
| 5488 |
|
| 5489 |
n.switchToFollowerLocked(leader) |
| 5490 |
} |
| 5491 |
|
| 5492 |
func (n *raft) switchToFollowerLocked(leader string) { |
| 5493 |
if n.State() == Closed { |
| 5494 |
return |
| 5495 |
} |
| 5496 |
|
| 5497 |
n.debug("Switching to follower") |
| 5498 |
|
| 5499 |
n.aflr = 0 |
| 5500 |
n.leaderState.Store(false) |
| 5501 |
n.leaderSince.Store(nil) |
| 5502 |
n.lxfer = false |
| 5503 |
|
| 5504 |
// Reset acks, we can't assume acks from a previous term are still valid in another term. |
| 5505 |
if len(n.acks) > 0 { |
| 5506 |
n.acks = make(map[uint64]map[string]struct{}) |
| 5507 |
} |
| 5508 |
n.updateLeader(leader) |
| 5509 |
n.switchState(Follower) |
| 5510 |
} |
| 5511 |
|
| 5512 |
func (n *raft) switchToCandidate() { |
| 5513 |
if n.State() == Closed { |
| 5514 |
return |
| 5515 |
} |
| 5516 |
|
| 5517 |
n.Lock() |
| 5518 |
defer n.Unlock() |
| 5519 |
|
| 5520 |
// If we are catching up or are in observer mode we can not switch. |
| 5521 |
// Avoid petitioning to become leader if we're behind on applies. |
| 5522 |
if n.observer || n.paused || n.processed < n.commit { |
| 5523 |
n.resetElect(minElectionTimeout / 4) |
| 5524 |
return |
| 5525 |
} |
| 5526 |
|
| 5527 |
// Do not campaign with an uncommitted membership change about us, |
| 5528 |
// otherwise we would try to become leader outside our peer set. |
| 5529 |
if n.membChange != nil && n.membChange.peer == n.id { |
| 5530 |
n.resetElect(minElectionTimeout) |
| 5531 |
return |
| 5532 |
} |
| 5533 |
|
| 5534 |
if n.State() != Candidate { |
| 5535 |
n.debug("Switching to candidate") |
| 5536 |
} else { |
| 5537 |
if n.lostQuorumLocked() && time.Since(n.llqrt) > 20*time.Second { |
| 5538 |
// We signal to the upper layers such that can alert on quorum lost. |
| 5539 |
n.updateLeadChange(false) |
| 5540 |
n.llqrt = time.Now() |
| 5541 |
} |
| 5542 |
} |
| 5543 |
// Increment the term. |
| 5544 |
n.term++ |
| 5545 |
n.vote = noVote |
| 5546 |
// Reset quorum paused. If it was previously set, we checked above that we've applied all committed entries. |
| 5547 |
n.quorumPaused = false |
| 5548 |
// Clear current Leader. |
| 5549 |
n.updateLeader(noLeader) |
| 5550 |
n.switchState(Candidate) |
| 5551 |
} |
| 5552 |
|
| 5553 |
func (n *raft) switchToLeader() { |
| 5554 |
if n.State() == Closed { |
| 5555 |
return |
| 5556 |
} |
| 5557 |
|
| 5558 |
n.Lock() |
| 5559 |
defer n.Unlock() |
| 5560 |
|
| 5561 |
n.debug("Switching to leader") |
| 5562 |
|
| 5563 |
n.lxfer = false |
| 5564 |
n.updateLeader(n.id) |
| 5565 |
n.switchState(Leader) |
| 5566 |
|
| 5567 |
// To send out our initial peer state. |
| 5568 |
// In our implementation this is equivalent to sending a NOOP-entry upon becoming leader. |
| 5569 |
// Wait for this message (and potentially more) to be applied. |
| 5570 |
// It's important to wait signaling we're leader if we're not up-to-date yet, as that |
| 5571 |
// would mean we're in a consistent state compared with the previous leader. |
| 5572 |
n.sendPeerState() |
| 5573 |
n.aflr = n.pindex |
| 5574 |
} |