oficina / equipo Public

hostedclient: guard live-driver VMs and retry cleanup stops

Code review round 1 of the Task 17 pre-flight. The driver logic moves to
an untagged liveDriver so offline tests run every path against the test
controller; live_test.go only reads the environment.

The crash steps register the VM guard before the Launch and before the
operator key is read; only the intended crash handover releases it.
Cleanup stops are sent again on transport failure, an unverified answer
or a signed 503. The sequence also wants Resume's epoch to rise by one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 41178b0000d992fcfa7f3eff4540363374c499b5 parent f95575c
3 files changed, +587 −285
  • internal/hostedclient/driver_offline_test.go +190 −0
  • internal/hostedclient/driver_test.go +325 −0
  • internal/hostedclient/live_test.go +72 −285
diff --git a/internal/hostedclient/driver_offline_test.go b/internal/hostedclient/driver_offline_test.go
new file mode 100644
index 00000000..3c6f1487
--- /dev/null
+++ b/internal/hostedclient/driver_offline_test.go
@@ -0,0 +1,190 @@
+package hostedclient
+
+import (
+ "context"
+ "crypto/ed25519"
+ "errors"
+ "net/http"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+)
+
+// offlineDriver is a liveDriver over the test controller with short waits.
+// Its cleanups are collected, not registered, so a test runs them itself
+// and then checks what they did.
+func offlineDriver(t *testing.T, e *ctlEnv, cl *Client) (*liveDriver, func()) {
+ t.Helper()
+ var cleanups []func()
+ d := &liveDriver{cl: cl, origin: e.srv.URL, rt: e.srv.Client().Transport, ctl: ctlPublic(), image: imgA,
+ lifetime: 2 * time.Hour, poll: 2 * time.Millisecond, stateBound: 5 * time.Second, cleanupBound: 5 * time.Second,
+ callTimeout: 5 * time.Second, logf: t.Logf, errorf: t.Errorf,
+ deferFn: func(f func()) { cleanups = append(cleanups, f) }}
+ run := func() {
+ for i := len(cleanups) - 1; i >= 0; i-- {
+ cleanups[i]()
+ }
+ cleanups = nil
+ }
+ return d, run
+}
+
+// settleInBackground moves the fake provider on and lets the controller
+// read it until the test ends, as the reaper's refresh does every 60 s in a
+// live run.
+func (e *ctlEnv) settleInBackground(t *testing.T) {
+ ctx, cancel := context.WithCancel(e.ctx)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ for ctx.Err() == nil {
+ e.fake.Tick()
+ _ = e.c.Refresh(ctx)
+ time.Sleep(2 * time.Millisecond)
+ }
+ }()
+ t.Cleanup(func() { cancel(); <-done })
+}
+
+// countingRT counts round trips, failing the first fail of them before
+// they reach the controller, as a connection reset would.
+type countingRT struct {
+ next http.RoundTripper
+ fail int64
+ calls atomic.Int64
+}
+
+var errReset = errors.New("connection reset by peer")
+
+func (c *countingRT) RoundTrip(r *http.Request) (*http.Response, error) {
+ if n := c.calls.Add(1); n <= c.fail {
+ return nil, errReset
+ }
+ return c.next.RoundTrip(r)
+}
+
+func clientVia(t *testing.T, e *ctlEnv, rt http.RoundTripper) *Client {
+ t.Helper()
+ t.Setenv(FlagEnv, "1")
+ cl, err := New(Config{BaseURL: e.srv.URL, KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(),
+ HTTP: &http.Client{Timeout: 5 * time.Second, Transport: rt}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return cl
+}
+
+func wantJobState(t *testing.T, cl *Client, attempt, want string) {
+ t.Helper()
+ v, err := cl.Get(context.Background(), attempt)
+ if err != nil || v.State != want {
+ t.Fatalf("Get(%s) = %s, %v; want %s", attempt, v.State, err, want)
+ }
+}
+
+// TestDriverSequenceOffline runs the whole live sequence against the test
+// controller: every step, the epoch rising by one, stop proof.
+func TestDriverSequenceOffline(t *testing.T) {
+ e := newCtlEnv(t)
+ e.settleInBackground(t)
+ cl := newClient(t, e.srv, keyInst, ctlPublic())
+ d, cleanup := offlineDriver(t, e, cl)
+ if err := d.sequence(e.ctx, "seq-1"); err != nil {
+ t.Fatalf("sequence = %v", err)
+ }
+ cleanup()
+ wantJobState(t, cl, "seq-1", "stopped")
+}
+
+// TestDriverCrashLaunchAnsweredStopsVM: against a controller with no crash
+// point the launch answers, the step fails, and its cleanup stops the VM
+// (review round 1, finding 1).
+func TestDriverCrashLaunchAnsweredStopsVM(t *testing.T) {
+ e := newCtlEnv(t)
+ e.settleInBackground(t)
+ cl := newClient(t, e.srv, keyInst, ctlPublic())
+ d, cleanup := offlineDriver(t, e, cl)
+ if err := d.crashLaunch(e.ctx, "crash-1"); err == nil {
+ t.Fatal("crashLaunch against a controller that answered = nil, want an error")
+ }
+ cleanup()
+ wantJobState(t, cl, "crash-1", "stopped")
+}
+
+// TestDriverCrashLaunchTransportHandsOver: the intended crash (the call
+// fails in transport) hands the VM over; the cleanup sends nothing.
+func TestDriverCrashLaunchTransportHandsOver(t *testing.T) {
+ e := newCtlEnv(t)
+ rt := &countingRT{next: e.srv.Client().Transport, fail: 1 << 30}
+ d, cleanup := offlineDriver(t, e, clientVia(t, e, rt))
+ if err := d.crashLaunch(e.ctx, "crash-2"); err != nil {
+ t.Fatalf("crashLaunch with the controller gone = %v, want nil", err)
+ }
+ before := rt.calls.Load()
+ cleanup()
+ if after := rt.calls.Load(); after != before {
+ t.Fatalf("the handed-over cleanup made %d calls, want none", after-before)
+ }
+}
+
+// TestDriverRecoverBadOperatorKeyStopsVM: a recover step whose operator key
+// cannot be read still stops the VM (review round 1, finding 1).
+func TestDriverRecoverBadOperatorKeyStopsVM(t *testing.T) {
+ e := newCtlEnv(t)
+ e.settleInBackground(t)
+ cl := newClient(t, e.srv, keyInst, ctlPublic())
+ if _, err := cl.Launch(e.ctx, launchReq("rec-1")); err != nil {
+ t.Fatal(err)
+ }
+ d, cleanup := offlineDriver(t, e, cl)
+ bad := func() (hostedwire.KeyID, ed25519.PrivateKey, error) {
+ return "", nil, errors.New("operator key file missing")
+ }
+ if err := d.crashRecover(e.ctx, "rec-1", bad); err == nil {
+ t.Fatal("crashRecover with no operator key = nil, want an error")
+ }
+ cleanup()
+ wantJobState(t, cl, "rec-1", "stopped")
+}
+
+// TestDriverStopRetriesTransport: a cleanup stop whose first calls fail in
+// transport sends Stop again and gets proof (review round 1, finding 2).
+func TestDriverStopRetriesTransport(t *testing.T) {
+ e := newCtlEnv(t)
+ e.settleInBackground(t)
+ cl := newClient(t, e.srv, keyInst, ctlPublic())
+ if _, err := cl.Launch(e.ctx, launchReq("stop-1")); err != nil {
+ t.Fatal(err)
+ }
+ rt := &countingRT{next: e.srv.Client().Transport, fail: 2}
+ d, cleanup := offlineDriver(t, e, clientVia(t, e, rt))
+ d.guard("stop-1")
+ cleanup()
+ if n := rt.calls.Load(); n < 3 {
+ t.Fatalf("cleanup made %d calls, want the two failures and a retry", n)
+ }
+ wantJobState(t, cl, "stop-1", "stopped")
+}
+
+func TestRetryableStop(t *testing.T) {
+ for _, row := range []struct {
+ err error
+ want bool
+ }{
+ {&APIError{Status: http.StatusAccepted, Code: "stop_pending", Kind: ErrStopPending}, true},
+ {&APIError{Status: http.StatusTooManyRequests, Code: "throttled", Kind: ErrThrottled}, true},
+ {&APIError{Status: http.StatusServiceUnavailable, Code: "unavailable", Kind: ErrUnavailable}, true},
+ {&APIError{Status: http.StatusServiceUnavailable, Code: "store_lost", Kind: ErrStoreLost}, true},
+ {transportError("stop", "sending", errReset), true},
+ {ErrUnverified, true},
+ {&APIError{Status: http.StatusForbidden, Code: "forbidden", Kind: ErrForbidden}, false},
+ {&APIError{Status: http.StatusConflict, Code: "conflict", Kind: ErrConflict}, false},
+ {errors.New("other"), false},
+ } {
+ if got := retryableStop(row.err); got != row.want {
+ t.Errorf("retryableStop(%v) = %v, want %v", row.err, got, row.want)
+ }
+ }
+}
diff --git a/internal/hostedclient/driver_test.go b/internal/hostedclient/driver_test.go
new file mode 100644
index 00000000..34ae6c74
--- /dev/null
+++ b/internal/hostedclient/driver_test.go
@@ -0,0 +1,325 @@
+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
+}
diff --git a/internal/hostedclient/live_test.go b/internal/hostedclient/live_test.go
index 1569c944..27da6c90 100644
--- a/internal/hostedclient/live_test.go
+++ b/internal/hostedclient/live_test.go
@@ -5,7 +5,8 @@ package hostedclient
// Live drivers for Task 17. They talk to a running equipo-hosted-controller
// through this package's client, so they launch and stop real VMs. They run
// only by hand, with -tags hostedlive and the environment below; without
-// EQUIPO_HOSTED_LIVE_URL they skip.
+// EQUIPO_HOSTED_LIVE_URL they skip. The logic is liveDriver
+// (driver_test.go), which the offline tests also run.
//
// EQUIPO_HOSTED_LIVE_URL https origin of the controller, such as https://127.0.0.1:8443
// EQUIPO_HOSTED_LIVE_CA_FILE PEM certificate the controller's TLS certificate chains to
@@ -19,7 +20,6 @@ package hostedclient
// EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID and EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE.
import (
- "bytes"
"context"
"crypto/ed25519"
"crypto/rand"
@@ -27,8 +27,7 @@ import (
"crypto/x509"
"encoding/base64"
"encoding/hex"
- "errors"
- "io"
+ "fmt"
"net/http"
"os"
"strings"
@@ -40,33 +39,21 @@ import (
)
const (
- liveURLEnv = "EQUIPO_HOSTED_LIVE_URL"
- liveCAFileEnv = "EQUIPO_HOSTED_LIVE_CA_FILE"
- liveKeyIDEnv = "EQUIPO_HOSTED_LIVE_KEY_ID"
- liveKeyFileEnv = "EQUIPO_HOSTED_LIVE_KEY_FILE"
- liveCtlKeyFileEnv = "EQUIPO_HOSTED_LIVE_CONTROLLER_KEY_FILE"
- liveImageEnv = "EQUIPO_HOSTED_LIVE_IMAGE"
- liveCrashStepEnv = "EQUIPO_HOSTED_LIVE_CRASH_STEP"
- liveAttemptEnv = "EQUIPO_HOSTED_LIVE_ATTEMPT"
- liveOpKeyIDEnv = "EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID"
- liveOpKeyFileEnv = "EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE"
- liveLifetime = time.Hour
- liveCallTimeout = 2 * time.Minute // a launch waits on the provider
- liveStateBound = 5 * time.Minute // the controller reads VM states once per reaper pass (60 s)
- livePoll = 5 * time.Second
- liveCleanupStopTime = 5 * time.Minute
+ liveURLEnv = "EQUIPO_HOSTED_LIVE_URL"
+ liveCAFileEnv = "EQUIPO_HOSTED_LIVE_CA_FILE"
+ liveKeyIDEnv = "EQUIPO_HOSTED_LIVE_KEY_ID"
+ liveKeyFileEnv = "EQUIPO_HOSTED_LIVE_KEY_FILE"
+ liveCtlKeyFileEnv = "EQUIPO_HOSTED_LIVE_CONTROLLER_KEY_FILE"
+ liveImageEnv = "EQUIPO_HOSTED_LIVE_IMAGE"
+ liveCrashStepEnv = "EQUIPO_HOSTED_LIVE_CRASH_STEP"
+ liveAttemptEnv = "EQUIPO_HOSTED_LIVE_ATTEMPT"
+ liveOpKeyIDEnv = "EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID"
+ liveOpKeyFileEnv = "EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE"
+ liveCallTimeout = 2 * time.Minute // a launch waits on the provider
)
-// liveEnv is a client for the controller the environment names.
-type liveEnv struct {
- cl *Client
- origin string
- ctl ed25519.PublicKey
- rt http.RoundTripper
- image isolatedjob.ImageDigest
-}
-
-func newLiveEnv(t *testing.T) *liveEnv {
+// newLiveDriver builds the driver for the controller the environment names.
+func newLiveDriver(t *testing.T) *liveDriver {
t.Helper()
origin := os.Getenv(liveURLEnv)
if origin == "" {
@@ -81,20 +68,29 @@ func newLiveEnv(t *testing.T) *liveEnv {
t.Fatalf("%s holds no PEM certificate", liveCAFileEnv)
}
rt := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}}
- e := &liveEnv{
- origin: strings.TrimSuffix(origin, "/"),
- ctl: readLivePublic(t, liveNeed(t, liveCtlKeyFileEnv)),
- rt: rt,
- image: isolatedjob.ImageDigest(liveNeed(t, liveImageEnv)),
+ ctl, err := readLiveB64(liveNeed(t, liveCtlKeyFileEnv), ed25519.PublicKeySize)
+ if err != nil {
+ t.Fatal(err)
+ }
+ seed, err := readLiveB64(liveNeed(t, liveKeyFileEnv), ed25519.SeedSize)
+ if err != nil {
+ t.Fatal(err)
+ }
+ d := &liveDriver{
+ origin: strings.TrimSuffix(origin, "/"), rt: rt, ctl: ed25519.PublicKey(ctl),
+ image: isolatedjob.ImageDigest(liveNeed(t, liveImageEnv)),
+ lifetime: time.Hour, poll: 5 * time.Second, stateBound: 5 * time.Minute, cleanupBound: 5 * time.Minute,
+ callTimeout: liveCallTimeout,
+ logf: t.Logf, errorf: t.Errorf, deferFn: t.Cleanup,
}
t.Setenv(FlagEnv, "1")
- e.cl, err = New(Config{BaseURL: origin, KeyID: hostedwire.KeyID(liveNeed(t, liveKeyIDEnv)),
- Key: readLiveSeed(t, liveNeed(t, liveKeyFileEnv)), ControllerKey: e.ctl,
+ d.cl, err = New(Config{BaseURL: origin, KeyID: hostedwire.KeyID(liveNeed(t, liveKeyIDEnv)),
+ Key: ed25519.NewKeyFromSeed(seed), ControllerKey: d.ctl,
HTTP: &http.Client{Timeout: liveCallTimeout, Transport: rt}})
if err != nil {
t.Fatalf("hostedclient.New: %v", err)
}
- return e
+ return d
}
func liveNeed(t *testing.T, name string) string {
@@ -106,183 +102,36 @@ func liveNeed(t *testing.T, name string) string {
return v
}
-// readLiveSeed reads a 32-byte ed25519 seed in standard base64, the format
-// of the controller's signing_key_file.
-func readLiveSeed(t *testing.T, path string) ed25519.PrivateKey {
- t.Helper()
- seed := readLiveB64(t, path, ed25519.SeedSize)
- return ed25519.NewKeyFromSeed(seed)
-}
-
-// readLivePublic reads a 32-byte ed25519 public key in standard base64, the
-// format of a verify_keys public_key.
-func readLivePublic(t *testing.T, path string) ed25519.PublicKey {
- t.Helper()
- return ed25519.PublicKey(readLiveB64(t, path, ed25519.PublicKeySize))
-}
-
-func readLiveB64(t *testing.T, path string, size int) []byte {
- t.Helper()
+// readLiveB64 reads size bytes in standard base64: an ed25519 seed (the
+// format of the controller's signing_key_file) or public key (a
+// verify_keys public_key).
+func readLiveB64(path string, size int) ([]byte, error) {
raw, err := os.ReadFile(path)
if err != nil {
- t.Fatalf("key file: %v", err)
+ return nil, fmt.Errorf("key file: %w", err)
}
b, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw)))
if err != nil || len(b) != size {
- t.Fatalf("key file %s must hold %d bytes in standard base64", path, size)
- }
- return b
-}
-
-func liveAttempt(t *testing.T) string {
- t.Helper()
- if a := os.Getenv(liveAttemptEnv); a != "" {
- return a
- }
- b := make([]byte, 6)
- if _, err := rand.Read(b); err != nil {
- t.Fatal(err)
- }
- return "task17-" + hex.EncodeToString(b)
-}
-
-func (e *liveEnv) launchRequest(attempt string) hostedwire.LaunchRequest {
- return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task17-live", Account: "task17-live",
- Image: e.image, Size: isolatedjob.SizeSmall, MaxLifetimeMS: liveLifetime.Milliseconds(),
- InstanceCode: "task17-code-" + attempt}
-}
-
-// waitFor reads the job until done accepts its view, for at most
-// liveStateBound, and returns the view and the time taken. A job that
-// reaches stopped or abandoned without done accepting it fails the test.
-func (e *liveEnv) waitFor(t *testing.T, attempt, what string, done func(hostedwire.JobView) bool) (hostedwire.JobView, time.Duration) {
- t.Helper()
- start := time.Now()
- for {
- v, err := e.cl.Get(context.Background(), attempt)
- if err != nil {
- t.Fatalf("Get(%s) while waiting for %s: %v", attempt, what, err)
- }
- if done(v) {
- return v, time.Since(start)
- }
- if v.State == "stopped" || v.State == "abandoned" {
- t.Fatalf("job %s is %s while waiting for %s", attempt, v.State, what)
- }
- if time.Since(start) > liveStateBound {
- t.Fatalf("job %s still %s after %v, want %s", attempt, v.State, liveStateBound, what)
- }
- time.Sleep(livePoll)
- }
-}
-
-func stateIs(s string) func(hostedwire.JobView) bool {
- return func(v hostedwire.JobView) bool { return v.State == s }
-}
-
-// 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.
-func (e *liveEnv) stopUntilProof(attempt, reason string, bound time.Duration) (hostedwire.StopProof, int, time.Duration, error) {
- start := time.Now()
- for calls := 1; ; calls++ {
- proof, err := e.cl.Stop(context.Background(), attempt, reason)
- if err == nil {
- return proof, calls, time.Since(start), nil
- }
- if !errors.Is(err, ErrStopPending) && !errors.Is(err, ErrThrottled) || time.Since(start) > bound {
- return proof, calls, time.Since(start), err
- }
- time.Sleep(livePoll)
+ return nil, fmt.Errorf("key file %s must hold %d bytes in standard base64", path, size)
}
+ return b, nil
}
-// stopOnFailure stops attempt's VM if the test ends without proof.
-func (e *liveEnv) stopOnFailure(t *testing.T, attempt string, proven *bool) {
- t.Cleanup(func() {
- if *proven {
- return
- }
- proof, calls, took, err := e.stopUntilProof(attempt, "task17 cleanup", liveCleanupStopTime)
- if err != nil {
- t.Errorf("cleanup stop of %s after %d calls and %v: %v; check the provider for a VM left running", attempt, calls, took, err)
- return
- }
- t.Logf("cleanup stop of %s: proof %s %s", attempt, proof.VMRef, proof.State)
- })
-}
-
-// TestLiveControllerSequence drives one Small VM through the controller:
-// launch, running, drain, quiescent, suspend, suspended, resume, running,
-// stop with proof. It logs each timing and the epoch.
+// TestLiveControllerSequence drives one Small VM through the controller
+// (liveDriver.sequence) and logs each timing and the epoch.
func TestLiveControllerSequence(t *testing.T) {
- e := newLiveEnv(t)
- ctx := context.Background()
- attempt := liveAttempt(t)
- t.Logf("attempt %s, image %s, size small", attempt, e.image)
- proven := false
- e.stopOnFailure(t, attempt, &proven)
-
- start := time.Now()
- view, err := e.cl.Launch(ctx, e.launchRequest(attempt))
- launchCall := time.Since(start)
- if err != nil {
- t.Fatalf("Launch(%s) after %v: %v", attempt, launchCall, err)
- }
- t.Logf("launch: call %v, state %s, vm %s, epoch %d", launchCall, view.State, view.VMRef, view.Epoch)
- running, toRunning := e.waitFor(t, attempt, "running", stateIs("running"))
- t.Logf("running: %v after the launch call returned; vm %s, epoch %d", toRunning, running.VMRef, running.Epoch)
-
- start = time.Now()
- gen, err := e.cl.Drain(ctx, attempt)
- drainCall := time.Since(start)
- if err != nil {
- t.Fatalf("Drain: %v", err)
- }
- start = time.Now()
- if err := e.cl.Quiescent(ctx, attempt, gen); err != nil {
- t.Fatalf("Quiescent(%d): %v", gen, err)
- }
- quiescentCall := time.Since(start)
- start = time.Now()
- if err := e.cl.Suspend(ctx, attempt, gen); err != nil {
- t.Fatalf("Suspend(%d): %v", gen, err)
- }
- suspendCall := time.Since(start)
- t.Logf("pause: generation %d, drain call %v, quiescent call %v, suspend call %v", gen, drainCall, quiescentCall, suspendCall)
- _, toSuspended := e.waitFor(t, attempt, "suspended", stateIs("suspended"))
- t.Logf("suspended: %v after the suspend call returned", toSuspended)
-
- opID := "resume-" + attempt
- start = time.Now()
- var epoch int64
- resumeCalls := 0
- for {
- resumeCalls++
- epoch, err = e.cl.Resume(ctx, attempt, opID)
- if err == nil {
- break
- }
- if !errors.Is(err, ErrResumePending) || time.Since(start) > liveStateBound {
- t.Fatalf("Resume(%s) call %d after %v: %v", opID, resumeCalls, time.Since(start), err)
+ d := newLiveDriver(t)
+ attempt := os.Getenv(liveAttemptEnv)
+ if attempt == "" {
+ b := make([]byte, 6)
+ if _, err := rand.Read(b); err != nil {
+ t.Fatal(err)
}
- time.Sleep(livePoll)
- }
- resumeTook := time.Since(start)
- t.Logf("resume: epoch %d (was %d), %d calls, %v from the first call to the epoch", epoch, running.Epoch, resumeCalls, resumeTook)
- after, toRunningAgain := e.waitFor(t, attempt, "running after resume", stateIs("running"))
- if after.Epoch != epoch {
- t.Errorf("job epoch after resume = %d, want %d", after.Epoch, epoch)
+ attempt = "task17-" + hex.EncodeToString(b)
}
- t.Logf("running after resume: %v after the epoch came back", toRunningAgain)
-
- proof, stopCalls, stopTook, err := e.stopUntilProof(attempt, "task17 done", liveStateBound)
- if err != nil {
- t.Fatalf("Stop(%s) after %d calls and %v: %v", attempt, stopCalls, stopTook, err)
+ if err := d.sequence(context.Background(), attempt); err != nil {
+ t.Fatal(err)
}
- proven = true
- t.Logf("stop: proof %s %s, %d calls, %v", proof.VMRef, proof.State, stopCalls, stopTook)
- t.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)
}
// TestLiveCrashRecovery is the "kill the controller between the provider
@@ -292,104 +141,42 @@ func TestLiveControllerSequence(t *testing.T) {
// - EQUIPO_HOSTED_LIVE_CRASH_STEP=launch, against a controller built with
// -tags hostedlive and run with EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1: the
// launch reaches the provider, the controller exits before saving the
-// Ref, and the call fails in transport.
+// Ref, and the call fails in transport. Any answer instead fails the
+// test and the VM is stopped.
// - EQUIPO_HOSTED_LIVE_CRASH_STEP=recover, after restarting the controller
// without EQUIPO_HOSTED_CRASH_AFTER_LAUNCH: the reaper's replay claims the
// VM, the operator's VM list shows exactly one VM for the attempt, and
-// the VM is stopped with proof.
+// the VM is stopped with proof. A failure, a bad operator key included,
+// still stops it.
//
// Both steps need the same EQUIPO_HOSTED_LIVE_ATTEMPT.
func TestLiveCrashRecovery(t *testing.T) {
- e := newLiveEnv(t)
+ d := newLiveDriver(t)
attempt := liveNeed(t, liveAttemptEnv)
+ var err error
switch step := liveNeed(t, liveCrashStepEnv); step {
case "launch":
- start := time.Now()
- view, err := e.cl.Launch(context.Background(), e.launchRequest(attempt))
- if err == nil {
- t.Fatalf("Launch(%s) = %+v, nil: the controller answered; was it built with -tags hostedlive and run with EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1? Stop this VM now", attempt, view)
- }
- if !errors.Is(err, ErrTransport) {
- t.Fatalf("Launch(%s) = %v, want a transport failure from the controller exiting", attempt, err)
- }
- t.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)
+ err = d.crashLaunch(context.Background(), attempt)
case "recover":
- opID := hostedwire.KeyID(liveNeed(t, liveOpKeyIDEnv))
- opKey := readLiveSeed(t, liveNeed(t, liveOpKeyFileEnv))
- proven := false
- e.stopOnFailure(t, attempt, &proven)
- v, took := e.waitFor(t, attempt, "a saved VM ref", func(v hostedwire.JobView) bool {
- return v.VMRef != "" && (v.State == "starting" || v.State == "running")
- })
- t.Logf("recover: job %s holds vm %s (%s) %v after the first read", attempt, v.VMRef, v.State, took)
- vms := e.listVMs(t, opID, opKey)
- mine, unowned := 0, 0
- for _, vm := range vms {
- t.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 {
- t.Errorf("listed vm %s for %s, but the job holds %s", vm.VMRef, attempt, v.VMRef)
- }
- case vm.AttemptID == "" && vm.State.Live():
- unowned++
+ err = d.crashRecover(context.Background(), attempt, func() (hostedwire.KeyID, ed25519.PrivateKey, error) {
+ id := os.Getenv(liveOpKeyIDEnv)
+ if id == "" {
+ return "", nil, fmt.Errorf("%s is not set", liveOpKeyIDEnv)
}
- }
- if mine != 1 {
- t.Errorf("the provider lists %d VMs for %s, want exactly 1", mine, attempt)
- }
- if unowned != 0 {
- t.Errorf("the provider lists %d live VMs no job owns, want 0", unowned)
- }
- proof, calls, stopTook, err := e.stopUntilProof(attempt, "task17 crash check done", liveStateBound)
- if err != nil {
- t.Fatalf("Stop(%s) after %d calls and %v: %v", attempt, calls, stopTook, err)
- }
- proven = true
- t.Logf("stop: proof %s %s, %d calls, %v", proof.VMRef, proof.State, calls, stopTook)
+ path := os.Getenv(liveOpKeyFileEnv)
+ if path == "" {
+ return "", nil, fmt.Errorf("%s is not set", liveOpKeyFileEnv)
+ }
+ seed, err := readLiveB64(path, ed25519.SeedSize)
+ if err != nil {
+ return "", nil, err
+ }
+ return hostedwire.KeyID(id), ed25519.NewKeyFromSeed(seed), nil
+ })
default:
t.Fatalf("%s = %q, want launch or recover", liveCrashStepEnv, step)
}
-}
-
-// 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 (e *liveEnv) listVMs(t *testing.T, id hostedwire.KeyID, key ed25519.PrivateKey) []hostedwire.VMView {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), liveCallTimeout)
- defer cancel()
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, e.origin+"/v1/vms", http.NoBody)
- if err != nil {
- t.Fatal(err)
- }
- nonce, err := hostedwire.NewNonce()
if err != nil {
t.Fatal(err)
}
- if err := hostedwire.SignRequest(req, nil, id, key, time.Now(), nonce); err != nil {
- t.Fatalf("sign /v1/vms: %v", err)
- }
- resp, err := e.rt.RoundTrip(req)
- if err != nil {
- t.Fatalf("GET /v1/vms: %v", err)
- }
- defer resp.Body.Close()
- body, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1))
- if err != nil {
- t.Fatalf("GET /v1/vms body: %v", err)
- }
- if err := hostedwire.VerifyResponse(resp, body, nonce, e.ctl); err != nil {
- t.Fatalf("GET /v1/vms answer does not verify: %v", err)
- }
- if resp.StatusCode != http.StatusOK {
- t.Fatalf("GET /v1/vms = %d %s", resp.StatusCode, body)
- }
- var list hostedwire.VMListResponse
- if err := hostedwire.DecodeStrict(bytes.NewReader(body), &list); err != nil {
- t.Fatalf("GET /v1/vms body: %v", err)
- }
- return list.VMs
}