| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "sync" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 12 | ) |
| 13 | |
| 14 | // ReflessProofDelay is how long, in controller time, a List must start after |
| 15 | // the stop request, the last launch dispatch and this process's Open before |
| 16 | // it can prove that a job with no VM Ref has no VM (R19). A launch whose |
| 17 | // reply was lost may still be landing until then. |
| 18 | const ReflessProofDelay = 2 * time.Minute |
| 19 | |
| 20 | // ProviderLaunchTimeout bounds every provider Launch call (Launch and |
| 21 | // Replay dispatch) (ruling R21). It is shorter than ReflessProofDelay, so a |
| 22 | // call that this process dispatched has returned or given up before a List |
| 23 | // can prove its job has no VM. |
| 24 | const ProviderLaunchTimeout = 60 * time.Second |
| 25 | |
| 26 | // ProviderCallTimeout bounds every other provider call (Get, List, Stop, |
| 27 | // Suspend, Resume and the network audit), retries included (ruling R27), so |
| 28 | // no stalled call holds an attempt lock or a reaper pass for longer. |
| 29 | const ProviderCallTimeout = 30 * time.Second |
| 30 | |
| 31 | // RestartGetTries is how many Refresh passes in a row may fail to read a |
| 32 | // pre-restart job's VM before the controller stops it as elapsed_unknown |
| 33 | // (R20). |
| 34 | const RestartGetTries = 3 |
| 35 | |
| 36 | // rebasedSet holds the jobs whose elapsed time Refresh has settled since this |
| 37 | // controller started: re-based on the provider's age, or stopped because the |
| 38 | // provider gave none. Each pre-restart job is settled once per process. |
| 39 | type rebasedSet struct { |
| 40 | mu sync.Mutex |
| 41 | done map[string]bool |
| 42 | fails map[string]int // consecutive Refresh passes whose Get failed |
| 43 | } |
| 44 | |
| 45 | // failGet counts one more failed Get for attempt and returns the count. |
| 46 | func (s *rebasedSet) failGet(attempt string) int { |
| 47 | s.mu.Lock() |
| 48 | defer s.mu.Unlock() |
| 49 | if s.fails == nil { |
| 50 | s.fails = map[string]int{} |
| 51 | } |
| 52 | s.fails[attempt]++ |
| 53 | return s.fails[attempt] |
| 54 | } |
| 55 | |
| 56 | // readOK ends attempt's run of failed Gets. |
| 57 | func (s *rebasedSet) readOK(attempt string) { |
| 58 | s.mu.Lock() |
| 59 | defer s.mu.Unlock() |
| 60 | delete(s.fails, attempt) |
| 61 | } |
| 62 | |
| 63 | func (s *rebasedSet) has(attempt string) bool { |
| 64 | s.mu.Lock() |
| 65 | defer s.mu.Unlock() |
| 66 | return s.done[attempt] |
| 67 | } |
| 68 | |
| 69 | func (s *rebasedSet) add(attempt string) { |
| 70 | s.mu.Lock() |
| 71 | defer s.mu.Unlock() |
| 72 | if s.done == nil { |
| 73 | s.done = map[string]bool{} |
| 74 | } |
| 75 | s.done[attempt] = true |
| 76 | } |
| 77 | |
| 78 | // Refresh reconciles the job table with the provider. One failing job does |
| 79 | // not stop the others; Refresh returns their errors joined. No transaction |
| 80 | // is held across a provider call. |
| 81 | // |
| 82 | // Every job with a VM Ref and no proof is read with Runner.Get: |
| 83 | // |
| 84 | // - a terminal state is proof and is saved. isolatedjob.ErrNotFound is |
| 85 | // proof only when confirmed by a second not-found NotFoundConfirm later |
| 86 | // with no live Get between (see notFound); the first is recorded and the |
| 87 | // job left pending. A job with no stop request ended on its own and gets |
| 88 | // the stop reason "ended", so replacements may go ahead; |
| 89 | // - a live state is saved as the job's state first, which also clears |
| 90 | // any first not-found (before anything below can return); |
| 91 | // - after a restart, a job launched at or before Store.OpenedAt has an |
| 92 | // untrusted elapsed time (the wall delta Open used says nothing about |
| 93 | // the real downtime). Once per process, with a provider age, its |
| 94 | // launched_t becomes min(launched_t, T before the Get minus the age) and |
| 95 | // its deadline, drain and stop times are recomputed with Deadlines, each |
| 96 | // only ever moved earlier. With no age, the controller stops it with the |
| 97 | // reason "elapsed_unknown". A Get that fails leaves it unsettled for the |
| 98 | // next pass; after RestartGetTries failed passes in a row it is stopped |
| 99 | // as elapsed_unknown too (R20), the Get error still returned; |
| 100 | // - an unknown state is left as it is; |
| 101 | // - a job with a stop request whose VM is not known to be stopping (live, |
| 102 | // unknown, or unreadable because Get failed) gets the provider stop |
| 103 | // again on every pass, whatever its restart state. |
| 104 | // |
| 105 | // Each job is reconciled under its attempt lock (R18), so the restart |
| 106 | // check and its settling are one step, and no other operation on the job |
| 107 | // interleaves with its provider calls. |
| 108 | // |
| 109 | // Then, when a job with no VM Ref is abandoned and has a stop request, one |
| 110 | // List: if it is complete, started at least ReflessProofDelay after the |
| 111 | // latest of that request, the job's last launch dispatch and OpenedAt, and |
| 112 | // shows no VM that is not terminal and not a saved Ref of some |
| 113 | // job, the job gets proof with an empty VMRef and state stopped. Until then |
| 114 | // it stays pending; the orphan reaper stops any such VM. |
| 115 | func (c *Controller) Refresh(ctx context.Context) error { |
| 116 | var withRef []string |
| 117 | refless := false |
| 118 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 119 | withRef, refless = withRef[:0], false |
| 120 | rows, err := tx.QueryContext(ctx, `SELECT attempt_id, vm_ref IS NOT NULL FROM jobs |
| 121 | WHERE stop_proof_json IS NULL |
| 122 | AND (vm_ref IS NOT NULL OR (state = ? AND stop_requested_t IS NOT NULL)) |
| 123 | ORDER BY launched_t, attempt_id`, JobAbandoned) |
| 124 | if err != nil { |
| 125 | return fmt.Errorf("hostedctl: list jobs to refresh: %w", err) |
| 126 | } |
| 127 | defer rows.Close() |
| 128 | for rows.Next() { |
| 129 | var id string |
| 130 | var hasRef bool |
| 131 | if err := rows.Scan(&id, &hasRef); err != nil { |
| 132 | return fmt.Errorf("hostedctl: list jobs to refresh: %w", err) |
| 133 | } |
| 134 | if hasRef { |
| 135 | withRef = append(withRef, id) |
| 136 | } else { |
| 137 | refless = true |
| 138 | } |
| 139 | } |
| 140 | return rows.Err() |
| 141 | }) |
| 142 | if err != nil { |
| 143 | return err |
| 144 | } |
| 145 | var errs []error |
| 146 | for _, id := range withRef { |
| 147 | if err := ctx.Err(); err != nil { |
| 148 | return errors.Join(append(errs, err)...) |
| 149 | } |
| 150 | if err := c.refreshOne(ctx, id); err != nil { |
| 151 | errs = append(errs, err) |
| 152 | } |
| 153 | } |
| 154 | if refless { |
| 155 | if err := c.proveRefless(ctx); err != nil { |
| 156 | errs = append(errs, err) |
| 157 | } |
| 158 | } |
| 159 | return errors.Join(errs...) |
| 160 | } |
| 161 | |
| 162 | // refreshOne reconciles one job with a VM Ref; see Refresh. |
| 163 | func (c *Controller) refreshOne(ctx context.Context, attempt string) error { |
| 164 | defer c.lockAttempt(attempt)() |
| 165 | var j jobRow |
| 166 | var reason sql.NullString |
| 167 | found := false |
| 168 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 169 | var err error |
| 170 | if j, found, err = loadJob(ctx, tx, attempt); err != nil || !found { |
| 171 | return err |
| 172 | } |
| 173 | return tx.QueryRowContext(ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, attempt).Scan(&reason) |
| 174 | }) |
| 175 | if err != nil { |
| 176 | return err |
| 177 | } |
| 178 | if !found || !j.ref.Valid || j.stopProof.Valid { |
| 179 | return nil |
| 180 | } |
| 181 | ref := isolatedjob.Ref(j.ref.String) |
| 182 | untrusted := c.store.Restarted() && T(j.launchedT) <= c.store.OpenedAt() && !c.rebased.has(attempt) |
| 183 | |
| 184 | before := c.store.Clock().Now() |
| 185 | job, gerr := c.runner.Get(ctx, ref) |
| 186 | at := c.store.Clock().Now() |
| 187 | c.reap.observeGet(attempt, job.State, gerr) // for the reaper's unknown-state count |
| 188 | rec := context.WithoutCancel(ctx) |
| 189 | switch { |
| 190 | case errors.Is(gerr, isolatedjob.ErrNotFound): |
| 191 | _, _, err := c.notFound(rec, "", attempt, ref, before, at, "refresh: provider holds no such VM") |
| 192 | return err |
| 193 | case gerr != nil: |
| 194 | err := fmt.Errorf("hostedctl: refresh %s: read VM %s: %w", attempt, ref, gerr) |
| 195 | if untrusted && c.rebased.failGet(attempt) >= RestartGetTries { |
| 196 | return errors.Join(err, c.stopElapsedUnknown(ctx, attempt)) |
| 197 | } |
| 198 | if j.stopRequested.Valid { |
| 199 | // A pending stop is sent again whatever the VM read and the |
| 200 | // restart state say: the provider's Stop is idempotent. |
| 201 | return errors.Join(err, c.resendStop(ctx, j, ref, reason.String)) |
| 202 | } |
| 203 | return err |
| 204 | case job.State.Terminal(): |
| 205 | _, err := c.recordProof(rec, "", attempt, StopProof{AttemptID: attempt, VMRef: ref, |
| 206 | State: job.State, ObservedAt: at}, "refresh: provider reports the VM "+string(job.State)) |
| 207 | return err |
| 208 | } |
| 209 | c.rebased.readOK(attempt) |
| 210 | if job.State.Live() { |
| 211 | // First, so a live sighting clears any first not-found even when |
| 212 | // the restart handling below stops the job. It gets ctx, not rec: |
| 213 | // its provider calls must end when the caller does (R27). |
| 214 | if err := c.mirrorLive(ctx, j, job.State); err != nil { |
| 215 | return err |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | if untrusted { |
| 220 | if !job.AgeKnown || job.ProviderAge < 0 { |
| 221 | return c.stopElapsedUnknown(ctx, attempt) |
| 222 | } |
| 223 | if err := c.rebase(rec, attempt, before-T(job.ProviderAge), job.ProviderAge); err != nil { |
| 224 | return err |
| 225 | } |
| 226 | c.rebased.add(attempt) |
| 227 | } |
| 228 | if j.stopRequested.Valid && job.State != isolatedjob.StateStopping { |
| 229 | // Live and not yet stopping, or unknown (it may be live). |
| 230 | return c.resendStop(ctx, j, ref, reason.String) |
| 231 | } |
| 232 | return nil |
| 233 | } |
| 234 | |
| 235 | // resendStop sends the provider stop again for j, whose stop was asked for |
| 236 | // and is not proven. A failure is audited with a fixed reason and returned; |
| 237 | // the next Refresh sends it again. |
| 238 | func (c *Controller) resendStop(ctx context.Context, j jobRow, ref isolatedjob.Ref, reason string) error { |
| 239 | perr := c.runner.Stop(ctx, ref, reason) |
| 240 | if perr == nil || errors.Is(perr, isolatedjob.ErrNotFound) { |
| 241 | return nil |
| 242 | } |
| 243 | r := stopReq{attempt: j.attempt, account: j.account, task: j.task, ref: ref} |
| 244 | aerr := c.auditStop(context.WithoutCancel(ctx), "", r, actionStopFailed, |
| 245 | "refresh: provider stop call failed; it is sent again on the next refresh") |
| 246 | return errors.Join(fmt.Errorf("hostedctl: refresh %s: stop VM %s: %w", j.attempt, ref, perr), aerr) |
| 247 | } |
| 248 | |
| 249 | // stopElapsedUnknown is the controller's own stop of a pre-restart job the |
| 250 | // provider gave no age for, or whose VM it could not read RestartGetTries |
| 251 | // passes in a row. The caller holds the attempt's lock. Once the request is recorded the job counts as |
| 252 | // settled; a pending or unknown result is left for the next Refresh. |
| 253 | func (c *Controller) stopElapsedUnknown(ctx context.Context, attempt string) error { |
| 254 | r, err := c.requestStop(context.WithoutCancel(ctx), "", attempt, reasonElapsedUnknown, false) |
| 255 | if err != nil { |
| 256 | return err |
| 257 | } |
| 258 | c.logElapsedUnknown(attempt) |
| 259 | c.rebased.add(attempt) |
| 260 | if r.proof != nil { |
| 261 | return nil |
| 262 | } |
| 263 | _, err = c.driveStop(ctx, "", r) |
| 264 | if errors.Is(err, ErrStopPending) || errors.Is(err, ErrStateUnknown) { |
| 265 | return nil |
| 266 | } |
| 267 | return err |
| 268 | } |
| 269 | |
| 270 | // rebase moves a pre-restart job's launch time back to cand when cand is |
| 271 | // earlier, and its deadline, drain and stop times to those Deadlines gives |
| 272 | // for it, each only when earlier than the stored one. It is audited even |
| 273 | // when nothing moves. |
| 274 | func (c *Controller) rebase(ctx context.Context, attempt string, cand T, age time.Duration) error { |
| 275 | var launchedBy, stopBy time.Duration |
| 276 | moved := false |
| 277 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 278 | moved = false |
| 279 | j, found, err := loadJob(ctx, tx, attempt) |
| 280 | if err != nil || !found || j.stopProof.Valid { |
| 281 | return err |
| 282 | } |
| 283 | spec, err := decodeSpec(j.specJSON, attempt) |
| 284 | if err != nil { |
| 285 | return err |
| 286 | } |
| 287 | launched := min(T(j.launchedT), cand) |
| 288 | deadline, drain, stop := Deadlines(launched, spec.MaxLifetime) |
| 289 | deadline, drain, stop = min(deadline, T(j.deadlineT)), min(drain, T(j.drainT)), min(stop, T(j.stopT)) |
| 290 | if _, err := tx.ExecContext(ctx, `UPDATE jobs SET launched_t = ?, deadline_t = ?, drain_t = ?, stop_t = ?, |
| 291 | revision = revision + 1 WHERE attempt_id = ?`, |
| 292 | int64(launched), int64(deadline), int64(drain), int64(stop), attempt); err != nil { |
| 293 | return fmt.Errorf("hostedctl: re-base %s: %w", attempt, err) |
| 294 | } |
| 295 | launchedBy, stopBy, moved = time.Duration(T(j.launchedT)-launched), time.Duration(T(j.stopT)-stop), true |
| 296 | return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: attempt, Action: actionRestartRebased, |
| 297 | Reason: fmt.Sprintf("after a restart the provider reports age %v; launched moved back by %v, stop time by %v", |
| 298 | age, launchedBy, stopBy), |
| 299 | At: c.store.Clock().Now()}) |
| 300 | }) |
| 301 | if err == nil && moved { |
| 302 | c.logRebased(attempt, age, launchedBy, stopBy) |
| 303 | } |
| 304 | return err |
| 305 | } |
| 306 | |
| 307 | // proveRefless issues proof for abandoned, stop-requested jobs with no VM |
| 308 | // Ref; see Refresh. An incomplete List proves nothing and is not an error. |
| 309 | // The List and the check for unlinked VMs come first; then each job is |
| 310 | // settled under its attempt lock in a transaction of its own. |
| 311 | func (c *Controller) proveRefless(ctx context.Context) error { |
| 312 | start := c.store.Clock().Now() |
| 313 | vms, err := c.runner.List(ctx) |
| 314 | at := c.store.Clock().Now() |
| 315 | if errors.Is(err, isolatedjob.ErrIncomplete) { |
| 316 | return nil |
| 317 | } |
| 318 | if err != nil { |
| 319 | return fmt.Errorf("hostedctl: list VMs for stop proof: %w", err) |
| 320 | } |
| 321 | ctx = context.WithoutCancel(ctx) // record what the list showed even if the caller has gone |
| 322 | var ids []string |
| 323 | err = c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 324 | ids = ids[:0] |
| 325 | saved := map[isolatedjob.Ref]bool{} |
| 326 | rows, err := tx.QueryContext(ctx, `SELECT vm_ref FROM jobs WHERE vm_ref IS NOT NULL`) |
| 327 | if err != nil { |
| 328 | return fmt.Errorf("hostedctl: read saved VM refs: %w", err) |
| 329 | } |
| 330 | for rows.Next() { |
| 331 | var ref string |
| 332 | if err := rows.Scan(&ref); err != nil { |
| 333 | _ = rows.Close() |
| 334 | return fmt.Errorf("hostedctl: read saved VM refs: %w", err) |
| 335 | } |
| 336 | saved[isolatedjob.Ref(ref)] = true |
| 337 | } |
| 338 | if err := errors.Join(rows.Err(), rows.Close()); err != nil { |
| 339 | return fmt.Errorf("hostedctl: read saved VM refs: %w", err) |
| 340 | } |
| 341 | for _, vm := range vms { |
| 342 | // An unknown state may be a live VM, so only terminal ones pass. |
| 343 | if !vm.State.Terminal() && !saved[vm.Ref] { |
| 344 | return nil // ids stays empty: no proof this pass |
| 345 | } |
| 346 | } |
| 347 | rows, err = tx.QueryContext(ctx, `SELECT attempt_id FROM jobs WHERE vm_ref IS NULL AND state = ? |
| 348 | AND stop_requested_t IS NOT NULL AND stop_proof_json IS NULL ORDER BY attempt_id`, JobAbandoned) |
| 349 | if err != nil { |
| 350 | return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err) |
| 351 | } |
| 352 | for rows.Next() { |
| 353 | var id string |
| 354 | if err := rows.Scan(&id); err != nil { |
| 355 | _ = rows.Close() |
| 356 | return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err) |
| 357 | } |
| 358 | ids = append(ids, id) |
| 359 | } |
| 360 | if err := errors.Join(rows.Err(), rows.Close()); err != nil { |
| 361 | return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err) |
| 362 | } |
| 363 | return nil |
| 364 | }) |
| 365 | if err != nil { |
| 366 | return err |
| 367 | } |
| 368 | var errs []error |
| 369 | for _, id := range ids { |
| 370 | if err := c.proveReflessOne(ctx, id, start, at); err != nil { |
| 371 | errs = append(errs, err) |
| 372 | } |
| 373 | } |
| 374 | return errors.Join(errs...) |
| 375 | } |
| 376 | |
| 377 | // proveReflessOne saves proof for one Ref-less job when the List that began |
| 378 | // at start began at least ReflessProofDelay after the latest of its stop |
| 379 | // request, its last launch dispatch and OpenedAt. |
| 380 | func (c *Controller) proveReflessOne(ctx context.Context, attempt string, start, at T) error { |
| 381 | defer c.lockAttempt(attempt)() |
| 382 | return c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 383 | j, found, err := loadJob(ctx, tx, attempt) |
| 384 | if err != nil { |
| 385 | return err |
| 386 | } |
| 387 | if !found || j.ref.Valid || j.state != JobAbandoned || !j.stopRequested.Valid || j.stopProof.Valid { |
| 388 | return nil |
| 389 | } |
| 390 | var dispatched sql.NullInt64 |
| 391 | if err := tx.QueryRowContext(ctx, `SELECT last_dispatch_t FROM jobs WHERE attempt_id = ?`, attempt).Scan(&dispatched); err != nil { |
| 392 | return fmt.Errorf("hostedctl: read last_dispatch_t of %s: %w", attempt, err) |
| 393 | } |
| 394 | since := max(T(j.stopRequested.Int64), c.store.OpenedAt()) |
| 395 | if dispatched.Valid { |
| 396 | since = max(since, T(dispatched.Int64)) |
| 397 | } |
| 398 | if start-since < T(ReflessProofDelay) { |
| 399 | return nil |
| 400 | } |
| 401 | p := StopProof{AttemptID: attempt, State: isolatedjob.StateStopped, ObservedAt: at} |
| 402 | return writeProof(ctx, tx, "", j, p, fmt.Sprintf( |
| 403 | "a complete list begun %v after the stop request, the last dispatch and the controller start shows no VM outside the job table", |
| 404 | time.Duration(start-since))) |
| 405 | }) |
| 406 | } |
| 407 | |
| 408 | // markDispatch records, just before a provider launch call, that one is |
| 409 | // about to be made for attempt (R19). Ref-less proof waits |
| 410 | // ReflessProofDelay past it, so a VM the call creates late is still seen. |
| 411 | func (c *Controller) markDispatch(ctx context.Context, attempt string) error { |
| 412 | return c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 413 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET last_dispatch_t = ?, revision = revision + 1 |
| 414 | WHERE attempt_id = ?`, int64(c.store.Clock().Now()), attempt) |
| 415 | if err != nil { |
| 416 | return fmt.Errorf("hostedctl: record dispatch of %s: %w", attempt, err) |
| 417 | } |
| 418 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 419 | return fmt.Errorf("hostedctl: record dispatch of %s: %d rows (%v)", attempt, n, err) |
| 420 | } |
| 421 | return nil |
| 422 | }) |
| 423 | } |
| 424 | |