| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/ed25519" |
| 7 | "database/sql" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "net/http" |
| 13 | "net/url" |
| 14 | "strings" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 18 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 19 | ) |
| 20 | |
| 21 | // HandlerConfig is what the controller's HTTP API needs besides the |
| 22 | // controller. Every field but Metrics is required. |
| 23 | type HandlerConfig struct { |
| 24 | // Keys are the verify keys and their roles. Each controller has keys of |
| 25 | // its own and keeps each key under one key ID for good: the key ID is not |
| 26 | // signed, so it must never move to another key or another controller. |
| 27 | Keys map[hostedwire.KeyID]hostedwire.VerifyKey |
| 28 | // Signing is the controller's key; every verified request's response is |
| 29 | // signed with it. |
| 30 | Signing ed25519.PrivateKey |
| 31 | // Wall is the wall clock a request's timestamp is checked against. |
| 32 | Wall func() time.Time |
| 33 | // Metrics, when set, counts launches and refusals. |
| 34 | Metrics *Metrics |
| 35 | } |
| 36 | |
| 37 | // Audit action the handler writes when a key's role may not use a route. The |
| 38 | // controller's methods audit their own refusals. |
| 39 | const actionAPIRefused = "api_refused" |
| 40 | |
| 41 | // Errors of the handler itself, before any controller method runs. |
| 42 | var ( |
| 43 | errNoRoute = errors.New("hostedctl: no such route") |
| 44 | errMethod = errors.New("hostedctl: method not allowed on this route") |
| 45 | errQuery = errors.New("hostedctl: routes take no query") |
| 46 | errRead = errors.New("hostedctl: reading the request body failed") |
| 47 | ) |
| 48 | |
| 49 | // apiError is how one kind of error is answered: its status, a fixed code |
| 50 | // and a fixed message. The error's own text is never sent. |
| 51 | type apiError struct { |
| 52 | err error |
| 53 | status int |
| 54 | code string |
| 55 | msg string |
| 56 | } |
| 57 | |
| 58 | // apiErrors maps errors to responses, first match wins. ErrStoreLost comes |
| 59 | // first, so a refusal whose audit row could not be written reports the lost |
| 60 | // store. ErrProviderLaunch is 502 rather than 500: the controller is well and |
| 61 | // the intent is saved, so the client may read the job again later. |
| 62 | var apiErrors = []apiError{ |
| 63 | {ErrStoreLost, http.StatusServiceUnavailable, "store_lost", "The controller lost its database. Try again later."}, |
| 64 | {hostedwire.ErrTooLarge, http.StatusRequestEntityTooLarge, "too_large", "The request body is too large."}, |
| 65 | {hostedwire.ErrNonceStore, http.StatusServiceUnavailable, "unavailable", "The request could not be checked. Try again later."}, |
| 66 | {hostedwire.ErrNotConfigured, http.StatusInternalServerError, "internal", "The controller failed. Try again later."}, |
| 67 | {hostedwire.ErrSharedKey, http.StatusInternalServerError, "internal", "The controller failed. Try again later."}, |
| 68 | {hostedwire.ErrUnsigned, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| 69 | {hostedwire.ErrMalformed, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| 70 | {hostedwire.ErrUnknownKey, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| 71 | {hostedwire.ErrSkew, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| 72 | {hostedwire.ErrBadSignature, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, |
| 73 | {hostedwire.ErrReplay, http.StatusUnauthorized, "replay", "This request was already used. Sign a new one."}, |
| 74 | {errRead, http.StatusBadRequest, "unreadable", "The request body could not be read."}, |
| 75 | {errQuery, http.StatusBadRequest, "query", "Routes take no query string."}, |
| 76 | {hostedwire.ErrBadJSON, http.StatusBadRequest, "bad_json", "The body is not the JSON object this route takes."}, |
| 77 | {hostedwire.ErrDuration, http.StatusBadRequest, "invalid", "The request has a field out of range."}, |
| 78 | {isolatedjob.ErrBootstrapTooLarge, http.StatusBadRequest, "invalid", "The request has a field out of range."}, |
| 79 | {isolatedjob.ErrInvalid, http.StatusBadRequest, "invalid", "The request has a field out of range."}, |
| 80 | {ErrImageNotAllowed, http.StatusBadRequest, "image_not_allowed", "The image is not in the allowlist."}, |
| 81 | {ErrForbidden, http.StatusForbidden, "forbidden", "This key may not do that."}, |
| 82 | {errNoRoute, http.StatusNotFound, "no_route", "No such route."}, |
| 83 | {isolatedjob.ErrNotFound, http.StatusNotFound, "not_found", "Not found."}, |
| 84 | {errMethod, http.StatusMethodNotAllowed, "method", "This route does not take that method."}, |
| 85 | {ErrStopPending, http.StatusAccepted, "stop_pending", "Stop accepted. The VM is not proven stopped yet; ask again."}, |
| 86 | {ErrGenerationCancelled, http.StatusConflict, "generation_cancelled", "That pause generation is cancelled or not the current one."}, |
| 87 | {ErrNotQuiescent, http.StatusConflict, "not_quiescent", "No quiescent acknowledgement for this pause generation."}, |
| 88 | {ErrResumePending, http.StatusConflict, "resume_pending", "A resume is pending. Retry with its operation ID."}, |
| 89 | {ErrReplacementLive, http.StatusConflict, "replacement_live", "The replaced attempt is not proven stopped."}, |
| 90 | {ErrStateUnknown, http.StatusConflict, "state_unknown", "The provider reports an unknown VM state."}, |
| 91 | {isolatedjob.ErrConflict, http.StatusConflict, "conflict", "The job's state does not allow that."}, |
| 92 | {ErrPastDeadline, http.StatusGone, "past_deadline", "The job's stop time has passed."}, |
| 93 | {isolatedjob.ErrThrottled, http.StatusTooManyRequests, "throttled", "The provider is busy. Try again later."}, |
| 94 | {ErrDisabled, http.StatusServiceUnavailable, "disabled", "Hosted launches are switched off."}, |
| 95 | {ErrNetworkAudit, http.StatusServiceUnavailable, "network_audit", "No network audit has passed recently. Try again later."}, |
| 96 | {ErrProviderLaunch, http.StatusBadGateway, "provider", "The provider call failed. Read the job again later."}, |
| 97 | {isolatedjob.ErrIncomplete, http.StatusBadGateway, "provider", "The provider call failed. Read the job again later."}, |
| 98 | } |
| 99 | |
| 100 | // errInternal answers every error apiErrors does not name. |
| 101 | var errInternal = apiError{status: http.StatusInternalServerError, code: "internal", msg: "The controller failed. Try again later."} |
| 102 | |
| 103 | // ErrorCode is one status and code pair the API may answer a refusal with. |
| 104 | type ErrorCode struct { |
| 105 | Status int |
| 106 | Code string |
| 107 | } |
| 108 | |
| 109 | // ErrorCodes lists every status and code pair of apiErrors and |
| 110 | // errInternal, each once, in table order. It returns a new slice, so |
| 111 | // clients can test their own mapping against the handler's. |
| 112 | func ErrorCodes() []ErrorCode { |
| 113 | var out []ErrorCode |
| 114 | seen := map[ErrorCode]bool{} |
| 115 | for _, a := range append(apiErrors[:len(apiErrors):len(apiErrors)], errInternal) { |
| 116 | ec := ErrorCode{Status: a.status, Code: a.code} |
| 117 | if !seen[ec] { |
| 118 | seen[ec] = true |
| 119 | out = append(out, ec) |
| 120 | } |
| 121 | } |
| 122 | return out |
| 123 | } |
| 124 | |
| 125 | // lookupError returns how err is answered. |
| 126 | func lookupError(err error) apiError { |
| 127 | for _, a := range apiErrors { |
| 128 | if errors.Is(err, a.err) { |
| 129 | return a |
| 130 | } |
| 131 | } |
| 132 | return errInternal |
| 133 | } |
| 134 | |
| 135 | // route is one API route. serve decodes body (already verified) and calls |
| 136 | // the controller; it returns the status and value of a success. |
| 137 | type route struct { |
| 138 | name string // for metrics and audit rows |
| 139 | method string |
| 140 | role hostedwire.Role |
| 141 | serve func(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) |
| 142 | } |
| 143 | |
| 144 | // jobActions are the POST routes under /v1/jobs/{attempt}/. |
| 145 | var jobActions = map[string]route{ |
| 146 | "stop": {"stop", http.MethodPost, hostedwire.RoleInstance, serveStop}, |
| 147 | "drain": {"drain", http.MethodPost, hostedwire.RoleInstance, serveDrain}, |
| 148 | "quiescent": {"quiescent", http.MethodPost, hostedwire.RoleInstance, serveQuiescent}, |
| 149 | "suspend": {"suspend", http.MethodPost, hostedwire.RoleInstance, serveSuspend}, |
| 150 | "reopen": {"reopen", http.MethodPost, hostedwire.RoleInstance, serveReopen}, |
| 151 | "resume": {"resume", http.MethodPost, hostedwire.RoleInstance, serveResume}, |
| 152 | } |
| 153 | |
| 154 | var ( |
| 155 | routeLaunch = route{"launch", http.MethodPost, hostedwire.RoleInstance, serveLaunch} |
| 156 | routeGet = route{"get", http.MethodGet, hostedwire.RoleInstance, serveGet} |
| 157 | routeVMs = route{"vms", http.MethodGet, hostedwire.RoleOperator, serveVMs} |
| 158 | ) |
| 159 | |
| 160 | // matchRoute finds r's route and the attempt its path names. Path segments |
| 161 | // are unescaped one by one, so an attempt ID may hold any character. |
| 162 | func matchRoute(r *http.Request) (route, string, error) { |
| 163 | seg := strings.Split(r.URL.EscapedPath(), "/") |
| 164 | var rt route |
| 165 | var attempt string |
| 166 | switch { |
| 167 | case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs": |
| 168 | rt = routeLaunch |
| 169 | case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "vms": |
| 170 | rt = routeVMs |
| 171 | case len(seg) == 4 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "": |
| 172 | rt, attempt = routeGet, seg[3] |
| 173 | case len(seg) == 5 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "": |
| 174 | a, ok := jobActions[seg[4]] |
| 175 | if !ok { |
| 176 | return route{}, "", errNoRoute |
| 177 | } |
| 178 | rt, attempt = a, seg[3] |
| 179 | default: |
| 180 | return route{}, "", errNoRoute |
| 181 | } |
| 182 | if attempt != "" { |
| 183 | var err error |
| 184 | if attempt, err = url.PathUnescape(attempt); err != nil { |
| 185 | return route{}, "", errNoRoute |
| 186 | } |
| 187 | } |
| 188 | if r.Method != rt.method { |
| 189 | return rt, attempt, errMethod |
| 190 | } |
| 191 | if r.URL.RawQuery != "" || r.URL.ForceQuery { |
| 192 | return rt, attempt, errQuery |
| 193 | } |
| 194 | return rt, attempt, nil |
| 195 | } |
| 196 | |
| 197 | // Handler returns the controller's HTTP API. It refuses a config with no |
| 198 | // keys, a key of the wrong length or with an unknown role, one public key |
| 199 | // under two key IDs, or a signing key of the wrong length. |
| 200 | // |
| 201 | // Each request goes through, in order: |
| 202 | // |
| 203 | // 1. Read the body, at most hostedwire.MaxBody+1 bytes; more is 413. |
| 204 | // 2. Verify the signature over exactly those bytes, which also records the |
| 205 | // nonce in the store (Store.Remember) so a replay is refused. |
| 206 | // 3. Match the route: an unknown path is 404, another method 405, a query |
| 207 | // 400. |
| 208 | // 4. Check the key's role against the route's; a mismatch is 403 with an |
| 209 | // api_refused audit row. |
| 210 | // 5. Decode the same bytes with hostedwire.DecodeStrict (a GET takes an |
| 211 | // empty body), then call the controller, which checks that the key |
| 212 | // created the attempt and audits its own refusals. |
| 213 | // |
| 214 | // A request with no valid signature (step 1, or a step 2 failure before the |
| 215 | // signature verified: missing or malformed headers, unknown key, skew, bad |
| 216 | // signature) is answered unsigned with a fixed body. Every other response, |
| 217 | // refusals included, is signed with hostedwire.SignResponse bound to the |
| 218 | // request's nonce; that covers a replay and a nonce-store failure, which |
| 219 | // come after the signature verified (ruling R25). For HEAD the signature |
| 220 | // covers the empty body actually sent. Every error is answered from apiErrors with a |
| 221 | // fixed code and message, never the error's own text. |
| 222 | func (c *Controller) Handler(hc HandlerConfig) (http.Handler, error) { |
| 223 | if err := CheckVerifyKeys(hc.Keys); err != nil { |
| 224 | return nil, err |
| 225 | } |
| 226 | if len(hc.Signing) != ed25519.PrivateKeySize { |
| 227 | return nil, errors.New("hostedctl: the signing key has the wrong length") |
| 228 | } |
| 229 | if hc.Wall == nil { |
| 230 | return nil, errors.New("hostedctl: the API needs a wall clock") |
| 231 | } |
| 232 | keys := make(map[hostedwire.KeyID]hostedwire.VerifyKey, len(hc.Keys)) |
| 233 | for id, k := range hc.Keys { |
| 234 | keys[id] = hostedwire.VerifyKey{Public: bytes.Clone(k.Public), Role: k.Role} |
| 235 | } |
| 236 | return &apiHandler{ |
| 237 | c: c, |
| 238 | v: &hostedwire.Verifier{Keys: keys, Nonces: c.store, Now: hc.Wall}, |
| 239 | sign: bytes.Clone(hc.Signing), |
| 240 | m: hc.Metrics, |
| 241 | }, nil |
| 242 | } |
| 243 | |
| 244 | // CheckVerifyKeys refuses an empty key table, a key ID or public key of the |
| 245 | // wrong form, a role other than instance or operator, and one public key |
| 246 | // under two key IDs. |
| 247 | func CheckVerifyKeys(keys map[hostedwire.KeyID]hostedwire.VerifyKey) error { |
| 248 | if len(keys) == 0 { |
| 249 | return errors.New("hostedctl: no verify keys") |
| 250 | } |
| 251 | seen := map[string]hostedwire.KeyID{} |
| 252 | for id, k := range keys { |
| 253 | if !validKeyID(string(id)) { |
| 254 | return fmt.Errorf("hostedctl: key ID %q must be 1 to 64 characters of A-Z, a-z, 0-9, '.', '_' or '-'", id) |
| 255 | } |
| 256 | if len(k.Public) != ed25519.PublicKeySize { |
| 257 | return fmt.Errorf("hostedctl: public key of %s has the wrong length", id) |
| 258 | } |
| 259 | if k.Role != hostedwire.RoleInstance && k.Role != hostedwire.RoleOperator { |
| 260 | return fmt.Errorf("hostedctl: key %s has role %q; want instance or operator", id, k.Role) |
| 261 | } |
| 262 | if other, dup := seen[string(k.Public)]; dup { |
| 263 | return fmt.Errorf("hostedctl: %w: %s and %s", hostedwire.ErrSharedKey, other, id) |
| 264 | } |
| 265 | seen[string(k.Public)] = id |
| 266 | } |
| 267 | return nil |
| 268 | } |
| 269 | |
| 270 | // validKeyID matches hostedwire's key ID rule: 1 to 64 characters of |
| 271 | // [A-Za-z0-9._-]. |
| 272 | func validKeyID(s string) bool { |
| 273 | if len(s) < 1 || len(s) > 64 { |
| 274 | return false |
| 275 | } |
| 276 | for i := 0; i < len(s); i++ { |
| 277 | c := s[i] |
| 278 | if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-') { |
| 279 | return false |
| 280 | } |
| 281 | } |
| 282 | return true |
| 283 | } |
| 284 | |
| 285 | type apiHandler struct { |
| 286 | c *Controller |
| 287 | v *hostedwire.Verifier |
| 288 | sign ed25519.PrivateKey |
| 289 | m *Metrics |
| 290 | } |
| 291 | |
| 292 | func (h *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 293 | body, err := io.ReadAll(io.LimitReader(r.Body, hostedwire.MaxBody+1)) |
| 294 | switch { |
| 295 | case err != nil: |
| 296 | err = errRead |
| 297 | case len(body) > hostedwire.MaxBody: |
| 298 | err = hostedwire.ErrTooLarge |
| 299 | } |
| 300 | var by hostedwire.KeyID |
| 301 | var key hostedwire.VerifyKey |
| 302 | if err == nil { |
| 303 | by, key, err = h.v.Verify(r, body) |
| 304 | } |
| 305 | if err != nil { |
| 306 | a := lookupError(err) |
| 307 | h.m.apiError("unverified", a.code) |
| 308 | h.write(w, r, a.status, errorBody(a), signedNonce(r, err)) |
| 309 | return |
| 310 | } |
| 311 | nonce := headerValue(r.Header, hostedwire.HeaderNonce) |
| 312 | ctx := r.Context() |
| 313 | |
| 314 | rt, attempt, err := matchRoute(r) |
| 315 | switch { |
| 316 | case err != nil: |
| 317 | case key.Role != rt.role: |
| 318 | err = h.refuseRole(ctx, by, key.Role, rt, attempt) |
| 319 | case rt.method == http.MethodGet && len(body) != 0: |
| 320 | err = fmt.Errorf("%w: a GET takes no body", hostedwire.ErrBadJSON) |
| 321 | } |
| 322 | var out any |
| 323 | if err == nil { |
| 324 | out, err = rt.serve(ctx, h.c, by, key, attempt, body) |
| 325 | } |
| 326 | name := rt.name |
| 327 | if name == "" { |
| 328 | name = "none" |
| 329 | } |
| 330 | if err != nil { |
| 331 | a := lookupError(err) |
| 332 | h.m.apiError(name, a.code) |
| 333 | if rt.name == routeLaunch.name { |
| 334 | h.m.launch(a.code) |
| 335 | } |
| 336 | h.write(w, r, a.status, errorBody(a), nonce) |
| 337 | return |
| 338 | } |
| 339 | resp, err := json.Marshal(out) |
| 340 | if err != nil { |
| 341 | h.m.apiError(name, errInternal.code) |
| 342 | h.write(w, r, errInternal.status, errorBody(errInternal), nonce) |
| 343 | return |
| 344 | } |
| 345 | if v, ok := out.(hostedwire.JobView); ok && rt.name == routeLaunch.name { |
| 346 | h.m.launch(v.State) |
| 347 | } |
| 348 | h.write(w, r, http.StatusOK, resp, nonce) |
| 349 | } |
| 350 | |
| 351 | // signedNonce returns the nonce to sign a verification failure for, or "" |
| 352 | // to leave it unsigned. Verify checks the signature before it records the |
| 353 | // nonce, so a replay or a nonce-store failure comes from a request whose |
| 354 | // signature verified (ruling R25): its refusal is signed, bound to its |
| 355 | // nonce. Every other failure has no valid signature and goes unsigned. |
| 356 | func signedNonce(r *http.Request, err error) string { |
| 357 | if errors.Is(err, hostedwire.ErrReplay) || errors.Is(err, hostedwire.ErrNonceStore) { |
| 358 | return headerValue(r.Header, hostedwire.HeaderNonce) |
| 359 | } |
| 360 | return "" |
| 361 | } |
| 362 | |
| 363 | // write sends body with status, signed for nonce unless nonce is empty. A |
| 364 | // HEAD response carries no body (HTTP forbids one, and Go drops it), so for |
| 365 | // HEAD the signature covers the empty body the client receives, with the |
| 366 | // status unchanged. |
| 367 | func (h *apiHandler) write(w http.ResponseWriter, r *http.Request, status int, body []byte, nonce string) { |
| 368 | if r.Method == http.MethodHead { |
| 369 | body = nil |
| 370 | } |
| 371 | hdr := w.Header() |
| 372 | hdr.Set("Content-Type", "application/json") |
| 373 | hdr.Set("Cache-Control", "no-store") |
| 374 | if nonce != "" { |
| 375 | hostedwire.SignResponse(hdr, status, nonce, body, h.sign) |
| 376 | } |
| 377 | w.WriteHeader(status) |
| 378 | _, _ = w.Write(body) |
| 379 | } |
| 380 | |
| 381 | func errorBody(a apiError) []byte { |
| 382 | b, _ := json.Marshal(hostedwire.ErrorResponse{Code: a.code, Message: a.msg}) |
| 383 | return b |
| 384 | } |
| 385 | |
| 386 | // headerValue returns the one value of name; Verify has already checked |
| 387 | // there is exactly one, under any spelling of the name. |
| 388 | func headerValue(h http.Header, name string) string { |
| 389 | for k, v := range h { |
| 390 | if strings.EqualFold(k, name) && len(v) == 1 { |
| 391 | return v[0] |
| 392 | } |
| 393 | } |
| 394 | return "" |
| 395 | } |
| 396 | |
| 397 | // refuseRole audits a key whose role may not use rt and returns ErrForbidden |
| 398 | // (joined with the audit's error, if any). |
| 399 | func (h *apiHandler) refuseRole(ctx context.Context, by hostedwire.KeyID, role hostedwire.Role, rt route, attempt string) error { |
| 400 | err := fmt.Errorf("%w: route %s needs the %s role", ErrForbidden, rt.name, rt.role) |
| 401 | if !printableASCII(attempt, maxNameLen) { |
| 402 | attempt = "" |
| 403 | } |
| 404 | aerr := h.c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 405 | return appendAudit(tx, Audit{Actor: by, Attempt: attempt, Action: actionAPIRefused, |
| 406 | Reason: fmt.Sprintf("route %s needs the %s role; the key has %s", rt.name, rt.role, role), At: h.c.store.Clock().Now()}) |
| 407 | }) |
| 408 | return errors.Join(err, aerr) |
| 409 | } |
| 410 | |
| 411 | // decode reads body into v with hostedwire.DecodeStrict: the same bytes the |
| 412 | // signature covers. |
| 413 | func decode(body []byte, v any) error { |
| 414 | return hostedwire.DecodeStrict(bytes.NewReader(body), v) |
| 415 | } |
| 416 | |
| 417 | func serveLaunch(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, _ string, body []byte) (any, error) { |
| 418 | var q hostedwire.LaunchRequest |
| 419 | if err := decode(body, &q); err != nil { |
| 420 | return nil, err |
| 421 | } |
| 422 | life, err := q.MaxLifetime() |
| 423 | if err != nil { |
| 424 | return nil, err |
| 425 | } |
| 426 | v, err := c.Launch(ctx, by, key, LaunchRequest{AttemptID: q.AttemptID, TaskID: q.TaskID, Account: q.Account, |
| 427 | Replaces: q.Replaces, Image: q.Image, Size: q.Size, MaxLifetime: life, InstanceCode: q.InstanceCode}) |
| 428 | if err != nil { |
| 429 | return nil, err |
| 430 | } |
| 431 | return wireView(v), nil |
| 432 | } |
| 433 | |
| 434 | // serveGet: Get takes no key, so the route's role check above is the only |
| 435 | // one; Get itself checks that by created the attempt. |
| 436 | func serveGet(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, attempt string, _ []byte) (any, error) { |
| 437 | v, err := c.Get(ctx, by, attempt) |
| 438 | if err != nil { |
| 439 | return nil, err |
| 440 | } |
| 441 | return wireView(v), nil |
| 442 | } |
| 443 | |
| 444 | func wireView(v JobView) hostedwire.JobView { |
| 445 | return hostedwire.JobView{AttemptID: v.AttemptID, LaunchID: v.LaunchID, State: v.State, VMRef: v.VMRef, Epoch: v.Epoch, |
| 446 | DeadlineInMS: v.DeadlineIn.Milliseconds(), DrainInMS: v.DrainIn.Milliseconds(), StopInMS: v.StopIn.Milliseconds()} |
| 447 | } |
| 448 | |
| 449 | func serveStop(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| 450 | var q hostedwire.StopRequest |
| 451 | if err := decode(body, &q); err != nil { |
| 452 | return nil, err |
| 453 | } |
| 454 | p, err := c.Stop(ctx, by, key, attempt, q.Reason) |
| 455 | if err != nil { |
| 456 | return nil, err |
| 457 | } |
| 458 | return p.wire(), nil |
| 459 | } |
| 460 | |
| 461 | func serveDrain(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| 462 | var q hostedwire.DrainRequest |
| 463 | if err := decode(body, &q); err != nil { |
| 464 | return nil, err |
| 465 | } |
| 466 | g, err := c.Drain(ctx, by, key, attempt) |
| 467 | if err != nil { |
| 468 | return nil, err |
| 469 | } |
| 470 | return hostedwire.DrainResponse{Generation: g}, nil |
| 471 | } |
| 472 | |
| 473 | func serveQuiescent(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| 474 | var q hostedwire.QuiescentRequest |
| 475 | if err := decode(body, &q); err != nil { |
| 476 | return nil, err |
| 477 | } |
| 478 | if err := c.Quiescent(ctx, by, key, attempt, q.Generation); err != nil { |
| 479 | return nil, err |
| 480 | } |
| 481 | return hostedwire.QuiescentResponse(q), nil |
| 482 | } |
| 483 | |
| 484 | func serveSuspend(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| 485 | var q hostedwire.SuspendRequest |
| 486 | if err := decode(body, &q); err != nil { |
| 487 | return nil, err |
| 488 | } |
| 489 | if err := c.Suspend(ctx, by, key, attempt, q.Generation); err != nil { |
| 490 | return nil, err |
| 491 | } |
| 492 | return hostedwire.SuspendResponse(q), nil |
| 493 | } |
| 494 | |
| 495 | func serveReopen(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| 496 | var q hostedwire.ReopenRequest |
| 497 | if err := decode(body, &q); err != nil { |
| 498 | return nil, err |
| 499 | } |
| 500 | if err := c.Reopen(ctx, by, key, attempt, q.Generation); err != nil { |
| 501 | return nil, err |
| 502 | } |
| 503 | return hostedwire.ReopenResponse(q), nil |
| 504 | } |
| 505 | |
| 506 | func serveResume(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { |
| 507 | var q hostedwire.ResumeRequest |
| 508 | if err := decode(body, &q); err != nil { |
| 509 | return nil, err |
| 510 | } |
| 511 | epoch, err := c.Resume(ctx, by, key, attempt, q.OperationID) |
| 512 | if err != nil { |
| 513 | return nil, err |
| 514 | } |
| 515 | return hostedwire.ResumeResponse{Epoch: epoch}, nil |
| 516 | } |
| 517 | |
| 518 | func serveVMs(ctx context.Context, c *Controller, _ hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, _ []byte) (any, error) { |
| 519 | vms, err := c.ListVMs(ctx) |
| 520 | if err != nil { |
| 521 | return nil, err |
| 522 | } |
| 523 | return hostedwire.VMListResponse{VMs: vms}, nil |
| 524 | } |
| 525 | |
| 526 | // ListVMs returns every VM the provider lists, each with the attempt whose |
| 527 | // saved Ref it is, or "" when it is no job's. A VM a launch intent may own |
| 528 | // but has no Ref saved yet shows "". It makes one provider List and changes |
| 529 | // nothing. |
| 530 | func (c *Controller) ListVMs(ctx context.Context) ([]hostedwire.VMView, error) { |
| 531 | vms, err := c.runner.List(ctx) |
| 532 | if err != nil { |
| 533 | return nil, err |
| 534 | } |
| 535 | owners := map[isolatedjob.Ref]string{} |
| 536 | err = c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 537 | rows, err := tx.QueryContext(ctx, `SELECT vm_ref, attempt_id FROM jobs WHERE vm_ref IS NOT NULL`) |
| 538 | if err != nil { |
| 539 | return fmt.Errorf("hostedctl: read job refs: %w", err) |
| 540 | } |
| 541 | defer rows.Close() |
| 542 | for rows.Next() { |
| 543 | var ref, attempt string |
| 544 | if err := rows.Scan(&ref, &attempt); err != nil { |
| 545 | return fmt.Errorf("hostedctl: read job refs: %w", err) |
| 546 | } |
| 547 | owners[isolatedjob.Ref(ref)] = attempt |
| 548 | } |
| 549 | return rows.Err() |
| 550 | }) |
| 551 | if err != nil { |
| 552 | return nil, err |
| 553 | } |
| 554 | out := make([]hostedwire.VMView, 0, len(vms)) |
| 555 | for _, vm := range vms { |
| 556 | v := hostedwire.VMView{VMRef: vm.Ref, State: vm.State, AttemptID: owners[vm.Ref], AgeKnown: vm.AgeKnown} |
| 557 | if vm.AgeKnown { |
| 558 | v.AgeMS = vm.ProviderAge.Milliseconds() |
| 559 | } |
| 560 | out = append(out, v) |
| 561 | } |
| 562 | return out, nil |
| 563 | } |
| 564 | |