package hostedctl import ( "context" "database/sql" "errors" "fmt" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) // PauseAckTimeout is how long, in controller time from Drain, the runner has // to acknowledge quiescent for a pause generation. Without an // acknowledgement by then the generation is cancelled, and a later one is // ignored (spec ยง3, the pause barrier). const PauseAckTimeout = 2 * time.Minute var ( // ErrGenerationCancelled: the pause generation named is not the // job's current one (an older or a later one), or it is cancelled, or // the pause it opened is closed. ErrGenerationCancelled = errors.New("hostedctl: pause generation is cancelled or not the current one") // ErrNotQuiescent: the current pause generation has no quiescent // acknowledgement yet, so the VM may not be suspended. ErrNotQuiescent = errors.New("hostedctl: no quiescent acknowledgement for this pause generation") // ErrPastDeadline: the job's stop time has passed. Suspended time // counts, so a suspended job may reach it. ErrPastDeadline = errors.New("hostedctl: the job's stop time has passed") ) // Audit actions written by the pause barrier. const ( actionDrain = "drain" actionDrainRefused = "drain_refused" actionQuiescent = "quiescent" actionQuiescentRepeated = "quiescent_repeated" actionQuiescentRefused = "quiescent_refused" actionSuspendRequested = "suspend_requested" actionSuspendRepeated = "suspend_repeated" actionSuspendRefused = "suspend_refused" actionSuspendFailed = "suspend_failed" actionSuspendResent = "suspend_resent" actionSuspendSettled = "suspend_settled" actionReopen = "reopen" actionReopenRepeated = "reopen_repeated" actionReopenRefused = "reopen_refused" actionPauseCancelled = "pause_cancelled" ) // pauseJob is a job row with its pause fields. type pauseJob struct { jobRow generation int64 started sql.NullInt64 // pause_started_t; absent unless a pause is open quiescent, cancelled bool } // loadPauseJob reads attempt's row and its pause fields inside tx. func loadPauseJob(ctx context.Context, tx *sql.Tx, attempt string) (pauseJob, bool, error) { j, found, err := loadJob(ctx, tx, attempt) if err != nil || !found { return pauseJob{}, found, err } p := pauseJob{jobRow: j} if err := tx.QueryRowContext(ctx, `SELECT pause_generation, pause_started_t, pause_quiescent, pause_cancelled FROM jobs WHERE attempt_id = ?`, attempt).Scan(&p.generation, &p.started, &p.quiescent, &p.cancelled); err != nil { return pauseJob{}, false, fmt.Errorf("hostedctl: read pause fields of %s: %w", attempt, err) } return p, true, nil } // currentGen reports whether gen is the job's current pause generation. // Only an exact match counts: an older generation was superseded and a later // one was never opened. func currentGen(gen int64, j *pauseJob) bool { return gen == j.generation } // creatorCall runs fn in one transaction for a call by `by`, holding key, on // attemptID. It refuses a key that is not an instance key, a malformed // attempt ID, an unknown attempt and another key's attempt, with // ErrForbidden (isolatedjob.ErrInvalid for the ID) and an audit row under // refused; an unknown attempt and another key's get the same text. fn gets // the job and an audit row filled in for it at the current controller time, // and appends its own row when it goes ahead. A refusal fn returns is // audited under refused, committed with anything fn wrote before it (a lazy // cancellation), and returned. func (c *Controller) creatorCall(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID, refused string, fn func(tx *sql.Tx, j *pauseJob, a Audit) (refusal, err error)) error { var refusal error err := c.store.Tx(ctx, func(tx *sql.Tx) error { refusal = nil a := Audit{Actor: by, At: c.store.Clock().Now()} valid := printableASCII(attemptID, maxNameLen) if valid { a.Attempt = attemptID } switch { case by == "" || key.Role != hostedwire.RoleInstance: refusal = fmt.Errorf("%w: needs the instance key that launched the attempt", ErrForbidden) case !valid: refusal = fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen) default: j, found, err := loadPauseJob(ctx, tx, attemptID) if err != nil { return err } if found { a.Account, a.Task = j.account, j.task } if !found || j.actor != string(by) { refusal = notCreator(attemptID) break } if refusal, err = fn(tx, &j, a); err != nil { return err } } if refusal == nil { return nil } a.Action, a.Reason = refused, refusal.Error() return appendAudit(tx, a) }) if err != nil { return err } return refusal } // notPausable refuses, with isolatedjob.ErrConflict, a job that holds stop // proof or has a stop request: neither may pause or resume. func notPausable(j *pauseJob) error { switch { case j.stopProof.Valid: return fmt.Errorf("%w: %s has stopped", isolatedjob.ErrConflict, j.attempt) case j.stopRequested.Valid: return fmt.Errorf("%w: a stop was asked for %s", isolatedjob.ErrConflict, j.attempt) } return nil } // expire cancels j's open generation, inside tx, when it is draining with no // quiescent acknowledgement and either more than PauseAckTimeout of // controller time has passed since Drain, or Drain came before this process // opened the store after a restart (at or before OpenedAt): the downtime is // unknown, so the time since Drain is too, and a late acknowledgement could // pass for an early one. Every call that touches a generation runs it first, // so cancellation needs no timer; the reaper may sweep too. A generation // acknowledged in time never expires. func (c *Controller) expire(ctx context.Context, tx *sql.Tx, j *pauseJob, now T) error { if j.state != JobDraining || j.cancelled || j.quiescent || !j.started.Valid { return nil } why := fmt.Sprintf("no quiescent acknowledgement within %v", PauseAckTimeout) switch { case c.store.Restarted() && T(j.started.Int64) <= c.store.OpenedAt(): why = "opened before the controller restarted and not acknowledged; the downtime is unknown" case now-T(j.started.Int64) <= T(PauseAckTimeout): return nil } res, err := tx.ExecContext(ctx, `UPDATE jobs SET pause_cancelled = 1, revision = revision + 1 WHERE attempt_id = ? AND pause_generation = ? AND pause_cancelled = 0`, j.attempt, j.generation) if err != nil { return fmt.Errorf("hostedctl: cancel pause of %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: cancel pause of %s: %d rows (%v)", j.attempt, n, err) } j.cancelled = true return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: j.attempt, Action: actionPauseCancelled, Reason: fmt.Sprintf("generation %d: %s; a late acknowledgement is ignored", j.generation, why), At: now}) } // Drain opens a new pause generation for attemptID and returns it: the // generation counter goes up by one, its start is the current controller // time, and the job's state becomes JobDraining. Only a running job, or one // already draining, may drain; draining again supersedes the open // generation, so an acknowledgement for it is refused from then on. A job // in any other state, or with a stop request or proof, gets // isolatedjob.ErrConflict. // // Drain, Quiescent, Suspend, Reopen and Resume are for the instance key // that launched the attempt (see creatorCall). Each call and each refusal // appends an audit row, and each runs under the attempt's lock. func (c *Controller) Drain(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID string) (int64, error) { defer c.lockAttempt(attemptID)() var gen int64 err := c.creatorCall(ctx, by, key, attemptID, actionDrainRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { gen = 0 if r := notPausable(j); r != nil { return r, nil } if j.state != JobRunning && j.state != JobDraining { return fmt.Errorf("%w: only a running job can drain; %s is %s", isolatedjob.ErrConflict, j.attempt, j.state), nil } next := j.generation + 1 res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, pause_generation = ?, pause_started_t = ?, pause_quiescent = 0, pause_cancelled = 0, revision = revision + 1 WHERE attempt_id = ? AND pause_generation = ?`, JobDraining, next, int64(a.At), j.attempt, j.generation) if err != nil { return nil, fmt.Errorf("hostedctl: drain %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return nil, fmt.Errorf("hostedctl: drain %s: %d rows (%v)", j.attempt, n, err) } a.Action = actionDrain a.Reason = fmt.Sprintf("pause generation %d opened; quiescent due within %v", next, PauseAckTimeout) if j.state == JobDraining { a.Reason += fmt.Sprintf("; generation %d superseded", j.generation) } gen = next return nil, appendAudit(tx, a) }) if err != nil { return 0, err } return gen, nil } // Quiescent records the runner's acknowledgement that it has stopped taking // work for generation. The generation must be the current one, open // (draining), not cancelled, and the acknowledgement must come at most // PauseAckTimeout after Drain; otherwise ErrGenerationCancelled, and a late // acknowledgement also cancels the generation. Acknowledging the same // generation again while its pause is open is accepted and changes nothing. func (c *Controller) Quiescent(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID string, generation int64) error { defer c.lockAttempt(attemptID)() return c.creatorCall(ctx, by, key, attemptID, actionQuiescentRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { if r := notPausable(j); r != nil { return r, nil } if err := c.expire(ctx, tx, j, a.At); err != nil { return nil, err } switch { case !currentGen(generation, j): return fmt.Errorf("%w: generation %d is not the current one (%d)", ErrGenerationCancelled, generation, j.generation), nil case j.quiescent: a.Action, a.Reason = actionQuiescentRepeated, fmt.Sprintf("generation %d acknowledged again", generation) return nil, appendAudit(tx, a) case j.cancelled: return fmt.Errorf("%w: generation %d was cancelled", ErrGenerationCancelled, generation), nil case j.state != JobDraining: return fmt.Errorf("%w: no pause is open for generation %d; the job is %s", ErrGenerationCancelled, generation, j.state), nil } res, err := tx.ExecContext(ctx, `UPDATE jobs SET pause_quiescent = 1, revision = revision + 1 WHERE attempt_id = ? AND pause_generation = ? AND state = ?`, j.attempt, generation, JobDraining) if err != nil { return nil, fmt.Errorf("hostedctl: record quiescent for %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return nil, fmt.Errorf("hostedctl: record quiescent for %s: %d rows (%v)", j.attempt, n, err) } a.Action, a.Reason = actionQuiescent, fmt.Sprintf("generation %d acknowledged after %v", generation, time.Duration(a.At-T(j.started.Int64))) return nil, appendAudit(tx, a) }) } // Suspend suspends attemptID's VM for generation. The generation must be // the current one and open, not cancelled (ErrGenerationCancelled), and // acknowledged quiescent (ErrNotQuiescent). One transaction records the // state JobSuspending; then, outside it, Runner.Suspend. A failed provider // call is audited and returned; the job stays suspending and Refresh sends // the suspend again while the VM still runs. Refresh moves the job to // JobSuspended once the provider reports the VM suspended. Asking again for // a generation already suspending or suspended returns nil with no provider // call. func (c *Controller) Suspend(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID string, generation int64) error { defer c.lockAttempt(attemptID)() var send *pauseJob err := c.creatorCall(ctx, by, key, attemptID, actionSuspendRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { send = nil if r := notPausable(j); r != nil { return r, nil } if err := c.expire(ctx, tx, j, a.At); err != nil { return nil, err } if !currentGen(generation, j) { return fmt.Errorf("%w: generation %d is not the current one (%d)", ErrGenerationCancelled, generation, j.generation), nil } switch j.state { case JobSuspending, JobSuspended: a.Action, a.Reason = actionSuspendRepeated, fmt.Sprintf("generation %d: suspend asked for again; job is %s", generation, j.state) return nil, appendAudit(tx, a) case JobDraining: default: return fmt.Errorf("%w: no pause is open for generation %d; the job is %s", ErrGenerationCancelled, generation, j.state), nil } if j.cancelled { return fmt.Errorf("%w: generation %d was cancelled", ErrGenerationCancelled, generation), nil } if !j.quiescent { return fmt.Errorf("%w: generation %d", ErrNotQuiescent, generation), nil } res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 WHERE attempt_id = ? AND state = ? AND pause_generation = ?`, JobSuspending, j.attempt, JobDraining, generation) if err != nil { return nil, fmt.Errorf("hostedctl: record suspend of %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return nil, fmt.Errorf("hostedctl: record suspend of %s: %d rows (%v)", j.attempt, n, err) } a.Action, a.Reason = actionSuspendRequested, fmt.Sprintf("generation %d quiescent; suspending VM %s", generation, j.ref.String) send = j return nil, appendAudit(tx, a) }) if err != nil || send == nil { return err } perr, aerr := c.sendSuspend(ctx, by, send, "") return errors.Join(perr, aerr) } // sendSuspend calls Runner.Suspend for j's VM, outside any transaction. A // failure is audited, with a fixed reason, and returned as perr; aerr is a // failure to write the audit row. resent names the audit action for a // successful call, or is empty for none. func (c *Controller) sendSuspend(ctx context.Context, actor hostedwire.KeyID, j *pauseJob, resent string) (perr, aerr error) { ref := isolatedjob.Ref(j.ref.String) perr = c.runner.Suspend(ctx, ref) action, reason := resent, "refresh: the VM still runs; suspend sent again" if perr != nil { action, reason = actionSuspendFailed, "provider suspend call failed; refresh sends it again while the VM runs" } if action != "" { aerr = c.auditPause(context.WithoutCancel(ctx), actor, j, action, reason) } if perr != nil { perr = fmt.Errorf("hostedctl: suspend %s: VM %s: %w", j.attempt, ref, perr) } return perr, aerr } // Reopen records that the runner takes work again after a cancelled or // abandoned pause of generation, the current one (else // ErrGenerationCancelled). The job returns to JobRunning and its pause // fields are cleared; the generation counter stays. A job whose times wait // for the first Refresh after a restart (ageUnsettled) gets // isolatedjob.ErrConflict, so its stop time is judged only once re-based. // Once the job's stop time has come admission never reopens // (ErrPastDeadline). A job already // running at that generation gets nil; a suspending, suspended or resuming // job gets isolatedjob.ErrConflict, as its VM is paused and needs Resume. func (c *Controller) Reopen(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID string, generation int64) error { defer c.lockAttempt(attemptID)() return c.creatorCall(ctx, by, key, attemptID, actionReopenRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { if r := notPausable(j); r != nil { return r, nil } if err := c.expire(ctx, tx, j, a.At); err != nil { return nil, err } if !currentGen(generation, j) { return fmt.Errorf("%w: generation %d is not the current one (%d)", ErrGenerationCancelled, generation, j.generation), nil } if c.ageUnsettled(j) { return fmt.Errorf("%w: the job's times wait for the first refresh after a restart; ask again", isolatedjob.ErrConflict), nil } if pastStop(j, a.At) { return fmt.Errorf("%w: %v ago; admission stays closed", ErrPastDeadline, time.Duration(a.At-T(j.stopT))), nil } switch j.state { case JobRunning: a.Action, a.Reason = actionReopenRepeated, fmt.Sprintf("generation %d: admission already open", generation) return nil, appendAudit(tx, a) case JobDraining: default: return fmt.Errorf("%w: %s is %s; it needs a resume, not a reopen", isolatedjob.ErrConflict, j.attempt, j.state), nil } res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, pause_started_t = NULL, pause_quiescent = 0, pause_cancelled = 0, revision = revision + 1 WHERE attempt_id = ? AND state = ? AND pause_generation = ?`, JobRunning, j.attempt, JobDraining, generation) if err != nil { return nil, fmt.Errorf("hostedctl: reopen %s: %w", j.attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return nil, fmt.Errorf("hostedctl: reopen %s: %d rows (%v)", j.attempt, n, err) } why := "abandoned" if j.cancelled { why = "cancelled" } a.Action, a.Reason = actionReopen, fmt.Sprintf("generation %d %s; the runner takes work again", generation, why) return nil, appendAudit(tx, a) }) }