| 1 |
// Copyright 2024-2025 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 |
// Raft Chain of Blocks (RCOB) is a replicated state machine on top of Raft used to test the latter. |
| 15 |
// Each value ("block") proposed to raft is a simple array of bytes (stateless, can be small or large). |
| 16 |
// Each replica state consists of a hash of all blocks delivered so far. |
| 17 |
// This makes it easy to check consistency over time. |
| 18 |
// If all replicas deliver the same blocks in the same order (the whole point of Raft!), then the N-th hash on each |
| 19 |
// replica should be identical. This invariant is easy to verify in test settings, because if at any point a replica |
| 20 |
// delivered (hashed) a different value, then all subsequent hashes will diverge from the rest. |
| 21 |
|
| 22 |
package server |
| 23 |
|
| 24 |
import ( |
| 25 |
"encoding" |
| 26 |
"encoding/json" |
| 27 |
"fmt" |
| 28 |
"hash" |
| 29 |
"hash/crc32" |
| 30 |
"math/rand" |
| 31 |
"sync" |
| 32 |
) |
| 33 |
|
| 34 |
// Static options (but may be useful to tweak when debugging) |
| 35 |
var RCOBOptions = struct { |
| 36 |
verbose bool |
| 37 |
// Proposed block [data] size is random between 1 and maxBlockSize |
| 38 |
maxBlockSize int |
| 39 |
// If set to true, the state machine will not take snapshots while in recovery |
| 40 |
// (corresponding to the 'ready' state machine member variable) |
| 41 |
safeSnapshots bool |
| 42 |
}{ |
| 43 |
false, |
| 44 |
10240, |
| 45 |
true, |
| 46 |
} |
| 47 |
|
| 48 |
// Simple state machine on top of Raft. |
| 49 |
// Each value delivered is hashed, N-th value hash should match on all replicas or something went wrong. |
| 50 |
// If even a single value in the chain of hash differs on one replica, hashes will diverge. |
| 51 |
type RCOBStateMachine struct { |
| 52 |
sync.Mutex |
| 53 |
s *Server |
| 54 |
n RaftNode |
| 55 |
cfg *RaftConfig |
| 56 |
wg sync.WaitGroup |
| 57 |
leader bool |
| 58 |
proposalSequence uint64 |
| 59 |
rng *rand.Rand |
| 60 |
hash hash.Hash |
| 61 |
blocksApplied uint64 |
| 62 |
blocksAppliedSinceSnapshot uint64 |
| 63 |
stopped bool |
| 64 |
ready bool |
| 65 |
} |
| 66 |
|
| 67 |
func (sm *RCOBStateMachine) waitGroup() *sync.WaitGroup { |
| 68 |
sm.Lock() |
| 69 |
defer sm.Unlock() |
| 70 |
return &sm.wg |
| 71 |
} |
| 72 |
|
| 73 |
// RCOBBlock is the structure of values replicated through Raft. |
| 74 |
// Block data is a random array of bytes. |
| 75 |
// Additional proposer metadata is present for debugging and for further ordering invariant checks (but not included |
| 76 |
// in the hash). |
| 77 |
type RCOBBlock struct { |
| 78 |
Proposer string |
| 79 |
ProposerSequence uint64 |
| 80 |
Data []byte |
| 81 |
} |
| 82 |
|
| 83 |
// logDebug is for fine-grained event logging, useful for debugging but default off |
| 84 |
func (sm *RCOBStateMachine) logDebug(format string, args ...any) { |
| 85 |
if RCOBOptions.verbose { |
| 86 |
fmt.Printf("["+sm.s.Name()+" ("+sm.n.ID()+")] "+format+"\n", args...) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
func (sm *RCOBStateMachine) server() *Server { |
| 91 |
sm.Lock() |
| 92 |
defer sm.Unlock() |
| 93 |
return sm.s |
| 94 |
} |
| 95 |
|
| 96 |
func (sm *RCOBStateMachine) node() RaftNode { |
| 97 |
sm.Lock() |
| 98 |
defer sm.Unlock() |
| 99 |
return sm.n |
| 100 |
} |
| 101 |
|
| 102 |
func (sm *RCOBStateMachine) propose(data []byte) { |
| 103 |
sm.Lock() |
| 104 |
defer sm.Unlock() |
| 105 |
if !sm.ready { |
| 106 |
sm.logDebug("Refusing to propose during recovery") |
| 107 |
} |
| 108 |
err := sm.n.ForwardProposal(data) |
| 109 |
if err != nil { |
| 110 |
sm.logDebug("block proposal error: %s", err) |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
func (sm *RCOBStateMachine) applyEntry(ce *CommittedEntry) { |
| 115 |
sm.Lock() |
| 116 |
defer sm.Unlock() |
| 117 |
if ce == nil { |
| 118 |
// A nil entry signals that the previous recovery backlog is over |
| 119 |
sm.logDebug("Recovery complete") |
| 120 |
sm.ready = true |
| 121 |
return |
| 122 |
} |
| 123 |
sm.logDebug("Apply entries #%d (%d entries)", ce.Index, len(ce.Entries)) |
| 124 |
for _, entry := range ce.Entries { |
| 125 |
if entry.Type == EntryNormal { |
| 126 |
sm.applyBlock(entry.Data) |
| 127 |
} else if entry.Type == EntrySnapshot { |
| 128 |
sm.loadSnapshot(entry.Data) |
| 129 |
} else if entry.Type == EntryCatchup { |
| 130 |
// Ignore. |
| 131 |
} else { |
| 132 |
panic(fmt.Sprintf("[%s] unknown entry type: %s", sm.s.Name(), entry.Type)) |
| 133 |
} |
| 134 |
} |
| 135 |
// Signal to the node that entries were applied |
| 136 |
sm.n.Applied(ce.Index) |
| 137 |
} |
| 138 |
|
| 139 |
func (sm *RCOBStateMachine) leaderChange(isLeader bool) { |
| 140 |
sm.Lock() |
| 141 |
defer sm.Unlock() |
| 142 |
if sm.leader && !isLeader { |
| 143 |
sm.logDebug("Leader change: no longer leader") |
| 144 |
} else if sm.leader && isLeader { |
| 145 |
sm.logDebug("Elected leader while already leader") |
| 146 |
} else if !sm.leader && isLeader { |
| 147 |
sm.logDebug("Leader change: i am leader") |
| 148 |
} else { |
| 149 |
sm.logDebug("Leader change") |
| 150 |
} |
| 151 |
sm.leader = isLeader |
| 152 |
if isLeader != sm.n.Leader() { |
| 153 |
sm.logDebug("⚠️ Leader state out of sync with underlying node") |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
func (sm *RCOBStateMachine) stop() { |
| 158 |
n, wg := sm.node(), sm.waitGroup() |
| 159 |
n.Stop() |
| 160 |
n.WaitForStop() |
| 161 |
wg.Wait() |
| 162 |
|
| 163 |
// Clear state, on restart it will be recovered from snapshot or peers |
| 164 |
sm.Lock() |
| 165 |
defer sm.Unlock() |
| 166 |
|
| 167 |
sm.stopped = true |
| 168 |
sm.blocksApplied = 0 |
| 169 |
sm.hash.Reset() |
| 170 |
sm.leader = false |
| 171 |
sm.logDebug("Stopped") |
| 172 |
} |
| 173 |
|
| 174 |
func (sm *RCOBStateMachine) restart() { |
| 175 |
sm.Lock() |
| 176 |
defer sm.Unlock() |
| 177 |
|
| 178 |
sm.logDebug("Restarting") |
| 179 |
|
| 180 |
sm.stopped = false |
| 181 |
sm.ready = false |
| 182 |
if sm.n.State() != Closed { |
| 183 |
return |
| 184 |
} |
| 185 |
|
| 186 |
// The filestore is stopped as well, so need to extract the parts to recreate it. |
| 187 |
rn := sm.n.(*raft) |
| 188 |
fs := rn.wal.(*fileStore) |
| 189 |
|
| 190 |
var err error |
| 191 |
sm.cfg.Log, err = newFileStore(fs.fcfg, fs.cfg.StreamConfig) |
| 192 |
if err != nil { |
| 193 |
panic(err) |
| 194 |
} |
| 195 |
sm.n, err = sm.s.startRaftNode(globalAccountName, sm.cfg, pprofLabels{}) |
| 196 |
if err != nil { |
| 197 |
panic(err) |
| 198 |
} |
| 199 |
// Finally restart the driver. |
| 200 |
go smLoop(sm) |
| 201 |
} |
| 202 |
|
| 203 |
func (sm *RCOBStateMachine) proposeBlock() { |
| 204 |
// Keep track how many blocks this replica proposed |
| 205 |
sm.proposalSequence += 1 |
| 206 |
|
| 207 |
// Create a block |
| 208 |
blockSize := 1 + sm.rng.Intn(RCOBOptions.maxBlockSize) |
| 209 |
block := RCOBBlock{ |
| 210 |
Proposer: sm.s.Name(), |
| 211 |
ProposerSequence: sm.proposalSequence, |
| 212 |
Data: make([]byte, blockSize), |
| 213 |
} |
| 214 |
|
| 215 |
// Data is random bytes |
| 216 |
sm.rng.Read(block.Data) |
| 217 |
|
| 218 |
// Serialize block to JSON |
| 219 |
blockData, err := json.Marshal(block) |
| 220 |
if err != nil { |
| 221 |
panic(fmt.Sprintf("serialization error: %s", err)) |
| 222 |
} |
| 223 |
|
| 224 |
sm.logDebug( |
| 225 |
"Proposing block <%s, %d, [%dB]>", |
| 226 |
block.Proposer, |
| 227 |
block.ProposerSequence, |
| 228 |
len(block.Data), |
| 229 |
) |
| 230 |
|
| 231 |
// Propose block (may fail, and that's ok) |
| 232 |
sm.propose(blockData) |
| 233 |
} |
| 234 |
|
| 235 |
func (sm *RCOBStateMachine) applyBlock(data []byte) { |
| 236 |
// Deserialize block |
| 237 |
var block RCOBBlock |
| 238 |
err := json.Unmarshal(data, &block) |
| 239 |
if err != nil { |
| 240 |
panic(fmt.Sprintf("deserialization error: %s", err)) |
| 241 |
} |
| 242 |
|
| 243 |
sm.logDebug("Applying block <%s, %d>", block.Proposer, block.ProposerSequence) |
| 244 |
|
| 245 |
// Hash the data on top of the existing running hash |
| 246 |
n, err := sm.hash.Write(block.Data) |
| 247 |
if n != len(block.Data) { |
| 248 |
panic(fmt.Sprintf("unexpected checksum written %d data block size: %d", n, len(block.Data))) |
| 249 |
} else if err != nil { |
| 250 |
panic(fmt.Sprintf("checksum error: %s", err)) |
| 251 |
} |
| 252 |
|
| 253 |
// Track numbers of blocks applied |
| 254 |
sm.blocksApplied += 1 |
| 255 |
sm.blocksAppliedSinceSnapshot += 1 |
| 256 |
|
| 257 |
sm.logDebug("Hash after %d blocks: %X ", sm.blocksApplied, sm.hash.Sum(nil)) |
| 258 |
} |
| 259 |
|
| 260 |
func (sm *RCOBStateMachine) getCurrentHash() (bool, uint64, string) { |
| 261 |
sm.Lock() |
| 262 |
defer sm.Unlock() |
| 263 |
|
| 264 |
// Return running, the number of blocks applied and the current running hash |
| 265 |
return !sm.stopped, sm.blocksApplied, fmt.Sprintf("%X", sm.hash.Sum(nil)) |
| 266 |
} |
| 267 |
|
| 268 |
// RCOBSnapshot structure for RCOB snapshots |
| 269 |
// Consists of the hash (32b) after BlocksCount blocks were hashed. |
| 270 |
// TODO: Could start storing last N blocks to make snapshot larger and exercise more code paths. |
| 271 |
// (a big chunk of random data would also do the trick) |
| 272 |
type RCOBSnapshot struct { |
| 273 |
SourceNode string |
| 274 |
HashData []byte |
| 275 |
BlocksCount uint64 |
| 276 |
} |
| 277 |
|
| 278 |
// createSnapshot asks the state machine to create a snapshot. |
| 279 |
// The request may be ignored if no blocks were applied since the last snapshot. |
| 280 |
func (sm *RCOBStateMachine) createSnapshot() { |
| 281 |
sm.Lock() |
| 282 |
defer sm.Unlock() |
| 283 |
|
| 284 |
if sm.blocksAppliedSinceSnapshot == 0 { |
| 285 |
sm.logDebug("Skip snapshot, no new entries") |
| 286 |
return |
| 287 |
} |
| 288 |
|
| 289 |
if RCOBOptions.safeSnapshots && !sm.ready { |
| 290 |
sm.logDebug("Skip snapshot, still recovering") |
| 291 |
return |
| 292 |
} |
| 293 |
|
| 294 |
sm.logDebug( |
| 295 |
"Snapshot (with %d blocks applied, %d since last snapshot)", |
| 296 |
sm.blocksApplied, |
| 297 |
sm.blocksAppliedSinceSnapshot, |
| 298 |
) |
| 299 |
|
| 300 |
// Serialize the internal state of the hash block |
| 301 |
serializedHash, err := sm.hash.(encoding.BinaryMarshaler).MarshalBinary() |
| 302 |
if err != nil { |
| 303 |
panic(fmt.Sprintf("failed to marshal hash: %s", err)) |
| 304 |
} |
| 305 |
|
| 306 |
// Create snapshot |
| 307 |
snapshot := RCOBSnapshot{ |
| 308 |
SourceNode: fmt.Sprintf("%s (%s)", sm.s.Name(), sm.n.ID()), |
| 309 |
HashData: serializedHash, |
| 310 |
BlocksCount: sm.blocksApplied, |
| 311 |
} |
| 312 |
|
| 313 |
// Serialize snapshot as JSON |
| 314 |
snapshotData, err := json.Marshal(snapshot) |
| 315 |
if err != nil { |
| 316 |
panic(fmt.Sprintf("failed to marshal snapshot: %s", err)) |
| 317 |
} |
| 318 |
|
| 319 |
// InstallSnapshot is actually "save the snapshot", which is an operation delegated to the node |
| 320 |
err = sm.n.InstallSnapshot(snapshotData, false) |
| 321 |
if err != nil { |
| 322 |
sm.logDebug("failed to snapshot: %s", err) |
| 323 |
return |
| 324 |
} |
| 325 |
|
| 326 |
// Reset counter since last snapshot |
| 327 |
sm.blocksAppliedSinceSnapshot = 0 |
| 328 |
} |
| 329 |
|
| 330 |
func (sm *RCOBStateMachine) loadSnapshot(data []byte) { |
| 331 |
// Deserialize snapshot from JSON |
| 332 |
var snapshot RCOBSnapshot |
| 333 |
err := json.Unmarshal(data, &snapshot) |
| 334 |
if err != nil { |
| 335 |
panic(fmt.Sprintf("failed to unmarshal snapshot: %s", err)) |
| 336 |
} |
| 337 |
|
| 338 |
sm.logDebug( |
| 339 |
"Applying snapshot (created by %s) taken after %d blocks", |
| 340 |
snapshot.SourceNode, |
| 341 |
snapshot.BlocksCount, |
| 342 |
) |
| 343 |
|
| 344 |
// Load internal hash state |
| 345 |
err = sm.hash.(encoding.BinaryUnmarshaler).UnmarshalBinary(snapshot.HashData) |
| 346 |
if err != nil { |
| 347 |
panic(fmt.Sprintf("failed to unmarshal hash data: %s", err)) |
| 348 |
} |
| 349 |
|
| 350 |
// Load block counter |
| 351 |
sm.blocksApplied = snapshot.BlocksCount |
| 352 |
|
| 353 |
// Reset number of blocks applied since snapshot |
| 354 |
sm.blocksAppliedSinceSnapshot = 0 |
| 355 |
|
| 356 |
sm.logDebug("Hash after snapshot with %d blocks: %X ", sm.blocksApplied, sm.hash.Sum(nil)) |
| 357 |
} |
| 358 |
|
| 359 |
// Factory function to create state machine on top of the given server/node |
| 360 |
func newRaftChainStateMachine(s *Server, cfg *RaftConfig, n RaftNode) stateMachine { |
| 361 |
// Create RNG seed based on server name and node id |
| 362 |
var seed int64 |
| 363 |
for _, c := range []byte(s.Name()) { |
| 364 |
seed += int64(c) |
| 365 |
} |
| 366 |
for _, c := range []byte(n.ID()) { |
| 367 |
seed += int64(c) |
| 368 |
} |
| 369 |
rng := rand.New(rand.NewSource(seed)) |
| 370 |
|
| 371 |
// Initialize empty hash block |
| 372 |
hashBlock := crc32.NewIEEE() |
| 373 |
|
| 374 |
return &RCOBStateMachine{s: s, n: n, cfg: cfg, rng: rng, hash: hashBlock} |
| 375 |
} |