| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "strings" |
| 8 | "sync" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 13 | ) |
| 14 | |
| 15 | // syncBuffer is a bytes.Buffer safe for the concurrent writes of slog. |
| 16 | type syncBuffer struct { |
| 17 | mu sync.Mutex |
| 18 | b bytes.Buffer |
| 19 | } |
| 20 | |
| 21 | func (s *syncBuffer) Write(p []byte) (int, error) { |
| 22 | s.mu.Lock() |
| 23 | defer s.mu.Unlock() |
| 24 | return s.b.Write(p) |
| 25 | } |
| 26 | |
| 27 | func (s *syncBuffer) String() string { |
| 28 | s.mu.Lock() |
| 29 | defer s.mu.Unlock() |
| 30 | return s.b.String() |
| 31 | } |
| 32 | |
| 33 | // wantLog fails unless one log line holds every part. |
| 34 | func (e *launchEnv) wantLog(parts ...string) { |
| 35 | e.t.Helper() |
| 36 | all := e.logs.String() |
| 37 | for _, line := range strings.Split(all, "\n") { |
| 38 | ok := line != "" |
| 39 | for _, p := range parts { |
| 40 | ok = ok && strings.Contains(line, p) |
| 41 | } |
| 42 | if ok { |
| 43 | return |
| 44 | } |
| 45 | } |
| 46 | e.t.Fatalf("no log line holds %q; the log:\n%s", parts, all) |
| 47 | } |
| 48 | |
| 49 | // badRefs is the fake provider answering with a malformed VM ref carrying |
| 50 | // sentinel text, on Launch, Get or List as set. |
| 51 | type badRefs struct { |
| 52 | *isolatedjob.Fake |
| 53 | launch, get, list bool |
| 54 | emptyGet bool // Get answers stopped with no Ref (R38) |
| 55 | } |
| 56 | |
| 57 | const badRef = isolatedjob.Ref("vm-1 SENTINEL-secret=hunter2") |
| 58 | |
| 59 | func (b *badRefs) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { |
| 60 | ref, err := b.Fake.Launch(ctx, s) |
| 61 | if b.launch && err == nil { |
| 62 | return badRef, nil |
| 63 | } |
| 64 | return ref, err |
| 65 | } |
| 66 | |
| 67 | func (b *badRefs) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { |
| 68 | j, err := b.Fake.Get(ctx, ref) |
| 69 | if b.get && err == nil { |
| 70 | j.Ref = badRef |
| 71 | } |
| 72 | if b.emptyGet && err == nil { |
| 73 | j = isolatedjob.Job{State: isolatedjob.StateStopped} // terminal, naming no VM |
| 74 | } |
| 75 | return j, err |
| 76 | } |
| 77 | |
| 78 | func (b *badRefs) List(ctx context.Context) ([]isolatedjob.Job, error) { |
| 79 | jobs, err := b.Fake.List(ctx) |
| 80 | if b.list && err == nil { |
| 81 | jobs = append(jobs, isolatedjob.Job{Ref: badRef, State: isolatedjob.StateRunning}) |
| 82 | } |
| 83 | return jobs, err |
| 84 | } |
| 85 | |
| 86 | // TestMalformedRefsNeverStoredOrLogged (ruling R36): a runner reply whose |
| 87 | // VM ref fails Ref.Valid is refused where it enters the controller, so the |
| 88 | // ref reaches no job row, unmatched VM, audit row, log line or error. |
| 89 | func TestMalformedRefsNeverStoredOrLogged(t *testing.T) { |
| 90 | t.Parallel() |
| 91 | e := newLaunchEnv(t) |
| 92 | bad := &badRefs{Fake: e.fake, launch: true} |
| 93 | e.run = bad |
| 94 | e.newController() |
| 95 | e.audit() |
| 96 | var errs []error |
| 97 | if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err == nil { |
| 98 | t.Fatal("Launch answered with a malformed ref = nil error, want a provider failure") |
| 99 | } else { |
| 100 | errs = append(errs, err) |
| 101 | } |
| 102 | if j, _ := e.job("att-1"); j.ref.Valid || j.state != JobWaiting { |
| 103 | t.Fatalf("att-1 after a malformed launch reply: ref %v state %s, want no ref and %s", j.ref, j.state, JobWaiting) |
| 104 | } |
| 105 | |
| 106 | bad.launch, bad.get, bad.list = false, true, true |
| 107 | e.launchWith("att-2", 2*time.Hour) |
| 108 | _, err := e.c.Reap(e.ctx) |
| 109 | errs = append(errs, err, e.c.Refresh(e.ctx)) |
| 110 | if _, err := e.c.ListVMs(e.ctx); !errors.Is(err, isolatedjob.ErrIncomplete) { |
| 111 | t.Errorf("ListVMs with a malformed ref listed = %v, want ErrIncomplete", err) |
| 112 | } else { |
| 113 | errs = append(errs, err) |
| 114 | } |
| 115 | if u := e.unmatched(); len(u) != 0 { |
| 116 | t.Errorf("unmatched_vms = %v, want nothing recorded from a list holding a malformed ref", u) |
| 117 | } |
| 118 | for _, err := range errs { |
| 119 | if err != nil && strings.Contains(err.Error(), "SENTINEL") { |
| 120 | t.Errorf("error %q quotes the malformed ref", err) |
| 121 | } |
| 122 | } |
| 123 | for _, a := range auditRows(t, e.store) { |
| 124 | if strings.Contains(a.Reason, "SENTINEL") { |
| 125 | t.Errorf("audit row %+v quotes the malformed ref", a) |
| 126 | } |
| 127 | } |
| 128 | if strings.Contains(e.logs.String(), "SENTINEL") { |
| 129 | t.Errorf("the log quotes the malformed ref:\n%s", e.logs) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | // TestGetWithoutRefNeverProof (ruling R38): a Get that reports a terminal |
| 134 | // state but names no VM is refused, so no stop, refresh or reaper pass |
| 135 | // takes it as stop proof. |
| 136 | func TestGetWithoutRefNeverProof(t *testing.T) { |
| 137 | t.Parallel() |
| 138 | e := newLaunchEnv(t) |
| 139 | bad := &badRefs{Fake: e.fake} |
| 140 | e.run = bad |
| 141 | e.newController() |
| 142 | e.audit() |
| 143 | e.launchWith("att-1", 2*time.Hour) |
| 144 | e.fake.Tick() |
| 145 | bad.emptyGet = true |
| 146 | if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); err == nil { |
| 147 | t.Fatalf("Stop with a Get naming no VM = proof %+v, want none", p) |
| 148 | } |
| 149 | _ = e.c.Refresh(e.ctx) |
| 150 | _, _ = e.c.Reap(e.ctx) |
| 151 | if s := e.stopCols("att-1"); s.proof.Valid { |
| 152 | t.Fatalf("stop proof %s recorded from a Get naming no VM", s.proof.String) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // TestControllerLogs: the records the Task 17 live check reads (round 1 of |
| 157 | // its code review) appear, at info, with fixed messages and no provider text. |
| 158 | func TestControllerLogs(t *testing.T) { |
| 159 | t.Parallel() |
| 160 | t.Run("orphan stopped", func(t *testing.T) { |
| 161 | t.Parallel() |
| 162 | e := newLaunchEnv(t) |
| 163 | stray := e.plant("stray-1") |
| 164 | e.reap() |
| 165 | e.clk.AdvanceMono(OrphanGrace) |
| 166 | e.reap() |
| 167 | e.wantLog("level=INFO", `msg="hosted controller: orphan VM stopped"`, "vm_ref="+string(stray), "first_seen_ns=", "grace=10m0s", |
| 168 | "seen_before_restart=false") |
| 169 | }) |
| 170 | t.Run("orphan seen before a restart", func(t *testing.T) { |
| 171 | t.Parallel() |
| 172 | e := newLaunchEnv(t) |
| 173 | stray := e.plant("stray-1") |
| 174 | e.reap() |
| 175 | e.clk.AdvanceMono(time.Minute) |
| 176 | e.down() |
| 177 | e.up() |
| 178 | e.clk.AdvanceMono(time.Second) |
| 179 | // The first stop after the restart fails, so the one that lands |
| 180 | // comes more than the grace after the sighting: the record must |
| 181 | // still say the sighting predates the restart. |
| 182 | e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle) |
| 183 | _, _ = e.c.Reap(e.ctx) |
| 184 | e.wantLog(`msg="hosted controller: orphan VM stop call failed; sent again next pass"`, "vm_ref="+string(stray)) |
| 185 | e.clk.AdvanceMono(OrphanGrace) |
| 186 | e.reap() |
| 187 | e.wantLog(`msg="hosted controller: orphan VM stopped"`, "vm_ref="+string(stray), "seen_before_restart=true") |
| 188 | }) |
| 189 | t.Run("orphan deferred", func(t *testing.T) { |
| 190 | t.Parallel() |
| 191 | e := newLaunchEnv(t) |
| 192 | e.lostLaunch("att-1") |
| 193 | stray := e.plant("stray-1") |
| 194 | for range 20 { |
| 195 | e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) |
| 196 | } |
| 197 | _, _ = e.c.Reap(e.ctx) |
| 198 | e.clk.AdvanceMono(OrphanGrace) |
| 199 | _, _ = e.c.Reap(e.ctx) |
| 200 | e.wantLog(`msg="hosted controller: orphan VM left running for a dispatched launch intent"`, "vm_ref="+string(stray), |
| 201 | "grace=10m0s", "dispatched_intents=1") |
| 202 | }) |
| 203 | t.Run("audit failed", func(t *testing.T) { |
| 204 | t.Parallel() |
| 205 | e := newLaunchEnv(t) |
| 206 | e.fake.SetAudit(isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true}, nil) |
| 207 | _ = e.c.RunAudit(e.ctx) |
| 208 | e.wantLog(`msg="hosted controller: network audit failed; launches refused"`, "resolver_enabled") |
| 209 | e.fake.SetAudit(isolatedjob.NetworkAudit{}, errors.New("provider says secret-detail-7")) |
| 210 | _ = e.c.RunAudit(e.ctx) |
| 211 | e.wantLog(`msg="hosted controller: network audit failed; launches refused"`, "provider_read_failed") |
| 212 | if strings.Contains(e.logs.String(), "secret-detail-7") { |
| 213 | t.Fatalf("the log quotes provider error text:\n%s", e.logs) |
| 214 | } |
| 215 | }) |
| 216 | restart := func(t *testing.T, ageUnknown bool) *launchEnv { |
| 217 | e := newLaunchEnv(t) |
| 218 | e.launchWith("att-1", 2*time.Hour) |
| 219 | e.fake.Tick() |
| 220 | e.down() |
| 221 | e.clk.AdvanceMono(10 * time.Minute) |
| 222 | e.clk.SetWall(testWall.Add(10 * time.Minute)) |
| 223 | e.up() |
| 224 | e.clk.AdvanceMono(time.Second) |
| 225 | if ageUnknown { |
| 226 | e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) |
| 227 | } |
| 228 | e.refresh() |
| 229 | return e |
| 230 | } |
| 231 | t.Run("restart rebase", func(t *testing.T) { |
| 232 | t.Parallel() |
| 233 | e := restart(t, false) |
| 234 | e.wantLog(`msg="hosted controller: restart re-based a job from the provider's age"`, "attempt=att-1", "provider_age=") |
| 235 | }) |
| 236 | t.Run("restart elapsed unknown", func(t *testing.T) { |
| 237 | t.Parallel() |
| 238 | e := restart(t, true) |
| 239 | e.wantLog(`msg="hosted controller: restart stop requested, elapsed time unknown"`, "attempt=att-1", "reason=elapsed_unknown") |
| 240 | if strings.Contains(e.logs.String(), testCode) { |
| 241 | t.Fatalf("the log holds the instance code:\n%s", e.logs) |
| 242 | } |
| 243 | }) |
| 244 | } |
| 245 | |