| 1 | package hostedclient |
| 2 | |
| 3 | // The Task 17 driver logic. live_test.go (hostedlive) wires it to a real |
| 4 | // controller from the environment; the offline tests below run it against |
| 5 | // the test controller and the fake provider, so CI checks every path the |
| 6 | // live run takes, failure cleanups included. |
| 7 | |
| 8 | import ( |
| 9 | "bytes" |
| 10 | "context" |
| 11 | "crypto/ed25519" |
| 12 | "errors" |
| 13 | "fmt" |
| 14 | "io" |
| 15 | "net/http" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 19 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 20 | ) |
| 21 | |
| 22 | // liveDriver drives one controller through cl. Steps return errors; the |
| 23 | // cleanups they register go through deferFn (t.Cleanup in a live run) and |
| 24 | // report through errorf. |
| 25 | type liveDriver struct { |
| 26 | cl *Client |
| 27 | origin string // for the operator's GET /v1/vms |
| 28 | rt http.RoundTripper // likewise |
| 29 | ctl ed25519.PublicKey // likewise |
| 30 | image isolatedjob.ImageDigest |
| 31 | |
| 32 | lifetime time.Duration // of each launched VM |
| 33 | poll time.Duration // between reads while waiting |
| 34 | stateBound time.Duration // for each wait for a state, a resume or a stop |
| 35 | cleanupBound time.Duration // for the stop a failure cleanup sends |
| 36 | callTimeout time.Duration // for the operator's list call |
| 37 | |
| 38 | logf func(format string, args ...any) |
| 39 | errorf func(format string, args ...any) |
| 40 | deferFn func(func()) |
| 41 | } |
| 42 | |
| 43 | func (d *liveDriver) launchRequest(attempt string) hostedwire.LaunchRequest { |
| 44 | return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task17-live", Account: "task17-live", |
| 45 | Image: d.image, Size: isolatedjob.SizeSmall, MaxLifetimeMS: d.lifetime.Milliseconds(), |
| 46 | InstanceCode: "task17-code-" + attempt} |
| 47 | } |
| 48 | |
| 49 | // vmGuard stops an attempt's VM when the step that registered it ends |
| 50 | // without releasing it. |
| 51 | type vmGuard struct{ released bool } |
| 52 | |
| 53 | // release ends the guard: the VM has stop proof, or is handed over on |
| 54 | // purpose (the crash step leaves it for the recover step). |
| 55 | func (g *vmGuard) release() { g.released = true } |
| 56 | |
| 57 | // guard registers, before anything can create a VM, the cleanup that stops |
| 58 | // attempt's VM unless the guard is released. An attempt the controller does |
| 59 | // not know for this key (forbidden) has nothing to stop. |
| 60 | func (d *liveDriver) guard(attempt string) *vmGuard { |
| 61 | g := &vmGuard{} |
| 62 | d.deferFn(func() { |
| 63 | if g.released { |
| 64 | return |
| 65 | } |
| 66 | proof, calls, took, err := d.stopUntilProof(context.Background(), attempt, "task17 cleanup", d.cleanupBound) |
| 67 | switch { |
| 68 | case errors.Is(err, ErrForbidden): |
| 69 | d.logf("cleanup: the controller holds no job %s for this key; nothing to stop", attempt) |
| 70 | case err != nil: |
| 71 | d.errorf("cleanup stop of %s after %d calls and %v: %v; check the provider for a VM left running", attempt, calls, took, err) |
| 72 | default: |
| 73 | d.logf("cleanup stop of %s: proof %s %s after %d calls", attempt, proof.VMRef, proof.State, calls) |
| 74 | } |
| 75 | }) |
| 76 | return g |
| 77 | } |
| 78 | |
| 79 | // retryableStop reports whether a Stop may simply be sent again: the stop |
| 80 | // is pending, the provider is busy, the controller is unavailable (503) or |
| 81 | // the exchange failed before a verified answer came back. Stop is |
| 82 | // idempotent, so resending is safe whatever the first call did. |
| 83 | func retryableStop(err error) bool { |
| 84 | var api *APIError |
| 85 | return errors.Is(err, ErrStopPending) || errors.Is(err, ErrThrottled) || errors.Is(err, ErrTransport) || |
| 86 | errors.Is(err, ErrUnverified) || errors.As(err, &api) && api.Status == http.StatusServiceUnavailable |
| 87 | } |
| 88 | |
| 89 | // stopUntilProof asks for a stop until the controller has proof, for at |
| 90 | // most bound, and returns the proof, the calls made and the time taken. The |
| 91 | // last error is returned when bound passes without proof. |
| 92 | func (d *liveDriver) stopUntilProof(ctx context.Context, attempt, reason string, bound time.Duration) (hostedwire.StopProof, int, time.Duration, error) { |
| 93 | start := time.Now() |
| 94 | for calls := 1; ; calls++ { |
| 95 | proof, err := d.cl.Stop(ctx, attempt, reason) |
| 96 | if err == nil { |
| 97 | return proof, calls, time.Since(start), nil |
| 98 | } |
| 99 | if !retryableStop(err) || time.Since(start) > bound { |
| 100 | return proof, calls, time.Since(start), err |
| 101 | } |
| 102 | time.Sleep(d.poll) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | // waitFor reads the job until done accepts its view, for at most |
| 107 | // stateBound. A job that reaches stopped or abandoned first is an error. |
| 108 | func (d *liveDriver) waitFor(ctx context.Context, attempt, what string, done func(hostedwire.JobView) bool) (hostedwire.JobView, time.Duration, error) { |
| 109 | start := time.Now() |
| 110 | for { |
| 111 | v, err := d.cl.Get(ctx, attempt) |
| 112 | if err != nil { |
| 113 | return v, time.Since(start), fmt.Errorf("Get(%s) while waiting for %s: %w", attempt, what, err) |
| 114 | } |
| 115 | if done(v) { |
| 116 | return v, time.Since(start), nil |
| 117 | } |
| 118 | if v.State == "stopped" || v.State == "abandoned" { |
| 119 | return v, time.Since(start), fmt.Errorf("job %s is %s while waiting for %s", attempt, v.State, what) |
| 120 | } |
| 121 | if time.Since(start) > d.stateBound { |
| 122 | return v, time.Since(start), fmt.Errorf("job %s still %s after %v, want %s", attempt, v.State, d.stateBound, what) |
| 123 | } |
| 124 | time.Sleep(d.poll) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func stateIs(s string) func(hostedwire.JobView) bool { |
| 129 | return func(v hostedwire.JobView) bool { return v.State == s } |
| 130 | } |
| 131 | |
| 132 | // sequence drives one Small VM: launch, running, drain, quiescent, suspend, |
| 133 | // suspended, resume (the epoch must rise by one), running, stop with proof. |
| 134 | // It logs each timing and the epoch. |
| 135 | func (d *liveDriver) sequence(ctx context.Context, attempt string) error { |
| 136 | d.logf("attempt %s, image %s, size small", attempt, d.image) |
| 137 | g := d.guard(attempt) |
| 138 | |
| 139 | start := time.Now() |
| 140 | view, err := d.cl.Launch(ctx, d.launchRequest(attempt)) |
| 141 | launchCall := time.Since(start) |
| 142 | if err != nil { |
| 143 | return fmt.Errorf("Launch(%s) after %v: %w", attempt, launchCall, err) |
| 144 | } |
| 145 | d.logf("launch: call %v, state %s, vm %s, epoch %d", launchCall, view.State, view.VMRef, view.Epoch) |
| 146 | running, toRunning, err := d.waitFor(ctx, attempt, "running", stateIs("running")) |
| 147 | if err != nil { |
| 148 | return err |
| 149 | } |
| 150 | d.logf("running: %v after the launch call returned; vm %s, epoch %d", toRunning, running.VMRef, running.Epoch) |
| 151 | |
| 152 | start = time.Now() |
| 153 | gen, err := d.cl.Drain(ctx, attempt) |
| 154 | drainCall := time.Since(start) |
| 155 | if err != nil { |
| 156 | return fmt.Errorf("Drain: %w", err) |
| 157 | } |
| 158 | start = time.Now() |
| 159 | if err := d.cl.Quiescent(ctx, attempt, gen); err != nil { |
| 160 | return fmt.Errorf("Quiescent(%d): %w", gen, err) |
| 161 | } |
| 162 | quiescentCall := time.Since(start) |
| 163 | start = time.Now() |
| 164 | if err := d.cl.Suspend(ctx, attempt, gen); err != nil { |
| 165 | return fmt.Errorf("Suspend(%d): %w", gen, err) |
| 166 | } |
| 167 | suspendCall := time.Since(start) |
| 168 | d.logf("pause: generation %d, drain call %v, quiescent call %v, suspend call %v", gen, drainCall, quiescentCall, suspendCall) |
| 169 | _, toSuspended, err := d.waitFor(ctx, attempt, "suspended", stateIs("suspended")) |
| 170 | if err != nil { |
| 171 | return err |
| 172 | } |
| 173 | d.logf("suspended: %v after the suspend call returned", toSuspended) |
| 174 | |
| 175 | opID := "resume-" + attempt |
| 176 | start = time.Now() |
| 177 | var epoch int64 |
| 178 | resumeCalls := 0 |
| 179 | for { |
| 180 | resumeCalls++ |
| 181 | epoch, err = d.cl.Resume(ctx, attempt, opID) |
| 182 | if err == nil { |
| 183 | break |
| 184 | } |
| 185 | if !errors.Is(err, ErrResumePending) || time.Since(start) > d.stateBound { |
| 186 | return fmt.Errorf("Resume(%s) call %d after %v: %w", opID, resumeCalls, time.Since(start), err) |
| 187 | } |
| 188 | time.Sleep(d.poll) |
| 189 | } |
| 190 | resumeTook := time.Since(start) |
| 191 | d.logf("resume: epoch %d (was %d), %d calls, %v from the first call to the epoch", epoch, running.Epoch, resumeCalls, resumeTook) |
| 192 | if epoch != running.Epoch+1 { |
| 193 | return fmt.Errorf("Resume gave epoch %d, want %d: one resume raises the epoch by one", epoch, running.Epoch+1) |
| 194 | } |
| 195 | after, toRunningAgain, err := d.waitFor(ctx, attempt, "running after resume", stateIs("running")) |
| 196 | if err != nil { |
| 197 | return err |
| 198 | } |
| 199 | if after.Epoch != epoch { |
| 200 | return fmt.Errorf("job epoch after resume = %d, want %d", after.Epoch, epoch) |
| 201 | } |
| 202 | d.logf("running after resume: %v after the epoch came back", toRunningAgain) |
| 203 | |
| 204 | proof, stopCalls, stopTook, err := d.stopUntilProof(ctx, attempt, "task17 done", d.stateBound) |
| 205 | if err != nil { |
| 206 | return fmt.Errorf("Stop(%s) after %d calls and %v: %w", attempt, stopCalls, stopTook, err) |
| 207 | } |
| 208 | g.release() |
| 209 | d.logf("stop: proof %s %s, %d calls, %v", proof.VMRef, proof.State, stopCalls, stopTook) |
| 210 | 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", |
| 211 | launchCall, toRunning, drainCall, quiescentCall, suspendCall, toSuspended, resumeTook, resumeCalls, epoch, toRunningAgain, stopTook, stopCalls) |
| 212 | return nil |
| 213 | } |
| 214 | |
| 215 | // crashLaunch is the crash check's first step, against a controller that |
| 216 | // exits after the provider call: the launch must fail in transport. Only |
| 217 | // then is the VM handed over to the recover step; an answer of any kind |
| 218 | // leaves the guard to stop it. |
| 219 | func (d *liveDriver) crashLaunch(ctx context.Context, attempt string) error { |
| 220 | g := d.guard(attempt) |
| 221 | start := time.Now() |
| 222 | view, err := d.cl.Launch(ctx, d.launchRequest(attempt)) |
| 223 | if err == nil { |
| 224 | 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) |
| 225 | } |
| 226 | if !errors.Is(err, ErrTransport) { |
| 227 | return fmt.Errorf("Launch(%s) = %w, want a transport failure from the controller exiting", attempt, err) |
| 228 | } |
| 229 | g.release() |
| 230 | 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) |
| 231 | return nil |
| 232 | } |
| 233 | |
| 234 | // operatorKey reads the operator's key ID and key, failing as a whole. |
| 235 | type operatorKey func() (hostedwire.KeyID, ed25519.PrivateKey, error) |
| 236 | |
| 237 | // crashRecover is the crash check's second step, after the restart: the |
| 238 | // replay claims the VM, the operator's list shows exactly one VM for the |
| 239 | // attempt and none unowned and live, and the VM is stopped with proof. The |
| 240 | // guard is registered before anything else, the operator key included. |
| 241 | func (d *liveDriver) crashRecover(ctx context.Context, attempt string, opKey operatorKey) error { |
| 242 | g := d.guard(attempt) |
| 243 | opID, key, err := opKey() |
| 244 | if err != nil { |
| 245 | return fmt.Errorf("operator key: %w", err) |
| 246 | } |
| 247 | v, took, err := d.waitFor(ctx, attempt, "a saved VM ref", func(v hostedwire.JobView) bool { |
| 248 | return v.VMRef != "" && (v.State == "starting" || v.State == "running") |
| 249 | }) |
| 250 | if err != nil { |
| 251 | return err |
| 252 | } |
| 253 | d.logf("recover: job %s holds vm %s (%s) %v after the first read", attempt, v.VMRef, v.State, took) |
| 254 | vms, err := d.listVMs(ctx, opID, key) |
| 255 | if err != nil { |
| 256 | return err |
| 257 | } |
| 258 | var errs []error |
| 259 | mine, unowned := 0, 0 |
| 260 | for _, vm := range vms { |
| 261 | d.logf("listed vm %s state %s attempt %q", vm.VMRef, vm.State, vm.AttemptID) |
| 262 | switch { |
| 263 | case vm.AttemptID == attempt: |
| 264 | mine++ |
| 265 | if vm.VMRef != v.VMRef { |
| 266 | errs = append(errs, fmt.Errorf("listed vm %s for %s, but the job holds %s", vm.VMRef, attempt, v.VMRef)) |
| 267 | } |
| 268 | case vm.AttemptID == "" && vm.State.Live(): |
| 269 | unowned++ |
| 270 | } |
| 271 | } |
| 272 | if mine != 1 { |
| 273 | errs = append(errs, fmt.Errorf("the provider lists %d VMs for %s, want exactly 1", mine, attempt)) |
| 274 | } |
| 275 | if unowned != 0 { |
| 276 | errs = append(errs, fmt.Errorf("the provider lists %d live VMs no job owns, want 0", unowned)) |
| 277 | } |
| 278 | proof, calls, stopTook, err := d.stopUntilProof(ctx, attempt, "task17 crash check done", d.stateBound) |
| 279 | if err != nil { |
| 280 | return errors.Join(append(errs, fmt.Errorf("Stop(%s) after %d calls and %v: %w", attempt, calls, stopTook, err))...) |
| 281 | } |
| 282 | g.release() |
| 283 | d.logf("stop: proof %s %s, %d calls, %v", proof.VMRef, proof.State, calls, stopTook) |
| 284 | return errors.Join(errs...) |
| 285 | } |
| 286 | |
| 287 | // listVMs is GET /v1/vms signed with the operator key. The client has no |
| 288 | // operator method, so the exchange is done here the way the client does |
| 289 | // it: one RoundTrip, the answer verified against the request's nonce |
| 290 | // before its status or body is used. |
| 291 | func (d *liveDriver) listVMs(ctx context.Context, id hostedwire.KeyID, key ed25519.PrivateKey) ([]hostedwire.VMView, error) { |
| 292 | ctx, cancel := context.WithTimeout(ctx, d.callTimeout) |
| 293 | defer cancel() |
| 294 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.origin+"/v1/vms", http.NoBody) |
| 295 | if err != nil { |
| 296 | return nil, err |
| 297 | } |
| 298 | nonce, err := hostedwire.NewNonce() |
| 299 | if err != nil { |
| 300 | return nil, err |
| 301 | } |
| 302 | if err := hostedwire.SignRequest(req, nil, id, key, time.Now(), nonce); err != nil { |
| 303 | return nil, fmt.Errorf("sign /v1/vms: %w", err) |
| 304 | } |
| 305 | resp, err := d.rt.RoundTrip(req) |
| 306 | if err != nil { |
| 307 | return nil, fmt.Errorf("GET /v1/vms: %w", err) |
| 308 | } |
| 309 | defer resp.Body.Close() |
| 310 | body, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1)) |
| 311 | if err != nil { |
| 312 | return nil, fmt.Errorf("GET /v1/vms body: %w", err) |
| 313 | } |
| 314 | if err := hostedwire.VerifyResponse(resp, body, nonce, d.ctl); err != nil { |
| 315 | return nil, fmt.Errorf("GET /v1/vms answer does not verify: %w", err) |
| 316 | } |
| 317 | if resp.StatusCode != http.StatusOK { |
| 318 | return nil, fmt.Errorf("GET /v1/vms = %d", resp.StatusCode) |
| 319 | } |
| 320 | var list hostedwire.VMListResponse |
| 321 | if err := hostedwire.DecodeStrict(bytes.NewReader(body), &list); err != nil { |
| 322 | return nil, fmt.Errorf("GET /v1/vms body: %w", err) |
| 323 | } |
| 324 | return list.VMs, nil |
| 325 | } |
| 326 | |