oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package hostedctl
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "fmt"
8 "slices"
9 "strings"
10 "sync"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/isolatedjob"
15)
16
17// reap runs one reaper pass and wants it to succeed.
18func (e *launchEnv) reap() ReapReport {
19 e.t.Helper()
20 r, err := e.c.Reap(e.ctx)
21 if err != nil {
22 e.t.Fatalf("Reap = (%+v, %v)", r, err)
23 }
24 return r
25}
26
27// alerts returns the alerts of kind the current controller has delivered.
28func (e *launchEnv) alerts(kind string) []Alert {
29 e.t.Helper()
30 var out []Alert
31 for _, a := range e.c.alerter.(*recordingAlerter).got {
32 if a.Kind == kind {
33 out = append(out, a)
34 }
35 }
36 return out
37}
38
39// unmatched reads unmatched_vms: each Ref with its first_seen_t.
40func (e *launchEnv) unmatched() map[isolatedjob.Ref]T {
41 e.t.Helper()
42 out := map[isolatedjob.Ref]T{}
43 if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
44 rows, err := tx.QueryContext(e.ctx, `SELECT vm_ref, first_seen_t FROM unmatched_vms`)
45 if err != nil {
46 return err
47 }
48 defer rows.Close()
49 for rows.Next() {
50 var ref string
51 var at int64
52 if err := rows.Scan(&ref, &at); err != nil {
53 return err
54 }
55 out[isolatedjob.Ref(ref)] = T(at)
56 }
57 return rows.Err()
58 }); err != nil {
59 e.t.Fatalf("read unmatched_vms = %v", err)
60 }
61 return out
62}
63
64// drainMark reads attempt's drain_marked_t.
65func (e *launchEnv) drainMark(attempt string) sql.NullInt64 {
66 e.t.Helper()
67 var m sql.NullInt64
68 if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
69 return tx.QueryRowContext(e.ctx, `SELECT drain_marked_t FROM jobs WHERE attempt_id = ?`, attempt).Scan(&m)
70 }); err != nil {
71 e.t.Fatalf("read drain_marked_t of %s = %v", attempt, err)
72 }
73 return m
74}
75
76// plant adds a running VM no job owns and returns its Ref.
77func (e *launchEnv) plant(name string) isolatedjob.Ref {
78 return e.fake.Plant(isolatedjob.LaunchSpec{AttemptID: name})
79}
80
81// lostLaunch launches attempt with its provider reply lost: the provider
82// makes the VM, the intent stays waiting with no Ref. It returns the VM's
83// Ref, read from the provider.
84func (e *launchEnv) lostLaunch(attempt string) isolatedjob.Ref {
85 e.t.Helper()
86 before := map[isolatedjob.Ref]bool{}
87 vms, _ := e.fake.List(e.ctx)
88 for _, vm := range vms {
89 before[vm.Ref] = true
90 }
91 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply)
92 if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request(attempt)); !errors.Is(err, ErrProviderLaunch) {
93 e.t.Fatalf("Launch(%s) with a lost reply = %v, want ErrProviderLaunch", attempt, err)
94 }
95 if j, _ := e.job(attempt); j.state != JobWaiting || j.ref.Valid {
96 e.t.Fatalf("%s after a lost reply: state %q ref %v; want waiting with no ref", attempt, j.state, j.ref)
97 }
98 vms, _ = e.fake.List(e.ctx)
99 for _, vm := range vms {
100 if !before[vm.Ref] {
101 return vm.Ref
102 }
103 }
104 e.t.Fatalf("the lost launch of %s made no VM", attempt)
105 return ""
106}
107
108// wantStops fails the test unless the provider stops so far are want.
109func (e *launchEnv) wantStops(want ...isolatedjob.Ref) {
110 e.t.Helper()
111 if got := e.fake.StopsIssued(); !slices.Equal(got, want) {
112 e.t.Fatalf("provider stops = %v, want %v", got, want)
113 }
114}
115
116// partialList wraps the provider. While armed, List returns everything the
117// provider holds together with ErrIncomplete, as an adapter that stopped
118// paging part way might: an incomplete answer may still carry VMs, and none
119// of them may be acted on.
120type partialList struct {
121 *isolatedjob.Fake
122 mu sync.Mutex
123 armed int
124}
125
126func (p *partialList) incomplete(n int) {
127 p.mu.Lock()
128 defer p.mu.Unlock()
129 p.armed += n
130}
131
132func (p *partialList) List(ctx context.Context) ([]isolatedjob.Job, error) {
133 vms, err := p.Fake.List(ctx)
134 p.mu.Lock()
135 defer p.mu.Unlock()
136 if err == nil && p.armed > 0 {
137 p.armed--
138 return vms, fmt.Errorf("%w: test stopped paging", isolatedjob.ErrIncomplete)
139 }
140 return vms, err
141}
142
143func TestReapReplaysIntentFirst(t *testing.T) {
144 t.Parallel()
145 e := newLaunchEnv(t)
146 ref := e.lostLaunch("att-1")
147
148 r := e.reap()
149 if j, _ := e.job("att-1"); !j.ref.Valid || isolatedjob.Ref(j.ref.String) != ref || j.state != JobStarting {
150 t.Fatalf("att-1 after a pass: ref %v state %q; want %s claimed by the replay, starting", j.ref, j.state, ref)
151 }
152 if r.Replayed != 1 || r.OrphansSeen != 0 || r.OrphansStopped != 0 {
153 t.Fatalf("report %+v, want one replayed and no orphans", r)
154 }
155 if u := e.unmatched(); len(u) != 0 {
156 t.Fatalf("unmatched_vms = %v; the intent's VM was taken for an orphan before the replay", u)
157 }
158 e.wantStops()
159}
160
161func TestReapStopsOrphanAfterTenMinutes(t *testing.T) {
162 t.Parallel()
163 e := newLaunchEnv(t)
164 stray := e.plant("stray-1")
165
166 r := e.reap()
167 seen := e.store.Clock().Now()
168 if r.OrphansSeen != 1 || r.OrphansStopped != 0 {
169 t.Fatalf("first pass: report %+v, want one orphan seen and none stopped", r)
170 }
171 if u := e.unmatched(); len(u) != 1 || u[stray] != seen {
172 t.Fatalf("unmatched_vms = %v, want %s first seen at %d", u, stray, seen)
173 }
174 if !e.hasAudit("", "", actionOrphanSeen, string(stray)) {
175 t.Fatal("no orphan_seen audit row")
176 }
177
178 e.clk.AdvanceMono(OrphanGrace - time.Second)
179 if r := e.reap(); r.OrphansSeen != 1 || r.OrphansStopped != 0 {
180 t.Fatalf("at 9 min 59 s: report %+v, want the orphan seen and not stopped", r)
181 }
182 e.wantStops()
183
184 e.clk.AdvanceMono(time.Second)
185 if r := e.reap(); r.OrphansStopped != 1 {
186 t.Fatalf("at 10 min: report %+v, want the orphan stopped", r)
187 }
188 e.wantStops(stray)
189 if a := e.alerts(AlertOrphanStopped); len(a) != 1 {
190 t.Fatalf("orphan_stopped alerts = %+v, want one", a)
191 }
192 if !e.hasAudit("", "", actionOrphanStopped, string(stray)) {
193 t.Fatal("no orphan_stopped audit row")
194 }
195
196 // Stopping, then stopped: no second stop or alert, and the row goes once
197 // the VM is terminal.
198 if r := e.reap(); r.OrphansStopped != 0 {
199 t.Fatalf("pass with the orphan stopping: report %+v, want no second stop", r)
200 }
201 e.fake.Tick()
202 if r := e.reap(); r.OrphansSeen != 0 {
203 t.Fatalf("pass with the orphan stopped: report %+v, want no orphan", r)
204 }
205 if u := e.unmatched(); len(u) != 0 {
206 t.Fatalf("unmatched_vms after the orphan stopped = %v, want empty", u)
207 }
208 e.wantStops(stray)
209 if a := e.alerts(AlertOrphanStopped); len(a) != 1 {
210 t.Fatalf("orphan_stopped alerts = %+v, want still one", a)
211 }
212}
213
214func TestReapRechecksOwnership(t *testing.T) {
215 t.Parallel()
216 e := newLaunchEnv(t)
217 ref := e.lostLaunch("att-1")
218 stray := e.plant("stray-1")
219
220 // Every pass's own replay is throttled, so the intent's VM stays
221 // unlinked and looks like an orphan for the whole grace. Passes run each
222 // minute, so each one's audit keeps the next replay's gate open.
223 for i := 0; i <= 10; i++ {
224 if i > 0 {
225 e.clk.AdvanceMono(time.Minute)
226 }
227 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
228 r := e.reap()
229 if i < 10 {
230 if r.OrphansSeen != 2 || r.OrphansStopped != 0 || r.Replayed != 0 {
231 t.Fatalf("pass %d: report %+v, want two orphans seen, none stopped, none replayed", i, r)
232 }
233 continue
234 }
235 // At 10 min the recheck replays again (no throttle this time), and
236 // the intent claims its VM before anything is stopped.
237 if r.OrphansStopped != 1 || r.Replayed != 1 {
238 t.Fatalf("pass at 10 min: report %+v, want one orphan stopped and one replayed", r)
239 }
240 }
241 e.wantStops(stray)
242 if j, _ := e.job("att-1"); isolatedjob.Ref(j.ref.String) != ref || j.state != JobStarting {
243 t.Fatalf("att-1: ref %v state %q; want %s claimed, starting", j.ref, j.state, ref)
244 }
245 if e.hasAudit("", "", actionOrphanStopped, string(ref)) {
246 t.Fatal("the claimed VM was audited as a stopped orphan")
247 }
248 e.reap()
249 if u := e.unmatched(); len(u) != 1 || u[stray] != 0 {
250 t.Fatalf("unmatched_vms after the claim = %v, want only %s, first seen at 0", u, stray)
251 }
252}
253
254func TestReapStopsAbandonedIntentVM(t *testing.T) {
255 t.Parallel()
256 e := newLaunchEnv(t)
257 ref := e.lostLaunch("att-1")
258 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) {
259 t.Fatalf("Stop of an intent with no ref = %v, want ErrStopPending", err)
260 }
261 if j, _ := e.job("att-1"); j.state != JobAbandoned {
262 t.Fatalf("att-1 after Stop is %q, want abandoned", j.state)
263 }
264
265 if r := e.reap(); r.OrphansSeen != 1 {
266 t.Fatalf("first pass: report %+v, want the abandoned intent's VM seen as an orphan", r)
267 }
268 e.clk.AdvanceMono(OrphanGrace)
269 if r := e.reap(); r.OrphansStopped != 1 {
270 t.Fatalf("at 10 min: report %+v, want the abandoned intent's VM stopped", r)
271 }
272 e.wantStops(ref)
273 if s := e.stopCols("att-1"); s.proof.Valid {
274 t.Fatal("att-1 has proof while its VM is still stopping")
275 }
276
277 // Once the VM is terminal, Refresh's complete List proves the intent.
278 e.fake.Tick()
279 e.reap()
280 if w := e.wireProof("att-1"); w.VMRef != "" || w.State != isolatedjob.StateStopped {
281 t.Fatalf("proof for att-1 = %+v, want stopped with no ref", w)
282 }
283}
284
285func TestIncompleteListSkipsOrphansOnly(t *testing.T) {
286 t.Parallel()
287 e := newLaunchEnv(t)
288 pl := &partialList{Fake: e.fake}
289 e.run = pl
290 e.newController()
291 e.audit()
292 e.launchWith("att-1", DrainBefore+OrphanGrace) // drain time at 10 min
293 e.fake.Tick()
294 stray := e.plant("stray-1")
295
296 if r := e.reap(); r.OrphansSeen != 1 || r.Skipped {
297 t.Fatalf("first pass: report %+v, want one orphan seen", r)
298 }
299 seen := e.unmatched()[stray]
300
301 e.clk.AdvanceMono(OrphanGrace)
302 pl.incomplete(1)
303 r := e.reap()
304 if !r.Skipped || r.OrphansStopped != 0 {
305 t.Fatalf("pass with an incomplete list: report %+v, want orphans skipped", r)
306 }
307 e.wantStops()
308 if u := e.unmatched(); len(u) != 1 || u[stray] != seen {
309 t.Fatalf("unmatched_vms after an incomplete list = %v, want %s still first seen at %d", u, stray, seen)
310 }
311 // The other steps ran.
312 if r.Drained != 1 || !e.drainMark("att-1").Valid {
313 t.Fatalf("pass with an incomplete list: report %+v, drain mark %v; want att-1 drained", r, e.drainMark("att-1"))
314 }
315 if err := e.c.audit.check(e.store.Clock().Now()); err != nil {
316 t.Fatalf("audit after the pass = %v, want a fresh pass", err)
317 }
318
319 e.clk.AdvanceMono(time.Minute)
320 if r := e.reap(); r.Skipped || r.OrphansStopped != 1 {
321 t.Fatalf("pass with a complete list: report %+v, want the orphan stopped", r)
322 }
323 e.wantStops(stray)
324}
325
326func TestDeadlineEnforcedDuringIncompleteLists(t *testing.T) {
327 t.Parallel()
328 e := newLaunchEnv(t)
329 ref := e.launchWith("att-1", time.Hour)
330 e.fake.Tick()
331 stopT := T(e.stopCols("att-1").stop)
332 e.clk.AdvanceMono(time.Duration(stopT-e.store.Clock().Now()) - time.Minute)
333
334 for i := range 3 {
335 e.fake.Inject(isolatedjob.OpList, isolatedjob.FaultIncompleteList)
336 r := e.reap()
337 if !r.Skipped {
338 t.Fatalf("pass %d: report %+v, want orphans skipped", i, r)
339 }
340 s := e.stopCols("att-1")
341 switch i {
342 case 0:
343 if r.Stopped != 0 || s.requested.Valid {
344 t.Fatalf("a minute before the stop time: report %+v requested %v; want no stop", r, s.requested)
345 }
346 e.wantStops()
347 case 1:
348 if r.Stopped != 1 || !s.requested.Valid || s.reason.String != reasonDeadline {
349 t.Fatalf("at the stop time: report %+v requested %v reason %v; want a deadline stop", r, s.requested, s.reason)
350 }
351 e.wantStops(ref)
352 case 2:
353 if w := e.wireProof("att-1"); w.VMRef != ref || w.State != isolatedjob.StateStopped || s.state != JobStopped {
354 t.Fatalf("after the stop: proof %+v state %q; want stopped %s", w, s.state, ref)
355 }
356 }
357 e.clk.AdvanceMono(time.Minute)
358 e.fake.Tick()
359 }
360}
361
362// TestDeadlineStopBeforeSlowReplay: a pass that finds a job past its stop
363// time sends its stop before replaying intents, so a launch call that hangs
364// (up to ProviderLaunchTimeout each) never delays it (R26): a deadline stop
365// for a job with no stop request, and, for a stop already requested whose
366// provider call failed, the call again with its reason and request kept.
367func TestDeadlineStopBeforeSlowReplay(t *testing.T) {
368 t.Parallel()
369 for _, pending := range []bool{false, true} {
370 e := newLaunchEnv(t)
371 ref := e.launchWith("att-1", 2*time.Hour)
372 want, reason := []isolatedjob.Ref{ref}, reasonDeadline
373 if pending { // a stop asked for whose provider call was throttled
374 e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle)
375 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); err == nil {
376 t.Fatal("throttled Stop = nil, want its error")
377 }
378 want, reason = []isolatedjob.Ref{ref, ref}, "done"
379 }
380 before := e.stopCols("att-1")
381 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
382 q := request("att-2")
383 q.MaxLifetime = 8 * time.Hour
384 if v, err := e.c.Launch(e.ctx, "inst-1", instKey, q); err != nil || v.State != JobWaiting {
385 t.Fatalf("throttled Launch(att-2) = (%+v, %v), want a waiting intent", v, err)
386 }
387 hold := &holdRunner{Fake: e.fake, entered: make(chan struct{}), release: make(chan struct{})}
388 e.run = hold
389 e.newController()
390 e.clk.AdvanceMono(2 * time.Hour) // att-1 is past its stop time; att-2 is not
391 e.audit()
392 done := make(chan error, 1)
393 go func() { _, err := e.c.Reap(e.ctx); done <- err }()
394 select {
395 case <-hold.entered:
396 case <-time.After(5 * time.Second):
397 t.Fatal("the pass's replay never reached the provider")
398 }
399 stops := e.fake.StopsIssued()
400 close(hold.release)
401 if err := <-done; err != nil {
402 t.Fatalf("pending %v: Reap = %v", pending, err)
403 }
404 if !slices.Equal(stops, want) {
405 t.Fatalf("pending %v: provider stops while the replay's launch call hung = %v, want %v", pending, stops, want)
406 }
407 s := e.stopCols("att-1")
408 if s.reason.String != reason || (pending && s.requested != before.requested) {
409 t.Fatalf("pending %v: att-1 stop reason %v requested %v (was %v), want %s and the request kept",
410 pending, s.reason, s.requested, before.requested, reason)
411 }
412 }
413}
414
415func TestReapDrainsThenStops(t *testing.T) {
416 t.Parallel()
417 e := newLaunchEnv(t)
418 ref := e.launchWith("att-1", time.Hour)
419 e.fake.Tick()
420 s := e.stopCols("att-1")
421 to := func(at int64) { e.clk.AdvanceMono(time.Duration(T(at) - e.store.Clock().Now())) }
422
423 to(s.drain - int64(time.Second))
424 if r := e.reap(); r.Drained != 0 || e.drainMark("att-1").Valid {
425 t.Fatalf("a second before the drain time: report %+v mark %v; want no drain", r, e.drainMark("att-1"))
426 }
427 to(s.drain)
428 if r := e.reap(); r.Drained != 1 || r.Stopped != 0 {
429 t.Fatalf("at the drain time: report %+v, want one drained, none stopped", r)
430 }
431 if m := e.drainMark("att-1"); !m.Valid || m.Int64 != s.drain {
432 t.Fatalf("drain_marked_t = %v, want %d", m, s.drain)
433 }
434 if !e.hasAudit("", "att-1", actionDeadlineDrain, "") {
435 t.Fatal("no deadline_drain audit row")
436 }
437 // The mark is a notice only: no pause generation, no state change.
438 if p := e.pauseCols("att-1"); p.state != JobRunning || p.gen != 0 {
439 t.Fatalf("after the drain mark: state %q generation %d; want running, 0", p.state, p.gen)
440 }
441 if r := e.reap(); r.Drained != 0 {
442 t.Fatalf("second pass past the drain time: report %+v, want no second drain", r)
443 }
444
445 to(s.stop - int64(time.Second))
446 if r := e.reap(); r.Stopped != 0 {
447 t.Fatalf("a second before the stop time: report %+v, want no stop", r)
448 }
449 e.wantStops()
450 to(s.stop)
451 if r := e.reap(); r.Stopped != 1 {
452 t.Fatalf("at the stop time: report %+v, want one stopped", r)
453 }
454 e.wantStops(ref)
455 if c := e.stopCols("att-1"); !c.requested.Valid || c.reason.String != reasonDeadline {
456 t.Fatalf("after the deadline stop: requested %v reason %v; want %s", c.requested, c.reason, reasonDeadline)
457 }
458 if !e.hasAudit("", "att-1", actionStopRequested, reasonDeadline) {
459 t.Fatal("no stop_requested audit row by the controller")
460 }
461 if r := e.reap(); r.Stopped != 0 {
462 t.Fatalf("pass after the deadline stop: report %+v, want no second request", r)
463 }
464 e.fake.Tick()
465 e.reap()
466 if w := e.wireProof("att-1"); w.VMRef != ref || w.State != isolatedjob.StateStopped {
467 t.Fatalf("proof = %+v, want stopped %s", w, ref)
468 }
469}
470
471func TestReaperUnderRollback(t *testing.T) {
472 t.Parallel()
473 e := newLaunchEnv(t)
474 stray := e.plant("stray-1")
475 e.reap()
476 seen := e.unmatched()[stray]
477
478 // Five minutes in, the wall clock goes back two hours.
479 e.clk.AdvanceMono(5 * time.Minute)
480 e.clk.SetWall(testWall.Add(-2 * time.Hour))
481 e.reap()
482 e.clk.AdvanceMono(5*time.Minute - time.Second)
483 if r := e.reap(); r.OrphansStopped != 0 {
484 t.Fatalf("at 9 min 59 s of elapsed time: report %+v, want no stop", r)
485 }
486 e.clk.AdvanceMono(time.Second)
487 if r := e.reap(); r.OrphansStopped != 1 {
488 t.Fatalf("at 10 min of elapsed time, wall clock 2 h back: report %+v, want the orphan stopped", r)
489 }
490 e.wantStops(stray)
491 if got := e.store.Clock().Now() - seen; got != T(OrphanGrace) {
492 t.Fatalf("controller time since the sighting = %v, want %v", time.Duration(got), OrphanGrace)
493 }
494}
495
496func TestOrphanGraceExpiresAfterRestart(t *testing.T) {
497 t.Parallel()
498 e := newLaunchEnv(t)
499 stray := e.plant("stray-1")
500 ref := e.lostLaunch("att-1")
501 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle) // this pass's replay
502 if r := e.reap(); r.OrphansSeen != 2 || r.Replayed != 0 {
503 t.Fatalf("first pass: report %+v, want two orphans seen, none replayed", r)
504 }
505 seen := e.unmatched()
506
507 // 30 min of real downtime; the wall clock says 2 min.
508 e.clk.AdvanceMono(time.Minute)
509 e.down()
510 e.clk.AdvanceMono(30 * time.Minute)
511 e.clk.SetWall(testWall.Add(2 * time.Minute))
512 e.up()
513 e.clk.AdvanceMono(time.Second)
514 if got := e.store.Clock().Now() - seen[stray]; got >= T(OrphanGrace) {
515 t.Fatalf("controller time since the sighting = %v; the test needs it under the grace", time.Duration(got))
516 }
517
518 // The new controller has no audit yet. Both sightings predate the
519 // restart, so their grace has run out; the recheck still applies: the
520 // waiting intent claims its VM, and only the stray is stopped.
521 r := e.reap()
522 if r.OrphansStopped != 1 || r.Replayed != 1 {
523 t.Fatalf("first pass after the restart: report %+v, want one orphan stopped and one replayed", r)
524 }
525 e.wantStops(stray)
526 if j, _ := e.job("att-1"); isolatedjob.Ref(j.ref.String) != ref {
527 t.Fatalf("att-1 ref %v, want %s claimed by the recheck", j.ref, ref)
528 }
529
530 // A VM first seen after the restart gets the full grace.
531 late := e.plant("stray-2")
532 e.reap()
533 e.clk.AdvanceMono(OrphanGrace - time.Second)
534 e.reap()
535 e.wantStops(stray)
536 e.clk.AdvanceMono(time.Second)
537 e.reap()
538 e.wantStops(stray, late)
539}
540
541func TestUnknownStateRetriedAndAlerted(t *testing.T) {
542 t.Parallel()
543 e := newLaunchEnv(t)
544 ref1 := e.launchWith("att-1", 2*time.Hour)
545 e.launchWith("att-2", 2*time.Hour)
546 e.fake.Tick()
547 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) {
548 t.Fatalf("Stop = %v, want ErrStopPending", err)
549 }
550 e.wantStops(ref1)
551 stops := 1
552
553 // unknown is how many of att-1, att-2 (in that order) read unknown.
554 pass := func(n, unknown, wantAlerts int) {
555 t.Helper()
556 for range unknown {
557 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState)
558 }
559 e.clk.AdvanceMono(ReapInterval)
560 r := e.reap()
561 if r.Unknown != unknown {
562 t.Fatalf("pass %d: report %+v, want %d unknown", n, r, unknown)
563 }
564 if unknown > 0 {
565 stops++ // att-1 has a stop asked for: sent again
566 }
567 got := e.fake.StopsIssued()
568 if len(got) != stops || slices.ContainsFunc(got, func(r isolatedjob.Ref) bool { return r != ref1 }) {
569 t.Fatalf("pass %d: provider stops %v, want %d, all to %s", n, got, stops, ref1)
570 }
571 if a := e.alerts(AlertUnknownState); len(a) != wantAlerts {
572 t.Fatalf("pass %d: unknown_state alerts %+v, want %d", n, a, wantAlerts)
573 }
574 }
575 pass(1, 2, 0)
576 pass(2, 2, 0)
577 pass(3, 2, 2) // three in a row: one alert for each job
578 pass(4, 2, 2) // once per episode
579 pass(5, 0, 2) // a known state ends both episodes
580 pass(6, 1, 2)
581 pass(7, 1, 2)
582 pass(8, 1, 3) // a new episode for att-1
583 if !e.hasAudit("", "att-1", actionUnknownState, "") {
584 t.Fatal("no unknown_state audit row for att-1")
585 }
586}
587
588func TestFailingAuditBlocksLaunchAndAlertsOnce(t *testing.T) {
589 t.Parallel()
590 e := newLaunchEnv(t)
591 bad := isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true} // resolver on
592 good := isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true}
593
594 e.fake.SetAudit(bad, nil)
595 for i := range 2 {
596 if _, err := e.c.Reap(e.ctx); err == nil {
597 t.Fatalf("pass %d with a failing audit = nil, want the audit failure", i)
598 }
599 if a := e.alerts(AlertAuditFailed); len(a) != 1 {
600 t.Fatalf("pass %d: audit_failed alerts %+v, want one", i, a)
601 }
602 if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request(fmt.Sprintf("att-%d", i))); !errors.Is(err, ErrNetworkAudit) {
603 t.Fatalf("Launch during a failing audit = %v, want ErrNetworkAudit", err)
604 }
605 }
606 if !e.hasAudit("", "", actionNetworkAuditFailed, "resolver enabled") {
607 t.Fatal("no network_audit_failed audit row")
608 }
609
610 e.fake.SetAudit(good, nil)
611 e.reap()
612 if !e.hasAudit("", "", actionNetworkAuditPassed, "") {
613 t.Fatal("no network_audit_passed audit row when the episode ended")
614 }
615 if v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-ok")); err != nil || v.VMRef == "" {
616 t.Fatalf("Launch after the audit passed = (%+v, %v), want a VM", v, err)
617 }
618
619 e.fake.SetAudit(bad, nil)
620 if _, err := e.c.Reap(e.ctx); err == nil {
621 t.Fatal("pass with the audit failing again = nil")
622 }
623 if a := e.alerts(AlertAuditFailed); len(a) != 2 {
624 t.Fatalf("audit_failed alerts after a second episode = %+v, want two", a)
625 }
626}
627
628// An alert the Alerter refuses is kept and sent on a later pass; the
629// pass's other steps still run.
630func TestReapAlertRetriedAfterAlerterError(t *testing.T) {
631 t.Parallel()
632 e := newLaunchEnv(t)
633 rec := e.c.alerter.(*recordingAlerter)
634 stray := e.plant("stray-1")
635 e.reap()
636 e.clk.AdvanceMono(OrphanGrace)
637 down := errors.New("pager down")
638 rec.fail = down
639 r, err := e.c.Reap(e.ctx)
640 if !errors.Is(err, down) || r.OrphansStopped != 1 {
641 t.Fatalf("pass with the alerter down = (%+v, %v), want the orphan stopped and the alerter error", r, err)
642 }
643 e.wantStops(stray)
644 rec.fail = nil
645 e.reap()
646 if a := e.alerts(AlertOrphanStopped); len(a) != 1 {
647 t.Fatalf("orphan_stopped alerts after the alerter came back = %+v, want one", a)
648 }
649}
650
651// countingList signals every List call, so a test can watch Loop's passes.
652type countingList struct {
653 *isolatedjob.Fake
654 calls chan struct{}
655}
656
657func (c *countingList) List(ctx context.Context) ([]isolatedjob.Job, error) {
658 select {
659 case c.calls <- struct{}{}:
660 default:
661 }
662 return c.Fake.List(ctx)
663}
664
665func TestReapLoopRunsPassesUntilDone(t *testing.T) {
666 t.Parallel()
667 e := newLaunchEnv(t)
668 cl := &countingList{Fake: e.fake, calls: make(chan struct{}, 1)}
669 e.run = cl
670 e.newController()
671 e.plant("stray-1")
672
673 ctx, cancel := context.WithCancel(e.ctx)
674 done := make(chan error, 1)
675 go func() { done <- e.c.Loop(ctx, time.Millisecond) }()
676 for i := range 2 {
677 select {
678 case <-cl.calls:
679 case <-time.After(5 * time.Second):
680 t.Fatalf("Loop ran %d passes in 5 s, want 2", i)
681 }
682 }
683 cancel()
684 select {
685 case <-done:
686 case <-time.After(5 * time.Second):
687 t.Fatal("Loop did not return after its context was cancelled")
688 }
689 if _, ok := e.c.LastReap(); !ok {
690 t.Fatal("LastReap after two passes reports none finished")
691 }
692 if u := e.unmatched(); len(u) != 1 {
693 t.Fatalf("unmatched_vms after Loop's passes = %v, want the orphan recorded", u)
694 }
695}
696
697// auditCount counts the audit rows with action whose reason names ref.
698func (e *launchEnv) auditCount(action string, ref isolatedjob.Ref) int {
699 e.t.Helper()
700 n := 0
701 for _, a := range auditRows(e.t, e.store) {
702 if a.Action == action && strings.Contains(a.Reason, string(ref)) {
703 n++
704 }
705 }
706 return n
707}
708
709// While a waiting intent that has been dispatched exists, an orphan whose
710// grace is over may be the VM its lost launch reply made: it is deferred,
711// whichever gate keeps the intent from claiming it (R22). Once the intent is
712// abandoned, the VM is an orphan again and is stopped.
713func TestReapDefersOrphansWhileIntentWaits(t *testing.T) {
714 t.Parallel()
715 bad := isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true} // resolver on
716 gates := []struct {
717 name string
718 set func(e *launchEnv)
719 }{
720 {"throttled", func(e *launchEnv) {
721 for range 20 {
722 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
723 }
724 }},
725 {"launches off", func(e *launchEnv) { e.c.cfg.Enabled = false }},
726 {"image removed", func(e *launchEnv) { delete(e.c.cfg.Images, imgA) }},
727 {"audit failing", func(e *launchEnv) {
728 e.fake.SetAudit(bad, nil)
729 _ = e.c.RunAudit(e.ctx) // recorded now, so the first pass's replay is gated too
730 }},
731 }
732 ends := []struct {
733 name string
734 end func(e *launchEnv)
735 }{
736 {"stop asked for", func(e *launchEnv) {
737 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) {
738 e.t.Fatalf("Stop of the waiting intent = %v, want ErrStopPending", err)
739 }
740 }},
741 {"stop time passed", func(e *launchEnv) {
742 e.clk.AdvanceMono(time.Duration(T(e.stopCols("att-1").stop) - e.store.Clock().Now()))
743 }},
744 }
745 for _, g := range gates {
746 for _, end := range ends {
747 t.Run(g.name+", "+end.name, func(t *testing.T) {
748 t.Parallel()
749 e := newLaunchEnv(t)
750 ref := e.lostLaunch("att-1")
751 stray := e.plant("stray-1")
752 g.set(e)
753 pass := func() ReapReport {
754 r, err := e.c.Reap(e.ctx)
755 if err != nil && g.name != "audit failing" {
756 t.Fatalf("Reap = (%+v, %v)", r, err)
757 }
758 return r
759 }
760 pass()
761 e.clk.AdvanceMono(OrphanGrace)
762 for i := range 2 {
763 if r := pass(); r.OrphansDeferred != 2 || r.OrphansStopped != 0 {
764 t.Fatalf("pass %d after the grace: report %+v, want both orphans deferred", i, r)
765 }
766 e.clk.AdvanceMono(time.Minute)
767 }
768 e.wantStops()
769 if j, _ := e.job("att-1"); j.state != JobWaiting {
770 t.Fatalf("att-1 is %q, want still waiting", j.state)
771 }
772 for _, r := range []isolatedjob.Ref{ref, stray} {
773 if n := e.auditCount(actionOrphanDeferred, r); n != 1 {
774 t.Fatalf("orphan_deferred rows for %s = %d, want one for the run of deferrals", r, n)
775 }
776 }
777
778 end.end(e)
779 if r := pass(); r.OrphansStopped != 2 || r.OrphansDeferred != 0 {
780 t.Fatalf("pass after the intent was abandoned: report %+v, want both orphans stopped", r)
781 }
782 if j, _ := e.job("att-1"); j.state != JobAbandoned {
783 t.Fatalf("att-1 is %q, want abandoned", j.state)
784 }
785 e.wantStops(ref, stray)
786 })
787 }
788 }
789}
790
791// stopGate wraps the provider. The first Stop signals entered and waits for
792// release. Every Stop records whether its Ref was a job's saved Ref at the
793// moment of the call.
794type stopGate struct {
795 *isolatedjob.Fake
796 store *Store
797 entered, release chan struct{}
798 mu sync.Mutex
799 calls int
800 savedAtStop map[isolatedjob.Ref]bool
801}
802
803func (g *stopGate) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error {
804 g.mu.Lock()
805 g.calls++
806 first := g.calls == 1
807 g.mu.Unlock()
808 if first {
809 close(g.entered)
810 <-g.release
811 }
812 var n int
813 if err := g.store.Tx(ctx, func(tx *sql.Tx) error {
814 return tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs WHERE vm_ref = ?`, string(ref)).Scan(&n)
815 }); err != nil {
816 return err
817 }
818 g.mu.Lock()
819 g.savedAtStop[ref] = n > 0
820 g.mu.Unlock()
821 return g.Fake.Stop(ctx, ref, reason)
822}
823
824// The orphan final check holds the ownership lock through its last Stop
825// (R23): a Replay that tries to claim the second candidate while the first
826// Stop is in flight waits, and no Stop ever reaches a VM a job holds.
827func TestReapOwnershipLockHoldsClaims(t *testing.T) {
828 t.Parallel()
829 e := newLaunchEnv(t)
830 g := &stopGate{Fake: e.fake, store: e.store, entered: make(chan struct{}), release: make(chan struct{}),
831 savedAtStop: map[isolatedjob.Ref]bool{}}
832 e.run = g
833 e.newController()
834 e.audit()
835 stray := e.plant("stray-1")
836 ref := e.lostLaunch("att-1")
837 // The lost launch marked a dispatch, so R22 alone would defer both
838 // orphans. Clearing the mark isolates the lock.
839 e.exec(`UPDATE jobs SET last_dispatch_t = NULL WHERE attempt_id = 'att-1'`)
840 e.c.cfg.Enabled = false // the pass's own replays create and claim nothing
841 e.reap()
842 e.clk.AdvanceMono(OrphanGrace)
843
844 waited := make(chan struct{})
845 e.c.ownership.waiting = func() { close(waited) }
846 reaped := make(chan error, 1)
847 go func() { _, err := e.c.Reap(e.ctx); reaped <- err }()
848 select {
849 case <-g.entered:
850 case <-time.After(5 * time.Second):
851 t.Fatal("the reaper never stopped the first orphan")
852 }
853 e.c.cfg.Enabled = true // the reaper read it before the Stop; a claim may go ahead now
854 replayed := make(chan error, 1)
855 go func() { replayed <- e.c.Replay(e.ctx) }()
856 select {
857 case <-waited: // the dispatch waits for the reaper
858 case err := <-replayed: // the claim landed during the Stop
859 replayed <- err
860 case <-time.After(5 * time.Second):
861 t.Fatal("the Replay neither waited nor finished")
862 }
863 close(g.release)
864 for _, ch := range []chan error{reaped, replayed} {
865 select {
866 case err := <-ch:
867 if err != nil {
868 t.Fatalf("Reap or Replay = %v", err)
869 }
870 case <-time.After(5 * time.Second):
871 t.Fatal("Reap or Replay did not finish")
872 }
873 }
874 g.mu.Lock()
875 defer g.mu.Unlock()
876 if len(g.savedAtStop) != 2 {
877 t.Fatalf("orphan stops = %v, want %s and %s", g.savedAtStop, stray, ref)
878 }
879 for r, saved := range g.savedAtStop {
880 if saved {
881 t.Fatalf("VM %s was stopped as an orphan while a job held it", r)
882 }
883 }
884 if j, _ := e.job("att-1"); isolatedjob.Ref(j.ref.String) != ref {
885 t.Fatalf("att-1 ref %v, want %s claimed once the reaper let go", j.ref, ref)
886 }
887}
888
889// scriptAuditor answers AuditNetwork from a script: true passes, false
890// fails. Calls past the script pass.
891type scriptAuditor struct {
892 mu sync.Mutex
893 script []bool
894 n int
895}
896
897func (s *scriptAuditor) AuditNetwork(context.Context) (isolatedjob.NetworkAudit, error) {
898 s.mu.Lock()
899 defer s.mu.Unlock()
900 s.n++
901 a := isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true}
902 if s.n <= len(s.script) && !s.script[s.n-1] {
903 a.ResolverDisabled = false
904 }
905 return a, nil
906}
907
908// The recheck's audit and step 6's share one run of failures: a pass at
909// either point ends it, a failure at either begins one.
910func TestReapAuditEpisodesAcrossBothAudits(t *testing.T) {
911 t.Parallel()
912 e := newLaunchEnv(t)
913 sa := &scriptAuditor{script: []bool{
914 true, // the setup audit
915 false, // pass 0, step 6
916 true, false, // pass 1: recheck, step 6
917 true, // pass 2, step 6
918 false, true, // pass 3: recheck, step 6
919 }}
920 c, err := New(e.cfg, Deps{Store: e.store, Runner: e.run, Auditor: sa, Alerter: &recordingAlerter{}})
921 if err != nil {
922 t.Fatal(err)
923 }
924 e.c = c
925 e.audit()
926 passed := func() int { return e.auditCount(actionNetworkAuditPassed, "") }
927 check := func(n int, wantErr bool, alerts, passes int) {
928 t.Helper()
929 _, err := e.c.Reap(e.ctx)
930 if (err != nil) != wantErr {
931 t.Fatalf("pass %d = %v, want an error %v", n, err, wantErr)
932 }
933 if a := e.alerts(AlertAuditFailed); len(a) != alerts {
934 t.Fatalf("pass %d: audit_failed alerts %d, want %d", n, len(a), alerts)
935 }
936 if p := passed(); p != passes {
937 t.Fatalf("pass %d: network_audit_passed rows %d, want %d", n, p, passes)
938 }
939 }
940 e.plant("stray-1")
941 check(0, true, 1, 0)
942 e.clk.AdvanceMono(OrphanGrace)
943 check(1, true, 2, 1) // failure, then success at the recheck, then failure: a new run
944 e.plant("stray-2")
945 check(2, false, 2, 2)
946 e.clk.AdvanceMono(OrphanGrace)
947 check(3, true, 3, 3) // the recheck's failure counts though step 6 passes
948 if sa.n != len(sa.script) {
949 t.Fatalf("audits run = %d, want %d", sa.n, len(sa.script))
950 }
951}
952
953// A stale live List entry for a job that already has proof still matches
954// its saved Ref: it is never an orphan.
955func TestReapProvenJobIsNeverOrphan(t *testing.T) {
956 t.Parallel()
957 e := newLaunchEnv(t)
958 sr := &slowRunner{Fake: e.fake, clk: e.clk}
959 e.run = sr
960 e.newController()
961 e.audit()
962 ref := e.launchWith("att-1", 2*time.Hour)
963 e.fake.Tick()
964 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) {
965 t.Fatalf("Stop = %v, want ErrStopPending", err)
966 }
967 e.fake.Tick()
968 e.refresh()
969 if w := e.wireProof("att-1"); w.VMRef != ref {
970 t.Fatalf("proof = %+v, want one for %s", w, ref)
971 }
972 e.fake.Vanish(ref)
973 sr.setExtra(isolatedjob.Job{Ref: ref, State: isolatedjob.StateRunning})
974 if r := e.reap(); r.OrphansSeen != 0 {
975 t.Fatalf("report %+v, want no orphan", r)
976 }
977 e.clk.AdvanceMono(OrphanGrace)
978 if r := e.reap(); r.OrphansSeen != 0 || r.OrphansStopped != 0 {
979 t.Fatalf("after the grace: report %+v, want no orphan", r)
980 }
981 e.wantStops(ref) // the instance's own stop only
982}
983
984// listScript wraps the provider's List. After List call n (counting from
985// 1) it runs script(n), which may change the fake; when script returns
986// true the answer comes with ErrIncomplete, VMs and all.
987type listScript struct {
988 *isolatedjob.Fake
989 mu sync.Mutex
990 n int
991 script func(n int) bool
992}
993
994func (l *listScript) List(ctx context.Context) ([]isolatedjob.Job, error) {
995 vms, err := l.Fake.List(ctx)
996 if err != nil {
997 return vms, err
998 }
999 l.mu.Lock()
1000 l.n++
1001 n := l.n
1002 l.mu.Unlock()
1003 if l.script(n) {
1004 return vms, fmt.Errorf("%w: test stopped paging", isolatedjob.ErrIncomplete)
1005 }
1006 return vms, nil
1007}
1008
1009// The final check lists again: a VM the first List showed and the provider
1010// has since forgotten is not stopped.
1011func TestReapRecheckListsAgain(t *testing.T) {
1012 t.Parallel()
1013 e := newLaunchEnv(t)
1014 var stray isolatedjob.Ref
1015 ls := &listScript{Fake: e.fake, script: func(n int) bool {
1016 if n == 2 { // the expiry pass's first List
1017 e.fake.Vanish(stray)
1018 }
1019 return false
1020 }}
1021 e.run = ls
1022 e.newController()
1023 e.audit()
1024 stray = e.plant("stray-1")
1025 e.reap()
1026 e.clk.AdvanceMono(OrphanGrace)
1027 if r := e.reap(); r.OrphansStopped != 0 {
1028 t.Fatalf("report %+v, want no stop of a VM the fresh list does not show", r)
1029 }
1030 e.wantStops()
1031}
1032
1033// An incomplete List in the final check stops nothing; the next complete
1034// one does.
1035func TestReapIncompleteRecheckListStopsNothing(t *testing.T) {
1036 t.Parallel()
1037 e := newLaunchEnv(t)
1038 ls := &listScript{Fake: e.fake, script: func(n int) bool { return n == 3 }} // the expiry pass's recheck
1039 e.run = ls
1040 e.newController()
1041 e.audit()
1042 stray := e.plant("stray-1")
1043 e.reap()
1044 e.clk.AdvanceMono(OrphanGrace)
1045 if r := e.reap(); !r.Skipped || r.OrphansStopped != 0 {
1046 t.Fatalf("pass with an incomplete recheck list: report %+v, want skipped, no stop", r)
1047 }
1048 e.wantStops()
1049 if u := e.unmatched(); len(u) != 1 {
1050 t.Fatalf("unmatched_vms = %v, want the orphan kept", u)
1051 }
1052 if r := e.reap(); r.Skipped || r.OrphansStopped != 1 {
1053 t.Fatalf("next pass: report %+v, want the orphan stopped", r)
1054 }
1055 e.wantStops(stray)
1056}
1057
1058// A dispatch that waits for the ownership lock checks its gates only once
1059// it holds the lock: a stop time, a stale audit or a failing audit reached
1060// during the wait means no provider launch (R23 placement, review r2).
1061func TestReapWaitingDispatchChecksGatesAfter(t *testing.T) {
1062 t.Parallel()
1063 bad := isolatedjob.NetworkAudit{IngressClosed: true, RouteOutAbsent: true} // resolver on
1064 cases := []struct {
1065 name string
1066 change func(e *launchEnv)
1067 want string // the intent's state after the dispatch
1068 launch bool // whether the provider is asked to launch
1069 }{
1070 {"nothing changes", func(*launchEnv) {}, JobStarting, true},
1071 {"stop time passes", func(e *launchEnv) {
1072 e.clk.AdvanceMono(time.Duration(T(e.stopCols("att-1").stop) - e.store.Clock().Now()))
1073 }, JobAbandoned, false},
1074 {"audit goes stale", func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Second) }, JobWaiting, false},
1075 {"audit fails", func(e *launchEnv) {
1076 e.fake.SetAudit(bad, nil)
1077 if err := e.c.RunAudit(e.ctx); err == nil {
1078 e.t.Fatal("RunAudit with the resolver on = nil")
1079 }
1080 }, JobWaiting, false},
1081 }
1082 for _, tc := range cases {
1083 t.Run(tc.name, func(t *testing.T) {
1084 t.Parallel()
1085 e := newLaunchEnv(t)
1086 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
1087 if v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil || v.State != JobWaiting {
1088 t.Fatalf("throttled Launch = (%+v, %v), want a waiting intent", v, err)
1089 }
1090 e.audit() // fresh, so only the change below can close a gate
1091
1092 // The orphan reaper's final check holds the lock for writing.
1093 e.c.ownership.mu.Lock()
1094 waited := make(chan struct{})
1095 e.c.ownership.waiting = func() { close(waited) }
1096 replayed := make(chan error, 1)
1097 go func() { replayed <- e.c.Replay(e.ctx) }()
1098 select {
1099 case <-waited:
1100 case err := <-replayed:
1101 e.c.ownership.mu.Unlock()
1102 t.Fatalf("Replay finished (%v) while the ownership lock was held for writing", err)
1103 case <-time.After(5 * time.Second):
1104 t.Fatal("the dispatch never waited for the ownership lock")
1105 }
1106 tc.change(e)
1107 launches := e.fake.Calls(isolatedjob.OpLaunch)
1108 e.c.ownership.mu.Unlock()
1109 select {
1110 case err := <-replayed:
1111 if err != nil {
1112 t.Fatalf("Replay = %v", err)
1113 }
1114 case <-time.After(5 * time.Second):
1115 t.Fatal("Replay did not finish once the lock was free")
1116 }
1117
1118 want := 0
1119 if tc.launch {
1120 want = 1
1121 }
1122 if got := e.fake.Calls(isolatedjob.OpLaunch) - launches; got != want {
1123 t.Fatalf("provider launches after the wait = %d, want %d", got, want)
1124 }
1125 if j, _ := e.job("att-1"); j.state != tc.want {
1126 t.Fatalf("att-1 is %q, want %q", j.state, tc.want)
1127 }
1128 if tc.want == JobAbandoned && !e.hasAudit("", "att-1", actionReplayAbandoned, "stop time passed") {
1129 t.Fatal("no replay_abandoned audit row")
1130 }
1131 })
1132 }
1133}
1134