| 1 |
// Copyright 2023-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 |
// Do not exlude this file with the !skip_js_tests since those helpers |
| 15 |
// are also used by MQTT. |
| 16 |
|
| 17 |
package server |
| 18 |
|
| 19 |
import ( |
| 20 |
"encoding/binary" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"math/rand" |
| 24 |
"sync" |
| 25 |
"testing" |
| 26 |
"time" |
| 27 |
) |
| 28 |
|
| 29 |
type stateMachine interface { |
| 30 |
server() *Server |
| 31 |
node() RaftNode |
| 32 |
waitGroup() *sync.WaitGroup |
| 33 |
// This will call forward as needed so can be called on any node. |
| 34 |
propose(data []byte) |
| 35 |
// When entries have been committed and can be applied. |
| 36 |
applyEntry(ce *CommittedEntry) |
| 37 |
// When a leader change happens. |
| 38 |
leaderChange(isLeader bool) |
| 39 |
// Stop the raft group. |
| 40 |
stop() |
| 41 |
// Restart |
| 42 |
restart() |
| 43 |
} |
| 44 |
|
| 45 |
// Factory function needed for constructor. |
| 46 |
type smFactory func(s *Server, cfg *RaftConfig, node RaftNode) stateMachine |
| 47 |
|
| 48 |
type smGroup []stateMachine |
| 49 |
|
| 50 |
// Leader of the group. |
| 51 |
func (sg smGroup) leader() stateMachine { |
| 52 |
for _, sm := range sg { |
| 53 |
if sm.node().Leader() { |
| 54 |
return sm |
| 55 |
} |
| 56 |
} |
| 57 |
return nil |
| 58 |
} |
| 59 |
|
| 60 |
func (sg smGroup) followers() smGroup { |
| 61 |
var f []stateMachine |
| 62 |
for _, sm := range sg { |
| 63 |
if sm.node().Leader() { |
| 64 |
continue |
| 65 |
} |
| 66 |
f = append(f, sm) |
| 67 |
} |
| 68 |
return f |
| 69 |
} |
| 70 |
|
| 71 |
// Wait on a leader to be elected. |
| 72 |
func (sg smGroup) waitOnLeader() stateMachine { |
| 73 |
expires := time.Now().Add(10 * time.Second) |
| 74 |
for time.Now().Before(expires) { |
| 75 |
for _, sm := range sg { |
| 76 |
if sm.node().Leader() { |
| 77 |
return sm |
| 78 |
} |
| 79 |
} |
| 80 |
time.Sleep(100 * time.Millisecond) |
| 81 |
} |
| 82 |
return nil |
| 83 |
} |
| 84 |
|
| 85 |
// Pick a random member. |
| 86 |
func (sg smGroup) randomMember() stateMachine { |
| 87 |
return sg[rand.Intn(len(sg))] |
| 88 |
} |
| 89 |
|
| 90 |
// Return a non-leader |
| 91 |
func (sg smGroup) nonLeader() stateMachine { |
| 92 |
for _, sm := range sg { |
| 93 |
if !sm.node().Leader() { |
| 94 |
return sm |
| 95 |
} |
| 96 |
} |
| 97 |
return nil |
| 98 |
} |
| 99 |
|
| 100 |
// Take out the lock on all nodes. |
| 101 |
func (sg smGroup) lockAll() { |
| 102 |
for _, sm := range sg { |
| 103 |
sm.node().(*raft).Lock() |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
// Release the lock on all nodes. |
| 108 |
func (sg smGroup) unlockAll() { |
| 109 |
for _, sm := range sg { |
| 110 |
sm.node().(*raft).Unlock() |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
// Acquire the lock on all follower nodes. |
| 115 |
func (sg smGroup) lockFollowers() []stateMachine { |
| 116 |
var locked []stateMachine |
| 117 |
for _, sm := range sg { |
| 118 |
if !sm.node().Leader() { |
| 119 |
locked = append(locked, sm) |
| 120 |
sm.node().(*raft).Lock() |
| 121 |
} |
| 122 |
} |
| 123 |
return locked[:] |
| 124 |
} |
| 125 |
|
| 126 |
// Create a raft group and place on numMembers servers at random. |
| 127 |
// Filestore based. |
| 128 |
func (c *cluster) createRaftGroup(name string, numMembers int, smf smFactory) smGroup { |
| 129 |
return c.createRaftGroupEx(name, numMembers, smf, defaultRaftTransport, FileStorage) |
| 130 |
} |
| 131 |
|
| 132 |
func (c *cluster) createMemRaftGroup(name string, numMembers int, smf smFactory) smGroup { |
| 133 |
return c.createRaftGroupEx(name, numMembers, smf, defaultRaftTransport, MemoryStorage) |
| 134 |
} |
| 135 |
|
| 136 |
func (c *cluster) createMockMemRaftGroup(name string, members int, smf smFactory) (*raftTransportHub, smGroup) { |
| 137 |
hub := newRaftTransportHub() |
| 138 |
return hub, c.createRaftGroupEx(name, members, smf, hub.newTransport, MemoryStorage) |
| 139 |
} |
| 140 |
|
| 141 |
func (c *cluster) createRaftGroupEx(name string, numMembers int, smf smFactory, rtf newTransportFunc, st StorageType) smGroup { |
| 142 |
c.t.Helper() |
| 143 |
if numMembers > len(c.servers) { |
| 144 |
c.t.Fatalf("Members > Peers: %d vs %d", numMembers, len(c.servers)) |
| 145 |
} |
| 146 |
servers := append([]*Server{}, c.servers...) |
| 147 |
rand.Shuffle(len(servers), func(i, j int) { servers[i], servers[j] = servers[j], servers[i] }) |
| 148 |
return c.createRaftGroupWithPeers(name, servers[:numMembers], smf, rtf, st) |
| 149 |
} |
| 150 |
|
| 151 |
func (c *cluster) createWAL(name string, st StorageType) WAL { |
| 152 |
c.t.Helper() |
| 153 |
var err error |
| 154 |
var store WAL |
| 155 |
if st == FileStorage { |
| 156 |
store, err = newFileStore( |
| 157 |
FileStoreConfig{ |
| 158 |
StoreDir: c.t.TempDir(), |
| 159 |
BlockSize: defaultMediumBlockSize, |
| 160 |
AsyncFlush: false, |
| 161 |
SyncInterval: 5 * time.Minute}, |
| 162 |
StreamConfig{ |
| 163 |
Name: name, |
| 164 |
Storage: FileStorage}) |
| 165 |
} else { |
| 166 |
store, err = newMemStore( |
| 167 |
&StreamConfig{ |
| 168 |
Name: name, |
| 169 |
Storage: MemoryStorage}) |
| 170 |
} |
| 171 |
require_NoError(c.t, err) |
| 172 |
return store |
| 173 |
} |
| 174 |
|
| 175 |
func serverPeerNames(servers []*Server) []string { |
| 176 |
var peers []string |
| 177 |
|
| 178 |
for _, s := range servers { |
| 179 |
// generate peer names. |
| 180 |
s.mu.RLock() |
| 181 |
peers = append(peers, s.sys.shash) |
| 182 |
s.mu.RUnlock() |
| 183 |
} |
| 184 |
|
| 185 |
return peers |
| 186 |
} |
| 187 |
|
| 188 |
func (c *cluster) createStateMachine(s *Server, cfg *RaftConfig, peers []string, smf smFactory) stateMachine { |
| 189 |
s.bootstrapRaftNode(cfg, peers, true) |
| 190 |
n, err := s.startRaftNode(globalAccountName, cfg, pprofLabels{}) |
| 191 |
require_NoError(c.t, err) |
| 192 |
sm := smf(s, cfg, n) |
| 193 |
go smLoop(sm) |
| 194 |
return sm |
| 195 |
} |
| 196 |
|
| 197 |
func (c *cluster) createRaftGroupWithPeers(name string, servers []*Server, smf smFactory, rtf newTransportFunc, st StorageType) smGroup { |
| 198 |
c.t.Helper() |
| 199 |
|
| 200 |
var sg smGroup |
| 201 |
peers := serverPeerNames(servers) |
| 202 |
|
| 203 |
for _, s := range servers { |
| 204 |
cfg := &RaftConfig{ |
| 205 |
Name: name, |
| 206 |
Store: c.t.TempDir(), |
| 207 |
Log: c.createWAL(name, st), |
| 208 |
NewTransport: rtf} |
| 209 |
sg = append(sg, c.createStateMachine(s, cfg, peers, smf)) |
| 210 |
} |
| 211 |
|
| 212 |
// Start campaigning early to speed up bootstrap leader election. |
| 213 |
sg[0].node().CampaignImmediately() |
| 214 |
return sg |
| 215 |
} |
| 216 |
|
| 217 |
func (c *cluster) addNodeEx(name string, smf smFactory, rtf newTransportFunc, st StorageType) stateMachine { |
| 218 |
c.t.Helper() |
| 219 |
|
| 220 |
server := c.addInNewServer() |
| 221 |
|
| 222 |
cfg := &RaftConfig{ |
| 223 |
Name: name, |
| 224 |
Store: c.t.TempDir(), |
| 225 |
Log: c.createWAL(name, st), |
| 226 |
NewTransport: rtf} |
| 227 |
|
| 228 |
peers := serverPeerNames(c.servers) |
| 229 |
return c.createStateMachine(server, cfg, peers, smf) |
| 230 |
} |
| 231 |
|
| 232 |
func (c *cluster) addRaftNode(name string, smf smFactory) stateMachine { |
| 233 |
return c.addNodeEx(name, smf, defaultRaftTransport, FileStorage) |
| 234 |
} |
| 235 |
|
| 236 |
func (c *cluster) addMemRaftNode(name string, smf smFactory) stateMachine { |
| 237 |
return c.addNodeEx(name, smf, defaultRaftTransport, MemoryStorage) |
| 238 |
} |
| 239 |
|
| 240 |
func (c *cluster) addMockMemRaftNode(name string, hub *raftTransportHub, smf smFactory) stateMachine { |
| 241 |
return c.addNodeEx(name, smf, hub.newTransport, MemoryStorage) |
| 242 |
} |
| 243 |
|
| 244 |
// Driver program for the state machine. |
| 245 |
// Should be run in its own go routine. |
| 246 |
func smLoop(sm stateMachine) { |
| 247 |
s, n, wg := sm.server(), sm.node(), sm.waitGroup() |
| 248 |
qch, lch, aq := n.QuitC(), n.LeadChangeC(), n.ApplyQ() |
| 249 |
|
| 250 |
// Wait group used to allow waiting until we exit from here. |
| 251 |
wg.Add(1) |
| 252 |
defer wg.Done() |
| 253 |
|
| 254 |
for { |
| 255 |
select { |
| 256 |
case <-s.quitCh: |
| 257 |
return |
| 258 |
case <-qch: |
| 259 |
return |
| 260 |
case <-aq.ch: |
| 261 |
ces := aq.pop() |
| 262 |
for _, ce := range ces { |
| 263 |
sm.applyEntry(ce) |
| 264 |
} |
| 265 |
aq.recycle(&ces) |
| 266 |
|
| 267 |
case lc := <-lch: |
| 268 |
sm.leaderChange(lc.isLeader) |
| 269 |
} |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
// Simple implementation of a replicated state. |
| 274 |
// The adder state just sums up int64 values. |
| 275 |
type stateAdder struct { |
| 276 |
sync.Mutex |
| 277 |
s *Server |
| 278 |
n RaftNode |
| 279 |
wg sync.WaitGroup |
| 280 |
cfg *RaftConfig |
| 281 |
sum int64 |
| 282 |
lch chan bool |
| 283 |
} |
| 284 |
|
| 285 |
// Simple getters for server and the raft node. |
| 286 |
func (a *stateAdder) server() *Server { |
| 287 |
a.Lock() |
| 288 |
defer a.Unlock() |
| 289 |
return a.s |
| 290 |
} |
| 291 |
|
| 292 |
func (a *stateAdder) node() RaftNode { |
| 293 |
a.Lock() |
| 294 |
defer a.Unlock() |
| 295 |
return a.n |
| 296 |
} |
| 297 |
|
| 298 |
func (a *stateAdder) waitGroup() *sync.WaitGroup { |
| 299 |
a.Lock() |
| 300 |
defer a.Unlock() |
| 301 |
return &a.wg |
| 302 |
} |
| 303 |
|
| 304 |
func (a *stateAdder) propose(data []byte) { |
| 305 |
// Don't hold state machine lock as we could deadlock if the node was locked as part of the test. |
| 306 |
n := a.node() |
| 307 |
n.ForwardProposal(data) |
| 308 |
} |
| 309 |
|
| 310 |
func (a *stateAdder) applyEntry(ce *CommittedEntry) { |
| 311 |
a.Lock() |
| 312 |
if ce == nil { |
| 313 |
// This means initial state is done/replayed. |
| 314 |
a.Unlock() |
| 315 |
return |
| 316 |
} |
| 317 |
for _, e := range ce.Entries { |
| 318 |
if e.Type == EntryNormal { |
| 319 |
delta, _ := binary.Varint(e.Data) |
| 320 |
a.sum += delta |
| 321 |
} else if e.Type == EntrySnapshot { |
| 322 |
a.sum, _ = binary.Varint(e.Data) |
| 323 |
} |
| 324 |
} |
| 325 |
// Update applied. |
| 326 |
// But don't hold state machine lock as we could deadlock if the node was locked as part of the test. |
| 327 |
n := a.n |
| 328 |
a.Unlock() |
| 329 |
n.Applied(ce.Index) |
| 330 |
} |
| 331 |
|
| 332 |
func (a *stateAdder) leaderChange(isLeader bool) { |
| 333 |
select { |
| 334 |
case a.lch <- isLeader: |
| 335 |
default: |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
// Adder specific to change the total. |
| 340 |
func (a *stateAdder) proposeDelta(delta int64) { |
| 341 |
data := make([]byte, binary.MaxVarintLen64) |
| 342 |
n := binary.PutVarint(data, int64(delta)) |
| 343 |
a.propose(data[:n]) |
| 344 |
} |
| 345 |
|
| 346 |
// Stop the group. |
| 347 |
func (a *stateAdder) stop() { |
| 348 |
n, wg := a.node(), a.waitGroup() |
| 349 |
n.Stop() |
| 350 |
n.WaitForStop() |
| 351 |
wg.Wait() |
| 352 |
} |
| 353 |
|
| 354 |
// Restart the group |
| 355 |
func (a *stateAdder) restart() { |
| 356 |
a.Lock() |
| 357 |
defer a.Unlock() |
| 358 |
|
| 359 |
if a.n.State() != Closed { |
| 360 |
return |
| 361 |
} |
| 362 |
|
| 363 |
// The filestore is stopped as well, so need to extract the parts to recreate it. |
| 364 |
rn := a.n.(*raft) |
| 365 |
var err error |
| 366 |
|
| 367 |
switch rn.wal.(type) { |
| 368 |
case *fileStore: |
| 369 |
fs := rn.wal.(*fileStore) |
| 370 |
a.cfg.Log, err = newFileStore(fs.fcfg, fs.cfg.StreamConfig) |
| 371 |
case *memStore: |
| 372 |
ms := rn.wal.(*memStore) |
| 373 |
a.cfg.Log, err = newMemStore(&ms.cfg) |
| 374 |
} |
| 375 |
if err != nil { |
| 376 |
panic(err) |
| 377 |
} |
| 378 |
|
| 379 |
// Must reset in-memory state. |
| 380 |
// A real restart would not preserve it, but more importantly we have no way to detect if we |
| 381 |
// already applied an entry. So, the sum must only be updated based on append entries or snapshots. |
| 382 |
a.sum = 0 |
| 383 |
|
| 384 |
a.n, err = a.s.startRaftNode(globalAccountName, a.cfg, pprofLabels{}) |
| 385 |
if err != nil { |
| 386 |
panic(err) |
| 387 |
} |
| 388 |
// Finally restart the driver. |
| 389 |
go smLoop(a) |
| 390 |
} |
| 391 |
|
| 392 |
// Total for the adder state machine. |
| 393 |
func (a *stateAdder) total() int64 { |
| 394 |
a.Lock() |
| 395 |
defer a.Unlock() |
| 396 |
return a.sum |
| 397 |
} |
| 398 |
|
| 399 |
// Install a snapshot. |
| 400 |
func (a *stateAdder) snapshot(t *testing.T) { |
| 401 |
// Don't hold state machine lock as we could deadlock if the node was locked as part of the test. |
| 402 |
a.Lock() |
| 403 |
sum := a.sum |
| 404 |
rn := a.n |
| 405 |
a.Unlock() |
| 406 |
|
| 407 |
data := make([]byte, binary.MaxVarintLen64) |
| 408 |
n := binary.PutVarint(data, sum) |
| 409 |
snap := data[:n] |
| 410 |
require_NoError(t, rn.InstallSnapshot(snap, false)) |
| 411 |
} |
| 412 |
|
| 413 |
// Helper to wait for a certain state. |
| 414 |
func (rg smGroup) waitOnTotal(t *testing.T, expected int64) { |
| 415 |
t.Helper() |
| 416 |
checkFor(t, 5*time.Second, 200*time.Millisecond, func() error { |
| 417 |
var err error |
| 418 |
for _, sm := range rg { |
| 419 |
if sm.node().State() == Closed { |
| 420 |
continue |
| 421 |
} |
| 422 |
asm := sm.(*stateAdder) |
| 423 |
if total := asm.total(); total != expected { |
| 424 |
err = errors.Join(err, fmt.Errorf("Adder on %v has wrong total: %d vs %d", |
| 425 |
asm.server(), total, expected)) |
| 426 |
} |
| 427 |
} |
| 428 |
return err |
| 429 |
}) |
| 430 |
} |
| 431 |
|
| 432 |
// Factory function. |
| 433 |
func newStateAdder(s *Server, cfg *RaftConfig, n RaftNode) stateMachine { |
| 434 |
return &stateAdder{s: s, n: n, cfg: cfg, lch: make(chan bool, 1)} |
| 435 |
} |
| 436 |
|
| 437 |
func initSingleMemRaftNode(t *testing.T) (*raft, func()) { |
| 438 |
t.Helper() |
| 439 |
n, c := initSingleMemRaftNodeWithCluster(t) |
| 440 |
cleanup := func() { |
| 441 |
c.shutdown() |
| 442 |
} |
| 443 |
return n, cleanup |
| 444 |
} |
| 445 |
|
| 446 |
func initSingleMemRaftNodeWithCluster(t *testing.T) (*raft, *cluster) { |
| 447 |
t.Helper() |
| 448 |
c := createJetStreamClusterExplicit(t, "R3S", 3) |
| 449 |
s := c.servers[0] // RunBasicJetStreamServer not available |
| 450 |
|
| 451 |
ms, err := newMemStore(&StreamConfig{Name: "TEST", Storage: MemoryStorage}) |
| 452 |
require_NoError(t, err) |
| 453 |
cfg := &RaftConfig{Name: "TEST", Store: t.TempDir(), Log: ms} |
| 454 |
|
| 455 |
id := s.sys.shash[:idLen] |
| 456 |
err = s.bootstrapRaftNode(cfg, []string{id}, true) |
| 457 |
require_NoError(t, err) |
| 458 |
n, err := s.initRaftNode(globalAccountName, cfg, pprofLabels{}) |
| 459 |
require_NoError(t, err) |
| 460 |
|
| 461 |
return n, c |
| 462 |
} |
| 463 |
|
| 464 |
// Encode an AppendEntry. |
| 465 |
// An AppendEntry is encoded into a buffer and that's stored into the WAL. |
| 466 |
// This is a helper function to generate that buffer. |
| 467 |
func encode(t *testing.T, ae *appendEntry) *appendEntry { |
| 468 |
t.Helper() |
| 469 |
buf, err := ae.encode(nil) |
| 470 |
require_NoError(t, err) |
| 471 |
ae.buf = buf |
| 472 |
return ae |
| 473 |
} |