package hostedctl import ( "bytes" "context" "errors" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/isolatedjob" ) // syncBuffer is a bytes.Buffer safe for the concurrent writes of slog. type syncBuffer struct { mu sync.Mutex b bytes.Buffer } func (s *syncBuffer) Write(p []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() return s.b.Write(p) } func (s *syncBuffer) String() string { s.mu.Lock() defer s.mu.Unlock() return s.b.String() } // wantLog fails unless one log line holds every part. func (e *launchEnv) wantLog(parts ...string) { e.t.Helper() all := e.logs.String() for _, line := range strings.Split(all, "\n") { ok := line != "" for _, p := range parts { ok = ok && strings.Contains(line, p) } if ok { return } } e.t.Fatalf("no log line holds %q; the log:\n%s", parts, all) } // badRefs is the fake provider answering with a malformed VM ref carrying // sentinel text, on Launch, Get or List as set. type badRefs struct { *isolatedjob.Fake launch, get, list bool emptyGet bool // Get answers stopped with no Ref (R38) } const badRef = isolatedjob.Ref("vm-1 SENTINEL-secret=hunter2") func (b *badRefs) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { ref, err := b.Fake.Launch(ctx, s) if b.launch && err == nil { return badRef, nil } return ref, err } func (b *badRefs) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { j, err := b.Fake.Get(ctx, ref) if b.get && err == nil { j.Ref = badRef } if b.emptyGet && err == nil { j = isolatedjob.Job{State: isolatedjob.StateStopped} // terminal, naming no VM } return j, err } func (b *badRefs) List(ctx context.Context) ([]isolatedjob.Job, error) { jobs, err := b.Fake.List(ctx) if b.list && err == nil { jobs = append(jobs, isolatedjob.Job{Ref: badRef, State: isolatedjob.StateRunning}) } return jobs, err } // TestMalformedRefsNeverStoredOrLogged (ruling R36): a runner reply whose // VM ref fails Ref.Valid is refused where it enters the controller, so the // ref reaches no job row, unmatched VM, audit row, log line or error. func TestMalformedRefsNeverStoredOrLogged(t *testing.T) { t.Parallel() e := newLaunchEnv(t) bad := &badRefs{Fake: e.fake, launch: true} e.run = bad e.newController() e.audit() var errs []error if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err == nil { t.Fatal("Launch answered with a malformed ref = nil error, want a provider failure") } else { errs = append(errs, err) } if j, _ := e.job("att-1"); j.ref.Valid || j.state != JobWaiting { t.Fatalf("att-1 after a malformed launch reply: ref %v state %s, want no ref and %s", j.ref, j.state, JobWaiting) } bad.launch, bad.get, bad.list = false, true, true e.launchWith("att-2", 2*time.Hour) _, err := e.c.Reap(e.ctx) errs = append(errs, err, e.c.Refresh(e.ctx)) if _, err := e.c.ListVMs(e.ctx); !errors.Is(err, isolatedjob.ErrIncomplete) { t.Errorf("ListVMs with a malformed ref listed = %v, want ErrIncomplete", err) } else { errs = append(errs, err) } if u := e.unmatched(); len(u) != 0 { t.Errorf("unmatched_vms = %v, want nothing recorded from a list holding a malformed ref", u) } for _, err := range errs { if err != nil && strings.Contains(err.Error(), "SENTINEL") { t.Errorf("error %q quotes the malformed ref", err) } } for _, a := range auditRows(t, e.store) { if strings.Contains(a.Reason, "SENTINEL") { t.Errorf("audit row %+v quotes the malformed ref", a) } } if strings.Contains(e.logs.String(), "SENTINEL") { t.Errorf("the log quotes the malformed ref:\n%s", e.logs) } } // TestGetWithoutRefNeverProof (ruling R38): a Get that reports a terminal // state but names no VM is refused, so no stop, refresh or reaper pass // takes it as stop proof. func TestGetWithoutRefNeverProof(t *testing.T) { t.Parallel() e := newLaunchEnv(t) bad := &badRefs{Fake: e.fake} e.run = bad e.newController() e.audit() e.launchWith("att-1", 2*time.Hour) e.fake.Tick() bad.emptyGet = true if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); err == nil { t.Fatalf("Stop with a Get naming no VM = proof %+v, want none", p) } _ = e.c.Refresh(e.ctx) _, _ = e.c.Reap(e.ctx) if s := e.stopCols("att-1"); s.proof.Valid { t.Fatalf("stop proof %s recorded from a Get naming no VM", s.proof.String) } } // TestControllerLogs: the records the Task 17 live check reads (round 1 of // its code review) appear, at info, with fixed messages and no provider text. func TestControllerLogs(t *testing.T) { t.Parallel() t.Run("orphan stopped", func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) stray := e.plant("stray-1") e.reap() e.clk.AdvanceMono(OrphanGrace) e.reap() e.wantLog("level=INFO", `msg="hosted controller: orphan VM stopped"`, "vm_ref="+string(stray), "first_seen_ns=", "grace=10m0s", "seen_before_restart=false") }) t.Run("orphan seen before a restart", func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) stray := e.plant("stray-1") e.reap() e.clk.AdvanceMono(time.Minute) e.down() e.up() e.clk.AdvanceMono(time.Second) // The first stop after the restart fails, so the one that lands // comes more than the grace after the sighting: the record must // still say the sighting predates the restart. e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle) _, _ = e.c.Reap(e.ctx) e.wantLog(`msg="hosted controller: orphan VM stop call failed; sent again next pass"`, "vm_ref="+string(stray)) e.clk.AdvanceMono(OrphanGrace) e.reap() e.wantLog(`msg="hosted controller: orphan VM stopped"`, "vm_ref="+string(stray), "seen_before_restart=true") }) t.Run("orphan deferred", func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) e.lostLaunch("att-1") stray := e.plant("stray-1") for range 20 { e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) } _, _ = e.c.Reap(e.ctx) e.clk.AdvanceMono(OrphanGrace) _, _ = e.c.Reap(e.ctx) e.wantLog(`msg="hosted controller: orphan VM left running for a dispatched launch intent"`, "vm_ref="+string(stray), "grace=10m0s", "dispatched_intents=1") }) t.Run("audit failed", func(t *testing.T) { t.Parallel() e := newLaunchEnv(t) e.fake.SetAudit(isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true}, nil) _ = e.c.RunAudit(e.ctx) e.wantLog(`msg="hosted controller: network audit failed; launches refused"`, "resolver_enabled") e.fake.SetAudit(isolatedjob.NetworkAudit{}, errors.New("provider says secret-detail-7")) _ = e.c.RunAudit(e.ctx) e.wantLog(`msg="hosted controller: network audit failed; launches refused"`, "provider_read_failed") if strings.Contains(e.logs.String(), "secret-detail-7") { t.Fatalf("the log quotes provider error text:\n%s", e.logs) } }) restart := func(t *testing.T, ageUnknown bool) *launchEnv { e := newLaunchEnv(t) e.launchWith("att-1", 2*time.Hour) e.fake.Tick() e.down() e.clk.AdvanceMono(10 * time.Minute) e.clk.SetWall(testWall.Add(10 * time.Minute)) e.up() e.clk.AdvanceMono(time.Second) if ageUnknown { e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) } e.refresh() return e } t.Run("restart rebase", func(t *testing.T) { t.Parallel() e := restart(t, false) e.wantLog(`msg="hosted controller: restart re-based a job from the provider's age"`, "attempt=att-1", "provider_age=") }) t.Run("restart elapsed unknown", func(t *testing.T) { t.Parallel() e := restart(t, true) e.wantLog(`msg="hosted controller: restart stop requested, elapsed time unknown"`, "attempt=att-1", "reason=elapsed_unknown") if strings.Contains(e.logs.String(), testCode) { t.Fatalf("the log holds the instance code:\n%s", e.logs) } }) }