package hostedctl import ( "context" "database/sql" "encoding/json" "errors" "fmt" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) var ( // ErrStopPending: the stop is recorded but the VM is not proven stopped // yet: it is still live, the provider has answered not-found only once // (NotFoundConfirm), or the job has no VM Ref and the provider has not // yet been seen to hold no VM for it. Ask again later. ErrStopPending = errors.New("hostedctl: stop asked for; the VM is not proven stopped yet") // ErrStateUnknown: the provider reported a state this package does not // know. It is never proof that the VM has stopped. ErrStateUnknown = errors.New("hostedctl: the provider reports an unknown VM state; no stop proof") ) // NotFoundConfirm is how far apart, in controller time, two not-found // answers from Runner.Get must be before they prove a VM gone. The // provider's Get is eventually consistent, so one not-found proves nothing // (ruling R17). It equals the reaper's interval (Task 13's ReapInterval). const NotFoundConfirm = 60 * time.Second // Stop reasons the controller writes itself. const ( // reasonElapsedUnknown: after a restart the provider gave no age for the // VM, so how long it has lived is unknown and the controller stops it. reasonElapsedUnknown = "elapsed_unknown" // reasonEnded: the VM ended, or the provider forgot it, with no stop // asked for. reasonEnded = "ended" ) // Audit actions written by Get, Stop and Refresh. const ( actionGetRefused = "get_refused" actionStopRefused = "stop_refused" actionStopRequested = "stop_requested" actionStopRepeated = "stop_repeated" actionStopFailed = "stop_failed" actionStopStateUnknown = "stop_state_unknown" actionStopProven = "stop_proven" actionVMNotFound = "vm_not_found" actionRestartRebased = "restart_rebased" ) // StopProof says the provider reported the job's VM terminal, or answered // not-found twice, NotFoundConfirm apart, with the first after the stop // request (or, with no request, after the VM was last seen live). It gates // replacement attempts. // VMRef is empty for a job that never had a Ref, and State is then // isolatedjob.StateStopped. ObservedAt is controller time. type StopProof struct { AttemptID string VMRef isolatedjob.Ref State isolatedjob.State ObservedAt T } func (p StopProof) wire() hostedwire.StopProof { return hostedwire.StopProof{AttemptID: p.AttemptID, VMRef: p.VMRef, State: p.State, ObservedAt: time.Duration(p.ObservedAt)} } // decodeProof reads a stored jobs.stop_proof_json and checks it is for attempt. func decodeProof(text, attempt string) (StopProof, error) { var w hostedwire.StopProof if err := json.Unmarshal([]byte(text), &w); err != nil { return StopProof{}, fmt.Errorf("hostedctl: stored stop proof for %s is unreadable: %w", attempt, err) } if w.AttemptID != attempt { return StopProof{}, fmt.Errorf("hostedctl: stored stop proof for %s names attempt %s", attempt, w.AttemptID) } return StopProof{AttemptID: w.AttemptID, VMRef: w.VMRef, State: w.State, ObservedAt: T(w.ObservedAt)}, nil } // notCreator is the refusal for a key that did not launch attempt. An // unknown attempt gets the same text, so a refusal never tells a key whether // another key's attempt exists. func notCreator(attempt string) error { return fmt.Errorf("%w: %s is not an attempt of this key", ErrForbidden, attempt) } // Get returns attempt's job as the store holds it. Only the instance key // that launched it may read it; anyone else, and any unknown attempt, gets // ErrForbidden and an audit row. Get makes no provider call. func (c *Controller) Get(ctx context.Context, by hostedwire.KeyID, attemptID string) (JobView, error) { var view JobView var refusal error err := c.store.Tx(ctx, func(tx *sql.Tx) error { view, refusal = JobView{}, nil now := c.store.Clock().Now() a := Audit{Actor: by, Action: actionGetRefused, At: now} if !printableASCII(attemptID, maxNameLen) { refusal = fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen) a.Reason = refusal.Error() return appendAudit(tx, a) } a.Attempt = attemptID j, found, err := loadJob(ctx, tx, attemptID) if err != nil { return err } if by == "" || !found || j.actor != string(by) { refusal = notCreator(attemptID) if found { a.Account, a.Task = j.account, j.task } a.Reason = refusal.Error() return appendAudit(tx, a) } view = j.view(now) return nil }) if err != nil { return JobView{}, err } if refusal != nil { return JobView{}, refusal } return view, nil } // Stop asks for attempt's VM to stop and returns proof once it has. // // Everything after the refusals runs under the attempt's lock (R18), so a // Stop waits for a launch dispatch in flight to settle. // // Only an instance key (RoleInstance) that launched attempt may stop it; // anyone else, an unknown attempt, or a malformed attempt ID or reason // (1 to 128 printable ASCII characters) gets an error and an audit row and // changes nothing. The controller's own stops do not come through here. // // In order: one transaction records stop_requested_t and stop_reason, unless // a stop was already asked for (the first reason is kept), and audits it. A // job that already holds proof returns it with no provider call. A job with // no VM Ref yet is marked JobAbandoned, so Replay never launches it, and // gets ErrStopPending: a lost launch reply may have made a VM the table does // not link, so Refresh issues its proof only once a complete List shows no // such VM. Otherwise, outside any transaction, Runner.Stop and then // Runner.Get: // // - a terminal state is proof: it is saved with state JobStopped in one // transaction and returned; // - isolatedjob.ErrNotFound from Get is proof only when an earlier // not-found, recorded after the stop request, is at least // NotFoundConfirm older than this Get; otherwise the first one is // recorded in notfound_since_t and the result is ErrStopPending; // - a live state (stopping included) gives ErrStopPending; // - an unknown state gives ErrStateUnknown; // - an error from Runner.Stop (a lost reply, a throttle) is returned. The // provider's Stop is idempotent, so the next Stop, or the next Refresh, // sends it again. // // stop_t is never changed. func (c *Controller) Stop(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID, reason string) (StopProof, error) { switch { case by == "" || key.Role != hostedwire.RoleInstance: return StopProof{}, c.refuseStop(ctx, by, attemptID, fmt.Errorf("%w: stop needs the instance key that launched the attempt", ErrForbidden)) case !printableASCII(attemptID, maxNameLen): return StopProof{}, c.refuseStop(ctx, by, "", fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen)) case !printableASCII(reason, maxNameLen): return StopProof{}, c.refuseStop(ctx, by, attemptID, fmt.Errorf("%w: stop reason must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen)) } defer c.lockAttempt(attemptID)() r, err := c.requestStop(ctx, by, attemptID, reason, true) if err != nil { return StopProof{}, err } if r.proof != nil { return *r.proof, nil } if r.ref == "" { return StopProof{}, fmt.Errorf("%w: %s has no VM ref yet; proof waits for a complete list showing no unlinked VM", ErrStopPending, attemptID) } return c.driveStop(ctx, by, r) } // refuseStop audits a refusal that came before any job was read, in a short // transaction of its own, and returns err. func (c *Controller) refuseStop(ctx context.Context, by hostedwire.KeyID, attempt string, err error) error { aerr := c.store.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Actor: by, Attempt: attempt, Action: actionStopRefused, Reason: err.Error(), At: c.store.Clock().Now()}) }) return errors.Join(err, aerr) } // stopReq is what requestStop read and recorded. type stopReq struct { attempt, account, task string ref isolatedjob.Ref // empty when the job has no VM Ref reason string // the stored reason, sent to the provider proof *StopProof // the stored proof, when there is one } // requestStop is Stop's first transaction, shared with the controller's own // stops (actor empty, creatorOnly false). It records the stop request and, // for a job with no Ref still waiting, abandons the intent. func (c *Controller) requestStop(ctx context.Context, actor hostedwire.KeyID, attempt, reason string, creatorOnly bool) (stopReq, error) { var r stopReq var refusal error err := c.store.Tx(ctx, func(tx *sql.Tx) error { r, refusal = stopReq{}, nil now := c.store.Clock().Now() j, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } a := Audit{Actor: actor, Attempt: attempt, At: now} if found { a.Account, a.Task = j.account, j.task } switch { case !found && !creatorOnly: return fmt.Errorf("hostedctl: stop %s: job is missing", attempt) case !found || (creatorOnly && j.actor != string(actor)): refusal = notCreator(attempt) a.Action, a.Reason = actionStopRefused, refusal.Error() return appendAudit(tx, a) } r = stopReq{attempt: attempt, account: j.account, task: j.task, ref: isolatedjob.Ref(j.ref.String)} if j.stopProof.Valid { p, err := decodeProof(j.stopProof.String, attempt) r.proof = &p return err } var stored sql.NullString if err := tx.QueryRowContext(ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, attempt).Scan(&stored); err != nil { return fmt.Errorf("hostedctl: read stop reason of %s: %w", attempt, err) } state := j.state if !j.ref.Valid && state == JobWaiting { state = JobAbandoned } r.reason = reason if stored.Valid { r.reason = stored.String } if j.stopRequested.Valid && state == j.state { a.Action, a.Reason = actionStopRepeated, "stop asked for again: "+reason return appendAudit(tx, a) } res, err := tx.ExecContext(ctx, `UPDATE jobs SET stop_requested_t = coalesce(stop_requested_t, ?), stop_reason = coalesce(stop_reason, ?), state = ?, revision = revision + 1 WHERE attempt_id = ? AND stop_proof_json IS NULL`, int64(now), reason, state, attempt) if err != nil { return fmt.Errorf("hostedctl: record stop request for %s: %w", attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: record stop request for %s: %d rows (%v)", attempt, n, err) } a.Action, a.Reason = actionStopRequested, "stop asked for: "+reason if state == JobAbandoned && j.state != JobAbandoned { a.Reason += "; intent abandoned before any VM ref was saved" } return appendAudit(tx, a) }) if err != nil { return stopReq{}, err } if refusal != nil { return stopReq{}, refusal } return r, nil } // driveStop sends the provider stop for a recorded request and then reads // the VM, outside any transaction. A failed stop call is audited, with a // fixed reason, and returned. func (c *Controller) driveStop(ctx context.Context, actor hostedwire.KeyID, r stopReq) (StopProof, error) { if perr := c.runner.Stop(ctx, r.ref, r.reason); perr != nil && !errors.Is(perr, isolatedjob.ErrNotFound) { aerr := c.auditStop(context.WithoutCancel(ctx), actor, r, actionStopFailed, "provider stop call failed; it is sent again on the next stop or refresh") return StopProof{}, errors.Join(fmt.Errorf("hostedctl: stop %s: %w", r.attempt, perr), aerr) } before := c.store.Clock().Now() job, gerr := c.runner.Get(ctx, r.ref) at := c.store.Clock().Now() // Record what the provider said even if the caller has gone. rec := context.WithoutCancel(ctx) switch { case errors.Is(gerr, isolatedjob.ErrNotFound): p, proven, err := c.notFound(rec, actor, r.attempt, r.ref, before, at, "provider holds no such VM after the stop request") if err != nil || proven { return p, err } return StopProof{}, fmt.Errorf("%w: VM %s not found once; proof needs a second not-found %v later", ErrStopPending, r.ref, NotFoundConfirm) case gerr != nil: return StopProof{}, fmt.Errorf("hostedctl: read VM %s of %s after stop: %w", r.ref, r.attempt, gerr) case job.State.Terminal(): return c.recordProof(rec, actor, r.attempt, StopProof{AttemptID: r.attempt, VMRef: r.ref, State: job.State, ObservedAt: at}, "provider reports the VM "+string(job.State)) case job.State.Live(): if err := c.mirrorState(rec, r.attempt, job.State); err != nil { return StopProof{}, err } return StopProof{}, fmt.Errorf("%w: VM %s is %s", ErrStopPending, r.ref, job.State) } aerr := c.auditStop(rec, actor, r, actionStopStateUnknown, "provider state unknown; no proof") return StopProof{}, errors.Join(fmt.Errorf("%w: VM %s of %s", ErrStateUnknown, r.ref, r.attempt), aerr) } // auditStop writes one audit row about r in a short transaction. func (c *Controller) auditStop(ctx context.Context, actor hostedwire.KeyID, r stopReq, action, reason string) error { return c.store.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Actor: actor, Account: r.account, Task: r.task, Attempt: r.attempt, Action: action, Reason: reason, At: c.store.Clock().Now()}) }) } // notFound handles a not-found answer from Runner.Get for attempt's VM ref, // read between controller times before and at. The answer is proof only // when notfound_since_t holds an earlier not-found that came after the stop // request (if any) and after this process's Open (R19), and is at least // NotFoundConfirm before this Get began; // any live Get in between has cleared it (mirrorState). Otherwise, when no // such first not-found is held, at is recorded as the first one. proven // reports whether p is proof; a job that already holds proof returns it. func (c *Controller) notFound(ctx context.Context, actor hostedwire.KeyID, attempt string, ref isolatedjob.Ref, before, at T, why string) (StopProof, bool, error) { var out StopProof proven := false err := c.store.Tx(ctx, func(tx *sql.Tx) error { out, proven = StopProof{}, false j, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } switch { case !found: return fmt.Errorf("hostedctl: not-found for %s: job is missing", attempt) case j.stopProof.Valid: out, err = decodeProof(j.stopProof.String, attempt) proven = err == nil return err case !j.ref.Valid || isolatedjob.Ref(j.ref.String) != ref: return fmt.Errorf("hostedctl: not-found for %s names VM %s, the job holds %q", attempt, ref, j.ref.String) } var since sql.NullInt64 if err := tx.QueryRowContext(ctx, `SELECT notfound_since_t FROM jobs WHERE attempt_id = ?`, attempt).Scan(&since); err != nil { return fmt.Errorf("hostedctl: read notfound_since_t of %s: %w", attempt, err) } // The first not-found must follow the stop request, if any, and this // process's Open: the time across a restart is untrusted (R19). first := since.Valid && (!j.stopRequested.Valid || since.Int64 >= j.stopRequested.Int64) && (!c.store.Restarted() || T(since.Int64) > c.store.OpenedAt()) if first && before-T(since.Int64) >= T(NotFoundConfirm) { out, proven = StopProof{AttemptID: attempt, VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: at}, true return writeProof(ctx, tx, actor, j, out, fmt.Sprintf("%s; not found twice, %v apart", why, time.Duration(before-T(since.Int64)))) } if first { return nil // waiting for the confirming not-found } res, err := tx.ExecContext(ctx, `UPDATE jobs SET notfound_since_t = ?, revision = revision + 1 WHERE attempt_id = ? AND stop_proof_json IS NULL`, int64(at), attempt) if err != nil { return fmt.Errorf("hostedctl: record not-found for %s: %w", attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: record not-found for %s: %d rows (%v)", attempt, n, err) } return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: attempt, Action: actionVMNotFound, Reason: fmt.Sprintf("%s; proof waits for a second not-found %v later", why, NotFoundConfirm), At: at}) }) if err != nil { return StopProof{}, false, err } return out, proven, nil } // recordProof saves p for a job with a VM Ref in one transaction, with the // job's state set to JobStopped, and returns it. A job that already holds // proof keeps it and returns that one. A job with no stop request ended on // its own: its stop_reason becomes reasonEnded, so replacements may go // ahead. func (c *Controller) recordProof(ctx context.Context, actor hostedwire.KeyID, attempt string, p StopProof, why string) (StopProof, error) { out := p err := c.store.Tx(ctx, func(tx *sql.Tx) error { out = p j, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } switch { case !found: return fmt.Errorf("hostedctl: stop proof for %s: job is missing", attempt) case j.stopProof.Valid: out, err = decodeProof(j.stopProof.String, attempt) return err case !j.ref.Valid || isolatedjob.Ref(j.ref.String) != p.VMRef: return fmt.Errorf("hostedctl: stop proof for %s names VM %s, the job holds %q", attempt, p.VMRef, j.ref.String) } return writeProof(ctx, tx, actor, j, p, why) }) if err != nil { return StopProof{}, err } return out, nil } // writeProof saves p on j's row inside tx and audits it. j holds no proof. func writeProof(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jobRow, p StopProof, why string) error { text, err := json.Marshal(p.wire()) if err != nil { return fmt.Errorf("hostedctl: encode stop proof: %w", err) } ended := !j.stopRequested.Valid res, err := tx.ExecContext(ctx, `UPDATE jobs SET stop_proof_json = ?, state = ?, stop_reason = CASE WHEN ? THEN coalesce(stop_reason, ?) ELSE stop_reason END, revision = revision + 1 WHERE attempt_id = ? AND stop_proof_json IS NULL`, string(text), JobStopped, ended, reasonEnded, j.attempt) if err != nil { return fmt.Errorf("hostedctl: save stop proof for %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: save stop proof for %s: %d rows (%v)", j.attempt, n, err) } if ended { why += "; no stop was asked for, so it ended on its own" } if err := appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt, Action: actionStopProven, Reason: why, At: p.ObservedAt}); err != nil { return err } // A resume still pending now never commits: fail it with the proof. return failPendingResume(ctx, tx, j.account, j.task, j.attempt, p.ObservedAt, "stop proven before the pending resume committed") } // mirrorState saves a live VM state the provider reported as the job's // state, unless the job holds proof. A live VM was seen, so any first // not-found held in notfound_since_t no longer counts and is cleared. func (c *Controller) mirrorState(ctx context.Context, attempt string, st isolatedjob.State) error { return c.store.Tx(ctx, func(tx *sql.Tx) error { _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, notfound_since_t = NULL, revision = revision + 1 WHERE attempt_id = ? AND vm_ref IS NOT NULL AND stop_proof_json IS NULL AND (state <> ? OR notfound_since_t IS NOT NULL)`, string(st), attempt, string(st)) if err != nil { return fmt.Errorf("hostedctl: save state of %s: %w", attempt, err) } return nil }) }