package hostedctl import ( "context" "errors" "fmt" "slices" "sync" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/isolatedjob" "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" ) // slowRunner wraps the fake provider. Each Get and List moves the fake // clock on by getDelay or listDelay while it runs, so the controller time // before a call and after it differ. List also returns extra, as VMs the // provider holds that no job knows. type slowRunner struct { *isolatedjob.Fake clk *isolatedjobtest.FakeClock getDelay, listDelay time.Duration mu sync.Mutex extra []isolatedjob.Job } func (r *slowRunner) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { r.clk.AdvanceMono(r.getDelay) return r.Fake.Get(ctx, ref) } func (r *slowRunner) List(ctx context.Context) ([]isolatedjob.Job, error) { r.clk.AdvanceMono(r.listDelay) jobs, err := r.Fake.List(ctx) if err != nil { return nil, err } r.mu.Lock() defer r.mu.Unlock() return append(jobs, r.extra...), nil } func (r *slowRunner) setExtra(jobs ...isolatedjob.Job) { r.mu.Lock() defer r.mu.Unlock() r.extra = jobs } // gatedGet wraps the fake provider's Get. Call n (counting from 1) answers // what answer(n) gives. Call 1 closes entered and waits for release, so a // test can start a second caller while the first is inside the provider // call. type gatedGet struct { *isolatedjob.Fake answer func(ctx context.Context, n int, ref isolatedjob.Ref) (isolatedjob.Job, error) mu sync.Mutex n int entered chan struct{} release chan struct{} } func newGatedGet(f *isolatedjob.Fake, answer func(context.Context, int, isolatedjob.Ref) (isolatedjob.Job, error)) *gatedGet { return &gatedGet{Fake: f, answer: answer, entered: make(chan struct{}), release: make(chan struct{})} } func (g *gatedGet) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { g.mu.Lock() g.n++ n := g.n g.mu.Unlock() if n == 1 { close(g.entered) <-g.release } return g.answer(ctx, n, ref) } // watchdog bounds every wait in the concurrency tests. A healthy run never // reaches it. const watchdog = 5 * time.Second // lockWaits makes e's controller report, on the returned channel, each // time a caller has to wait for an attempt lock. func lockWaits(e *launchEnv) chan string { waits := make(chan string, 16) e.c.attempts.waiting = func(id string) { waits <- id } return waits } // overlap runs two Refresh passes on e: the second starts while the first // is inside its Get (held by gg). The second then either waits for the // attempt lock, seen through the lock's waiting hook, or, when nothing // serialises the two, runs to its end; only then is the first let go. func overlap(t *testing.T, e *launchEnv, gg *gatedGet) [2]error { t.Helper() waits := lockWaits(e) first, second := make(chan error, 1), make(chan error, 1) go func() { first <- e.c.Refresh(e.ctx) }() select { case <-gg.entered: case <-time.After(watchdog): t.Fatal("the first Refresh never reached the provider") } go func() { second <- e.c.Refresh(e.ctx) }() var out [2]error secondDone := false select { case <-waits: // serialised: the second waits for the attempt case out[1] = <-second: secondDone = true case <-time.After(watchdog): t.Fatal("the second Refresh neither waited for the attempt nor finished") } close(gg.release) for i, ch := range []chan error{first, second} { if i == 1 && secondDone { break } select { case out[i] = <-ch: case <-time.After(watchdog): t.Fatalf("Refresh %d did not finish", i) } } return out } func notFoundAnswer(ref isolatedjob.Ref) (isolatedjob.Job, error) { return isolatedjob.Job{}, fmt.Errorf("%w: %s (stale read)", isolatedjob.ErrNotFound, ref) } // blockLaunch wraps the fake provider's Launch. Once armed, the next // Launch signals entered and waits for release before reaching the fake. type blockLaunch struct { *isolatedjob.Fake armed atomic.Bool entered chan struct{} release chan struct{} } func (b *blockLaunch) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { if b.armed.CompareAndSwap(true, false) { close(b.entered) <-b.release } return b.Fake.Launch(ctx, s) } // TestStopWaitsForDispatch: a Stop that arrives while a launch dispatch is // between its gate check and the provider's answer waits for the answer // (R18), so proof for a job with no Ref can never be issued while a // dispatched launch may still create its VM. func TestStopWaitsForDispatch(t *testing.T) { t.Parallel() type result struct { err error } run := func(t *testing.T, viaReplay bool, fault isolatedjob.Fault) (*launchEnv, chan result) { e := newLaunchEnv(t) bl := &blockLaunch{Fake: e.fake, entered: make(chan struct{}), release: make(chan struct{})} e.run = bl e.newController() e.audit() waits := lockWaits(e) launched := make(chan error, 1) if viaReplay { e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil { t.Fatalf("throttled Launch = %v", err) } bl.armed.Store(true) go func() { launched <- e.c.Replay(e.ctx) }() } else { bl.armed.Store(true) go func() { _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) launched <- err }() } <-bl.entered // past every gate; the provider call is in flight dispatchedAt := e.store.Clock().Now() if s := e.stopCols("att-1"); !s.lastDispatch.Valid || T(s.lastDispatch.Int64) != dispatchedAt { t.Fatalf("last_dispatch_t during the provider call = %v, want %d", s.lastDispatch, dispatchedAt) } if fault != "" { e.fake.Inject(isolatedjob.OpLaunch, fault) } stopped := make(chan result, 1) go func() { _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done") stopped <- result{err} }() select { case <-waits: // Stop waits for the attempt, as it must case r := <-stopped: t.Fatalf("Stop returned (%v) while the launch call was in flight; it must wait for the answer", r.err) case <-time.After(watchdog): t.Fatal("Stop neither waited for the attempt nor returned") } // However long the call takes, nothing proves the attempt stopped. // Refresh has nothing to do for att-1 yet; if a broken lock let the // Stop through, it waits for the attempt instead, which must not // prove anything either. e.clk.AdvanceMono(3 * time.Minute) refreshed := make(chan error, 1) go func() { refreshed <- e.c.Refresh(e.ctx) }() done := false select { case <-refreshed: done = true case <-waits: case <-time.After(watchdog): t.Fatal("Refresh neither finished nor waited for the attempt") } close(bl.release) if err := <-launched; viaReplay && err != nil && fault == "" { t.Fatalf("Replay = %v", err) } if !done { <-refreshed } return e, stopped } t.Run("replay paused after its gate check, launch reply lost", func(t *testing.T) { e, stopped := run(t, true, isolatedjob.FaultLostReply) if r := <-stopped; !errors.Is(r.err, ErrStopPending) { t.Fatalf("Stop after the dispatch settled = %v, want ErrStopPending", r.err) } e.clk.AdvanceMono(3 * time.Minute) e.refresh() if s := e.stopCols("att-1"); s.proof.Valid && e.fake.LiveByAttempt()["att-1"] > 0 { t.Fatalf("proof %s while the dispatched launch's VM is live", s.proof.String) } if e.fake.LiveByAttempt()["att-1"] != 1 { t.Fatal("the lost launch made no VM; the test needs one") } }) t.Run("delayed provider launch", func(t *testing.T) { e, stopped := run(t, false, "") if r := <-stopped; !errors.Is(r.err, ErrStopPending) { t.Fatalf("Stop after the launch answered = %v, want ErrStopPending (the VM is stopping)", r.err) } s := e.stopCols("att-1") if s.proof.Valid { t.Fatalf("proof %s for a VM that is only stopping", s.proof.String) } if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.VMRef == "" { t.Fatalf("Get after the delayed launch = (%+v, %v), want the job to hold its VM ref", v, err) } }) } // TestStopIntentWithoutRefFences: Ref-less proof waits ReflessProofDelay // after the last dispatch as well as the stop request (R19), and the List // that proves it is judged by when it began and by every VM it shows that // is not terminal. func TestStopIntentWithoutRefFences(t *testing.T) { t.Parallel() stopIntent := func(t *testing.T, e *launchEnv) T { t.Helper() e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil { t.Fatalf("throttled Launch = %v", err) } asked := e.store.Clock().Now() if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err) } return asked } t.Run("proof waits past the last dispatch", func(t *testing.T) { e := newLaunchEnv(t) e.clk.AdvanceMono(time.Minute) at := e.store.Clock().Now() asked := stopIntent(t, e) if s := e.stopCols("att-1"); !s.lastDispatch.Valid || T(s.lastDispatch.Int64) != at { t.Fatalf("last_dispatch_t after a throttled launch = %v, want %d", s.lastDispatch, at) } // A dispatch that crossed the stop request (a crash mid-call, or a // path without the attempt lock) leaves a later mark. dispatched := asked + T(time.Minute) e.exec(`UPDATE jobs SET last_dispatch_t = ? WHERE attempt_id = 'att-1'`, int64(dispatched)) e.clk.AdvanceMono(ReflessProofDelay + 30*time.Second) e.refresh() if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s from a list begun %v after the last dispatch", s.proof.String, time.Duration(e.store.Clock().Now()-dispatched)) } e.clk.AdvanceMono(30 * time.Second) e.refresh() e.wireProof("att-1") }) t.Run("slow list is judged by its start", func(t *testing.T) { e := newLaunchEnv(t) slow := &slowRunner{Fake: e.fake, clk: e.clk, listDelay: 30 * time.Second} e.run = slow e.newController() e.audit() asked := stopIntent(t, e) e.clk.AdvanceMono(ReflessProofDelay - 20*time.Second) e.refresh() // begins 20 s early, ends 10 s late if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s from a list begun %v after the request", s.proof.String, ReflessProofDelay-20*time.Second) } e.refresh() // begins 10 s late if w := e.wireProof("att-1"); T(w.ObservedAt) != asked+T(ReflessProofDelay+40*time.Second) { t.Fatalf("proof observed at %d, want the end of the second list, %d", w.ObservedAt, asked+T(ReflessProofDelay+40*time.Second)) } }) t.Run("an unknown-state VM outside the table blocks proof", func(t *testing.T) { e := newLaunchEnv(t) slow := &slowRunner{Fake: e.fake, clk: e.clk} slow.setExtra(isolatedjob.Job{Ref: "vm-ghost", State: isolatedjob.StateUnknown}) e.run = slow e.newController() e.audit() stopIntent(t, e) e.clk.AdvanceMono(ReflessProofDelay + time.Minute) e.refresh() if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s while the list shows an unlinked VM in an unknown state", s.proof.String) } slow.setExtra(isolatedjob.Job{Ref: "vm-ghost", State: isolatedjob.StateStopped}) e.refresh() e.wireProof("att-1") }) } // TestStopNotFoundSlowGet: the NotFoundConfirm gap runs from the end of the // first not-found Get to the start of the second, so slow calls cannot // shrink it. func TestStopNotFoundSlowGet(t *testing.T) { t.Parallel() e := newLaunchEnv(t) slow := &slowRunner{Fake: e.fake, clk: e.clk, getDelay: 10 * time.Second} e.run = slow e.newController() e.audit() ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.fake.Vanish(ref) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on the first not-found = %v, want ErrStopPending", err) } first := T(e.stopCols("att-1").notFoundSince.Int64) if first != e.store.Clock().Now() { t.Fatalf("notfound_since_t = %d, want the end of the Get, %d", first, e.store.Clock().Now()) } e.clk.AdvanceMono(NotFoundConfirm - 5*time.Second) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on a not-found Get begun %v after the first ended = %v, want ErrStopPending", NotFoundConfirm-5*time.Second, err) } e.clk.AdvanceMono(time.Second) // the next Get begins NotFoundConfirm + 6 s after the first ended if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.VMRef != ref { t.Fatalf("Stop on a confirming not-found = (%+v, %v), want proof", p, err) } } // TestStopNotFoundRacesLiveRead: a not-found that a Refresh read before a // live read by another Refresh must not be saved after it (R18). func TestStopNotFoundRacesLiveRead(t *testing.T) { t.Parallel() e := newLaunchEnv(t) e.launchWith("att-1", 2*time.Hour) e.fake.Tick() gg := newGatedGet(e.fake, func(ctx context.Context, n int, ref isolatedjob.Ref) (isolatedjob.Job, error) { if n == 1 { return notFoundAnswer(ref) } return e.fake.Get(ctx, ref) }) e.run = gg e.newController() for i, err := range overlap(t, e, gg) { if err != nil { t.Fatalf("Refresh %d = %v", i, err) } } if s := e.stopCols("att-1"); s.notFoundSince.Valid || s.state != JobRunning { t.Fatalf("after a not-found and a live read: state %q notfound_since_t %v; want running and no not-found held", s.state, s.notFoundSince) } } // TestStopNotFoundClearedBeforeRestartStop: a live read clears a held // not-found even when the restart handling then stops the job and returns. func TestStopNotFoundClearedBeforeRestartStop(t *testing.T) { t.Parallel() e := newLaunchEnv(t) flaky := ¬FoundOnce{Fake: e.fake} e.run = flaky e.newController() e.audit() e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.down() e.clk.AdvanceMono(time.Minute) e.up() e.clk.AdvanceMono(time.Second) // The creator asks for a stop; the VM is stopping. Then one not-found. if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop = %v, want ErrStopPending", err) } e.clk.AdvanceMono(time.Second) flaky.n = 1 e.refresh() if s := e.stopCols("att-1"); !s.notFoundSince.Valid { t.Fatal("no not-found held after a not-found read") } // A live read with no age: the job is stopped as elapsed_unknown, and the // Get inside that stop fails, so only the first live read can clear it. e.clk.AdvanceMono(30 * time.Second) e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultThrottle) _ = e.c.Refresh(e.ctx) if s := e.stopCols("att-1"); s.notFoundSince.Valid { t.Fatalf("notfound_since_t %d kept after a live read", s.notFoundSince.Int64) } e.clk.AdvanceMono(40 * time.Second) flaky.n = 1 e.refresh() if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s from not-founds with a live read between", s.proof.String) } } // TestRestartOverlappingRefresh: two Refresh passes at once settle a // pre-restart job once (R18): never both re-based and stopped. A second // restart settles it again. func TestRestartOverlappingRefresh(t *testing.T) { t.Parallel() e := newLaunchEnv(t) e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.down() e.clk.AdvanceMono(10 * time.Minute) e.clk.SetWall(testWall.Add(10 * time.Minute)) gg := newGatedGet(e.fake, func(ctx context.Context, n int, ref isolatedjob.Ref) (isolatedjob.Job, error) { j, err := e.fake.Get(ctx, ref) if n >= 2 { j.ProviderAge, j.AgeKnown = 0, false } return j, err }) e.run = gg e.up() e.clk.AdvanceMono(time.Second) for i, err := range overlap(t, e, gg) { if err != nil { t.Fatalf("Refresh %d = %v", i, err) } } rebased := e.hasAudit("", "att-1", actionRestartRebased, "") stopped := e.stopCols("att-1").requested.Valid if rebased == stopped { t.Fatalf("after two overlapping passes: re-based %v, stopped %v; want exactly one", rebased, stopped) } // A second restart: the new process settles the job again; with no age // it is stopped. if !stopped { e.run = e.fake e.down() e.clk.AdvanceMono(time.Minute) e.up() e.clk.AdvanceMono(time.Second) e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) e.refresh() if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown { t.Fatalf("after a second restart with no age: reason %v, want %s", s.reason, reasonElapsedUnknown) } } } // TestRestartRetriesFailedGet: a pre-restart job whose Get fails is retried; // after RestartGetTries failed passes in a row it is stopped as // elapsed_unknown, the stop request saved first (R20). func TestRestartRetriesFailedGet(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.down() e.clk.AdvanceMono(10 * time.Minute) e.up() e.clk.AdvanceMono(time.Second) for pass := 1; pass <= RestartGetTries; pass++ { e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultThrottle) err := e.c.Refresh(e.ctx) if !errors.Is(err, isolatedjob.ErrThrottled) { t.Fatalf("pass %d: Refresh = %v, want the Get error", pass, err) } s := e.stopCols("att-1") if pass < RestartGetTries && (s.requested.Valid || len(e.fake.StopsIssued()) != 0) { t.Fatalf("pass %d: stopped after %d failed reads, want %d first", pass, pass, RestartGetTries) } if pass == RestartGetTries { if s.reason.String != reasonElapsedUnknown || !s.requested.Valid { t.Fatalf("pass %d: requested %v reason %v; want a stop for %s", pass, s.requested, s.reason, reasonElapsedUnknown) } if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref}) { t.Fatalf("provider stops = %v, want %s", got, ref) } } e.clk.AdvanceMono(time.Minute) } } // TestRestartWallJump: a forward wall jump across a restart with almost no // real downtime gives neither proof path any trusted time (R19). func TestRestartWallJump(t *testing.T) { t.Parallel() jump := func(e *launchEnv) { e.down() e.clk.AdvanceMono(time.Second) e.clk.SetWall(testWall.Add(10 * time.Minute)) e.up() e.clk.AdvanceMono(time.Second) } t.Run("not-found pair", func(t *testing.T) { e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.fake.Vanish(ref) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on the first not-found = %v, want ErrStopPending", err) } jump(e) now := e.store.Clock().Now() if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on a not-found after the wall jump = %v, want ErrStopPending: the first one is from before Open", err) } if s := e.stopCols("att-1"); T(s.notFoundSince.Int64) != now { t.Fatalf("notfound_since_t = %v, want it restarted at %d", s.notFoundSince, now) } e.clk.AdvanceMono(NotFoundConfirm) if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.VMRef != ref { t.Fatalf("Stop on a confirming not-found = (%+v, %v), want proof", p, err) } }) t.Run("not-found saved at the restored time", func(t *testing.T) { // With the wall clock behind the checkpoint, T restores to the // checkpoint, so a not-found saved just before the exit equals // OpenedAt. It is from before Open and does not count. e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.fake.Vanish(ref) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on the first not-found = %v, want ErrStopPending", err) } e.down() e.clk.SetWall(testWall.Add(-time.Hour)) e.up() if s := e.stopCols("att-1"); T(s.notFoundSince.Int64) != e.store.OpenedAt() { t.Fatalf("notfound_since_t %d, OpenedAt %d; the test needs them equal", s.notFoundSince.Int64, e.store.OpenedAt()) } e.clk.AdvanceMono(NotFoundConfirm + time.Second) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on a not-found paired with one saved at OpenedAt = %v, want ErrStopPending", err) } }) t.Run("ref-less list", func(t *testing.T) { e := newLaunchEnv(t) e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil { t.Fatalf("throttled Launch = %v", err) } if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop = %v, want ErrStopPending", err) } jump(e) e.refresh() if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s 1 s after a restart", s.proof.String) } e.clk.AdvanceMono(ReflessProofDelay) e.refresh() e.wireProof("att-1") }) } // TestRestartRetriesPendingStop: once the elapsed_unknown stop is asked // for, Refresh sends it again on every pass, even when Get keeps failing // and the job already counts as settled after the restart (review r2, // finding 4). func TestRestartRetriesPendingStop(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.down() e.clk.AdvanceMono(10 * time.Minute) e.up() e.clk.AdvanceMono(time.Second) for pass := 1; pass <= RestartGetTries; pass++ { e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultThrottle) if pass == RestartGetTries { e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle) // the first stop call fails } if err := e.c.Refresh(e.ctx); !errors.Is(err, isolatedjob.ErrThrottled) { t.Fatalf("pass %d: Refresh = %v, want the throttle", pass, err) } } if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown { t.Fatalf("after %d failed reads: reason %v, want %s requested", RestartGetTries, s.reason, reasonElapsedUnknown) } if e.fake.LiveByAttempt()["att-1"] != 1 || len(e.fake.StopsIssued()) != 1 { t.Fatalf("after a throttled stop: live %v, stops %v; want the VM running and one stop tried", e.fake.LiveByAttempt(), e.fake.StopsIssued()) } // Get still fails; Stop would now work. The next pass must send it. e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultThrottle) if err := e.c.Refresh(e.ctx); !errors.Is(err, isolatedjob.ErrThrottled) { t.Fatalf("pass %d: Refresh = %v, want the Get throttle", RestartGetTries+1, err) } if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref, ref}) { t.Fatalf("provider stops = %v, want the stop sent again", got) } vms, err := e.fake.List(e.ctx) if err != nil || len(vms) != 1 || vms[0].State != isolatedjob.StateStopping { t.Fatalf("VMs after the retried stop = (%v, %v), want one stopping", vms, err) } } // deadlineLaunch wraps the fake provider's Launch and records the context // deadline of each call. type deadlineLaunch struct { *isolatedjob.Fake mu sync.Mutex calls []launchDeadline } type launchDeadline struct { left time.Duration // time until the deadline, at the call set bool } func (d *deadlineLaunch) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { dl, ok := ctx.Deadline() d.mu.Lock() d.calls = append(d.calls, launchDeadline{left: time.Until(dl), set: ok}) d.mu.Unlock() return d.Fake.Launch(ctx, s) } // TestProviderLaunchTimeout: every provider Launch call, from Launch and // from Replay, carries a deadline at most ProviderLaunchTimeout (60 s) // away, derived from the caller's context (ruling R21). func TestProviderLaunchTimeout(t *testing.T) { t.Parallel() if ProviderLaunchTimeout != 60*time.Second || ProviderLaunchTimeout >= ReflessProofDelay { t.Fatalf("ProviderLaunchTimeout = %v, want 60s and under ReflessProofDelay %v", ProviderLaunchTimeout, ReflessProofDelay) } e := newLaunchEnv(t) dl := &deadlineLaunch{Fake: e.fake} e.run = dl e.newController() e.audit() long, cancel := context.WithTimeout(e.ctx, time.Hour) defer cancel() e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) if _, err := e.c.Launch(long, "inst-1", instKey, request("att-1")); err != nil { t.Fatalf("throttled Launch = %v", err) } if err := e.c.Replay(e.ctx); err != nil { // no deadline of its own t.Fatalf("Replay = %v", err) } short, cancel2 := context.WithTimeout(e.ctx, 5*time.Second) defer cancel2() if _, err := e.c.Launch(short, "inst-1", instKey, request("att-2")); err != nil { t.Fatalf("Launch = %v", err) } if len(dl.calls) != 3 { t.Fatalf("provider launches = %d, want 3", len(dl.calls)) } for i, c := range dl.calls { limit := ProviderLaunchTimeout if i == 2 { limit = 5 * time.Second // the caller's own, shorter deadline still holds } if !c.set || c.left <= 0 || c.left > limit { t.Fatalf("provider launch %d: deadline set %v, %v left; want one at most %v away", i, c.set, c.left, limit) } } } // deadlineAll wraps the fake provider and records, for every call other // than Launch, whether its context had a deadline at most // ProviderCallTimeout away. type deadlineAll struct { *isolatedjob.Fake mu sync.Mutex bad []string ops map[string]int } func (d *deadlineAll) note(ctx context.Context, op string) { dl, ok := ctx.Deadline() d.mu.Lock() defer d.mu.Unlock() d.ops[op]++ if left := time.Until(dl); !ok || left <= 0 || left > ProviderCallTimeout { d.bad = append(d.bad, fmt.Sprintf("%s: deadline set %v, %v left", op, ok, left)) } } func (d *deadlineAll) Get(ctx context.Context, r isolatedjob.Ref) (isolatedjob.Job, error) { d.note(ctx, "get") return d.Fake.Get(ctx, r) } func (d *deadlineAll) List(ctx context.Context) ([]isolatedjob.Job, error) { d.note(ctx, "list") return d.Fake.List(ctx) } func (d *deadlineAll) Stop(ctx context.Context, r isolatedjob.Ref, why string) error { d.note(ctx, "stop") return d.Fake.Stop(ctx, r, why) } func (d *deadlineAll) Suspend(ctx context.Context, r isolatedjob.Ref) error { d.note(ctx, "suspend") return d.Fake.Suspend(ctx, r) } func (d *deadlineAll) Resume(ctx context.Context, r isolatedjob.Ref) error { d.note(ctx, "resume") return d.Fake.Resume(ctx, r) } func (d *deadlineAll) AuditNetwork(ctx context.Context) (isolatedjob.NetworkAudit, error) { d.note(ctx, "audit") return d.Fake.AuditNetwork(ctx) } // TestProviderCallsBounded: every provider call other than Launch, the // network audit included, carries a deadline at most ProviderCallTimeout // away, though the caller's context has none (ruling R27). func TestProviderCallsBounded(t *testing.T) { t.Parallel() e := newLaunchEnv(t) d := &deadlineAll{Fake: e.fake, ops: map[string]int{}} c, err := New(e.cfg, Deps{Store: e.store, Runner: d, Auditor: d, Alerter: &recordingAlerter{}}) if err != nil { t.Fatal(err) } e.c = c e.audit() e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.reap() e.suspendJob() if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume = %v, want ErrResumePending", err) } if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop = %v, want ErrStopPending", err) } for _, op := range []string{"get", "list", "stop", "suspend", "resume", "audit"} { if d.ops[op] == 0 { t.Fatalf("no %s call made; calls %v", op, d.ops) } } if len(d.bad) > 0 { t.Fatalf("unbounded provider calls: %v", d.bad) } } // ctxBlock wraps the fake provider. A call to op closes entered and then // waits for its context to end. type ctxBlock struct { *isolatedjob.Fake op isolatedjob.Op entered chan struct{} } func (b *ctxBlock) block(ctx context.Context, op isolatedjob.Op) (bool, error) { if op != b.op { return false, nil } close(b.entered) <-ctx.Done() return true, ctx.Err() } func (b *ctxBlock) Suspend(ctx context.Context, r isolatedjob.Ref) error { if held, err := b.block(ctx, isolatedjob.OpSuspend); held { return err } return b.Fake.Suspend(ctx, r) } func (b *ctxBlock) Resume(ctx context.Context, r isolatedjob.Ref) error { if held, err := b.block(ctx, isolatedjob.OpResume); held { return err } return b.Fake.Resume(ctx, r) } // TestRefreshRecoveryCallsCancel: the suspend and the resume Refresh sends // again for a pause or resume it is finishing end when Refresh's context // is cancelled; they are not detached from it (B2-2, R27). func TestRefreshRecoveryCallsCancel(t *testing.T) { t.Parallel() for _, op := range []isolatedjob.Op{isolatedjob.OpSuspend, isolatedjob.OpResume} { e := runningJob(t) if op == isolatedjob.OpSuspend { // suspending, the VM still running g := e.drain() e.ack(g) e.fake.Inject(isolatedjob.OpSuspend, isolatedjob.FaultThrottle) if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", g); err == nil { t.Fatal("throttled Suspend = nil, want its error") } } else { // resuming, the VM still suspended e.suspendJob() e.fake.Inject(isolatedjob.OpResume, isolatedjob.FaultThrottle) if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("throttled Resume = %v, want ErrResumePending", err) } } b := &ctxBlock{Fake: e.fake, op: op, entered: make(chan struct{})} e.run = b e.newController() ctx, cancel := context.WithCancel(e.ctx) done := make(chan error, 1) go func() { done <- e.c.Refresh(ctx) }() select { case <-b.entered: case <-time.After(5 * time.Second): cancel() t.Fatalf("Refresh never sent the %s again", op) } cancel() select { case <-done: case <-time.After(5 * time.Second): t.Fatalf("Refresh still in its %s call 5 s after its context was cancelled", op) } } }