package hostedctl import ( "context" "database/sql" "errors" "fmt" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/isolatedjob" ) // reap runs one reaper pass and wants it to succeed. func (e *launchEnv) reap() ReapReport { e.t.Helper() r, err := e.c.Reap(e.ctx) if err != nil { e.t.Fatalf("Reap = (%+v, %v)", r, err) } return r } // alerts returns the alerts of kind the current controller has delivered. func (e *launchEnv) alerts(kind string) []Alert { e.t.Helper() var out []Alert for _, a := range e.c.alerter.(*recordingAlerter).got { if a.Kind == kind { out = append(out, a) } } return out } // unmatched reads unmatched_vms: each Ref with its first_seen_t. func (e *launchEnv) unmatched() map[isolatedjob.Ref]T { e.t.Helper() out := map[isolatedjob.Ref]T{} if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error { rows, err := tx.QueryContext(e.ctx, `SELECT vm_ref, first_seen_t FROM unmatched_vms`) if err != nil { return err } defer rows.Close() for rows.Next() { var ref string var at int64 if err := rows.Scan(&ref, &at); err != nil { return err } out[isolatedjob.Ref(ref)] = T(at) } return rows.Err() }); err != nil { e.t.Fatalf("read unmatched_vms = %v", err) } return out } // drainMark reads attempt's drain_marked_t. func (e *launchEnv) drainMark(attempt string) sql.NullInt64 { e.t.Helper() var m sql.NullInt64 if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(e.ctx, `SELECT drain_marked_t FROM jobs WHERE attempt_id = ?`, attempt).Scan(&m) }); err != nil { e.t.Fatalf("read drain_marked_t of %s = %v", attempt, err) } return m } // plant adds a running VM no job owns and returns its Ref. func (e *launchEnv) plant(name string) isolatedjob.Ref { return e.fake.Plant(isolatedjob.LaunchSpec{AttemptID: name}) } // lostLaunch launches attempt with its provider reply lost: the provider // makes the VM, the intent stays waiting with no Ref. It returns the VM's // Ref, read from the provider. func (e *launchEnv) lostLaunch(attempt string) isolatedjob.Ref { e.t.Helper() before := map[isolatedjob.Ref]bool{} vms, _ := e.fake.List(e.ctx) for _, vm := range vms { before[vm.Ref] = true } e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply) if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request(attempt)); !errors.Is(err, ErrProviderLaunch) { e.t.Fatalf("Launch(%s) with a lost reply = %v, want ErrProviderLaunch", attempt, err) } if j, _ := e.job(attempt); j.state != JobWaiting || j.ref.Valid { e.t.Fatalf("%s after a lost reply: state %q ref %v; want waiting with no ref", attempt, j.state, j.ref) } vms, _ = e.fake.List(e.ctx) for _, vm := range vms { if !before[vm.Ref] { return vm.Ref } } e.t.Fatalf("the lost launch of %s made no VM", attempt) return "" } // wantStops fails the test unless the provider stops so far are want. func (e *launchEnv) wantStops(want ...isolatedjob.Ref) { e.t.Helper() if got := e.fake.StopsIssued(); !slices.Equal(got, want) { e.t.Fatalf("provider stops = %v, want %v", got, want) } } // partialList wraps the provider. While armed, List returns everything the // provider holds together with ErrIncomplete, as an adapter that stopped // paging part way might: an incomplete answer may still carry VMs, and none // of them may be acted on. type partialList struct { *isolatedjob.Fake mu sync.Mutex armed int } func (p *partialList) incomplete(n int) { p.mu.Lock() defer p.mu.Unlock() p.armed += n } func (p *partialList) List(ctx context.Context) ([]isolatedjob.Job, error) { vms, err := p.Fake.List(ctx) p.mu.Lock() defer p.mu.Unlock() if err == nil && p.armed > 0 { p.armed-- return vms, fmt.Errorf("%w: test stopped paging", isolatedjob.ErrIncomplete) } return vms, err } func TestReapReplaysIntentFirst(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.lostLaunch("att-1") r := e.reap() if j, _ := e.job("att-1"); !j.ref.Valid || isolatedjob.Ref(j.ref.String) != ref || j.state != JobStarting { t.Fatalf("att-1 after a pass: ref %v state %q; want %s claimed by the replay, starting", j.ref, j.state, ref) } if r.Replayed != 1 || r.OrphansSeen != 0 || r.OrphansStopped != 0 { t.Fatalf("report %+v, want one replayed and no orphans", r) } if u := e.unmatched(); len(u) != 0 { t.Fatalf("unmatched_vms = %v; the intent's VM was taken for an orphan before the replay", u) } e.wantStops() } func TestReapStopsOrphanAfterTenMinutes(t *testing.T) { t.Parallel() e := newLaunchEnv(t) stray := e.plant("stray-1") r := e.reap() seen := e.store.Clock().Now() if r.OrphansSeen != 1 || r.OrphansStopped != 0 { t.Fatalf("first pass: report %+v, want one orphan seen and none stopped", r) } if u := e.unmatched(); len(u) != 1 || u[stray] != seen { t.Fatalf("unmatched_vms = %v, want %s first seen at %d", u, stray, seen) } if !e.hasAudit("", "", actionOrphanSeen, string(stray)) { t.Fatal("no orphan_seen audit row") } e.clk.AdvanceMono(OrphanGrace - time.Second) if r := e.reap(); r.OrphansSeen != 1 || r.OrphansStopped != 0 { t.Fatalf("at 9 min 59 s: report %+v, want the orphan seen and not stopped", r) } e.wantStops() e.clk.AdvanceMono(time.Second) if r := e.reap(); r.OrphansStopped != 1 { t.Fatalf("at 10 min: report %+v, want the orphan stopped", r) } e.wantStops(stray) if a := e.alerts(AlertOrphanStopped); len(a) != 1 { t.Fatalf("orphan_stopped alerts = %+v, want one", a) } if !e.hasAudit("", "", actionOrphanStopped, string(stray)) { t.Fatal("no orphan_stopped audit row") } // Stopping, then stopped: no second stop or alert, and the row goes once // the VM is terminal. if r := e.reap(); r.OrphansStopped != 0 { t.Fatalf("pass with the orphan stopping: report %+v, want no second stop", r) } e.fake.Tick() if r := e.reap(); r.OrphansSeen != 0 { t.Fatalf("pass with the orphan stopped: report %+v, want no orphan", r) } if u := e.unmatched(); len(u) != 0 { t.Fatalf("unmatched_vms after the orphan stopped = %v, want empty", u) } e.wantStops(stray) if a := e.alerts(AlertOrphanStopped); len(a) != 1 { t.Fatalf("orphan_stopped alerts = %+v, want still one", a) } } func TestReapRechecksOwnership(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.lostLaunch("att-1") stray := e.plant("stray-1") // Every pass's own replay is throttled, so the intent's VM stays // unlinked and looks like an orphan for the whole grace. Passes run each // minute, so each one's audit keeps the next replay's gate open. for i := 0; i <= 10; i++ { if i > 0 { e.clk.AdvanceMono(time.Minute) } e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) r := e.reap() if i < 10 { if r.OrphansSeen != 2 || r.OrphansStopped != 0 || r.Replayed != 0 { t.Fatalf("pass %d: report %+v, want two orphans seen, none stopped, none replayed", i, r) } continue } // At 10 min the recheck replays again (no throttle this time), and // the intent claims its VM before anything is stopped. if r.OrphansStopped != 1 || r.Replayed != 1 { t.Fatalf("pass at 10 min: report %+v, want one orphan stopped and one replayed", r) } } e.wantStops(stray) if j, _ := e.job("att-1"); isolatedjob.Ref(j.ref.String) != ref || j.state != JobStarting { t.Fatalf("att-1: ref %v state %q; want %s claimed, starting", j.ref, j.state, ref) } if e.hasAudit("", "", actionOrphanStopped, string(ref)) { t.Fatal("the claimed VM was audited as a stopped orphan") } e.reap() if u := e.unmatched(); len(u) != 1 || u[stray] != 0 { t.Fatalf("unmatched_vms after the claim = %v, want only %s, first seen at 0", u, stray) } } func TestReapStopsAbandonedIntentVM(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.lostLaunch("att-1") if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop of an intent with no ref = %v, want ErrStopPending", err) } if j, _ := e.job("att-1"); j.state != JobAbandoned { t.Fatalf("att-1 after Stop is %q, want abandoned", j.state) } if r := e.reap(); r.OrphansSeen != 1 { t.Fatalf("first pass: report %+v, want the abandoned intent's VM seen as an orphan", r) } e.clk.AdvanceMono(OrphanGrace) if r := e.reap(); r.OrphansStopped != 1 { t.Fatalf("at 10 min: report %+v, want the abandoned intent's VM stopped", r) } e.wantStops(ref) if s := e.stopCols("att-1"); s.proof.Valid { t.Fatal("att-1 has proof while its VM is still stopping") } // Once the VM is terminal, Refresh's complete List proves the intent. e.fake.Tick() e.reap() if w := e.wireProof("att-1"); w.VMRef != "" || w.State != isolatedjob.StateStopped { t.Fatalf("proof for att-1 = %+v, want stopped with no ref", w) } } func TestIncompleteListSkipsOrphansOnly(t *testing.T) { t.Parallel() e := newLaunchEnv(t) pl := &partialList{Fake: e.fake} e.run = pl e.newController() e.audit() e.launchWith("att-1", DrainBefore+OrphanGrace) // drain time at 10 min e.fake.Tick() stray := e.plant("stray-1") if r := e.reap(); r.OrphansSeen != 1 || r.Skipped { t.Fatalf("first pass: report %+v, want one orphan seen", r) } seen := e.unmatched()[stray] e.clk.AdvanceMono(OrphanGrace) pl.incomplete(1) r := e.reap() if !r.Skipped || r.OrphansStopped != 0 { t.Fatalf("pass with an incomplete list: report %+v, want orphans skipped", r) } e.wantStops() if u := e.unmatched(); len(u) != 1 || u[stray] != seen { t.Fatalf("unmatched_vms after an incomplete list = %v, want %s still first seen at %d", u, stray, seen) } // The other steps ran. if r.Drained != 1 || !e.drainMark("att-1").Valid { t.Fatalf("pass with an incomplete list: report %+v, drain mark %v; want att-1 drained", r, e.drainMark("att-1")) } if err := e.c.audit.check(e.store.Clock().Now()); err != nil { t.Fatalf("audit after the pass = %v, want a fresh pass", err) } e.clk.AdvanceMono(time.Minute) if r := e.reap(); r.Skipped || r.OrphansStopped != 1 { t.Fatalf("pass with a complete list: report %+v, want the orphan stopped", r) } e.wantStops(stray) } func TestDeadlineEnforcedDuringIncompleteLists(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.launchWith("att-1", time.Hour) e.fake.Tick() stopT := T(e.stopCols("att-1").stop) e.clk.AdvanceMono(time.Duration(stopT-e.store.Clock().Now()) - time.Minute) for i := range 3 { e.fake.Inject(isolatedjob.OpList, isolatedjob.FaultIncompleteList) r := e.reap() if !r.Skipped { t.Fatalf("pass %d: report %+v, want orphans skipped", i, r) } s := e.stopCols("att-1") switch i { case 0: if r.Stopped != 0 || s.requested.Valid { t.Fatalf("a minute before the stop time: report %+v requested %v; want no stop", r, s.requested) } e.wantStops() case 1: if r.Stopped != 1 || !s.requested.Valid || s.reason.String != reasonDeadline { t.Fatalf("at the stop time: report %+v requested %v reason %v; want a deadline stop", r, s.requested, s.reason) } e.wantStops(ref) case 2: if w := e.wireProof("att-1"); w.VMRef != ref || w.State != isolatedjob.StateStopped || s.state != JobStopped { t.Fatalf("after the stop: proof %+v state %q; want stopped %s", w, s.state, ref) } } e.clk.AdvanceMono(time.Minute) e.fake.Tick() } } // TestDeadlineStopBeforeSlowReplay: a pass that finds a job past its stop // time sends its stop before replaying intents, so a launch call that hangs // (up to ProviderLaunchTimeout each) never delays it (R26): a deadline stop // for a job with no stop request, and, for a stop already requested whose // provider call failed, the call again with its reason and request kept. func TestDeadlineStopBeforeSlowReplay(t *testing.T) { t.Parallel() for _, pending := range []bool{false, true} { e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) want, reason := []isolatedjob.Ref{ref}, reasonDeadline if pending { // a stop asked for whose provider call was throttled e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); err == nil { t.Fatal("throttled Stop = nil, want its error") } want, reason = []isolatedjob.Ref{ref, ref}, "done" } before := e.stopCols("att-1") e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) q := request("att-2") q.MaxLifetime = 8 * time.Hour if v, err := e.c.Launch(e.ctx, "inst-1", instKey, q); err != nil || v.State != JobWaiting { t.Fatalf("throttled Launch(att-2) = (%+v, %v), want a waiting intent", v, err) } hold := &holdRunner{Fake: e.fake, entered: make(chan struct{}), release: make(chan struct{})} e.run = hold e.newController() e.clk.AdvanceMono(2 * time.Hour) // att-1 is past its stop time; att-2 is not e.audit() done := make(chan error, 1) go func() { _, err := e.c.Reap(e.ctx); done <- err }() select { case <-hold.entered: case <-time.After(5 * time.Second): t.Fatal("the pass's replay never reached the provider") } stops := e.fake.StopsIssued() close(hold.release) if err := <-done; err != nil { t.Fatalf("pending %v: Reap = %v", pending, err) } if !slices.Equal(stops, want) { t.Fatalf("pending %v: provider stops while the replay's launch call hung = %v, want %v", pending, stops, want) } s := e.stopCols("att-1") if s.reason.String != reason || (pending && s.requested != before.requested) { t.Fatalf("pending %v: att-1 stop reason %v requested %v (was %v), want %s and the request kept", pending, s.reason, s.requested, before.requested, reason) } } } func TestReapDrainsThenStops(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.launchWith("att-1", time.Hour) e.fake.Tick() s := e.stopCols("att-1") to := func(at int64) { e.clk.AdvanceMono(time.Duration(T(at) - e.store.Clock().Now())) } to(s.drain - int64(time.Second)) if r := e.reap(); r.Drained != 0 || e.drainMark("att-1").Valid { t.Fatalf("a second before the drain time: report %+v mark %v; want no drain", r, e.drainMark("att-1")) } to(s.drain) if r := e.reap(); r.Drained != 1 || r.Stopped != 0 { t.Fatalf("at the drain time: report %+v, want one drained, none stopped", r) } if m := e.drainMark("att-1"); !m.Valid || m.Int64 != s.drain { t.Fatalf("drain_marked_t = %v, want %d", m, s.drain) } if !e.hasAudit("", "att-1", actionDeadlineDrain, "") { t.Fatal("no deadline_drain audit row") } // The mark is a notice only: no pause generation, no state change. if p := e.pauseCols("att-1"); p.state != JobRunning || p.gen != 0 { t.Fatalf("after the drain mark: state %q generation %d; want running, 0", p.state, p.gen) } if r := e.reap(); r.Drained != 0 { t.Fatalf("second pass past the drain time: report %+v, want no second drain", r) } to(s.stop - int64(time.Second)) if r := e.reap(); r.Stopped != 0 { t.Fatalf("a second before the stop time: report %+v, want no stop", r) } e.wantStops() to(s.stop) if r := e.reap(); r.Stopped != 1 { t.Fatalf("at the stop time: report %+v, want one stopped", r) } e.wantStops(ref) if c := e.stopCols("att-1"); !c.requested.Valid || c.reason.String != reasonDeadline { t.Fatalf("after the deadline stop: requested %v reason %v; want %s", c.requested, c.reason, reasonDeadline) } if !e.hasAudit("", "att-1", actionStopRequested, reasonDeadline) { t.Fatal("no stop_requested audit row by the controller") } if r := e.reap(); r.Stopped != 0 { t.Fatalf("pass after the deadline stop: report %+v, want no second request", r) } e.fake.Tick() e.reap() if w := e.wireProof("att-1"); w.VMRef != ref || w.State != isolatedjob.StateStopped { t.Fatalf("proof = %+v, want stopped %s", w, ref) } } func TestReaperUnderRollback(t *testing.T) { t.Parallel() e := newLaunchEnv(t) stray := e.plant("stray-1") e.reap() seen := e.unmatched()[stray] // Five minutes in, the wall clock goes back two hours. e.clk.AdvanceMono(5 * time.Minute) e.clk.SetWall(testWall.Add(-2 * time.Hour)) e.reap() e.clk.AdvanceMono(5*time.Minute - time.Second) if r := e.reap(); r.OrphansStopped != 0 { t.Fatalf("at 9 min 59 s of elapsed time: report %+v, want no stop", r) } e.clk.AdvanceMono(time.Second) if r := e.reap(); r.OrphansStopped != 1 { t.Fatalf("at 10 min of elapsed time, wall clock 2 h back: report %+v, want the orphan stopped", r) } e.wantStops(stray) if got := e.store.Clock().Now() - seen; got != T(OrphanGrace) { t.Fatalf("controller time since the sighting = %v, want %v", time.Duration(got), OrphanGrace) } } func TestOrphanGraceExpiresAfterRestart(t *testing.T) { t.Parallel() e := newLaunchEnv(t) stray := e.plant("stray-1") ref := e.lostLaunch("att-1") e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) // this pass's replay if r := e.reap(); r.OrphansSeen != 2 || r.Replayed != 0 { t.Fatalf("first pass: report %+v, want two orphans seen, none replayed", r) } seen := e.unmatched() // 30 min of real downtime; the wall clock says 2 min. e.clk.AdvanceMono(time.Minute) e.down() e.clk.AdvanceMono(30 * time.Minute) e.clk.SetWall(testWall.Add(2 * time.Minute)) e.up() e.clk.AdvanceMono(time.Second) if got := e.store.Clock().Now() - seen[stray]; got >= T(OrphanGrace) { t.Fatalf("controller time since the sighting = %v; the test needs it under the grace", time.Duration(got)) } // The new controller has no audit yet. Both sightings predate the // restart, so their grace has run out; the recheck still applies: the // waiting intent claims its VM, and only the stray is stopped. r := e.reap() if r.OrphansStopped != 1 || r.Replayed != 1 { t.Fatalf("first pass after the restart: report %+v, want one orphan stopped and one replayed", r) } e.wantStops(stray) if j, _ := e.job("att-1"); isolatedjob.Ref(j.ref.String) != ref { t.Fatalf("att-1 ref %v, want %s claimed by the recheck", j.ref, ref) } // A VM first seen after the restart gets the full grace. late := e.plant("stray-2") e.reap() e.clk.AdvanceMono(OrphanGrace - time.Second) e.reap() e.wantStops(stray) e.clk.AdvanceMono(time.Second) e.reap() e.wantStops(stray, late) } func TestUnknownStateRetriedAndAlerted(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref1 := e.launchWith("att-1", 2*time.Hour) e.launchWith("att-2", 2*time.Hour) e.fake.Tick() if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop = %v, want ErrStopPending", err) } e.wantStops(ref1) stops := 1 // unknown is how many of att-1, att-2 (in that order) read unknown. pass := func(n, unknown, wantAlerts int) { t.Helper() for range unknown { e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState) } e.clk.AdvanceMono(ReapInterval) r := e.reap() if r.Unknown != unknown { t.Fatalf("pass %d: report %+v, want %d unknown", n, r, unknown) } if unknown > 0 { stops++ // att-1 has a stop asked for: sent again } got := e.fake.StopsIssued() if len(got) != stops || slices.ContainsFunc(got, func(r isolatedjob.Ref) bool { return r != ref1 }) { t.Fatalf("pass %d: provider stops %v, want %d, all to %s", n, got, stops, ref1) } if a := e.alerts(AlertUnknownState); len(a) != wantAlerts { t.Fatalf("pass %d: unknown_state alerts %+v, want %d", n, a, wantAlerts) } } pass(1, 2, 0) pass(2, 2, 0) pass(3, 2, 2) // three in a row: one alert for each job pass(4, 2, 2) // once per episode pass(5, 0, 2) // a known state ends both episodes pass(6, 1, 2) pass(7, 1, 2) pass(8, 1, 3) // a new episode for att-1 if !e.hasAudit("", "att-1", actionUnknownState, "") { t.Fatal("no unknown_state audit row for att-1") } } func TestFailingAuditBlocksLaunchAndAlertsOnce(t *testing.T) { t.Parallel() e := newLaunchEnv(t) bad := isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true} // resolver on good := isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true} e.fake.SetAudit(bad, nil) for i := range 2 { if _, err := e.c.Reap(e.ctx); err == nil { t.Fatalf("pass %d with a failing audit = nil, want the audit failure", i) } if a := e.alerts(AlertAuditFailed); len(a) != 1 { t.Fatalf("pass %d: audit_failed alerts %+v, want one", i, a) } if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request(fmt.Sprintf("att-%d", i))); !errors.Is(err, ErrNetworkAudit) { t.Fatalf("Launch during a failing audit = %v, want ErrNetworkAudit", err) } } if !e.hasAudit("", "", actionNetworkAuditFailed, "resolver enabled") { t.Fatal("no network_audit_failed audit row") } e.fake.SetAudit(good, nil) e.reap() if !e.hasAudit("", "", actionNetworkAuditPassed, "") { t.Fatal("no network_audit_passed audit row when the episode ended") } if v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-ok")); err != nil || v.VMRef == "" { t.Fatalf("Launch after the audit passed = (%+v, %v), want a VM", v, err) } e.fake.SetAudit(bad, nil) if _, err := e.c.Reap(e.ctx); err == nil { t.Fatal("pass with the audit failing again = nil") } if a := e.alerts(AlertAuditFailed); len(a) != 2 { t.Fatalf("audit_failed alerts after a second episode = %+v, want two", a) } } // An alert the Alerter refuses is kept and sent on a later pass; the // pass's other steps still run. func TestReapAlertRetriedAfterAlerterError(t *testing.T) { t.Parallel() e := newLaunchEnv(t) rec := e.c.alerter.(*recordingAlerter) stray := e.plant("stray-1") e.reap() e.clk.AdvanceMono(OrphanGrace) down := errors.New("pager down") rec.fail = down r, err := e.c.Reap(e.ctx) if !errors.Is(err, down) || r.OrphansStopped != 1 { t.Fatalf("pass with the alerter down = (%+v, %v), want the orphan stopped and the alerter error", r, err) } e.wantStops(stray) rec.fail = nil e.reap() if a := e.alerts(AlertOrphanStopped); len(a) != 1 { t.Fatalf("orphan_stopped alerts after the alerter came back = %+v, want one", a) } } // countingList signals every List call, so a test can watch Loop's passes. type countingList struct { *isolatedjob.Fake calls chan struct{} } func (c *countingList) List(ctx context.Context) ([]isolatedjob.Job, error) { select { case c.calls <- struct{}{}: default: } return c.Fake.List(ctx) } func TestReapLoopRunsPassesUntilDone(t *testing.T) { t.Parallel() e := newLaunchEnv(t) cl := &countingList{Fake: e.fake, calls: make(chan struct{}, 1)} e.run = cl e.newController() e.plant("stray-1") ctx, cancel := context.WithCancel(e.ctx) done := make(chan error, 1) go func() { done <- e.c.Loop(ctx, time.Millisecond) }() for i := range 2 { select { case <-cl.calls: case <-time.After(5 * time.Second): t.Fatalf("Loop ran %d passes in 5 s, want 2", i) } } cancel() select { case <-done: case <-time.After(5 * time.Second): t.Fatal("Loop did not return after its context was cancelled") } if _, ok := e.c.LastReap(); !ok { t.Fatal("LastReap after two passes reports none finished") } if u := e.unmatched(); len(u) != 1 { t.Fatalf("unmatched_vms after Loop's passes = %v, want the orphan recorded", u) } } // auditCount counts the audit rows with action whose reason names ref. func (e *launchEnv) auditCount(action string, ref isolatedjob.Ref) int { e.t.Helper() n := 0 for _, a := range auditRows(e.t, e.store) { if a.Action == action && strings.Contains(a.Reason, string(ref)) { n++ } } return n } // While a waiting intent that has been dispatched exists, an orphan whose // grace is over may be the VM its lost launch reply made: it is deferred, // whichever gate keeps the intent from claiming it (R22). Once the intent is // abandoned, the VM is an orphan again and is stopped. func TestReapDefersOrphansWhileIntentWaits(t *testing.T) { t.Parallel() bad := isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true} // resolver on gates := []struct { name string set func(e *launchEnv) }{ {"throttled", func(e *launchEnv) { for range 20 { e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) } }}, {"launches off", func(e *launchEnv) { e.c.cfg.Enabled = false }}, {"image removed", func(e *launchEnv) { delete(e.c.cfg.Images, imgA) }}, {"audit failing", func(e *launchEnv) { e.fake.SetAudit(bad, nil) _ = e.c.RunAudit(e.ctx) // recorded now, so the first pass's replay is gated too }}, } ends := []struct { name string end func(e *launchEnv) }{ {"stop asked for", func(e *launchEnv) { if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) { e.t.Fatalf("Stop of the waiting intent = %v, want ErrStopPending", err) } }}, {"stop time passed", func(e *launchEnv) { e.clk.AdvanceMono(time.Duration(T(e.stopCols("att-1").stop) - e.store.Clock().Now())) }}, } for _, g := range gates { for _, end := range ends { t.Run(g.name+", "+end.name, func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.lostLaunch("att-1") stray := e.plant("stray-1") g.set(e) pass := func() ReapReport { r, err := e.c.Reap(e.ctx) if err != nil && g.name != "audit failing" { t.Fatalf("Reap = (%+v, %v)", r, err) } return r } pass() e.clk.AdvanceMono(OrphanGrace) for i := range 2 { if r := pass(); r.OrphansDeferred != 2 || r.OrphansStopped != 0 { t.Fatalf("pass %d after the grace: report %+v, want both orphans deferred", i, r) } e.clk.AdvanceMono(time.Minute) } e.wantStops() if j, _ := e.job("att-1"); j.state != JobWaiting { t.Fatalf("att-1 is %q, want still waiting", j.state) } for _, r := range []isolatedjob.Ref{ref, stray} { if n := e.auditCount(actionOrphanDeferred, r); n != 1 { t.Fatalf("orphan_deferred rows for %s = %d, want one for the run of deferrals", r, n) } } end.end(e) if r := pass(); r.OrphansStopped != 2 || r.OrphansDeferred != 0 { t.Fatalf("pass after the intent was abandoned: report %+v, want both orphans stopped", r) } if j, _ := e.job("att-1"); j.state != JobAbandoned { t.Fatalf("att-1 is %q, want abandoned", j.state) } e.wantStops(ref, stray) }) } } } // stopGate wraps the provider. The first Stop signals entered and waits for // release. Every Stop records whether its Ref was a job's saved Ref at the // moment of the call. type stopGate struct { *isolatedjob.Fake store *Store entered, release chan struct{} mu sync.Mutex calls int savedAtStop map[isolatedjob.Ref]bool } func (g *stopGate) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error { g.mu.Lock() g.calls++ first := g.calls == 1 g.mu.Unlock() if first { close(g.entered) <-g.release } var n int if err := g.store.Tx(ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs WHERE vm_ref = ?`, string(ref)).Scan(&n) }); err != nil { return err } g.mu.Lock() g.savedAtStop[ref] = n > 0 g.mu.Unlock() return g.Fake.Stop(ctx, ref, reason) } // The orphan final check holds the ownership lock through its last Stop // (R23): a Replay that tries to claim the second candidate while the first // Stop is in flight waits, and no Stop ever reaches a VM a job holds. func TestReapOwnershipLockHoldsClaims(t *testing.T) { t.Parallel() e := newLaunchEnv(t) g := &stopGate{Fake: e.fake, store: e.store, entered: make(chan struct{}), release: make(chan struct{}), savedAtStop: map[isolatedjob.Ref]bool{}} e.run = g e.newController() e.audit() stray := e.plant("stray-1") ref := e.lostLaunch("att-1") // The lost launch marked a dispatch, so R22 alone would defer both // orphans. Clearing the mark isolates the lock. e.exec(`UPDATE jobs SET last_dispatch_t = NULL WHERE attempt_id = 'att-1'`) e.c.cfg.Enabled = false // the pass's own replays create and claim nothing e.reap() e.clk.AdvanceMono(OrphanGrace) waited := make(chan struct{}) e.c.ownership.waiting = func() { close(waited) } reaped := make(chan error, 1) go func() { _, err := e.c.Reap(e.ctx); reaped <- err }() select { case <-g.entered: case <-time.After(5 * time.Second): t.Fatal("the reaper never stopped the first orphan") } e.c.cfg.Enabled = true // the reaper read it before the Stop; a claim may go ahead now replayed := make(chan error, 1) go func() { replayed <- e.c.Replay(e.ctx) }() select { case <-waited: // the dispatch waits for the reaper case err := <-replayed: // the claim landed during the Stop replayed <- err case <-time.After(5 * time.Second): t.Fatal("the Replay neither waited nor finished") } close(g.release) for _, ch := range []chan error{reaped, replayed} { select { case err := <-ch: if err != nil { t.Fatalf("Reap or Replay = %v", err) } case <-time.After(5 * time.Second): t.Fatal("Reap or Replay did not finish") } } g.mu.Lock() defer g.mu.Unlock() if len(g.savedAtStop) != 2 { t.Fatalf("orphan stops = %v, want %s and %s", g.savedAtStop, stray, ref) } for r, saved := range g.savedAtStop { if saved { t.Fatalf("VM %s was stopped as an orphan while a job held it", r) } } if j, _ := e.job("att-1"); isolatedjob.Ref(j.ref.String) != ref { t.Fatalf("att-1 ref %v, want %s claimed once the reaper let go", j.ref, ref) } } // scriptAuditor answers AuditNetwork from a script: true passes, false // fails. Calls past the script pass. type scriptAuditor struct { mu sync.Mutex script []bool n int } func (s *scriptAuditor) AuditNetwork(context.Context) (isolatedjob.NetworkAudit, error) { s.mu.Lock() defer s.mu.Unlock() s.n++ a := isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true} if s.n <= len(s.script) && !s.script[s.n-1] { a.ResolverDisabled = false } return a, nil } // The recheck's audit and step 6's share one run of failures: a pass at // either point ends it, a failure at either begins one. func TestReapAuditEpisodesAcrossBothAudits(t *testing.T) { t.Parallel() e := newLaunchEnv(t) sa := &scriptAuditor{script: []bool{ true, // the setup audit false, // pass 0, step 6 true, false, // pass 1: recheck, step 6 true, // pass 2, step 6 false, true, // pass 3: recheck, step 6 }} c, err := New(e.cfg, Deps{Store: e.store, Runner: e.run, Auditor: sa, Alerter: &recordingAlerter{}}) if err != nil { t.Fatal(err) } e.c = c e.audit() passed := func() int { return e.auditCount(actionNetworkAuditPassed, "") } check := func(n int, wantErr bool, alerts, passes int) { t.Helper() _, err := e.c.Reap(e.ctx) if (err != nil) != wantErr { t.Fatalf("pass %d = %v, want an error %v", n, err, wantErr) } if a := e.alerts(AlertAuditFailed); len(a) != alerts { t.Fatalf("pass %d: audit_failed alerts %d, want %d", n, len(a), alerts) } if p := passed(); p != passes { t.Fatalf("pass %d: network_audit_passed rows %d, want %d", n, p, passes) } } e.plant("stray-1") check(0, true, 1, 0) e.clk.AdvanceMono(OrphanGrace) check(1, true, 2, 1) // failure, then success at the recheck, then failure: a new run e.plant("stray-2") check(2, false, 2, 2) e.clk.AdvanceMono(OrphanGrace) check(3, true, 3, 3) // the recheck's failure counts though step 6 passes if sa.n != len(sa.script) { t.Fatalf("audits run = %d, want %d", sa.n, len(sa.script)) } } // A stale live List entry for a job that already has proof still matches // its saved Ref: it is never an orphan. func TestReapProvenJobIsNeverOrphan(t *testing.T) { t.Parallel() e := newLaunchEnv(t) sr := &slowRunner{Fake: e.fake, clk: e.clk} e.run = sr e.newController() e.audit() ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop = %v, want ErrStopPending", err) } e.fake.Tick() e.refresh() if w := e.wireProof("att-1"); w.VMRef != ref { t.Fatalf("proof = %+v, want one for %s", w, ref) } e.fake.Vanish(ref) sr.setExtra(isolatedjob.Job{Ref: ref, State: isolatedjob.StateRunning}) if r := e.reap(); r.OrphansSeen != 0 { t.Fatalf("report %+v, want no orphan", r) } e.clk.AdvanceMono(OrphanGrace) if r := e.reap(); r.OrphansSeen != 0 || r.OrphansStopped != 0 { t.Fatalf("after the grace: report %+v, want no orphan", r) } e.wantStops(ref) // the instance's own stop only } // listScript wraps the provider's List. After List call n (counting from // 1) it runs script(n), which may change the fake; when script returns // true the answer comes with ErrIncomplete, VMs and all. type listScript struct { *isolatedjob.Fake mu sync.Mutex n int script func(n int) bool } func (l *listScript) List(ctx context.Context) ([]isolatedjob.Job, error) { vms, err := l.Fake.List(ctx) if err != nil { return vms, err } l.mu.Lock() l.n++ n := l.n l.mu.Unlock() if l.script(n) { return vms, fmt.Errorf("%w: test stopped paging", isolatedjob.ErrIncomplete) } return vms, nil } // The final check lists again: a VM the first List showed and the provider // has since forgotten is not stopped. func TestReapRecheckListsAgain(t *testing.T) { t.Parallel() e := newLaunchEnv(t) var stray isolatedjob.Ref ls := &listScript{Fake: e.fake, script: func(n int) bool { if n == 2 { // the expiry pass's first List e.fake.Vanish(stray) } return false }} e.run = ls e.newController() e.audit() stray = e.plant("stray-1") e.reap() e.clk.AdvanceMono(OrphanGrace) if r := e.reap(); r.OrphansStopped != 0 { t.Fatalf("report %+v, want no stop of a VM the fresh list does not show", r) } e.wantStops() } // An incomplete List in the final check stops nothing; the next complete // one does. func TestReapIncompleteRecheckListStopsNothing(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ls := &listScript{Fake: e.fake, script: func(n int) bool { return n == 3 }} // the expiry pass's recheck e.run = ls e.newController() e.audit() stray := e.plant("stray-1") e.reap() e.clk.AdvanceMono(OrphanGrace) if r := e.reap(); !r.Skipped || r.OrphansStopped != 0 { t.Fatalf("pass with an incomplete recheck list: report %+v, want skipped, no stop", r) } e.wantStops() if u := e.unmatched(); len(u) != 1 { t.Fatalf("unmatched_vms = %v, want the orphan kept", u) } if r := e.reap(); r.Skipped || r.OrphansStopped != 1 { t.Fatalf("next pass: report %+v, want the orphan stopped", r) } e.wantStops(stray) } // A dispatch that waits for the ownership lock checks its gates only once // it holds the lock: a stop time, a stale audit or a failing audit reached // during the wait means no provider launch (R23 placement, review r2). func TestReapWaitingDispatchChecksGatesAfter(t *testing.T) { t.Parallel() bad := isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true} // resolver on cases := []struct { name string change func(e *launchEnv) want string // the intent's state after the dispatch launch bool // whether the provider is asked to launch }{ {"nothing changes", func(*launchEnv) {}, JobStarting, true}, {"stop time passes", func(e *launchEnv) { e.clk.AdvanceMono(time.Duration(T(e.stopCols("att-1").stop) - e.store.Clock().Now())) }, JobAbandoned, false}, {"audit goes stale", func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Second) }, JobWaiting, false}, {"audit fails", func(e *launchEnv) { e.fake.SetAudit(bad, nil) if err := e.c.RunAudit(e.ctx); err == nil { e.t.Fatal("RunAudit with the resolver on = nil") } }, JobWaiting, false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) if v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil || v.State != JobWaiting { t.Fatalf("throttled Launch = (%+v, %v), want a waiting intent", v, err) } e.audit() // fresh, so only the change below can close a gate // The orphan reaper's final check holds the lock for writing. e.c.ownership.mu.Lock() waited := make(chan struct{}) e.c.ownership.waiting = func() { close(waited) } replayed := make(chan error, 1) go func() { replayed <- e.c.Replay(e.ctx) }() select { case <-waited: case err := <-replayed: e.c.ownership.mu.Unlock() t.Fatalf("Replay finished (%v) while the ownership lock was held for writing", err) case <-time.After(5 * time.Second): t.Fatal("the dispatch never waited for the ownership lock") } tc.change(e) launches := e.fake.Calls(isolatedjob.OpLaunch) e.c.ownership.mu.Unlock() select { case err := <-replayed: if err != nil { t.Fatalf("Replay = %v", err) } case <-time.After(5 * time.Second): t.Fatal("Replay did not finish once the lock was free") } want := 0 if tc.launch { want = 1 } if got := e.fake.Calls(isolatedjob.OpLaunch) - launches; got != want { t.Fatalf("provider launches after the wait = %d, want %d", got, want) } if j, _ := e.job("att-1"); j.state != tc.want { t.Fatalf("att-1 is %q, want %q", j.state, tc.want) } if tc.want == JobAbandoned && !e.hasAudit("", "att-1", actionReplayAbandoned, "stop time passed") { t.Fatal("no replay_abandoned audit row") } }) } }