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 "bytes"
5 "context"
6 "database/sql"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "log/slog"
11 "path/filepath"
12 "strings"
13 "sync"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/hostedwire"
18 "amadan.net/oficina/equipo/internal/isolatedjob"
19 "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
20)
21
22const (
23 imgA = isolatedjob.ImageDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
24 imgB = isolatedjob.ImageDigest("sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
25 imgOther = isolatedjob.ImageDigest("sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc")
26
27 // testCode is the instance code every test request carries. It must
28 // never appear in an audit row, an error or a JobView.
29 testCode = "code-SECRET-4f2a9c"
30)
31
32var (
33 instKey = hostedwire.VerifyKey{Role: hostedwire.RoleInstance}
34 opKey = hostedwire.VerifyKey{Role: hostedwire.RoleOperator}
35)
36
37// launchEnv is one controller over a fresh store and a fake provider, with a
38// passing network audit just run.
39type launchEnv struct {
40 t *testing.T
41 ctx context.Context
42 path string
43 clk *isolatedjobtest.FakeClock
44 gc *gateClock // the store's clock: clk, with a signal a test can arm
45 fake *isolatedjob.Fake
46 run isolatedjob.Runner // what the controller calls; the fake unless a test wraps it
47 cfg Config
48 store *Store
49 c *Controller
50 logs *syncBuffer // every controller's Deps.Log, as text (logs_test.go)
51}
52
53func newLaunchEnv(t *testing.T) *launchEnv {
54 t.Helper()
55 clk := isolatedjobtest.NewFakeClock(testWall)
56 fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits())
57 e := &launchEnv{
58 t: t, ctx: context.Background(), path: filepath.Join(t.TempDir(), "hosted.db"),
59 clk: clk, gc: &gateClock{FakeClock: clk}, fake: fake, run: fake,
60 cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true, imgB: true},
61 ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint},
62 }
63 e.store = openStore(t, e.path, e.gc)
64 e.newController()
65 e.audit()
66 return e
67}
68
69// gateClock is the test clock with one extra: after arm, the next Mono call
70// reads the time and then closes the returned channel, so a test learns that
71// a goroutine has just read the clock.
72type gateClock struct {
73 *isolatedjobtest.FakeClock
74 mu sync.Mutex
75 armed chan struct{}
76}
77
78func (g *gateClock) arm() <-chan struct{} {
79 g.mu.Lock()
80 defer g.mu.Unlock()
81 g.armed = make(chan struct{})
82 return g.armed
83}
84
85func (g *gateClock) Mono() time.Duration {
86 d := g.FakeClock.Mono()
87 g.mu.Lock()
88 defer g.mu.Unlock()
89 if g.armed != nil {
90 close(g.armed)
91 g.armed = nil
92 }
93 return d
94}
95
96// newController builds a controller over e.store with e.cfg and e.run. It
97// has no network audit until e.audit runs.
98func (e *launchEnv) newController() {
99 e.t.Helper()
100 if e.logs == nil {
101 e.logs = &syncBuffer{}
102 }
103 c, err := New(e.cfg, Deps{Store: e.store, Runner: e.run, Auditor: e.fake, Alerter: &recordingAlerter{},
104 Log: slog.New(slog.NewTextHandler(e.logs, nil))})
105 if err != nil {
106 e.t.Fatalf("New = %v", err)
107 }
108 e.c = c
109}
110
111// audit runs the network audit and wants it to pass.
112func (e *launchEnv) audit() {
113 e.t.Helper()
114 if err := e.c.RunAudit(e.ctx); err != nil {
115 e.t.Fatalf("RunAudit = %v, want a pass", err)
116 }
117}
118
119// reopen closes the store, as a controller that exits, then opens it again
120// and builds a new controller over the same fake provider.
121func (e *launchEnv) reopen() {
122 e.t.Helper()
123 if err := e.store.Close(); err != nil {
124 e.t.Fatalf("Close = %v", err)
125 }
126 e.store = openStore(e.t, e.path, e.gc)
127 e.newController()
128}
129
130func (e *launchEnv) exec(query string, args ...any) {
131 e.t.Helper()
132 if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
133 _, err := tx.ExecContext(e.ctx, query, args...)
134 return err
135 }); err != nil {
136 e.t.Fatalf("%s = %v", query, err)
137 }
138}
139
140// job reads one job row; ok is false when there is none.
141func (e *launchEnv) job(attempt string) (jobRow, bool) {
142 e.t.Helper()
143 var j jobRow
144 var found bool
145 if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
146 var err error
147 j, found, err = loadJob(e.ctx, tx, attempt)
148 return err
149 }); err != nil {
150 e.t.Fatalf("loadJob(%s) = %v", attempt, err)
151 }
152 return j, found
153}
154
155func (e *launchEnv) jobCount() int {
156 e.t.Helper()
157 var n int
158 if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
159 return tx.QueryRowContext(e.ctx, `SELECT count(*) FROM jobs`).Scan(&n)
160 }); err != nil {
161 e.t.Fatal(err)
162 }
163 return n
164}
165
166// noCodeInAudit fails the test when any audit row holds the instance code.
167func (e *launchEnv) noCodeInAudit() {
168 e.t.Helper()
169 for _, a := range auditRows(e.t, e.store) {
170 if strings.Contains(string(a.Actor)+a.Account+a.Task+a.Attempt+a.Action+a.Reason, testCode) {
171 e.t.Fatalf("audit row %+v holds the instance code", a)
172 }
173 }
174}
175
176// lastAudit returns the newest audit row.
177func (e *launchEnv) lastAudit() Audit {
178 e.t.Helper()
179 rows := auditRows(e.t, e.store)
180 if len(rows) == 0 {
181 e.t.Fatal("no audit rows")
182 }
183 return rows[len(rows)-1]
184}
185
186func request(attempt string) LaunchRequest {
187 return LaunchRequest{
188 AttemptID: attempt, TaskID: "task-1", Account: "acct-1",
189 Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetime: 2 * time.Hour,
190 InstanceCode: testCode,
191 }
192}
193
194// intentProbe wraps the fake provider. At each Launch it reads the job row
195// for the attempt from the store in a helper goroutine, as the provider is
196// called. If the read has not finished after 2 s, something holds the store
197// across the provider call: the probe marks the call blocked and returns an
198// error at once, so the caller can unwind and release the store. join then
199// waits for every helper.
200type intentProbe struct {
201 *isolatedjob.Fake
202 store *Store
203 mu sync.Mutex
204 seen []*probeSeen
205}
206
207type probeSeen struct {
208 spec isolatedjob.LaunchSpec
209 row jobRow
210 found bool
211 err error
212 blocked bool
213 done chan struct{}
214}
215
216var errProbeBlocked = errors.New("probe: the store was held across the provider call")
217
218func (p *intentProbe) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
219 got := &probeSeen{spec: s, done: make(chan struct{})}
220 p.mu.Lock()
221 p.seen = append(p.seen, got)
222 p.mu.Unlock()
223 go func() {
224 defer close(got.done)
225 got.err = p.store.Tx(context.Background(), func(tx *sql.Tx) error {
226 var err error
227 got.row, got.found, err = loadJob(context.Background(), tx, s.AttemptID)
228 return err
229 })
230 }()
231 select {
232 case <-got.done:
233 case <-time.After(2 * time.Second):
234 got.blocked = true
235 return "", errProbeBlocked
236 }
237 return p.Fake.Launch(ctx, s)
238}
239
240// join waits for every read the probe started and returns what each saw.
241// Call it after the probed call has returned; nothing then holds the store.
242func (p *intentProbe) join(t *testing.T) []*probeSeen {
243 t.Helper()
244 p.mu.Lock()
245 seen := append([]*probeSeen(nil), p.seen...)
246 p.mu.Unlock()
247 for _, g := range seen {
248 select {
249 case <-g.done:
250 case <-time.After(5 * time.Second):
251 t.Fatal("a probe read of the store is still blocked after the launch returned")
252 }
253 }
254 return seen
255}
256
257func TestLaunchSavesIntentBeforeProvider(t *testing.T) {
258 e := newLaunchEnv(t)
259 probe := &intentProbe{Fake: e.fake, store: e.store}
260 e.run = probe
261 e.newController()
262 e.audit()
263 e.clk.AdvanceMono(3 * time.Minute)
264 launchedAt := e.store.Clock().Now()
265
266 q := request("att-1")
267 v, err := e.c.Launch(e.ctx, "inst-1", instKey, q)
268 all := probe.join(t)
269 for i, g := range all {
270 if g.blocked {
271 t.Fatalf("provider call %d: a store read waited 2 s; a transaction is held across the provider call", i)
272 }
273 if g.err != nil {
274 t.Fatalf("provider call %d: reading the store = %v", i, g.err)
275 }
276 if !g.found {
277 t.Fatalf("provider call %d: the provider was called before the launch intent was saved", i)
278 }
279 }
280 if err != nil {
281 t.Fatalf("Launch = %v", err)
282 }
283 if len(all) != 1 {
284 t.Fatalf("provider launches = %d, want 1", len(all))
285 }
286 seen := all[0]
287 r := seen.row
288 if r.state != JobWaiting || r.ref.Valid || r.actor != "inst-1" || r.task != "task-1" || r.account != "acct-1" {
289 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",
290 r.state, r.ref, r.actor, r.task, r.account)
291 }
292 saved, err := decodeSpec(r.specJSON, "att-1")
293 if err != nil {
294 t.Fatalf("decode saved spec = %v", err)
295 }
296 if saved.AttemptID != seen.spec.AttemptID || saved.Image != seen.spec.Image || saved.Size != seen.spec.Size ||
297 saved.MaxLifetime != seen.spec.MaxLifetime || !bytes.Equal(saved.Bootstrap, seen.spec.Bootstrap) {
298 t.Fatalf("saved spec %+v differs from the one sent %+v", saved, seen.spec)
299 }
300 var boot hostedwire.Bootstrap
301 if err := json.Unmarshal(seen.spec.Bootstrap, &boot); err != nil {
302 t.Fatalf("bootstrap is not JSON: %v", err)
303 }
304 if boot != (hostedwire.Bootstrap{Version: 1, LaunchID: v.LaunchID, InstanceCode: testCode}) || len(v.LaunchID) < 26 {
305 t.Fatalf("bootstrap = %+v, want version 1, launch ID %q (26+ characters) and the instance code", boot, v.LaunchID)
306 }
307 wantDeadline, wantDrain, wantStop := Deadlines(launchedAt, 2*time.Hour)
308 if T(r.launchedT) != launchedAt || T(r.deadlineT) != wantDeadline || T(r.drainT) != wantDrain || T(r.stopT) != wantStop {
309 t.Fatalf("intent times = launched %d deadline %d drain %d stop %d, want %d %d %d %d",
310 r.launchedT, r.deadlineT, r.drainT, r.stopT, launchedAt, wantDeadline, wantDrain, wantStop)
311 }
312
313 after, _ := e.job("att-1")
314 if v.State != JobStarting || v.VMRef == "" || after.state != JobStarting || isolatedjob.Ref(after.ref.String) != v.VMRef {
315 t.Fatalf("after Launch: view %+v, row state %q ref %v; want starting with the saved ref", v, after.state, after.ref)
316 }
317 if v.DeadlineIn != 2*time.Hour || v.DrainIn != 75*time.Minute || v.StopIn != 110*time.Minute {
318 t.Fatalf("view countdowns = %v %v %v, want 2h 1h15m 1h50m", v.DeadlineIn, v.DrainIn, v.StopIn)
319 }
320 if strings.Contains(strings.Join([]string{v.AttemptID, v.LaunchID, v.State, string(v.VMRef)}, " "), testCode) {
321 t.Fatalf("view %+v holds the instance code", v)
322 }
323 e.noCodeInAudit()
324}
325
326func TestLaunchIdempotentOnAttempt(t *testing.T) {
327 e := newLaunchEnv(t)
328 first, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
329 if err != nil {
330 t.Fatalf("first Launch = %v", err)
331 }
332 e.clk.AdvanceMono(10 * time.Minute)
333 e.audit()
334 second, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
335 if err != nil {
336 t.Fatalf("second Launch = %v", err)
337 }
338 if second.LaunchID != first.LaunchID || second.VMRef != first.VMRef || second.State != JobStarting {
339 t.Fatalf("second view %+v, want the first's launch ID and ref %+v", second, first)
340 }
341 if second.DeadlineIn != first.DeadlineIn-10*time.Minute {
342 t.Fatalf("second DeadlineIn = %v, want %v: deadlines never move", second.DeadlineIn, first.DeadlineIn-10*time.Minute)
343 }
344 if err := e.c.Replay(e.ctx); err != nil {
345 t.Fatalf("Replay = %v", err)
346 }
347 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 {
348 t.Fatalf("provider launches = %d, want 1", n)
349 }
350 if n := e.jobCount(); n != 1 {
351 t.Fatalf("job rows = %d, want 1", n)
352 }
353 if got := e.lastAudit(); got.Action != actionLaunchRepeated || got.Actor != "inst-1" || got.Attempt != "att-1" {
354 t.Fatalf("last audit = %+v, want a %s row for inst-1 att-1", got, actionLaunchRepeated)
355 }
356 e.noCodeInAudit()
357}
358
359func TestLaunchConflictOnChangedRequest(t *testing.T) {
360 cases := []struct {
361 name string
362 by hostedwire.KeyID
363 change func(*LaunchRequest)
364 }{
365 {"task", "inst-1", func(q *LaunchRequest) { q.TaskID = "task-2" }},
366 {"account", "inst-1", func(q *LaunchRequest) { q.Account = "acct-2" }},
367 {"image", "inst-1", func(q *LaunchRequest) { q.Image = imgB }},
368 {"size", "inst-1", func(q *LaunchRequest) { q.Size = isolatedjob.SizeLarge }},
369 {"lifetime", "inst-1", func(q *LaunchRequest) { q.MaxLifetime = 3 * time.Hour }},
370 {"instance code", "inst-1", func(q *LaunchRequest) { q.InstanceCode = "code-other" }},
371 {"another key", "inst-2", func(*LaunchRequest) {}},
372 }
373 for _, tc := range cases {
374 t.Run(tc.name, func(t *testing.T) {
375 t.Parallel()
376 e := newLaunchEnv(t)
377 first, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
378 if err != nil {
379 t.Fatalf("first Launch = %v", err)
380 }
381 before, _ := e.job("att-1")
382 q := request("att-1")
383 tc.change(&q)
384 v, err := e.c.Launch(e.ctx, tc.by, instKey, q)
385 if !errors.Is(err, isolatedjob.ErrConflict) || v != (JobView{}) {
386 t.Fatalf("changed Launch = (%+v, %v), want (zero view, ErrConflict)", v, err)
387 }
388 if strings.Contains(err.Error(), testCode) || strings.Contains(err.Error(), "code-other") {
389 t.Fatalf("error %q holds an instance code", err)
390 }
391 after, _ := e.job("att-1")
392 if after != before || after.launchID != first.LaunchID {
393 t.Fatalf("job changed by a conflicting launch: %+v, want %+v", after, before)
394 }
395 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 {
396 t.Fatalf("provider launches = %d, want 1", n)
397 }
398 if got := e.lastAudit(); got.Action != actionLaunchRefused || got.Actor != tc.by || got.Attempt != "att-1" {
399 t.Fatalf("last audit = %+v, want a %s row for %s att-1", got, actionLaunchRefused, tc.by)
400 }
401 e.noCodeInAudit()
402 })
403 }
404}
405
406// holdRunner wraps the fake provider and holds the first Launch call until
407// release is closed; later calls go straight through.
408type holdRunner struct {
409 *isolatedjob.Fake
410 once sync.Once
411 entered chan struct{}
412 release chan struct{}
413}
414
415func (h *holdRunner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
416 first := false
417 h.once.Do(func() { first = true; close(h.entered) })
418 if first {
419 <-h.release
420 }
421 return h.Fake.Launch(ctx, s)
422}
423
424func TestConcurrentLaunchSameAttempt(t *testing.T) {
425 e := newLaunchEnv(t)
426 hold := &holdRunner{Fake: e.fake, entered: make(chan struct{}), release: make(chan struct{})}
427 e.run = hold
428 e.newController()
429 e.audit()
430
431 const n = 20
432 views := make([]JobView, n)
433 errs := make([]error, n)
434 finished := make(chan int, n)
435 start := make(chan struct{})
436 var wg sync.WaitGroup
437 for i := range n {
438 wg.Add(1)
439 go func() {
440 defer wg.Done()
441 <-start
442 views[i], errs[i] = e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
443 finished <- i
444 }()
445 }
446 close(start)
447 // The first provider call is held. Every other caller must answer from
448 // the saved intent meanwhile, without reaching the provider.
449 select {
450 case <-hold.entered:
451 case <-time.After(5 * time.Second):
452 t.Fatal("no provider call within 5 s")
453 }
454 early := map[int]bool{}
455 for range n - 1 {
456 select {
457 case i := <-finished:
458 early[i] = true
459 case <-time.After(5 * time.Second):
460 close(hold.release)
461 t.Fatalf("only %d of %d other launches returned while the first provider call was held", len(early), n-1)
462 }
463 }
464 close(hold.release)
465 wg.Wait()
466
467 for i, err := range errs {
468 if err != nil {
469 t.Fatalf("Launch %d = %v", i, err)
470 }
471 }
472 j, _ := e.job("att-1")
473 for i, v := range views {
474 if v.LaunchID != j.launchID {
475 t.Fatalf("view %d launch ID %q, want the one intent's %q", i, v.LaunchID, j.launchID)
476 }
477 if early[i] && (v.State != JobWaiting || v.VMRef != "") {
478 t.Fatalf("view %d, returned while the provider call was held = %+v, want waiting with no ref", i, v)
479 }
480 if !early[i] && (v.State != JobStarting || string(v.VMRef) != j.ref.String) {
481 t.Fatalf("view %d, the launching call = %+v, want starting with the saved ref %q", i, v, j.ref.String)
482 }
483 }
484 if j.state != JobStarting || !j.ref.Valid {
485 t.Fatalf("job = state %q ref %v, want starting with a ref", j.state, j.ref)
486 }
487 if got := e.jobCount(); got != 1 {
488 t.Fatalf("job rows = %d, want 1", got)
489 }
490 if live := e.fake.LiveByAttempt(); live["att-1"] != 1 || len(live) != 1 {
491 t.Fatalf("live VMs = %v, want one for att-1", live)
492 }
493 if c := e.fake.Calls(isolatedjob.OpLaunch); c != 1 {
494 t.Fatalf("provider launches = %d, want 1", c)
495 }
496}
497
498func TestCrashBetweenLaunchAndSave(t *testing.T) {
499 e := newLaunchEnv(t)
500 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply)
501 v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
502 if !errors.Is(err, ErrProviderLaunch) || errors.Is(err, isolatedjob.ErrLostReply) || v != (JobView{}) {
503 t.Fatalf("Launch with a lost reply = (%+v, %v), want (zero view, ErrProviderLaunch) with the provider's error dropped", v, err)
504 }
505 if live := e.fake.LiveByAttempt(); live["att-1"] != 1 {
506 t.Fatalf("live VMs after the lost reply = %v, want one for att-1", live)
507 }
508 if j, ok := e.job("att-1"); !ok || j.state != JobWaiting || j.ref.Valid {
509 t.Fatalf("job after the lost reply = %+v (found %v), want waiting with no ref", j, ok)
510 }
511
512 e.reopen()
513 if err := e.c.Replay(e.ctx); err != nil {
514 t.Fatalf("Replay before any audit = %v", err)
515 }
516 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 {
517 t.Fatalf("provider launches with no audit since the restart = %d, want 1", n)
518 }
519 e.audit()
520 if err := e.c.Replay(e.ctx); err != nil {
521 t.Fatalf("Replay = %v", err)
522 }
523 vms, err := e.fake.List(e.ctx)
524 if err != nil || len(vms) != 1 {
525 t.Fatalf("provider VMs = %v, %v; want exactly one", vms, err)
526 }
527 j, _ := e.job("att-1")
528 if j.state != JobStarting || j.ref.String != string(vms[0].Ref) {
529 t.Fatalf("job after Replay = state %q ref %v, want starting with %s", j.state, j.ref, vms[0].Ref)
530 }
531 if live := e.fake.LiveByAttempt(); live["att-1"] != 1 || len(live) != 1 {
532 t.Fatalf("live VMs = %v, want one for att-1", live)
533 }
534 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 2 {
535 t.Fatalf("provider launches = %d, want 2 (the lost one and the replay)", n)
536 }
537 if got := e.lastAudit(); got.Action != actionReplayStarted || got.Actor != "" {
538 t.Fatalf("last audit = %+v, want a %s row by the controller", got, actionReplayStarted)
539 }
540 e.noCodeInAudit()
541}
542
543// TestReplayRefusesChangedProviderConfig: a launch reply is lost, then the
544// controller restarts with other provider settings for the image (another
545// image version, say). Replay must not re-send the intent, which would ask
546// for a different VM under the same client token: it abandons the intent as
547// config_changed, with an alert and no provider call, and the VM the lost
548// reply made is reaped as an orphan (R29).
549func TestReplayRefusesChangedProviderConfig(t *testing.T) {
550 t.Parallel()
551 e := newLaunchEnv(t)
552 ref := e.lostLaunch("att-1")
553 e.down()
554 e.cfg.ProviderFingerprint = func(d isolatedjob.ImageDigest, s isolatedjob.Size) string { return testFingerprint(d, s) + "/v2" }
555 e.up()
556 e.audit()
557 if err := e.c.Replay(e.ctx); err != nil {
558 t.Fatalf("Replay = %v", err)
559 }
560 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 {
561 t.Fatalf("provider launches = %d, want only the lost one", n)
562 }
563 if j, _ := e.job("att-1"); j.state != JobAbandoned || j.ref.Valid {
564 t.Fatalf("att-1 after Replay: state %q ref %v; want abandoned with no ref", j.state, j.ref)
565 }
566 if !e.hasAudit("", "att-1", actionReplayAbandoned, reasonConfigChanged) {
567 t.Fatalf("no %s audit row naming %s", actionReplayAbandoned, reasonConfigChanged)
568 }
569 if a := e.alerts(AlertConfigChanged); len(a) != 1 || !strings.Contains(a[0].Detail, "att-1") {
570 t.Fatalf("%s alerts = %+v, want one naming att-1", AlertConfigChanged, a)
571 }
572 e.reap()
573 e.clk.AdvanceMono(OrphanGrace)
574 if r := e.reap(); r.OrphansStopped != 1 || r.OrphansDeferred != 0 {
575 t.Fatalf("pass after the grace = %+v, want the lost reply's VM stopped as an orphan", r)
576 }
577 e.wantStops(ref)
578}
579
580// TestLaunchRechecksGatesBeforeDispatch: a launch passes its gates, then
581// queues for transaction 1 while the audit goes stale. Once the intent is
582// saved it must not reach the provider.
583func TestLaunchRechecksGatesBeforeDispatch(t *testing.T) {
584 e := newLaunchEnv(t)
585
586 // Hold transaction admission.
587 entered, release := make(chan struct{}), make(chan struct{})
588 blocker := make(chan error, 1)
589 go func() {
590 blocker <- e.store.Tx(e.ctx, func(*sql.Tx) error { close(entered); <-release; return nil })
591 }()
592 <-entered
593
594 // The launch's gate check is its first clock read; once it has read
595 // the clock it can only go on to queue behind the held transaction.
596 read := e.gc.arm()
597 type result struct {
598 v JobView
599 err error
600 }
601 done := make(chan result, 1)
602 go func() {
603 v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
604 done <- result{v, err}
605 }()
606 select {
607 case <-read:
608 case <-time.After(5 * time.Second):
609 close(release)
610 t.Fatal("the launch did not read the clock within 5 s")
611 }
612 e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) // the audit goes stale while it waits
613 close(release)
614 if err := <-blocker; err != nil {
615 t.Fatalf("holding transaction = %v", err)
616 }
617 r := <-done
618
619 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 0 {
620 t.Fatalf("provider launches = %d, want 0: the audit went stale before dispatch", n)
621 }
622 if r.err != nil || r.v.State != JobWaiting || r.v.VMRef != "" || r.v.LaunchID == "" {
623 t.Fatalf("Launch = (%+v, %v), want a waiting view with a launch ID and no error", r.v, r.err)
624 }
625 if j, ok := e.job("att-1"); !ok || j.state != JobWaiting || j.ref.Valid {
626 t.Fatalf("job = %+v (found %v), want the intent kept, waiting, with no ref", j, ok)
627 }
628 if got := e.lastAudit(); got.Action != actionLaunchDeferred || got.Actor != "inst-1" || !strings.Contains(got.Reason, "network audit") {
629 t.Fatalf("last audit = %+v, want %s for inst-1 naming the audit", got, actionLaunchDeferred)
630 }
631
632 // The kept intent launches once a fresh audit passes.
633 e.audit()
634 if err := e.c.Replay(e.ctx); err != nil {
635 t.Fatalf("Replay = %v", err)
636 }
637 if j, _ := e.job("att-1"); j.state != JobStarting || !j.ref.Valid {
638 t.Fatalf("job after Replay = state %q ref %v, want starting with a ref", j.state, j.ref)
639 }
640}
641
642// TestDispatchRechecksGatesAfterMarker: dispatch passes its gates, then
643// waits for the store to record its dispatch marker. A gate that fails
644// while the marker waits must still stop the provider call: the stop time
645// passing abandons the intent; a failed or stale audit leaves it waiting.
646func TestDispatchRechecksGatesAfterMarker(t *testing.T) {
647 t.Parallel()
648 for _, tc := range []struct {
649 name string
650 invalidate func(e *launchEnv)
651 state string
652 }{
653 {"stop time passes", func(e *launchEnv) { e.clk.AdvanceMono(2 * time.Hour) }, JobAbandoned},
654 {"audit fails", func(e *launchEnv) { e.fake.SetAudit(isolatedjob.NetworkAudit{}, nil); _ = e.c.RunAudit(e.ctx) }, JobWaiting},
655 {"audit goes stale", func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) }, JobWaiting},
656 } {
657 t.Run(tc.name, func(t *testing.T) {
658 t.Parallel()
659 e := newLaunchEnv(t)
660 held, release, blocker := make(chan struct{}), make(chan struct{}), make(chan error, 1)
661 e.c.beforeMark = func() { // hold the store, so the marker's transaction queues behind it
662 go func() { blocker <- e.store.Tx(e.ctx, func(*sql.Tx) error { close(held); <-release; return nil }) }()
663 <-held
664 }
665 done := make(chan error, 1)
666 go func() { _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); done <- err }()
667 select {
668 case <-held:
669 case <-time.After(5 * time.Second):
670 t.Fatal("dispatch did not reach its marker within 5 s")
671 }
672 tc.invalidate(e)
673 close(release)
674 if err := errors.Join(<-blocker, <-done); err != nil {
675 t.Fatalf("Launch = %v", err)
676 }
677 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 0 {
678 t.Fatalf("provider launches = %d, want 0", n)
679 }
680 if s := e.stopCols("att-1"); s.state != tc.state || !s.lastDispatch.Valid {
681 t.Fatalf("att-1 = %+v, want %s with its dispatch marker", s, tc.state)
682 }
683 })
684 }
685}
686
687// leakRunner wraps the fake provider. While fail is set, Launch returns the
688// error fail builds from the spec instead of launching.
689type leakRunner struct {
690 *isolatedjob.Fake
691 fail func(isolatedjob.LaunchSpec) error
692}
693
694func (l *leakRunner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
695 if l.fail != nil {
696 return "", l.fail(s)
697 }
698 return l.Fake.Launch(ctx, s)
699}
700
701// TestLaunchProviderTextNeverReturned: a provider error whose text quotes
702// the bootstrap must not carry the instance code into a returned error or an
703// audit row, from Launch or from Replay. The isolatedjob sentinel it wraps
704// still matches.
705func TestLaunchProviderTextNeverReturned(t *testing.T) {
706 cases := []struct {
707 name string
708 fail func(isolatedjob.LaunchSpec) error
709 want error // nil: a throttle, which Launch and Replay do not return
710 }{
711 {"invalid", func(s isolatedjob.LaunchSpec) error {
712 return fmt.Errorf("ValidationException: RunHookPayload %s rejected: %w", s.Bootstrap, isolatedjob.ErrInvalid)
713 }, isolatedjob.ErrInvalid},
714 {"conflict", func(s isolatedjob.LaunchSpec) error {
715 return fmt.Errorf("IdempotentParameterMismatch for %s: %w", s.Bootstrap, isolatedjob.ErrConflict)
716 }, isolatedjob.ErrConflict},
717 {"unclassified", func(s isolatedjob.LaunchSpec) error {
718 return fmt.Errorf("InternalFailure echoing %s", s.Bootstrap)
719 }, ErrProviderLaunch},
720 {"throttle", func(s isolatedjob.LaunchSpec) error {
721 return fmt.Errorf("TooManyRequests for %s: %w", s.Bootstrap, isolatedjob.ErrThrottled)
722 }, nil},
723 }
724 for _, tc := range cases {
725 t.Run(tc.name, func(t *testing.T) {
726 t.Parallel()
727 e := newLaunchEnv(t)
728 leak := &leakRunner{Fake: e.fake, fail: tc.fail}
729 e.run = leak
730 e.newController()
731 e.audit()
732 check := func(path string, err error) {
733 t.Helper()
734 if tc.want == nil {
735 if err != nil {
736 t.Fatalf("%s with a throttle = %v, want nil", path, err)
737 }
738 } else if !errors.Is(err, tc.want) {
739 t.Fatalf("%s = %v, want it to match %v", path, err, tc.want)
740 }
741 if err != nil && (strings.Contains(err.Error(), testCode) || strings.Contains(err.Error(), "launch_id")) {
742 t.Fatalf("%s error %q carries the provider's text and the instance code", path, err)
743 }
744 e.noCodeInAudit()
745 }
746 v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
747 check("Launch", err)
748 if tc.want != nil && v != (JobView{}) {
749 t.Fatalf("Launch view = %+v, want zero with an error", v)
750 }
751 check("Replay", e.c.Replay(e.ctx))
752 if j, _ := e.job("att-1"); j.state != JobWaiting || j.ref.Valid {
753 t.Fatalf("job = state %q ref %v, want waiting with no ref", j.state, j.ref)
754 }
755 })
756 }
757}
758
759func TestLaunchRefusals(t *testing.T) {
760 // launchOld launches att-old for by and returns its ref.
761 launchOld := func(e *launchEnv, by hostedwire.KeyID) {
762 e.t.Helper()
763 if _, err := e.c.Launch(e.ctx, by, instKey, request("att-old")); err != nil {
764 e.t.Fatalf("Launch att-old = %v", err)
765 }
766 }
767 proveStopped := func(e *launchEnv) {
768 e.exec(`UPDATE jobs SET stop_proof_json = '{"state":"stopped"}' WHERE attempt_id = 'att-old'`)
769 }
770 replacing := func(q *LaunchRequest) { q.Replaces = "att-old" }
771 cases := []struct {
772 name string
773 setup func(*launchEnv)
774 by hostedwire.KeyID
775 key hostedwire.VerifyKey
776 edit func(*LaunchRequest)
777 want error // nil: the launch goes ahead
778 }{
779 {name: "flag off", setup: func(e *launchEnv) { e.cfg.Enabled = false; e.newController(); e.audit() }, want: ErrDisabled},
780 {name: "operator role", key: opKey, want: ErrForbidden},
781 {name: "no key ID", by: "-", want: ErrForbidden},
782 {name: "image not allowed", edit: func(q *LaunchRequest) { q.Image = imgOther }, want: ErrImageNotAllowed},
783 {name: "no audit yet", setup: func(e *launchEnv) { e.newController() }, want: ErrNetworkAudit},
784 {name: "stale audit", setup: func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) }, want: ErrNetworkAudit},
785 {name: "audit exactly 5 min old", setup: func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge) }},
786 {name: "failing audit", setup: func(e *launchEnv) {
787 e.fake.SetAudit(isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true}, nil)
788 if err := e.c.RunAudit(e.ctx); err == nil {
789 e.t.Fatal("RunAudit with a route out = nil, want a failure")
790 }
791 }, want: ErrNetworkAudit},
792 {name: "audit call fails", setup: func(e *launchEnv) {
793 e.fake.SetAudit(isolatedjob.NetworkAudit{}, errors.New("api down"))
794 _ = e.c.RunAudit(e.ctx)
795 }, want: ErrNetworkAudit},
796 {name: "empty instance code", edit: func(q *LaunchRequest) { q.InstanceCode = "" }, want: isolatedjob.ErrInvalid},
797 {name: "non-ASCII instance code", edit: func(q *LaunchRequest) { q.InstanceCode = testCode + "é" }, want: isolatedjob.ErrInvalid},
798 {name: "empty task", edit: func(q *LaunchRequest) { q.TaskID = "" }, want: isolatedjob.ErrInvalid},
799 {name: "lifetime within the stop margin", edit: func(q *LaunchRequest) { q.MaxLifetime = StopBefore }, want: isolatedjob.ErrInvalid},
800 {name: "live replaced attempt", setup: func(e *launchEnv) { launchOld(e, "inst-1") }, edit: replacing, want: ErrReplacementLive},
801 {name: "replaced attempt unknown", edit: replacing, want: ErrReplacementLive},
802 {name: "replaced attempt of another key", setup: func(e *launchEnv) { launchOld(e, "inst-2"); proveStopped(e) }, edit: replacing, want: ErrReplacementLive},
803 {name: "replaced attempt proven stopped", setup: func(e *launchEnv) { launchOld(e, "inst-1"); proveStopped(e) }, edit: replacing},
804 }
805 for _, tc := range cases {
806 t.Run(tc.name, func(t *testing.T) {
807 t.Parallel()
808 e := newLaunchEnv(t)
809 if tc.setup != nil {
810 tc.setup(e)
811 }
812 by, key := tc.by, tc.key
813 if by == "" {
814 by = "inst-1"
815 } else if by == "-" {
816 by = ""
817 }
818 if key.Role == "" {
819 key = instKey
820 }
821 q := request("att-1")
822 if tc.edit != nil {
823 tc.edit(&q)
824 }
825 callsBefore, rowsBefore := e.fake.Calls(isolatedjob.OpLaunch), e.jobCount()
826 v, err := e.c.Launch(e.ctx, by, key, q)
827 if tc.want == nil {
828 if err != nil || v.State != JobStarting {
829 t.Fatalf("Launch = (%+v, %v), want it started", v, err)
830 }
831 return
832 }
833 if !errors.Is(err, tc.want) || v != (JobView{}) {
834 t.Fatalf("Launch = (%+v, %v), want (zero view, %v)", v, err, tc.want)
835 }
836 if strings.Contains(err.Error(), testCode) {
837 t.Fatalf("error %q holds the instance code", err)
838 }
839 if n := e.fake.Calls(isolatedjob.OpLaunch); n != callsBefore {
840 t.Fatalf("provider launches = %d, want %d: a refusal calls nothing", n, callsBefore)
841 }
842 if n := e.jobCount(); n != rowsBefore {
843 t.Fatalf("job rows = %d, want %d: a refusal saves no intent", n, rowsBefore)
844 }
845 if got := e.lastAudit(); got.Action != actionLaunchRefused || got.Actor != by || got.Attempt != "att-1" {
846 t.Fatalf("last audit = %+v, want a %s row for %q att-1", got, actionLaunchRefused, by)
847 }
848 e.noCodeInAudit()
849 })
850 }
851}
852
853func TestThrottleWaitsThenReplays(t *testing.T) {
854 e := newLaunchEnv(t)
855 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
856 v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
857 if err != nil || v.State != JobWaiting || v.VMRef != "" || v.LaunchID == "" {
858 t.Fatalf("throttled Launch = (%+v, %v), want a waiting view with a launch ID and no error", v, err)
859 }
860 if live := e.fake.LiveByAttempt(); len(live) != 0 {
861 t.Fatalf("live VMs after a throttle = %v, want none", live)
862 }
863 if got := e.lastAudit(); got.Action != actionLaunchThrottled {
864 t.Fatalf("last audit = %+v, want %s", got, actionLaunchThrottled)
865 }
866
867 e.clk.AdvanceMono(time.Minute)
868 if err := e.c.Replay(e.ctx); err != nil {
869 t.Fatalf("Replay = %v", err)
870 }
871 j, _ := e.job("att-1")
872 if j.state != JobStarting || !j.ref.Valid || j.launchID != v.LaunchID {
873 t.Fatalf("job after Replay = %+v, want starting with a ref and launch ID %s", j, v.LaunchID)
874 }
875 if live := e.fake.LiveByAttempt(); live["att-1"] != 1 || len(live) != 1 {
876 t.Fatalf("live VMs = %v, want one for att-1", live)
877 }
878 if err := e.c.Replay(e.ctx); err != nil {
879 t.Fatalf("second Replay = %v", err)
880 }
881 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 2 {
882 t.Fatalf("provider launches = %d, want 2: a saved ref is never replayed", n)
883 }
884 e.noCodeInAudit()
885}
886
887func TestThrottleThenRefusal(t *testing.T) {
888 cases := []struct {
889 name string
890 refuse func(*launchEnv)
891 restore func(*launchEnv) // nil when the refusal is permanent
892 want string
893 }{
894 {"flag off", func(e *launchEnv) { e.c.cfg.Enabled = false }, func(e *launchEnv) { e.c.cfg.Enabled = true }, JobWaiting},
895 {"image removed", func(e *launchEnv) { delete(e.c.cfg.Images, imgA) }, func(e *launchEnv) { e.c.cfg.Images[imgA] = true }, JobWaiting},
896 {"stale audit", func(e *launchEnv) { e.clk.AdvanceMono(AuditMaxAge + time.Nanosecond) }, func(e *launchEnv) { e.audit() }, JobWaiting},
897 {"failing audit", func(e *launchEnv) {
898 e.fake.SetAudit(isolatedjob.NetworkAudit{ResolverDisabled: true, RouteOutAbsent: true}, nil)
899 _ = e.c.RunAudit(e.ctx)
900 }, func(e *launchEnv) {
901 e.fake.SetAudit(isolatedjob.NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true}, nil)
902 e.audit()
903 }, JobWaiting},
904 {"stop requested", func(e *launchEnv) {
905 e.exec(`UPDATE jobs SET stop_requested_t = ?, stop_reason = 'asked' WHERE attempt_id = 'att-1'`, int64(e.store.Clock().Now()))
906 }, nil, JobAbandoned},
907 {"stop time passed", func(e *launchEnv) {
908 e.clk.AdvanceMono(2*time.Hour - StopBefore) // exactly stop_t
909 e.audit()
910 }, nil, JobAbandoned},
911 }
912 for _, tc := range cases {
913 t.Run(tc.name, func(t *testing.T) {
914 t.Parallel()
915 e := newLaunchEnv(t)
916 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
917 if v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil || v.State != JobWaiting {
918 t.Fatalf("throttled Launch = (%+v, %v), want waiting", v, err)
919 }
920 before, _ := e.job("att-1")
921 tc.refuse(e)
922 if err := e.c.Replay(e.ctx); err != nil {
923 t.Fatalf("Replay = %v", err)
924 }
925 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 {
926 t.Fatalf("provider launches = %d, want 1: a failed gate calls nothing", n)
927 }
928 j, ok := e.job("att-1")
929 if !ok || j.state != tc.want || j.ref.Valid || j.specJSON != before.specJSON || j.launchID != before.launchID {
930 t.Fatalf("job after Replay = %+v (found %v), want it kept, %s, with no ref", j, ok, tc.want)
931 }
932 if tc.want == JobAbandoned {
933 if got := e.lastAudit(); got.Action != actionReplayAbandoned || got.Attempt != "att-1" {
934 t.Fatalf("last audit = %+v, want %s for att-1", got, actionReplayAbandoned)
935 }
936 // Abandoned is final: a later replay with every gate open
937 // still calls nothing.
938 e.audit()
939 if err := e.c.Replay(e.ctx); err != nil {
940 t.Fatalf("Replay after abandoning = %v", err)
941 }
942 if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 {
943 t.Fatalf("provider launches after abandoning = %d, want 1", n)
944 }
945 return
946 }
947 // A transient refusal keeps the intent for a later replay.
948 tc.restore(e)
949 if err := e.c.Replay(e.ctx); err != nil {
950 t.Fatalf("Replay once the gate passes = %v", err)
951 }
952 if j, _ := e.job("att-1"); j.state != JobStarting || !j.ref.Valid {
953 t.Fatalf("job once the gate passes = state %q ref %v, want starting with a ref", j.state, j.ref)
954 }
955 if live := e.fake.LiveByAttempt(); live["att-1"] != 1 {
956 t.Fatalf("live VMs = %v, want one for att-1", live)
957 }
958 })
959 }
960}
961
962func TestDeadlines(t *testing.T) {
963 cases := []struct {
964 launched T
965 life time.Duration
966 deadline, drain, stopTime T
967 }{
968 {0, 8 * time.Hour, T(8 * time.Hour), T(7*time.Hour + 15*time.Minute), T(7*time.Hour + 50*time.Minute)},
969 {0, 15 * time.Minute, T(15 * time.Minute), 0, T(5 * time.Minute)},
970 {T(time.Hour), 15 * time.Minute, T(75 * time.Minute), T(time.Hour), T(65 * time.Minute)},
971 {T(time.Hour), 5 * time.Minute, T(65 * time.Minute), T(time.Hour), T(time.Hour)},
972 {T(time.Hour), 0, T(time.Hour), T(time.Hour), T(time.Hour)},
973 }
974 for _, tc := range cases {
975 d, dr, s := Deadlines(tc.launched, tc.life)
976 if d != tc.deadline || dr != tc.drain || s != tc.stopTime {
977 t.Errorf("Deadlines(%v, %v) = (%v, %v, %v), want (%v, %v, %v)", time.Duration(tc.launched), tc.life,
978 time.Duration(d), time.Duration(dr), time.Duration(s),
979 time.Duration(tc.deadline), time.Duration(tc.drain), time.Duration(tc.stopTime))
980 }
981 }
982}
983