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 "errors"
6 "fmt"
7 "slices"
8 "sync"
9 "sync/atomic"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/isolatedjob"
14 "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
15)
16
17// slowRunner wraps the fake provider. Each Get and List moves the fake
18// clock on by getDelay or listDelay while it runs, so the controller time
19// before a call and after it differ. List also returns extra, as VMs the
20// provider holds that no job knows.
21type slowRunner struct {
22 *isolatedjob.Fake
23 clk *isolatedjobtest.FakeClock
24 getDelay, listDelay time.Duration
25 mu sync.Mutex
26 extra []isolatedjob.Job
27}
28
29func (r *slowRunner) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) {
30 r.clk.AdvanceMono(r.getDelay)
31 return r.Fake.Get(ctx, ref)
32}
33
34func (r *slowRunner) List(ctx context.Context) ([]isolatedjob.Job, error) {
35 r.clk.AdvanceMono(r.listDelay)
36 jobs, err := r.Fake.List(ctx)
37 if err != nil {
38 return nil, err
39 }
40 r.mu.Lock()
41 defer r.mu.Unlock()
42 return append(jobs, r.extra...), nil
43}
44
45func (r *slowRunner) setExtra(jobs ...isolatedjob.Job) {
46 r.mu.Lock()
47 defer r.mu.Unlock()
48 r.extra = jobs
49}
50
51// gatedGet wraps the fake provider's Get. Call n (counting from 1) answers
52// what answer(n) gives. Call 1 closes entered and waits for release, so a
53// test can start a second caller while the first is inside the provider
54// call.
55type gatedGet struct {
56 *isolatedjob.Fake
57 answer func(ctx context.Context, n int, ref isolatedjob.Ref) (isolatedjob.Job, error)
58 mu sync.Mutex
59 n int
60 entered chan struct{}
61 release chan struct{}
62}
63
64func newGatedGet(f *isolatedjob.Fake, answer func(context.Context, int, isolatedjob.Ref) (isolatedjob.Job, error)) *gatedGet {
65 return &gatedGet{Fake: f, answer: answer, entered: make(chan struct{}), release: make(chan struct{})}
66}
67
68func (g *gatedGet) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) {
69 g.mu.Lock()
70 g.n++
71 n := g.n
72 g.mu.Unlock()
73 if n == 1 {
74 close(g.entered)
75 <-g.release
76 }
77 return g.answer(ctx, n, ref)
78}
79
80// watchdog bounds every wait in the concurrency tests. A healthy run never
81// reaches it.
82const watchdog = 5 * time.Second
83
84// lockWaits makes e's controller report, on the returned channel, each
85// time a caller has to wait for an attempt lock.
86func lockWaits(e *launchEnv) chan string {
87 waits := make(chan string, 16)
88 e.c.attempts.waiting = func(id string) { waits <- id }
89 return waits
90}
91
92// overlap runs two Refresh passes on e: the second starts while the first
93// is inside its Get (held by gg). The second then either waits for the
94// attempt lock, seen through the lock's waiting hook, or, when nothing
95// serialises the two, runs to its end; only then is the first let go.
96func overlap(t *testing.T, e *launchEnv, gg *gatedGet) [2]error {
97 t.Helper()
98 waits := lockWaits(e)
99 first, second := make(chan error, 1), make(chan error, 1)
100 go func() { first <- e.c.Refresh(e.ctx) }()
101 select {
102 case <-gg.entered:
103 case <-time.After(watchdog):
104 t.Fatal("the first Refresh never reached the provider")
105 }
106 go func() { second <- e.c.Refresh(e.ctx) }()
107 var out [2]error
108 secondDone := false
109 select {
110 case <-waits: // serialised: the second waits for the attempt
111 case out[1] = <-second:
112 secondDone = true
113 case <-time.After(watchdog):
114 t.Fatal("the second Refresh neither waited for the attempt nor finished")
115 }
116 close(gg.release)
117 for i, ch := range []chan error{first, second} {
118 if i == 1 && secondDone {
119 break
120 }
121 select {
122 case out[i] = <-ch:
123 case <-time.After(watchdog):
124 t.Fatalf("Refresh %d did not finish", i)
125 }
126 }
127 return out
128}
129
130func notFoundAnswer(ref isolatedjob.Ref) (isolatedjob.Job, error) {
131 return isolatedjob.Job{}, fmt.Errorf("%w: %s (stale read)", isolatedjob.ErrNotFound, ref)
132}
133
134// blockLaunch wraps the fake provider's Launch. Once armed, the next
135// Launch signals entered and waits for release before reaching the fake.
136type blockLaunch struct {
137 *isolatedjob.Fake
138 armed atomic.Bool
139 entered chan struct{}
140 release chan struct{}
141}
142
143func (b *blockLaunch) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
144 if b.armed.CompareAndSwap(true, false) {
145 close(b.entered)
146 <-b.release
147 }
148 return b.Fake.Launch(ctx, s)
149}
150
151// TestStopWaitsForDispatch: a Stop that arrives while a launch dispatch is
152// between its gate check and the provider's answer waits for the answer
153// (R18), so proof for a job with no Ref can never be issued while a
154// dispatched launch may still create its VM.
155func TestStopWaitsForDispatch(t *testing.T) {
156 t.Parallel()
157 type result struct {
158 err error
159 }
160 run := func(t *testing.T, viaReplay bool, fault isolatedjob.Fault) (*launchEnv, chan result) {
161 e := newLaunchEnv(t)
162 bl := &blockLaunch{Fake: e.fake, entered: make(chan struct{}), release: make(chan struct{})}
163 e.run = bl
164 e.newController()
165 e.audit()
166 waits := lockWaits(e)
167
168 launched := make(chan error, 1)
169 if viaReplay {
170 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
171 if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil {
172 t.Fatalf("throttled Launch = %v", err)
173 }
174 bl.armed.Store(true)
175 go func() { launched <- e.c.Replay(e.ctx) }()
176 } else {
177 bl.armed.Store(true)
178 go func() {
179 _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
180 launched <- err
181 }()
182 }
183 <-bl.entered // past every gate; the provider call is in flight
184 dispatchedAt := e.store.Clock().Now()
185 if s := e.stopCols("att-1"); !s.lastDispatch.Valid || T(s.lastDispatch.Int64) != dispatchedAt {
186 t.Fatalf("last_dispatch_t during the provider call = %v, want %d", s.lastDispatch, dispatchedAt)
187 }
188 if fault != "" {
189 e.fake.Inject(isolatedjob.OpLaunch, fault)
190 }
191
192 stopped := make(chan result, 1)
193 go func() {
194 _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done")
195 stopped <- result{err}
196 }()
197 select {
198 case <-waits: // Stop waits for the attempt, as it must
199 case r := <-stopped:
200 t.Fatalf("Stop returned (%v) while the launch call was in flight; it must wait for the answer", r.err)
201 case <-time.After(watchdog):
202 t.Fatal("Stop neither waited for the attempt nor returned")
203 }
204
205 // However long the call takes, nothing proves the attempt stopped.
206 // Refresh has nothing to do for att-1 yet; if a broken lock let the
207 // Stop through, it waits for the attempt instead, which must not
208 // prove anything either.
209 e.clk.AdvanceMono(3 * time.Minute)
210 refreshed := make(chan error, 1)
211 go func() { refreshed <- e.c.Refresh(e.ctx) }()
212 done := false
213 select {
214 case <-refreshed:
215 done = true
216 case <-waits:
217 case <-time.After(watchdog):
218 t.Fatal("Refresh neither finished nor waited for the attempt")
219 }
220 close(bl.release)
221 if err := <-launched; viaReplay && err != nil && fault == "" {
222 t.Fatalf("Replay = %v", err)
223 }
224 if !done {
225 <-refreshed
226 }
227 return e, stopped
228 }
229
230 t.Run("replay paused after its gate check, launch reply lost", func(t *testing.T) {
231 e, stopped := run(t, true, isolatedjob.FaultLostReply)
232 if r := <-stopped; !errors.Is(r.err, ErrStopPending) {
233 t.Fatalf("Stop after the dispatch settled = %v, want ErrStopPending", r.err)
234 }
235 e.clk.AdvanceMono(3 * time.Minute)
236 e.refresh()
237 if s := e.stopCols("att-1"); s.proof.Valid && e.fake.LiveByAttempt()["att-1"] > 0 {
238 t.Fatalf("proof %s while the dispatched launch's VM is live", s.proof.String)
239 }
240 if e.fake.LiveByAttempt()["att-1"] != 1 {
241 t.Fatal("the lost launch made no VM; the test needs one")
242 }
243 })
244 t.Run("delayed provider launch", func(t *testing.T) {
245 e, stopped := run(t, false, "")
246 if r := <-stopped; !errors.Is(r.err, ErrStopPending) {
247 t.Fatalf("Stop after the launch answered = %v, want ErrStopPending (the VM is stopping)", r.err)
248 }
249 s := e.stopCols("att-1")
250 if s.proof.Valid {
251 t.Fatalf("proof %s for a VM that is only stopping", s.proof.String)
252 }
253 if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.VMRef == "" {
254 t.Fatalf("Get after the delayed launch = (%+v, %v), want the job to hold its VM ref", v, err)
255 }
256 })
257}
258
259// TestStopIntentWithoutRefFences: Ref-less proof waits ReflessProofDelay
260// after the last dispatch as well as the stop request (R19), and the List
261// that proves it is judged by when it began and by every VM it shows that
262// is not terminal.
263func TestStopIntentWithoutRefFences(t *testing.T) {
264 t.Parallel()
265 stopIntent := func(t *testing.T, e *launchEnv) T {
266 t.Helper()
267 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
268 if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil {
269 t.Fatalf("throttled Launch = %v", err)
270 }
271 asked := e.store.Clock().Now()
272 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
273 t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err)
274 }
275 return asked
276 }
277 t.Run("proof waits past the last dispatch", func(t *testing.T) {
278 e := newLaunchEnv(t)
279 e.clk.AdvanceMono(time.Minute)
280 at := e.store.Clock().Now()
281 asked := stopIntent(t, e)
282 if s := e.stopCols("att-1"); !s.lastDispatch.Valid || T(s.lastDispatch.Int64) != at {
283 t.Fatalf("last_dispatch_t after a throttled launch = %v, want %d", s.lastDispatch, at)
284 }
285 // A dispatch that crossed the stop request (a crash mid-call, or a
286 // path without the attempt lock) leaves a later mark.
287 dispatched := asked + T(time.Minute)
288 e.exec(`UPDATE jobs SET last_dispatch_t = ? WHERE attempt_id = 'att-1'`, int64(dispatched))
289 e.clk.AdvanceMono(ReflessProofDelay + 30*time.Second)
290 e.refresh()
291 if s := e.stopCols("att-1"); s.proof.Valid {
292 t.Fatalf("proof %s from a list begun %v after the last dispatch",
293 s.proof.String, time.Duration(e.store.Clock().Now()-dispatched))
294 }
295 e.clk.AdvanceMono(30 * time.Second)
296 e.refresh()
297 e.wireProof("att-1")
298 })
299 t.Run("slow list is judged by its start", func(t *testing.T) {
300 e := newLaunchEnv(t)
301 slow := &slowRunner{Fake: e.fake, clk: e.clk, listDelay: 30 * time.Second}
302 e.run = slow
303 e.newController()
304 e.audit()
305 asked := stopIntent(t, e)
306 e.clk.AdvanceMono(ReflessProofDelay - 20*time.Second)
307 e.refresh() // begins 20 s early, ends 10 s late
308 if s := e.stopCols("att-1"); s.proof.Valid {
309 t.Fatalf("proof %s from a list begun %v after the request", s.proof.String, ReflessProofDelay-20*time.Second)
310 }
311 e.refresh() // begins 10 s late
312 if w := e.wireProof("att-1"); T(w.ObservedAt) != asked+T(ReflessProofDelay+40*time.Second) {
313 t.Fatalf("proof observed at %d, want the end of the second list, %d", w.ObservedAt, asked+T(ReflessProofDelay+40*time.Second))
314 }
315 })
316 t.Run("an unknown-state VM outside the table blocks proof", func(t *testing.T) {
317 e := newLaunchEnv(t)
318 slow := &slowRunner{Fake: e.fake, clk: e.clk}
319 slow.setExtra(isolatedjob.Job{Ref: "vm-ghost", State: isolatedjob.StateUnknown})
320 e.run = slow
321 e.newController()
322 e.audit()
323 stopIntent(t, e)
324 e.clk.AdvanceMono(ReflessProofDelay + time.Minute)
325 e.refresh()
326 if s := e.stopCols("att-1"); s.proof.Valid {
327 t.Fatalf("proof %s while the list shows an unlinked VM in an unknown state", s.proof.String)
328 }
329 slow.setExtra(isolatedjob.Job{Ref: "vm-ghost", State: isolatedjob.StateStopped})
330 e.refresh()
331 e.wireProof("att-1")
332 })
333}
334
335// TestStopNotFoundSlowGet: the NotFoundConfirm gap runs from the end of the
336// first not-found Get to the start of the second, so slow calls cannot
337// shrink it.
338func TestStopNotFoundSlowGet(t *testing.T) {
339 t.Parallel()
340 e := newLaunchEnv(t)
341 slow := &slowRunner{Fake: e.fake, clk: e.clk, getDelay: 10 * time.Second}
342 e.run = slow
343 e.newController()
344 e.audit()
345 ref := e.launchWith("att-1", 2*time.Hour)
346 e.fake.Tick()
347 e.fake.Vanish(ref)
348
349 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
350 t.Fatalf("Stop on the first not-found = %v, want ErrStopPending", err)
351 }
352 first := T(e.stopCols("att-1").notFoundSince.Int64)
353 if first != e.store.Clock().Now() {
354 t.Fatalf("notfound_since_t = %d, want the end of the Get, %d", first, e.store.Clock().Now())
355 }
356 e.clk.AdvanceMono(NotFoundConfirm - 5*time.Second)
357 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
358 t.Fatalf("Stop on a not-found Get begun %v after the first ended = %v, want ErrStopPending",
359 NotFoundConfirm-5*time.Second, err)
360 }
361 e.clk.AdvanceMono(time.Second) // the next Get begins NotFoundConfirm + 6 s after the first ended
362 if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.VMRef != ref {
363 t.Fatalf("Stop on a confirming not-found = (%+v, %v), want proof", p, err)
364 }
365}
366
367// TestStopNotFoundRacesLiveRead: a not-found that a Refresh read before a
368// live read by another Refresh must not be saved after it (R18).
369func TestStopNotFoundRacesLiveRead(t *testing.T) {
370 t.Parallel()
371 e := newLaunchEnv(t)
372 e.launchWith("att-1", 2*time.Hour)
373 e.fake.Tick()
374 gg := newGatedGet(e.fake, func(ctx context.Context, n int, ref isolatedjob.Ref) (isolatedjob.Job, error) {
375 if n == 1 {
376 return notFoundAnswer(ref)
377 }
378 return e.fake.Get(ctx, ref)
379 })
380 e.run = gg
381 e.newController()
382
383 for i, err := range overlap(t, e, gg) {
384 if err != nil {
385 t.Fatalf("Refresh %d = %v", i, err)
386 }
387 }
388 if s := e.stopCols("att-1"); s.notFoundSince.Valid || s.state != JobRunning {
389 t.Fatalf("after a not-found and a live read: state %q notfound_since_t %v; want running and no not-found held",
390 s.state, s.notFoundSince)
391 }
392}
393
394// TestStopNotFoundClearedBeforeRestartStop: a live read clears a held
395// not-found even when the restart handling then stops the job and returns.
396func TestStopNotFoundClearedBeforeRestartStop(t *testing.T) {
397 t.Parallel()
398 e := newLaunchEnv(t)
399 flaky := &notFoundOnce{Fake: e.fake}
400 e.run = flaky
401 e.newController()
402 e.audit()
403 e.launchWith("att-1", 2*time.Hour)
404 e.fake.Tick()
405 e.down()
406 e.clk.AdvanceMono(time.Minute)
407 e.up()
408 e.clk.AdvanceMono(time.Second)
409
410 // The creator asks for a stop; the VM is stopping. Then one not-found.
411 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
412 t.Fatalf("Stop = %v, want ErrStopPending", err)
413 }
414 e.clk.AdvanceMono(time.Second)
415 flaky.n = 1
416 e.refresh()
417 if s := e.stopCols("att-1"); !s.notFoundSince.Valid {
418 t.Fatal("no not-found held after a not-found read")
419 }
420
421 // A live read with no age: the job is stopped as elapsed_unknown, and the
422 // Get inside that stop fails, so only the first live read can clear it.
423 e.clk.AdvanceMono(30 * time.Second)
424 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
425 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultThrottle)
426 _ = e.c.Refresh(e.ctx)
427 if s := e.stopCols("att-1"); s.notFoundSince.Valid {
428 t.Fatalf("notfound_since_t %d kept after a live read", s.notFoundSince.Int64)
429 }
430 e.clk.AdvanceMono(40 * time.Second)
431 flaky.n = 1
432 e.refresh()
433 if s := e.stopCols("att-1"); s.proof.Valid {
434 t.Fatalf("proof %s from not-founds with a live read between", s.proof.String)
435 }
436}
437
438// TestRestartOverlappingRefresh: two Refresh passes at once settle a
439// pre-restart job once (R18): never both re-based and stopped. A second
440// restart settles it again.
441func TestRestartOverlappingRefresh(t *testing.T) {
442 t.Parallel()
443 e := newLaunchEnv(t)
444 e.launchWith("att-1", 2*time.Hour)
445 e.fake.Tick()
446 e.down()
447 e.clk.AdvanceMono(10 * time.Minute)
448 e.clk.SetWall(testWall.Add(10 * time.Minute))
449 gg := newGatedGet(e.fake, func(ctx context.Context, n int, ref isolatedjob.Ref) (isolatedjob.Job, error) {
450 j, err := e.fake.Get(ctx, ref)
451 if n >= 2 {
452 j.ProviderAge, j.AgeKnown = 0, false
453 }
454 return j, err
455 })
456 e.run = gg
457 e.up()
458 e.clk.AdvanceMono(time.Second)
459
460 for i, err := range overlap(t, e, gg) {
461 if err != nil {
462 t.Fatalf("Refresh %d = %v", i, err)
463 }
464 }
465 rebased := e.hasAudit("", "att-1", actionRestartRebased, "")
466 stopped := e.stopCols("att-1").requested.Valid
467 if rebased == stopped {
468 t.Fatalf("after two overlapping passes: re-based %v, stopped %v; want exactly one", rebased, stopped)
469 }
470
471 // A second restart: the new process settles the job again; with no age
472 // it is stopped.
473 if !stopped {
474 e.run = e.fake
475 e.down()
476 e.clk.AdvanceMono(time.Minute)
477 e.up()
478 e.clk.AdvanceMono(time.Second)
479 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
480 e.refresh()
481 if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown {
482 t.Fatalf("after a second restart with no age: reason %v, want %s", s.reason, reasonElapsedUnknown)
483 }
484 }
485}
486
487// TestRestartRetriesFailedGet: a pre-restart job whose Get fails is retried;
488// after RestartGetTries failed passes in a row it is stopped as
489// elapsed_unknown, the stop request saved first (R20).
490func TestRestartRetriesFailedGet(t *testing.T) {
491 t.Parallel()
492 e := newLaunchEnv(t)
493 ref := e.launchWith("att-1", 2*time.Hour)
494 e.fake.Tick()
495 e.down()
496 e.clk.AdvanceMono(10 * time.Minute)
497 e.up()
498 e.clk.AdvanceMono(time.Second)
499
500 for pass := 1; pass <= RestartGetTries; pass++ {
501 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultThrottle)
502 err := e.c.Refresh(e.ctx)
503 if !errors.Is(err, isolatedjob.ErrThrottled) {
504 t.Fatalf("pass %d: Refresh = %v, want the Get error", pass, err)
505 }
506 s := e.stopCols("att-1")
507 if pass < RestartGetTries && (s.requested.Valid || len(e.fake.StopsIssued()) != 0) {
508 t.Fatalf("pass %d: stopped after %d failed reads, want %d first", pass, pass, RestartGetTries)
509 }
510 if pass == RestartGetTries {
511 if s.reason.String != reasonElapsedUnknown || !s.requested.Valid {
512 t.Fatalf("pass %d: requested %v reason %v; want a stop for %s", pass, s.requested, s.reason, reasonElapsedUnknown)
513 }
514 if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref}) {
515 t.Fatalf("provider stops = %v, want %s", got, ref)
516 }
517 }
518 e.clk.AdvanceMono(time.Minute)
519 }
520}
521
522// TestRestartWallJump: a forward wall jump across a restart with almost no
523// real downtime gives neither proof path any trusted time (R19).
524func TestRestartWallJump(t *testing.T) {
525 t.Parallel()
526 jump := func(e *launchEnv) {
527 e.down()
528 e.clk.AdvanceMono(time.Second)
529 e.clk.SetWall(testWall.Add(10 * time.Minute))
530 e.up()
531 e.clk.AdvanceMono(time.Second)
532 }
533 t.Run("not-found pair", func(t *testing.T) {
534 e := newLaunchEnv(t)
535 ref := e.launchWith("att-1", 2*time.Hour)
536 e.fake.Tick()
537 e.fake.Vanish(ref)
538 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
539 t.Fatalf("Stop on the first not-found = %v, want ErrStopPending", err)
540 }
541 jump(e)
542 now := e.store.Clock().Now()
543 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
544 t.Fatalf("Stop on a not-found after the wall jump = %v, want ErrStopPending: the first one is from before Open", err)
545 }
546 if s := e.stopCols("att-1"); T(s.notFoundSince.Int64) != now {
547 t.Fatalf("notfound_since_t = %v, want it restarted at %d", s.notFoundSince, now)
548 }
549 e.clk.AdvanceMono(NotFoundConfirm)
550 if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.VMRef != ref {
551 t.Fatalf("Stop on a confirming not-found = (%+v, %v), want proof", p, err)
552 }
553 })
554 t.Run("not-found saved at the restored time", func(t *testing.T) {
555 // With the wall clock behind the checkpoint, T restores to the
556 // checkpoint, so a not-found saved just before the exit equals
557 // OpenedAt. It is from before Open and does not count.
558 e := newLaunchEnv(t)
559 ref := e.launchWith("att-1", 2*time.Hour)
560 e.fake.Tick()
561 e.fake.Vanish(ref)
562 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
563 t.Fatalf("Stop on the first not-found = %v, want ErrStopPending", err)
564 }
565 e.down()
566 e.clk.SetWall(testWall.Add(-time.Hour))
567 e.up()
568 if s := e.stopCols("att-1"); T(s.notFoundSince.Int64) != e.store.OpenedAt() {
569 t.Fatalf("notfound_since_t %d, OpenedAt %d; the test needs them equal", s.notFoundSince.Int64, e.store.OpenedAt())
570 }
571 e.clk.AdvanceMono(NotFoundConfirm + time.Second)
572 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
573 t.Fatalf("Stop on a not-found paired with one saved at OpenedAt = %v, want ErrStopPending", err)
574 }
575 })
576 t.Run("ref-less list", func(t *testing.T) {
577 e := newLaunchEnv(t)
578 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
579 if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil {
580 t.Fatalf("throttled Launch = %v", err)
581 }
582 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
583 t.Fatalf("Stop = %v, want ErrStopPending", err)
584 }
585 jump(e)
586 e.refresh()
587 if s := e.stopCols("att-1"); s.proof.Valid {
588 t.Fatalf("proof %s 1 s after a restart", s.proof.String)
589 }
590 e.clk.AdvanceMono(ReflessProofDelay)
591 e.refresh()
592 e.wireProof("att-1")
593 })
594}
595
596// TestRestartRetriesPendingStop: once the elapsed_unknown stop is asked
597// for, Refresh sends it again on every pass, even when Get keeps failing
598// and the job already counts as settled after the restart (review r2,
599// finding 4).
600func TestRestartRetriesPendingStop(t *testing.T) {
601 t.Parallel()
602 e := newLaunchEnv(t)
603 ref := e.launchWith("att-1", 2*time.Hour)
604 e.fake.Tick()
605 e.down()
606 e.clk.AdvanceMono(10 * time.Minute)
607 e.up()
608 e.clk.AdvanceMono(time.Second)
609
610 for pass := 1; pass <= RestartGetTries; pass++ {
611 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultThrottle)
612 if pass == RestartGetTries {
613 e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle) // the first stop call fails
614 }
615 if err := e.c.Refresh(e.ctx); !errors.Is(err, isolatedjob.ErrThrottled) {
616 t.Fatalf("pass %d: Refresh = %v, want the throttle", pass, err)
617 }
618 }
619 if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown {
620 t.Fatalf("after %d failed reads: reason %v, want %s requested", RestartGetTries, s.reason, reasonElapsedUnknown)
621 }
622 if e.fake.LiveByAttempt()["att-1"] != 1 || len(e.fake.StopsIssued()) != 1 {
623 t.Fatalf("after a throttled stop: live %v, stops %v; want the VM running and one stop tried",
624 e.fake.LiveByAttempt(), e.fake.StopsIssued())
625 }
626
627 // Get still fails; Stop would now work. The next pass must send it.
628 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultThrottle)
629 if err := e.c.Refresh(e.ctx); !errors.Is(err, isolatedjob.ErrThrottled) {
630 t.Fatalf("pass %d: Refresh = %v, want the Get throttle", RestartGetTries+1, err)
631 }
632 if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref, ref}) {
633 t.Fatalf("provider stops = %v, want the stop sent again", got)
634 }
635 vms, err := e.fake.List(e.ctx)
636 if err != nil || len(vms) != 1 || vms[0].State != isolatedjob.StateStopping {
637 t.Fatalf("VMs after the retried stop = (%v, %v), want one stopping", vms, err)
638 }
639}
640
641// deadlineLaunch wraps the fake provider's Launch and records the context
642// deadline of each call.
643type deadlineLaunch struct {
644 *isolatedjob.Fake
645 mu sync.Mutex
646 calls []launchDeadline
647}
648
649type launchDeadline struct {
650 left time.Duration // time until the deadline, at the call
651 set bool
652}
653
654func (d *deadlineLaunch) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
655 dl, ok := ctx.Deadline()
656 d.mu.Lock()
657 d.calls = append(d.calls, launchDeadline{left: time.Until(dl), set: ok})
658 d.mu.Unlock()
659 return d.Fake.Launch(ctx, s)
660}
661
662// TestProviderLaunchTimeout: every provider Launch call, from Launch and
663// from Replay, carries a deadline at most ProviderLaunchTimeout (60 s)
664// away, derived from the caller's context (ruling R21).
665func TestProviderLaunchTimeout(t *testing.T) {
666 t.Parallel()
667 if ProviderLaunchTimeout != 60*time.Second || ProviderLaunchTimeout >= ReflessProofDelay {
668 t.Fatalf("ProviderLaunchTimeout = %v, want 60s and under ReflessProofDelay %v", ProviderLaunchTimeout, ReflessProofDelay)
669 }
670 e := newLaunchEnv(t)
671 dl := &deadlineLaunch{Fake: e.fake}
672 e.run = dl
673 e.newController()
674 e.audit()
675
676 long, cancel := context.WithTimeout(e.ctx, time.Hour)
677 defer cancel()
678 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
679 if _, err := e.c.Launch(long, "inst-1", instKey, request("att-1")); err != nil {
680 t.Fatalf("throttled Launch = %v", err)
681 }
682 if err := e.c.Replay(e.ctx); err != nil { // no deadline of its own
683 t.Fatalf("Replay = %v", err)
684 }
685 short, cancel2 := context.WithTimeout(e.ctx, 5*time.Second)
686 defer cancel2()
687 if _, err := e.c.Launch(short, "inst-1", instKey, request("att-2")); err != nil {
688 t.Fatalf("Launch = %v", err)
689 }
690 if len(dl.calls) != 3 {
691 t.Fatalf("provider launches = %d, want 3", len(dl.calls))
692 }
693 for i, c := range dl.calls {
694 limit := ProviderLaunchTimeout
695 if i == 2 {
696 limit = 5 * time.Second // the caller's own, shorter deadline still holds
697 }
698 if !c.set || c.left <= 0 || c.left > limit {
699 t.Fatalf("provider launch %d: deadline set %v, %v left; want one at most %v away", i, c.set, c.left, limit)
700 }
701 }
702}
703
704// deadlineAll wraps the fake provider and records, for every call other
705// than Launch, whether its context had a deadline at most
706// ProviderCallTimeout away.
707type deadlineAll struct {
708 *isolatedjob.Fake
709 mu sync.Mutex
710 bad []string
711 ops map[string]int
712}
713
714func (d *deadlineAll) note(ctx context.Context, op string) {
715 dl, ok := ctx.Deadline()
716 d.mu.Lock()
717 defer d.mu.Unlock()
718 d.ops[op]++
719 if left := time.Until(dl); !ok || left <= 0 || left > ProviderCallTimeout {
720 d.bad = append(d.bad, fmt.Sprintf("%s: deadline set %v, %v left", op, ok, left))
721 }
722}
723
724func (d *deadlineAll) Get(ctx context.Context, r isolatedjob.Ref) (isolatedjob.Job, error) {
725 d.note(ctx, "get")
726 return d.Fake.Get(ctx, r)
727}
728
729func (d *deadlineAll) List(ctx context.Context) ([]isolatedjob.Job, error) {
730 d.note(ctx, "list")
731 return d.Fake.List(ctx)
732}
733
734func (d *deadlineAll) Stop(ctx context.Context, r isolatedjob.Ref, why string) error {
735 d.note(ctx, "stop")
736 return d.Fake.Stop(ctx, r, why)
737}
738
739func (d *deadlineAll) Suspend(ctx context.Context, r isolatedjob.Ref) error {
740 d.note(ctx, "suspend")
741 return d.Fake.Suspend(ctx, r)
742}
743
744func (d *deadlineAll) Resume(ctx context.Context, r isolatedjob.Ref) error {
745 d.note(ctx, "resume")
746 return d.Fake.Resume(ctx, r)
747}
748
749func (d *deadlineAll) AuditNetwork(ctx context.Context) (isolatedjob.NetworkAudit, error) {
750 d.note(ctx, "audit")
751 return d.Fake.AuditNetwork(ctx)
752}
753
754// TestProviderCallsBounded: every provider call other than Launch, the
755// network audit included, carries a deadline at most ProviderCallTimeout
756// away, though the caller's context has none (ruling R27).
757func TestProviderCallsBounded(t *testing.T) {
758 t.Parallel()
759 e := newLaunchEnv(t)
760 d := &deadlineAll{Fake: e.fake, ops: map[string]int{}}
761 c, err := New(e.cfg, Deps{Store: e.store, Runner: d, Auditor: d, Alerter: &recordingAlerter{}})
762 if err != nil {
763 t.Fatal(err)
764 }
765 e.c = c
766 e.audit()
767 e.launchWith("att-1", 2*time.Hour)
768 e.fake.Tick()
769 e.reap()
770 e.suspendJob()
771 if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) {
772 t.Fatalf("Resume = %v, want ErrResumePending", err)
773 }
774 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "done"); !errors.Is(err, ErrStopPending) {
775 t.Fatalf("Stop = %v, want ErrStopPending", err)
776 }
777 for _, op := range []string{"get", "list", "stop", "suspend", "resume", "audit"} {
778 if d.ops[op] == 0 {
779 t.Fatalf("no %s call made; calls %v", op, d.ops)
780 }
781 }
782 if len(d.bad) > 0 {
783 t.Fatalf("unbounded provider calls: %v", d.bad)
784 }
785}
786
787// ctxBlock wraps the fake provider. A call to op closes entered and then
788// waits for its context to end.
789type ctxBlock struct {
790 *isolatedjob.Fake
791 op isolatedjob.Op
792 entered chan struct{}
793}
794
795func (b *ctxBlock) block(ctx context.Context, op isolatedjob.Op) (bool, error) {
796 if op != b.op {
797 return false, nil
798 }
799 close(b.entered)
800 <-ctx.Done()
801 return true, ctx.Err()
802}
803
804func (b *ctxBlock) Suspend(ctx context.Context, r isolatedjob.Ref) error {
805 if held, err := b.block(ctx, isolatedjob.OpSuspend); held {
806 return err
807 }
808 return b.Fake.Suspend(ctx, r)
809}
810
811func (b *ctxBlock) Resume(ctx context.Context, r isolatedjob.Ref) error {
812 if held, err := b.block(ctx, isolatedjob.OpResume); held {
813 return err
814 }
815 return b.Fake.Resume(ctx, r)
816}
817
818// TestRefreshRecoveryCallsCancel: the suspend and the resume Refresh sends
819// again for a pause or resume it is finishing end when Refresh's context
820// is cancelled; they are not detached from it (B2-2, R27).
821func TestRefreshRecoveryCallsCancel(t *testing.T) {
822 t.Parallel()
823 for _, op := range []isolatedjob.Op{isolatedjob.OpSuspend, isolatedjob.OpResume} {
824 e := runningJob(t)
825 if op == isolatedjob.OpSuspend { // suspending, the VM still running
826 g := e.drain()
827 e.ack(g)
828 e.fake.Inject(isolatedjob.OpSuspend, isolatedjob.FaultThrottle)
829 if err := e.c.Suspend(e.ctx, "inst-1", instKey, "att-1", g); err == nil {
830 t.Fatal("throttled Suspend = nil, want its error")
831 }
832 } else { // resuming, the VM still suspended
833 e.suspendJob()
834 e.fake.Inject(isolatedjob.OpResume, isolatedjob.FaultThrottle)
835 if _, err := e.resume("op-1"); !errors.Is(err, ErrResumePending) {
836 t.Fatalf("throttled Resume = %v, want ErrResumePending", err)
837 }
838 }
839 b := &ctxBlock{Fake: e.fake, op: op, entered: make(chan struct{})}
840 e.run = b
841 e.newController()
842 ctx, cancel := context.WithCancel(e.ctx)
843 done := make(chan error, 1)
844 go func() { done <- e.c.Refresh(ctx) }()
845 select {
846 case <-b.entered:
847 case <-time.After(5 * time.Second):
848 cancel()
849 t.Fatalf("Refresh never sent the %s again", op)
850 }
851 cancel()
852 select {
853 case <-done:
854 case <-time.After(5 * time.Second):
855 t.Fatalf("Refresh still in its %s call 5 s after its context was cancelled", op)
856 }
857 }
858}
859