| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 11 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 12 | ) |
| 13 | |
| 14 | // PauseAckTimeout is how long, in controller time from Drain, the runner has |
| 15 | // to acknowledge quiescent for a pause generation. Without an |
| 16 | // acknowledgement by then the generation is cancelled, and a later one is |
| 17 | // ignored (spec §3, the pause barrier). |
| 18 | const PauseAckTimeout = 2 * time.Minute |
| 19 | |
| 20 | var ( |
| 21 | // ErrGenerationCancelled: the pause generation named is not the |
| 22 | // job's current one (an older or a later one), or it is cancelled, or |
| 23 | // the pause it opened is closed. |
| 24 | ErrGenerationCancelled = errors.New("hostedctl: pause generation is cancelled or not the current one") |
| 25 | // ErrNotQuiescent: the current pause generation has no quiescent |
| 26 | // acknowledgement yet, so the VM may not be suspended. |
| 27 | ErrNotQuiescent = errors.New("hostedctl: no quiescent acknowledgement for this pause generation") |
| 28 | // ErrPastDeadline: the job's stop time has passed. Suspended time |
| 29 | // counts, so a suspended job may reach it. |
| 30 | ErrPastDeadline = errors.New("hostedctl: the job's stop time has passed") |
| 31 | ) |
| 32 | |
| 33 | // Audit actions written by the pause barrier. |
| 34 | const ( |
| 35 | actionDrain = "drain" |
| 36 | actionDrainRefused = "drain_refused" |
| 37 | actionQuiescent = "quiescent" |
| 38 | actionQuiescentRepeated = "quiescent_repeated" |
| 39 | actionQuiescentRefused = "quiescent_refused" |
| 40 | actionSuspendRequested = "suspend_requested" |
| 41 | actionSuspendRepeated = "suspend_repeated" |
| 42 | actionSuspendRefused = "suspend_refused" |
| 43 | actionSuspendFailed = "suspend_failed" |
| 44 | actionSuspendResent = "suspend_resent" |
| 45 | actionSuspendSettled = "suspend_settled" |
| 46 | actionReopen = "reopen" |
| 47 | actionReopenRepeated = "reopen_repeated" |
| 48 | actionReopenRefused = "reopen_refused" |
| 49 | actionPauseCancelled = "pause_cancelled" |
| 50 | ) |
| 51 | |
| 52 | // pauseJob is a job row with its pause fields. |
| 53 | type pauseJob struct { |
| 54 | jobRow |
| 55 | generation int64 |
| 56 | started sql.NullInt64 // pause_started_t; absent unless a pause is open |
| 57 | quiescent, cancelled bool |
| 58 | } |
| 59 | |
| 60 | // loadPauseJob reads attempt's row and its pause fields inside tx. |
| 61 | func loadPauseJob(ctx context.Context, tx *sql.Tx, attempt string) (pauseJob, bool, error) { |
| 62 | j, found, err := loadJob(ctx, tx, attempt) |
| 63 | if err != nil || !found { |
| 64 | return pauseJob{}, found, err |
| 65 | } |
| 66 | p := pauseJob{jobRow: j} |
| 67 | if err := tx.QueryRowContext(ctx, `SELECT pause_generation, pause_started_t, pause_quiescent, pause_cancelled |
| 68 | FROM jobs WHERE attempt_id = ?`, attempt).Scan(&p.generation, &p.started, &p.quiescent, &p.cancelled); err != nil { |
| 69 | return pauseJob{}, false, fmt.Errorf("hostedctl: read pause fields of %s: %w", attempt, err) |
| 70 | } |
| 71 | return p, true, nil |
| 72 | } |
| 73 | |
| 74 | // currentGen reports whether gen is the job's current pause generation. |
| 75 | // Only an exact match counts: an older generation was superseded and a later |
| 76 | // one was never opened. |
| 77 | func currentGen(gen int64, j *pauseJob) bool { return gen == j.generation } |
| 78 | |
| 79 | // creatorCall runs fn in one transaction for a call by `by`, holding key, on |
| 80 | // attemptID. It refuses a key that is not an instance key, a malformed |
| 81 | // attempt ID, an unknown attempt and another key's attempt, with |
| 82 | // ErrForbidden (isolatedjob.ErrInvalid for the ID) and an audit row under |
| 83 | // refused; an unknown attempt and another key's get the same text. fn gets |
| 84 | // the job and an audit row filled in for it at the current controller time, |
| 85 | // and appends its own row when it goes ahead. A refusal fn returns is |
| 86 | // audited under refused, committed with anything fn wrote before it (a lazy |
| 87 | // cancellation), and returned. |
| 88 | func (c *Controller) creatorCall(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID, refused string, |
| 89 | fn func(tx *sql.Tx, j *pauseJob, a Audit) (refusal, err error)) error { |
| 90 | var refusal error |
| 91 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 92 | refusal = nil |
| 93 | a := Audit{Actor: by, At: c.store.Clock().Now()} |
| 94 | valid := printableASCII(attemptID, maxNameLen) |
| 95 | if valid { |
| 96 | a.Attempt = attemptID |
| 97 | } |
| 98 | switch { |
| 99 | case by == "" || key.Role != hostedwire.RoleInstance: |
| 100 | refusal = fmt.Errorf("%w: needs the instance key that launched the attempt", ErrForbidden) |
| 101 | case !valid: |
| 102 | refusal = fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen) |
| 103 | default: |
| 104 | j, found, err := loadPauseJob(ctx, tx, attemptID) |
| 105 | if err != nil { |
| 106 | return err |
| 107 | } |
| 108 | if found { |
| 109 | a.Account, a.Task = j.account, j.task |
| 110 | } |
| 111 | if !found || j.actor != string(by) { |
| 112 | refusal = notCreator(attemptID) |
| 113 | break |
| 114 | } |
| 115 | if refusal, err = fn(tx, &j, a); err != nil { |
| 116 | return err |
| 117 | } |
| 118 | } |
| 119 | if refusal == nil { |
| 120 | return nil |
| 121 | } |
| 122 | a.Action, a.Reason = refused, refusal.Error() |
| 123 | return appendAudit(tx, a) |
| 124 | }) |
| 125 | if err != nil { |
| 126 | return err |
| 127 | } |
| 128 | return refusal |
| 129 | } |
| 130 | |
| 131 | // notPausable refuses, with isolatedjob.ErrConflict, a job that holds stop |
| 132 | // proof or has a stop request: neither may pause or resume. |
| 133 | func notPausable(j *pauseJob) error { |
| 134 | switch { |
| 135 | case j.stopProof.Valid: |
| 136 | return fmt.Errorf("%w: %s has stopped", isolatedjob.ErrConflict, j.attempt) |
| 137 | case j.stopRequested.Valid: |
| 138 | return fmt.Errorf("%w: a stop was asked for %s", isolatedjob.ErrConflict, j.attempt) |
| 139 | } |
| 140 | return nil |
| 141 | } |
| 142 | |
| 143 | // expire cancels j's open generation, inside tx, when it is draining with no |
| 144 | // quiescent acknowledgement and either more than PauseAckTimeout of |
| 145 | // controller time has passed since Drain, or Drain came before this process |
| 146 | // opened the store after a restart (at or before OpenedAt): the downtime is |
| 147 | // unknown, so the time since Drain is too, and a late acknowledgement could |
| 148 | // pass for an early one. Every call that touches a generation runs it first, |
| 149 | // so cancellation needs no timer; the reaper may sweep too. A generation |
| 150 | // acknowledged in time never expires. |
| 151 | func (c *Controller) expire(ctx context.Context, tx *sql.Tx, j *pauseJob, now T) error { |
| 152 | if j.state != JobDraining || j.cancelled || j.quiescent || !j.started.Valid { |
| 153 | return nil |
| 154 | } |
| 155 | why := fmt.Sprintf("no quiescent acknowledgement within %v", PauseAckTimeout) |
| 156 | switch { |
| 157 | case c.store.Restarted() && T(j.started.Int64) <= c.store.OpenedAt(): |
| 158 | why = "opened before the controller restarted and not acknowledged; the downtime is unknown" |
| 159 | case now-T(j.started.Int64) <= T(PauseAckTimeout): |
| 160 | return nil |
| 161 | } |
| 162 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET pause_cancelled = 1, revision = revision + 1 |
| 163 | WHERE attempt_id = ? AND pause_generation = ? AND pause_cancelled = 0`, j.attempt, j.generation) |
| 164 | if err != nil { |
| 165 | return fmt.Errorf("hostedctl: cancel pause of %s: %w", j.attempt, err) |
| 166 | } |
| 167 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 168 | return fmt.Errorf("hostedctl: cancel pause of %s: %d rows (%v)", j.attempt, n, err) |
| 169 | } |
| 170 | j.cancelled = true |
| 171 | return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: j.attempt, Action: actionPauseCancelled, |
| 172 | Reason: fmt.Sprintf("generation %d: %s; a late acknowledgement is ignored", j.generation, why), At: now}) |
| 173 | } |
| 174 | |
| 175 | // Drain opens a new pause generation for attemptID and returns it: the |
| 176 | // generation counter goes up by one, its start is the current controller |
| 177 | // time, and the job's state becomes JobDraining. Only a running job, or one |
| 178 | // already draining, may drain; draining again supersedes the open |
| 179 | // generation, so an acknowledgement for it is refused from then on. A job |
| 180 | // in any other state, or with a stop request or proof, gets |
| 181 | // isolatedjob.ErrConflict. |
| 182 | // |
| 183 | // Drain, Quiescent, Suspend, Reopen and Resume are for the instance key |
| 184 | // that launched the attempt (see creatorCall). Each call and each refusal |
| 185 | // appends an audit row, and each runs under the attempt's lock. |
| 186 | func (c *Controller) Drain(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID string) (int64, error) { |
| 187 | defer c.lockAttempt(attemptID)() |
| 188 | var gen int64 |
| 189 | err := c.creatorCall(ctx, by, key, attemptID, actionDrainRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { |
| 190 | gen = 0 |
| 191 | if r := notPausable(j); r != nil { |
| 192 | return r, nil |
| 193 | } |
| 194 | if j.state != JobRunning && j.state != JobDraining { |
| 195 | return fmt.Errorf("%w: only a running job can drain; %s is %s", isolatedjob.ErrConflict, j.attempt, j.state), nil |
| 196 | } |
| 197 | next := j.generation + 1 |
| 198 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, pause_generation = ?, pause_started_t = ?, |
| 199 | pause_quiescent = 0, pause_cancelled = 0, revision = revision + 1 |
| 200 | WHERE attempt_id = ? AND pause_generation = ?`, JobDraining, next, int64(a.At), j.attempt, j.generation) |
| 201 | if err != nil { |
| 202 | return nil, fmt.Errorf("hostedctl: drain %s: %w", j.attempt, err) |
| 203 | } |
| 204 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 205 | return nil, fmt.Errorf("hostedctl: drain %s: %d rows (%v)", j.attempt, n, err) |
| 206 | } |
| 207 | a.Action = actionDrain |
| 208 | a.Reason = fmt.Sprintf("pause generation %d opened; quiescent due within %v", next, PauseAckTimeout) |
| 209 | if j.state == JobDraining { |
| 210 | a.Reason += fmt.Sprintf("; generation %d superseded", j.generation) |
| 211 | } |
| 212 | gen = next |
| 213 | return nil, appendAudit(tx, a) |
| 214 | }) |
| 215 | if err != nil { |
| 216 | return 0, err |
| 217 | } |
| 218 | return gen, nil |
| 219 | } |
| 220 | |
| 221 | // Quiescent records the runner's acknowledgement that it has stopped taking |
| 222 | // work for generation. The generation must be the current one, open |
| 223 | // (draining), not cancelled, and the acknowledgement must come at most |
| 224 | // PauseAckTimeout after Drain; otherwise ErrGenerationCancelled, and a late |
| 225 | // acknowledgement also cancels the generation. Acknowledging the same |
| 226 | // generation again while its pause is open is accepted and changes nothing. |
| 227 | func (c *Controller) Quiescent(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID string, generation int64) error { |
| 228 | defer c.lockAttempt(attemptID)() |
| 229 | return c.creatorCall(ctx, by, key, attemptID, actionQuiescentRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { |
| 230 | if r := notPausable(j); r != nil { |
| 231 | return r, nil |
| 232 | } |
| 233 | if err := c.expire(ctx, tx, j, a.At); err != nil { |
| 234 | return nil, err |
| 235 | } |
| 236 | switch { |
| 237 | case !currentGen(generation, j): |
| 238 | return fmt.Errorf("%w: generation %d is not the current one (%d)", ErrGenerationCancelled, generation, j.generation), nil |
| 239 | case j.quiescent: |
| 240 | a.Action, a.Reason = actionQuiescentRepeated, fmt.Sprintf("generation %d acknowledged again", generation) |
| 241 | return nil, appendAudit(tx, a) |
| 242 | case j.cancelled: |
| 243 | return fmt.Errorf("%w: generation %d was cancelled", ErrGenerationCancelled, generation), nil |
| 244 | case j.state != JobDraining: |
| 245 | return fmt.Errorf("%w: no pause is open for generation %d; the job is %s", ErrGenerationCancelled, generation, j.state), nil |
| 246 | } |
| 247 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET pause_quiescent = 1, revision = revision + 1 |
| 248 | WHERE attempt_id = ? AND pause_generation = ? AND state = ?`, j.attempt, generation, JobDraining) |
| 249 | if err != nil { |
| 250 | return nil, fmt.Errorf("hostedctl: record quiescent for %s: %w", j.attempt, err) |
| 251 | } |
| 252 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 253 | return nil, fmt.Errorf("hostedctl: record quiescent for %s: %d rows (%v)", j.attempt, n, err) |
| 254 | } |
| 255 | a.Action, a.Reason = actionQuiescent, fmt.Sprintf("generation %d acknowledged after %v", generation, |
| 256 | time.Duration(a.At-T(j.started.Int64))) |
| 257 | return nil, appendAudit(tx, a) |
| 258 | }) |
| 259 | } |
| 260 | |
| 261 | // Suspend suspends attemptID's VM for generation. The generation must be |
| 262 | // the current one and open, not cancelled (ErrGenerationCancelled), and |
| 263 | // acknowledged quiescent (ErrNotQuiescent). One transaction records the |
| 264 | // state JobSuspending; then, outside it, Runner.Suspend. A failed provider |
| 265 | // call is audited and returned; the job stays suspending and Refresh sends |
| 266 | // the suspend again while the VM still runs. Refresh moves the job to |
| 267 | // JobSuspended once the provider reports the VM suspended. Asking again for |
| 268 | // a generation already suspending or suspended returns nil with no provider |
| 269 | // call. |
| 270 | func (c *Controller) Suspend(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID string, generation int64) error { |
| 271 | defer c.lockAttempt(attemptID)() |
| 272 | var send *pauseJob |
| 273 | err := c.creatorCall(ctx, by, key, attemptID, actionSuspendRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { |
| 274 | send = nil |
| 275 | if r := notPausable(j); r != nil { |
| 276 | return r, nil |
| 277 | } |
| 278 | if err := c.expire(ctx, tx, j, a.At); err != nil { |
| 279 | return nil, err |
| 280 | } |
| 281 | if !currentGen(generation, j) { |
| 282 | return fmt.Errorf("%w: generation %d is not the current one (%d)", ErrGenerationCancelled, generation, j.generation), nil |
| 283 | } |
| 284 | switch j.state { |
| 285 | case JobSuspending, JobSuspended: |
| 286 | a.Action, a.Reason = actionSuspendRepeated, fmt.Sprintf("generation %d: suspend asked for again; job is %s", generation, j.state) |
| 287 | return nil, appendAudit(tx, a) |
| 288 | case JobDraining: |
| 289 | default: |
| 290 | return fmt.Errorf("%w: no pause is open for generation %d; the job is %s", ErrGenerationCancelled, generation, j.state), nil |
| 291 | } |
| 292 | if j.cancelled { |
| 293 | return fmt.Errorf("%w: generation %d was cancelled", ErrGenerationCancelled, generation), nil |
| 294 | } |
| 295 | if !j.quiescent { |
| 296 | return fmt.Errorf("%w: generation %d", ErrNotQuiescent, generation), nil |
| 297 | } |
| 298 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 |
| 299 | WHERE attempt_id = ? AND state = ? AND pause_generation = ?`, JobSuspending, j.attempt, JobDraining, generation) |
| 300 | if err != nil { |
| 301 | return nil, fmt.Errorf("hostedctl: record suspend of %s: %w", j.attempt, err) |
| 302 | } |
| 303 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 304 | return nil, fmt.Errorf("hostedctl: record suspend of %s: %d rows (%v)", j.attempt, n, err) |
| 305 | } |
| 306 | a.Action, a.Reason = actionSuspendRequested, fmt.Sprintf("generation %d quiescent; suspending VM %s", generation, j.ref.String) |
| 307 | send = j |
| 308 | return nil, appendAudit(tx, a) |
| 309 | }) |
| 310 | if err != nil || send == nil { |
| 311 | return err |
| 312 | } |
| 313 | perr, aerr := c.sendSuspend(ctx, by, send, "") |
| 314 | return errors.Join(perr, aerr) |
| 315 | } |
| 316 | |
| 317 | // sendSuspend calls Runner.Suspend for j's VM, outside any transaction. A |
| 318 | // failure is audited, with a fixed reason, and returned as perr; aerr is a |
| 319 | // failure to write the audit row. resent names the audit action for a |
| 320 | // successful call, or is empty for none. |
| 321 | func (c *Controller) sendSuspend(ctx context.Context, actor hostedwire.KeyID, j *pauseJob, resent string) (perr, aerr error) { |
| 322 | ref := isolatedjob.Ref(j.ref.String) |
| 323 | perr = c.runner.Suspend(ctx, ref) |
| 324 | action, reason := resent, "refresh: the VM still runs; suspend sent again" |
| 325 | if perr != nil { |
| 326 | action, reason = actionSuspendFailed, "provider suspend call failed; refresh sends it again while the VM runs" |
| 327 | } |
| 328 | if action != "" { |
| 329 | aerr = c.auditPause(context.WithoutCancel(ctx), actor, j, action, reason) |
| 330 | } |
| 331 | if perr != nil { |
| 332 | perr = fmt.Errorf("hostedctl: suspend %s: VM %s: %w", j.attempt, ref, perr) |
| 333 | } |
| 334 | return perr, aerr |
| 335 | } |
| 336 | |
| 337 | // Reopen records that the runner takes work again after a cancelled or |
| 338 | // abandoned pause of generation, the current one (else |
| 339 | // ErrGenerationCancelled). The job returns to JobRunning and its pause |
| 340 | // fields are cleared; the generation counter stays. A job whose times wait |
| 341 | // for the first Refresh after a restart (ageUnsettled) gets |
| 342 | // isolatedjob.ErrConflict, so its stop time is judged only once re-based. |
| 343 | // Once the job's stop time has come admission never reopens |
| 344 | // (ErrPastDeadline). A job already |
| 345 | // running at that generation gets nil; a suspending, suspended or resuming |
| 346 | // job gets isolatedjob.ErrConflict, as its VM is paused and needs Resume. |
| 347 | func (c *Controller) Reopen(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID string, generation int64) error { |
| 348 | defer c.lockAttempt(attemptID)() |
| 349 | return c.creatorCall(ctx, by, key, attemptID, actionReopenRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { |
| 350 | if r := notPausable(j); r != nil { |
| 351 | return r, nil |
| 352 | } |
| 353 | if err := c.expire(ctx, tx, j, a.At); err != nil { |
| 354 | return nil, err |
| 355 | } |
| 356 | if !currentGen(generation, j) { |
| 357 | return fmt.Errorf("%w: generation %d is not the current one (%d)", ErrGenerationCancelled, generation, j.generation), nil |
| 358 | } |
| 359 | if c.ageUnsettled(j) { |
| 360 | return fmt.Errorf("%w: the job's times wait for the first refresh after a restart; ask again", isolatedjob.ErrConflict), nil |
| 361 | } |
| 362 | if pastStop(j, a.At) { |
| 363 | return fmt.Errorf("%w: %v ago; admission stays closed", ErrPastDeadline, time.Duration(a.At-T(j.stopT))), nil |
| 364 | } |
| 365 | switch j.state { |
| 366 | case JobRunning: |
| 367 | a.Action, a.Reason = actionReopenRepeated, fmt.Sprintf("generation %d: admission already open", generation) |
| 368 | return nil, appendAudit(tx, a) |
| 369 | case JobDraining: |
| 370 | default: |
| 371 | return fmt.Errorf("%w: %s is %s; it needs a resume, not a reopen", isolatedjob.ErrConflict, j.attempt, j.state), nil |
| 372 | } |
| 373 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, pause_started_t = NULL, pause_quiescent = 0, |
| 374 | pause_cancelled = 0, revision = revision + 1 WHERE attempt_id = ? AND state = ? AND pause_generation = ?`, |
| 375 | JobRunning, j.attempt, JobDraining, generation) |
| 376 | if err != nil { |
| 377 | return nil, fmt.Errorf("hostedctl: reopen %s: %w", j.attempt, err) |
| 378 | } |
| 379 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 380 | return nil, fmt.Errorf("hostedctl: reopen %s: %d rows (%v)", j.attempt, n, err) |
| 381 | } |
| 382 | why := "abandoned" |
| 383 | if j.cancelled { |
| 384 | why = "cancelled" |
| 385 | } |
| 386 | a.Action, a.Reason = actionReopen, fmt.Sprintf("generation %d %s; the runner takes work again", generation, why) |
| 387 | return nil, appendAudit(tx, a) |
| 388 | }) |
| 389 | } |
| 390 | |