| 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 | // ErrResumePending: a resume operation is prepared but not committed: the |
| 15 | // VM does not run yet, or the provider call failed or its reply was lost. |
| 16 | // Retry with the same operation ID; Refresh also finishes it. A new |
| 17 | // operation ID while another is pending gets it too. |
| 18 | var ErrResumePending = errors.New("hostedctl: a resume is pending; retry with its operation ID") |
| 19 | |
| 20 | // maxOperationIDLen bounds a resume operation ID. |
| 21 | const maxOperationIDLen = 64 |
| 22 | |
| 23 | // resume_ops.status values. |
| 24 | const ( |
| 25 | opPending = "pending" |
| 26 | opDone = "done" |
| 27 | opFailed = "failed" |
| 28 | ) |
| 29 | |
| 30 | // Audit actions written by Resume and by Refresh finishing a resume. |
| 31 | const ( |
| 32 | actionResumePrepared = "resume_prepared" |
| 33 | actionResumeContinued = "resume_continued" |
| 34 | actionResumeRepeated = "resume_repeated" |
| 35 | actionResumeRefused = "resume_refused" |
| 36 | actionResumeCallFailed = "resume_call_failed" |
| 37 | actionResumeResent = "resume_resent" |
| 38 | actionResumeCommitted = "resume_committed" |
| 39 | actionResumeFailed = "resume_failed" |
| 40 | ) |
| 41 | |
| 42 | // resumeOp is one resume_ops row. |
| 43 | type resumeOp struct { |
| 44 | id, status string |
| 45 | prepared int64 |
| 46 | result sql.NullInt64 |
| 47 | } |
| 48 | |
| 49 | // validOperationID reports whether s is 1 to maxOperationIDLen characters, |
| 50 | // each a letter, a digit or '-'. |
| 51 | func validOperationID(s string) bool { |
| 52 | if len(s) == 0 || len(s) > maxOperationIDLen { |
| 53 | return false |
| 54 | } |
| 55 | for i := 0; i < len(s); i++ { |
| 56 | switch b := s[i]; { |
| 57 | case b >= 'a' && b <= 'z', b >= 'A' && b <= 'Z', b >= '0' && b <= '9', b == '-': |
| 58 | default: |
| 59 | return false |
| 60 | } |
| 61 | } |
| 62 | return true |
| 63 | } |
| 64 | |
| 65 | // loadResumeOp reads the row for (attempt, op) inside tx, whatever other |
| 66 | // operations the attempt has had since. |
| 67 | func loadResumeOp(ctx context.Context, tx *sql.Tx, attempt, op string) (resumeOp, bool, error) { |
| 68 | r := resumeOp{id: op} |
| 69 | err := tx.QueryRowContext(ctx, `SELECT status, prepared_epoch, result_epoch FROM resume_ops |
| 70 | WHERE attempt_id = ? AND operation_id = ?`, attempt, op).Scan(&r.status, &r.prepared, &r.result) |
| 71 | switch { |
| 72 | case errors.Is(err, sql.ErrNoRows): |
| 73 | return resumeOp{}, false, nil |
| 74 | case err != nil: |
| 75 | return resumeOp{}, false, fmt.Errorf("hostedctl: read resume operation %s of %s: %w", op, attempt, err) |
| 76 | } |
| 77 | return r, true, nil |
| 78 | } |
| 79 | |
| 80 | // pendingResumeOp reads attempt's pending resume row, if any (at most one). |
| 81 | func pendingResumeOp(ctx context.Context, tx *sql.Tx, attempt string) (resumeOp, bool, error) { |
| 82 | r := resumeOp{status: opPending} |
| 83 | err := tx.QueryRowContext(ctx, `SELECT operation_id, prepared_epoch FROM resume_ops |
| 84 | WHERE attempt_id = ? AND status = ?`, attempt, opPending).Scan(&r.id, &r.prepared) |
| 85 | switch { |
| 86 | case errors.Is(err, sql.ErrNoRows): |
| 87 | return resumeOp{}, false, nil |
| 88 | case err != nil: |
| 89 | return resumeOp{}, false, fmt.Errorf("hostedctl: read pending resume of %s: %w", attempt, err) |
| 90 | } |
| 91 | return r, true, nil |
| 92 | } |
| 93 | |
| 94 | // failPendingResume marks attempt's pending resume, if any, failed inside |
| 95 | // tx, with an audit row giving why. The row stays, so a retry of its |
| 96 | // operation ID is refused rather than prepared again. writeProof calls it, |
| 97 | // so every proof path fails a pending resume in the transaction that saves |
| 98 | // the proof. |
| 99 | func failPendingResume(ctx context.Context, tx *sql.Tx, account, task, attempt string, now T, why string) error { |
| 100 | res, err := tx.ExecContext(ctx, `UPDATE resume_ops SET status = ?, completed_t = ? |
| 101 | WHERE attempt_id = ? AND status = ?`, opFailed, int64(now), attempt, opPending) |
| 102 | if err != nil { |
| 103 | return fmt.Errorf("hostedctl: fail pending resume of %s: %w", attempt, err) |
| 104 | } |
| 105 | if n, err := res.RowsAffected(); err != nil || n == 0 { |
| 106 | return err |
| 107 | } |
| 108 | return appendAudit(tx, Audit{Account: account, Task: task, Attempt: attempt, Action: actionResumeFailed, |
| 109 | Reason: why, At: now}) |
| 110 | } |
| 111 | |
| 112 | // failDeadResume marks j's pending resume failed, inside tx, when the job |
| 113 | // holds stop proof or has a stop request: that resume is never committed. |
| 114 | func failDeadResume(ctx context.Context, tx *sql.Tx, j *pauseJob, now T) error { |
| 115 | if !j.stopProof.Valid && !j.stopRequested.Valid { |
| 116 | return nil |
| 117 | } |
| 118 | return failPendingResume(ctx, tx, j.account, j.task, j.attempt, now, |
| 119 | "a stop was asked for before the pending resume committed") |
| 120 | } |
| 121 | |
| 122 | // failResumeAtDeadline marks j's pending resume failed, inside tx, because |
| 123 | // the job's stop time has come: a resume never commits past it and the |
| 124 | // provider is not called again. observed is the VM state just read, or |
| 125 | // empty when none was: a live one becomes the state of a resuming job (the |
| 126 | // epoch is not raised) and clears notfound_since_t. With none the job stays |
| 127 | // resuming, with no pending row, and the next Refresh mirrors the VM. |
| 128 | func failResumeAtDeadline(ctx context.Context, tx *sql.Tx, j *pauseJob, now T, observed isolatedjob.State) error { |
| 129 | if err := failPendingResume(ctx, tx, j.account, j.task, j.attempt, now, |
| 130 | fmt.Sprintf("stop time passed %v ago before the pending resume committed", time.Duration(now-T(j.stopT)))); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | if !observed.Live() { |
| 134 | return nil |
| 135 | } |
| 136 | if _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 |
| 137 | WHERE attempt_id = ? AND state = ?`, string(observed), j.attempt, JobResuming); err != nil { |
| 138 | return fmt.Errorf("hostedctl: settle resume of %s at its stop time: %w", j.attempt, err) |
| 139 | } |
| 140 | return clearNotFound(ctx, tx, j.attempt) |
| 141 | } |
| 142 | |
| 143 | // clearNotFound drops attempt's first not-found inside tx: a live VM was |
| 144 | // just seen, so it no longer counts towards stop proof. The job's state is |
| 145 | // left alone. |
| 146 | func clearNotFound(ctx context.Context, tx *sql.Tx, attempt string) error { |
| 147 | if _, err := tx.ExecContext(ctx, `UPDATE jobs SET notfound_since_t = NULL, revision = revision + 1 |
| 148 | WHERE attempt_id = ? AND notfound_since_t IS NOT NULL`, attempt); err != nil { |
| 149 | return fmt.Errorf("hostedctl: clear not-found of %s: %w", attempt, err) |
| 150 | } |
| 151 | return nil |
| 152 | } |
| 153 | |
| 154 | // ageUnsettled reports whether j existed before this process opened the |
| 155 | // store and Refresh has not yet re-based its times from the provider's age |
| 156 | // (or stopped it as elapsed_unknown): until then its stop time is not to be |
| 157 | // trusted, so no resume is driven for it. It is refreshOne's test for an |
| 158 | // untrusted elapsed time. |
| 159 | func (c *Controller) ageUnsettled(j *pauseJob) bool { |
| 160 | return c.store.Restarted() && T(j.launchedT) <= c.store.OpenedAt() && !c.rebased.has(j.attempt) |
| 161 | } |
| 162 | |
| 163 | // pastStop reports whether j's stop time has come at now. |
| 164 | func pastStop(j *pauseJob, now T) bool { return now >= T(j.stopT) } |
| 165 | |
| 166 | // commitResume is step 3 inside tx, once the provider reports the VM |
| 167 | // running: the job's epoch becomes op's prepared epoch, which must be one |
| 168 | // above the stored epoch, the job is running with its pause closed (the |
| 169 | // generation counter stays), and op is done with that epoch. op must be |
| 170 | // pending, so an operation raises the epoch at most once. |
| 171 | func commitResume(ctx context.Context, tx *sql.Tx, j *pauseJob, op resumeOp, actor hostedwire.KeyID, now T) error { |
| 172 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET epoch = ?, state = ?, pause_started_t = NULL, pause_quiescent = 0, |
| 173 | pause_cancelled = 0, notfound_since_t = NULL, revision = revision + 1 WHERE attempt_id = ? AND epoch = ?`, |
| 174 | op.prepared, JobRunning, j.attempt, op.prepared-1) |
| 175 | if err != nil { |
| 176 | return fmt.Errorf("hostedctl: commit resume of %s: %w", j.attempt, err) |
| 177 | } |
| 178 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 179 | 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) |
| 180 | } |
| 181 | res, err = tx.ExecContext(ctx, `UPDATE resume_ops SET status = ?, result_epoch = ?, completed_t = ? |
| 182 | WHERE attempt_id = ? AND operation_id = ? AND status = ?`, opDone, op.prepared, int64(now), j.attempt, op.id, opPending) |
| 183 | if err != nil { |
| 184 | return fmt.Errorf("hostedctl: commit resume of %s: %w", j.attempt, err) |
| 185 | } |
| 186 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 187 | return fmt.Errorf("hostedctl: commit resume %s of %s: %d rows (%v)", op.id, j.attempt, n, err) |
| 188 | } |
| 189 | return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt, |
| 190 | Action: actionResumeCommitted, Reason: fmt.Sprintf("operation %s: the VM runs; epoch %d", op.id, op.prepared), At: now}) |
| 191 | } |
| 192 | |
| 193 | // Resume resumes attemptID's suspended VM under operationID (1 to 64 |
| 194 | // letters, digits and '-') and returns the job's new epoch. An operation |
| 195 | // raises the epoch exactly once, however often it is retried. Under the |
| 196 | // attempt's lock, in three steps: |
| 197 | // |
| 198 | // 1. Prepare, in one transaction. A done operation returns its epoch with |
| 199 | // no provider call, whatever operations came after it; a failed one |
| 200 | // gets isolatedjob.ErrConflict. Then a stop request or proof gives |
| 201 | // ErrConflict; a job whose times wait for the first Refresh after a |
| 202 | // restart (ageUnsettled) gives ErrResumePending; the job's stop time |
| 203 | // reached gives ErrPastDeadline, |
| 204 | // with no provider call and no new row; a pending operation is failed |
| 205 | // then. A pending operation carries on with its prepared epoch. A new operation while another is pending |
| 206 | // gets ErrResumePending; one for a job that is not suspended gets |
| 207 | // ErrConflict. Otherwise a pending row with prepared epoch = epoch + 1 |
| 208 | // is saved and the job becomes JobResuming. |
| 209 | // 2. Outside any transaction, the stop time checked again, then |
| 210 | // Runner.Resume. A failure is audited and returned wrapped in |
| 211 | // ErrResumePending; the row stays pending. |
| 212 | // 3. Runner.Get, then finishResume. Terminal: the stop proof is saved, |
| 213 | // failing the row in the same transaction, and ErrConflict returned. |
| 214 | // The stop time come meanwhile: the row is failed, ErrPastDeadline. |
| 215 | // Running: one transaction sets the job's epoch to the prepared one and |
| 216 | // marks the row done (commitResume). Anything else, still suspended |
| 217 | // included (the provider reports suspended while the VM's resume hook |
| 218 | // runs): ErrResumePending, epoch 0. Every live reading clears |
| 219 | // notfound_since_t, so a stale not-found never combines with a later |
| 220 | // one into stop proof. |
| 221 | // |
| 222 | // New-epoch credentials come from the prepared epoch, so the resume hook |
| 223 | // can finish before the commit. After a crash or a lost reply, a retry with |
| 224 | // the same ID or Refresh (mirrorLive) finishes the operation. |
| 225 | func (c *Controller) Resume(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID, operationID string) (int64, error) { |
| 226 | defer c.lockAttempt(attemptID)() |
| 227 | var epoch int64 |
| 228 | var send *pauseJob |
| 229 | var op resumeOp |
| 230 | err := c.creatorCall(ctx, by, key, attemptID, actionResumeRefused, func(tx *sql.Tx, j *pauseJob, a Audit) (error, error) { |
| 231 | epoch, send = 0, nil |
| 232 | if !validOperationID(operationID) { |
| 233 | return fmt.Errorf("%w: operation id must be 1 to %d letters, digits or '-'", isolatedjob.ErrInvalid, maxOperationIDLen), nil |
| 234 | } |
| 235 | if err := failDeadResume(ctx, tx, j, a.At); err != nil { |
| 236 | return nil, err |
| 237 | } |
| 238 | o, found, err := loadResumeOp(ctx, tx, j.attempt, operationID) |
| 239 | if err != nil { |
| 240 | return nil, err |
| 241 | } |
| 242 | switch { |
| 243 | case found && o.status == opDone: |
| 244 | epoch = o.result.Int64 |
| 245 | a.Action, a.Reason = actionResumeRepeated, fmt.Sprintf("operation %s already done at epoch %d", operationID, epoch) |
| 246 | return nil, appendAudit(tx, a) |
| 247 | case found && o.status != opPending: |
| 248 | return fmt.Errorf("%w: resume operation %s failed", isolatedjob.ErrConflict, operationID), nil |
| 249 | } |
| 250 | if r := notPausable(j); r != nil { |
| 251 | return r, nil |
| 252 | } |
| 253 | if c.ageUnsettled(j) { |
| 254 | return fmt.Errorf("%w: the job's times wait for the first refresh after a restart", ErrResumePending), nil |
| 255 | } |
| 256 | if pastStop(j, a.At) { |
| 257 | if found { // pending: it never commits now |
| 258 | if err := failResumeAtDeadline(ctx, tx, j, a.At, ""); err != nil { |
| 259 | return nil, err |
| 260 | } |
| 261 | } |
| 262 | return fmt.Errorf("%w: %v ago", ErrPastDeadline, time.Duration(a.At-T(j.stopT))), nil |
| 263 | } |
| 264 | if found { |
| 265 | a.Action, a.Reason = actionResumeContinued, fmt.Sprintf("operation %s pending at epoch %d; resume sent again", operationID, o.prepared) |
| 266 | op, send = o, j |
| 267 | return nil, appendAudit(tx, a) |
| 268 | } |
| 269 | other, busy, err := pendingResumeOp(ctx, tx, j.attempt) |
| 270 | if err != nil { |
| 271 | return nil, err |
| 272 | } |
| 273 | if busy { |
| 274 | return fmt.Errorf("%w: operation %s is pending", ErrResumePending, other.id), nil |
| 275 | } |
| 276 | if j.state != JobSuspended { |
| 277 | return fmt.Errorf("%w: only a suspended job can resume; %s is %s", isolatedjob.ErrConflict, j.attempt, j.state), nil |
| 278 | } |
| 279 | o = resumeOp{id: operationID, status: opPending, prepared: j.epoch + 1} |
| 280 | if _, err := tx.ExecContext(ctx, `INSERT INTO resume_ops (attempt_id, operation_id, status, prepared_epoch, prepared_t) |
| 281 | VALUES (?, ?, ?, ?, ?)`, j.attempt, operationID, opPending, o.prepared, int64(a.At)); err != nil { |
| 282 | return nil, fmt.Errorf("hostedctl: prepare resume of %s: %w", j.attempt, err) |
| 283 | } |
| 284 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 |
| 285 | WHERE attempt_id = ? AND state = ? AND epoch = ?`, JobResuming, j.attempt, JobSuspended, j.epoch) |
| 286 | if err != nil { |
| 287 | return nil, fmt.Errorf("hostedctl: prepare resume of %s: %w", j.attempt, err) |
| 288 | } |
| 289 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 290 | return nil, fmt.Errorf("hostedctl: prepare resume of %s: %d rows (%v)", j.attempt, n, err) |
| 291 | } |
| 292 | a.Action, a.Reason = actionResumePrepared, fmt.Sprintf("operation %s prepared at epoch %d", operationID, o.prepared) |
| 293 | op, send = o, j |
| 294 | return nil, appendAudit(tx, a) |
| 295 | }) |
| 296 | if err != nil { |
| 297 | return 0, err |
| 298 | } |
| 299 | if send == nil { |
| 300 | return epoch, nil |
| 301 | } |
| 302 | return c.driveResume(ctx, by, send, op) |
| 303 | } |
| 304 | |
| 305 | // driveResume is Resume's steps 2 and 3 for a prepared or pending op. The |
| 306 | // stop time is checked again just before the provider call and again in |
| 307 | // the transaction that would commit (finishResume), so time that passes |
| 308 | // during the calls cannot let a resume commit past it. |
| 309 | func (c *Controller) driveResume(ctx context.Context, actor hostedwire.KeyID, j *pauseJob, op resumeOp) (int64, error) { |
| 310 | ref := isolatedjob.Ref(j.ref.String) |
| 311 | rec := context.WithoutCancel(ctx) // record what the provider said even if the caller has gone |
| 312 | if now := c.store.Clock().Now(); pastStop(j, now) { |
| 313 | return c.finishResume(rec, actor, j, op.id, "", now) |
| 314 | } |
| 315 | if perr := c.runner.Resume(ctx, ref); perr != nil { |
| 316 | aerr := c.auditPause(rec, actor, j, actionResumeCallFailed, |
| 317 | fmt.Sprintf("operation %s: provider resume call failed; the operation stays pending", op.id)) |
| 318 | return 0, errors.Join(fmt.Errorf("%w: operation %s: resume VM %s: %w", ErrResumePending, op.id, ref, perr), aerr) |
| 319 | } |
| 320 | job, gerr := c.runner.Get(ctx, ref) |
| 321 | at := c.store.Clock().Now() |
| 322 | if gerr != nil { |
| 323 | return 0, fmt.Errorf("%w: operation %s: read VM %s: %w", ErrResumePending, op.id, ref, gerr) |
| 324 | } |
| 325 | return c.finishResume(rec, actor, j, op.id, job.State, at) |
| 326 | } |
| 327 | |
| 328 | // finishResume settles operation opID of j's attempt from the VM state st |
| 329 | // that a Get ending at at reported, or from no reading when st is empty. |
| 330 | // |
| 331 | // - Terminal: the stop proof is saved, which fails the pending operation |
| 332 | // in the same transaction (writeProof); isolatedjob.ErrConflict. |
| 333 | // - The job's stop time has come: the operation is failed |
| 334 | // (failResumeAtDeadline); ErrPastDeadline. |
| 335 | // - Running: commitResume; the epoch. |
| 336 | // - Any other state: a live one clears notfound_since_t, the controller |
| 337 | // state untouched; ErrResumePending. |
| 338 | // |
| 339 | // An operation already done returns its epoch; a failed one ErrConflict. |
| 340 | func (c *Controller) finishResume(ctx context.Context, actor hostedwire.KeyID, j *pauseJob, opID string, st isolatedjob.State, at T) (int64, error) { |
| 341 | attempt := j.attempt |
| 342 | if st.Terminal() { |
| 343 | if _, err := c.recordProof(ctx, actor, attempt, StopProof{AttemptID: attempt, VMRef: isolatedjob.Ref(j.ref.String), |
| 344 | State: st, ObservedAt: at}, "resume: provider reports the VM "+string(st)); err != nil { |
| 345 | return 0, err |
| 346 | } |
| 347 | return 0, fmt.Errorf("%w: VM is %s; resume operation %s failed", isolatedjob.ErrConflict, st, opID) |
| 348 | } |
| 349 | var epoch int64 |
| 350 | var refusal error |
| 351 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 352 | epoch, refusal = 0, nil |
| 353 | p, found, err := loadPauseJob(ctx, tx, attempt) |
| 354 | if err != nil { |
| 355 | return err |
| 356 | } |
| 357 | if !found { |
| 358 | return fmt.Errorf("hostedctl: resume %s: job is missing", attempt) |
| 359 | } |
| 360 | now := c.store.Clock().Now() |
| 361 | if err := failDeadResume(ctx, tx, &p, now); err != nil { |
| 362 | return err |
| 363 | } |
| 364 | op, found, err := loadResumeOp(ctx, tx, attempt, opID) |
| 365 | switch { |
| 366 | case err != nil: |
| 367 | return err |
| 368 | case !found: |
| 369 | return fmt.Errorf("hostedctl: resume %s: operation %s is missing", attempt, opID) |
| 370 | case op.status == opDone: |
| 371 | epoch = op.result.Int64 |
| 372 | return nil |
| 373 | case op.status != opPending: |
| 374 | refusal = fmt.Errorf("%w: resume operation %s failed", isolatedjob.ErrConflict, opID) |
| 375 | return nil |
| 376 | case pastStop(&p, now): |
| 377 | refusal = fmt.Errorf("%w: %v ago; resume operation %s failed", ErrPastDeadline, time.Duration(now-T(p.stopT)), opID) |
| 378 | return failResumeAtDeadline(ctx, tx, &p, now, st) |
| 379 | case st == isolatedjob.StateRunning: |
| 380 | epoch = op.prepared |
| 381 | return commitResume(ctx, tx, &p, op, actor, now) |
| 382 | } |
| 383 | refusal = fmt.Errorf("%w: operation %s: VM %s is %s", ErrResumePending, opID, p.ref.String, st) |
| 384 | if !st.Live() { |
| 385 | return nil |
| 386 | } |
| 387 | return clearNotFound(ctx, tx, attempt) |
| 388 | }) |
| 389 | if err != nil { |
| 390 | return 0, err |
| 391 | } |
| 392 | return epoch, refusal |
| 393 | } |
| 394 | |
| 395 | // auditPause writes one audit row about j in a short transaction. |
| 396 | func (c *Controller) auditPause(ctx context.Context, actor hostedwire.KeyID, j *pauseJob, action, reason string) error { |
| 397 | return c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 398 | return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt, |
| 399 | Action: action, Reason: reason, At: c.store.Clock().Now()}) |
| 400 | }) |
| 401 | } |
| 402 | |
| 403 | // pauseState reports whether state is one the controller sets for the pause |
| 404 | // barrier or a resume and settles itself: Refresh never overwrites it with |
| 405 | // the VM's live state. |
| 406 | func pauseState(state string) bool { |
| 407 | return state == JobDraining || state == JobSuspending || state == JobResuming |
| 408 | } |
| 409 | |
| 410 | // mirrorLive is Refresh's hook for the pause barrier and resumes. refreshOne |
| 411 | // calls it, in place of mirrorState, with j as it read the job under the |
| 412 | // attempt's lock (so j is current; the hook does not take the lock again) |
| 413 | // and the live state st that Get just reported. No transaction is held |
| 414 | // across a provider call. |
| 415 | // |
| 416 | // A job in none of the pause states, with no stop request, is mirrored as |
| 417 | // before. A job with a stop request is mirrored too, as the stop wins, and |
| 418 | // its pending resume, if any, is marked failed. Otherwise the job's state |
| 419 | // is left alone (a live sighting still clears notfound_since_t, as |
| 420 | // mirrorState does) and only the transitions the controller expects are |
| 421 | // settled: |
| 422 | // |
| 423 | // - draining: the generation is cancelled if its acknowledgement is late; |
| 424 | // - suspending: a suspended VM makes the job JobSuspended; a VM still |
| 425 | // running gets Runner.Suspend again (the first call may never have |
| 426 | // reached the provider), unless the stop time has come; |
| 427 | // - resuming: once the stop time has come the pending operation is |
| 428 | // failed and the job takes the VM's state, with no provider call and no |
| 429 | // commit (failResumeAtDeadline). Before it, a running VM commits the |
| 430 | // pending operation (commitResume) and a suspended one gets |
| 431 | // Runner.Resume again. |
| 432 | // |
| 433 | // While the job's age is unsettled after a restart (ageUnsettled, refreshOne's |
| 434 | // untrusted test), only the not-found marker is cleared: refreshOne re-bases |
| 435 | // the job's times from the provider's age, or stops it as elapsed_unknown, |
| 436 | // right after the hook, and recovery waits for the next pass, so it is |
| 437 | // judged against the settled stop time. |
| 438 | // |
| 439 | // Every live sighting clears notfound_since_t before the hook returns, so |
| 440 | // refreshOne's restart handling after it sees the cleared value. A provider |
| 441 | // call the hook makes that fails is audited and sent again next pass, not |
| 442 | // returned: only store errors are, so a failing re-send never holds up |
| 443 | // refreshOne's restart handling. Unknown states never get here, so a |
| 444 | // pending resume stays pending for the next pass; a terminal VM gets proof |
| 445 | // from refreshOne, which fails its pending resume in the same transaction |
| 446 | // (writeProof). |
| 447 | // |
| 448 | // Provider calls get call, the caller's context, so they end when it does; |
| 449 | // store writes use a detached copy, so what Get saw is recorded even then. |
| 450 | func (c *Controller) mirrorLive(call context.Context, j jobRow, st isolatedjob.State) error { |
| 451 | ctx := context.WithoutCancel(call) |
| 452 | if !pauseState(j.state) && !j.stopRequested.Valid { |
| 453 | return c.mirrorState(ctx, j.attempt, st) |
| 454 | } |
| 455 | var next func() error |
| 456 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 457 | next = nil |
| 458 | p, found, err := loadPauseJob(ctx, tx, j.attempt) |
| 459 | if err != nil || !found || p.stopProof.Valid { |
| 460 | return err |
| 461 | } |
| 462 | now := c.store.Clock().Now() |
| 463 | if p.stopRequested.Valid || !pauseState(p.state) { |
| 464 | next = func() error { return c.mirrorState(ctx, p.attempt, st) } |
| 465 | return failDeadResume(ctx, tx, &p, now) |
| 466 | } |
| 467 | if err := clearNotFound(ctx, tx, p.attempt); err != nil || c.ageUnsettled(&p) { |
| 468 | return err |
| 469 | } |
| 470 | a := Audit{Account: p.account, Task: p.task, Attempt: p.attempt, At: now} |
| 471 | switch { |
| 472 | case p.state == JobDraining: |
| 473 | return c.expire(ctx, tx, &p, now) |
| 474 | case p.state == JobSuspending && st == isolatedjob.StateSuspended: |
| 475 | if _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1 |
| 476 | WHERE attempt_id = ? AND state = ?`, JobSuspended, p.attempt, JobSuspending); err != nil { |
| 477 | return fmt.Errorf("hostedctl: settle suspend of %s: %w", p.attempt, err) |
| 478 | } |
| 479 | a.Action, a.Reason = actionSuspendSettled, fmt.Sprintf("generation %d: provider reports the VM suspended", p.generation) |
| 480 | return appendAudit(tx, a) |
| 481 | case p.state == JobSuspending && st == isolatedjob.StateRunning && !pastStop(&p, now): |
| 482 | next = func() error { |
| 483 | _, aerr := c.sendSuspend(call, "", &p, actionSuspendResent) // a failed call is audited and sent again next pass |
| 484 | return aerr |
| 485 | } |
| 486 | return nil |
| 487 | case p.state != JobResuming: |
| 488 | return nil |
| 489 | } |
| 490 | op, ok, err := pendingResumeOp(ctx, tx, p.attempt) |
| 491 | switch { |
| 492 | case err != nil: |
| 493 | return err |
| 494 | case !ok: // nothing to finish; the VM's own state is the best record |
| 495 | next = func() error { return c.mirrorState(ctx, p.attempt, st) } |
| 496 | return nil |
| 497 | case pastStop(&p, now): |
| 498 | return failResumeAtDeadline(ctx, tx, &p, now, st) |
| 499 | case st == isolatedjob.StateRunning: |
| 500 | return commitResume(ctx, tx, &p, op, "", now) |
| 501 | case st == isolatedjob.StateSuspended: |
| 502 | next = func() error { return c.resendResume(call, &p, op) } |
| 503 | } |
| 504 | return nil |
| 505 | }) |
| 506 | if err != nil || next == nil { |
| 507 | return err |
| 508 | } |
| 509 | return next() |
| 510 | } |
| 511 | |
| 512 | // resendResume is Refresh sending the provider resume again for j's |
| 513 | // pending op while the VM still reports suspended. The stop time is checked |
| 514 | // again just before the call; once it has come there is no call and the |
| 515 | // next pass fails the operation. The call's outcome is audited; only a |
| 516 | // failure to write that row is returned. A failed call is sent again on |
| 517 | // the next pass. |
| 518 | func (c *Controller) resendResume(ctx context.Context, j *pauseJob, op resumeOp) error { |
| 519 | if pastStop(j, c.store.Clock().Now()) { |
| 520 | return nil |
| 521 | } |
| 522 | perr := c.runner.Resume(ctx, isolatedjob.Ref(j.ref.String)) |
| 523 | rec := context.WithoutCancel(ctx) |
| 524 | if perr != nil { |
| 525 | return c.auditPause(rec, "", j, actionResumeCallFailed, |
| 526 | fmt.Sprintf("refresh: operation %s: provider resume call failed; the operation stays pending", op.id)) |
| 527 | } |
| 528 | return c.auditPause(rec, "", j, actionResumeResent, fmt.Sprintf("refresh: operation %s pending; the VM still reports suspended, resume sent again", op.id)) |
| 529 | } |
| 530 | |