package hostedctl import ( "bytes" "context" "database/sql" "encoding/json" "errors" "fmt" "log/slog" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" ) const ( imgA = isolatedjob.ImageDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") imgB = isolatedjob.ImageDigest("sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") imgOther = isolatedjob.ImageDigest("sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc") // testCode is the instance code every test request carries. It must // never appear in an audit row, an error or a JobView. testCode = "code-SECRET-4f2a9c" ) var ( instKey = hostedwire.VerifyKey{Role: hostedwire.RoleInstance} opKey = hostedwire.VerifyKey{Role: hostedwire.RoleOperator} ) // launchEnv is one controller over a fresh store and a fake provider, with a // passing network audit just run. type launchEnv struct { t *testing.T ctx context.Context path string clk *isolatedjobtest.FakeClock gc *gateClock // the store's clock: clk, with a signal a test can arm fake *isolatedjob.Fake run isolatedjob.Runner // what the controller calls; the fake unless a test wraps it cfg Config store *Store c *Controller logs *syncBuffer // every controller's Deps.Log, as text (logs_test.go) } func newLaunchEnv(t *testing.T) *launchEnv { t.Helper() clk := isolatedjobtest.NewFakeClock(testWall) fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits()) e := &launchEnv{ t: t, ctx: context.Background(), path: filepath.Join(t.TempDir(), "hosted.db"), clk: clk, gc: &gateClock{FakeClock: clk}, fake: fake, run: fake, cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true, imgB: true}, ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint}, } e.store = openStore(t, e.path, e.gc) e.newController() e.audit() return e } // gateClock is the test clock with one extra: after arm, the next Mono call // reads the time and then closes the returned channel, so a test learns that // a goroutine has just read the clock. type gateClock struct { *isolatedjobtest.FakeClock mu sync.Mutex armed chan struct{} } func (g *gateClock) arm() <-chan struct{} { g.mu.Lock() defer g.mu.Unlock() g.armed = make(chan struct{}) return g.armed } func (g *gateClock) Mono() time.Duration { d := g.FakeClock.Mono() g.mu.Lock() defer g.mu.Unlock() if g.armed != nil { close(g.armed) g.armed = nil } return d } // newController builds a controller over e.store with e.cfg and e.run. It // has no network audit until e.audit runs. func (e *launchEnv) newController() { e.t.Helper() if e.logs == nil { e.logs = &syncBuffer{} } c, err := New(e.cfg, Deps{Store: e.store, Runner: e.run, Auditor: e.fake, Alerter: &recordingAlerter{}, Log: slog.New(slog.NewTextHandler(e.logs, nil))}) if err != nil { e.t.Fatalf("New = %v", err) } e.c = c } // audit runs the network audit and wants it to pass. func (e *launchEnv) audit() { e.t.Helper() if err := e.c.RunAudit(e.ctx); err != nil { e.t.Fatalf("RunAudit = %v, want a pass", err) } } // reopen closes the store, as a controller that exits, then opens it again // and builds a new controller over the same fake provider. func (e *launchEnv) reopen() { e.t.Helper() if err := e.store.Close(); err != nil { e.t.Fatalf("Close = %v", err) } e.store = openStore(e.t, e.path, e.gc) e.newController() } func (e *launchEnv) exec(query string, args ...any) { e.t.Helper() if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error { _, err := tx.ExecContext(e.ctx, query, args...) return err }); err != nil { e.t.Fatalf("%s = %v", query, err) } } // job reads one job row; ok is false when there is none. func (e *launchEnv) job(attempt string) (jobRow, bool) { e.t.Helper() var j jobRow var found bool if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error { var err error j, found, err = loadJob(e.ctx, tx, attempt) return err }); err != nil { e.t.Fatalf("loadJob(%s) = %v", attempt, err) } return j, found } func (e *launchEnv) jobCount() int { e.t.Helper() var n int if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(e.ctx, `SELECT count(*) FROM jobs`).Scan(&n) }); err != nil { e.t.Fatal(err) } return n } // noCodeInAudit fails the test when any audit row holds the instance code. func (e *launchEnv) noCodeInAudit() { e.t.Helper() for _, a := range auditRows(e.t, e.store) { if strings.Contains(string(a.Actor)+a.Account+a.Task+a.Attempt+a.Action+a.Reason, testCode) { e.t.Fatalf("audit row %+v holds the instance code", a) } } } // lastAudit returns the newest audit row. func (e *launchEnv) lastAudit() Audit { e.t.Helper() rows := auditRows(e.t, e.store) if len(rows) == 0 { e.t.Fatal("no audit rows") } return rows[len(rows)-1] } func request(attempt string) LaunchRequest { return LaunchRequest{ AttemptID: attempt, TaskID: "task-1", Account: "acct-1", Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetime: 2 * time.Hour, InstanceCode: testCode, } } // intentProbe wraps the fake provider. At each Launch it reads the job row // for the attempt from the store in a helper goroutine, as the provider is // called. If the read has not finished after 2 s, something holds the store // across the provider call: the probe marks the call blocked and returns an // error at once, so the caller can unwind and release the store. join then // waits for every helper. type intentProbe struct { *isolatedjob.Fake store *Store mu sync.Mutex seen []*probeSeen } type probeSeen struct { spec isolatedjob.LaunchSpec row jobRow found bool err error blocked bool done chan struct{} } var errProbeBlocked = errors.New("probe: the store was held across the provider call") func (p *intentProbe) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { got := &probeSeen{spec: s, done: make(chan struct{})} p.mu.Lock() p.seen = append(p.seen, got) p.mu.Unlock() go func() { defer close(got.done) got.err = p.store.Tx(context.Background(), func(tx *sql.Tx) error { var err error got.row, got.found, err = loadJob(context.Background(), tx, s.AttemptID) return err }) }() select { case <-got.done: case <-time.After(2 * time.Second): got.blocked = true return "", errProbeBlocked } return p.Fake.Launch(ctx, s) } // join waits for every read the probe started and returns what each saw. // Call it after the probed call has returned; nothing then holds the store. func (p *intentProbe) join(t *testing.T) []*probeSeen { t.Helper() p.mu.Lock() seen := append([]*probeSeen(nil), p.seen...) p.mu.Unlock() for _, g := range seen { select { case <-g.done: case <-time.After(5 * time.Second): t.Fatal("a probe read of the store is still blocked after the launch returned") } } return seen } func TestLaunchSavesIntentBeforeProvider(t *testing.T) { e := newLaunchEnv(t) probe := &intentProbe{Fake: e.fake, store: e.store} e.run = probe e.newController() e.audit() e.clk.AdvanceMono(3 * time.Minute) launchedAt := e.store.Clock().Now() q := request("att-1") v, err := e.c.Launch(e.ctx, "inst-1", instKey, q) all := probe.join(t) for i, g := range all { if g.blocked { t.Fatalf("provider call %d: a store read waited 2 s; a transaction is held across the provider call", i) } if g.err != nil { t.Fatalf("provider call %d: reading the store = %v", i, g.err) } if !g.found { t.Fatalf("provider call %d: the provider was called before the launch intent was saved", i) } } if err != nil { t.Fatalf("Launch = %v", err) } if len(all) != 1 { t.Fatalf("provider launches = %d, want 1", len(all)) } seen := all[0] r := seen.row if r.state != JobWaiting || r.ref.Valid || r.actor != "inst-1" || r.task != "task-1" || r.account != "acct-1" { t.Fatalf("intent during the provider call = state %q ref %v actor %q task %q account %q, want waiting, no ref, inst-1, task-1, acct-1", r.state, r.ref, r.actor, r.task, r.account) } saved, err := decodeSpec(r.specJSON, "att-1") if err != nil { t.Fatalf("decode saved spec = %v", err) } if saved.AttemptID != seen.spec.AttemptID || saved.Image != seen.spec.Image || saved.Size != seen.spec.Size || saved.MaxLifetime != seen.spec.MaxLifetime || !bytes.Equal(saved.Bootstrap, seen.spec.Bootstrap) { t.Fatalf("saved spec %+v differs from the one sent %+v", saved, seen.spec) } var boot hostedwire.Bootstrap if err := json.Unmarshal(seen.spec.Bootstrap, &boot); err != nil { t.Fatalf("bootstrap is not JSON: %v", err) } if boot != (hostedwire.Bootstrap{Version: 1, LaunchID: v.LaunchID, InstanceCode: testCode}) || len(v.LaunchID) < 26 { t.Fatalf("bootstrap = %+v, want version 1, launch ID %q (26+ characters) and the instance code", boot, v.LaunchID) } wantDeadline, wantDrain, wantStop := Deadlines(launchedAt, 2*time.Hour) if T(r.launchedT) != launchedAt || T(r.deadlineT) != wantDeadline || T(r.drainT) != wantDrain || T(r.stopT) != wantStop { t.Fatalf("intent times = launched %d deadline %d drain %d stop %d, want %d %d %d %d", r.launchedT, r.deadlineT, r.drainT, r.stopT, launchedAt, wantDeadline, wantDrain, wantStop) } after, _ := e.job("att-1") if v.State != JobStarting || v.VMRef == "" || after.state != JobStarting || isolatedjob.Ref(after.ref.String) != v.VMRef { t.Fatalf("after Launch: view %+v, row state %q ref %v; want starting with the saved ref", v, after.state, after.ref) } if v.DeadlineIn != 2*time.Hour || v.DrainIn != 75*time.Minute || v.StopIn != 110*time.Minute { t.Fatalf("view countdowns = %v %v %v, want 2h 1h15m 1h50m", v.DeadlineIn, v.DrainIn, v.StopIn) } if strings.Contains(strings.Join([]string{v.AttemptID, v.LaunchID, v.State, string(v.VMRef)}, " "), testCode) { t.Fatalf("view %+v holds the instance code", v) } e.noCodeInAudit() } func TestLaunchIdempotentOnAttempt(t *testing.T) { e := newLaunchEnv(t) first, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) if err != nil { t.Fatalf("first Launch = %v", err) } e.clk.AdvanceMono(10 * time.Minute) e.audit() second, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) if err != nil { t.Fatalf("second Launch = %v", err) } if second.LaunchID != first.LaunchID || second.VMRef != first.VMRef || second.State != JobStarting { t.Fatalf("second view %+v, want the first's launch ID and ref %+v", second, first) } if second.DeadlineIn != first.DeadlineIn-10*time.Minute { t.Fatalf("second DeadlineIn = %v, want %v: deadlines never move", second.DeadlineIn, first.DeadlineIn-10*time.Minute) } if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay = %v", err) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 { t.Fatalf("provider launches = %d, want 1", n) } if n := e.jobCount(); n != 1 { t.Fatalf("job rows = %d, want 1", n) } if got := e.lastAudit(); got.Action != actionLaunchRepeated || got.Actor != "inst-1" || got.Attempt != "att-1" { t.Fatalf("last audit = %+v, want a %s row for inst-1 att-1", got, actionLaunchRepeated) } e.noCodeInAudit() } func TestLaunchConflictOnChangedRequest(t *testing.T) { cases := []struct { name string by hostedwire.KeyID change func(*LaunchRequest) }{ {"task", "inst-1", func(q *LaunchRequest) { q.TaskID = "task-2" }}, {"account", "inst-1", func(q *LaunchRequest) { q.Account = "acct-2" }}, {"image", "inst-1", func(q *LaunchRequest) { q.Image = imgB }}, {"size", "inst-1", func(q *LaunchRequest) { q.Size = isolatedjob.SizeLarge }}, {"lifetime", "inst-1", func(q *LaunchRequest) { q.MaxLifetime = 3 * time.Hour }}, {"instance code", "inst-1", func(q *LaunchRequest) { q.InstanceCode = "code-other" }}, {"another key", "inst-2", func(*LaunchRequest) {}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) first, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) if err != nil { t.Fatalf("first Launch = %v", err) } before, _ := e.job("att-1") q := request("att-1") tc.change(&q) v, err := e.c.Launch(e.ctx, tc.by, instKey, q) if !errors.Is(err, isolatedjob.ErrConflict) || v != (JobView{}) { t.Fatalf("changed Launch = (%+v, %v), want (zero view, ErrConflict)", v, err) } if strings.Contains(err.Error(), testCode) || strings.Contains(err.Error(), "code-other") { t.Fatalf("error %q holds an instance code", err) } after, _ := e.job("att-1") if after != before || after.launchID != first.LaunchID { t.Fatalf("job changed by a conflicting launch: %+v, want %+v", after, before) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 { t.Fatalf("provider launches = %d, want 1", n) } if got := e.lastAudit(); got.Action != actionLaunchRefused || got.Actor != tc.by || got.Attempt != "att-1" { t.Fatalf("last audit = %+v, want a %s row for %s att-1", got, actionLaunchRefused, tc.by) } e.noCodeInAudit() }) } } // holdRunner wraps the fake provider and holds the first Launch call until // release is closed; later calls go straight through. type holdRunner struct { *isolatedjob.Fake once sync.Once entered chan struct{} release chan struct{} } func (h *holdRunner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { first := false h.once.Do(func() { first = true; close(h.entered) }) if first { <-h.release } return h.Fake.Launch(ctx, s) } func TestConcurrentLaunchSameAttempt(t *testing.T) { e := newLaunchEnv(t) hold := &holdRunner{Fake: e.fake, entered: make(chan struct{}), release: make(chan struct{})} e.run = hold e.newController() e.audit() const n = 20 views := make([]JobView, n) errs := make([]error, n) finished := make(chan int, n) start := make(chan struct{}) var wg sync.WaitGroup for i := range n { wg.Add(1) go func() { defer wg.Done() <-start views[i], errs[i] = e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) finished <- i }() } close(start) // The first provider call is held. Every other caller must answer from // the saved intent meanwhile, without reaching the provider. select { case <-hold.entered: case <-time.After(5 * time.Second): t.Fatal("no provider call within 5 s") } early := map[int]bool{} for range n - 1 { select { case i := <-finished: early[i] = true case <-time.After(5 * time.Second): close(hold.release) t.Fatalf("only %d of %d other launches returned while the first provider call was held", len(early), n-1) } } close(hold.release) wg.Wait() for i, err := range errs { if err != nil { t.Fatalf("Launch %d = %v", i, err) } } j, _ := e.job("att-1") for i, v := range views { if v.LaunchID != j.launchID { t.Fatalf("view %d launch ID %q, want the one intent's %q", i, v.LaunchID, j.launchID) } if early[i] && (v.State != JobWaiting || v.VMRef != "") { t.Fatalf("view %d, returned while the provider call was held = %+v, want waiting with no ref", i, v) } if !early[i] && (v.State != JobStarting || string(v.VMRef) != j.ref.String) { t.Fatalf("view %d, the launching call = %+v, want starting with the saved ref %q", i, v, j.ref.String) } } if j.state != JobStarting || !j.ref.Valid { t.Fatalf("job = state %q ref %v, want starting with a ref", j.state, j.ref) } if got := e.jobCount(); got != 1 { t.Fatalf("job rows = %d, want 1", got) } if live := e.fake.LiveByAttempt(); live["att-1"] != 1 || len(live) != 1 { t.Fatalf("live VMs = %v, want one for att-1", live) } if c := e.fake.Calls(isolatedjob.OpLaunch); c != 1 { t.Fatalf("provider launches = %d, want 1", c) } } func TestCrashBetweenLaunchAndSave(t *testing.T) { e := newLaunchEnv(t) e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply) v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) if !errors.Is(err, ErrProviderLaunch) || errors.Is(err, isolatedjob.ErrLostReply) || v != (JobView{}) { t.Fatalf("Launch with a lost reply = (%+v, %v), want (zero view, ErrProviderLaunch) with the provider's error dropped", v, err) } if live := e.fake.LiveByAttempt(); live["att-1"] != 1 { t.Fatalf("live VMs after the lost reply = %v, want one for att-1", live) } if j, ok := e.job("att-1"); !ok || j.state != JobWaiting || j.ref.Valid { t.Fatalf("job after the lost reply = %+v (found %v), want waiting with no ref", j, ok) } e.reopen() if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay before any audit = %v", err) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 { t.Fatalf("provider launches with no audit since the restart = %d, want 1", n) } e.audit() if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay = %v", err) } vms, err := e.fake.List(e.ctx) if err != nil || len(vms) != 1 { t.Fatalf("provider VMs = %v, %v; want exactly one", vms, err) } j, _ := e.job("att-1") if j.state != JobStarting || j.ref.String != string(vms[0].Ref) { t.Fatalf("job after Replay = state %q ref %v, want starting with %s", j.state, j.ref, vms[0].Ref) } if live := e.fake.LiveByAttempt(); live["att-1"] != 1 || len(live) != 1 { t.Fatalf("live VMs = %v, want one for att-1", live) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 2 { t.Fatalf("provider launches = %d, want 2 (the lost one and the replay)", n) } if got := e.lastAudit(); got.Action != actionReplayStarted || got.Actor != "" { t.Fatalf("last audit = %+v, want a %s row by the controller", got, actionReplayStarted) } e.noCodeInAudit() } // TestReplayRefusesChangedProviderConfig: a launch reply is lost, then the // controller restarts with other provider settings for the image (another // image version, say). Replay must not re-send the intent, which would ask // for a different VM under the same client token: it abandons the intent as // config_changed, with an alert and no provider call, and the VM the lost // reply made is reaped as an orphan (R29). func TestReplayRefusesChangedProviderConfig(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.lostLaunch("att-1") e.down() e.cfg.ProviderFingerprint = func(d isolatedjob.ImageDigest, s isolatedjob.Size) string { return testFingerprint(d, s) + "/v2" } e.up() e.audit() if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay = %v", err) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 { t.Fatalf("provider launches = %d, want only the lost one", n) } if j, _ := e.job("att-1"); j.state != JobAbandoned || j.ref.Valid { t.Fatalf("att-1 after Replay: state %q ref %v; want abandoned with no ref", j.state, j.ref) } if !e.hasAudit("", "att-1", actionReplayAbandoned, reasonConfigChanged) { t.Fatalf("no %s audit row naming %s", actionReplayAbandoned, reasonConfigChanged) } if a := e.alerts(AlertConfigChanged); len(a) != 1 || !strings.Contains(a[0].Detail, "att-1") { t.Fatalf("%s alerts = %+v, want one naming att-1", AlertConfigChanged, a) } e.reap() e.clk.AdvanceMono(OrphanGrace) if r := e.reap(); r.OrphansStopped != 1 || r.OrphansDeferred != 0 { t.Fatalf("pass after the grace = %+v, want the lost reply's VM stopped as an orphan", r) } e.wantStops(ref) } // TestLaunchRechecksGatesBeforeDispatch: a launch passes its gates, then // queues for transaction 1 while the audit goes stale. Once the intent is // saved it must not reach the provider. func TestLaunchRechecksGatesBeforeDispatch(t *testing.T) { e := newLaunchEnv(t) // Hold transaction admission. entered, release := make(chan struct{}), make(chan struct{}) blocker := make(chan error, 1) go func() { blocker <- e.store.Tx(e.ctx, func(*sql.Tx) error { close(entered); <-release; return nil }) }() <-entered // The launch's gate check is its first clock read; once it has read // the clock it can only go on to queue behind the held transaction. read := e.gc.arm() type result struct { v JobView err error } done := make(chan result, 1) go func() { v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) done <- result{v, err} }() select { case <-read: case <-time.After(5 * time.Second): close(release) t.Fatal("the launch did not read the clock within 5 s") } e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) // the audit goes stale while it waits close(release) if err := <-blocker; err != nil { t.Fatalf("holding transaction = %v", err) } r := <-done if n := e.fake.Calls(isolatedjob.OpLaunch); n != 0 { t.Fatalf("provider launches = %d, want 0: the audit went stale before dispatch", n) } if r.err != nil || r.v.State != JobWaiting || r.v.VMRef != "" || r.v.LaunchID == "" { t.Fatalf("Launch = (%+v, %v), want a waiting view with a launch ID and no error", r.v, r.err) } if j, ok := e.job("att-1"); !ok || j.state != JobWaiting || j.ref.Valid { t.Fatalf("job = %+v (found %v), want the intent kept, waiting, with no ref", j, ok) } if got := e.lastAudit(); got.Action != actionLaunchDeferred || got.Actor != "inst-1" || !strings.Contains(got.Reason, "network audit") { t.Fatalf("last audit = %+v, want %s for inst-1 naming the audit", got, actionLaunchDeferred) } // The kept intent launches once a fresh audit passes. e.audit() if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay = %v", err) } if j, _ := e.job("att-1"); j.state != JobStarting || !j.ref.Valid { t.Fatalf("job after Replay = state %q ref %v, want starting with a ref", j.state, j.ref) } } // TestDispatchRechecksGatesAfterMarker: dispatch passes its gates, then // waits for the store to record its dispatch marker. A gate that fails // while the marker waits must still stop the provider call: the stop time // passing abandons the intent; a failed or stale audit leaves it waiting. func TestDispatchRechecksGatesAfterMarker(t *testing.T) { t.Parallel() for _, tc := range []struct { name string invalidate func(e *launchEnv) state string }{ {"stop time passes", func(e *launchEnv) { e.clk.AdvanceMono(2 * time.Hour) }, JobAbandoned}, {"audit fails", func(e *launchEnv) { e.fake.SetAudit(isolatedjob.NetworkAudit{}, nil); _ = e.c.RunAudit(e.ctx) }, JobWaiting}, {"audit goes stale", func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) }, JobWaiting}, } { t.Run(tc.name, func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) held, release, blocker := make(chan struct{}), make(chan struct{}), make(chan error, 1) e.c.beforeMark = func() { // hold the store, so the marker's transaction queues behind it go func() { blocker <- e.store.Tx(e.ctx, func(*sql.Tx) error { close(held); <-release; return nil }) }() <-held } done := make(chan error, 1) go func() { _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); done <- err }() select { case <-held: case <-time.After(5 * time.Second): t.Fatal("dispatch did not reach its marker within 5 s") } tc.invalidate(e) close(release) if err := errors.Join(<-blocker, <-done); err != nil { t.Fatalf("Launch = %v", err) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 0 { t.Fatalf("provider launches = %d, want 0", n) } if s := e.stopCols("att-1"); s.state != tc.state || !s.lastDispatch.Valid { t.Fatalf("att-1 = %+v, want %s with its dispatch marker", s, tc.state) } }) } } // leakRunner wraps the fake provider. While fail is set, Launch returns the // error fail builds from the spec instead of launching. type leakRunner struct { *isolatedjob.Fake fail func(isolatedjob.LaunchSpec) error } func (l *leakRunner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { if l.fail != nil { return "", l.fail(s) } return l.Fake.Launch(ctx, s) } // TestLaunchProviderTextNeverReturned: a provider error whose text quotes // the bootstrap must not carry the instance code into a returned error or an // audit row, from Launch or from Replay. The isolatedjob sentinel it wraps // still matches. func TestLaunchProviderTextNeverReturned(t *testing.T) { cases := []struct { name string fail func(isolatedjob.LaunchSpec) error want error // nil: a throttle, which Launch and Replay do not return }{ {"invalid", func(s isolatedjob.LaunchSpec) error { return fmt.Errorf("ValidationException: RunHookPayload %s rejected: %w", s.Bootstrap, isolatedjob.ErrInvalid) }, isolatedjob.ErrInvalid}, {"conflict", func(s isolatedjob.LaunchSpec) error { return fmt.Errorf("IdempotentParameterMismatch for %s: %w", s.Bootstrap, isolatedjob.ErrConflict) }, isolatedjob.ErrConflict}, {"unclassified", func(s isolatedjob.LaunchSpec) error { return fmt.Errorf("InternalFailure echoing %s", s.Bootstrap) }, ErrProviderLaunch}, {"throttle", func(s isolatedjob.LaunchSpec) error { return fmt.Errorf("TooManyRequests for %s: %w", s.Bootstrap, isolatedjob.ErrThrottled) }, nil}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) leak := &leakRunner{Fake: e.fake, fail: tc.fail} e.run = leak e.newController() e.audit() check := func(path string, err error) { t.Helper() if tc.want == nil { if err != nil { t.Fatalf("%s with a throttle = %v, want nil", path, err) } } else if !errors.Is(err, tc.want) { t.Fatalf("%s = %v, want it to match %v", path, err, tc.want) } if err != nil && (strings.Contains(err.Error(), testCode) || strings.Contains(err.Error(), "launch_id")) { t.Fatalf("%s error %q carries the provider's text and the instance code", path, err) } e.noCodeInAudit() } v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) check("Launch", err) if tc.want != nil && v != (JobView{}) { t.Fatalf("Launch view = %+v, want zero with an error", v) } check("Replay", e.c.Replay(e.ctx)) if j, _ := e.job("att-1"); j.state != JobWaiting || j.ref.Valid { t.Fatalf("job = state %q ref %v, want waiting with no ref", j.state, j.ref) } }) } } func TestLaunchRefusals(t *testing.T) { // launchOld launches att-old for by and returns its ref. launchOld := func(e *launchEnv, by hostedwire.KeyID) { e.t.Helper() if _, err := e.c.Launch(e.ctx, by, instKey, request("att-old")); err != nil { e.t.Fatalf("Launch att-old = %v", err) } } proveStopped := func(e *launchEnv) { e.exec(`UPDATE jobs SET stop_proof_json = '{"state":"stopped"}' WHERE attempt_id = 'att-old'`) } replacing := func(q *LaunchRequest) { q.Replaces = "att-old" } cases := []struct { name string setup func(*launchEnv) by hostedwire.KeyID key hostedwire.VerifyKey edit func(*LaunchRequest) want error // nil: the launch goes ahead }{ {name: "flag off", setup: func(e *launchEnv) { e.cfg.Enabled = false; e.newController(); e.audit() }, want: ErrDisabled}, {name: "operator role", key: opKey, want: ErrForbidden}, {name: "no key ID", by: "-", want: ErrForbidden}, {name: "image not allowed", edit: func(q *LaunchRequest) { q.Image = imgOther }, want: ErrImageNotAllowed}, {name: "no audit yet", setup: func(e *launchEnv) { e.newController() }, want: ErrNetworkAudit}, {name: "stale audit", setup: func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) }, want: ErrNetworkAudit}, {name: "audit exactly 5 min old", setup: func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge) }}, {name: "failing audit", setup: func(e *launchEnv) { e.fake.SetAudit(isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true}, nil) if err := e.c.RunAudit(e.ctx); err == nil { e.t.Fatal("RunAudit with a route out = nil, want a failure") } }, want: ErrNetworkAudit}, {name: "audit call fails", setup: func(e *launchEnv) { e.fake.SetAudit(isolatedjob.NetworkAudit{}, errors.New("api down")) _ = e.c.RunAudit(e.ctx) }, want: ErrNetworkAudit}, {name: "empty instance code", edit: func(q *LaunchRequest) { q.InstanceCode = "" }, want: isolatedjob.ErrInvalid}, {name: "non-ASCII instance code", edit: func(q *LaunchRequest) { q.InstanceCode = testCode + "é" }, want: isolatedjob.ErrInvalid}, {name: "empty task", edit: func(q *LaunchRequest) { q.TaskID = "" }, want: isolatedjob.ErrInvalid}, {name: "lifetime within the stop margin", edit: func(q *LaunchRequest) { q.MaxLifetime = StopBefore }, want: isolatedjob.ErrInvalid}, {name: "live replaced attempt", setup: func(e *launchEnv) { launchOld(e, "inst-1") }, edit: replacing, want: ErrReplacementLive}, {name: "replaced attempt unknown", edit: replacing, want: ErrReplacementLive}, {name: "replaced attempt of another key", setup: func(e *launchEnv) { launchOld(e, "inst-2"); proveStopped(e) }, edit: replacing, want: ErrReplacementLive}, {name: "replaced attempt proven stopped", setup: func(e *launchEnv) { launchOld(e, "inst-1"); proveStopped(e) }, edit: replacing}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) if tc.setup != nil { tc.setup(e) } by, key := tc.by, tc.key if by == "" { by = "inst-1" } else if by == "-" { by = "" } if key.Role == "" { key = instKey } q := request("att-1") if tc.edit != nil { tc.edit(&q) } callsBefore, rowsBefore := e.fake.Calls(isolatedjob.OpLaunch), e.jobCount() v, err := e.c.Launch(e.ctx, by, key, q) if tc.want == nil { if err != nil || v.State != JobStarting { t.Fatalf("Launch = (%+v, %v), want it started", v, err) } return } if !errors.Is(err, tc.want) || v != (JobView{}) { t.Fatalf("Launch = (%+v, %v), want (zero view, %v)", v, err, tc.want) } if strings.Contains(err.Error(), testCode) { t.Fatalf("error %q holds the instance code", err) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != callsBefore { t.Fatalf("provider launches = %d, want %d: a refusal calls nothing", n, callsBefore) } if n := e.jobCount(); n != rowsBefore { t.Fatalf("job rows = %d, want %d: a refusal saves no intent", n, rowsBefore) } if got := e.lastAudit(); got.Action != actionLaunchRefused || got.Actor != by || got.Attempt != "att-1" { t.Fatalf("last audit = %+v, want a %s row for %q att-1", got, actionLaunchRefused, by) } e.noCodeInAudit() }) } } func TestThrottleWaitsThenReplays(t *testing.T) { e := newLaunchEnv(t) e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")) if err != nil || v.State != JobWaiting || v.VMRef != "" || v.LaunchID == "" { t.Fatalf("throttled Launch = (%+v, %v), want a waiting view with a launch ID and no error", v, err) } if live := e.fake.LiveByAttempt(); len(live) != 0 { t.Fatalf("live VMs after a throttle = %v, want none", live) } if got := e.lastAudit(); got.Action != actionLaunchThrottled { t.Fatalf("last audit = %+v, want %s", got, actionLaunchThrottled) } e.clk.AdvanceMono(time.Minute) if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay = %v", err) } j, _ := e.job("att-1") if j.state != JobStarting || !j.ref.Valid || j.launchID != v.LaunchID { t.Fatalf("job after Replay = %+v, want starting with a ref and launch ID %s", j, v.LaunchID) } if live := e.fake.LiveByAttempt(); live["att-1"] != 1 || len(live) != 1 { t.Fatalf("live VMs = %v, want one for att-1", live) } if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("second Replay = %v", err) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 2 { t.Fatalf("provider launches = %d, want 2: a saved ref is never replayed", n) } e.noCodeInAudit() } func TestThrottleThenRefusal(t *testing.T) { cases := []struct { name string refuse func(*launchEnv) restore func(*launchEnv) // nil when the refusal is permanent want string }{ {"flag off", func(e *launchEnv) { e.c.cfg.Enabled = false }, func(e *launchEnv) { e.c.cfg.Enabled = true }, JobWaiting}, {"image removed", func(e *launchEnv) { delete(e.c.cfg.Images, imgA) }, func(e *launchEnv) { e.c.cfg.Images[imgA] = true }, JobWaiting}, {"stale audit", func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) }, func(e *launchEnv) { e.audit() }, JobWaiting}, {"failing audit", func(e *launchEnv) { e.fake.SetAudit(isolatedjob.NetworkAudit{ResolverDisabled: true, RouteOutAbsent: true}, nil) _ = e.c.RunAudit(e.ctx) }, func(e *launchEnv) { e.fake.SetAudit(isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true}, nil) e.audit() }, JobWaiting}, {"stop requested", func(e *launchEnv) { e.exec(`UPDATE jobs SET stop_requested_t = ?, stop_reason = 'asked' WHERE attempt_id = 'att-1'`, int64(e.store.Clock().Now())) }, nil, JobAbandoned}, {"stop time passed", func(e *launchEnv) { e.clk.AdvanceMono(2*time.Hour - StopBefore) // exactly stop_t e.audit() }, nil, JobAbandoned}, } 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 waiting", v, err) } before, _ := e.job("att-1") tc.refuse(e) if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay = %v", err) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 { t.Fatalf("provider launches = %d, want 1: a failed gate calls nothing", n) } j, ok := e.job("att-1") if !ok || j.state != tc.want || j.ref.Valid || j.specJSON != before.specJSON || j.launchID != before.launchID { t.Fatalf("job after Replay = %+v (found %v), want it kept, %s, with no ref", j, ok, tc.want) } if tc.want == JobAbandoned { if got := e.lastAudit(); got.Action != actionReplayAbandoned || got.Attempt != "att-1" { t.Fatalf("last audit = %+v, want %s for att-1", got, actionReplayAbandoned) } // Abandoned is final: a later replay with every gate open // still calls nothing. e.audit() if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay after abandoning = %v", err) } if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 { t.Fatalf("provider launches after abandoning = %d, want 1", n) } return } // A transient refusal keeps the intent for a later replay. tc.restore(e) if err := e.c.Replay(e.ctx); err != nil { t.Fatalf("Replay once the gate passes = %v", err) } if j, _ := e.job("att-1"); j.state != JobStarting || !j.ref.Valid { t.Fatalf("job once the gate passes = state %q ref %v, want starting with a ref", j.state, j.ref) } if live := e.fake.LiveByAttempt(); live["att-1"] != 1 { t.Fatalf("live VMs = %v, want one for att-1", live) } }) } } func TestDeadlines(t *testing.T) { cases := []struct { launched T life time.Duration deadline, drain, stopTime T }{ {0, 8 * time.Hour, T(8 * time.Hour), T(7*time.Hour + 15*time.Minute), T(7*time.Hour + 50*time.Minute)}, {0, 15 * time.Minute, T(15 * time.Minute), 0, T(5 * time.Minute)}, {T(time.Hour), 15 * time.Minute, T(75 * time.Minute), T(time.Hour), T(65 * time.Minute)}, {T(time.Hour), 5 * time.Minute, T(65 * time.Minute), T(time.Hour), T(time.Hour)}, {T(time.Hour), 0, T(time.Hour), T(time.Hour), T(time.Hour)}, } for _, tc := range cases { d, dr, s := Deadlines(tc.launched, tc.life) if d != tc.deadline || dr != tc.drain || s != tc.stopTime { t.Errorf("Deadlines(%v, %v) = (%v, %v, %v), want (%v, %v, %v)", time.Duration(tc.launched), tc.life, time.Duration(d), time.Duration(dr), time.Duration(s), time.Duration(tc.deadline), time.Duration(tc.drain), time.Duration(tc.stopTime)) } } }