package hostedctl import ( "database/sql" "errors" "testing" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) // pauseCols are the jobs columns the pause barrier and resume write. type pauseCols struct { state string gen, epoch int64 started sql.NullInt64 quiescent, cancelled bool } func (e *launchEnv) pauseCols(attempt string) pauseCols { e.t.Helper() var p pauseCols if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(e.ctx, `SELECT state, pause_generation, epoch, pause_started_t, pause_quiescent, pause_cancelled FROM jobs WHERE attempt_id = ?`, attempt).Scan( &p.state, &p.gen, &p.epoch, &p.started, &p.quiescent, &p.cancelled) }); err != nil { e.t.Fatalf("read pause columns of %s = %v", attempt, err) } return p } // runningJob is a controller with att-1 launched for inst-1 (lifetime 2 h), // its VM running and the job's state saved as running. func runningJob(t *testing.T) *launchEnv { t.Helper() e := newLaunchEnv(t) e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.refresh() if p := e.pauseCols("att-1"); p.state != JobRunning { t.Fatalf("att-1 after launch and refresh is %q, want running", p.state) } return e } func (e *launchEnv) drain() int64 { e.t.Helper() g, err := e.c.Drain(e.ctx, "inst-1", instKey, "att-1") if err != nil || g < 1 { e.t.Fatalf("Drain = (%d, %v), want a new generation", g, err) } return g } func (e *launchEnv) ack(g int64) { e.t.Helper() if err := e.c.Quiescent(e.ctx, "inst-1", instKey, "att-1", g); err != nil { e.t.Fatalf("Quiescent(%d) = %v", g, err) } } // suspendJob drains att-1, acknowledges, suspends, and lets the VM and the // job settle as suspended. It returns the generation. func (e *launchEnv) suspendJob() int64 { e.t.Helper() g := e.drain() e.ack(g) if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", g); err != nil { e.t.Fatalf("Suspend(%d) = %v", g, err) } e.fake.Tick() e.refresh() if p := e.pauseCols("att-1"); p.state != JobSuspended { e.t.Fatalf("att-1 after suspend and refresh is %q, want suspended", p.state) } return g } func TestSuspendNeedsCurrentAck(t *testing.T) { t.Parallel() for _, tc := range []struct { name string // setup opens generations and acknowledges as the case needs; it // returns the generation Suspend is asked for, the current one, and // whether the current one may still be suspended afterwards. setup func(e *launchEnv) (asked, current int64, live bool) wantErr error }{ {"no acknowledgement", func(e *launchEnv) (int64, int64, bool) { g := e.drain() return g, g, true }, ErrNotQuiescent}, {"an older generation", func(e *launchEnv) (int64, int64, bool) { g1 := e.drain() g2 := e.drain() if err := e.c.Quiescent(e.ctx, "inst-1", instKey, "att-1", g1); !errors.Is(err, ErrGenerationCancelled) { e.t.Fatalf("Quiescent for a superseded generation = %v, want ErrGenerationCancelled", err) } e.ack(g2) return g1, g2, true }, ErrGenerationCancelled}, {"the next generation", func(e *launchEnv) (int64, int64, bool) { g := e.drain() e.ack(g) return g + 1, g, true }, ErrGenerationCancelled}, {"a cancelled generation", func(e *launchEnv) (int64, int64, bool) { g := e.drain() e.clk.AdvanceMono(PauseAckTimeout + time.Second) return g, g, false }, ErrGenerationCancelled}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() e := runningJob(t) asked, current, live := tc.setup(e) if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", asked); !errors.Is(err, tc.wantErr) { t.Fatalf("Suspend(%d) with current generation %d = %v, want %v", asked, current, err, tc.wantErr) } if a := e.lastAudit(); a.Actor != "inst-1" || a.Action != actionSuspendRefused { t.Fatalf("audit after the refusal = %+v, want suspend_refused by inst-1", a) } if n := e.fake.Calls(isolatedjob.OpSuspend); n != 0 { t.Fatalf("a refused Suspend reached the provider %d times", n) } if p := e.pauseCols("att-1"); p.state != JobDraining || p.gen != current { t.Fatalf("after the refusal: %+v, want draining at generation %d", p, current) } if !live { return } if p := e.pauseCols("att-1"); !p.quiescent { e.ack(current) } if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", current); err != nil { t.Fatalf("Suspend of the acknowledged current generation %d = %v", current, err) } if p := e.pauseCols("att-1"); p.state != JobSuspending || e.fake.Calls(isolatedjob.OpSuspend) != 1 { t.Fatalf("after Suspend: %+v, %d provider suspends; want suspending, 1", p, e.fake.Calls(isolatedjob.OpSuspend)) } }) } } func TestLateAckIgnored(t *testing.T) { t.Parallel() e := runningJob(t) g := e.drain() e.clk.AdvanceMono(PauseAckTimeout + time.Second) if err := e.c.Quiescent(e.ctx, "inst-1", instKey, "att-1", g); !errors.Is(err, ErrGenerationCancelled) { t.Fatalf("Quiescent at 2m1s = %v, want ErrGenerationCancelled", err) } if p := e.pauseCols("att-1"); !p.cancelled || p.quiescent || p.state != JobDraining { t.Fatalf("after a late ack: %+v, want draining, cancelled, not quiescent", p) } if !e.hasAudit("", "att-1", actionPauseCancelled, "no quiescent acknowledgement") { t.Fatal("no pause_cancelled audit row") } if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", g); !errors.Is(err, ErrGenerationCancelled) { t.Fatalf("Suspend after a late ack = %v, want ErrGenerationCancelled", err) } if n := e.fake.Calls(isolatedjob.OpSuspend); n != 0 { t.Fatalf("provider suspends = %d, want 0", n) } // The runner takes work again: admission reopens; the counter stays. if err := e.c.Reopen(e.ctx, "inst-1", instKey, "att-1", g+1); !errors.Is(err, ErrGenerationCancelled) { t.Fatalf("Reopen of another generation = %v, want ErrGenerationCancelled", err) } if err := e.c.Reopen(e.ctx, "inst-1", instKey, "att-1", g); err != nil { t.Fatalf("Reopen(%d) = %v", g, err) } if p := e.pauseCols("att-1"); p.state != JobRunning || p.gen != g || p.started.Valid || p.quiescent || p.cancelled { t.Fatalf("after Reopen: %+v, want running at generation %d with the pause fields reset", p, g) } // An acknowledgement at exactly PauseAckTimeout is in time. g2 := e.drain() if g2 != g+1 { t.Fatalf("next Drain = %d, want %d", g2, g+1) } e.clk.AdvanceMono(PauseAckTimeout) e.ack(g2) e.clk.AdvanceMono(time.Hour) // a timely ack does not expire if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", g2); err != nil { t.Fatalf("Suspend after an ack at exactly 2m = %v", err) } } // TestPauseAckAcrossRestartCancelled: drain, then a restart whose ten // minutes of downtime the wall clock hides. The old generation's // acknowledgement must be refused, before the first Refresh and after it, // and its Suspend too: controller time cannot tell it was late. A // generation opened after the restart is acknowledged as usual. func TestPauseAckAcrossRestartCancelled(t *testing.T) { t.Parallel() for _, refreshFirst := range []bool{false, true} { e := runningJob(t) g := e.drain() e.down() e.clk.AdvanceMono(10 * time.Minute) e.restart() if refreshFirst { e.refresh() } if err := e.c.Quiescent(e.ctx, "inst-1", instKey, "att-1", g); !errors.Is(err, ErrGenerationCancelled) { t.Fatalf("refresh first %v: Quiescent(%d) after the restart = %v, want ErrGenerationCancelled", refreshFirst, g, err) } if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", g); !errors.Is(err, ErrGenerationCancelled) { t.Fatalf("refresh first %v: Suspend(%d) = %v, want ErrGenerationCancelled", refreshFirst, g, err) } if p := e.pauseCols("att-1"); !p.cancelled || p.quiescent || p.state != JobDraining || e.fake.Calls(isolatedjob.OpSuspend) != 0 { t.Fatalf("refresh first %v: %+v, want the generation cancelled and no suspend", refreshFirst, p) } e.clk.AdvanceMono(time.Second) e.ack(e.drain()) } } // TestReopenWaitsForRestartReconciliation: a job drains at 1 h 40 min of // its 1 h 50 min to stop; a restart hides 15 minutes of downtime. Reopen // before the first Refresh must not open admission against the stale stop // time; once Refresh re-bases the job on the provider's age, Reopen sees // the stop time has passed. func TestReopenWaitsForRestartReconciliation(t *testing.T) { t.Parallel() e := runningJob(t) e.clk.AdvanceMono(100 * time.Minute) g := e.drain() e.down() e.clk.AdvanceMono(15 * time.Minute) e.restart() if err := e.c.Reopen(e.ctx, "inst-1", instKey, "att-1", g); !errors.Is(err, isolatedjob.ErrConflict) { t.Fatalf("Reopen before the first refresh = %v, want ErrConflict", err) } if p := e.pauseCols("att-1"); p.state != JobDraining { t.Fatalf("att-1 after the refused Reopen is %q, want draining", p.state) } e.refresh() if err := e.c.Reopen(e.ctx, "inst-1", instKey, "att-1", g); !errors.Is(err, ErrPastDeadline) { t.Fatalf("Reopen after the re-base = %v, want ErrPastDeadline", err) } if p := e.pauseCols("att-1"); p.state != JobDraining { t.Fatalf("att-1 after Reopen past its stop time is %q, want draining", p.state) } } func TestSuspendedTimeCountsToDeadline(t *testing.T) { t.Parallel() e := runningJob(t) before := e.stopCols("att-1") e.suspendJob() e.clk.AdvanceMono(30 * time.Minute) e.refresh() v, err := e.c.Get(e.ctx, "inst-1", "att-1") if err != nil { t.Fatal(err) } now := e.store.Clock().Now() if want := time.Duration(T(before.stop) - now); v.StopIn != want || v.DeadlineIn != time.Duration(T(before.deadline)-now) { t.Fatalf("while suspended: StopIn %v DeadlineIn %v, want %v and %v (suspended time counts)", v.StopIn, v.DeadlineIn, want, time.Duration(T(before.deadline)-now)) } if _, err := e.c.Resume(e.ctx, "inst-1", instKey, "att-1", "op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume = %v, want ErrResumePending until the VM runs", err) } e.fake.Tick() if ep, err := e.c.Resume(e.ctx, "inst-1", instKey, "att-1", "op-1"); err != nil || ep != 1 { t.Fatalf("Resume after the VM runs = (%d, %v), want (1, nil)", ep, err) } after := e.stopCols("att-1") if after.launched != before.launched || after.deadline != before.deadline || after.drain != before.drain || after.stop != before.stop { t.Fatalf("times moved across suspend and resume: %+v, want %+v", after, before) } } func TestSuspendAndResumeRoles(t *testing.T) { t.Parallel() e := runningJob(t) g := e.drain() calls := map[string]func(by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string) error{ actionDrainRefused: func(by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string) error { _, err := e.c.Drain(e.ctx, by, key, attempt) return err }, actionQuiescentRefused: func(by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string) error { return e.c.Quiescent(e.ctx, by, key, attempt, g) }, actionSuspendRefused: func(by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string) error { return e.c.Suspend(e.ctx, by, key, attempt, g) }, actionReopenRefused: func(by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string) error { return e.c.Reopen(e.ctx, by, key, attempt, g) }, actionResumeRefused: func(by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string) error { _, err := e.c.Resume(e.ctx, by, key, attempt, "op-1") return err }, } for refused, call := range calls { for _, tc := range []struct { name string by hostedwire.KeyID key hostedwire.VerifyKey attempt string }{ {"another instance", "inst-2", instKey, "att-1"}, {"an operator key with the creator's id", "inst-1", opKey, "att-1"}, {"no key id", "", instKey, "att-1"}, {"an unknown attempt", "inst-1", instKey, "att-9"}, } { if err := call(tc.by, tc.key, tc.attempt); !errors.Is(err, ErrForbidden) { t.Fatalf("%s by %s = %v, want ErrForbidden", refused, tc.name, err) } if a := e.lastAudit(); a.Actor != tc.by || a.Action != refused { t.Fatalf("audit after %s by %s = %+v, want %s by %q", refused, tc.name, a, refused, tc.by) } } } if p := e.pauseCols("att-1"); p.state != JobDraining || p.gen != g || p.quiescent || p.epoch != 0 { t.Fatalf("refused calls changed the job: %+v", p) } if n := e.fake.Calls(isolatedjob.OpSuspend) + e.fake.Calls(isolatedjob.OpResume); n != 0 { t.Fatalf("refused calls reached the provider %d times", n) } if ops := e.resumeOps("att-1"); len(ops) != 0 { t.Fatalf("refused calls prepared resume operations: %+v", ops) } } func TestSuspendRefreshSettles(t *testing.T) { t.Parallel() e := runningJob(t) g := e.drain() e.exec(`UPDATE jobs SET notfound_since_t = 1 WHERE attempt_id = 'att-1'`) // a first not-found e.refresh() if p, s := e.pauseCols("att-1"), e.stopCols("att-1"); p.state != JobDraining || s.notFoundSince.Valid { t.Fatalf("Refresh of a draining job with a running VM left %q, not-found since %v; want draining, cleared", p.state, s.notFoundSince) } e.ack(g) // The suspend call is throttled and does nothing: Refresh sends it again. e.fake.Inject(isolatedjob.OpSuspend, isolatedjob.FaultThrottle) if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", g); !errors.Is(err, isolatedjob.ErrThrottled) { t.Fatalf("throttled Suspend = %v, want ErrThrottled", err) } if p := e.pauseCols("att-1"); p.state != JobSuspending { t.Fatalf("after a throttled suspend call the job is %q, want suspending", p.state) } e.refresh() if p, n := e.pauseCols("att-1"), e.fake.Calls(isolatedjob.OpSuspend); p.state != JobSuspending || n != 2 { t.Fatalf("Refresh with the VM still running: %q, %d provider suspends; want suspending, 2", p.state, n) } e.refresh() // the VM is suspending now: nothing to send if n := e.fake.Calls(isolatedjob.OpSuspend); n != 2 { t.Fatalf("provider suspends = %d after a refresh of a suspending VM, want 2", n) } e.fake.Tick() e.refresh() if p := e.pauseCols("att-1"); p.state != JobSuspended { t.Fatalf("Refresh with the VM suspended left %q, want suspended", p.state) } // A prepared resume: Refresh keeps resuming while the VM is suspended, // sends the resume again, and commits once the VM runs. if _, err := e.c.Resume(e.ctx, "inst-1", instKey, "att-1", "op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume = %v, want ErrResumePending", err) } // A re-send that fails is audited and tried again; Refresh goes on. e.fake.Inject(isolatedjob.OpResume, isolatedjob.FaultThrottle) e.refresh() if !e.hasAudit("", "att-1", actionResumeCallFailed, "op-1") { t.Fatal("no resume_call_failed audit row for a failed re-send") } e.refresh() if p, n := e.pauseCols("att-1"), e.fake.Calls(isolatedjob.OpResume); p.state != JobResuming || p.epoch != 0 || n != 3 { t.Fatalf("Refresh with the VM suspended: %+v, %d provider resumes; want resuming at epoch 0, 3", p, n) } e.fake.Tick() e.refresh() if p := e.pauseCols("att-1"); p.state != JobRunning || p.epoch != 1 || p.started.Valid || p.quiescent || p.gen != g { t.Fatalf("Refresh with the VM running: %+v, want running at epoch 1, pause closed, generation %d", p, g) } if ops := e.resumeOps("att-1"); len(ops) != 1 || ops[0].status != "done" || ops[0].result.Int64 != 1 { t.Fatalf("resume operations = %+v, want op-1 done at epoch 1", ops) } }