package hostedctl import ( "context" "database/sql" "errors" "fmt" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) // ErrResumePending: a resume operation is prepared but not committed: the // VM does not run yet, or the provider call failed or its reply was lost. // Retry with the same operation ID; Refresh also finishes it. A new // operation ID while another is pending gets it too. var ErrResumePending = errors.New("hostedctl: a resume is pending; retry with its operation ID") // maxOperationIDLen bounds a resume operation ID. const maxOperationIDLen = 64 // resume_ops.status values. const ( opPending = "pending" opDone = "done" opFailed = "failed" ) // Audit actions written by Resume and by Refresh finishing a resume. const ( actionResumePrepared = "resume_prepared" actionResumeContinued = "resume_continued" actionResumeRepeated = "resume_repeated" actionResumeRefused = "resume_refused" actionResumeCallFailed = "resume_call_failed" actionResumeResent = "resume_resent" actionResumeCommitted = "resume_committed" actionResumeFailed = "resume_failed" ) // resumeOp is one resume_ops row. type resumeOp struct { id, status string prepared int64 result sql.NullInt64 } // validOperationID reports whether s is 1 to maxOperationIDLen characters, // each a letter, a digit or '-'. func validOperationID(s string) bool { if len(s) == 0 || len(s) > maxOperationIDLen { return false } for i := 0; i < len(s); i++ { switch b := s[i]; { case b >= 'a' && b <= 'z', b >= 'A' && b <= 'Z', b >= '0' && b <= '9', b == '-': default: return false } } return true } // loadResumeOp reads the row for (attempt, op) inside tx, whatever other // operations the attempt has had since. func loadResumeOp(ctx context.Context, tx *sql.Tx, attempt, op string) (resumeOp, bool, error) { r := resumeOp{id: op} err := tx.QueryRowContext(ctx, `SELECT status, prepared_epoch, result_epoch FROM resume_ops WHERE attempt_id = ? AND operation_id = ?`, attempt, op).Scan(&r.status, &r.prepared, &r.result) switch { case errors.Is(err, sql.ErrNoRows): return resumeOp{}, false, nil case err != nil: return resumeOp{}, false, fmt.Errorf("hostedctl: read resume operation %s of %s: %w", op, attempt, err) } return r, true, nil } // pendingResumeOp reads attempt's pending resume row, if any (at most one). func pendingResumeOp(ctx context.Context, tx *sql.Tx, attempt string) (resumeOp, bool, error) { r := resumeOp{status: opPending} err := tx.QueryRowContext(ctx, `SELECT operation_id, prepared_epoch FROM resume_ops WHERE attempt_id = ? AND status = ?`, attempt, opPending).Scan(&r.id, &r.prepared) switch { case errors.Is(err, sql.ErrNoRows): return resumeOp{}, false, nil case err != nil: return resumeOp{}, false, fmt.Errorf("hostedctl: read pending resume of %s: %w", attempt, err) } return r, true, nil } // failPendingResume marks attempt's pending resume, if any, failed inside // tx, with an audit row giving why. The row stays, so a retry of its // operation ID is refused rather than prepared again. writeProof calls it, // so every proof path fails a pending resume in the transaction that saves // the proof. func failPendingResume(ctx context.Context, tx *sql.Tx, account, task, attempt string, now T, why string) error { res, err := tx.ExecContext(ctx, `UPDATE resume_ops SET status = ?, completed_t = ? WHERE attempt_id = ? AND status = ?`, opFailed, int64(now), attempt, opPending) if err != nil { return fmt.Errorf("hostedctl: fail pending resume of %s: %w", attempt, err) } if n, err := res.RowsAffected(); err != nil || n == 0 { return err } return appendAudit(tx, Audit{Account: account, Task: task, Attempt: attempt, Action: actionResumeFailed, Reason: why, At: now}) } // failDeadResume marks j's pending resume failed, inside tx, when the job // holds stop proof or has a stop request: that resume is never committed. func failDeadResume(ctx context.Context, tx *sql.Tx, j *pauseJob, now T) error { if !j.stopProof.Valid && !j.stopRequested.Valid { return nil } return failPendingResume(ctx, tx, j.account, j.task, j.attempt, now, "a stop was asked for before the pending resume committed") } // failResumeAtDeadline marks j's pending resume failed, inside tx, because // the job's stop time has come: a resume never commits past it and the // provider is not called again. observed is the VM state just read, or // empty when none was: a live one becomes the state of a resuming job (the // epoch is not raised) and clears notfound_since_t. With none the job stays // resuming, with no pending row, and the next Refresh mirrors the VM. func failResumeAtDeadline(ctx context.Context, tx *sql.Tx, j *pauseJob, now T, observed isolatedjob.State) error { if err := failPendingResume(ctx, tx, j.account, j.task, j.attempt, now, fmt.Sprintf("stop time passed %v ago before the pending resume committed", time.Duration(now-T(j.stopT)))); err != nil { return err } if !observed.Live() { return nil } if _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 WHERE attempt_id = ? AND state = ?`, string(observed), j.attempt, JobResuming); err != nil { return fmt.Errorf("hostedctl: settle resume of %s at its stop time: %w", j.attempt, err) } return clearNotFound(ctx, tx, j.attempt) } // clearNotFound drops attempt's first not-found inside tx: a live VM was // just seen, so it no longer counts towards stop proof. The job's state is // left alone. func clearNotFound(ctx context.Context, tx *sql.Tx, attempt string) error { if _, err := tx.ExecContext(ctx, `UPDATE jobs SET notfound_since_t = NULL, revision = revision + 1 WHERE attempt_id = ? AND notfound_since_t IS NOT NULL`, attempt); err != nil { return fmt.Errorf("hostedctl: clear not-found of %s: %w", attempt, err) } return nil } // ageUnsettled reports whether j existed before this process opened the // store and Refresh has not yet re-based its times from the provider's age // (or stopped it as elapsed_unknown): until then its stop time is not to be // trusted, so no resume is driven for it. It is refreshOne's test for an // untrusted elapsed time. func (c *Controller) ageUnsettled(j *pauseJob) bool { return c.store.Restarted() && T(j.launchedT) <= c.store.OpenedAt() && !c.rebased.has(j.attempt) } // pastStop reports whether j's stop time has come at now. func pastStop(j *pauseJob, now T) bool { return now >= T(j.stopT) } // commitResume is step 3 inside tx, once the provider reports the VM // running: the job's epoch becomes op's prepared epoch, which must be one // above the stored epoch, the job is running with its pause closed (the // generation counter stays), and op is done with that epoch. op must be // pending, so an operation raises the epoch at most once. func commitResume(ctx context.Context, tx *sql.Tx, j *pauseJob, op resumeOp, actor hostedwire.KeyID, now T) error { res, err := tx.ExecContext(ctx, `UPDATE jobs SET epoch = ?, state = ?, pause_started_t = NULL, pause_quiescent = 0, pause_cancelled = 0, notfound_since_t = NULL, revision = revision + 1 WHERE attempt_id = ? AND epoch = ?`, op.prepared, JobRunning, j.attempt, op.prepared-1) if err != nil { return fmt.Errorf("hostedctl: commit resume of %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: commit resume %s of %s: epoch is not %d (%d rows, %v)", op.id, j.attempt, op.prepared-1, n, err) } res, err = tx.ExecContext(ctx, `UPDATE resume_ops SET status = ?, result_epoch = ?, completed_t = ? WHERE attempt_id = ? AND operation_id = ? AND status = ?`, opDone, op.prepared, int64(now), j.attempt, op.id, opPending) if err != nil { return fmt.Errorf("hostedctl: commit resume of %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: commit resume %s of %s: %d rows (%v)", op.id, j.attempt, n, err) } return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt, Action: actionResumeCommitted, Reason: fmt.Sprintf("operation %s: the VM runs; epoch %d", op.id, op.prepared), At: now}) } // Resume resumes attemptID's suspended VM under operationID (1 to 64 // letters, digits and '-') and returns the job's new epoch. An operation // raises the epoch exactly once, however often it is retried. Under the // attempt's lock, in three steps: // // 1. Prepare, in one transaction. A done operation returns its epoch with // no provider call, whatever operations came after it; a failed one // gets isolatedjob.ErrConflict. Then a stop request or proof gives // ErrConflict; a job whose times wait for the first Refresh after a // restart (ageUnsettled) gives ErrResumePending; the job's stop time // reached gives ErrPastDeadline, // with no provider call and no new row; a pending operation is failed // then. A pending operation carries on with its prepared epoch. A new operation while another is pending // gets ErrResumePending; one for a job that is not suspended gets // ErrConflict. Otherwise a pending row with prepared epoch = epoch + 1 // is saved and the job becomes JobResuming. // 2. Outside any transaction, the stop time checked again, then // Runner.Resume. A failure is audited and returned wrapped in // ErrResumePending; the row stays pending. // 3. Runner.Get, then finishResume. Terminal: the stop proof is saved, // failing the row in the same transaction, and ErrConflict returned. // The stop time come meanwhile: the row is failed, ErrPastDeadline. // Running: one transaction sets the job's epoch to the prepared one and // marks the row done (commitResume). Anything else, still suspended // included (the provider reports suspended while the VM's resume hook // runs): ErrResumePending, epoch 0. Every live reading clears // notfound_since_t, so a stale not-found never combines with a later // one into stop proof. // // New-epoch credentials come from the prepared epoch, so the resume hook // can finish before the commit. After a crash or a lost reply, a retry with // the same ID or Refresh (mirrorLive) finishes the operation. func (c *Controller) Resume(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID, operationID string) (int64, error) { defer c.lockAttempt(attemptID)() var epoch int64 var send *pauseJob var op resumeOp err := c.creatorCall(ctx, by, key, attemptID, actionResumeRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { epoch, send = 0, nil if !validOperationID(operationID) { return fmt.Errorf("%w: operation id must be 1 to %d letters, digits or '-'", isolatedjob.ErrInvalid, maxOperationIDLen), nil } if err := failDeadResume(ctx, tx, j, a.At); err != nil { return nil, err } o, found, err := loadResumeOp(ctx, tx, j.attempt, operationID) if err != nil { return nil, err } switch { case found && o.status == opDone: epoch = o.result.Int64 a.Action, a.Reason = actionResumeRepeated, fmt.Sprintf("operation %s already done at epoch %d", operationID, epoch) return nil, appendAudit(tx, a) case found && o.status != opPending: return fmt.Errorf("%w: resume operation %s failed", isolatedjob.ErrConflict, operationID), nil } if r := notPausable(j); r != nil { return r, nil } if c.ageUnsettled(j) { return fmt.Errorf("%w: the job's times wait for the first refresh after a restart", ErrResumePending), nil } if pastStop(j, a.At) { if found { // pending: it never commits now if err := failResumeAtDeadline(ctx, tx, j, a.At, ""); err != nil { return nil, err } } return fmt.Errorf("%w: %v ago", ErrPastDeadline, time.Duration(a.At-T(j.stopT))), nil } if found { a.Action, a.Reason = actionResumeContinued, fmt.Sprintf("operation %s pending at epoch %d; resume sent again", operationID, o.prepared) op, send = o, j return nil, appendAudit(tx, a) } other, busy, err := pendingResumeOp(ctx, tx, j.attempt) if err != nil { return nil, err } if busy { return fmt.Errorf("%w: operation %s is pending", ErrResumePending, other.id), nil } if j.state != JobSuspended { return fmt.Errorf("%w: only a suspended job can resume; %s is %s", isolatedjob.ErrConflict, j.attempt, j.state), nil } o = resumeOp{id: operationID, status: opPending, prepared: j.epoch + 1} if _, err := tx.ExecContext(ctx, `INSERT INTO resume_ops (attempt_id, operation_id, status, prepared_epoch, prepared_t) VALUES (?, ?, ?, ?, ?)`, j.attempt, operationID, opPending, o.prepared, int64(a.At)); err != nil { return nil, fmt.Errorf("hostedctl: prepare resume of %s: %w", j.attempt, err) } res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 WHERE attempt_id = ? AND state = ? AND epoch = ?`, JobResuming, j.attempt, JobSuspended, j.epoch) if err != nil { return nil, fmt.Errorf("hostedctl: prepare resume of %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return nil, fmt.Errorf("hostedctl: prepare resume of %s: %d rows (%v)", j.attempt, n, err) } a.Action, a.Reason = actionResumePrepared, fmt.Sprintf("operation %s prepared at epoch %d", operationID, o.prepared) op, send = o, j return nil, appendAudit(tx, a) }) if err != nil { return 0, err } if send == nil { return epoch, nil } return c.driveResume(ctx, by, send, op) } // driveResume is Resume's steps 2 and 3 for a prepared or pending op. The // stop time is checked again just before the provider call and again in // the transaction that would commit (finishResume), so time that passes // during the calls cannot let a resume commit past it. func (c *Controller) driveResume(ctx context.Context, actor hostedwire.KeyID, j *pauseJob, op resumeOp) (int64, error) { ref := isolatedjob.Ref(j.ref.String) rec := context.WithoutCancel(ctx) // record what the provider said even if the caller has gone if now := c.store.Clock().Now(); pastStop(j, now) { return c.finishResume(rec, actor, j, op.id, "", now) } if perr := c.runner.Resume(ctx, ref); perr != nil { aerr := c.auditPause(rec, actor, j, actionResumeCallFailed, fmt.Sprintf("operation %s: provider resume call failed; the operation stays pending", op.id)) return 0, errors.Join(fmt.Errorf("%w: operation %s: resume VM %s: %w", ErrResumePending, op.id, ref, perr), aerr) } job, gerr := c.runner.Get(ctx, ref) at := c.store.Clock().Now() if gerr != nil { return 0, fmt.Errorf("%w: operation %s: read VM %s: %w", ErrResumePending, op.id, ref, gerr) } return c.finishResume(rec, actor, j, op.id, job.State, at) } // finishResume settles operation opID of j's attempt from the VM state st // that a Get ending at at reported, or from no reading when st is empty. // // - Terminal: the stop proof is saved, which fails the pending operation // in the same transaction (writeProof); isolatedjob.ErrConflict. // - The job's stop time has come: the operation is failed // (failResumeAtDeadline); ErrPastDeadline. // - Running: commitResume; the epoch. // - Any other state: a live one clears notfound_since_t, the controller // state untouched; ErrResumePending. // // An operation already done returns its epoch; a failed one ErrConflict. func (c *Controller) finishResume(ctx context.Context, actor hostedwire.KeyID, j *pauseJob, opID string, st isolatedjob.State, at T) (int64, error) { attempt := j.attempt if st.Terminal() { if _, err := c.recordProof(ctx, actor, attempt, StopProof{AttemptID: attempt, VMRef: isolatedjob.Ref(j.ref.String), State: st, ObservedAt: at}, "resume: provider reports the VM "+string(st)); err != nil { return 0, err } return 0, fmt.Errorf("%w: VM is %s; resume operation %s failed", isolatedjob.ErrConflict, st, opID) } var epoch int64 var refusal error err := c.store.Tx(ctx, func(tx *sql.Tx) error { epoch, refusal = 0, nil p, found, err := loadPauseJob(ctx, tx, attempt) if err != nil { return err } if !found { return fmt.Errorf("hostedctl: resume %s: job is missing", attempt) } now := c.store.Clock().Now() if err := failDeadResume(ctx, tx, &p, now); err != nil { return err } op, found, err := loadResumeOp(ctx, tx, attempt, opID) switch { case err != nil: return err case !found: return fmt.Errorf("hostedctl: resume %s: operation %s is missing", attempt, opID) case op.status == opDone: epoch = op.result.Int64 return nil case op.status != opPending: refusal = fmt.Errorf("%w: resume operation %s failed", isolatedjob.ErrConflict, opID) return nil case pastStop(&p, now): refusal = fmt.Errorf("%w: %v ago; resume operation %s failed", ErrPastDeadline, time.Duration(now-T(p.stopT)), opID) return failResumeAtDeadline(ctx, tx, &p, now, st) case st == isolatedjob.StateRunning: epoch = op.prepared return commitResume(ctx, tx, &p, op, actor, now) } refusal = fmt.Errorf("%w: operation %s: VM %s is %s", ErrResumePending, opID, p.ref.String, st) if !st.Live() { return nil } return clearNotFound(ctx, tx, attempt) }) if err != nil { return 0, err } return epoch, refusal } // auditPause writes one audit row about j in a short transaction. func (c *Controller) auditPause(ctx context.Context, actor hostedwire.KeyID, j *pauseJob, action, reason string) error { return c.store.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt, Action: action, Reason: reason, At: c.store.Clock().Now()}) }) } // pauseState reports whether state is one the controller sets for the pause // barrier or a resume and settles itself: Refresh never overwrites it with // the VM's live state. func pauseState(state string) bool { return state == JobDraining || state == JobSuspending || state == JobResuming } // mirrorLive is Refresh's hook for the pause barrier and resumes. refreshOne // calls it, in place of mirrorState, with j as it read the job under the // attempt's lock (so j is current; the hook does not take the lock again) // and the live state st that Get just reported. No transaction is held // across a provider call. // // A job in none of the pause states, with no stop request, is mirrored as // before. A job with a stop request is mirrored too, as the stop wins, and // its pending resume, if any, is marked failed. Otherwise the job's state // is left alone (a live sighting still clears notfound_since_t, as // mirrorState does) and only the transitions the controller expects are // settled: // // - draining: the generation is cancelled if its acknowledgement is late; // - suspending: a suspended VM makes the job JobSuspended; a VM still // running gets Runner.Suspend again (the first call may never have // reached the provider), unless the stop time has come; // - resuming: once the stop time has come the pending operation is // failed and the job takes the VM's state, with no provider call and no // commit (failResumeAtDeadline). Before it, a running VM commits the // pending operation (commitResume) and a suspended one gets // Runner.Resume again. // // While the job's age is unsettled after a restart (ageUnsettled, refreshOne's // untrusted test), only the not-found marker is cleared: refreshOne re-bases // the job's times from the provider's age, or stops it as elapsed_unknown, // right after the hook, and recovery waits for the next pass, so it is // judged against the settled stop time. // // Every live sighting clears notfound_since_t before the hook returns, so // refreshOne's restart handling after it sees the cleared value. A provider // call the hook makes that fails is audited and sent again next pass, not // returned: only store errors are, so a failing re-send never holds up // refreshOne's restart handling. Unknown states never get here, so a // pending resume stays pending for the next pass; a terminal VM gets proof // from refreshOne, which fails its pending resume in the same transaction // (writeProof). // // Provider calls get call, the caller's context, so they end when it does; // store writes use a detached copy, so what Get saw is recorded even then. func (c *Controller) mirrorLive(call context.Context, j jobRow, st isolatedjob.State) error { ctx := context.WithoutCancel(call) if !pauseState(j.state) && !j.stopRequested.Valid { return c.mirrorState(ctx, j.attempt, st) } var next func() error err := c.store.Tx(ctx, func(tx *sql.Tx) error { next = nil p, found, err := loadPauseJob(ctx, tx, j.attempt) if err != nil || !found || p.stopProof.Valid { return err } now := c.store.Clock().Now() if p.stopRequested.Valid || !pauseState(p.state) { next = func() error { return c.mirrorState(ctx, p.attempt, st) } return failDeadResume(ctx, tx, &p, now) } if err := clearNotFound(ctx, tx, p.attempt); err != nil || c.ageUnsettled(&p) { return err } a := Audit{Account: p.account, Task: p.task, Attempt: p.attempt, At: now} switch { case p.state == JobDraining: return c.expire(ctx, tx, &p, now) case p.state == JobSuspending && st == isolatedjob.StateSuspended: if _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 WHERE attempt_id = ? AND state = ?`, JobSuspended, p.attempt, JobSuspending); err != nil { return fmt.Errorf("hostedctl: settle suspend of %s: %w", p.attempt, err) } a.Action, a.Reason = actionSuspendSettled, fmt.Sprintf("generation %d: provider reports the VM suspended", p.generation) return appendAudit(tx, a) case p.state == JobSuspending && st == isolatedjob.StateRunning && !pastStop(&p, now): next = func() error { _, aerr := c.sendSuspend(call, "", &p, actionSuspendResent) // a failed call is audited and sent again next pass return aerr } return nil case p.state != JobResuming: return nil } op, ok, err := pendingResumeOp(ctx, tx, p.attempt) switch { case err != nil: return err case !ok: // nothing to finish; the VM's own state is the best record next = func() error { return c.mirrorState(ctx, p.attempt, st) } return nil case pastStop(&p, now): return failResumeAtDeadline(ctx, tx, &p, now, st) case st == isolatedjob.StateRunning: return commitResume(ctx, tx, &p, op, "", now) case st == isolatedjob.StateSuspended: next = func() error { return c.resendResume(call, &p, op) } } return nil }) if err != nil || next == nil { return err } return next() } // resendResume is Refresh sending the provider resume again for j's // pending op while the VM still reports suspended. The stop time is checked // again just before the call; once it has come there is no call and the // next pass fails the operation. The call's outcome is audited; only a // failure to write that row is returned. A failed call is sent again on // the next pass. func (c *Controller) resendResume(ctx context.Context, j *pauseJob, op resumeOp) error { if pastStop(j, c.store.Clock().Now()) { return nil } perr := c.runner.Resume(ctx, isolatedjob.Ref(j.ref.String)) rec := context.WithoutCancel(ctx) if perr != nil { return c.auditPause(rec, "", j, actionResumeCallFailed, fmt.Sprintf("refresh: operation %s: provider resume call failed; the operation stays pending", op.id)) } return c.auditPause(rec, "", j, actionResumeResent, fmt.Sprintf("refresh: operation %s pending; the VM still reports suspended, resume sent again", op.id)) }