package hostedclient // The Task 17 driver logic. live_test.go (hostedlive) wires it to a real // controller from the environment; the offline tests below run it against // the test controller and the fake provider, so CI checks every path the // live run takes, failure cleanups included. import ( "bytes" "context" "crypto/ed25519" "errors" "fmt" "io" "net/http" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) // liveDriver drives one controller through cl. Steps return errors; the // cleanups they register go through deferFn (t.Cleanup in a live run) and // report through errorf. type liveDriver struct { cl *Client origin string // for the operator's GET /v1/vms rt http.RoundTripper // likewise ctl ed25519.PublicKey // likewise image isolatedjob.ImageDigest lifetime time.Duration // of each launched VM poll time.Duration // between reads while waiting stateBound time.Duration // for each wait for a state, a resume or a stop cleanupBound time.Duration // for the stop a failure cleanup sends callTimeout time.Duration // for the operator's list call logf func(format string, args ...any) errorf func(format string, args ...any) deferFn func(func()) } func (d *liveDriver) launchRequest(attempt string) hostedwire.LaunchRequest { return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task17-live", Account: "task17-live", Image: d.image, Size: isolatedjob.SizeSmall, MaxLifetimeMS: d.lifetime.Milliseconds(), InstanceCode: "task17-code-" + attempt} } // vmGuard stops an attempt's VM when the step that registered it ends // without releasing it. type vmGuard struct{ released bool } // release ends the guard: the VM has stop proof, or is handed over on // purpose (the crash step leaves it for the recover step). func (g *vmGuard) release() { g.released = true } // guard registers, before anything can create a VM, the cleanup that stops // attempt's VM unless the guard is released. An attempt the controller does // not know for this key (forbidden) has nothing to stop. func (d *liveDriver) guard(attempt string) *vmGuard { g := &vmGuard{} d.deferFn(func() { if g.released { return } proof, calls, took, err := d.stopUntilProof(context.Background(), attempt, "task17 cleanup", d.cleanupBound) switch { case errors.Is(err, ErrForbidden): d.logf("cleanup: the controller holds no job %s for this key; nothing to stop", attempt) case err != nil: d.errorf("cleanup stop of %s after %d calls and %v: %v; check the provider for a VM left running", attempt, calls, took, err) default: d.logf("cleanup stop of %s: proof %s %s after %d calls", attempt, proof.VMRef, proof.State, calls) } }) return g } // retryableStop reports whether a Stop may simply be sent again: the stop // is pending, the provider is busy, the controller is unavailable (503) or // the exchange failed before a verified answer came back. Stop is // idempotent, so resending is safe whatever the first call did. func retryableStop(err error) bool { var api *APIError return errors.Is(err, ErrStopPending) || errors.Is(err, ErrThrottled) || errors.Is(err, ErrTransport) || errors.Is(err, ErrUnverified) || errors.As(err, &api) && api.Status == http.StatusServiceUnavailable } // stopUntilProof asks for a stop until the controller has proof, for at // most bound, and returns the proof, the calls made and the time taken. The // last error is returned when bound passes without proof. func (d *liveDriver) stopUntilProof(ctx context.Context, attempt, reason string, bound time.Duration) (hostedwire.StopProof, int, time.Duration, error) { start := time.Now() for calls := 1; ; calls++ { proof, err := d.cl.Stop(ctx, attempt, reason) if err == nil { return proof, calls, time.Since(start), nil } if !retryableStop(err) || time.Since(start) > bound { return proof, calls, time.Since(start), err } time.Sleep(d.poll) } } // waitFor reads the job until done accepts its view, for at most // stateBound. A job that reaches stopped or abandoned first is an error. func (d *liveDriver) waitFor(ctx context.Context, attempt, what string, done func(hostedwire.JobView) bool) (hostedwire.JobView, time.Duration, error) { start := time.Now() for { v, err := d.cl.Get(ctx, attempt) if err != nil { return v, time.Since(start), fmt.Errorf("Get(%s) while waiting for %s: %w", attempt, what, err) } if done(v) { return v, time.Since(start), nil } if v.State == "stopped" || v.State == "abandoned" { return v, time.Since(start), fmt.Errorf("job %s is %s while waiting for %s", attempt, v.State, what) } if time.Since(start) > d.stateBound { return v, time.Since(start), fmt.Errorf("job %s still %s after %v, want %s", attempt, v.State, d.stateBound, what) } time.Sleep(d.poll) } } func stateIs(s string) func(hostedwire.JobView) bool { return func(v hostedwire.JobView) bool { return v.State == s } } // sequence drives one Small VM: launch, running, drain, quiescent, suspend, // suspended, resume (the epoch must rise by one), running, stop with proof. // It logs each timing and the epoch. func (d *liveDriver) sequence(ctx context.Context, attempt string) error { d.logf("attempt %s, image %s, size small", attempt, d.image) g := d.guard(attempt) start := time.Now() view, err := d.cl.Launch(ctx, d.launchRequest(attempt)) launchCall := time.Since(start) if err != nil { return fmt.Errorf("Launch(%s) after %v: %w", attempt, launchCall, err) } d.logf("launch: call %v, state %s, vm %s, epoch %d", launchCall, view.State, view.VMRef, view.Epoch) running, toRunning, err := d.waitFor(ctx, attempt, "running", stateIs("running")) if err != nil { return err } d.logf("running: %v after the launch call returned; vm %s, epoch %d", toRunning, running.VMRef, running.Epoch) start = time.Now() gen, err := d.cl.Drain(ctx, attempt) drainCall := time.Since(start) if err != nil { return fmt.Errorf("Drain: %w", err) } start = time.Now() if err := d.cl.Quiescent(ctx, attempt, gen); err != nil { return fmt.Errorf("Quiescent(%d): %w", gen, err) } quiescentCall := time.Since(start) start = time.Now() if err := d.cl.Suspend(ctx, attempt, gen); err != nil { return fmt.Errorf("Suspend(%d): %w", gen, err) } suspendCall := time.Since(start) d.logf("pause: generation %d, drain call %v, quiescent call %v, suspend call %v", gen, drainCall, quiescentCall, suspendCall) _, toSuspended, err := d.waitFor(ctx, attempt, "suspended", stateIs("suspended")) if err != nil { return err } d.logf("suspended: %v after the suspend call returned", toSuspended) opID := "resume-" + attempt start = time.Now() var epoch int64 resumeCalls := 0 for { resumeCalls++ epoch, err = d.cl.Resume(ctx, attempt, opID) if err == nil { break } if !errors.Is(err, ErrResumePending) || time.Since(start) > d.stateBound { return fmt.Errorf("Resume(%s) call %d after %v: %w", opID, resumeCalls, time.Since(start), err) } time.Sleep(d.poll) } resumeTook := time.Since(start) d.logf("resume: epoch %d (was %d), %d calls, %v from the first call to the epoch", epoch, running.Epoch, resumeCalls, resumeTook) if epoch != running.Epoch+1 { return fmt.Errorf("Resume gave epoch %d, want %d: one resume raises the epoch by one", epoch, running.Epoch+1) } after, toRunningAgain, err := d.waitFor(ctx, attempt, "running after resume", stateIs("running")) if err != nil { return err } if after.Epoch != epoch { return fmt.Errorf("job epoch after resume = %d, want %d", after.Epoch, epoch) } d.logf("running after resume: %v after the epoch came back", toRunningAgain) proof, stopCalls, stopTook, err := d.stopUntilProof(ctx, attempt, "task17 done", d.stateBound) if err != nil { return fmt.Errorf("Stop(%s) after %d calls and %v: %w", attempt, stopCalls, stopTook, err) } g.release() d.logf("stop: proof %s %s, %d calls, %v", proof.VMRef, proof.State, stopCalls, stopTook) d.logf("timings: launch_call=%v to_running=%v drain_call=%v quiescent_call=%v suspend_call=%v to_suspended=%v resume=%v resume_calls=%d epoch=%d to_running_after_resume=%v stop_to_proof=%v stop_calls=%d", launchCall, toRunning, drainCall, quiescentCall, suspendCall, toSuspended, resumeTook, resumeCalls, epoch, toRunningAgain, stopTook, stopCalls) return nil } // crashLaunch is the crash check's first step, against a controller that // exits after the provider call: the launch must fail in transport. Only // then is the VM handed over to the recover step; an answer of any kind // leaves the guard to stop it. func (d *liveDriver) crashLaunch(ctx context.Context, attempt string) error { g := d.guard(attempt) start := time.Now() view, err := d.cl.Launch(ctx, d.launchRequest(attempt)) if err == nil { return fmt.Errorf("Launch(%s) = %+v, nil: the controller answered; was it built with -tags hostedlive and run with EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1? The VM is stopped by the cleanup", attempt, view) } if !errors.Is(err, ErrTransport) { return fmt.Errorf("Launch(%s) = %w, want a transport failure from the controller exiting", attempt, err) } g.release() d.logf("launch: the controller went away %v into the call (%v); restart it without the crash switch and run the recover step", time.Since(start), err) return nil } // operatorKey reads the operator's key ID and key, failing as a whole. type operatorKey func() (hostedwire.KeyID, ed25519.PrivateKey, error) // crashRecover is the crash check's second step, after the restart: the // replay claims the VM, the operator's list shows exactly one VM for the // attempt and none unowned and live, and the VM is stopped with proof. The // guard is registered before anything else, the operator key included. func (d *liveDriver) crashRecover(ctx context.Context, attempt string, opKey operatorKey) error { g := d.guard(attempt) opID, key, err := opKey() if err != nil { return fmt.Errorf("operator key: %w", err) } v, took, err := d.waitFor(ctx, attempt, "a saved VM ref", func(v hostedwire.JobView) bool { return v.VMRef != "" && (v.State == "starting" || v.State == "running") }) if err != nil { return err } d.logf("recover: job %s holds vm %s (%s) %v after the first read", attempt, v.VMRef, v.State, took) vms, err := d.listVMs(ctx, opID, key) if err != nil { return err } var errs []error mine, unowned := 0, 0 for _, vm := range vms { d.logf("listed vm %s state %s attempt %q", vm.VMRef, vm.State, vm.AttemptID) switch { case vm.AttemptID == attempt: mine++ if vm.VMRef != v.VMRef { errs = append(errs, fmt.Errorf("listed vm %s for %s, but the job holds %s", vm.VMRef, attempt, v.VMRef)) } case vm.AttemptID == "" && vm.State.Live(): unowned++ } } if mine != 1 { errs = append(errs, fmt.Errorf("the provider lists %d VMs for %s, want exactly 1", mine, attempt)) } if unowned != 0 { errs = append(errs, fmt.Errorf("the provider lists %d live VMs no job owns, want 0", unowned)) } proof, calls, stopTook, err := d.stopUntilProof(ctx, attempt, "task17 crash check done", d.stateBound) if err != nil { return errors.Join(append(errs, fmt.Errorf("Stop(%s) after %d calls and %v: %w", attempt, calls, stopTook, err))...) } g.release() d.logf("stop: proof %s %s, %d calls, %v", proof.VMRef, proof.State, calls, stopTook) return errors.Join(errs...) } // listVMs is GET /v1/vms signed with the operator key. The client has no // operator method, so the exchange is done here the way the client does // it: one RoundTrip, the answer verified against the request's nonce // before its status or body is used. func (d *liveDriver) listVMs(ctx context.Context, id hostedwire.KeyID, key ed25519.PrivateKey) ([]hostedwire.VMView, error) { ctx, cancel := context.WithTimeout(ctx, d.callTimeout) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.origin+"/v1/vms", http.NoBody) if err != nil { return nil, err } nonce, err := hostedwire.NewNonce() if err != nil { return nil, err } if err := hostedwire.SignRequest(req, nil, id, key, time.Now(), nonce); err != nil { return nil, fmt.Errorf("sign /v1/vms: %w", err) } resp, err := d.rt.RoundTrip(req) if err != nil { return nil, fmt.Errorf("GET /v1/vms: %w", err) } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1)) if err != nil { return nil, fmt.Errorf("GET /v1/vms body: %w", err) } if err := hostedwire.VerifyResponse(resp, body, nonce, d.ctl); err != nil { return nil, fmt.Errorf("GET /v1/vms answer does not verify: %w", err) } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("GET /v1/vms = %d", resp.StatusCode) } var list hostedwire.VMListResponse if err := hostedwire.DecodeStrict(bytes.NewReader(body), &list); err != nil { return nil, fmt.Errorf("GET /v1/vms body: %w", err) } return list.VMs, nil }