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) } } }