package hostedctl import ( "context" "crypto/rand" "crypto/sha256" "database/sql" "encoding/binary" "encoding/hex" "encoding/json" "errors" "fmt" "math" "strings" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) var ( // ErrDisabled: launches are off (EQUIPO_HOSTED_ENABLED is not 1). ErrDisabled = errors.New("hostedctl: hosted launches are disabled") // ErrForbidden: the verified key's role may not make this call. ErrForbidden = errors.New("hostedctl: this key may not do that") // ErrImageNotAllowed: the image digest is not in Config.Images. ErrImageNotAllowed = errors.New("hostedctl: image is not in the allowlist") // ErrReplacementLive: the attempt named in Replaces is unknown, belongs // to another key, or has no stop proof yet. ErrReplacementLive = errors.New("hostedctl: replaced attempt is not proven stopped") // ErrProviderLaunch: the provider's launch call failed in a way none of // the isolatedjob sentinels names. The provider's own text is dropped, // as it might echo the request and with it the instance code. ErrProviderLaunch = errors.New("hostedctl: provider launch failed") ) // DrainBefore and StopBefore place a job's drain and stop times before its // deadline (spec ยง3: draining at 7 h 15 min and a forced stop at 7 h 50 min // of an 8 hour lifetime). const ( DrainBefore = 45 * time.Minute StopBefore = 10 * time.Minute ) // maxNameLen bounds TaskID and Account. Controller policy (ruling R16): the // two IDs are written into audit rows and alerts, so they are kept short and // printable. const maxNameLen = 128 // launchIDLen is the length of a launch ID: 128 random bits in hex. const launchIDLen = 32 // purposeTask is jobs.purpose for a launch that runs a task attempt. const purposeTask = "task" // Audit actions written by Launch and Replay. const ( actionLaunchRefused = "launch_refused" actionLaunchIntent = "launch_intent" actionLaunchRepeated = "launch_repeated" actionLaunchDeferred = "launch_deferred" actionLaunchStarted = "launch_started" actionLaunchThrottled = "launch_throttled" actionLaunchFailed = "launch_failed" actionLaunchAbandoned = "launch_abandoned" actionReplayStarted = "replay_started" actionReplayThrottled = "replay_throttled" actionReplayFailed = "replay_failed" actionReplayAbandoned = "replay_abandoned" actionVMAfterAbandon = "vm_after_abandon" providerFailureReason = "provider error; intent kept for replay" providerThrottleReason = "provider throttled; intent kept for replay" reasonConfigChanged = "config_changed" ) // AlertConfigChanged: a launch intent was abandoned because the provider // settings it was saved with changed (ruling R29). const AlertConfigChanged = "config_changed" // LaunchRequest asks for one VM for one task attempt. InstanceCode is a // secret: it goes into the VM's bootstrap and the saved spec, and nowhere // else. type LaunchRequest struct { AttemptID, TaskID, Account, Replaces string Image isolatedjob.ImageDigest Size isolatedjob.Size MaxLifetime time.Duration InstanceCode string } // JobView is the controller's view of one attempt. The *In fields count down // in controller time from the moment the view was read, and are zero once // passed. type JobView struct { AttemptID, LaunchID, State string VMRef isolatedjob.Ref Epoch int64 DeadlineIn, DrainIn, StopIn time.Duration } // Deadlines returns a job's deadline (launched plus lifetime), its drain // time (DrainBefore the deadline) and its stop time (StopBefore the // deadline). Drain and stop are never before launched; a negative lifetime // counts as zero and the deadline saturates rather than overflow. func Deadlines(launched T, lifetime time.Duration) (deadline, drain, stop T) { lifetime = max(lifetime, 0) deadline = launched + T(lifetime) if deadline < launched { deadline = T(math.MaxInt64) } drain = max(launched, deadline-T(DrainBefore)) stop = max(launched, deadline-T(StopBefore)) return deadline, drain, stop } // Launch saves a launch intent for q and then asks the provider for the VM. // // In order it refuses: launches switched off (ErrDisabled); a key without // RoleInstance (ErrForbidden); a malformed request (isolatedjob.ErrInvalid, // or ErrBootstrapTooLarge; see checkRequest for the controller's own // limits); an image outside Config.Images (ErrImageNotAllowed); no passing // network audit begun within AuditMaxAge (ErrNetworkAudit). Each refusal is // audited and creates nothing. // // Transaction 1 then looks up q.AttemptID. A job saved for the same request // by the same key is returned as it stands, with no provider call; a // different request, or another key, gives isolatedjob.ErrConflict. A new // attempt naming Replaces needs that attempt to exist, belong to by and // carry stop proof (ErrReplacementLive). Otherwise transaction 1 draws a // fresh launch ID, builds the exact LaunchSpec and saves it as a JobWaiting // intent with deadlines from the current controller time. // // After that commit, dispatch re-reads the intent and re-checks every gate // that guards VM creation, as Replay does, immediately before the provider // call: a stop asked for or the stop time reached abandons the intent // (JobAbandoned); launches off, the image dropped or no fresh passing audit // leaves it JobWaiting, and Launch returns that view with a nil error. Time // spent queueing for transaction 1 can let the audit go stale, so the check // before it is not enough. // // The provider call runs outside any transaction, with the attempt ID as // its client token. On success transaction 2 saves the Ref and JobStarting. // A throttle returns the JobWaiting view and a nil error: Replay launches it // once the provider allows. Any other provider error, a lost reply included, // returns a zero view and a fixed error (see providerError); the intent // stays JobWaiting for Replay, which re-sends the same spec, so a VM the lost // call created is found again rather than doubled. func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, q LaunchRequest) (JobView, error) { if !c.cfg.Enabled { return c.refuse(ctx, by, q, ErrDisabled) } if by == "" || key.Role != hostedwire.RoleInstance { return c.refuse(ctx, by, q, fmt.Errorf("%w: launch needs an instance key", ErrForbidden)) } if err := c.checkRequest(q); err != nil { return c.refuse(ctx, by, q, err) } if !c.cfg.Images[q.Image] { return c.refuse(ctx, by, q, fmt.Errorf("%w: %s", ErrImageNotAllowed, q.Image)) } if err := c.audit.check(c.store.Clock().Now()); err != nil { return c.refuse(ctx, by, q, err) } view, created, err := c.saveIntent(ctx, by, q) if err != nil || !created { return view, err } view, gate, err := c.dispatch(ctx, by, q.AttemptID, false) if gate != nil { aerr := c.store.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Actor: by, Account: q.Account, Task: q.TaskID, Attempt: q.AttemptID, Action: actionLaunchDeferred, Reason: "intent kept for replay: " + gate.Error(), At: c.store.Clock().Now()}) }) if aerr != nil { return JobView{}, aerr } } return view, err } // refuse audits a refusal that came before any transaction, in a short // transaction of its own, and returns err. The row names the request's // attempt, task and account, never its instance code. func (c *Controller) refuse(ctx context.Context, by hostedwire.KeyID, q LaunchRequest, err error) (JobView, error) { aerr := c.store.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Actor: by, Account: q.Account, Task: q.TaskID, Attempt: q.AttemptID, Action: actionLaunchRefused, Reason: err.Error(), At: c.store.Clock().Now()}) }) if aerr != nil { return JobView{}, errors.Join(err, aerr) } return JobView{}, err } // checkRequest checks q's fields, then validates the spec q would give // against the runner's limits. That spec carries a placeholder launch ID of // the real length, so the bootstrap size checked is the size sent; the real // ID is drawn only in transaction 1, for a new intent. // // Two limits are controller policy (ruling R16), beyond what the provider // needs: TaskID and Account must be 1 to maxNameLen printable ASCII // characters, as they appear in audit rows and alerts; and MaxLifetime must // be more than StopBefore, since a shorter one has its stop time at launch // and the reaper would stop it, or Replay abandon it, at once. func (c *Controller) checkRequest(q LaunchRequest) error { switch { case !printableASCII(q.TaskID, maxNameLen): return fmt.Errorf("%w: task id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen) case !printableASCII(q.Account, maxNameLen): return fmt.Errorf("%w: account must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen) case q.Replaces != "" && !printableASCII(q.Replaces, maxNameLen): return fmt.Errorf("%w: replaced attempt id must be printable ASCII", isolatedjob.ErrInvalid) case q.MaxLifetime <= StopBefore: return fmt.Errorf("%w: lifetime %v must be more than %v", isolatedjob.ErrInvalid, q.MaxLifetime, StopBefore) case !printableASCII(q.InstanceCode, math.MaxInt): // The text never repeats the code. return fmt.Errorf("%w: instance code must be one or more printable ASCII characters", isolatedjob.ErrInvalid) } spec, err := buildSpec(q, strings.Repeat("0", launchIDLen)) if err != nil { return err } return spec.Validate(c.runner.Limits()) } // buildSpec is the LaunchSpec for q with launchID in its bootstrap. func buildSpec(q LaunchRequest, launchID string) (isolatedjob.LaunchSpec, error) { boot, err := json.Marshal(hostedwire.Bootstrap{Version: hostedwire.BootstrapVersion, LaunchID: launchID, InstanceCode: q.InstanceCode}) if err != nil { return isolatedjob.LaunchSpec{}, fmt.Errorf("hostedctl: encode bootstrap: %w", err) } return isolatedjob.LaunchSpec{AttemptID: q.AttemptID, Image: q.Image, Size: q.Size, MaxLifetime: q.MaxLifetime, Bootstrap: boot}, nil } // printableASCII reports whether s is 1 to n bytes, each from ' ' to '~'. // The AWS adapter refuses payloads that are not ASCII. func printableASCII(s string, n int) bool { if len(s) == 0 || len(s) > n { return false } for i := 0; i < len(s); i++ { if s[i] < 0x20 || s[i] > 0x7e { return false } } return true } // newLaunchID returns 128 random bits as launchIDLen lower-case hex digits. func newLaunchID() (string, error) { var b [launchIDLen / 2]byte if _, err := rand.Read(b[:]); err != nil { return "", fmt.Errorf("hostedctl: launch id: %w", err) } return hex.EncodeToString(b[:]), nil } // requestHash is the SHA-256, in hex, of a canonical encoding of q and by: // each field as its length (uvarint) and then its bytes, in a fixed order. // It decides whether a repeated launch is the same request. func requestHash(by hostedwire.KeyID, q LaunchRequest) string { h := sha256.New() field := func(s string) { _, _ = h.Write(binary.AppendUvarint(nil, uint64(len(s)))) _, _ = h.Write([]byte(s)) } field("hostedctl launch request v1") field(string(by)) field(q.AttemptID) field(q.TaskID) field(q.Account) field(q.Replaces) field(string(q.Image)) field(string(q.Size)) field(fmt.Sprint(int64(q.MaxLifetime))) field(q.InstanceCode) return hex.EncodeToString(h.Sum(nil)) } // storedSpec is the layout of jobs.spec_json: the exact LaunchSpec sent to // the provider, so a replay re-sends identical bytes. type storedSpec struct { AttemptID string `json:"attempt_id"` Image isolatedjob.ImageDigest `json:"image"` Size isolatedjob.Size `json:"size"` MaxLifetimeNS int64 `json:"max_lifetime_ns"` Bootstrap []byte `json:"bootstrap"` } func encodeSpec(s isolatedjob.LaunchSpec) (string, error) { b, err := json.Marshal(storedSpec{AttemptID: s.AttemptID, Image: s.Image, Size: s.Size, MaxLifetimeNS: int64(s.MaxLifetime), Bootstrap: s.Bootstrap}) if err != nil { return "", fmt.Errorf("hostedctl: encode launch spec: %w", err) } return string(b), nil } // decodeSpec reads a saved spec and checks it is the one for attempt. func decodeSpec(text, attempt string) (isolatedjob.LaunchSpec, error) { var s storedSpec if err := json.Unmarshal([]byte(text), &s); err != nil { return isolatedjob.LaunchSpec{}, fmt.Errorf("hostedctl: saved spec for %s is unreadable", attempt) } if s.AttemptID != attempt { return isolatedjob.LaunchSpec{}, fmt.Errorf("hostedctl: saved spec for %s names attempt %s", attempt, s.AttemptID) } return isolatedjob.LaunchSpec{AttemptID: s.AttemptID, Image: s.Image, Size: s.Size, MaxLifetime: time.Duration(s.MaxLifetimeNS), Bootstrap: s.Bootstrap}, nil } // saveIntent is transaction 1. It returns the existing job's view when the // same request was saved before (created false), or draws a launch ID, // builds the spec, saves the new intent and returns its view (created // true). A conflict or a live replaced attempt is audited, committed, and // returned as the error. func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q LaunchRequest) (JobView, bool, error) { hash := requestHash(by, q) var view JobView var created bool var refusal error err := c.store.Tx(ctx, func(tx *sql.Tx) error { view, created, refusal = JobView{}, false, nil now := c.store.Clock().Now() a := Audit{Actor: by, Account: q.Account, Task: q.TaskID, Attempt: q.AttemptID, At: now} j, found, err := loadJob(ctx, tx, q.AttemptID) if err != nil { return err } if found { if j.specSHA != hash { refusal = fmt.Errorf("%w: attempt %s was asked for with a different request", isolatedjob.ErrConflict, q.AttemptID) a.Action, a.Reason = actionLaunchRefused, refusal.Error() return appendAudit(tx, a) } view = j.view(now) a.Action, a.Reason = actionLaunchRepeated, "same request again; job is "+j.state return appendAudit(tx, a) } if q.Replaces != "" { if err := checkReplaces(ctx, tx, by, q.Replaces); err != nil { if !errors.Is(err, ErrReplacementLive) { return err // a lookup error denies and saves nothing } refusal = err a.Action, a.Reason = actionLaunchRefused, err.Error() return appendAudit(tx, a) } } launchID, err := newLaunchID() if err != nil { return err } spec, err := buildSpec(q, launchID) if err != nil { return err } specJSON, err := encodeSpec(spec) if err != nil { return err } deadline, drain, stop := Deadlines(now, spec.MaxLifetime) replaces := sql.NullString{String: q.Replaces, Valid: q.Replaces != ""} if _, err := tx.ExecContext(ctx, `INSERT INTO jobs (attempt_id, launch_id, task_id, account_id, actor_key, purpose, replaces_attempt, spec_json, spec_sha256, provider_fingerprint, state, launched_t, deadline_t, drain_t, stop_t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, q.AttemptID, launchID, q.TaskID, q.Account, string(by), purposeTask, replaces, specJSON, hash, c.cfg.ProviderFingerprint(spec.Image, spec.Size), JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil { return fmt.Errorf("hostedctl: save launch intent: %w", err) } a.Action = actionLaunchIntent a.Reason = fmt.Sprintf("intent saved: launch %s, image %s, size %s, lifetime %v", launchID, spec.Image, spec.Size, spec.MaxLifetime) if err := appendAudit(tx, a); err != nil { return err } view = JobView{AttemptID: q.AttemptID, LaunchID: launchID, State: JobWaiting, DeadlineIn: until(now, deadline), DrainIn: until(now, drain), StopIn: until(now, stop)} created = true return nil }) if err != nil { return JobView{}, false, err } if refusal != nil { return JobView{}, false, refusal } return view, created, nil } // checkReplaces returns ErrReplacementLive unless attempt exists, was // launched by by and carries stop proof. An unknown attempt and another // key's attempt get the same message, so the refusal tells nobody whether // another key's attempt exists. func checkReplaces(ctx context.Context, tx *sql.Tx, by hostedwire.KeyID, attempt string) error { r, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } if !found || r.actor != string(by) { return fmt.Errorf("%w: %s is not an attempt of this key", ErrReplacementLive, attempt) } if !r.stopProof.Valid { return fmt.Errorf("%w: %s has no stop proof", ErrReplacementLive, attempt) } return nil } // dispatch sends attempt's saved spec to the provider if, read again just // now, it is still a waiting intent with no Ref and every creation gate // passes. Launch (actor by, replay false) and Replay (actor empty, replay // true) both create VMs only through it. // // In its own transaction it re-reads the row. An intent no longer waiting, // or holding a Ref, is returned as it stands. A stop asked for, or the stop // time reached, marks it JobAbandoned with an audit row; so does a provider // fingerprint other than the one saved with the intent (R29), which also // raises an AlertConfigChanged alert. Then, outside the // transaction and just before the call, it checks the transient gates // (creatable); a failure is returned as gate with the waiting view and no // provider call. Otherwise it records the dispatch marker (markDispatch, // R19), checks the stop time and the transient gates again once the marker // has committed, and only then calls the provider and settles the answer. func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attempt string, replay bool) (view JobView, gate, err error) { // The attempt's lock (R18) is held from the gate check to the settled // answer, so a Stop cannot land between them. defer c.lockAttempt(attempt)() // R23: the ownership lock, taken before the row is read and the gates // are checked and held to the settled answer, so the orphan reaper's // final check cannot run in between (ownershipLock, reaper.go), and a // wait for it never lets a gate that passed go stale before the call. defer c.ownership.rlock()() var spec isolatedjob.LaunchSpec var stopAt T // the intent's stop time; the attempt lock keeps it still ready, changed := false, false err = c.store.Tx(ctx, func(tx *sql.Tx) error { ready, changed = false, false j, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } if !found { return fmt.Errorf("hostedctl: launch intent %s is missing", attempt) } now := c.store.Clock().Now() if j.state != JobWaiting || j.ref.Valid { view = j.view(now) return nil } if spec, err = decodeSpec(j.specJSON, attempt); err != nil { return err } reason := abandonReason(j, now) if fp := c.cfg.ProviderFingerprint(spec.Image, spec.Size); reason == "" && fp != j.fingerprint { reason, changed = fmt.Sprintf("%s: the provider settings for image %s at size %s changed since the intent was saved (%q, now %q)", reasonConfigChanged, spec.Image, spec.Size, j.fingerprint, fp), true } if reason != "" { view, err = abandonIntent(ctx, tx, actor, j, replay, reason, now) return err } view, stopAt = j.view(now), T(j.stopT) ready = true return nil }) if err != nil { return JobView{}, nil, err } if changed { return view, nil, c.alertConfigChanged(ctx, attempt, view) } if !ready { return view, nil, nil } if gate := c.creatable(spec.Image, c.store.Clock().Now()); gate != nil { return view, gate, nil } if c.beforeMark != nil { c.beforeMark() } if err := c.markDispatch(ctx, attempt); err != nil { return JobView{}, nil, err } // The marker's transaction may have queued for the store while the stop // time passed or the audit failed or went stale, so both are checked // again once it commits, in memory, immediately before the call. if now := c.store.Clock().Now(); now >= stopAt { view, err = c.abandonDue(ctx, actor, attempt, replay) return view, nil, err } else if gate := c.creatable(spec.Image, now); gate != nil { return view, gate, nil } // R21: c.runner bounds the call by ProviderLaunchTimeout, so no launch // call this process makes can outlive the Ref-less proof fence // (ReflessProofDelay) that starts at its dispatch. ref, perr := c.runner.Launch(ctx, spec) // Record the answer even if the caller has gone: a VM may now exist. view, err = c.settle(context.WithoutCancel(ctx), actor, attempt, ref, perr, replay) return view, nil, err } // providerError turns a provider launch error into a fixed error for // attempt. It keeps the isolatedjob sentinel the error matches, so // errors.Is still works, and drops the provider's own text, which might // echo the request and with it the instance code. An error matching none // becomes ErrProviderLaunch. func providerError(attempt string, err error) error { for _, s := range []error{ isolatedjob.ErrThrottled, isolatedjob.ErrConflict, isolatedjob.ErrInvalid, isolatedjob.ErrBootstrapTooLarge, isolatedjob.ErrNotFound, isolatedjob.ErrIncomplete, context.Canceled, context.DeadlineExceeded, } { if errors.Is(err, s) { return fmt.Errorf("hostedctl: launch %s: provider refused: %w", attempt, s) } } return fmt.Errorf("hostedctl: launch %s: %w", attempt, ErrProviderLaunch) } // settle records what the provider said about a launch of attempt. actor is // the key that asked, or empty for Replay. A Ref is saved by transaction 2 // (saveRef). A throttle is audited and returns the waiting view with a nil // error. Any other error is audited with a fixed reason and returned as // providerError gives it. func (c *Controller) settle(ctx context.Context, actor hostedwire.KeyID, attempt string, ref isolatedjob.Ref, perr error, replay bool) (JobView, error) { if perr == nil && ref == "" { perr = errors.New("provider returned no VM ref") } if perr == nil { return c.saveRef(ctx, actor, attempt, ref, replay) } throttled := errors.Is(perr, isolatedjob.ErrThrottled) fixed := providerError(attempt, perr) action, reason := actionLaunchFailed, providerFailureReason switch { case throttled && replay: action, reason = actionReplayThrottled, providerThrottleReason case throttled: action, reason = actionLaunchThrottled, providerThrottleReason case replay: action = actionReplayFailed } var view JobView err := c.store.Tx(ctx, func(tx *sql.Tx) error { now := c.store.Clock().Now() j, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } if !found { return fmt.Errorf("hostedctl: launch intent %s is missing", attempt) } view = j.view(now) return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: attempt, Action: action, Reason: reason, At: now}) }) if throttled && err == nil { return view, nil } return JobView{}, errors.Join(fixed, err) } // saveRef is transaction 2: it saves ref for a waiting intent and moves it // to JobStarting. A ref already saved, by a concurrent call for the same // attempt, is left as it is. An intent abandoned while the call was in // flight keeps no ref: the VM is audited and left for the orphan reaper, // which finds no job owning it. func (c *Controller) saveRef(ctx context.Context, actor hostedwire.KeyID, attempt string, ref isolatedjob.Ref, replay bool) (JobView, error) { var view JobView err := c.store.Tx(ctx, func(tx *sql.Tx) error { now := c.store.Clock().Now() j, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } if !found { return fmt.Errorf("hostedctl: launch intent %s is missing", attempt) } a := Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: attempt, At: now} switch { case j.ref.Valid && j.ref.String == string(ref): view = j.view(now) return nil case j.ref.Valid: return fmt.Errorf("hostedctl: attempt %s: provider returned VM %s but the job holds %s", attempt, ref, j.ref.String) case j.state == JobAbandoned: a.Action = actionVMAfterAbandon a.Reason = fmt.Sprintf("provider created VM %s after the intent was abandoned; left for the orphan reaper", ref) view = j.view(now) return appendAudit(tx, a) case j.state != JobWaiting: return fmt.Errorf("hostedctl: attempt %s is %s; VM %s not recorded", attempt, j.state, ref) } res, err := tx.ExecContext(ctx, `UPDATE jobs SET vm_ref = ?, state = ?, revision = revision + 1 WHERE attempt_id = ? AND vm_ref IS NULL AND state = ?`, string(ref), JobStarting, attempt, JobWaiting) if err != nil { return fmt.Errorf("hostedctl: save VM ref: %w", err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: save VM ref for %s: %d rows (%v)", attempt, n, err) } a.Action, a.Reason = actionLaunchStarted, fmt.Sprintf("provider started VM %s", ref) if replay { a.Action = actionReplayStarted } if err := appendAudit(tx, a); err != nil { return err } j.ref, j.state = sql.NullString{String: string(ref), Valid: true}, JobStarting view = j.view(now) return nil }) if err != nil { return JobView{}, err } return view, nil } // Replay launches every intent that has no Ref yet, in launch order, each // with its saved spec, through dispatch. Before each provider call the // gates are re-checked: // // - a stop asked for, the intent's stop time reached, or provider // settings changed since it was saved (config_changed, alerted): the // intent is marked JobAbandoned and audited, and never replayed again; // - launches switched off, the image no longer allowed, or no passing // audit begun within AuditMaxAge: the intent stays JobWaiting for a later // pass, with no audit row, as nothing changed. // // A gate that fails makes no provider call. A throttle leaves the intent // waiting and is not an error. Replay returns the other failures joined; one // intent's failure does not stop the others. func (c *Controller) Replay(ctx context.Context) error { var pending []string err := c.store.Tx(ctx, func(tx *sql.Tx) error { pending = pending[:0] rows, err := tx.QueryContext(ctx, `SELECT attempt_id FROM jobs WHERE state = ? AND vm_ref IS NULL ORDER BY launched_t, attempt_id`, JobWaiting) if err != nil { return fmt.Errorf("hostedctl: list launch intents: %w", err) } defer rows.Close() for rows.Next() { var id string if err := rows.Scan(&id); err != nil { return fmt.Errorf("hostedctl: list launch intents: %w", err) } pending = append(pending, id) } return rows.Err() }) if err != nil { return err } var errs []error for _, id := range pending { if err := ctx.Err(); err != nil { errs = append(errs, err) break } if _, _, err := c.dispatch(ctx, "", id, true); err != nil { errs = append(errs, err) } } return errors.Join(errs...) } // abandonIntent marks waiting intent j JobAbandoned inside tx, with an audit // row giving reason, and returns its view. It is never launched again; a VM // a lost reply made for it is an orphan. func abandonIntent(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jobRow, replay bool, reason string, now T) (JobView, error) { res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 WHERE attempt_id = ? AND state = ? AND vm_ref IS NULL`, JobAbandoned, j.attempt, JobWaiting) if err != nil { return JobView{}, fmt.Errorf("hostedctl: abandon %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return JobView{}, fmt.Errorf("hostedctl: abandon %s: %d rows (%v)", j.attempt, n, err) } action := actionLaunchAbandoned if replay { action = actionReplayAbandoned } j.state = JobAbandoned return j.view(now), appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt, Action: action, Reason: reason, At: now}) } // abandonDue abandons attempt's waiting intent, in a transaction of its own, // once dispatch finds its stop time come after the dispatch marker. An // intent no longer waiting is returned as it stands. func (c *Controller) abandonDue(ctx context.Context, actor hostedwire.KeyID, attempt string, replay bool) (JobView, error) { var view JobView err := c.store.Tx(ctx, func(tx *sql.Tx) error { j, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } if !found { return fmt.Errorf("hostedctl: launch intent %s is missing", attempt) } now := c.store.Clock().Now() reason := abandonReason(j, now) if j.state != JobWaiting || j.ref.Valid || reason == "" { view = j.view(now) return nil } view, err = abandonIntent(ctx, tx, actor, j, replay, reason+"; found after the dispatch was recorded", now) return err }) if err != nil { return JobView{}, err } return view, nil } // alertConfigChanged sends the AlertConfigChanged alert for an intent // abandoned because the provider settings changed, even if the caller has // gone. The abandonment is already committed and audited. func (c *Controller) alertConfigChanged(ctx context.Context, attempt string, v JobView) error { err := c.alerter.Alert(context.WithoutCancel(ctx), Alert{Kind: AlertConfigChanged, At: c.store.Clock().Now(), Detail: fmt.Sprintf( "launch intent %s (launch %s) was abandoned: the provider settings changed since it was saved; a VM its lost reply made is reaped as an orphan", attempt, v.LaunchID)}) if err != nil { return fmt.Errorf("hostedctl: deliver %s alert for %s: %w", AlertConfigChanged, attempt, err) } return nil } // abandonReason returns why a waiting intent must never be launched, or "" // when nothing stops it: a stop was asked for, or its stop time has come. func abandonReason(j jobRow, now T) string { if j.stopRequested.Valid { return "stop asked for before the VM was launched" } if now >= T(j.stopT) { return fmt.Sprintf("stop time passed before the VM was launched (%v after it)", time.Duration(now-T(j.stopT))) } return "" } // creatable checks the transient creation gates: launches on, the image // still allowed, and a passing audit begun within AuditMaxAge. func (c *Controller) creatable(img isolatedjob.ImageDigest, now T) error { if !c.cfg.Enabled { return ErrDisabled } if !c.cfg.Images[img] { return fmt.Errorf("%w: %s", ErrImageNotAllowed, img) } return c.audit.check(now) } // jobRow is the part of a jobs row that launches read. type jobRow struct { attempt, launchID, task, account, actor, state, specJSON, specSHA string fingerprint string // provider_fingerprint ref sql.NullString launchedT, deadlineT, drainT, stopT, epoch int64 stopRequested sql.NullInt64 stopProof sql.NullString } // loadJob reads attempt's row inside tx. found is false when there is none. func loadJob(ctx context.Context, tx *sql.Tx, attempt string) (jobRow, bool, error) { var j jobRow err := tx.QueryRowContext(ctx, `SELECT attempt_id, launch_id, task_id, account_id, actor_key, state, spec_json, spec_sha256, provider_fingerprint, vm_ref, launched_t, deadline_t, drain_t, stop_t, epoch, stop_requested_t, stop_proof_json FROM jobs WHERE attempt_id = ?`, attempt).Scan(&j.attempt, &j.launchID, &j.task, &j.account, &j.actor, &j.state, &j.specJSON, &j.specSHA, &j.fingerprint, &j.ref, &j.launchedT, &j.deadlineT, &j.drainT, &j.stopT, &j.epoch, &j.stopRequested, &j.stopProof) switch { case errors.Is(err, sql.ErrNoRows): return jobRow{}, false, nil case err != nil: return jobRow{}, false, fmt.Errorf("hostedctl: read job %s: %w", attempt, err) } return j, true, nil } // view is the JobView of j at controller time now. func (j jobRow) view(now T) JobView { return JobView{ AttemptID: j.attempt, LaunchID: j.launchID, State: j.state, VMRef: isolatedjob.Ref(j.ref.String), Epoch: j.epoch, DeadlineIn: until(now, T(j.deadlineT)), DrainIn: until(now, T(j.drainT)), StopIn: until(now, T(j.stopT)), } } // until is how long from now to at, or zero once at has passed. func until(now, at T) time.Duration { if at <= now { return 0 } return time.Duration(at - now) }