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 "encoding/json"
7 "errors"
8 "fmt"
9 "slices"
10 "strings"
11 "sync"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/hostedwire"
16 "amadan.net/oficina/equipo/internal/isolatedjob"
17)
18
19// stopCols are the jobs columns stop and refresh write.
20type stopCols struct {
21 state string
22 requested, notFoundSince sql.NullInt64
23 lastDispatch sql.NullInt64
24 reason, proof sql.NullString
25 launched, deadline, drain, stop int64
26}
27
28func (e *launchEnv) stopCols(attempt string) stopCols {
29 e.t.Helper()
30 var s stopCols
31 if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
32 return tx.QueryRowContext(e.ctx, `SELECT state, stop_requested_t, notfound_since_t, last_dispatch_t, stop_reason, stop_proof_json,
33 launched_t, deadline_t, drain_t, stop_t FROM jobs WHERE attempt_id = ?`, attempt).Scan(
34 &s.state, &s.requested, &s.notFoundSince, &s.lastDispatch, &s.reason, &s.proof, &s.launched, &s.deadline, &s.drain, &s.stop)
35 }); err != nil {
36 e.t.Fatalf("read stop columns of %s = %v", attempt, err)
37 }
38 return s
39}
40
41// wireProof decodes the stored proof of attempt, which must be there.
42func (e *launchEnv) wireProof(attempt string) hostedwire.StopProof {
43 e.t.Helper()
44 s := e.stopCols(attempt)
45 if !s.proof.Valid {
46 e.t.Fatalf("%s has no stored stop proof", attempt)
47 }
48 var p hostedwire.StopProof
49 if err := json.Unmarshal([]byte(s.proof.String), &p); err != nil {
50 e.t.Fatalf("stored proof %q is not the wire shape: %v", s.proof.String, err)
51 }
52 return p
53}
54
55// launchWith launches attempt for inst-1 with lifetime life and returns its
56// Ref.
57func (e *launchEnv) launchWith(attempt string, life time.Duration) isolatedjob.Ref {
58 e.t.Helper()
59 q := request(attempt)
60 q.MaxLifetime = life
61 v, err := e.c.Launch(e.ctx, "inst-1", instKey, q)
62 if err != nil || v.VMRef == "" {
63 e.t.Fatalf("Launch(%s) = (%+v, %v), want a started VM", attempt, v, err)
64 }
65 return v.VMRef
66}
67
68// replace launches attempt as the replacement of replaced, for inst-1.
69func (e *launchEnv) replace(attempt, replaced string) error {
70 e.t.Helper()
71 q := request(attempt)
72 q.Replaces = replaced
73 _, err := e.c.Launch(e.ctx, "inst-1", instKey, q)
74 return err
75}
76
77// down closes the store, as a controller that exits. up opens it again and
78// builds a new controller over the same fake provider. Time the test moves
79// between the two is downtime.
80func (e *launchEnv) down() {
81 e.t.Helper()
82 if err := e.store.Close(); err != nil {
83 e.t.Fatalf("Close = %v", err)
84 }
85}
86
87func (e *launchEnv) up() {
88 e.t.Helper()
89 e.store = openStore(e.t, e.path, e.clk)
90 e.newController()
91 if !e.store.Restarted() {
92 e.t.Fatal("Restarted() = false after a restart")
93 }
94}
95
96func (e *launchEnv) refresh() {
97 e.t.Helper()
98 if err := e.c.Refresh(e.ctx); err != nil {
99 e.t.Fatalf("Refresh = %v", err)
100 }
101}
102
103func (e *launchEnv) hasAudit(actor hostedwire.KeyID, attempt, action, reasonPart string) bool {
104 e.t.Helper()
105 for _, a := range auditRows(e.t, e.store) {
106 if a.Actor == actor && a.Attempt == attempt && a.Action == action && strings.Contains(a.Reason, reasonPart) {
107 return true
108 }
109 }
110 return false
111}
112
113// stopProbe wraps the fake provider. At each Stop, Get and List it reads
114// the store from another goroutine, as the provider is called, the way
115// intentProbe does: a read still blocked after 2 s means a transaction is
116// held across the provider call, and the call then fails with
117// errProbeBlocked instead of hanging. join waits for every read.
118type stopProbe struct {
119 *isolatedjob.Fake
120 store *Store
121 mu sync.Mutex
122 ops []isolatedjob.Op
123 reads []*probeRead
124}
125
126type probeRead struct {
127 op isolatedjob.Op
128 requested sql.NullInt64 // the job's stop_requested_t, at Stop and Get
129 reason sql.NullString // the job's stop_reason, at Stop and Get
130 err error
131 blocked bool
132 done chan struct{}
133}
134
135// read starts the store read for op on ref ("" for List) and reports
136// whether it finished within 2 s.
137func (p *stopProbe) read(op isolatedjob.Op, ref isolatedjob.Ref) bool {
138 r := &probeRead{op: op, done: make(chan struct{})}
139 p.mu.Lock()
140 p.ops = append(p.ops, op)
141 p.reads = append(p.reads, r)
142 p.mu.Unlock()
143 go func() {
144 defer close(r.done)
145 ctx := context.Background()
146 r.err = p.store.Tx(ctx, func(tx *sql.Tx) error {
147 if ref == "" {
148 var n int
149 return tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs`).Scan(&n)
150 }
151 return tx.QueryRowContext(ctx, `SELECT stop_requested_t, stop_reason FROM jobs WHERE vm_ref = ?`,
152 string(ref)).Scan(&r.requested, &r.reason)
153 })
154 }()
155 select {
156 case <-r.done:
157 return true
158 case <-time.After(2 * time.Second):
159 r.blocked = true
160 return false
161 }
162}
163
164func (p *stopProbe) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error {
165 if !p.read(isolatedjob.OpStop, ref) {
166 return errProbeBlocked
167 }
168 return p.Fake.Stop(ctx, ref, reason)
169}
170
171func (p *stopProbe) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) {
172 if !p.read(isolatedjob.OpGet, ref) {
173 return isolatedjob.Job{}, errProbeBlocked
174 }
175 return p.Fake.Get(ctx, ref)
176}
177
178func (p *stopProbe) List(ctx context.Context) ([]isolatedjob.Job, error) {
179 if !p.read(isolatedjob.OpList, "") {
180 return nil, errProbeBlocked
181 }
182 return p.Fake.List(ctx)
183}
184
185// join waits for every read the probe started and fails the test when one
186// was blocked or failed. Call it after the probed calls have returned.
187func (p *stopProbe) join(t *testing.T) []*probeRead {
188 t.Helper()
189 p.mu.Lock()
190 reads := append([]*probeRead(nil), p.reads...)
191 p.mu.Unlock()
192 for i, r := range reads {
193 select {
194 case <-r.done:
195 case <-time.After(5 * time.Second):
196 t.Fatalf("probe read %d (%s) is still blocked after the call returned", i, r.op)
197 }
198 if r.blocked {
199 t.Fatalf("provider %s (call %d): a store read waited 2 s; a transaction is held across the provider call", r.op, i)
200 }
201 if r.err != nil {
202 t.Fatalf("provider %s (call %d): reading the store = %v", r.op, i, r.err)
203 }
204 }
205 return reads
206}
207
208func TestStopRecordsRequestBeforeProvider(t *testing.T) {
209 t.Parallel()
210 e := newLaunchEnv(t)
211 probe := &stopProbe{Fake: e.fake, store: e.store}
212 e.run = probe
213 e.newController()
214 e.audit()
215 e.launchWith("att-1", 2*time.Hour)
216 e.fake.Tick()
217 e.clk.AdvanceMono(7 * time.Minute)
218 asked := e.store.Clock().Now()
219
220 _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done")
221 reads := probe.join(t)
222 if !errors.Is(err, ErrStopPending) {
223 t.Fatalf("Stop of a running VM = %v, want ErrStopPending (it is only stopping)", err)
224 }
225 if len(reads) != 2 || reads[0].op != isolatedjob.OpStop || reads[1].op != isolatedjob.OpGet {
226 t.Fatalf("provider calls = %v, want stop then get", probe.ops)
227 }
228 for _, r := range reads {
229 if !r.requested.Valid || T(r.requested.Int64) != asked || r.reason.String != "task done" {
230 t.Fatalf("at the provider %s: stop_requested_t %v, reason %v; want %d and \"task done\" already saved",
231 r.op, r.requested, r.reason, asked)
232 }
233 }
234 if s := e.stopCols("att-1"); s.proof.Valid || s.state != JobStopping {
235 t.Fatalf("after Stop: state %q, proof %v; want stopping and no proof", s.state, s.proof)
236 }
237 if !e.hasAudit("inst-1", "att-1", actionStopRequested, "task done") {
238 t.Fatal("no stop_requested audit row by inst-1")
239 }
240
241 // Refresh's Get and its List for a job with no Ref run outside any
242 // transaction too.
243 e.audit()
244 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
245 if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-2")); err != nil {
246 t.Fatalf("throttled Launch = %v", err)
247 }
248 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-2", "task done"); !errors.Is(err, ErrStopPending) {
249 t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err)
250 }
251 e.clk.AdvanceMono(3 * time.Minute)
252 err = e.c.Refresh(e.ctx)
253 reads = probe.join(t)
254 if err != nil {
255 t.Fatalf("Refresh = %v", err)
256 }
257 var ops []isolatedjob.Op
258 for _, r := range reads[2:] {
259 ops = append(ops, r.op)
260 }
261 if !slices.Contains(ops, isolatedjob.OpGet) || !slices.Contains(ops, isolatedjob.OpList) {
262 t.Fatalf("Refresh provider calls = %v, want a get and a list", ops)
263 }
264}
265
266func TestStopProofNeedsTerminalState(t *testing.T) {
267 t.Parallel()
268 e := newLaunchEnv(t)
269 ref := e.launchWith("att-1", 2*time.Hour)
270 e.fake.Tick()
271 before := e.stopCols("att-1")
272
273 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
274 t.Fatalf("Stop while the VM is stopping = %v, want ErrStopPending", err)
275 }
276 if s := e.stopCols("att-1"); s.proof.Valid {
277 t.Fatalf("a stopping VM gave proof %s", s.proof.String)
278 }
279 if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
280 t.Fatalf("replacement while the VM is stopping = %v, want ErrReplacementLive", err)
281 }
282
283 e.fake.Tick() // stopping to stopped
284 e.clk.AdvanceMono(time.Minute)
285 at := e.store.Clock().Now()
286 p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "again")
287 if err != nil {
288 t.Fatalf("Stop of a stopped VM = %v, want proof", err)
289 }
290 want := StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: at}
291 if p != want {
292 t.Fatalf("proof = %+v, want %+v", p, want)
293 }
294 if w := e.wireProof("att-1"); w != (hostedwire.StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: time.Duration(at)}) {
295 t.Fatalf("stored proof = %+v, want the wire shape of %+v", w, want)
296 }
297 s := e.stopCols("att-1")
298 if s.state != JobStopped || s.reason.String != "task done" || s.stop != before.stop || s.deadline != before.deadline {
299 t.Fatalf("after proof: state %q reason %v stop_t %d deadline_t %d; want stopped, the first reason, times %d %d unchanged",
300 s.state, s.reason, s.stop, s.deadline, before.stop, before.deadline)
301 }
302
303 stops, gets := e.fake.Calls(isolatedjob.OpStop), e.fake.Calls(isolatedjob.OpGet)
304 again, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "once more")
305 if err != nil || again != p {
306 t.Fatalf("Stop of a proven job = (%+v, %v), want the stored proof %+v", again, err, p)
307 }
308 if e.fake.Calls(isolatedjob.OpStop) != stops || e.fake.Calls(isolatedjob.OpGet) != gets {
309 t.Fatal("Stop of a proven job called the provider")
310 }
311 if err := e.replace("att-2", "att-1"); err != nil {
312 t.Fatalf("replacement after proof = %v", err)
313 }
314 if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.State != JobStopped || v.VMRef != ref {
315 t.Fatalf("Get after proof = (%+v, %v), want stopped with ref %s", v, err, ref)
316 }
317}
318
319func TestUnknownStateIsNeverProof(t *testing.T) {
320 t.Parallel()
321 e := newLaunchEnv(t)
322 e.launchWith("att-1", 2*time.Hour)
323 e.fake.Tick()
324
325 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState)
326 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStateUnknown) {
327 t.Fatalf("Stop with the provider state unknown = %v, want ErrStateUnknown", err)
328 }
329 if s := e.stopCols("att-1"); s.proof.Valid || s.state == JobStopped {
330 t.Fatalf("unknown state gave state %q, proof %v", s.state, s.proof)
331 }
332 if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
333 t.Fatalf("replacement after an unknown state = %v, want ErrReplacementLive", err)
334 }
335
336 // The VM has really stopped, but the provider still reports unknown.
337 e.fake.Tick()
338 stateBefore := e.stopCols("att-1").state
339 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState)
340 e.refresh()
341 if s := e.stopCols("att-1"); s.proof.Valid || s.state != stateBefore {
342 t.Fatalf("Refresh with an unknown state: state %q (was %q), proof %v; want it left alone", s.state, stateBefore, s.proof)
343 }
344 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultUnknownState)
345 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStateUnknown) {
346 t.Fatalf("second Stop with the state unknown = %v, want ErrStateUnknown", err)
347 }
348 if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
349 t.Fatalf("replacement after a second unknown state = %v, want ErrReplacementLive", err)
350 }
351
352 // Once the provider answers, the proof comes.
353 if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.State != isolatedjob.StateStopped {
354 t.Fatalf("Stop once the state is known = (%+v, %v), want stopped proof", p, err)
355 }
356}
357
358func TestLostStopReplyRetries(t *testing.T) {
359 t.Parallel()
360 t.Run("reply lost after the stop took effect", func(t *testing.T) {
361 e := newLaunchEnv(t)
362 ref := e.launchWith("att-1", 2*time.Hour)
363 e.fake.Tick()
364 e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultLostReply)
365 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, isolatedjob.ErrLostReply) {
366 t.Fatalf("Stop with a lost reply = %v, want the provider error", err)
367 }
368 if s := e.stopCols("att-1"); !s.requested.Valid || s.proof.Valid {
369 t.Fatalf("after a lost reply: requested %v proof %v; want the request kept and no proof", s.requested, s.proof)
370 }
371 if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
372 t.Fatalf("replacement after a lost stop reply = %v, want ErrReplacementLive", err)
373 }
374 e.fake.Tick()
375 p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done")
376 if err != nil || p.VMRef != ref || p.State != isolatedjob.StateStopped {
377 t.Fatalf("retried Stop = (%+v, %v), want proof for %s", p, err, ref)
378 }
379 if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref, ref}) {
380 t.Fatalf("provider stops = %v, want the stop sent again", got)
381 }
382 })
383 t.Run("stop throttled, sent again by Refresh", func(t *testing.T) {
384 e := newLaunchEnv(t)
385 ref := e.launchWith("att-1", 2*time.Hour)
386 e.fake.Tick()
387 e.fake.Inject(isolatedjob.OpStop, isolatedjob.FaultThrottle)
388 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, isolatedjob.ErrThrottled) {
389 t.Fatalf("throttled Stop = %v, want the provider error", err)
390 }
391 if live := e.fake.LiveByAttempt()["att-1"]; live != 1 {
392 t.Fatalf("live VMs after a throttled stop = %d, want 1", live)
393 }
394 e.refresh() // the VM is still running: Refresh sends the stop again
395 if got := e.fake.StopsIssued(); len(got) != 2 {
396 t.Fatalf("provider stops after Refresh = %v, want a second one", got)
397 }
398 e.fake.Tick()
399 e.fake.Tick()
400 e.refresh()
401 w := e.wireProof("att-1")
402 if w.VMRef != ref || w.State != isolatedjob.StateStopped {
403 t.Fatalf("proof after Refresh = %+v, want stopped %s", w, ref)
404 }
405 if s := e.stopCols("att-1"); s.reason.String != "task done" {
406 t.Fatalf("stop reason = %v, want the requested one, not ended", s.reason)
407 }
408 })
409}
410
411func TestStopOfGoneVMSucceeds(t *testing.T) {
412 t.Parallel()
413 e := newLaunchEnv(t)
414 ref := e.launchWith("att-1", 2*time.Hour)
415 e.fake.Tick()
416 e.fake.Vanish(ref)
417
418 // The provider's Get is eventually consistent: one not-found is no proof.
419 e.clk.AdvanceMono(time.Minute)
420 first := e.store.Clock().Now()
421 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
422 t.Fatalf("Stop on the first not-found = %v, want ErrStopPending", err)
423 }
424 if s := e.stopCols("att-1"); s.proof.Valid || !s.notFoundSince.Valid || T(s.notFoundSince.Int64) != first {
425 t.Fatalf("after one not-found: proof %v notfound_since_t %v; want no proof, since %d", s.proof, s.notFoundSince, first)
426 }
427 if err := e.replace("att-2", "att-1"); !errors.Is(err, ErrReplacementLive) {
428 t.Fatalf("replacement after one not-found = %v, want ErrReplacementLive", err)
429 }
430 e.clk.AdvanceMono(NotFoundConfirm - time.Nanosecond)
431 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
432 t.Fatalf("Stop on a second not-found under %v later = %v, want ErrStopPending", NotFoundConfirm, err)
433 }
434 if s := e.stopCols("att-1"); T(s.notFoundSince.Int64) != first {
435 t.Fatalf("notfound_since_t moved to %d on a second not-found, want %d kept", s.notFoundSince.Int64, first)
436 }
437
438 e.clk.AdvanceMono(time.Nanosecond)
439 at := e.store.Clock().Now()
440 p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done")
441 want := StopProof{AttemptID: "att-1", VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: at}
442 if err != nil || p != want {
443 t.Fatalf("Stop on a not-found %v after the first = (%+v, %v), want %+v", NotFoundConfirm, p, err, want)
444 }
445 e.audit()
446 if err := e.replace("att-2", "att-1"); err != nil {
447 t.Fatalf("replacement after proof = %v", err)
448 }
449}
450
451// notFoundOnce wraps the fake provider; its next n Gets answer not-found
452// whatever the VM's state, as an eventually consistent provider can.
453type notFoundOnce struct {
454 *isolatedjob.Fake
455 n int
456}
457
458func (p *notFoundOnce) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) {
459 if p.n > 0 {
460 p.n--
461 return isolatedjob.Job{}, fmt.Errorf("%w: %s (stale read)", isolatedjob.ErrNotFound, ref)
462 }
463 return p.Fake.Get(ctx, ref)
464}
465
466func TestStopNotFoundThenRunning(t *testing.T) {
467 t.Parallel()
468 e := newLaunchEnv(t)
469 flaky := &notFoundOnce{Fake: e.fake}
470 e.run = flaky
471 e.newController()
472 e.audit()
473 e.launchWith("att-1", 2*time.Hour)
474 e.fake.Tick()
475
476 flaky.n = 1
477 e.refresh()
478 if s := e.stopCols("att-1"); s.proof.Valid || !s.notFoundSince.Valid {
479 t.Fatalf("after one not-found: proof %v notfound_since_t %v; want no proof and a since time", s.proof, s.notFoundSince)
480 }
481 e.clk.AdvanceMono(NotFoundConfirm)
482 e.refresh() // the VM shows running
483 if s := e.stopCols("att-1"); s.proof.Valid || s.notFoundSince.Valid || s.state != JobRunning {
484 t.Fatalf("after a running Get: state %q proof %v notfound_since_t %v; want running, no proof, since cleared",
485 s.state, s.proof, s.notFoundSince)
486 }
487
488 // A new not-found starts a new wait; the one before the running Get no
489 // longer counts.
490 e.clk.AdvanceMono(time.Minute)
491 flaky.n = 1
492 e.refresh()
493 e.clk.AdvanceMono(NotFoundConfirm / 2)
494 flaky.n = 1
495 e.refresh()
496 if s := e.stopCols("att-1"); s.proof.Valid {
497 t.Fatalf("proof %s from not-founds %v apart", s.proof.String, NotFoundConfirm/2)
498 }
499
500 // After a stop request, a not-found from before it does not count.
501 e.clk.AdvanceMono(NotFoundConfirm)
502 asked := e.store.Clock().Now()
503 flaky.n = 1
504 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
505 t.Fatalf("Stop on a not-found with the earlier one before the request = %v, want ErrStopPending", err)
506 }
507 if s := e.stopCols("att-1"); s.proof.Valid || T(s.notFoundSince.Int64) != asked {
508 t.Fatalf("after Stop: proof %v notfound_since_t %v; want no proof, since %d", s.proof, s.notFoundSince, asked)
509 }
510 e.clk.AdvanceMono(NotFoundConfirm)
511 flaky.n = 1
512 if p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); err != nil || p.State != isolatedjob.StateStopped {
513 t.Fatalf("Stop on a second not-found after the request = (%+v, %v), want proof", p, err)
514 }
515}
516
517func TestStopIntentWithoutRef(t *testing.T) {
518 t.Parallel()
519 t.Run("lost launch reply left a VM", func(t *testing.T) {
520 e := newLaunchEnv(t)
521 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply)
522 if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err == nil {
523 t.Fatal("Launch with a lost reply = nil error")
524 }
525 if e.fake.LiveByAttempt()["att-1"] != 1 {
526 t.Fatal("the lost launch made no VM")
527 }
528 e.clk.AdvanceMono(time.Minute)
529 asked := e.store.Clock().Now()
530 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
531 t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err)
532 }
533 if s := e.stopCols("att-1"); s.state != JobAbandoned || T(s.requested.Int64) != asked || s.proof.Valid {
534 t.Fatalf("after Stop: state %q requested %v proof %v; want abandoned at %d, no proof", s.state, s.requested, s.proof, asked)
535 }
536 launches := e.fake.Calls(isolatedjob.OpLaunch)
537 if err := e.c.Replay(e.ctx); err != nil || e.fake.Calls(isolatedjob.OpLaunch) != launches {
538 t.Fatalf("Replay after Stop = %v with %d launches, want none", err, e.fake.Calls(isolatedjob.OpLaunch)-launches)
539 }
540
541 // The lost reply's VM is live and no job holds its Ref: no proof.
542 e.clk.AdvanceMono(5 * time.Minute)
543 e.refresh()
544 if s := e.stopCols("att-1"); s.proof.Valid {
545 t.Fatalf("proof %s while an unlinked VM is live", s.proof.String)
546 }
547
548 // The orphan reaper (Task 13) stops it; stand in for it.
549 vms, err := e.fake.List(e.ctx)
550 if err != nil || len(vms) != 1 {
551 t.Fatalf("List = (%v, %v), want the one orphan", vms, err)
552 }
553 if err := e.fake.Stop(e.ctx, vms[0].Ref, "orphan"); err != nil {
554 t.Fatal(err)
555 }
556 e.fake.Tick()
557
558 e.fake.Inject(isolatedjob.OpList, isolatedjob.FaultIncompleteList)
559 _ = e.c.Refresh(e.ctx)
560 if s := e.stopCols("att-1"); s.proof.Valid {
561 t.Fatalf("proof %s from an incomplete list", s.proof.String)
562 }
563
564 at := e.store.Clock().Now()
565 e.refresh()
566 w := e.wireProof("att-1")
567 if w != (hostedwire.StopProof{AttemptID: "att-1", State: isolatedjob.StateStopped, ObservedAt: time.Duration(at)}) {
568 t.Fatalf("proof = %+v, want att-1, no ref, stopped, at %d", w, at)
569 }
570 p, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "again")
571 if err != nil || p.VMRef != "" || p.State != isolatedjob.StateStopped {
572 t.Fatalf("Stop after proof = (%+v, %v), want the stored proof", p, err)
573 }
574 e.audit()
575 if err := e.replace("att-2", "att-1"); err != nil {
576 t.Fatalf("replacement after proof = %v", err)
577 }
578 })
579 t.Run("list must start 2 minutes after the request", func(t *testing.T) {
580 e := newLaunchEnv(t)
581 e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
582 if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil {
583 t.Fatalf("throttled Launch = %v", err)
584 }
585 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
586 t.Fatalf("Stop of an intent with no Ref = %v, want ErrStopPending", err)
587 }
588 e.clk.AdvanceMono(2*time.Minute - time.Nanosecond)
589 e.refresh()
590 if s := e.stopCols("att-1"); s.proof.Valid {
591 t.Fatalf("proof %s from a list started under 2 minutes after the request", s.proof.String)
592 }
593 e.clk.AdvanceMono(time.Nanosecond)
594 e.refresh()
595 if w := e.wireProof("att-1"); w.VMRef != "" || w.State != isolatedjob.StateStopped {
596 t.Fatalf("proof = %+v, want no ref and stopped", w)
597 }
598 })
599}
600
601func TestStopRoles(t *testing.T) {
602 t.Parallel()
603 e := newLaunchEnv(t)
604 ref := e.launchWith("att-1", 2*time.Hour)
605 e.fake.Tick()
606
607 for _, tc := range []struct {
608 name string
609 by hostedwire.KeyID
610 key hostedwire.VerifyKey
611 }{
612 {"another instance", "inst-2", instKey},
613 {"an operator", "op-1", opKey},
614 {"an operator key with the creator's id", "inst-1", opKey},
615 {"no key id", "", instKey},
616 } {
617 if _, err := e.c.Stop(e.ctx, tc.by, tc.key, "att-1", "mine now"); !errors.Is(err, ErrForbidden) {
618 t.Fatalf("Stop by %s = %v, want ErrForbidden", tc.name, err)
619 }
620 if a := e.lastAudit(); a.Actor != tc.by || a.Action != actionStopRefused {
621 t.Fatalf("audit after Stop by %s = %+v, want stop_refused by %q", tc.name, a, tc.by)
622 }
623 }
624 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-9", "no such"); !errors.Is(err, ErrForbidden) {
625 t.Fatalf("Stop of an unknown attempt = %v, want ErrForbidden", err)
626 }
627 if got := e.fake.StopsIssued(); len(got) != 0 {
628 t.Fatalf("refused stops reached the provider: %v", got)
629 }
630 if s := e.stopCols("att-1"); s.requested.Valid {
631 t.Fatalf("a refused stop recorded a request at %d", s.requested.Int64)
632 }
633
634 if _, err := e.c.Get(e.ctx, "inst-2", "att-1"); !errors.Is(err, ErrForbidden) {
635 t.Fatalf("Get by another instance = %v, want ErrForbidden", err)
636 }
637 if a := e.lastAudit(); a.Actor != "inst-2" || a.Action != actionGetRefused {
638 t.Fatalf("audit after Get by another instance = %+v, want get_refused", a)
639 }
640 if _, err := e.c.Get(e.ctx, "inst-1", "att-9"); !errors.Is(err, ErrForbidden) {
641 t.Fatalf("Get of an unknown attempt = %v, want ErrForbidden", err)
642 }
643 if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.VMRef != ref || v.AttemptID != "att-1" {
644 t.Fatalf("Get by the creator = (%+v, %v), want the job", v, err)
645 }
646 if _, err := e.c.Stop(e.ctx, "inst-1", instKey, "att-1", "task done"); !errors.Is(err, ErrStopPending) {
647 t.Fatalf("Stop by the creator = %v, want ErrStopPending", err)
648 }
649}
650
651func TestRestartFindsVMGone(t *testing.T) {
652 t.Parallel()
653 e := newLaunchEnv(t)
654 refA := e.launchWith("att-a", 2*time.Hour)
655 refB := e.launchWith("att-b", 2*time.Hour)
656 e.fake.Tick()
657
658 // While the controller is down, A's VM disappears and B's reaches its
659 // lifetime and stops.
660 e.down()
661 e.fake.Vanish(refA)
662 e.clk.AdvanceMono(2 * time.Hour)
663 e.fake.Tick()
664 e.fake.Tick()
665 e.clk.SetWall(testWall.Add(2 * time.Hour))
666 e.up()
667 // A not-found at exactly OpenedAt cannot be told from one saved before
668 // the restart, so it never counts; real time always moves after Open.
669 e.clk.AdvanceMono(time.Second)
670
671 e.refresh()
672 // B is terminal: proof at once. A is only not found: it waits for a
673 // second not-found NotFoundConfirm later.
674 if s := e.stopCols("att-a"); s.proof.Valid || !s.notFoundSince.Valid {
675 t.Fatalf("att-a after one not-found: proof %v notfound_since_t %v; want no proof yet", s.proof, s.notFoundSince)
676 }
677 e.audit()
678 if err := e.replace("att-a2", "att-a"); !errors.Is(err, ErrReplacementLive) {
679 t.Fatalf("replacement after one not-found = %v, want ErrReplacementLive", err)
680 }
681 e.clk.AdvanceMono(NotFoundConfirm)
682 e.refresh()
683 for _, c := range []struct {
684 attempt string
685 ref isolatedjob.Ref
686 }{{"att-a", refA}, {"att-b", refB}} {
687 w := e.wireProof(c.attempt)
688 if w.VMRef != c.ref || w.State != isolatedjob.StateStopped {
689 t.Fatalf("proof for %s = %+v, want stopped %s", c.attempt, w, c.ref)
690 }
691 if s := e.stopCols(c.attempt); s.state != JobStopped || s.reason.String != reasonEnded || s.requested.Valid {
692 t.Fatalf("%s after Refresh: state %q reason %v requested %v; want stopped, ended, no request",
693 c.attempt, s.state, s.reason, s.requested)
694 }
695 }
696 if got := e.fake.StopsIssued(); len(got) != 0 {
697 t.Fatalf("Refresh stopped %v; both VMs had already ended", got)
698 }
699 if err := e.replace("att-a2", "att-a"); err != nil {
700 t.Fatalf("replacement of a VM that ended while the controller was down = %v", err)
701 }
702}
703
704func TestRestartUsesProviderAge(t *testing.T) {
705 t.Parallel()
706 const life = 2 * time.Hour
707 run := func(t *testing.T, downtime, wallMove time.Duration) (old, got stopCols, want T) {
708 e := newLaunchEnv(t)
709 e.clk.AdvanceMono(time.Minute)
710 monoAtLaunch := e.clk.Mono()
711 e.launchWith("att-1", life)
712 e.fake.Tick()
713 e.clk.AdvanceMono(20 * time.Minute)
714 old = e.stopCols("att-1")
715
716 e.down()
717 e.clk.AdvanceMono(downtime)
718 e.clk.SetWall(testWall.Add(wallMove))
719 e.up()
720
721 age := e.clk.Mono() - monoAtLaunch // what the provider reports
722 want = min(T(old.launched), e.store.Clock().Now()-T(age))
723 e.refresh()
724 got = e.stopCols("att-1")
725 wd, wdr, ws := Deadlines(want, life)
726 if T(got.launched) != want || T(got.deadline) != wd || T(got.drain) != wdr || T(got.stop) != ws {
727 t.Fatalf("after Refresh: launched %d deadline %d drain %d stop %d; want %d %d %d %d",
728 got.launched, got.deadline, got.drain, got.stop, want, wd, wdr, ws)
729 }
730 if got.deadline > old.deadline || got.drain > old.drain || got.stop > old.stop || got.launched > old.launched {
731 t.Fatalf("Refresh moved a time later: %+v from %+v", got, old)
732 }
733 if !e.hasAudit("", "att-1", actionRestartRebased, "") {
734 t.Fatal("no restart_rebased audit row")
735 }
736 return old, got, want
737 }
738 t.Run("wall clock went back", func(t *testing.T) {
739 old, got, _ := run(t, 40*time.Minute, -3*time.Hour)
740 if got.launched >= old.launched || got.stop >= old.stop {
741 t.Fatalf("40 min of downtime with the wall clock back: launched %d stop %d, want both earlier than %d %d",
742 got.launched, got.stop, old.launched, old.stop)
743 }
744 })
745 t.Run("wall clock far ahead", func(t *testing.T) {
746 old, got, _ := run(t, 30*time.Minute, 5*time.Hour)
747 if got.launched != old.launched || got.stop != old.stop {
748 t.Fatalf("wall delta beyond the provider age moved times: %+v from %+v", got, old)
749 }
750 })
751}
752
753func TestRestartDowntimeExceedsWallDelta(t *testing.T) {
754 t.Parallel()
755 const life = 4 * time.Hour
756 e := newLaunchEnv(t)
757 ref1 := e.launchWith("att-1", life) // its age will be unknown
758 e.clk.AdvanceMono(time.Minute)
759 monoAt2 := e.clk.Mono()
760 e.launchWith("att-2", life)
761 e.fake.Tick()
762 old2 := e.stopCols("att-2")
763 // An orphan the reaper first sees just before the exit (ruling R1).
764 stray := e.plant("stray-1")
765 e.reap()
766 strayAt := e.unmatched()[stray]
767
768 // Two hours of real downtime; the wall clock reads only 5 min on.
769 e.down()
770 e.clk.AdvanceMono(2 * time.Hour)
771 e.clk.SetWall(testWall.Add(5 * time.Minute))
772 e.up()
773
774 now := e.store.Clock().Now()
775 if got := time.Duration(now - T(old2.launched)); got > 15*time.Minute {
776 t.Fatalf("controller time moved %v across the restart; the test needs the wall delta to understate it", got)
777 }
778 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown) // att-1 is read first
779 e.refresh()
780
781 want := now - T(e.clk.Mono()-monoAt2)
782 wd, wdr, ws := Deadlines(want, life)
783 got := e.stopCols("att-2")
784 if T(got.launched) != want || T(got.deadline) != wd || T(got.drain) != wdr || T(got.stop) != ws {
785 t.Fatalf("att-2 with a trusted age: launched %d deadline %d drain %d stop %d; want %d %d %d %d",
786 got.launched, got.deadline, got.drain, got.stop, want, wd, wdr, ws)
787 }
788 if got.requested.Valid {
789 t.Fatal("att-2 has a trusted age but was stopped")
790 }
791 s1 := e.stopCols("att-1")
792 if !s1.requested.Valid || s1.reason.String != reasonElapsedUnknown {
793 t.Fatalf("att-1 with no age: requested %v reason %v; want stopped with %s", s1.requested, s1.reason, reasonElapsedUnknown)
794 }
795 if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref1}) {
796 t.Fatalf("provider stops = %v, want only %s", got, ref1)
797 }
798
799 // The orphan's grace is expired too: the controller time since its
800 // sighting understates the downtime, so the first pass stops it.
801 if got := e.store.Clock().Now() - strayAt; got >= T(OrphanGrace) {
802 t.Fatalf("controller time since the orphan's sighting = %v; the test needs it under the grace", time.Duration(got))
803 }
804 if r := e.reap(); r.OrphansStopped != 1 {
805 t.Fatalf("first reaper pass after the restart: report %+v, want the orphan stopped", r)
806 }
807 if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref1, stray}) {
808 t.Fatalf("provider stops = %v, want %s then the orphan %s", got, ref1, stray)
809 }
810}
811
812func TestRestartStopsWhenElapsedUnknown(t *testing.T) {
813 t.Parallel()
814 e := newLaunchEnv(t)
815 ref1 := e.launchWith("att-1", 2*time.Hour) // age unknown after the restart
816 e.clk.AdvanceMono(time.Minute)
817 e.launchWith("att-3", 2*time.Hour) // age known after the restart
818 e.fake.Tick()
819
820 e.down()
821 e.clk.AdvanceMono(10 * time.Minute)
822 e.clk.SetWall(testWall.Add(10 * time.Minute))
823 e.up()
824 e.audit()
825 e.clk.AdvanceMono(time.Minute)
826 e.launchWith("att-2", 2*time.Hour) // launched after the restart
827 e.fake.Tick()
828
829 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
830 e.refresh()
831 s1 := e.stopCols("att-1")
832 if !s1.requested.Valid || s1.reason.String != reasonElapsedUnknown || s1.state != JobStopping {
833 t.Fatalf("att-1 after Refresh: requested %v reason %v state %q; want a stop for %s, stopping",
834 s1.requested, s1.reason, s1.state, reasonElapsedUnknown)
835 }
836 if !e.hasAudit("", "att-1", actionStopRequested, reasonElapsedUnknown) {
837 t.Fatal("no stop_requested audit row by the controller for att-1")
838 }
839
840 // Each job is re-based once per process: a later unknown age stops
841 // neither the job already re-based nor one launched after the restart.
842 for range 3 {
843 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
844 }
845 e.refresh()
846 if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref1}) {
847 t.Fatalf("provider stops = %v, want only %s", got, ref1)
848 }
849 for _, a := range []string{"att-2", "att-3"} {
850 if s := e.stopCols(a); s.requested.Valid {
851 t.Fatalf("%s was stopped (%v); its elapsed time is known", a, s.reason)
852 }
853 }
854
855 e.fake.Tick()
856 e.refresh()
857 if w := e.wireProof("att-1"); w.VMRef != ref1 || w.State != isolatedjob.StateStopped {
858 t.Fatalf("proof for att-1 = %+v, want stopped %s", w, ref1)
859 }
860 if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown {
861 t.Fatalf("att-1 reason after proof = %v, want %s kept", s.reason, reasonElapsedUnknown)
862 }
863}
864
865// A wall clock behind the checkpoint restores T to the checkpoint itself, so
866// a job saved just before the exit can have launched_t equal to OpenedAt. It
867// still existed before the restart.
868func TestRestartJobAtOpenTime(t *testing.T) {
869 t.Parallel()
870 e := newLaunchEnv(t)
871 ref := e.launchWith("att-1", 2*time.Hour)
872 e.fake.Tick()
873 e.down()
874 e.clk.AdvanceMono(3 * time.Hour)
875 e.clk.SetWall(testWall.Add(-time.Hour))
876 e.up()
877 if s := e.stopCols("att-1"); T(s.launched) != e.store.OpenedAt() {
878 t.Fatalf("launched_t %d, OpenedAt %d; the test needs them equal", s.launched, e.store.OpenedAt())
879 }
880 e.fake.Inject(isolatedjob.OpGet, isolatedjob.FaultAgeUnknown)
881 e.refresh()
882 if s := e.stopCols("att-1"); s.reason.String != reasonElapsedUnknown {
883 t.Fatalf("job launched at OpenedAt with no age: reason %v, want %s", s.reason, reasonElapsedUnknown)
884 }
885 if got := e.fake.StopsIssued(); !slices.Equal(got, []isolatedjob.Ref{ref}) {
886 t.Fatalf("provider stops = %v, want %s", got, ref)
887 }
888}
889