package hostedctl import ( "context" "database/sql" "errors" "testing" "time" "amadan.net/oficina/equipo/internal/isolatedjob" ) // opRow is one resume_ops row. type opRow struct { id, status string prepared int64 result sql.NullInt64 } func (e *launchEnv) resumeOps(attempt string) []opRow { e.t.Helper() var out []opRow if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error { out = out[:0] rows, err := tx.QueryContext(e.ctx, `SELECT operation_id, status, prepared_epoch, result_epoch FROM resume_ops WHERE attempt_id = ? ORDER BY prepared_t, operation_id`, attempt) if err != nil { return err } defer rows.Close() for rows.Next() { var r opRow if err := rows.Scan(&r.id, &r.status, &r.prepared, &r.result); err != nil { return err } out = append(out, r) } return rows.Err() }); err != nil { e.t.Fatalf("read resume operations of %s = %v", attempt, err) } return out } func (e *launchEnv) resume(op string) (int64, error) { e.t.Helper() return e.c.Resume(e.ctx, "inst-1", instKey, "att-1", op) } // resumeDone wants Resume(op) to return epoch with no error. func (e *launchEnv) resumeDone(op string, epoch int64) { e.t.Helper() if got, err := e.resume(op); err != nil || got != epoch { e.t.Fatalf("Resume(%s) = (%d, %v), want (%d, nil)", op, got, err, epoch) } } // wantResume checks the job's state and epoch, the one pending or settled // row, and how many provider resumes were made. func (e *launchEnv) wantResume(state string, epoch int64, ops []opRow, calls int) { e.t.Helper() p := e.pauseCols("att-1") got := e.resumeOps("att-1") n := e.fake.Calls(isolatedjob.OpResume) ok := p.state == state && p.epoch == epoch && len(got) == len(ops) && n == calls for i := 0; ok && i < len(ops); i++ { ok = got[i].id == ops[i].id && got[i].status == ops[i].status && got[i].prepared == ops[i].prepared && got[i].result == ops[i].result } if !ok { e.t.Fatalf("job %q at epoch %d, ops %+v, %d provider resumes; want %q at %d, %+v, %d", p.state, p.epoch, got, n, state, epoch, ops, calls) } } func pending(id string, prepared int64) opRow { return opRow{id: id, status: "pending", prepared: prepared} } func done(id string, epoch int64) opRow { return opRow{id: id, status: "done", prepared: epoch, result: sql.NullInt64{Int64: epoch, Valid: true}} } // resumeProbe wraps the fake provider's Resume with a hook before the call // (a non-nil error from it is returned without calling the provider) and one // after it. type resumeProbe struct { *isolatedjob.Fake before func() error after func() } func (p *resumeProbe) Resume(ctx context.Context, ref isolatedjob.Ref) error { if p.before != nil { if err := p.before(); err != nil { return err } } err := p.Fake.Resume(ctx, ref) if p.after != nil { p.after() } return err } // probe puts p in front of the fake provider for a new controller. func (e *launchEnv) probe(p *resumeProbe) { e.t.Helper() p.Fake = e.fake e.run = p e.newController() } // restart is a controller restart over the same fake provider, with no // probe: Close (already done by the crash) is followed by Open and New. func (e *launchEnv) restart() { e.t.Helper() e.run = e.fake e.up() } func TestResumePreparesEpochBeforeProvider(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() type seen struct { state string epoch int64 status sql.NullString prep sql.NullInt64 err error } var at []seen e.probe(&resumeProbe{before: func() error { // A transaction held across the call would make this read wait; // the deadline turns that into an error. rctx, cancel := context.WithTimeout(e.ctx, 2*time.Second) defer cancel() var s seen s.err = e.store.Tx(rctx, func(tx *sql.Tx) error { if err := tx.QueryRowContext(rctx, `SELECT state, epoch FROM jobs WHERE attempt_id = 'att-1'`).Scan(&s.state, &s.epoch); err != nil { return err } err := tx.QueryRowContext(rctx, `SELECT status, prepared_epoch FROM resume_ops WHERE attempt_id = 'att-1' AND operation_id = 'op-1'`).Scan(&s.status, &s.prep) if errors.Is(err, sql.ErrNoRows) { return nil } return err }) at = append(at, s) return nil }}) if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume = %v, want ErrResumePending while the VM still reports suspended", err) } if len(at) != 1 { t.Fatalf("provider resumes = %d, want 1", len(at)) } s := at[0] if s.err != nil || s.state != JobResuming || s.epoch != 0 || s.status.String != "pending" || s.prep.Int64 != 1 { t.Fatalf("store at the provider call: %+v; want resuming at epoch 0 with op-1 pending at epoch 1", s) } } func TestResumeCrashBeforeProvider(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() e.probe(&resumeProbe{before: func() error { if err := e.store.Close(); err != nil { t.Errorf("Close = %v", err) } return errors.New("the controller died before the call") }}) if _, err := e.resume("op-1"); err == nil { t.Fatal("Resume across a crash = nil error") } e.restart() e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 0) e.refresh() // the first pass after the restart only re-bases the job's times e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 0) e.refresh() // the VM is suspended: the resume is sent e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 1) e.fake.Tick() e.refresh() // the VM runs: commit e.wantResume(JobRunning, 1, []opRow{done("op-1", 1)}, 1) e.resumeDone("op-1", 1) e.refresh() e.wantResume(JobRunning, 1, []opRow{done("op-1", 1)}, 1) } func TestResumeCrashAfterProvider(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() e.probe(&resumeProbe{after: func() { e.fake.Tick() // the VM runs before the controller can commit if err := e.store.Close(); err != nil { t.Errorf("Close = %v", err) } }}) if _, err := e.resume("op-1"); err == nil { t.Fatal("Resume across a crash = nil error") } e.restart() e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 1) // Until the first Refresh re-bases the job's times, a retry waits, and // that Refresh drives no resume (the VM already runs: no commit yet). if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume before the first refresh after a restart = %v, want ErrResumePending", err) } e.refresh() e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 1) // The client retries: a no-op provider resume, then the commit. e.resumeDone("op-1", 1) e.wantResume(JobRunning, 1, []opRow{done("op-1", 1)}, 2) e.refresh() e.resumeDone("op-1", 1) e.wantResume(JobRunning, 1, []opRow{done("op-1", 1)}, 2) if got := e.fake.LiveByAttempt()["att-1"]; got != 1 { t.Fatalf("live VMs for att-1 = %d, want 1", got) } } func TestResumeLostReply(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() e.fake.Inject(isolatedjob.OpResume, isolatedjob.FaultLostReply) _, err := e.resume("op-1") if !errors.Is(err, ErrResumePending) || !errors.Is(err, isolatedjob.ErrLostReply) { t.Fatalf("Resume with a lost reply = %v, want ErrResumePending and the lost reply", err) } e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 1) // The resume took effect but the VM still reports suspended: neither a // retry nor Refresh may commit yet. if ep, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) || ep != 0 { t.Fatalf("retry while the VM is suspended = (%d, %v), want (0, ErrResumePending)", ep, err) } e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 2) e.refresh() e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 3) e.fake.Tick() e.resumeDone("op-1", 1) e.wantResume(JobRunning, 1, []opRow{done("op-1", 1)}, 4) e.refresh() e.resumeDone("op-1", 1) e.wantResume(JobRunning, 1, []opRow{done("op-1", 1)}, 4) } func TestResumeRetrySameOperation(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() for i := 0; i < 2; i++ { if ep, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) || ep != 0 { t.Fatalf("Resume %d while suspended = (%d, %v), want (0, ErrResumePending)", i+1, ep, err) } } e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 2) e.fake.Tick() e.resumeDone("op-1", 1) for i := 0; i < 3; i++ { e.resumeDone("op-1", 1) e.refresh() } e.wantResume(JobRunning, 1, []opRow{done("op-1", 1)}, 3) if !e.hasAudit("inst-1", "att-1", actionResumeRepeated, "op-1") { t.Fatal("no resume_repeated audit row for a retry of a done operation") } } func TestResumeOperationsRemembered(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() if _, err := e.resume("op-a"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume(op-a) = %v, want ErrResumePending", err) } e.fake.Tick() e.resumeDone("op-a", 1) e.clk.AdvanceMono(time.Minute) // op-b is the latest operation by time e.suspendJob() if _, err := e.resume("op-b"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume(op-b) = %v, want ErrResumePending", err) } e.fake.Tick() e.resumeDone("op-b", 2) calls := e.fake.Calls(isolatedjob.OpResume) e.resumeDone("op-a", 1) e.resumeDone("op-b", 2) e.wantResume(JobRunning, 2, []opRow{done("op-a", 1), done("op-b", 2)}, calls) } func TestResumeOtherOperationWhilePending(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() if _, err := e.resume("op-a"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume(op-a) = %v, want ErrResumePending", err) } if ep, err := e.resume("op-b"); !errors.Is(err, ErrResumePending) || ep != 0 { t.Fatalf("Resume(op-b) while op-a is pending = (%d, %v), want (0, ErrResumePending)", ep, err) } e.wantResume(JobResuming, 0, []opRow{pending("op-a", 1)}, 1) e.fake.Tick() e.resumeDone("op-a", 1) if _, err := e.resume("op-b"); !errors.Is(err, isolatedjob.ErrConflict) { t.Fatalf("Resume(op-b) of a running job = %v, want ErrConflict", err) } e.wantResume(JobRunning, 1, []opRow{done("op-a", 1)}, 2) for _, bad := range []string{"", "op 1", "op_1", "op/1", string(make([]byte, 65))} { if _, err := e.resume(bad); !errors.Is(err, isolatedjob.ErrInvalid) { t.Fatalf("Resume(%q) = %v, want ErrInvalid", bad, err) } } } func TestResumePastDeadlineRefused(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() stop := e.stopCols("att-1").stop e.clk.AdvanceMono(time.Duration(T(stop) - e.store.Clock().Now())) if _, err := e.resume("op-1"); !errors.Is(err, ErrPastDeadline) { t.Fatalf("Resume at the stop time = %v, want ErrPastDeadline", err) } e.wantResume(JobSuspended, 0, nil, 0) if a := e.lastAudit(); a.Action != actionResumeRefused || a.Actor != "inst-1" { t.Fatalf("audit = %+v, want resume_refused by inst-1", a) } // A pending operation is failed past the stop time, with no further // provider call; a retry of it is refused from then on. e2 := runningJob(t) e2.suspendJob() e2.fake.Inject(isolatedjob.OpResume, isolatedjob.FaultThrottle) if _, err := e2.resume("op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("throttled Resume = %v, want ErrResumePending", err) } stop = e2.stopCols("att-1").stop e2.clk.AdvanceMono(time.Duration(T(stop)-e2.store.Clock().Now()) + time.Second) if _, err := e2.resume("op-1"); !errors.Is(err, ErrPastDeadline) { t.Fatalf("retry of a pending Resume past the stop time = %v, want ErrPastDeadline", err) } failed := opRow{id: "op-1", status: "failed", prepared: 1} e2.wantResume(JobResuming, 0, []opRow{failed}, 1) if _, err := e2.resume("op-1"); !errors.Is(err, isolatedjob.ErrConflict) { t.Fatalf("retry of a failed operation = %v, want ErrConflict", err) } e2.wantResume(JobResuming, 0, []opRow{failed}, 1) // Admission does not reopen past the stop time either. e3 := runningJob(t) g := e3.drain() stop = e3.stopCols("att-1").stop e3.clk.AdvanceMono(time.Duration(T(stop) - e3.store.Clock().Now())) if err := e3.c.Reopen(e3.ctx, "inst-1", instKey, "att-1", g); !errors.Is(err, ErrPastDeadline) { t.Fatalf("Reopen at the stop time = %v, want ErrPastDeadline", err) } if p := e3.pauseCols("att-1"); p.state != JobDraining { t.Fatalf("after a refused Reopen the job is %q, want draining", p.state) } } func TestResumeRefreshPastDeadline(t *testing.T) { t.Parallel() e := runningJob(t) 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) } stop := e.stopCols("att-1").stop e.clk.AdvanceMono(time.Duration(T(stop) - e.store.Clock().Now())) e.refresh() e.wantResume(JobSuspended, 0, []opRow{{id: "op-1", status: "failed", prepared: 1}}, 1) e.fake.Tick() e.refresh() e.wantResume(JobSuspended, 0, []opRow{{id: "op-1", status: "failed", prepared: 1}}, 1) } func TestResumeRestartRebasesFirst(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() e.probe(&resumeProbe{after: func() { e.fake.Tick() // the VM runs before the controller can commit if err := e.store.Close(); err != nil { t.Errorf("Close = %v", err) } }}) if _, err := e.resume("op-1"); err == nil { t.Fatal("Resume across a crash = nil error") } // Down for 2 h with the wall clock stopped: the restored controller // time knows nothing of it, the provider's age does. e.clk.AdvanceMono(2 * time.Hour) e.restart() before := e.stopCols("att-1") e.refresh() // re-base only: no commit against the stale stop time e.wantResume(JobResuming, 0, []opRow{pending("op-1", 1)}, 1) if after := e.stopCols("att-1"); after.stop >= before.stop || T(after.stop) > e.store.Clock().Now() { t.Fatalf("stop time %d after the first refresh (was %d, now %d); want it re-based into the past", after.stop, before.stop, e.store.Clock().Now()) } e.refresh() // past the re-based stop time: the operation fails e.wantResume(JobRunning, 0, []opRow{{id: "op-1", status: "failed", prepared: 1}}, 1) } func TestResumeDeadlineDuringProviderCall(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() e.probe(&resumeProbe{after: func() { stop := e.stopCols("att-1").stop e.clk.AdvanceMono(time.Duration(T(stop) - e.store.Clock().Now())) e.fake.Tick() // the VM runs, but only once the stop time has come }}) if ep, err := e.resume("op-1"); !errors.Is(err, ErrPastDeadline) || ep != 0 { t.Fatalf("Resume whose provider call crossed the stop time = (%d, %v), want (0, ErrPastDeadline)", ep, err) } e.wantResume(JobRunning, 0, []opRow{{id: "op-1", status: "failed", prepared: 1}}, 1) } func TestResumeLiveReadClearsNotFound(t *testing.T) { t.Parallel() e := runningJob(t) flaky := ¬FoundOnce{Fake: e.fake} e.run = flaky e.newController() e.suspendJob() if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume = %v, want ErrResumePending", err) } flaky.n = 1 // a stale not-found e.refresh() if s := e.stopCols("att-1"); !s.notFoundSince.Valid { t.Fatal("no first not-found recorded") } // The retry reads the VM live (still suspended): the not-found is void. if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("retry = %v, want ErrResumePending", err) } if s := e.stopCols("att-1"); s.notFoundSince.Valid || s.state != JobResuming { t.Fatalf("after a live read: not-found since %v, state %q; want cleared, resuming", s.notFoundSince, s.state) } e.clk.AdvanceMono(NotFoundConfirm + time.Second) flaky.n = 1 // another stale not-found e.refresh() if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s from two not-founds with a live read between them", s.proof.String) } e.audit() // a fresh passing network audit, so only the replacement rule can refuse if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) { t.Fatalf("replacement of att-1 = %v, want ErrReplacementLive", err) } } // TestResumeFailedByProof: every way the job gets stop proof while a resume // is pending fails the operation with the proof, keeps its row, leaves the // epoch, and sends no further resume. func TestResumeFailedByProof(t *testing.T) { t.Parallel() for _, tc := range []struct { name string end func(t *testing.T, e *launchEnv, ref isolatedjob.Ref) }{ {"the VM ends on its own", func(t *testing.T, e *launchEnv, ref isolatedjob.Ref) { if err := e.fake.Stop(e.ctx, ref, "provider ended it"); err != nil { t.Fatal(err) } e.fake.Tick() e.refresh() }}, {"the VM is gone, confirmed", func(t *testing.T, e *launchEnv, ref isolatedjob.Ref) { e.fake.Vanish(ref) e.refresh() e.clk.AdvanceMono(NotFoundConfirm + time.Second) e.refresh() }}, {"the instance stops it", func(t *testing.T, e *launchEnv, ref isolatedjob.Ref) { 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.fake.Tick() if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil { t.Fatalf("Stop once stopped = %v, want proof", err) } }}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() e := runningJob(t) e.suspendJob() e.fake.Inject(isolatedjob.OpResume, isolatedjob.FaultLostReply) if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) { t.Fatalf("Resume with a lost reply = %v, want ErrResumePending", err) } v, err := e.c.Get(e.ctx, "inst-1", "att-1") if err != nil { t.Fatal(err) } tc.end(t, e, v.VMRef) failed := []opRow{{id: "op-1", status: "failed", prepared: 1}} e.wantResume(JobStopped, 0, failed, 1) if !e.stopCols("att-1").proof.Valid { t.Fatal("no stop proof") } e.refresh() if _, err := e.resume("op-1"); !errors.Is(err, isolatedjob.ErrConflict) { t.Fatalf("retry after proof = %v, want ErrConflict", err) } e.wantResume(JobStopped, 0, failed, 1) }) } }