| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "math/rand" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "runtime/debug" |
| 13 | "slices" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 21 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 22 | "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" |
| 23 | ) |
| 24 | |
| 25 | // TestLifecycleSimulation drives the real controller, over the real store |
| 26 | // and the fake provider, through random launches, crashes, provider faults, |
| 27 | // pauses, resumes, orphans, stops, wall-clock jumps and time advances, and |
| 28 | // checks the invariants of spec §14 (I1 to I7, sim_model_test.go) after |
| 29 | // every step and every reaper pass. The directed scenarios (simScenarios) |
| 30 | // run first. Each seed fixes the random choices, though not the order in |
| 31 | // which the two goroutines of a concurrent duplicate launch run; |
| 32 | // EQUIPO_SIM_SEEDS=n runs seeds 1 to n (default 200) and EQUIPO_SIM_SEED=s |
| 33 | // runs seed s alone. A failure prints its seed and step log. |
| 34 | func TestLifecycleSimulation(t *testing.T) { |
| 35 | seeds := []int64{} |
| 36 | n := 200 |
| 37 | if v := os.Getenv("EQUIPO_SIM_SEEDS"); v != "" { |
| 38 | var err error |
| 39 | if n, err = strconv.Atoi(v); err != nil || n < 1 { |
| 40 | t.Fatalf("EQUIPO_SIM_SEEDS=%q: want a positive count", v) |
| 41 | } |
| 42 | } |
| 43 | for s := 1; s <= n; s++ { |
| 44 | seeds = append(seeds, int64(s)) |
| 45 | } |
| 46 | if v := os.Getenv("EQUIPO_SIM_SEED"); v != "" { |
| 47 | s, err := strconv.ParseInt(v, 10, 64) |
| 48 | if err != nil { |
| 49 | t.Fatalf("EQUIPO_SIM_SEED=%q: want a seed", v) |
| 50 | } |
| 51 | seeds = []int64{s} |
| 52 | } |
| 53 | dir := t.TempDir() |
| 54 | template := simTemplate(t, dir) |
| 55 | var mu sync.Mutex |
| 56 | var fails []*simFailure |
| 57 | for i, sc := range simScenarios { |
| 58 | if f := runSim(dir, -int64(i+1), template, sc.name, sc.run); f != nil { |
| 59 | fails = append(fails, f) |
| 60 | } |
| 61 | } |
| 62 | next := make(chan int64) |
| 63 | var wg sync.WaitGroup |
| 64 | for range min(runtime.GOMAXPROCS(0), 8, len(seeds)) { |
| 65 | wg.Add(1) |
| 66 | go func() { |
| 67 | defer wg.Done() |
| 68 | for seed := range next { |
| 69 | if f := runSim(dir, seed, template, "", (*simWorld).randomSteps); f != nil { |
| 70 | mu.Lock() |
| 71 | fails = append(fails, f) |
| 72 | mu.Unlock() |
| 73 | } |
| 74 | } |
| 75 | }() |
| 76 | } |
| 77 | for _, seed := range seeds { |
| 78 | mu.Lock() |
| 79 | stop := len(fails) >= 3 // enough to show; the rest would only repeat it |
| 80 | mu.Unlock() |
| 81 | if stop { |
| 82 | break |
| 83 | } |
| 84 | next <- seed |
| 85 | } |
| 86 | close(next) |
| 87 | wg.Wait() |
| 88 | slices.SortFunc(fails, func(a, b *simFailure) int { return int(a.seed - b.seed) }) |
| 89 | for _, f := range fails { |
| 90 | what := fmt.Sprintf("seed %d", f.seed) |
| 91 | if f.name != "" { |
| 92 | what = "scenario " + f.name |
| 93 | } |
| 94 | t.Errorf("%s failed at step %d:\n %s", what, f.step, strings.Join(f.bad, "\n ")) |
| 95 | } |
| 96 | if len(fails) > 0 { |
| 97 | log := fails[0].log |
| 98 | if lines := strings.Split(log, "\n"); len(lines) > simLogLines { |
| 99 | log = fmt.Sprintf("(%d earlier lines left out)\n%s", len(lines)-simLogLines, strings.Join(lines[len(lines)-simLogLines:], "\n")) |
| 100 | } |
| 101 | what := fmt.Sprintf("seed %d (EQUIPO_SIM_SEED=%d replays it)", fails[0].seed, fails[0].seed) |
| 102 | if fails[0].name != "" { |
| 103 | what = "scenario " + fails[0].name |
| 104 | } |
| 105 | t.Logf("step log of %s:\n%s", what, log) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // simTemplate migrates one store and returns its file with the clock |
| 110 | // checkpoint removed, so each seed starts from a copy that Open still |
| 111 | // treats as fresh (T at 0, not restarted). Creating a store from nothing |
| 112 | // costs tens of milliseconds of disk syncs; a copy costs almost none. |
| 113 | func simTemplate(t *testing.T, dir string) []byte { |
| 114 | t.Helper() |
| 115 | path := filepath.Join(dir, "template.db") |
| 116 | s, err := Open(context.Background(), path, isolatedjobtest.NewFakeClock(testWall)) |
| 117 | if err != nil { |
| 118 | t.Fatalf("open the template store: %v", err) |
| 119 | } |
| 120 | if err := s.Close(); err != nil { |
| 121 | t.Fatalf("close the template store: %v", err) |
| 122 | } |
| 123 | db, err := sql.Open("sqlite", path) |
| 124 | if err != nil { |
| 125 | t.Fatalf("open the template file: %v", err) |
| 126 | } |
| 127 | if _, err := db.Exec(`DELETE FROM clock`); err != nil { |
| 128 | t.Fatalf("template: remove the clock checkpoint: %v", err) |
| 129 | } |
| 130 | if err := db.Close(); err != nil { |
| 131 | t.Fatalf("close the template file: %v", err) |
| 132 | } |
| 133 | b, err := os.ReadFile(path) |
| 134 | if err != nil { |
| 135 | t.Fatalf("read the template: %v", err) |
| 136 | } |
| 137 | return b |
| 138 | } |
| 139 | |
| 140 | // simSteps is how many operations one seed runs; simLogLines is how much |
| 141 | // of a failing seed's step log is printed. |
| 142 | const ( |
| 143 | simSteps = 40 |
| 144 | simLogLines = 400 |
| 145 | ) |
| 146 | |
| 147 | const simActor hostedwire.KeyID = "inst-1" |
| 148 | |
| 149 | type simFailure struct { |
| 150 | name string // a directed scenario's; empty for a random seed |
| 151 | seed int64 |
| 152 | step int |
| 153 | bad []string |
| 154 | log string |
| 155 | } |
| 156 | |
| 157 | // simPause is the model of one attempt's pause barrier. |
| 158 | type simPause struct { |
| 159 | gen int64 |
| 160 | drainedAt T |
| 161 | open bool // drained and not reopened or resumed since |
| 162 | acked bool // the current generation was acknowledged in time |
| 163 | } |
| 164 | |
| 165 | // simReturned is an epoch a Resume call returned, checked against the store. |
| 166 | type simReturned struct { |
| 167 | attempt, op string |
| 168 | epoch int64 |
| 169 | } |
| 170 | |
| 171 | // simModel is what the simulation itself expects, kept only as far as the |
| 172 | // invariants need it. |
| 173 | type simModel struct { |
| 174 | next, nextOp, nextOrphan int |
| 175 | req map[string]LaunchRequest |
| 176 | stopAt map[string]T // stop time from the launch step's time and the lifetime |
| 177 | pause map[string]*simPause |
| 178 | ops map[string][]string // resume operation IDs used, per attempt |
| 179 | done map[[2]string]int64 // (attempt, operation) -> epoch, once seen done |
| 180 | returned []simReturned |
| 181 | deferral map[isolatedjob.Ref]*simDeferral // R22 deferral of VMs with no saved Ref |
| 182 | } |
| 183 | |
| 184 | // simWorld is one seed's controller, store, fake and model clock. |
| 185 | type simWorld struct { |
| 186 | seed int64 |
| 187 | rng *rand.Rand |
| 188 | ctx context.Context |
| 189 | path string |
| 190 | clk *isolatedjobtest.FakeClock |
| 191 | fake *isolatedjob.Fake |
| 192 | run *simRunner |
| 193 | cfg Config |
| 194 | store *Store |
| 195 | c *Controller |
| 196 | |
| 197 | // The model's controller clock: restored at open as the store should, |
| 198 | // from the checkpoint written at close. |
| 199 | opened bool |
| 200 | restarted bool |
| 201 | base, openedAt T |
| 202 | monoAtOpen time.Duration |
| 203 | cpT T |
| 204 | cpWall time.Time |
| 205 | opT T // controller time when the current step began |
| 206 | auditBad int |
| 207 | step int |
| 208 | snap *simSnap |
| 209 | m simModel |
| 210 | bad []string |
| 211 | logMu sync.Mutex |
| 212 | lines []string |
| 213 | off []bool // simOps kinds this seed leaves out (swarm testing) |
| 214 | follow string // the step the runner's protocol takes next, if any |
| 215 | short bool // the next time advance is a short one |
| 216 | } |
| 217 | |
| 218 | func newSimWorld(dir string, seed int64) *simWorld { |
| 219 | clk := isolatedjobtest.NewFakeClock(testWall) |
| 220 | fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits()) |
| 221 | fake.SetBackstop(false) |
| 222 | w := &simWorld{ |
| 223 | seed: seed, rng: rand.New(rand.NewSource(seed)), ctx: context.Background(), |
| 224 | path: filepath.Join(dir, fmt.Sprintf("sim-%d.db", seed)), clk: clk, fake: fake, |
| 225 | cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true}, |
| 226 | ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint}, |
| 227 | m: simModel{req: map[string]LaunchRequest{}, stopAt: map[string]T{}, pause: map[string]*simPause{}, |
| 228 | ops: map[string][]string{}, done: map[[2]string]int64{}, deferral: map[isolatedjob.Ref]*simDeferral{}}, |
| 229 | } |
| 230 | w.run = newSimRunner(fake, w) |
| 231 | // Swarm testing: each seed leaves out some kinds of step, so some |
| 232 | // seeds run long pause and resume sequences that a stop would cut |
| 233 | // short, and others pile up faults. Launches and time always run. |
| 234 | w.off = make([]bool, len(simOps)) |
| 235 | for i, o := range simOps { |
| 236 | w.off[i] = !o.always && w.rng.Intn(5) < 2 |
| 237 | } |
| 238 | return w |
| 239 | } |
| 240 | |
| 241 | func (w *simWorld) now() T { return w.base + T(w.clk.Mono()-w.monoAtOpen) } |
| 242 | |
| 243 | func (w *simWorld) logf(format string, args ...any) { |
| 244 | w.logMu.Lock() |
| 245 | defer w.logMu.Unlock() |
| 246 | w.lines = append(w.lines, fmt.Sprintf(format, args...)) |
| 247 | } |
| 248 | |
| 249 | // runSim runs one seed's random steps, or one directed scenario, in a world |
| 250 | // of its own, and returns its failure, if any. |
| 251 | func runSim(dir string, seed int64, template []byte, name string, body func(*simWorld)) (f *simFailure) { |
| 252 | w := newSimWorld(dir, seed) |
| 253 | defer w.cleanup() |
| 254 | if err := os.WriteFile(w.path, template, 0o600); err != nil { |
| 255 | return &simFailure{name: name, seed: seed, bad: []string{err.Error()}} |
| 256 | } |
| 257 | fail := func(bad ...string) *simFailure { |
| 258 | return &simFailure{name: name, seed: seed, step: w.step, bad: bad, log: strings.Join(w.lines, "\n")} |
| 259 | } |
| 260 | defer func() { |
| 261 | if p := recover(); p != nil { |
| 262 | f = fail(fmt.Sprintf("panic: %v\n%s", p, debug.Stack())) |
| 263 | } |
| 264 | }() |
| 265 | if err := w.open(); err != nil { |
| 266 | return fail(err.Error()) |
| 267 | } |
| 268 | if w.pass() { |
| 269 | body(w) |
| 270 | } |
| 271 | if w.bad != nil { |
| 272 | return fail(w.bad...) |
| 273 | } |
| 274 | return nil |
| 275 | } |
| 276 | |
| 277 | func (w *simWorld) randomSteps() { |
| 278 | for range simSteps { |
| 279 | op := w.pickOp() |
| 280 | if !w.do(op.name, func() string { return op.run(w) }) { |
| 281 | return |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | // do runs one step: it logs it, runs it, then the invariants. It reports |
| 287 | // whether everything still holds. |
| 288 | func (w *simWorld) do(what string, run func() string) bool { |
| 289 | w.step++ |
| 290 | w.opT = w.now() |
| 291 | w.logf("step %d at %v: %s", w.step, simDur(w.opT), what) |
| 292 | w.logf(" %s", run()) |
| 293 | if w.bad == nil { |
| 294 | w.verify() |
| 295 | } |
| 296 | return w.bad == nil |
| 297 | } |
| 298 | |
| 299 | // want is a directed scenario's own expectation, checked after the |
| 300 | // invariants: a scenario that does not reach the state it means to test |
| 301 | // fails rather than passing vacuously. |
| 302 | func (w *simWorld) want(ok bool, format string, args ...any) bool { |
| 303 | if !ok && w.bad == nil { |
| 304 | w.bad = []string{"scenario: " + fmt.Sprintf(format, args...)} |
| 305 | } |
| 306 | return w.bad == nil |
| 307 | } |
| 308 | |
| 309 | func (w *simWorld) cleanup() { |
| 310 | if w.opened { |
| 311 | _ = w.store.Close() |
| 312 | } |
| 313 | for _, suffix := range []string{"", "-wal", "-shm"} { |
| 314 | _ = os.Remove(w.path + suffix) |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | // open opens the store and builds a controller, as the process starting. |
| 319 | // The model restores controller time the way the store must: the |
| 320 | // checkpoint's time plus the wall time since it, never less. |
| 321 | func (w *simWorld) open() error { |
| 322 | s, err := Open(w.ctx, w.path, w.clk) |
| 323 | if err != nil { |
| 324 | return fmt.Errorf("open: %w", err) |
| 325 | } |
| 326 | // A crash here is Close and Open, never a power cut, so the store's |
| 327 | // disk syncs buy the simulation nothing and cost most of its time. |
| 328 | // Only this test connection changes; it must run outside a transaction. |
| 329 | if _, err := s.conn.ExecContext(w.ctx, `PRAGMA synchronous = OFF`); err != nil { |
| 330 | _ = s.Close() |
| 331 | return fmt.Errorf("open: turn off disk syncs: %w", err) |
| 332 | } |
| 333 | w.base = 0 |
| 334 | if w.cpWall != (time.Time{}) { |
| 335 | w.restarted = true |
| 336 | w.base = w.cpT |
| 337 | if wall := w.clk.Wall(); wall.After(w.cpWall) { |
| 338 | w.base += T(wall.Sub(w.cpWall)) |
| 339 | } |
| 340 | } |
| 341 | w.monoAtOpen, w.openedAt = w.clk.Mono(), w.base |
| 342 | c, err := New(w.cfg, Deps{Store: s, Runner: w.run, Auditor: w.fake, Alerter: &recordingAlerter{}}) |
| 343 | if err != nil { |
| 344 | _ = s.Close() |
| 345 | return fmt.Errorf("new: %w", err) |
| 346 | } |
| 347 | w.store, w.c, w.opened = s, c, true |
| 348 | w.run.mu.Lock() |
| 349 | w.run.openPass = w.run.passNo |
| 350 | w.run.mu.Unlock() |
| 351 | return nil |
| 352 | } |
| 353 | |
| 354 | // close closes the store, as the process exiting; Close checkpoints. |
| 355 | func (w *simWorld) close() error { |
| 356 | w.cpT, w.cpWall = w.now(), w.clk.Wall() |
| 357 | w.opened = false |
| 358 | return w.store.Close() |
| 359 | } |
| 360 | |
| 361 | // verify reads a snapshot and runs every invariant; it records the first |
| 362 | // violations in w.bad. |
| 363 | func (w *simWorld) verify() bool { |
| 364 | s, err := w.read() |
| 365 | if err != nil { |
| 366 | w.bad = []string{err.Error()} |
| 367 | return false |
| 368 | } |
| 369 | w.snap = s |
| 370 | if bad := w.check(s); len(bad) > 0 { |
| 371 | w.bad = bad |
| 372 | return false |
| 373 | } |
| 374 | return true |
| 375 | } |
| 376 | |
| 377 | // pass runs one reaper pass, as Loop would, then the invariants. |
| 378 | func (w *simWorld) pass() bool { |
| 379 | a := isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true} |
| 380 | if w.auditBad > 0 { |
| 381 | w.auditBad-- |
| 382 | a.ResolverDisabled = false |
| 383 | } |
| 384 | w.fake.SetAudit(a, nil) |
| 385 | w.run.beginPass() |
| 386 | rep, err := w.c.Reap(w.ctx) |
| 387 | w.run.endPass() |
| 388 | w.logf(" pass at %v: %+v %s", simDur(w.now()), rep, errText(err)) |
| 389 | return w.verify() |
| 390 | } |
| 391 | |
| 392 | // advance moves time forward by d in steps of at most ReapInterval, with |
| 393 | // the provider's progress (Tick) and a reaper pass at each step. While |
| 394 | // nothing can change it skips ahead, but never past a recorded drain or stop |
| 395 | // time, where a pass runs, and never while a fault window (failing audits, |
| 396 | // incomplete Lists) or a queued List fault would have played out in the |
| 397 | // passes left out: a quiet pass calls only List and the audit. |
| 398 | func (w *simWorld) advance(d time.Duration) string { |
| 399 | passes := 0 |
| 400 | for d > 0 && w.bad == nil { |
| 401 | step := min(d, ReapInterval) |
| 402 | if step > time.Second && w.rng.Intn(4) == 0 { |
| 403 | step = time.Duration(1+w.rng.Int63n(int64(step/time.Second))) * time.Second |
| 404 | } |
| 405 | if d > ReapInterval && w.snap.quiet() && w.faultFree() { |
| 406 | skip := d |
| 407 | if at, ok := w.snap.nextEvent(w.now()); ok && time.Duration(at-w.now()) < skip { |
| 408 | skip = time.Duration(at - w.now()) |
| 409 | } |
| 410 | if skip > step { |
| 411 | step = skip |
| 412 | w.logf(" quiet: skip %v", skip) |
| 413 | } |
| 414 | } |
| 415 | w.clk.AdvanceMono(step) |
| 416 | w.clk.SetWall(w.clk.Wall().Add(step)) |
| 417 | d -= step |
| 418 | w.fake.Tick() |
| 419 | w.pass() |
| 420 | passes++ |
| 421 | } |
| 422 | return fmt.Sprintf("%d passes", passes) |
| 423 | } |
| 424 | |
| 425 | // simOp is one kind of step. Its weight is multiplied by simBoost while |
| 426 | // some job without proof is ready for it (boost), so the runner's side of |
| 427 | // the pause protocol (drain, acknowledge, suspend, resume) is followed |
| 428 | // often enough to reach its later steps; the step itself still picks any |
| 429 | // job, and the generation or operation it names, at random. |
| 430 | // faultFree reports whether no failing audit, incomplete-List window or |
| 431 | // queued List fault is waiting for a pass. |
| 432 | func (w *simWorld) faultFree() bool { |
| 433 | w.run.mu.Lock() |
| 434 | defer w.run.mu.Unlock() |
| 435 | return w.auditBad == 0 && w.run.incomplete == 0 && len(w.run.pending[isolatedjob.OpList]) == 0 |
| 436 | } |
| 437 | |
| 438 | type simOp struct { |
| 439 | name string |
| 440 | weight int |
| 441 | boost func(w *simWorld, j *simJob) bool |
| 442 | run func(w *simWorld) string |
| 443 | always bool // never left out of a seed |
| 444 | } |
| 445 | |
| 446 | // The pause protocol's next step for job j, by the model. |
| 447 | func simToDrain(_ *simWorld, j *simJob) bool { return j.state == JobRunning } |
| 448 | |
| 449 | func simToAck(w *simWorld, j *simJob) bool { |
| 450 | p := w.m.pause[j.attempt] |
| 451 | return j.state == JobDraining && p != nil && p.open && !p.acked |
| 452 | } |
| 453 | |
| 454 | func simToSuspend(w *simWorld, j *simJob) bool { |
| 455 | p := w.m.pause[j.attempt] |
| 456 | return j.state == JobDraining && p != nil && p.acked |
| 457 | } |
| 458 | |
| 459 | func simToResume(_ *simWorld, j *simJob) bool { |
| 460 | return j.state == JobSuspended || j.state == JobResuming |
| 461 | } |
| 462 | |
| 463 | const simBoost = 4 |
| 464 | |
| 465 | var simOps = []simOp{ |
| 466 | {"launch", 10, nil, (*simWorld).opLaunch, true}, |
| 467 | {"launch a replacement", 5, nil, (*simWorld).opReplace, false}, |
| 468 | {"launch a concurrent duplicate", 3, nil, (*simWorld).opDuplicate, false}, |
| 469 | {"crash and reopen", 4, nil, (*simWorld).opCrash, false}, |
| 470 | {"fault: lost reply", 4, nil, (*simWorld).opLostReply, false}, |
| 471 | {"fault: throttle", 3, nil, (*simWorld).opThrottle, false}, |
| 472 | {"fault: incomplete lists", 3, nil, (*simWorld).opIncomplete, false}, |
| 473 | {"fault: unknown state", 3, nil, (*simWorld).opUnknownState, false}, |
| 474 | {"fault: unknown age", 2, nil, (*simWorld).opUnknownAge, false}, |
| 475 | {"fault: failing network audit", 3, nil, (*simWorld).opAuditFails, false}, |
| 476 | {"drain", 4, simToDrain, (*simWorld).opDrain, false}, |
| 477 | {"acknowledge quiescent", 3, simToAck, (*simWorld).opAck, false}, |
| 478 | {"suspend", 3, simToSuspend, (*simWorld).opSuspend, false}, |
| 479 | {"reopen", 1, nil, (*simWorld).opReopen, false}, |
| 480 | {"resume", 3, simToResume, (*simWorld).opResume, false}, |
| 481 | {"plant an orphan", 3, nil, (*simWorld).opPlant, false}, |
| 482 | {"stop", 5, nil, (*simWorld).opStop, false}, |
| 483 | {"a VM ends by itself", 1, nil, (*simWorld).opEnd, false}, |
| 484 | {"the provider forgets a stopped VM", 1, nil, (*simWorld).opVanish, false}, |
| 485 | {"wall-clock jump", 3, nil, (*simWorld).opWall, false}, |
| 486 | {"time advance", 16, nil, (*simWorld).opAdvance, true}, |
| 487 | } |
| 488 | |
| 489 | func (w *simWorld) pickOp() simOp { |
| 490 | // A runner follows the pause protocol promptly: after a drain it |
| 491 | // usually acknowledges, then suspends, then waits for the VM, then |
| 492 | // resumes. Any other step may still come in between. |
| 493 | if next := w.follow; next != "" { |
| 494 | w.follow = "" |
| 495 | for i, o := range simOps { |
| 496 | if o.name == next && !w.off[i] && w.rng.Intn(10) < 7 { |
| 497 | return o |
| 498 | } |
| 499 | } |
| 500 | } |
| 501 | weights := make([]int, len(simOps)) |
| 502 | total := 0 |
| 503 | for i, o := range simOps { |
| 504 | if w.off[i] { |
| 505 | continue |
| 506 | } |
| 507 | weights[i] = o.weight |
| 508 | if o.boost != nil && w.anyJob(o.boost) { |
| 509 | weights[i] *= simBoost |
| 510 | } |
| 511 | total += weights[i] |
| 512 | } |
| 513 | n := w.rng.Intn(total) |
| 514 | for i, o := range simOps { |
| 515 | if n -= weights[i]; n < 0 { |
| 516 | return o |
| 517 | } |
| 518 | } |
| 519 | return simOps[len(simOps)-1] |
| 520 | } |
| 521 | |
| 522 | // simLives are the lifetimes launches ask for, short ones often so stop |
| 523 | // times come within a few passes. |
| 524 | var simLives = []struct { |
| 525 | d time.Duration |
| 526 | weight int |
| 527 | }{{11 * time.Minute, 3}, {12 * time.Minute, 2}, {15 * time.Minute, 3}, {20 * time.Minute, 3}, {30 * time.Minute, 4}, |
| 528 | {45 * time.Minute, 4}, {time.Hour, 4}, {2 * time.Hour, 2}, {8 * time.Hour, 1}} |
| 529 | |
| 530 | func (w *simWorld) newRequest(replaces string) LaunchRequest { |
| 531 | w.m.next++ |
| 532 | id := fmt.Sprintf("a%d", w.m.next) |
| 533 | total := 0 |
| 534 | for _, l := range simLives { |
| 535 | total += l.weight |
| 536 | } |
| 537 | n, life := w.rng.Intn(total), simLives[0].d |
| 538 | for _, l := range simLives { |
| 539 | if n -= l.weight; n < 0 { |
| 540 | life = l.d |
| 541 | break |
| 542 | } |
| 543 | } |
| 544 | q := LaunchRequest{AttemptID: id, TaskID: "task-" + id, Account: "acct-1", Replaces: replaces, |
| 545 | Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetime: life, InstanceCode: testCode} |
| 546 | w.m.req[id] = q |
| 547 | return q |
| 548 | } |
| 549 | |
| 550 | // anyJob reports whether some job without proof satisfies ok. |
| 551 | func (w *simWorld) anyJob(ok func(*simWorld, *simJob) bool) bool { |
| 552 | for _, id := range w.snap.order { |
| 553 | if j := w.snap.jobs[id]; j.proof == "" && ok(w, j) { |
| 554 | return true |
| 555 | } |
| 556 | } |
| 557 | return false |
| 558 | } |
| 559 | |
| 560 | // pickReady returns, four times in five, a random job without proof that |
| 561 | // satisfies ready; otherwise, or when there is none, pickJob(states...). |
| 562 | func (w *simWorld) pickReady(ready func(*simWorld, *simJob) bool, states ...string) string { |
| 563 | var ids []string |
| 564 | for _, id := range w.snap.order { |
| 565 | if j := w.snap.jobs[id]; j.proof == "" && ready(w, j) { |
| 566 | ids = append(ids, id) |
| 567 | } |
| 568 | } |
| 569 | if len(ids) > 0 && w.rng.Intn(5) != 0 { |
| 570 | return ids[w.rng.Intn(len(ids))] |
| 571 | } |
| 572 | return w.pickJob(states...) |
| 573 | } |
| 574 | |
| 575 | // pickJob returns a random attempt in one of states (any state when none |
| 576 | // is given) that holds no proof, or "" when there is none. |
| 577 | func (w *simWorld) pickJob(states ...string) string { |
| 578 | var ids []string |
| 579 | for _, id := range w.snap.order { |
| 580 | j := w.snap.jobs[id] |
| 581 | if j.proof == "" && (len(states) == 0 || slices.Contains(states, j.state)) { |
| 582 | ids = append(ids, id) |
| 583 | } |
| 584 | } |
| 585 | if len(ids) == 0 { |
| 586 | if len(states) > 0 && len(w.snap.order) > 0 && w.rng.Intn(6) == 0 { |
| 587 | return w.snap.order[w.rng.Intn(len(w.snap.order))] // a job in the wrong state is refused |
| 588 | } |
| 589 | return "" |
| 590 | } |
| 591 | return ids[w.rng.Intn(len(ids))] |
| 592 | } |
| 593 | |
| 594 | func (w *simWorld) maybeLost(op isolatedjob.Op, oneIn int) string { |
| 595 | if w.rng.Intn(oneIn) != 0 { |
| 596 | return "" |
| 597 | } |
| 598 | w.run.queue(op, isolatedjob.FaultLostReply) |
| 599 | return " (reply lost)" |
| 600 | } |
| 601 | |
| 602 | func (w *simWorld) opLaunch() string { |
| 603 | q := w.newRequest("") |
| 604 | lost := w.maybeLost(isolatedjob.OpLaunch, 4) |
| 605 | v, err := w.c.Launch(w.ctx, simActor, instKey, q) |
| 606 | return fmt.Sprintf("launch %s life %v%s -> %s", q.AttemptID, q.MaxLifetime, lost, viewText(v, err)) |
| 607 | } |
| 608 | |
| 609 | func (w *simWorld) opReplace() string { |
| 610 | var proven, all []string |
| 611 | for _, id := range w.snap.order { |
| 612 | all = append(all, id) |
| 613 | if w.snap.jobs[id].proof != "" { |
| 614 | proven = append(proven, id) |
| 615 | } |
| 616 | } |
| 617 | if len(all) == 0 { |
| 618 | return w.opLaunch() |
| 619 | } |
| 620 | old := all[w.rng.Intn(len(all))] |
| 621 | if len(proven) > 0 && w.rng.Intn(4) != 0 { |
| 622 | old = proven[w.rng.Intn(len(proven))] |
| 623 | } |
| 624 | q := w.newRequest(old) |
| 625 | lost := w.maybeLost(isolatedjob.OpLaunch, 4) |
| 626 | v, err := w.c.Launch(w.ctx, simActor, instKey, q) |
| 627 | return fmt.Sprintf("launch %s replacing %s%s -> %s", q.AttemptID, old, lost, viewText(v, err)) |
| 628 | } |
| 629 | |
| 630 | func (w *simWorld) opDuplicate() string { |
| 631 | var q LaunchRequest |
| 632 | if len(w.snap.order) > 0 && w.rng.Intn(3) == 0 { |
| 633 | q = w.m.req[w.snap.order[w.rng.Intn(len(w.snap.order))]] |
| 634 | } else { |
| 635 | q = w.newRequest("") |
| 636 | } |
| 637 | lost := w.maybeLost(isolatedjob.OpLaunch, 3) |
| 638 | // The two goroutines run in whatever order the scheduler picks, so a |
| 639 | // seed fixes which requests race but not which one wins, or which |
| 640 | // one meets a queued fault: replaying a seed can differ here. |
| 641 | out := make([]string, 2) |
| 642 | var wg sync.WaitGroup |
| 643 | for i := range out { |
| 644 | wg.Add(1) |
| 645 | go func() { |
| 646 | defer wg.Done() |
| 647 | v, err := w.c.Launch(w.ctx, simActor, instKey, q) |
| 648 | out[i] = viewText(v, err) |
| 649 | }() |
| 650 | } |
| 651 | wg.Wait() |
| 652 | return fmt.Sprintf("launch %s twice at once%s -> %s; %s", q.AttemptID, lost, out[0], out[1]) |
| 653 | } |
| 654 | |
| 655 | func (w *simWorld) opCrash() string { |
| 656 | var down, extra time.Duration |
| 657 | if w.rng.Intn(2) == 0 { |
| 658 | down = time.Duration(1+w.rng.Intn(1200)) * time.Second |
| 659 | } |
| 660 | if w.rng.Intn(3) == 0 { |
| 661 | extra = time.Duration(w.rng.Intn(7200)-3600) * time.Second |
| 662 | } |
| 663 | switch { |
| 664 | case w.cfg.Enabled && w.rng.Intn(8) == 0: |
| 665 | w.cfg.Enabled = false |
| 666 | case !w.cfg.Enabled && w.rng.Intn(2) == 0: |
| 667 | w.cfg.Enabled = true |
| 668 | } |
| 669 | return w.crash(down, extra, w.rng.Intn(10) < 7) |
| 670 | } |
| 671 | |
| 672 | // crash closes the store, lets down pass (the wall clock moves down plus |
| 673 | // extra), opens it again and builds a new controller; with pass, the first |
| 674 | // reaper pass runs at once, as Loop's does. |
| 675 | func (w *simWorld) crash(down, extra time.Duration, pass bool) string { |
| 676 | if err := w.close(); err != nil { |
| 677 | w.bad = []string{"close: " + err.Error()} |
| 678 | return "close failed" |
| 679 | } |
| 680 | wall := w.clk.Wall().Add(down + extra) |
| 681 | w.clk.AdvanceMono(down) |
| 682 | w.clk.SetWall(wall) |
| 683 | if down > 0 { |
| 684 | w.fake.Tick() |
| 685 | } |
| 686 | if err := w.open(); err != nil { |
| 687 | w.bad = []string{err.Error()} |
| 688 | return "reopen failed" |
| 689 | } |
| 690 | out := fmt.Sprintf("down %v, wall moved %v, launches enabled %v", down, wall.Sub(w.cpWall), w.cfg.Enabled) |
| 691 | if pass { |
| 692 | w.pass() |
| 693 | out += ", first pass run" |
| 694 | } |
| 695 | return out |
| 696 | } |
| 697 | |
| 698 | func (w *simWorld) opLostReply() string { |
| 699 | op := []isolatedjob.Op{isolatedjob.OpLaunch, isolatedjob.OpStop, isolatedjob.OpResume}[w.rng.Intn(3)] |
| 700 | w.run.queue(op, isolatedjob.FaultLostReply) |
| 701 | return fmt.Sprintf("the next %s reply is lost", op) |
| 702 | } |
| 703 | |
| 704 | func (w *simWorld) opThrottle() string { |
| 705 | ops := []isolatedjob.Op{isolatedjob.OpLaunch, isolatedjob.OpGet, isolatedjob.OpSuspend, isolatedjob.OpResume, |
| 706 | isolatedjob.OpStop, isolatedjob.OpList} |
| 707 | op := ops[w.rng.Intn(len(ops))] |
| 708 | w.run.queue(op, isolatedjob.FaultThrottle) |
| 709 | return fmt.Sprintf("the next %s is throttled", op) |
| 710 | } |
| 711 | |
| 712 | func (w *simWorld) opIncomplete() string { |
| 713 | k := 1 + w.rng.Intn(6) |
| 714 | w.run.mu.Lock() |
| 715 | w.run.incomplete += k |
| 716 | w.run.mu.Unlock() |
| 717 | return fmt.Sprintf("every List is incomplete for %d more passes", k) |
| 718 | } |
| 719 | |
| 720 | func (w *simWorld) opUnknownState() string { |
| 721 | w.run.queue(isolatedjob.OpGet, isolatedjob.FaultUnknownState) |
| 722 | return "the next Get reads unknown" |
| 723 | } |
| 724 | |
| 725 | func (w *simWorld) opUnknownAge() string { |
| 726 | w.run.queue(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) |
| 727 | return "the next Get gives no age" |
| 728 | } |
| 729 | |
| 730 | func (w *simWorld) opAuditFails() string { |
| 731 | k := 5 + w.rng.Intn(16) |
| 732 | w.auditBad += k |
| 733 | return fmt.Sprintf("the network audit fails for %d more passes", k) |
| 734 | } |
| 735 | |
| 736 | // genChoice picks a generation to name: the current one mostly, else the |
| 737 | // one before or the one after. |
| 738 | func (w *simWorld) genChoice(id string) (int64, string) { |
| 739 | cur := int64(0) |
| 740 | if p := w.m.pause[id]; p != nil { |
| 741 | cur = p.gen |
| 742 | } |
| 743 | switch n := w.rng.Intn(20); { |
| 744 | case n < 14: |
| 745 | return cur, "current" |
| 746 | case n < 17: |
| 747 | return cur - 1, "stale" |
| 748 | } |
| 749 | return cur + 1, "next" |
| 750 | } |
| 751 | |
| 752 | func (w *simWorld) opDrain() string { |
| 753 | id := w.pickReady(simToDrain, JobRunning, JobDraining) |
| 754 | if id == "" { |
| 755 | return "no job to drain" |
| 756 | } |
| 757 | gen, err := w.drain(id) |
| 758 | if err == nil { |
| 759 | w.follow = "acknowledge quiescent" |
| 760 | } |
| 761 | return fmt.Sprintf("drain %s -> generation %d %s", id, gen, errText(err)) |
| 762 | } |
| 763 | |
| 764 | func (w *simWorld) drain(id string) (int64, error) { |
| 765 | gen, err := w.c.Drain(w.ctx, simActor, instKey, id) |
| 766 | if err == nil { |
| 767 | w.m.pause[id] = &simPause{gen: gen, drainedAt: w.now(), open: true} |
| 768 | } |
| 769 | return gen, err |
| 770 | } |
| 771 | |
| 772 | // ack sends Quiescent for gen and records an in-time acknowledgement of |
| 773 | // the current generation in the model's history. A generation drained |
| 774 | // before the last restart is never in time: the downtime is unknown. |
| 775 | func (w *simWorld) ack(id string, gen int64) error { |
| 776 | err := w.c.Quiescent(w.ctx, simActor, instKey, id, gen) |
| 777 | if p := w.m.pause[id]; err == nil && p != nil && p.open && gen == p.gen && w.now()-p.drainedAt <= T(PauseAckTimeout) && |
| 778 | !(w.restarted && p.drainedAt <= w.openedAt) { |
| 779 | p.acked = true |
| 780 | } |
| 781 | return err |
| 782 | } |
| 783 | |
| 784 | func (w *simWorld) suspend(id string, gen int64) error { |
| 785 | w.run.mu.Lock() |
| 786 | w.run.suspendOp = &simGen{attempt: id, gen: gen} |
| 787 | w.run.mu.Unlock() |
| 788 | err := w.c.Suspend(w.ctx, simActor, instKey, id, gen) |
| 789 | w.run.mu.Lock() |
| 790 | w.run.suspendOp = nil |
| 791 | w.run.mu.Unlock() |
| 792 | return err |
| 793 | } |
| 794 | |
| 795 | func (w *simWorld) resume(id, op string) (int64, error) { |
| 796 | epoch, err := w.c.Resume(w.ctx, simActor, instKey, id, op) |
| 797 | if err == nil { // a commit, if this call made one, closes the pause in check |
| 798 | w.m.returned = append(w.m.returned, simReturned{attempt: id, op: op, epoch: epoch}) |
| 799 | } |
| 800 | return epoch, err |
| 801 | } |
| 802 | |
| 803 | func (w *simWorld) opAck() string { |
| 804 | id := w.pickReady(simToAck, JobDraining) |
| 805 | if id == "" { |
| 806 | return "no job to acknowledge" |
| 807 | } |
| 808 | gen, kind := w.genChoice(id) |
| 809 | p := w.m.pause[id] |
| 810 | if kind == "current" && p != nil && w.now()-p.drainedAt > T(PauseAckTimeout) { |
| 811 | kind = "late" |
| 812 | } |
| 813 | err := w.ack(id, gen) |
| 814 | if err == nil && p != nil && p.acked && gen == p.gen { |
| 815 | w.follow = "suspend" |
| 816 | } |
| 817 | return fmt.Sprintf("quiescent %s generation %d (%s) -> %s", id, gen, kind, errText(err)) |
| 818 | } |
| 819 | |
| 820 | func (w *simWorld) opSuspend() string { |
| 821 | id := w.pickReady(simToSuspend, JobDraining, JobSuspending) |
| 822 | if id == "" { |
| 823 | return "no job to suspend" |
| 824 | } |
| 825 | gen, kind := w.genChoice(id) |
| 826 | fault := "" |
| 827 | if w.rng.Intn(5) == 0 { |
| 828 | w.run.queue(isolatedjob.OpSuspend, isolatedjob.FaultThrottle) |
| 829 | fault = " (throttled)" |
| 830 | } |
| 831 | err := w.suspend(id, gen) |
| 832 | if err == nil { |
| 833 | w.follow, w.short = "time advance", true |
| 834 | } |
| 835 | return fmt.Sprintf("suspend %s generation %d (%s)%s -> %s", id, gen, kind, fault, errText(err)) |
| 836 | } |
| 837 | |
| 838 | func (w *simWorld) opReopen() string { |
| 839 | id := w.pickJob(JobDraining) |
| 840 | if id == "" { |
| 841 | return "no job to reopen" |
| 842 | } |
| 843 | gen, kind := w.genChoice(id) |
| 844 | err := w.c.Reopen(w.ctx, simActor, instKey, id, gen) |
| 845 | if p := w.m.pause[id]; err == nil && p != nil && gen == p.gen { |
| 846 | p.open, p.acked = false, false |
| 847 | } |
| 848 | return fmt.Sprintf("reopen %s generation %d (%s) -> %s", id, gen, kind, errText(err)) |
| 849 | } |
| 850 | |
| 851 | func (w *simWorld) opResume() string { |
| 852 | id := w.pickReady(simToResume, JobSuspended, JobResuming) |
| 853 | if id == "" { |
| 854 | return "no job to resume" |
| 855 | } |
| 856 | op, kind := "", "new" |
| 857 | if used := w.m.ops[id]; len(used) > 0 && w.rng.Intn(5) < 2 { |
| 858 | op, kind = used[w.rng.Intn(len(used))], "repeated" |
| 859 | } else { |
| 860 | w.m.nextOp++ |
| 861 | op = fmt.Sprintf("op-%d", w.m.nextOp) |
| 862 | w.m.ops[id] = append(w.m.ops[id], op) |
| 863 | } |
| 864 | lost := w.maybeLost(isolatedjob.OpResume, 3) |
| 865 | epoch, err := w.resume(id, op) |
| 866 | if err != nil { |
| 867 | w.follow, w.short = "time advance", true |
| 868 | } |
| 869 | return fmt.Sprintf("resume %s operation %s (%s)%s -> epoch %d %s", id, op, kind, lost, epoch, errText(err)) |
| 870 | } |
| 871 | |
| 872 | // closePause records that the pause of attempt ended in a newly committed |
| 873 | // resume. |
| 874 | func (w *simWorld) closePause(id string) { |
| 875 | if p := w.m.pause[id]; p != nil { |
| 876 | p.open, p.acked = false, false |
| 877 | } |
| 878 | } |
| 879 | |
| 880 | func (w *simWorld) opPlant() string { |
| 881 | w.m.nextOrphan++ |
| 882 | ref := w.run.plant(fmt.Sprintf("orphan-%d", w.m.nextOrphan)) |
| 883 | return fmt.Sprintf("planted orphan %s", ref) |
| 884 | } |
| 885 | |
| 886 | func (w *simWorld) opStop() string { |
| 887 | id := w.pickJob() |
| 888 | if id == "" { |
| 889 | return "no job to stop" |
| 890 | } |
| 891 | lost := w.maybeLost(isolatedjob.OpStop, 5) |
| 892 | p, err := w.c.Stop(w.ctx, simActor, instKey, id, "simulation stop") |
| 893 | return fmt.Sprintf("stop %s%s -> proof %+v %s", id, lost, p, errText(err)) |
| 894 | } |
| 895 | |
| 896 | // vmsIn returns the fake's VMs whose state passes keep, in launch order. |
| 897 | func (w *simWorld) vmsIn(keep func(isolatedjob.State) bool) []isolatedjob.Ref { |
| 898 | var out []isolatedjob.Ref |
| 899 | for _, vm := range w.snap.vms { |
| 900 | if keep(vm.State) { |
| 901 | out = append(out, vm.Ref) |
| 902 | } |
| 903 | } |
| 904 | return out |
| 905 | } |
| 906 | |
| 907 | func (w *simWorld) opEnd() string { |
| 908 | refs := w.vmsIn(func(s isolatedjob.State) bool { return s.Live() && s != isolatedjob.StateStopping }) |
| 909 | if len(refs) == 0 { |
| 910 | return "no live VM" |
| 911 | } |
| 912 | ref := refs[w.rng.Intn(len(refs))] |
| 913 | w.run.end(ref) // the provider's own doing: no controller call |
| 914 | return fmt.Sprintf("%s ends by itself", ref) |
| 915 | } |
| 916 | |
| 917 | func (w *simWorld) opVanish() string { |
| 918 | refs := w.vmsIn(isolatedjob.State.Terminal) |
| 919 | if len(refs) == 0 { |
| 920 | return "no stopped VM" |
| 921 | } |
| 922 | ref := refs[w.rng.Intn(len(refs))] |
| 923 | w.fake.Vanish(ref) |
| 924 | return fmt.Sprintf("the provider forgets %s", ref) |
| 925 | } |
| 926 | |
| 927 | func (w *simWorld) opWall() string { |
| 928 | d := time.Duration(w.rng.Int63n(int64(6*time.Hour))) - 3*time.Hour |
| 929 | w.clk.SetWall(w.clk.Wall().Add(d)) |
| 930 | return fmt.Sprintf("wall clock moves %v", d) |
| 931 | } |
| 932 | |
| 933 | func (w *simWorld) opAdvance() string { |
| 934 | var d time.Duration |
| 935 | short := w.short // waiting for the VM to settle after a suspend or resume |
| 936 | w.short = false |
| 937 | switch n := w.rng.Intn(20); { |
| 938 | case n < 10 || short: |
| 939 | d = time.Duration(1+w.rng.Intn(60)) * time.Second |
| 940 | case n < 19: |
| 941 | d = time.Duration(61+w.rng.Intn(540)) * time.Second |
| 942 | default: |
| 943 | d = time.Duration(901+w.rng.Intn(9*3600-900)) * time.Second |
| 944 | } |
| 945 | out := fmt.Sprintf("advance %v: %s", d, w.advance(d)) |
| 946 | if short && w.bad == nil && w.anyJob(simToResume) { |
| 947 | w.follow = "resume" |
| 948 | } |
| 949 | return out |
| 950 | } |
| 951 | |
| 952 | // simScenarios are directed sequences with fixed choices, run before the |
| 953 | // random seeds under the same invariants. Each crash after a lost reply |
| 954 | // first confirms the provider's effect and the unresolved store state, then |
| 955 | // reopens before anything reconciles; the others reach, every run, the |
| 956 | // states the thinnest random coverage depends on. |
| 957 | var simScenarios = []struct { |
| 958 | name string |
| 959 | run func(*simWorld) |
| 960 | }{ |
| 961 | {"lost launch reply, crash, reconcile", (*simWorld).scLostLaunch}, |
| 962 | {"lost stop reply, crash, reconcile", (*simWorld).scLostStop}, |
| 963 | {"lost resume reply, crash, reconcile", (*simWorld).scLostResume}, |
| 964 | {"throttled resume while the VM stays suspended", (*simWorld).scThrottledResume}, |
| 965 | {"a waiting intent's VM outlives its orphan grace", (*simWorld).scOrphanRecheck}, |
| 966 | {"future generations are refused", (*simWorld).scFutureGen}, |
| 967 | } |
| 968 | |
| 969 | // launchFor launches a new attempt with lifetime life, its reply lost when |
| 970 | // lost, and returns its ID and Launch's error. |
| 971 | func (w *simWorld) launchFor(life time.Duration, lost bool) (string, error) { |
| 972 | q := w.newRequest("") |
| 973 | q.MaxLifetime = life |
| 974 | w.m.req[q.AttemptID] = q |
| 975 | if lost { |
| 976 | w.run.queue(isolatedjob.OpLaunch, isolatedjob.FaultLostReply) |
| 977 | } |
| 978 | _, err := w.c.Launch(w.ctx, simActor, instKey, q) |
| 979 | return q.AttemptID, err |
| 980 | } |
| 981 | |
| 982 | // vmsOf returns the VMs of attempt id in the latest snapshot. |
| 983 | func (w *simWorld) vmsOf(id string) []isolatedjob.Job { |
| 984 | w.run.mu.Lock() |
| 985 | defer w.run.mu.Unlock() |
| 986 | var out []isolatedjob.Job |
| 987 | for _, vm := range w.snap.vms { |
| 988 | if w.run.ownerLocked(w.snap, vm.Ref) == id { |
| 989 | out = append(out, vm) |
| 990 | } |
| 991 | } |
| 992 | return out |
| 993 | } |
| 994 | |
| 995 | // oneVM reports whether attempt id has exactly one VM, in state st. |
| 996 | func (w *simWorld) oneVM(id string, st isolatedjob.State) bool { |
| 997 | vms := w.vmsOf(id) |
| 998 | return w.want(len(vms) == 1 && vms[0].State == st, "%s has VMs %+v, want one %s", id, vms, st) |
| 999 | } |
| 1000 | |
| 1001 | func (w *simWorld) try(what string, run func() error, ok func(error) bool) bool { |
| 1002 | var err error |
| 1003 | return w.do(what, func() string { err = run(); return errText(err) }) && w.want(ok(err), "%s: unexpected result %v", what, err) |
| 1004 | } |
| 1005 | |
| 1006 | func (w *simWorld) wait(d time.Duration) bool { |
| 1007 | return w.do(fmt.Sprintf("advance %v", d), func() string { return w.advance(d) }) |
| 1008 | } |
| 1009 | |
| 1010 | func simOK(err error) bool { return err == nil } |
| 1011 | |
| 1012 | // running launches an attempt with lifetime life and waits for it to run. |
| 1013 | func (w *simWorld) running(life time.Duration) (string, bool) { |
| 1014 | var id string |
| 1015 | ok := w.try("launch", func() (err error) { id, err = w.launchFor(life, false); return err }, simOK) && |
| 1016 | w.wait(ReapInterval) && w.want(w.snap.jobs[id].state == JobRunning, "%s is %s, want running", id, w.snap.jobs[id].state) |
| 1017 | return id, ok |
| 1018 | } |
| 1019 | |
| 1020 | // suspended runs an attempt through drain, acknowledgement and suspend |
| 1021 | // until the store holds it suspended. |
| 1022 | func (w *simWorld) suspended() (string, bool) { |
| 1023 | id, ok := w.running(time.Hour) |
| 1024 | var gen int64 |
| 1025 | ok = ok && w.try("drain", func() (err error) { gen, err = w.drain(id); return err }, simOK) && |
| 1026 | w.try("acknowledge", func() error { return w.ack(id, gen) }, simOK) && |
| 1027 | w.try("suspend", func() error { return w.suspend(id, gen) }, simOK) && |
| 1028 | w.wait(ReapInterval) && w.want(w.snap.jobs[id].state == JobSuspended, "%s is %s, want suspended", id, w.snap.jobs[id].state) |
| 1029 | return id, ok |
| 1030 | } |
| 1031 | |
| 1032 | func (w *simWorld) scLostLaunch() { |
| 1033 | var id string |
| 1034 | _ = w.try("launch with its reply lost", func() (err error) { id, err = w.launchFor(time.Hour, true); return err }, |
| 1035 | func(err error) bool { return errors.Is(err, ErrProviderLaunch) }) && |
| 1036 | w.oneVM(id, isolatedjob.StateStarting) && |
| 1037 | w.want(w.snap.jobs[id].state == JobWaiting && w.snap.jobs[id].ref == "" && w.snap.jobs[id].dispatched, |
| 1038 | "%s after the lost reply: %+v, want a dispatched waiting intent with no Ref", id, w.snap.jobs[id]) && |
| 1039 | w.do("crash before any reconciliation", func() string { return w.crash(0, 0, false) }) && |
| 1040 | w.wait(2*ReapInterval) && w.oneVM(id, isolatedjob.StateRunning) && |
| 1041 | w.want(w.snap.jobs[id].ref == w.vmsOf(id)[0].Ref, "%s holds Ref %q after the replays", id, w.snap.jobs[id].ref) && |
| 1042 | w.wait(time.Hour) && w.want(w.snap.jobs[id].proof != "", "%s has no proof after its stop time", id) |
| 1043 | } |
| 1044 | |
| 1045 | func (w *simWorld) scLostStop() { |
| 1046 | id, ok := w.running(time.Hour) |
| 1047 | _ = ok && w.try("stop with its reply lost", func() error { |
| 1048 | w.run.queue(isolatedjob.OpStop, isolatedjob.FaultLostReply) |
| 1049 | _, err := w.c.Stop(w.ctx, simActor, instKey, id, "scenario stop") |
| 1050 | return err |
| 1051 | }, func(err error) bool { return errors.Is(err, isolatedjob.ErrLostReply) }) && |
| 1052 | w.oneVM(id, isolatedjob.StateStopping) && |
| 1053 | w.want(w.snap.jobs[id].stopRequested && w.snap.jobs[id].proof == "", "%s after the lost stop: %+v", id, w.snap.jobs[id]) && |
| 1054 | w.do("crash before any reconciliation", func() string { return w.crash(0, 0, false) }) && |
| 1055 | w.wait(2*ReapInterval) && w.want(w.snap.jobs[id].proof != "", "%s has no proof after the reopen", id) |
| 1056 | } |
| 1057 | |
| 1058 | func (w *simWorld) scLostResume() { |
| 1059 | id, ok := w.suspended() |
| 1060 | var epoch int64 |
| 1061 | _ = ok && w.try("resume op-1 with its reply lost", func() (err error) { |
| 1062 | w.run.queue(isolatedjob.OpResume, isolatedjob.FaultLostReply) |
| 1063 | _, err = w.resume(id, "op-1") |
| 1064 | return err |
| 1065 | }, func(err error) bool { return errors.Is(err, ErrResumePending) }) && |
| 1066 | w.do("the provider finishes the resume", func() string { w.fake.Tick(); return "tick" }) && |
| 1067 | w.oneVM(id, isolatedjob.StateRunning) && |
| 1068 | w.want(w.snap.jobs[id].state == JobResuming && w.snap.jobs[id].epoch == 0 && len(w.snap.ops) == 1 && w.snap.ops[0].status == opPending, |
| 1069 | "%s after the lost resume: %+v, operations %+v", id, w.snap.jobs[id], w.snap.ops) && |
| 1070 | w.do("crash before any reconciliation", func() string { return w.crash(0, 0, false) }) && |
| 1071 | w.wait(2*ReapInterval) && w.want(w.snap.jobs[id].epoch == 1, "%s epoch %d after recovery, want 1", id, w.snap.jobs[id].epoch) && |
| 1072 | w.try("resume op-1 again", func() (err error) { epoch, err = w.resume(id, "op-1"); return err }, simOK) && |
| 1073 | w.want(epoch == 1, "the repeated op-1 returned epoch %d, want 1", epoch) |
| 1074 | } |
| 1075 | |
| 1076 | func (w *simWorld) scThrottledResume() { |
| 1077 | id, ok := w.suspended() |
| 1078 | _ = ok && w.try("resume op-1, the provider call throttled", func() (err error) { |
| 1079 | w.run.queue(isolatedjob.OpResume, isolatedjob.FaultThrottle) |
| 1080 | _, err = w.resume(id, "op-1") |
| 1081 | return err |
| 1082 | }, func(err error) bool { return errors.Is(err, ErrResumePending) }) && |
| 1083 | w.oneVM(id, isolatedjob.StateSuspended) && |
| 1084 | w.want(w.snap.jobs[id].epoch == 0, "%s committed epoch %d with no provider resume", id, w.snap.jobs[id].epoch) && |
| 1085 | w.wait(3*ReapInterval) && w.want(w.snap.jobs[id].epoch == 1, "%s epoch %d once Refresh resumed it, want 1", id, w.snap.jobs[id].epoch) |
| 1086 | } |
| 1087 | |
| 1088 | func (w *simWorld) scOrphanRecheck() { |
| 1089 | var id string |
| 1090 | _ = w.try("launch with its reply lost", func() (err error) { id, err = w.launchFor(2*time.Hour, true); return err }, |
| 1091 | func(err error) bool { return errors.Is(err, ErrProviderLaunch) }) && |
| 1092 | w.do("the network audit fails from now, for 15 passes", func() string { |
| 1093 | w.auditBad = 15 |
| 1094 | w.fake.SetAudit(isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true}, nil) |
| 1095 | return errText(w.c.RunAudit(w.ctx)) // recorded now, so no replay can claim the VM |
| 1096 | }) && |
| 1097 | w.wait(12*time.Minute) && w.oneVM(id, isolatedjob.StateRunning) && |
| 1098 | w.want(w.snap.jobs[id].state == JobWaiting, "%s is %s, want still waiting", id, w.snap.jobs[id].state) && |
| 1099 | w.wait(6*time.Minute) && w.want(w.snap.jobs[id].ref == w.vmsOf(id)[0].Ref, "%s did not claim its VM once audits passed", id) |
| 1100 | } |
| 1101 | |
| 1102 | func (w *simWorld) scFutureGen() { |
| 1103 | id, ok := w.running(time.Hour) |
| 1104 | var gen int64 |
| 1105 | refused := func(err error) bool { return errors.Is(err, ErrGenerationCancelled) } |
| 1106 | _ = ok && w.try("drain", func() (err error) { gen, err = w.drain(id); return err }, simOK) && |
| 1107 | w.try("acknowledge the next generation", func() error { return w.ack(id, gen+1) }, refused) && |
| 1108 | w.try("acknowledge the current generation", func() error { return w.ack(id, gen) }, simOK) && |
| 1109 | w.try("suspend the next generation", func() error { return w.suspend(id, gen+1) }, refused) && |
| 1110 | w.try("suspend the current generation", func() error { return w.suspend(id, gen) }, simOK) |
| 1111 | } |
| 1112 | |
| 1113 | func viewText(v JobView, err error) string { |
| 1114 | if err != nil { |
| 1115 | return errText(err) |
| 1116 | } |
| 1117 | return fmt.Sprintf("%s %s", v.State, v.VMRef) |
| 1118 | } |
| 1119 | |
| 1120 | func faultNote(f isolatedjob.Fault) string { |
| 1121 | if f == "" { |
| 1122 | return "" |
| 1123 | } |
| 1124 | return " [" + string(f) + "]" |
| 1125 | } |
| 1126 | |
| 1127 | func errText(err error) string { |
| 1128 | if err == nil { |
| 1129 | return "ok" |
| 1130 | } |
| 1131 | s := strings.ReplaceAll(err.Error(), "\n", " | ") |
| 1132 | if len(s) > 200 { |
| 1133 | s = s[:200] + "..." |
| 1134 | } |
| 1135 | return "error: " + s |
| 1136 | } |
| 1137 | |
| 1138 | func simDur(t T) time.Duration { return time.Duration(t) } |
| 1139 | |