oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package hostedclient
2
3import (
4 "context"
5 "crypto/ed25519"
6 "errors"
7 "net/http"
8 "sync/atomic"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/hostedwire"
13)
14
15// offlineDriver is a liveDriver over the test controller with short waits.
16// Its cleanups are collected, not registered, so a test runs them itself
17// and then checks what they did.
18func offlineDriver(t *testing.T, e *ctlEnv, cl *Client) (*liveDriver, func()) {
19 t.Helper()
20 var cleanups []func()
21 d := &liveDriver{cl: cl, origin: e.srv.URL, rt: e.srv.Client().Transport, ctl: ctlPublic(), image: imgA,
22 lifetime: 2 * time.Hour, poll: 2 * time.Millisecond, stateBound: 5 * time.Second, cleanupBound: 5 * time.Second,
23 callTimeout: 5 * time.Second, logf: t.Logf, errorf: t.Errorf,
24 deferFn: func(f func()) { cleanups = append(cleanups, f) }}
25 run := func() {
26 for i := len(cleanups) - 1; i >= 0; i-- {
27 cleanups[i]()
28 }
29 cleanups = nil
30 }
31 return d, run
32}
33
34// settleInBackground moves the fake provider on and lets the controller
35// read it until the test ends, as the reaper's refresh does every 60 s in a
36// live run.
37func (e *ctlEnv) settleInBackground(t *testing.T) {
38 ctx, cancel := context.WithCancel(e.ctx)
39 done := make(chan struct{})
40 go func() {
41 defer close(done)
42 for ctx.Err() == nil {
43 e.fake.Tick()
44 _ = e.c.Refresh(ctx)
45 time.Sleep(2 * time.Millisecond)
46 }
47 }()
48 t.Cleanup(func() { cancel(); <-done })
49}
50
51// countingRT counts round trips, failing the first fail of them before
52// they reach the controller, as a connection reset would.
53type countingRT struct {
54 next http.RoundTripper
55 fail int64
56 calls atomic.Int64
57}
58
59var errReset = errors.New("connection reset by peer")
60
61func (c *countingRT) RoundTrip(r *http.Request) (*http.Response, error) {
62 if n := c.calls.Add(1); n <= c.fail {
63 return nil, errReset
64 }
65 return c.next.RoundTrip(r)
66}
67
68func clientVia(t *testing.T, e *ctlEnv, rt http.RoundTripper) *Client {
69 t.Helper()
70 t.Setenv(FlagEnv, "1")
71 cl, err := New(Config{BaseURL: e.srv.URL, KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(),
72 HTTP: &http.Client{Timeout: 5 * time.Second, Transport: rt}})
73 if err != nil {
74 t.Fatal(err)
75 }
76 return cl
77}
78
79func wantJobState(t *testing.T, cl *Client, attempt, want string) {
80 t.Helper()
81 v, err := cl.Get(context.Background(), attempt)
82 if err != nil || v.State != want {
83 t.Fatalf("Get(%s) = %s, %v; want %s", attempt, v.State, err, want)
84 }
85}
86
87// TestDriverSequenceOffline runs the whole live sequence against the test
88// controller: every step, the epoch rising by one, stop proof.
89func TestDriverSequenceOffline(t *testing.T) {
90 e := newCtlEnv(t)
91 e.settleInBackground(t)
92 cl := newClient(t, e.srv, keyInst, ctlPublic())
93 d, cleanup := offlineDriver(t, e, cl)
94 if err := d.sequence(e.ctx, "seq-1"); err != nil {
95 t.Fatalf("sequence = %v", err)
96 }
97 cleanup()
98 wantJobState(t, cl, "seq-1", "stopped")
99}
100
101// TestDriverCrashLaunchAnsweredStopsVM: against a controller with no crash
102// point the launch answers, the step fails, and its cleanup stops the VM
103// (review round 1, finding 1).
104func TestDriverCrashLaunchAnsweredStopsVM(t *testing.T) {
105 e := newCtlEnv(t)
106 e.settleInBackground(t)
107 cl := newClient(t, e.srv, keyInst, ctlPublic())
108 d, cleanup := offlineDriver(t, e, cl)
109 if err := d.crashLaunch(e.ctx, "crash-1"); err == nil {
110 t.Fatal("crashLaunch against a controller that answered = nil, want an error")
111 }
112 cleanup()
113 wantJobState(t, cl, "crash-1", "stopped")
114}
115
116// TestDriverCrashLaunchTransportHandsOver: the intended crash (the call
117// fails in transport) hands the VM over; the cleanup sends nothing.
118func TestDriverCrashLaunchTransportHandsOver(t *testing.T) {
119 e := newCtlEnv(t)
120 rt := &countingRT{next: e.srv.Client().Transport, fail: 1 << 30}
121 d, cleanup := offlineDriver(t, e, clientVia(t, e, rt))
122 if err := d.crashLaunch(e.ctx, "crash-2"); err != nil {
123 t.Fatalf("crashLaunch with the controller gone = %v, want nil", err)
124 }
125 before := rt.calls.Load()
126 cleanup()
127 if after := rt.calls.Load(); after != before {
128 t.Fatalf("the handed-over cleanup made %d calls, want none", after-before)
129 }
130}
131
132// TestDriverRecoverBadOperatorKeyStopsVM: a recover step whose operator key
133// cannot be read still stops the VM (review round 1, finding 1).
134func TestDriverRecoverBadOperatorKeyStopsVM(t *testing.T) {
135 e := newCtlEnv(t)
136 e.settleInBackground(t)
137 cl := newClient(t, e.srv, keyInst, ctlPublic())
138 if _, err := cl.Launch(e.ctx, launchReq("rec-1")); err != nil {
139 t.Fatal(err)
140 }
141 d, cleanup := offlineDriver(t, e, cl)
142 bad := func() (hostedwire.KeyID, ed25519.PrivateKey, error) {
143 return "", nil, errors.New("operator key file missing")
144 }
145 if err := d.crashRecover(e.ctx, "rec-1", bad); err == nil {
146 t.Fatal("crashRecover with no operator key = nil, want an error")
147 }
148 cleanup()
149 wantJobState(t, cl, "rec-1", "stopped")
150}
151
152// TestDriverStopRetriesTransport: a cleanup stop whose first calls fail in
153// transport sends Stop again and gets proof (review round 1, finding 2).
154func TestDriverStopRetriesTransport(t *testing.T) {
155 e := newCtlEnv(t)
156 e.settleInBackground(t)
157 cl := newClient(t, e.srv, keyInst, ctlPublic())
158 if _, err := cl.Launch(e.ctx, launchReq("stop-1")); err != nil {
159 t.Fatal(err)
160 }
161 rt := &countingRT{next: e.srv.Client().Transport, fail: 2}
162 d, cleanup := offlineDriver(t, e, clientVia(t, e, rt))
163 d.guard("stop-1")
164 cleanup()
165 if n := rt.calls.Load(); n < 3 {
166 t.Fatalf("cleanup made %d calls, want the two failures and a retry", n)
167 }
168 wantJobState(t, cl, "stop-1", "stopped")
169}
170
171func TestRetryableStop(t *testing.T) {
172 for _, row := range []struct {
173 err error
174 want bool
175 }{
176 {&APIError{Status: http.StatusAccepted, Code: "stop_pending", Kind: ErrStopPending}, true},
177 {&APIError{Status: http.StatusTooManyRequests, Code: "throttled", Kind: ErrThrottled}, true},
178 {&APIError{Status: http.StatusServiceUnavailable, Code: "unavailable", Kind: ErrUnavailable}, true},
179 {&APIError{Status: http.StatusServiceUnavailable, Code: "store_lost", Kind: ErrStoreLost}, true},
180 {transportError("stop", "sending", errReset), true},
181 {ErrUnverified, true},
182 {&APIError{Status: http.StatusForbidden, Code: "forbidden", Kind: ErrForbidden}, false},
183 {&APIError{Status: http.StatusConflict, Code: "conflict", Kind: ErrConflict}, false},
184 {errors.New("other"), false},
185 } {
186 if got := retryableStop(row.err); got != row.want {
187 t.Errorf("retryableStop(%v) = %v, want %v", row.err, got, row.want)
188 }
189 }
190}
191