| 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 | // ReapInterval is how often Loop runs a reaper pass unless told otherwise |
| 15 | // (spec §10). |
| 16 | const ReapInterval = 60 * time.Second |
| 17 | |
| 18 | // OrphanGrace is how long, in controller time, a listed VM that matches no |
| 19 | // job is left alone before the reaper rechecks its ownership and stops it |
| 20 | // (spec §10). After a restart, an orphan first seen before Open has used up |
| 21 | // its grace: the downtime is unknown, so the time since the sighting is too. |
| 22 | const OrphanGrace = 10 * time.Minute |
| 23 | |
| 24 | // UnknownAlertPasses is how many reaper passes in a row a job's VM must read |
| 25 | // unknown before the reaper raises an unknown_state alert for it. |
| 26 | const UnknownAlertPasses = 3 |
| 27 | |
| 28 | // Alert kinds the reaper raises. Details name VMs, attempts, tasks and |
| 29 | // accounts, never credentials. |
| 30 | const ( |
| 31 | // AlertOrphanStopped: the reaper stopped a VM that matched no job. |
| 32 | AlertOrphanStopped = "orphan_stopped" |
| 33 | // AlertUnknownState: a job's VM read unknown on UnknownAlertPasses |
| 34 | // passes in a row. Raised once per run of unknown reads. |
| 35 | AlertUnknownState = "unknown_state" |
| 36 | // AlertAuditFailed: the network audit failed, so launches are refused. |
| 37 | // Raised once per run of failed audits. |
| 38 | AlertAuditFailed = "audit_failed" |
| 39 | ) |
| 40 | |
| 41 | // Stop reasons the reaper sends to the provider. |
| 42 | const ( |
| 43 | reasonDeadline = "deadline" // the job reached its stop time |
| 44 | reasonOrphan = "orphan" // the VM matched no job |
| 45 | ) |
| 46 | |
| 47 | // Audit actions written by the reaper. |
| 48 | const ( |
| 49 | actionDeadlineDrain = "deadline_drain" |
| 50 | actionOrphanSeen = "orphan_seen" |
| 51 | actionOrphanStopped = "orphan_stopped" |
| 52 | actionOrphanStopFailed = "orphan_stop_failed" |
| 53 | actionOrphanDeferred = "orphan_deferred" |
| 54 | actionUnknownState = "unknown_state" |
| 55 | actionNetworkAuditFailed = "network_audit_failed" |
| 56 | actionNetworkAuditPassed = "network_audit_passed" |
| 57 | ) |
| 58 | |
| 59 | // ReapReport counts what one reaper pass did. |
| 60 | type ReapReport struct { |
| 61 | // Skipped: orphan processing was skipped because a List was incomplete |
| 62 | // or failed: the whole step on the first List, or the stops on the |
| 63 | // recheck's List. The pass's other steps ran. |
| 64 | Skipped bool |
| 65 | // Replayed: launch intents that gained a VM Ref in the pass's replays. |
| 66 | Replayed int |
| 67 | // Drained: jobs given their drain mark in this pass. |
| 68 | Drained int |
| 69 | // Stopped: jobs whose deadline stop this pass asked for. |
| 70 | Stopped int |
| 71 | // OrphansSeen: listed VMs, not terminal, that match no job's saved Ref. |
| 72 | OrphansSeen int |
| 73 | // OrphansStopped: orphans the provider was asked to stop in this pass. |
| 74 | OrphansStopped int |
| 75 | // OrphansDeferred: orphans whose grace is over left running in this |
| 76 | // pass because a waiting intent that has been dispatched might own |
| 77 | // them (ruling R22). |
| 78 | OrphansDeferred int |
| 79 | // Unknown: jobs whose VM read unknown in this pass's Refresh. |
| 80 | Unknown int |
| 81 | } |
| 82 | |
| 83 | // ReapResult is one finished pass: its report, its error and the controller |
| 84 | // time at which it finished. |
| 85 | type ReapResult struct { |
| 86 | Report ReapReport |
| 87 | Err error |
| 88 | At T |
| 89 | } |
| 90 | |
| 91 | // reapState is the reaper's in-memory state. A restart starts it afresh: |
| 92 | // alerts held back by an Alerter failure are lost, and running episodes |
| 93 | // alert again. |
| 94 | type reapState struct { |
| 95 | pass sync.Mutex // held for a whole pass: one pass at a time |
| 96 | |
| 97 | mu sync.Mutex |
| 98 | observed map[string]bool // attempt -> Refresh's latest Get read unknown; absent: no answer since the last pass |
| 99 | last ReapResult |
| 100 | ran bool |
| 101 | |
| 102 | // Used only under pass. |
| 103 | unknownRuns map[string]int // attempt -> passes in a row its VM read unknown |
| 104 | unknownAlerted map[string]bool // attempt -> its current run was alerted |
| 105 | orphanAlerted map[isolatedjob.Ref]bool |
| 106 | orphanDeferred map[isolatedjob.Ref]bool // orphans whose current deferral was audited |
| 107 | auditFailing bool // an audit_failed episode is open |
| 108 | queued []Alert // alerts not yet delivered, oldest first |
| 109 | } |
| 110 | |
| 111 | // ownershipLock keeps VM ownership still while the orphan reaper decides |
| 112 | // (ruling R23). Every dispatch holds it for reading from before it reads the |
| 113 | // intent and checks the creation gates to its settled answer (a saved Ref, |
| 114 | // or the intent left waiting or abandoned), so a wait for it never lets a |
| 115 | // checked gate go stale before the provider call; the |
| 116 | // orphan final check holds it for writing from its fresh List to its last |
| 117 | // provider Stop. So no Ref is saved, and no intent is newly marked |
| 118 | // dispatched, between the reaper reading ownership and stopping a VM. |
| 119 | // |
| 120 | // Lock order: an attempt lock, then this. The orphan path takes no attempt |
| 121 | // lock. Never take it inside a store transaction. |
| 122 | type ownershipLock struct { |
| 123 | mu sync.RWMutex |
| 124 | // waiting, when set, is called each time a dispatch finds the lock |
| 125 | // held for writing and is about to wait. Tests use it to see the wait |
| 126 | // without sleeping; production leaves it nil. |
| 127 | waiting func() |
| 128 | } |
| 129 | |
| 130 | // rlock takes the lock for reading and returns its release. |
| 131 | func (o *ownershipLock) rlock() func() { |
| 132 | if !o.mu.TryRLock() { |
| 133 | if o.waiting != nil { |
| 134 | o.waiting() |
| 135 | } |
| 136 | o.mu.RLock() |
| 137 | } |
| 138 | return o.mu.RUnlock |
| 139 | } |
| 140 | |
| 141 | // observeGet records what Refresh's Get said about attempt's VM, for the |
| 142 | // reaper's unknown-state count. A state that is neither live nor terminal |
| 143 | // counts as unknown; a not-found is a known answer; any other error says |
| 144 | // nothing. |
| 145 | func (s *reapState) observeGet(attempt string, st isolatedjob.State, err error) { |
| 146 | s.mu.Lock() |
| 147 | defer s.mu.Unlock() |
| 148 | if s.observed == nil { |
| 149 | s.observed = map[string]bool{} |
| 150 | } |
| 151 | switch { |
| 152 | case err == nil: |
| 153 | s.observed[attempt] = !st.Live() && !st.Terminal() |
| 154 | case errors.Is(err, isolatedjob.ErrNotFound): |
| 155 | s.observed[attempt] = false |
| 156 | default: |
| 157 | delete(s.observed, attempt) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // takeObserved returns and forgets the latest observation for attempt. ok |
| 162 | // is false when there is none. |
| 163 | func (s *reapState) takeObserved(attempt string) (unknown, ok bool) { |
| 164 | s.mu.Lock() |
| 165 | defer s.mu.Unlock() |
| 166 | unknown, ok = s.observed[attempt] |
| 167 | delete(s.observed, attempt) |
| 168 | return unknown, ok |
| 169 | } |
| 170 | |
| 171 | // raise queues a for delivery at the end of the pass. The caller holds pass. |
| 172 | func (s *reapState) raise(a Alert) { s.queued = append(s.queued, a) } |
| 173 | |
| 174 | // LastReap returns the last finished pass, and false when none has finished. |
| 175 | // Task 15's metrics read it. |
| 176 | func (c *Controller) LastReap() (ReapResult, bool) { |
| 177 | c.reap.mu.Lock() |
| 178 | defer c.reap.mu.Unlock() |
| 179 | return c.reap.last, c.reap.ran |
| 180 | } |
| 181 | |
| 182 | // Loop runs Reap at once and then every `every` (ReapInterval when every is |
| 183 | // not positive) until ctx is done, one pass at a time. A pass's error never |
| 184 | // ends the loop; it is kept for LastReap, and the last pass's error is |
| 185 | // returned when ctx is done. |
| 186 | func (c *Controller) Loop(ctx context.Context, every time.Duration) error { |
| 187 | if every <= 0 { |
| 188 | every = ReapInterval |
| 189 | } |
| 190 | tick := time.NewTicker(every) |
| 191 | defer tick.Stop() |
| 192 | var last error |
| 193 | for { |
| 194 | if ctx.Err() != nil { |
| 195 | return last |
| 196 | } |
| 197 | _, last = c.Reap(ctx) |
| 198 | select { |
| 199 | case <-ctx.Done(): |
| 200 | return last |
| 201 | case <-tick.C: |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // Reap runs one reaper pass (spec §10). Passes run one at a time. In order: |
| 207 | // |
| 208 | // 1. Checkpoint controller time. A failure ends the pass: the store is |
| 209 | // needed for everything after it. Then every recorded job past its |
| 210 | // stop time gets its deadline stop (reapOverdue, R26), so the slow |
| 211 | // launch calls of step 2 never hold it up. |
| 212 | // 2. Replay launch intents, with their gates (Replay), so a VM a lost |
| 213 | // launch reply made is claimed before anything looks for orphans. |
| 214 | // 3. Refresh. |
| 215 | // 4. Recorded jobs, by their saved Ref, whatever List returns: a job past |
| 216 | // its drain time gets its drain mark (a notice; no pause), a job past |
| 217 | // its stop time gets a deadline stop, and a VM that read unknown is |
| 218 | // counted and, after UnknownAlertPasses passes, alerted (Refresh has |
| 219 | // already sent a requested stop again). See reapJob and trackUnknown. |
| 220 | // 5. Orphans, only on a complete List (reapOrphans): VMs that match no |
| 221 | // job's saved Ref are recorded in unmatched_vms and stopped once |
| 222 | // OrphanGrace has passed and a recheck still finds them unclaimed, |
| 223 | // unless a dispatched waiting intent may own them (deferred, R22). |
| 224 | // 6. The network audit (reaperAudit). While it fails, launches are |
| 225 | // refused; an audit_failed alert goes out when a run of failures |
| 226 | // begins. |
| 227 | // |
| 228 | // Then the pass's alerts are delivered. A step's failure, an Alerter's |
| 229 | // included, does not stop the steps after it; the pass returns every |
| 230 | // failure joined, and keeps its result for LastReap. |
| 231 | func (c *Controller) Reap(ctx context.Context) (ReapReport, error) { |
| 232 | c.reap.pass.Lock() |
| 233 | defer c.reap.pass.Unlock() |
| 234 | var rep ReapReport |
| 235 | err := c.reapPass(ctx, &rep) |
| 236 | c.reap.mu.Lock() |
| 237 | c.reap.last, c.reap.ran = ReapResult{Report: rep, Err: err, At: c.store.Clock().Now()}, true |
| 238 | c.reap.mu.Unlock() |
| 239 | return rep, err |
| 240 | } |
| 241 | |
| 242 | func (c *Controller) reapPass(ctx context.Context, rep *ReapReport) error { |
| 243 | if err := c.store.Checkpoint(ctx); err != nil { |
| 244 | return fmt.Errorf("hostedctl: reap: clock checkpoint: %w", err) |
| 245 | } |
| 246 | errs := []error{c.reapOverdue(ctx, rep)} |
| 247 | n, err := c.replayCounted(ctx) |
| 248 | rep.Replayed += n |
| 249 | errs = append(errs, err) |
| 250 | errs = append(errs, c.Refresh(ctx)) |
| 251 | errs = append(errs, c.reapJobs(ctx, rep)) |
| 252 | errs = append(errs, c.reapOrphans(ctx, rep)) |
| 253 | errs = append(errs, c.reaperAudit(ctx)) |
| 254 | errs = append(errs, c.sendAlerts(ctx)) |
| 255 | return errors.Join(errs...) |
| 256 | } |
| 257 | |
| 258 | // replayCounted runs Replay when an intent is waiting and returns how many |
| 259 | // of the intents waiting before it hold a VM Ref after it. |
| 260 | func (c *Controller) replayCounted(ctx context.Context) (int, error) { |
| 261 | var waiting []string |
| 262 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 263 | var err error |
| 264 | waiting, err = textColumn(ctx, tx, `SELECT attempt_id FROM jobs WHERE state = ? AND vm_ref IS NULL`, JobWaiting) |
| 265 | return err |
| 266 | }) |
| 267 | if err != nil || len(waiting) == 0 { |
| 268 | return 0, err |
| 269 | } |
| 270 | rerr := c.Replay(ctx) |
| 271 | n := 0 |
| 272 | err = c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 273 | n = 0 |
| 274 | for _, id := range waiting { |
| 275 | j, found, err := loadJob(ctx, tx, id) |
| 276 | if err != nil { |
| 277 | return err |
| 278 | } |
| 279 | if found && j.ref.Valid { |
| 280 | n++ |
| 281 | } |
| 282 | } |
| 283 | return nil |
| 284 | }) |
| 285 | return n, errors.Join(rerr, err) |
| 286 | } |
| 287 | |
| 288 | // reapOverdue is step 1b (ruling R26): every job with a saved Ref and no |
| 289 | // proof whose stop time has come is stopped before Replay, so launch calls, |
| 290 | // each up to ProviderLaunchTimeout, never delay it. With no stop request it |
| 291 | // gets its deadline stop (reapJob). With one, whatever its reason, the |
| 292 | // provider stop is sent again (resendStop), its recorded reason and request |
| 293 | // time unchanged, so a stop whose provider call failed is retried here too. |
| 294 | // Re-basing after a restart only moves stop times earlier, so this never |
| 295 | // stops a job early; step 4 and Refresh repeat idempotently. |
| 296 | func (c *Controller) reapOverdue(ctx context.Context, rep *ReapReport) error { |
| 297 | var ids []string |
| 298 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 299 | var err error |
| 300 | ids, err = textColumn(ctx, tx, `SELECT attempt_id FROM jobs WHERE vm_ref IS NOT NULL AND stop_proof_json IS NULL |
| 301 | AND stop_t <= ? ORDER BY launched_t, attempt_id`, int64(c.store.Clock().Now())) |
| 302 | return err |
| 303 | }) |
| 304 | if err != nil { |
| 305 | return err |
| 306 | } |
| 307 | var errs []error |
| 308 | for _, id := range ids { |
| 309 | if err := ctx.Err(); err != nil { |
| 310 | return errors.Join(append(errs, err)...) |
| 311 | } |
| 312 | pending, err := c.resendPendingStop(ctx, id) |
| 313 | if err == nil && !pending { |
| 314 | _, err = c.reapJob(ctx, id, rep) |
| 315 | } |
| 316 | errs = append(errs, err) |
| 317 | } |
| 318 | return errors.Join(errs...) |
| 319 | } |
| 320 | |
| 321 | // resendPendingStop sends the provider stop again, under the attempt's |
| 322 | // lock, for a job with a saved Ref, a stop request and no proof, with the |
| 323 | // recorded reason. pending is false, and nothing is sent, for any other job. |
| 324 | func (c *Controller) resendPendingStop(ctx context.Context, attempt string) (pending bool, err error) { |
| 325 | defer c.lockAttempt(attempt)() |
| 326 | var j jobRow |
| 327 | var reason sql.NullString |
| 328 | err = c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 329 | var found bool |
| 330 | var err error |
| 331 | if j, found, err = loadJob(ctx, tx, attempt); err != nil || !found { |
| 332 | return err |
| 333 | } |
| 334 | pending = j.ref.Valid && j.stopRequested.Valid && !j.stopProof.Valid |
| 335 | return tx.QueryRowContext(ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, attempt).Scan(&reason) |
| 336 | }) |
| 337 | if err != nil || !pending { |
| 338 | return pending, err |
| 339 | } |
| 340 | return true, c.resendStop(ctx, j, isolatedjob.Ref(j.ref.String), reason.String) |
| 341 | } |
| 342 | |
| 343 | // reapJobs is step 4: every job with a saved Ref and no proof, in launch |
| 344 | // order. It reads no List, so an incomplete one never holds up a deadline. |
| 345 | func (c *Controller) reapJobs(ctx context.Context, rep *ReapReport) error { |
| 346 | var ids []string |
| 347 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 348 | var err error |
| 349 | ids, err = textColumn(ctx, tx, `SELECT attempt_id FROM jobs WHERE vm_ref IS NOT NULL AND stop_proof_json IS NULL |
| 350 | ORDER BY launched_t, attempt_id`) |
| 351 | return err |
| 352 | }) |
| 353 | if err != nil { |
| 354 | return err |
| 355 | } |
| 356 | var errs []error |
| 357 | for _, id := range ids { |
| 358 | if err := ctx.Err(); err != nil { |
| 359 | errs = append(errs, err) |
| 360 | break |
| 361 | } |
| 362 | j, err := c.reapJob(ctx, id, rep) |
| 363 | errs = append(errs, err, c.trackUnknown(ctx, id, j, rep)) |
| 364 | } |
| 365 | c.forgetUnknowns(ids) |
| 366 | return errors.Join(errs...) |
| 367 | } |
| 368 | |
| 369 | // reapJob handles one recorded job under its attempt lock. A job with a stop |
| 370 | // asked for, or proof, is left to Refresh. Otherwise, by controller time: |
| 371 | // |
| 372 | // - at or past its stop time, it gets a stop with the reason "deadline": |
| 373 | // the request is recorded first (requestStop), then the provider stop is |
| 374 | // sent and the VM read (driveStop). Refresh proves it on a later pass; |
| 375 | // - at or past its drain time and not yet marked, drain_marked_t is set |
| 376 | // and audited. This is the notice before the stop; it opens no pause |
| 377 | // generation and leaves the job's state alone. |
| 378 | // |
| 379 | // It returns the job as read, zero when it is gone. |
| 380 | func (c *Controller) reapJob(ctx context.Context, attempt string, rep *ReapReport) (jobRow, error) { |
| 381 | defer c.lockAttempt(attempt)() |
| 382 | var j jobRow |
| 383 | marked, stop := false, false |
| 384 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 385 | marked, stop = false, false |
| 386 | var found bool |
| 387 | var err error |
| 388 | if j, found, err = loadJob(ctx, tx, attempt); err != nil || !found { |
| 389 | return err |
| 390 | } |
| 391 | if !j.ref.Valid || j.stopProof.Valid || j.stopRequested.Valid { |
| 392 | return nil |
| 393 | } |
| 394 | now := c.store.Clock().Now() |
| 395 | if now >= T(j.stopT) { |
| 396 | stop = true |
| 397 | return nil |
| 398 | } |
| 399 | if now < T(j.drainT) { |
| 400 | return nil |
| 401 | } |
| 402 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET drain_marked_t = ?, revision = revision + 1 |
| 403 | WHERE attempt_id = ? AND drain_marked_t IS NULL`, int64(now), attempt) |
| 404 | if err != nil { |
| 405 | return fmt.Errorf("hostedctl: mark drain of %s: %w", attempt, err) |
| 406 | } |
| 407 | n, err := res.RowsAffected() |
| 408 | if err != nil { |
| 409 | return fmt.Errorf("hostedctl: mark drain of %s: %w", attempt, err) |
| 410 | } |
| 411 | if n == 0 { |
| 412 | return nil // marked on an earlier pass |
| 413 | } |
| 414 | marked = true |
| 415 | return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: attempt, Action: actionDeadlineDrain, |
| 416 | Reason: fmt.Sprintf("drain time reached; VM %s is stopped in %v", j.ref.String, time.Duration(T(j.stopT)-now)), At: now}) |
| 417 | }) |
| 418 | if err != nil { |
| 419 | return j, err |
| 420 | } |
| 421 | if marked { |
| 422 | rep.Drained++ |
| 423 | } |
| 424 | if !stop { |
| 425 | return j, nil |
| 426 | } |
| 427 | r, err := c.requestStop(context.WithoutCancel(ctx), "", attempt, reasonDeadline, false) |
| 428 | if err != nil { |
| 429 | return j, err |
| 430 | } |
| 431 | rep.Stopped++ |
| 432 | if r.proof != nil { |
| 433 | return j, nil |
| 434 | } |
| 435 | if _, err := c.driveStop(ctx, "", r); err != nil && !errors.Is(err, ErrStopPending) && !errors.Is(err, ErrStateUnknown) { |
| 436 | return j, err |
| 437 | } |
| 438 | return j, nil |
| 439 | } |
| 440 | |
| 441 | // trackUnknown counts attempt's run of unknown reads from this pass's |
| 442 | // Refresh. A known state, or a not-found, ends the run. When the run reaches |
| 443 | // UnknownAlertPasses one unknown_state alert is raised and audited; the |
| 444 | // next comes only after a known read ends the run and a new one reaches the |
| 445 | // count. A stop asked for is sent again by Refresh on every unknown read |
| 446 | // (refreshOne), so it is not sent again here. |
| 447 | func (c *Controller) trackUnknown(ctx context.Context, attempt string, j jobRow, rep *ReapReport) error { |
| 448 | unknown, ok := c.reap.takeObserved(attempt) |
| 449 | if !ok { |
| 450 | return nil |
| 451 | } |
| 452 | s := &c.reap |
| 453 | if !unknown { |
| 454 | delete(s.unknownRuns, attempt) |
| 455 | delete(s.unknownAlerted, attempt) |
| 456 | return nil |
| 457 | } |
| 458 | rep.Unknown++ |
| 459 | if s.unknownRuns == nil { |
| 460 | s.unknownRuns, s.unknownAlerted = map[string]int{}, map[string]bool{} |
| 461 | } |
| 462 | s.unknownRuns[attempt]++ |
| 463 | if s.unknownRuns[attempt] < UnknownAlertPasses || s.unknownAlerted[attempt] { |
| 464 | return nil |
| 465 | } |
| 466 | s.unknownAlerted[attempt] = true |
| 467 | then := "no stop has been asked for" |
| 468 | if j.stopRequested.Valid { |
| 469 | then = "its stop is sent again each pass" |
| 470 | } |
| 471 | detail := fmt.Sprintf("VM %s of attempt %s (task %s, account %s) read unknown on %d passes in a row; %s", |
| 472 | j.ref.String, attempt, j.task, j.account, s.unknownRuns[attempt], then) |
| 473 | now := c.store.Clock().Now() |
| 474 | s.raise(Alert{Kind: AlertUnknownState, Detail: detail, At: now}) |
| 475 | return c.store.Tx(context.WithoutCancel(ctx), func(tx *sql.Tx) error { |
| 476 | return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: attempt, Action: actionUnknownState, |
| 477 | Reason: detail, At: now}) |
| 478 | }) |
| 479 | } |
| 480 | |
| 481 | // forgetUnknowns drops the unknown-read runs of attempts no longer in ids |
| 482 | // (proven, or gone) and any observation not taken this pass. |
| 483 | func (c *Controller) forgetUnknowns(ids []string) { |
| 484 | keep := make(map[string]bool, len(ids)) |
| 485 | for _, id := range ids { |
| 486 | keep[id] = true |
| 487 | } |
| 488 | for id := range c.reap.unknownRuns { |
| 489 | if !keep[id] { |
| 490 | delete(c.reap.unknownRuns, id) |
| 491 | delete(c.reap.unknownAlerted, id) |
| 492 | } |
| 493 | } |
| 494 | c.reap.mu.Lock() |
| 495 | clear(c.reap.observed) |
| 496 | c.reap.mu.Unlock() |
| 497 | } |
| 498 | |
| 499 | // orphan is a listed VM that matches no job, with when it was first seen. |
| 500 | type orphan struct { |
| 501 | ref isolatedjob.Ref |
| 502 | firstSeen T |
| 503 | } |
| 504 | |
| 505 | // reapOrphans is step 5. It needs a complete List: an incomplete one (or any |
| 506 | // List error) skips this step alone, with nothing recorded or stopped, even |
| 507 | // if the answer carried VMs. With a complete List, trackOrphans updates |
| 508 | // unmatched_vms, and the orphans whose grace is over go to recheckOrphans. |
| 509 | func (c *Controller) reapOrphans(ctx context.Context, rep *ReapReport) error { |
| 510 | vms, err := c.runner.List(ctx) |
| 511 | if err != nil { |
| 512 | rep.Skipped = true |
| 513 | if errors.Is(err, isolatedjob.ErrIncomplete) { |
| 514 | return nil |
| 515 | } |
| 516 | return fmt.Errorf("hostedctl: reap: list VMs: %w", err) |
| 517 | } |
| 518 | expired, err := c.trackOrphans(context.WithoutCancel(ctx), vms, rep) |
| 519 | if err != nil || len(expired) == 0 { |
| 520 | return err |
| 521 | } |
| 522 | return c.recheckOrphans(ctx, expired, rep) |
| 523 | } |
| 524 | |
| 525 | // trackOrphans records, in one transaction, every listed VM that is not |
| 526 | // terminal (unknown counts as possibly live) and is not a saved Ref of any |
| 527 | // job. That includes a VM made for an intent that was abandoned, which |
| 528 | // never gets a Ref. A first sighting is inserted into unmatched_vms with the |
| 529 | // current controller time and audited; a row whose VM is no longer such a |
| 530 | // VM (gone, terminal or now matched) is deleted. It returns the orphans |
| 531 | // whose grace is over (graceOver), leaving out those already stopping. |
| 532 | func (c *Controller) trackOrphans(ctx context.Context, vms []isolatedjob.Job, rep *ReapReport) ([]orphan, error) { |
| 533 | var expired []orphan |
| 534 | live := map[isolatedjob.Ref]bool{} |
| 535 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 536 | expired = expired[:0] |
| 537 | clear(live) |
| 538 | saved, err := savedRefs(ctx, tx) |
| 539 | if err != nil { |
| 540 | return err |
| 541 | } |
| 542 | known, err := unmatchedVMs(ctx, tx) |
| 543 | if err != nil { |
| 544 | return err |
| 545 | } |
| 546 | now := c.store.Clock().Now() |
| 547 | for _, vm := range vms { |
| 548 | if vm.State.Terminal() || saved[vm.Ref] || live[vm.Ref] { |
| 549 | continue |
| 550 | } |
| 551 | live[vm.Ref] = true |
| 552 | first, ok := known[vm.Ref] |
| 553 | if !ok { |
| 554 | first = now |
| 555 | if _, err := tx.ExecContext(ctx, `INSERT INTO unmatched_vms (vm_ref, first_seen_t) VALUES (?, ?)`, |
| 556 | string(vm.Ref), int64(now)); err != nil { |
| 557 | return fmt.Errorf("hostedctl: record unmatched VM %s: %w", vm.Ref, err) |
| 558 | } |
| 559 | if err := appendAudit(tx, Audit{Action: actionOrphanSeen, At: now, Reason: fmt.Sprintf( |
| 560 | "VM %s (%s) matches no job; it is stopped after %v unless a job claims it", vm.Ref, vm.State, OrphanGrace)}); err != nil { |
| 561 | return err |
| 562 | } |
| 563 | } |
| 564 | if vm.State != isolatedjob.StateStopping && c.graceOver(first, now) { |
| 565 | expired = append(expired, orphan{ref: vm.Ref, firstSeen: first}) |
| 566 | } |
| 567 | } |
| 568 | for ref := range known { |
| 569 | if live[ref] { |
| 570 | continue |
| 571 | } |
| 572 | if _, err := tx.ExecContext(ctx, `DELETE FROM unmatched_vms WHERE vm_ref = ?`, string(ref)); err != nil { |
| 573 | return fmt.Errorf("hostedctl: forget unmatched VM %s: %w", ref, err) |
| 574 | } |
| 575 | } |
| 576 | return nil |
| 577 | }) |
| 578 | if err != nil { |
| 579 | return nil, err |
| 580 | } |
| 581 | rep.OrphansSeen = len(live) |
| 582 | for ref := range c.reap.orphanAlerted { |
| 583 | if !live[ref] { |
| 584 | delete(c.reap.orphanAlerted, ref) |
| 585 | } |
| 586 | } |
| 587 | for ref := range c.reap.orphanDeferred { |
| 588 | if !live[ref] { |
| 589 | delete(c.reap.orphanDeferred, ref) |
| 590 | } |
| 591 | } |
| 592 | return expired, nil |
| 593 | } |
| 594 | |
| 595 | // graceOver reports whether an orphan first seen at first has had its |
| 596 | // grace at controller time now: OrphanGrace has passed, or it was first |
| 597 | // seen before this process opened the store after a restart, as the |
| 598 | // downtime since is unknown. |
| 599 | func (c *Controller) graceOver(first, now T) bool { |
| 600 | return now-first >= T(OrphanGrace) || (c.store.Restarted() && first < c.store.OpenedAt()) |
| 601 | } |
| 602 | |
| 603 | // recheckOrphans makes sure each orphan whose grace is over is still |
| 604 | // nobody's before it is stopped: |
| 605 | // |
| 606 | // 1. Replay again, so a waiting intent whose lost launch reply made the VM |
| 607 | // claims it through its client token. A controller with no fresh |
| 608 | // passing audit (a fresh one has none until step 6) runs the audit |
| 609 | // first (reaperAudit, so its result counts like step 6's), or Replay |
| 610 | // would create nothing and so claim nothing. |
| 611 | // 2. The final check, holding the ownership lock for writing until the |
| 612 | // last provider Stop (R23), so no dispatch saves a Ref or marks an |
| 613 | // intent dispatched meanwhile: List again (it must be complete; |
| 614 | // otherwise nothing is stopped), then read the saved Refs and count the |
| 615 | // waiting intents that have been dispatched, after the List, so a Ref |
| 616 | // saved while the List ran is seen. |
| 617 | // |
| 618 | // An orphan no longer listed, terminal, stopping or now matched is left. |
| 619 | // While any waiting intent has been dispatched (last_dispatch_t set), the |
| 620 | // rest are deferred, not stopped (R22): the table cannot tell which unlinked |
| 621 | // VM such an intent's lost launch reply made. Each deferral is audited once |
| 622 | // until the orphan is stopped or leaves the candidates. Abandoned intents |
| 623 | // never defer: their VMs are orphans. A waiting intent is abandoned by its |
| 624 | // stop time at the latest, so deferral ends within the job's lifetime. |
| 625 | // Otherwise the orphan is stopped (stopOrphan). |
| 626 | func (c *Controller) recheckOrphans(ctx context.Context, expired []orphan, rep *ReapReport) error { |
| 627 | var errs []error |
| 628 | if c.audit.check(c.store.Clock().Now()) != nil { |
| 629 | errs = append(errs, c.reaperAudit(ctx)) |
| 630 | } |
| 631 | n, err := c.replayCounted(ctx) |
| 632 | rep.Replayed += n |
| 633 | errs = append(errs, err) |
| 634 | return errors.Join(append(errs, c.finalOrphanCheck(ctx, expired, rep))...) |
| 635 | } |
| 636 | |
| 637 | // finalOrphanCheck is step 2 of recheckOrphans, under the ownership lock. |
| 638 | func (c *Controller) finalOrphanCheck(ctx context.Context, expired []orphan, rep *ReapReport) error { |
| 639 | c.ownership.mu.Lock() |
| 640 | defer c.ownership.mu.Unlock() |
| 641 | vms, err := c.runner.List(ctx) |
| 642 | if err != nil { |
| 643 | rep.Skipped = true |
| 644 | if errors.Is(err, isolatedjob.ErrIncomplete) { |
| 645 | return nil |
| 646 | } |
| 647 | return fmt.Errorf("hostedctl: reap: list VMs for the ownership recheck: %w", err) |
| 648 | } |
| 649 | var saved map[isolatedjob.Ref]bool |
| 650 | var dispatched int |
| 651 | if err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 652 | var err error |
| 653 | if saved, err = savedRefs(ctx, tx); err != nil { |
| 654 | return err |
| 655 | } |
| 656 | if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs WHERE state = ? AND vm_ref IS NULL |
| 657 | AND last_dispatch_t IS NOT NULL`, JobWaiting).Scan(&dispatched); err != nil { |
| 658 | return fmt.Errorf("hostedctl: reap: count dispatched intents: %w", err) |
| 659 | } |
| 660 | return nil |
| 661 | }); err != nil { |
| 662 | return err |
| 663 | } |
| 664 | listed := make(map[isolatedjob.Ref]isolatedjob.State, len(vms)) |
| 665 | for _, vm := range vms { |
| 666 | listed[vm.Ref] = vm.State |
| 667 | } |
| 668 | var errs []error |
| 669 | for _, o := range expired { |
| 670 | st, ok := listed[o.ref] |
| 671 | if !ok || st.Terminal() || st == isolatedjob.StateStopping || saved[o.ref] { |
| 672 | continue |
| 673 | } |
| 674 | if dispatched > 0 { |
| 675 | errs = append(errs, c.deferOrphan(ctx, o, dispatched, rep)) |
| 676 | continue |
| 677 | } |
| 678 | delete(c.reap.orphanDeferred, o.ref) |
| 679 | errs = append(errs, c.stopOrphan(ctx, o, rep)) |
| 680 | } |
| 681 | return errors.Join(errs...) |
| 682 | } |
| 683 | |
| 684 | // deferOrphan counts an orphan left running because n waiting intents have |
| 685 | // been dispatched (R22), and audits it once per run of deferrals. |
| 686 | func (c *Controller) deferOrphan(ctx context.Context, o orphan, n int, rep *ReapReport) error { |
| 687 | rep.OrphansDeferred++ |
| 688 | c.logOrphanDeferred(o, c.store.Clock().Now(), n) |
| 689 | if c.reap.orphanDeferred[o.ref] { |
| 690 | return nil |
| 691 | } |
| 692 | if c.reap.orphanDeferred == nil { |
| 693 | c.reap.orphanDeferred = map[isolatedjob.Ref]bool{} |
| 694 | } |
| 695 | c.reap.orphanDeferred[o.ref] = true |
| 696 | return c.auditReaper(context.WithoutCancel(ctx), actionOrphanDeferred, fmt.Sprintf( |
| 697 | "VM %s matches no job and its grace is over, but %d waiting launch intent(s) were dispatched and may own it; "+ |
| 698 | "it is stopped once they hold a VM or are abandoned", o.ref, n)) |
| 699 | } |
| 700 | |
| 701 | // stopOrphan sends the provider stop for an orphan, with the reason |
| 702 | // "orphan", then audits it and raises one orphan_stopped alert per VM. No |
| 703 | // job owns the VM, so no proof is recorded. A failed stop call is audited |
| 704 | // and returned; the next pass rechecks and sends it again. |
| 705 | func (c *Controller) stopOrphan(ctx context.Context, o orphan, rep *ReapReport) error { |
| 706 | now := c.store.Clock().Now() |
| 707 | why := fmt.Sprintf("matched no job for %v", time.Duration(now-o.firstSeen)) |
| 708 | if now-o.firstSeen < T(OrphanGrace) { |
| 709 | why = "matched no job since before the controller restarted (downtime unknown, so its grace counts as over)" |
| 710 | } |
| 711 | perr := c.runner.Stop(ctx, o.ref, reasonOrphan) |
| 712 | rec := context.WithoutCancel(ctx) |
| 713 | if perr != nil && !errors.Is(perr, isolatedjob.ErrNotFound) { |
| 714 | c.logOrphanStopFailed(o) |
| 715 | aerr := c.auditReaper(rec, actionOrphanStopFailed, |
| 716 | fmt.Sprintf("VM %s %s; the provider stop call failed and is sent again next pass", o.ref, why)) |
| 717 | return errors.Join(fmt.Errorf("hostedctl: reap: stop orphan VM %s: %w", o.ref, perr), aerr) |
| 718 | } |
| 719 | rep.OrphansStopped++ |
| 720 | c.logOrphanStopped(o, now) |
| 721 | reason := fmt.Sprintf("VM %s %s and was still unclaimed after a replay and a fresh list; provider stop sent", o.ref, why) |
| 722 | if !c.reap.orphanAlerted[o.ref] { |
| 723 | if c.reap.orphanAlerted == nil { |
| 724 | c.reap.orphanAlerted = map[isolatedjob.Ref]bool{} |
| 725 | } |
| 726 | c.reap.orphanAlerted[o.ref] = true |
| 727 | c.reap.raise(Alert{Kind: AlertOrphanStopped, Detail: reason, At: now}) |
| 728 | } |
| 729 | return c.auditReaper(rec, actionOrphanStopped, reason) |
| 730 | } |
| 731 | |
| 732 | // reaperAudit runs every audit the reaper triggers: step 6, and the |
| 733 | // recheck's when no fresh passing audit is held. It calls RunAudit, which |
| 734 | // records the result the launch gates read, and tracks runs of failures |
| 735 | // across both: when a run begins it audits the failure and raises one |
| 736 | // audit_failed alert; the first passing audit after it ends the run and is |
| 737 | // audited. A failing audit is returned. An audit cut short by ctx starts no |
| 738 | // run. |
| 739 | func (c *Controller) reaperAudit(ctx context.Context) error { |
| 740 | err := c.RunAudit(ctx) |
| 741 | rec := context.WithoutCancel(ctx) |
| 742 | switch { |
| 743 | case err == nil && !c.reap.auditFailing: |
| 744 | return nil |
| 745 | case err == nil: |
| 746 | c.reap.auditFailing = false |
| 747 | return c.auditReaper(rec, actionNetworkAuditPassed, "network audit passes again; launches may go ahead") |
| 748 | case c.reap.auditFailing || ctx.Err() != nil: |
| 749 | return err |
| 750 | } |
| 751 | c.reap.auditFailing = true |
| 752 | c.reap.raise(Alert{Kind: AlertAuditFailed, At: c.store.Clock().Now(), |
| 753 | Detail: "network audit failed; launches are refused until it passes: " + err.Error()}) |
| 754 | return errors.Join(err, c.auditReaper(rec, actionNetworkAuditFailed, "launches refused: "+err.Error())) |
| 755 | } |
| 756 | |
| 757 | // sendAlerts delivers the queued alerts in order. One the Alerter refuses |
| 758 | // stays queued for the next pass, and its error is returned. |
| 759 | func (c *Controller) sendAlerts(ctx context.Context) error { |
| 760 | var errs []error |
| 761 | keep := c.reap.queued[:0] |
| 762 | for _, a := range c.reap.queued { |
| 763 | if err := c.alerter.Alert(ctx, a); err != nil { |
| 764 | keep = append(keep, a) |
| 765 | errs = append(errs, fmt.Errorf("hostedctl: deliver %s alert: %w", a.Kind, err)) |
| 766 | } |
| 767 | } |
| 768 | clear(c.reap.queued[len(keep):]) |
| 769 | c.reap.queued = keep |
| 770 | return errors.Join(errs...) |
| 771 | } |
| 772 | |
| 773 | // auditReaper writes one audit row by the controller about no attempt. |
| 774 | func (c *Controller) auditReaper(ctx context.Context, action, reason string) error { |
| 775 | return c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 776 | return appendAudit(tx, Audit{Action: action, Reason: reason, At: c.store.Clock().Now()}) |
| 777 | }) |
| 778 | } |
| 779 | |
| 780 | // savedRefs reads every VM Ref saved on a job, proven or not. |
| 781 | func savedRefs(ctx context.Context, tx *sql.Tx) (map[isolatedjob.Ref]bool, error) { |
| 782 | ids, err := textColumn(ctx, tx, `SELECT vm_ref FROM jobs WHERE vm_ref IS NOT NULL`) |
| 783 | if err != nil { |
| 784 | return nil, err |
| 785 | } |
| 786 | out := make(map[isolatedjob.Ref]bool, len(ids)) |
| 787 | for _, r := range ids { |
| 788 | out[isolatedjob.Ref(r)] = true |
| 789 | } |
| 790 | return out, nil |
| 791 | } |
| 792 | |
| 793 | // unmatchedVMs reads unmatched_vms. |
| 794 | func unmatchedVMs(ctx context.Context, tx *sql.Tx) (map[isolatedjob.Ref]T, error) { |
| 795 | rows, err := tx.QueryContext(ctx, `SELECT vm_ref, first_seen_t FROM unmatched_vms`) |
| 796 | if err != nil { |
| 797 | return nil, fmt.Errorf("hostedctl: read unmatched VMs: %w", err) |
| 798 | } |
| 799 | defer rows.Close() |
| 800 | out := map[isolatedjob.Ref]T{} |
| 801 | for rows.Next() { |
| 802 | var ref string |
| 803 | var first int64 |
| 804 | if err := rows.Scan(&ref, &first); err != nil { |
| 805 | return nil, fmt.Errorf("hostedctl: read unmatched VMs: %w", err) |
| 806 | } |
| 807 | out[isolatedjob.Ref(ref)] = T(first) |
| 808 | } |
| 809 | if err := rows.Err(); err != nil { |
| 810 | return nil, fmt.Errorf("hostedctl: read unmatched VMs: %w", err) |
| 811 | } |
| 812 | return out, nil |
| 813 | } |
| 814 | |
| 815 | // textColumn runs a query returning one text column and collects it. |
| 816 | func textColumn(ctx context.Context, tx *sql.Tx, query string, args ...any) ([]string, error) { |
| 817 | rows, err := tx.QueryContext(ctx, query, args...) |
| 818 | if err != nil { |
| 819 | return nil, fmt.Errorf("hostedctl: reap: query: %w", err) |
| 820 | } |
| 821 | defer rows.Close() |
| 822 | var out []string |
| 823 | for rows.Next() { |
| 824 | var s string |
| 825 | if err := rows.Scan(&s); err != nil { |
| 826 | return nil, fmt.Errorf("hostedctl: reap: query: %w", err) |
| 827 | } |
| 828 | out = append(out, s) |
| 829 | } |
| 830 | if err := rows.Err(); err != nil { |
| 831 | return nil, fmt.Errorf("hostedctl: reap: query: %w", err) |
| 832 | } |
| 833 | return out, nil |
| 834 | } |
| 835 | |