package hostedctl import ( "context" "database/sql" "encoding/json" "errors" "fmt" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) // stopCols are the jobs columns stop and refresh write. type stopCols struct { state string requested, notFoundSince sql.NullInt64 lastDispatch sql.NullInt64 reason, proof sql.NullString launched, deadline, drain, stop int64 } func (e *launchEnv) stopCols(attempt string) stopCols { e.t.Helper() var s stopCols if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(e.ctx, `SELECT state, stop_requested_t, notfound_since_t, last_dispatch_t, stop_reason, stop_proof_json, launched_t, deadline_t, drain_t, stop_t FROM jobs WHERE attempt_id = ?`, attempt).Scan( &s.state, &s.requested, &s.notFoundSince, &s.lastDispatch, &s.reason, &s.proof, &s.launched, &s.deadline, &s.drain, &s.stop) }); err != nil { e.t.Fatalf("read stop columns of %s = %v", attempt, err) } return s } // wireProof decodes the stored proof of attempt, which must be there. func (e *launchEnv) wireProof(attempt string) hostedwire.StopProof { e.t.Helper() s := e.stopCols(attempt) if !s.proof.Valid { e.t.Fatalf("%s has no stored stop proof", attempt) } var p hostedwire.StopProof if err := json.Unmarshal([]byte(s.proof.String), &p); err != nil { e.t.Fatalf("stored proof %q is not the wire shape: %v", s.proof.String, err) } return p } // launchWith launches attempt for inst-1 with lifetime life and returns its // Ref. func (e *launchEnv) launchWith(attempt string, life time.Duration) isolatedjob.Ref { e.t.Helper() q := request(attempt) q.MaxLifetime = life v, err := e.c.Launch(e.ctx, "inst-1", instKey, q) if err != nil || v.VMRef == "" { e.t.Fatalf("Launch(%s) = (%+v, %v), want a started VM", attempt, v, err) } return v.VMRef } // replace launches attempt as the replacement of replaced, for inst-1. func (e *launchEnv) replace(attempt, replaced string) error { e.t.Helper() q := request(attempt) q.Replaces = replaced _, err := e.c.Launch(e.ctx, "inst-1", instKey, q) return err } // down closes the store, as a controller that exits. up opens it again and // builds a new controller over the same fake provider. Time the test moves // between the two is downtime. func (e *launchEnv) down() { e.t.Helper() if err := e.store.Close(); err != nil { e.t.Fatalf("Close = %v", err) } } func (e *launchEnv) up() { e.t.Helper() e.store = openStore(e.t, e.path, e.clk) e.newController() if !e.store.Restarted() { e.t.Fatal("Restarted() = false after a restart") } } func (e *launchEnv) refresh() { e.t.Helper() if err := e.c.Refresh(e.ctx); err != nil { e.t.Fatalf("Refresh = %v", err) } } func (e *launchEnv) hasAudit(actor hostedwire.KeyID, attempt, action, reasonPart string) bool { e.t.Helper() for _, a := range auditRows(e.t, e.store) { if a.Actor == actor && a.Attempt == attempt && a.Action == action && strings.Contains(a.Reason, reasonPart) { return true } } return false } // stopProbe wraps the fake provider. At each Stop, Get and List it reads // the store from another goroutine, as the provider is called, the way // intentProbe does: a read still blocked after 2 s means a transaction is // held across the provider call, and the call then fails with // errProbeBlocked instead of hanging. join waits for every read. type stopProbe struct { *isolatedjob.Fake store *Store mu sync.Mutex ops []isolatedjob.Op reads []*probeRead } type probeRead struct { op isolatedjob.Op requested sql.NullInt64 // the job's stop_requested_t, at Stop and Get reason sql.NullString // the job's stop_reason, at Stop and Get err error blocked bool done chan struct{} } // read starts the store read for op on ref ("" for List) and reports // whether it finished within 2 s. func (p *stopProbe) read(op isolatedjob.Op, ref isolatedjob.Ref) bool { r := &probeRead{op: op, done: make(chan struct{})} p.mu.Lock() p.ops = append(p.ops, op) p.reads = append(p.reads, r) p.mu.Unlock() go func() { defer close(r.done) ctx := context.Background() r.err = p.store.Tx(ctx, func(tx *sql.Tx) error { if ref == "" { var n int return tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs`).Scan(&n) } return tx.QueryRowContext(ctx, `SELECT stop_requested_t, stop_reason FROM jobs WHERE vm_ref = ?`, string(ref)).Scan(&r.requested, &r.reason) }) }() select { case <-r.done: return true case <-time.After(2 * time.Second): r.blocked = true return false } } func (p *stopProbe) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error { if !p.read(isolatedjob.OpStop, ref) { return errProbeBlocked } return p.Fake.Stop(ctx, ref, reason) } func (p *stopProbe) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { if !p.read(isolatedjob.OpGet, ref) { return isolatedjob.Job{}, errProbeBlocked } return p.Fake.Get(ctx, ref) } func (p *stopProbe) List(ctx context.Context) ([]isolatedjob.Job, error) { if !p.read(isolatedjob.OpList, "") { return nil, errProbeBlocked } return p.Fake.List(ctx) } // join waits for every read the probe started and fails the test when one // was blocked or failed. Call it after the probed calls have returned. func (p *stopProbe) join(t *testing.T) []*probeRead { t.Helper() p.mu.Lock() reads := append([]*probeRead(nil), p.reads...) p.mu.Unlock() for i, r := range reads { select { case <-r.done: case <-time.After(5 * time.Second): t.Fatalf("probe read %d (%s) is still blocked after the call returned", i, r.op) } if r.blocked { t.Fatalf("provider %s (call %d): a store read waited 2 s; a transaction is held across the provider call", r.op, i) } if r.err != nil { t.Fatalf("provider %s (call %d): reading the store = %v", r.op, i, r.err) } } return reads } func TestStopRecordsRequestBeforeProvider(t *testing.T) { t.Parallel() e := newLaunchEnv(t) probe := &stopProbe{Fake: e.fake, store: e.store} e.run = probe e.newController() e.audit() e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.clk.AdvanceMono(7 * time.Minute) asked := e.store.Clock().Now() _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done") reads := probe.join(t) if !errors.Is(err, ErrStopPending) { t.Fatalf("Stop of a running VM = %v, want ErrStopPending (it is only stopping)", err) } if len(reads) != 2 || reads[0].op != isolatedjob.OpStop || reads[1].op != isolatedjob.OpGet { t.Fatalf("provider calls = %v, want stop then get", probe.ops) } for _, r := range reads { if !r.requested.Valid || T(r.requested.Int64) != asked || r.reason.String != "task done" { t.Fatalf("at the provider %s: stop_requested_t %v, reason %v; want %d and \"task done\" already saved", r.op, r.requested, r.reason, asked) } } if s := e.stopCols("att-1"); s.proof.Valid || s.state != JobStopping { t.Fatalf("after Stop: state %q, proof %v; want stopping and no proof", s.state, s.proof) } if !e.hasAudit("inst-1", "att-1", actionStopRequested, "task done") { t.Fatal("no stop_requested audit row by inst-1") } // Refresh's Get and its List for a job with no Ref run outside any // transaction too. e.audit() e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-2")); err != nil { t.Fatalf("throttled Launch = %v", err) } if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-2", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err) } e.clk.AdvanceMono(3 * time.Minute) err = e.c.Refresh(e.ctx) reads = probe.join(t) if err != nil { t.Fatalf("Refresh = %v", err) } var ops []isolatedjob.Op for _, r := range reads[2:] { ops = append(ops, r.op) } if !slices.Contains(ops, isolatedjob.OpGet) || !slices.Contains(ops, isolatedjob.OpList) { t.Fatalf("Refresh provider calls = %v, want a get and a list", ops) } } func TestStopProofNeedsTerminalState(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() before := e.stopCols("att-1") if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop while the VM is stopping = %v, want ErrStopPending", err) } if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("a stopping VM gave proof %s", s.proof.String) } if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) { t.Fatalf("replacement while the VM is stopping = %v, want ErrReplacementLive", err) } e.fake.Tick() // stopping to stopped e.clk.AdvanceMono(time.Minute) at := e.store.Clock().Now() p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "again") if err != nil { t.Fatalf("Stop of a stopped VM = %v, want proof", err) } want := StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: at} if p != want { t.Fatalf("proof = %+v, want %+v", p, want) } if w := e.wireProof("att-1"); w != (hostedwire.StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: time.Duration(at)}) { t.Fatalf("stored proof = %+v, want the wire shape of %+v", w, want) } s := e.stopCols("att-1") if s.state != JobStopped || s.reason.String != "task done" || s.stop != before.stop || s.deadline != before.deadline { t.Fatalf("after proof: state %q reason %v stop_t %d deadline_t %d; want stopped, the first reason, times %d %d unchanged", s.state, s.reason, s.stop, s.deadline, before.stop, before.deadline) } stops, gets := e.fake.Calls(isolatedjob.OpStop), e.fake.Calls(isolatedjob.OpGet) again, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "once more") if err != nil || again != p { t.Fatalf("Stop of a proven job = (%+v, %v), want the stored proof %+v", again, err, p) } if e.fake.Calls(isolatedjob.OpStop) != stops || e.fake.Calls(isolatedjob.OpGet) != gets { t.Fatal("Stop of a proven job called the provider") } if err := e.replace("att-2", "att-1"); err != nil { t.Fatalf("replacement after proof = %v", err) } if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.State != JobStopped || v.VMRef != ref { t.Fatalf("Get after proof = (%+v, %v), want stopped with ref %s", v, err, ref) } } func TestUnknownStateIsNeverProof(t *testing.T) { t.Parallel() e := newLaunchEnv(t) e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStateUnknown) { t.Fatalf("Stop with the provider state unknown = %v, want ErrStateUnknown", err) } if s := e.stopCols("att-1"); s.proof.Valid || s.state == JobStopped { t.Fatalf("unknown state gave state %q, proof %v", s.state, s.proof) } if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) { t.Fatalf("replacement after an unknown state = %v, want ErrReplacementLive", err) } // The VM has really stopped, but the provider still reports unknown. e.fake.Tick() stateBefore := e.stopCols("att-1").state e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState) e.refresh() if s := e.stopCols("att-1"); s.proof.Valid || s.state != stateBefore { t.Fatalf("Refresh with an unknown state: state %q (was %q), proof %v; want it left alone", s.state, stateBefore, s.proof) } e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStateUnknown) { t.Fatalf("second Stop with the state unknown = %v, want ErrStateUnknown", err) } if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) { t.Fatalf("replacement after a second unknown state = %v, want ErrReplacementLive", err) } // Once the provider answers, the proof comes. if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.State != isolatedjob.StateStopped { t.Fatalf("Stop once the state is known = (%+v, %v), want stopped proof", p, err) } } func TestLostStopReplyRetries(t *testing.T) { t.Parallel() t.Run("reply lost after the stop took effect", func(t *testing.T) { e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultLostReply) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, isolatedjob.ErrLostReply) { t.Fatalf("Stop with a lost reply = %v, want the provider error", err) } if s := e.stopCols("att-1"); !s.requested.Valid || s.proof.Valid { t.Fatalf("after a lost reply: requested %v proof %v; want the request kept and no proof", s.requested, s.proof) } if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) { t.Fatalf("replacement after a lost stop reply = %v, want ErrReplacementLive", err) } e.fake.Tick() p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done") if err != nil || p.VMRef != ref || p.State != isolatedjob.StateStopped { t.Fatalf("retried Stop = (%+v, %v), want proof for %s", p, err, ref) } if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref, ref}) { t.Fatalf("provider stops = %v, want the stop sent again", got) } }) t.Run("stop throttled, sent again by Refresh", func(t *testing.T) { e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, isolatedjob.ErrThrottled) { t.Fatalf("throttled Stop = %v, want the provider error", err) } if live := e.fake.LiveByAttempt()["att-1"]; live != 1 { t.Fatalf("live VMs after a throttled stop = %d, want 1", live) } e.refresh() // the VM is still running: Refresh sends the stop again if got := e.fake.StopsIssued(); len(got) != 2 { t.Fatalf("provider stops after Refresh = %v, want a second one", got) } e.fake.Tick() e.fake.Tick() e.refresh() w := e.wireProof("att-1") if w.VMRef != ref || w.State != isolatedjob.StateStopped { t.Fatalf("proof after Refresh = %+v, want stopped %s", w, ref) } if s := e.stopCols("att-1"); s.reason.String != "task done" { t.Fatalf("stop reason = %v, want the requested one, not ended", s.reason) } }) } func TestStopOfGoneVMSucceeds(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.fake.Vanish(ref) // The provider's Get is eventually consistent: one not-found is no proof. e.clk.AdvanceMono(time.Minute) first := e.store.Clock().Now() if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on the first not-found = %v, want ErrStopPending", err) } if s := e.stopCols("att-1"); s.proof.Valid || !s.notFoundSince.Valid || T(s.notFoundSince.Int64) != first { t.Fatalf("after one not-found: proof %v notfound_since_t %v; want no proof, since %d", s.proof, s.notFoundSince, first) } if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) { t.Fatalf("replacement after one not-found = %v, want ErrReplacementLive", err) } e.clk.AdvanceMono(NotFoundConfirm - time.Nanosecond) if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on a second not-found under %v later = %v, want ErrStopPending", NotFoundConfirm, err) } if s := e.stopCols("att-1"); T(s.notFoundSince.Int64) != first { t.Fatalf("notfound_since_t moved to %d on a second not-found, want %d kept", s.notFoundSince.Int64, first) } e.clk.AdvanceMono(time.Nanosecond) at := e.store.Clock().Now() p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done") want := StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: at} if err != nil || p != want { t.Fatalf("Stop on a not-found %v after the first = (%+v, %v), want %+v", NotFoundConfirm, p, err, want) } e.audit() if err := e.replace("att-2", "att-1"); err != nil { t.Fatalf("replacement after proof = %v", err) } } // notFoundOnce wraps the fake provider; its next n Gets answer not-found // whatever the VM's state, as an eventually consistent provider can. type notFoundOnce struct { *isolatedjob.Fake n int } func (p *notFoundOnce) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { if p.n > 0 { p.n-- return isolatedjob.Job{}, fmt.Errorf("%w: %s (stale read)", isolatedjob.ErrNotFound, ref) } return p.Fake.Get(ctx, ref) } func TestStopNotFoundThenRunning(t *testing.T) { t.Parallel() e := newLaunchEnv(t) flaky := ¬FoundOnce{Fake: e.fake} e.run = flaky e.newController() e.audit() e.launchWith("att-1", 2*time.Hour) e.fake.Tick() flaky.n = 1 e.refresh() if s := e.stopCols("att-1"); s.proof.Valid || !s.notFoundSince.Valid { t.Fatalf("after one not-found: proof %v notfound_since_t %v; want no proof and a since time", s.proof, s.notFoundSince) } e.clk.AdvanceMono(NotFoundConfirm) e.refresh() // the VM shows running if s := e.stopCols("att-1"); s.proof.Valid || s.notFoundSince.Valid || s.state != JobRunning { t.Fatalf("after a running Get: state %q proof %v notfound_since_t %v; want running, no proof, since cleared", s.state, s.proof, s.notFoundSince) } // A new not-found starts a new wait; the one before the running Get no // longer counts. e.clk.AdvanceMono(time.Minute) flaky.n = 1 e.refresh() e.clk.AdvanceMono(NotFoundConfirm / 2) flaky.n = 1 e.refresh() if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s from not-founds %v apart", s.proof.String, NotFoundConfirm/2) } // After a stop request, a not-found from before it does not count. e.clk.AdvanceMono(NotFoundConfirm) asked := e.store.Clock().Now() flaky.n = 1 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop on a not-found with the earlier one before the request = %v, want ErrStopPending", err) } if s := e.stopCols("att-1"); s.proof.Valid || T(s.notFoundSince.Int64) != asked { t.Fatalf("after Stop: proof %v notfound_since_t %v; want no proof, since %d", s.proof, s.notFoundSince, asked) } e.clk.AdvanceMono(NotFoundConfirm) flaky.n = 1 if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.State != isolatedjob.StateStopped { t.Fatalf("Stop on a second not-found after the request = (%+v, %v), want proof", p, err) } } func TestStopIntentWithoutRef(t *testing.T) { t.Parallel() t.Run("lost launch reply left a VM", func(t *testing.T) { e := newLaunchEnv(t) e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply) if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err == nil { t.Fatal("Launch with a lost reply = nil error") } if e.fake.LiveByAttempt()["att-1"] != 1 { t.Fatal("the lost launch made no VM") } e.clk.AdvanceMono(time.Minute) asked := e.store.Clock().Now() if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err) } if s := e.stopCols("att-1"); s.state != JobAbandoned || T(s.requested.Int64) != asked || s.proof.Valid { t.Fatalf("after Stop: state %q requested %v proof %v; want abandoned at %d, no proof", s.state, s.requested, s.proof, asked) } launches := e.fake.Calls(isolatedjob.OpLaunch) if err := e.c.Replay(e.ctx); err != nil || e.fake.Calls(isolatedjob.OpLaunch) != launches { t.Fatalf("Replay after Stop = %v with %d launches, want none", err, e.fake.Calls(isolatedjob.OpLaunch)-launches) } // The lost reply's VM is live and no job holds its Ref: no proof. e.clk.AdvanceMono(5 * time.Minute) e.refresh() if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s while an unlinked VM is live", s.proof.String) } // The orphan reaper (Task 13) stops it; stand in for it. vms, err := e.fake.List(e.ctx) if err != nil || len(vms) != 1 { t.Fatalf("List = (%v, %v), want the one orphan", vms, err) } if err := e.fake.Stop(e.ctx, vms[0].Ref, "orphan"); err != nil { t.Fatal(err) } e.fake.Tick() e.fake.Inject(isolatedjob.OpList, isolatedjob.FaultIncompleteList) _ = e.c.Refresh(e.ctx) if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s from an incomplete list", s.proof.String) } at := e.store.Clock().Now() e.refresh() w := e.wireProof("att-1") if w != (hostedwire.StopProof{AttemptID: "att-1", State: isolatedjob.StateStopped, ObservedAt: time.Duration(at)}) { t.Fatalf("proof = %+v, want att-1, no ref, stopped, at %d", w, at) } p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "again") if err != nil || p.VMRef != "" || p.State != isolatedjob.StateStopped { t.Fatalf("Stop after proof = (%+v, %v), want the stored proof", p, err) } e.audit() if err := e.replace("att-2", "att-1"); err != nil { t.Fatalf("replacement after proof = %v", err) } }) t.Run("list must start 2 minutes after the request", func(t *testing.T) { e := newLaunchEnv(t) e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil { t.Fatalf("throttled Launch = %v", err) } if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err) } e.clk.AdvanceMono(2*time.Minute - time.Nanosecond) e.refresh() if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("proof %s from a list started under 2 minutes after the request", s.proof.String) } e.clk.AdvanceMono(time.Nanosecond) e.refresh() if w := e.wireProof("att-1"); w.VMRef != "" || w.State != isolatedjob.StateStopped { t.Fatalf("proof = %+v, want no ref and stopped", w) } }) } func TestStopRoles(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() for _, tc := range []struct { name string by hostedwire.KeyID key hostedwire.VerifyKey }{ {"another instance", "inst-2", instKey}, {"an operator", "op-1", opKey}, {"an operator key with the creator's id", "inst-1", opKey}, {"no key id", "", instKey}, } { if _, err := e.c.Stop(e.ctx, tc.by, tc.key, "att-1", "mine now"); !errors.Is(err, ErrForbidden) { t.Fatalf("Stop by %s = %v, want ErrForbidden", tc.name, err) } if a := e.lastAudit(); a.Actor != tc.by || a.Action != actionStopRefused { t.Fatalf("audit after Stop by %s = %+v, want stop_refused by %q", tc.name, a, tc.by) } } if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-9", "no such"); !errors.Is(err, ErrForbidden) { t.Fatalf("Stop of an unknown attempt = %v, want ErrForbidden", err) } if got := e.fake.StopsIssued(); len(got) != 0 { t.Fatalf("refused stops reached the provider: %v", got) } if s := e.stopCols("att-1"); s.requested.Valid { t.Fatalf("a refused stop recorded a request at %d", s.requested.Int64) } if _, err := e.c.Get(e.ctx, "inst-2", "att-1"); !errors.Is(err, ErrForbidden) { t.Fatalf("Get by another instance = %v, want ErrForbidden", err) } if a := e.lastAudit(); a.Actor != "inst-2" || a.Action != actionGetRefused { t.Fatalf("audit after Get by another instance = %+v, want get_refused", a) } if _, err := e.c.Get(e.ctx, "inst-1", "att-9"); !errors.Is(err, ErrForbidden) { t.Fatalf("Get of an unknown attempt = %v, want ErrForbidden", err) } if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.VMRef != ref || v.AttemptID != "att-1" { t.Fatalf("Get by the creator = (%+v, %v), want the job", v, err) } if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) { t.Fatalf("Stop by the creator = %v, want ErrStopPending", err) } } func TestRestartFindsVMGone(t *testing.T) { t.Parallel() e := newLaunchEnv(t) refA := e.launchWith("att-a", 2*time.Hour) refB := e.launchWith("att-b", 2*time.Hour) e.fake.Tick() // While the controller is down, A's VM disappears and B's reaches its // lifetime and stops. e.down() e.fake.Vanish(refA) e.clk.AdvanceMono(2 * time.Hour) e.fake.Tick() e.fake.Tick() e.clk.SetWall(testWall.Add(2 * time.Hour)) e.up() // A not-found at exactly OpenedAt cannot be told from one saved before // the restart, so it never counts; real time always moves after Open. e.clk.AdvanceMono(time.Second) e.refresh() // B is terminal: proof at once. A is only not found: it waits for a // second not-found NotFoundConfirm later. if s := e.stopCols("att-a"); s.proof.Valid || !s.notFoundSince.Valid { t.Fatalf("att-a after one not-found: proof %v notfound_since_t %v; want no proof yet", s.proof, s.notFoundSince) } e.audit() if err := e.replace("att-a2", "att-a"); !errors.Is(err, ErrReplacementLive) { t.Fatalf("replacement after one not-found = %v, want ErrReplacementLive", err) } e.clk.AdvanceMono(NotFoundConfirm) e.refresh() for _, c := range []struct { attempt string ref isolatedjob.Ref }{{"att-a", refA}, {"att-b", refB}} { w := e.wireProof(c.attempt) if w.VMRef != c.ref || w.State != isolatedjob.StateStopped { t.Fatalf("proof for %s = %+v, want stopped %s", c.attempt, w, c.ref) } if s := e.stopCols(c.attempt); s.state != JobStopped || s.reason.String != reasonEnded || s.requested.Valid { t.Fatalf("%s after Refresh: state %q reason %v requested %v; want stopped, ended, no request", c.attempt, s.state, s.reason, s.requested) } } if got := e.fake.StopsIssued(); len(got) != 0 { t.Fatalf("Refresh stopped %v; both VMs had already ended", got) } if err := e.replace("att-a2", "att-a"); err != nil { t.Fatalf("replacement of a VM that ended while the controller was down = %v", err) } } func TestRestartUsesProviderAge(t *testing.T) { t.Parallel() const life = 2 * time.Hour run := func(t *testing.T, downtime, wallMove time.Duration) (old, got stopCols, want T) { e := newLaunchEnv(t) e.clk.AdvanceMono(time.Minute) monoAtLaunch := e.clk.Mono() e.launchWith("att-1", life) e.fake.Tick() e.clk.AdvanceMono(20 * time.Minute) old = e.stopCols("att-1") e.down() e.clk.AdvanceMono(downtime) e.clk.SetWall(testWall.Add(wallMove)) e.up() age := e.clk.Mono() - monoAtLaunch // what the provider reports want = min(T(old.launched), e.store.Clock().Now()-T(age)) e.refresh() got = e.stopCols("att-1") wd, wdr, ws := Deadlines(want, life) if T(got.launched) != want || T(got.deadline) != wd || T(got.drain) != wdr || T(got.stop) != ws { t.Fatalf("after Refresh: launched %d deadline %d drain %d stop %d; want %d %d %d %d", got.launched, got.deadline, got.drain, got.stop, want, wd, wdr, ws) } if got.deadline > old.deadline || got.drain > old.drain || got.stop > old.stop || got.launched > old.launched { t.Fatalf("Refresh moved a time later: %+v from %+v", got, old) } if !e.hasAudit("", "att-1", actionRestartRebased, "") { t.Fatal("no restart_rebased audit row") } return old, got, want } t.Run("wall clock went back", func(t *testing.T) { old, got, _ := run(t, 40*time.Minute, -3*time.Hour) if got.launched >= old.launched || got.stop >= old.stop { t.Fatalf("40 min of downtime with the wall clock back: launched %d stop %d, want both earlier than %d %d", got.launched, got.stop, old.launched, old.stop) } }) t.Run("wall clock far ahead", func(t *testing.T) { old, got, _ := run(t, 30*time.Minute, 5*time.Hour) if got.launched != old.launched || got.stop != old.stop { t.Fatalf("wall delta beyond the provider age moved times: %+v from %+v", got, old) } }) } func TestRestartDowntimeExceedsWallDelta(t *testing.T) { t.Parallel() const life = 4 * time.Hour e := newLaunchEnv(t) ref1 := e.launchWith("att-1", life) // its age will be unknown e.clk.AdvanceMono(time.Minute) monoAt2 := e.clk.Mono() e.launchWith("att-2", life) e.fake.Tick() old2 := e.stopCols("att-2") // An orphan the reaper first sees just before the exit (ruling R1). stray := e.plant("stray-1") e.reap() strayAt := e.unmatched()[stray] // Two hours of real downtime; the wall clock reads only 5 min on. e.down() e.clk.AdvanceMono(2 * time.Hour) e.clk.SetWall(testWall.Add(5 * time.Minute)) e.up() now := e.store.Clock().Now() if got := time.Duration(now - T(old2.launched)); got > 15*time.Minute { t.Fatalf("controller time moved %v across the restart; the test needs the wall delta to understate it", got) } e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) // att-1 is read first e.refresh() want := now - T(e.clk.Mono()-monoAt2) wd, wdr, ws := Deadlines(want, life) got := e.stopCols("att-2") if T(got.launched) != want || T(got.deadline) != wd || T(got.drain) != wdr || T(got.stop) != ws { t.Fatalf("att-2 with a trusted age: launched %d deadline %d drain %d stop %d; want %d %d %d %d", got.launched, got.deadline, got.drain, got.stop, want, wd, wdr, ws) } if got.requested.Valid { t.Fatal("att-2 has a trusted age but was stopped") } s1 := e.stopCols("att-1") if !s1.requested.Valid || s1.reason.String != reasonElapsedUnknown { t.Fatalf("att-1 with no age: requested %v reason %v; want stopped with %s", s1.requested, s1.reason, reasonElapsedUnknown) } if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref1}) { t.Fatalf("provider stops = %v, want only %s", got, ref1) } // The orphan's grace is expired too: the controller time since its // sighting understates the downtime, so the first pass stops it. if got := e.store.Clock().Now() - strayAt; got >= T(OrphanGrace) { t.Fatalf("controller time since the orphan's sighting = %v; the test needs it under the grace", time.Duration(got)) } if r := e.reap(); r.OrphansStopped != 1 { t.Fatalf("first reaper pass after the restart: report %+v, want the orphan stopped", r) } if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref1, stray}) { t.Fatalf("provider stops = %v, want %s then the orphan %s", got, ref1, stray) } } func TestRestartStopsWhenElapsedUnknown(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref1 := e.launchWith("att-1", 2*time.Hour) // age unknown after the restart e.clk.AdvanceMono(time.Minute) e.launchWith("att-3", 2*time.Hour) // age known after the restart e.fake.Tick() e.down() e.clk.AdvanceMono(10 * time.Minute) e.clk.SetWall(testWall.Add(10 * time.Minute)) e.up() e.audit() e.clk.AdvanceMono(time.Minute) e.launchWith("att-2", 2*time.Hour) // launched after the restart e.fake.Tick() e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) e.refresh() s1 := e.stopCols("att-1") if !s1.requested.Valid || s1.reason.String != reasonElapsedUnknown || s1.state != JobStopping { t.Fatalf("att-1 after Refresh: requested %v reason %v state %q; want a stop for %s, stopping", s1.requested, s1.reason, s1.state, reasonElapsedUnknown) } if !e.hasAudit("", "att-1", actionStopRequested, reasonElapsedUnknown) { t.Fatal("no stop_requested audit row by the controller for att-1") } // Each job is re-based once per process: a later unknown age stops // neither the job already re-based nor one launched after the restart. for range 3 { e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) } e.refresh() if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref1}) { t.Fatalf("provider stops = %v, want only %s", got, ref1) } for _, a := range []string{"att-2", "att-3"} { if s := e.stopCols(a); s.requested.Valid { t.Fatalf("%s was stopped (%v); its elapsed time is known", a, s.reason) } } e.fake.Tick() e.refresh() if w := e.wireProof("att-1"); w.VMRef != ref1 || w.State != isolatedjob.StateStopped { t.Fatalf("proof for att-1 = %+v, want stopped %s", w, ref1) } if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown { t.Fatalf("att-1 reason after proof = %v, want %s kept", s.reason, reasonElapsedUnknown) } } // A wall clock behind the checkpoint restores T to the checkpoint itself, so // a job saved just before the exit can have launched_t equal to OpenedAt. It // still existed before the restart. func TestRestartJobAtOpenTime(t *testing.T) { t.Parallel() e := newLaunchEnv(t) ref := e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.down() e.clk.AdvanceMono(3 * time.Hour) e.clk.SetWall(testWall.Add(-time.Hour)) e.up() if s := e.stopCols("att-1"); T(s.launched) != e.store.OpenedAt() { t.Fatalf("launched_t %d, OpenedAt %d; the test needs them equal", s.launched, e.store.OpenedAt()) } e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) e.refresh() if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown { t.Fatalf("job launched at OpenedAt with no age: reason %v, want %s", s.reason, reasonElapsedUnknown) } if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref}) { t.Fatalf("provider stops = %v, want %s", got, ref) } }