package hostedctl import ( "context" "database/sql" "errors" "fmt" "sync" "time" "amadan.net/oficina/equipo/internal/isolatedjob" ) // ReapInterval is how often Loop runs a reaper pass unless told otherwise // (spec §10). const ReapInterval = 60 * time.Second // OrphanGrace is how long, in controller time, a listed VM that matches no // job is left alone before the reaper rechecks its ownership and stops it // (spec §10). After a restart, an orphan first seen before Open has used up // its grace: the downtime is unknown, so the time since the sighting is too. const OrphanGrace = 10 * time.Minute // UnknownAlertPasses is how many reaper passes in a row a job's VM must read // unknown before the reaper raises an unknown_state alert for it. const UnknownAlertPasses = 3 // Alert kinds the reaper raises. Details name VMs, attempts, tasks and // accounts, never credentials. const ( // AlertOrphanStopped: the reaper stopped a VM that matched no job. AlertOrphanStopped = "orphan_stopped" // AlertUnknownState: a job's VM read unknown on UnknownAlertPasses // passes in a row. Raised once per run of unknown reads. AlertUnknownState = "unknown_state" // AlertAuditFailed: the network audit failed, so launches are refused. // Raised once per run of failed audits. AlertAuditFailed = "audit_failed" ) // Stop reasons the reaper sends to the provider. const ( reasonDeadline = "deadline" // the job reached its stop time reasonOrphan = "orphan" // the VM matched no job ) // Audit actions written by the reaper. const ( actionDeadlineDrain = "deadline_drain" actionOrphanSeen = "orphan_seen" actionOrphanStopped = "orphan_stopped" actionOrphanStopFailed = "orphan_stop_failed" actionOrphanDeferred = "orphan_deferred" actionUnknownState = "unknown_state" actionNetworkAuditFailed = "network_audit_failed" actionNetworkAuditPassed = "network_audit_passed" ) // ReapReport counts what one reaper pass did. type ReapReport struct { // Skipped: orphan processing was skipped because a List was incomplete // or failed: the whole step on the first List, or the stops on the // recheck's List. The pass's other steps ran. Skipped bool // Replayed: launch intents that gained a VM Ref in the pass's replays. Replayed int // Drained: jobs given their drain mark in this pass. Drained int // Stopped: jobs whose deadline stop this pass asked for. Stopped int // OrphansSeen: listed VMs, not terminal, that match no job's saved Ref. OrphansSeen int // OrphansStopped: orphans the provider was asked to stop in this pass. OrphansStopped int // OrphansDeferred: orphans whose grace is over left running in this // pass because a waiting intent that has been dispatched might own // them (ruling R22). OrphansDeferred int // Unknown: jobs whose VM read unknown in this pass's Refresh. Unknown int } // ReapResult is one finished pass: its report, its error and the controller // time at which it finished. type ReapResult struct { Report ReapReport Err error At T } // reapState is the reaper's in-memory state. A restart starts it afresh: // alerts held back by an Alerter failure are lost, and running episodes // alert again. type reapState struct { pass sync.Mutex // held for a whole pass: one pass at a time mu sync.Mutex observed map[string]bool // attempt -> Refresh's latest Get read unknown; absent: no answer since the last pass last ReapResult ran bool // Used only under pass. unknownRuns map[string]int // attempt -> passes in a row its VM read unknown unknownAlerted map[string]bool // attempt -> its current run was alerted orphanAlerted map[isolatedjob.Ref]bool orphanDeferred map[isolatedjob.Ref]bool // orphans whose current deferral was audited auditFailing bool // an audit_failed episode is open queued []Alert // alerts not yet delivered, oldest first } // ownershipLock keeps VM ownership still while the orphan reaper decides // (ruling R23). Every dispatch holds it for reading from before it reads the // intent and checks the creation gates to its settled answer (a saved Ref, // or the intent left waiting or abandoned), so a wait for it never lets a // checked gate go stale before the provider call; the // orphan final check holds it for writing from its fresh List to its last // provider Stop. So no Ref is saved, and no intent is newly marked // dispatched, between the reaper reading ownership and stopping a VM. // // Lock order: an attempt lock, then this. The orphan path takes no attempt // lock. Never take it inside a store transaction. type ownershipLock struct { mu sync.RWMutex // waiting, when set, is called each time a dispatch finds the lock // held for writing and is about to wait. Tests use it to see the wait // without sleeping; production leaves it nil. waiting func() } // rlock takes the lock for reading and returns its release. func (o *ownershipLock) rlock() func() { if !o.mu.TryRLock() { if o.waiting != nil { o.waiting() } o.mu.RLock() } return o.mu.RUnlock } // observeGet records what Refresh's Get said about attempt's VM, for the // reaper's unknown-state count. A state that is neither live nor terminal // counts as unknown; a not-found is a known answer; any other error says // nothing. func (s *reapState) observeGet(attempt string, st isolatedjob.State, err error) { s.mu.Lock() defer s.mu.Unlock() if s.observed == nil { s.observed = map[string]bool{} } switch { case err == nil: s.observed[attempt] = !st.Live() && !st.Terminal() case errors.Is(err, isolatedjob.ErrNotFound): s.observed[attempt] = false default: delete(s.observed, attempt) } } // takeObserved returns and forgets the latest observation for attempt. ok // is false when there is none. func (s *reapState) takeObserved(attempt string) (unknown, ok bool) { s.mu.Lock() defer s.mu.Unlock() unknown, ok = s.observed[attempt] delete(s.observed, attempt) return unknown, ok } // raise queues a for delivery at the end of the pass. The caller holds pass. func (s *reapState) raise(a Alert) { s.queued = append(s.queued, a) } // LastReap returns the last finished pass, and false when none has finished. // Task 15's metrics read it. func (c *Controller) LastReap() (ReapResult, bool) { c.reap.mu.Lock() defer c.reap.mu.Unlock() return c.reap.last, c.reap.ran } // Loop runs Reap at once and then every `every` (ReapInterval when every is // not positive) until ctx is done, one pass at a time. A pass's error never // ends the loop; it is kept for LastReap, and the last pass's error is // returned when ctx is done. func (c *Controller) Loop(ctx context.Context, every time.Duration) error { if every <= 0 { every = ReapInterval } tick := time.NewTicker(every) defer tick.Stop() var last error for { if ctx.Err() != nil { return last } _, last = c.Reap(ctx) select { case <-ctx.Done(): return last case <-tick.C: } } } // Reap runs one reaper pass (spec §10). Passes run one at a time. In order: // // 1. Checkpoint controller time. A failure ends the pass: the store is // needed for everything after it. Then every recorded job past its // stop time gets its deadline stop (reapOverdue, R26), so the slow // launch calls of step 2 never hold it up. // 2. Replay launch intents, with their gates (Replay), so a VM a lost // launch reply made is claimed before anything looks for orphans. // 3. Refresh. // 4. Recorded jobs, by their saved Ref, whatever List returns: a job past // its drain time gets its drain mark (a notice; no pause), a job past // its stop time gets a deadline stop, and a VM that read unknown is // counted and, after UnknownAlertPasses passes, alerted (Refresh has // already sent a requested stop again). See reapJob and trackUnknown. // 5. Orphans, only on a complete List (reapOrphans): VMs that match no // job's saved Ref are recorded in unmatched_vms and stopped once // OrphanGrace has passed and a recheck still finds them unclaimed, // unless a dispatched waiting intent may own them (deferred, R22). // 6. The network audit (reaperAudit). While it fails, launches are // refused; an audit_failed alert goes out when a run of failures // begins. // // Then the pass's alerts are delivered. A step's failure, an Alerter's // included, does not stop the steps after it; the pass returns every // failure joined, and keeps its result for LastReap. func (c *Controller) Reap(ctx context.Context) (ReapReport, error) { c.reap.pass.Lock() defer c.reap.pass.Unlock() var rep ReapReport err := c.reapPass(ctx, &rep) c.reap.mu.Lock() c.reap.last, c.reap.ran = ReapResult{Report: rep, Err: err, At: c.store.Clock().Now()}, true c.reap.mu.Unlock() return rep, err } func (c *Controller) reapPass(ctx context.Context, rep *ReapReport) error { if err := c.store.Checkpoint(ctx); err != nil { return fmt.Errorf("hostedctl: reap: clock checkpoint: %w", err) } errs := []error{c.reapOverdue(ctx, rep)} n, err := c.replayCounted(ctx) rep.Replayed += n errs = append(errs, err) errs = append(errs, c.Refresh(ctx)) errs = append(errs, c.reapJobs(ctx, rep)) errs = append(errs, c.reapOrphans(ctx, rep)) errs = append(errs, c.reaperAudit(ctx)) errs = append(errs, c.sendAlerts(ctx)) return errors.Join(errs...) } // replayCounted runs Replay when an intent is waiting and returns how many // of the intents waiting before it hold a VM Ref after it. func (c *Controller) replayCounted(ctx context.Context) (int, error) { var waiting []string err := c.store.Tx(ctx, func(tx *sql.Tx) error { var err error waiting, err = textColumn(ctx, tx, `SELECT attempt_id FROM jobs WHERE state = ? AND vm_ref IS NULL`, JobWaiting) return err }) if err != nil || len(waiting) == 0 { return 0, err } rerr := c.Replay(ctx) n := 0 err = c.store.Tx(ctx, func(tx *sql.Tx) error { n = 0 for _, id := range waiting { j, found, err := loadJob(ctx, tx, id) if err != nil { return err } if found && j.ref.Valid { n++ } } return nil }) return n, errors.Join(rerr, err) } // reapOverdue is step 1b (ruling R26): every job with a saved Ref and no // proof whose stop time has come is stopped before Replay, so launch calls, // each up to ProviderLaunchTimeout, never delay it. With no stop request it // gets its deadline stop (reapJob). With one, whatever its reason, the // provider stop is sent again (resendStop), its recorded reason and request // time unchanged, so a stop whose provider call failed is retried here too. // Re-basing after a restart only moves stop times earlier, so this never // stops a job early; step 4 and Refresh repeat idempotently. func (c *Controller) reapOverdue(ctx context.Context, rep *ReapReport) error { var ids []string err := c.store.Tx(ctx, func(tx *sql.Tx) error { var err error ids, err = textColumn(ctx, tx, `SELECT attempt_id FROM jobs WHERE vm_ref IS NOT NULL AND stop_proof_json IS NULL AND stop_t <= ? ORDER BY launched_t, attempt_id`, int64(c.store.Clock().Now())) return err }) if err != nil { return err } var errs []error for _, id := range ids { if err := ctx.Err(); err != nil { return errors.Join(append(errs, err)...) } pending, err := c.resendPendingStop(ctx, id) if err == nil && !pending { _, err = c.reapJob(ctx, id, rep) } errs = append(errs, err) } return errors.Join(errs...) } // resendPendingStop sends the provider stop again, under the attempt's // lock, for a job with a saved Ref, a stop request and no proof, with the // recorded reason. pending is false, and nothing is sent, for any other job. func (c *Controller) resendPendingStop(ctx context.Context, attempt string) (pending bool, err error) { defer c.lockAttempt(attempt)() var j jobRow var reason sql.NullString err = c.store.Tx(ctx, func(tx *sql.Tx) error { var found bool var err error if j, found, err = loadJob(ctx, tx, attempt); err != nil || !found { return err } pending = j.ref.Valid && j.stopRequested.Valid && !j.stopProof.Valid return tx.QueryRowContext(ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, attempt).Scan(&reason) }) if err != nil || !pending { return pending, err } return true, c.resendStop(ctx, j, isolatedjob.Ref(j.ref.String), reason.String) } // reapJobs is step 4: every job with a saved Ref and no proof, in launch // order. It reads no List, so an incomplete one never holds up a deadline. func (c *Controller) reapJobs(ctx context.Context, rep *ReapReport) error { var ids []string err := c.store.Tx(ctx, func(tx *sql.Tx) error { var err error ids, err = textColumn(ctx, tx, `SELECT attempt_id FROM jobs WHERE vm_ref IS NOT NULL AND stop_proof_json IS NULL ORDER BY launched_t, attempt_id`) return err }) if err != nil { return err } var errs []error for _, id := range ids { if err := ctx.Err(); err != nil { errs = append(errs, err) break } j, err := c.reapJob(ctx, id, rep) errs = append(errs, err, c.trackUnknown(ctx, id, j, rep)) } c.forgetUnknowns(ids) return errors.Join(errs...) } // reapJob handles one recorded job under its attempt lock. A job with a stop // asked for, or proof, is left to Refresh. Otherwise, by controller time: // // - at or past its stop time, it gets a stop with the reason "deadline": // the request is recorded first (requestStop), then the provider stop is // sent and the VM read (driveStop). Refresh proves it on a later pass; // - at or past its drain time and not yet marked, drain_marked_t is set // and audited. This is the notice before the stop; it opens no pause // generation and leaves the job's state alone. // // It returns the job as read, zero when it is gone. func (c *Controller) reapJob(ctx context.Context, attempt string, rep *ReapReport) (jobRow, error) { defer c.lockAttempt(attempt)() var j jobRow marked, stop := false, false err := c.store.Tx(ctx, func(tx *sql.Tx) error { marked, stop = false, false var found bool var err error if j, found, err = loadJob(ctx, tx, attempt); err != nil || !found { return err } if !j.ref.Valid || j.stopProof.Valid || j.stopRequested.Valid { return nil } now := c.store.Clock().Now() if now >= T(j.stopT) { stop = true return nil } if now < T(j.drainT) { return nil } res, err := tx.ExecContext(ctx, `UPDATE jobs SET drain_marked_t = ?, revision = revision + 1 WHERE attempt_id = ? AND drain_marked_t IS NULL`, int64(now), attempt) if err != nil { return fmt.Errorf("hostedctl: mark drain of %s: %w", attempt, err) } n, err := res.RowsAffected() if err != nil { return fmt.Errorf("hostedctl: mark drain of %s: %w", attempt, err) } if n == 0 { return nil // marked on an earlier pass } marked = true return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: attempt, Action: actionDeadlineDrain, Reason: fmt.Sprintf("drain time reached; VM %s is stopped in %v", j.ref.String, time.Duration(T(j.stopT)-now)), At: now}) }) if err != nil { return j, err } if marked { rep.Drained++ } if !stop { return j, nil } r, err := c.requestStop(context.WithoutCancel(ctx), "", attempt, reasonDeadline, false) if err != nil { return j, err } rep.Stopped++ if r.proof != nil { return j, nil } if _, err := c.driveStop(ctx, "", r); err != nil && !errors.Is(err, ErrStopPending) && !errors.Is(err, ErrStateUnknown) { return j, err } return j, nil } // trackUnknown counts attempt's run of unknown reads from this pass's // Refresh. A known state, or a not-found, ends the run. When the run reaches // UnknownAlertPasses one unknown_state alert is raised and audited; the // next comes only after a known read ends the run and a new one reaches the // count. A stop asked for is sent again by Refresh on every unknown read // (refreshOne), so it is not sent again here. func (c *Controller) trackUnknown(ctx context.Context, attempt string, j jobRow, rep *ReapReport) error { unknown, ok := c.reap.takeObserved(attempt) if !ok { return nil } s := &c.reap if !unknown { delete(s.unknownRuns, attempt) delete(s.unknownAlerted, attempt) return nil } rep.Unknown++ if s.unknownRuns == nil { s.unknownRuns, s.unknownAlerted = map[string]int{}, map[string]bool{} } s.unknownRuns[attempt]++ if s.unknownRuns[attempt] < UnknownAlertPasses || s.unknownAlerted[attempt] { return nil } s.unknownAlerted[attempt] = true then := "no stop has been asked for" if j.stopRequested.Valid { then = "its stop is sent again each pass" } detail := fmt.Sprintf("VM %s of attempt %s (task %s, account %s) read unknown on %d passes in a row; %s", j.ref.String, attempt, j.task, j.account, s.unknownRuns[attempt], then) now := c.store.Clock().Now() s.raise(Alert{Kind: AlertUnknownState, Detail: detail, At: now}) return c.store.Tx(context.WithoutCancel(ctx), func(tx *sql.Tx) error { return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: attempt, Action: actionUnknownState, Reason: detail, At: now}) }) } // forgetUnknowns drops the unknown-read runs of attempts no longer in ids // (proven, or gone) and any observation not taken this pass. func (c *Controller) forgetUnknowns(ids []string) { keep := make(map[string]bool, len(ids)) for _, id := range ids { keep[id] = true } for id := range c.reap.unknownRuns { if !keep[id] { delete(c.reap.unknownRuns, id) delete(c.reap.unknownAlerted, id) } } c.reap.mu.Lock() clear(c.reap.observed) c.reap.mu.Unlock() } // orphan is a listed VM that matches no job, with when it was first seen. type orphan struct { ref isolatedjob.Ref firstSeen T } // reapOrphans is step 5. It needs a complete List: an incomplete one (or any // List error) skips this step alone, with nothing recorded or stopped, even // if the answer carried VMs. With a complete List, trackOrphans updates // unmatched_vms, and the orphans whose grace is over go to recheckOrphans. func (c *Controller) reapOrphans(ctx context.Context, rep *ReapReport) error { vms, err := c.runner.List(ctx) if err != nil { rep.Skipped = true if errors.Is(err, isolatedjob.ErrIncomplete) { return nil } return fmt.Errorf("hostedctl: reap: list VMs: %w", err) } expired, err := c.trackOrphans(context.WithoutCancel(ctx), vms, rep) if err != nil || len(expired) == 0 { return err } return c.recheckOrphans(ctx, expired, rep) } // trackOrphans records, in one transaction, every listed VM that is not // terminal (unknown counts as possibly live) and is not a saved Ref of any // job. That includes a VM made for an intent that was abandoned, which // never gets a Ref. A first sighting is inserted into unmatched_vms with the // current controller time and audited; a row whose VM is no longer such a // VM (gone, terminal or now matched) is deleted. It returns the orphans // whose grace is over (graceOver), leaving out those already stopping. func (c *Controller) trackOrphans(ctx context.Context, vms []isolatedjob.Job, rep *ReapReport) ([]orphan, error) { var expired []orphan live := map[isolatedjob.Ref]bool{} err := c.store.Tx(ctx, func(tx *sql.Tx) error { expired = expired[:0] clear(live) saved, err := savedRefs(ctx, tx) if err != nil { return err } known, err := unmatchedVMs(ctx, tx) if err != nil { return err } now := c.store.Clock().Now() for _, vm := range vms { if vm.State.Terminal() || saved[vm.Ref] || live[vm.Ref] { continue } live[vm.Ref] = true first, ok := known[vm.Ref] if !ok { first = now if _, err := tx.ExecContext(ctx, `INSERT INTO unmatched_vms (vm_ref, first_seen_t) VALUES (?, ?)`, string(vm.Ref), int64(now)); err != nil { return fmt.Errorf("hostedctl: record unmatched VM %s: %w", vm.Ref, err) } if err := appendAudit(tx, Audit{Action: actionOrphanSeen, At: now, Reason: fmt.Sprintf( "VM %s (%s) matches no job; it is stopped after %v unless a job claims it", vm.Ref, vm.State, OrphanGrace)}); err != nil { return err } } if vm.State != isolatedjob.StateStopping && c.graceOver(first, now) { expired = append(expired, orphan{ref: vm.Ref, firstSeen: first}) } } for ref := range known { if live[ref] { continue } if _, err := tx.ExecContext(ctx, `DELETE FROM unmatched_vms WHERE vm_ref = ?`, string(ref)); err != nil { return fmt.Errorf("hostedctl: forget unmatched VM %s: %w", ref, err) } } return nil }) if err != nil { return nil, err } rep.OrphansSeen = len(live) for ref := range c.reap.orphanAlerted { if !live[ref] { delete(c.reap.orphanAlerted, ref) } } for ref := range c.reap.orphanDeferred { if !live[ref] { delete(c.reap.orphanDeferred, ref) } } return expired, nil } // graceOver reports whether an orphan first seen at first has had its // grace at controller time now: OrphanGrace has passed, or it was first // seen before this process opened the store after a restart, as the // downtime since is unknown. func (c *Controller) graceOver(first, now T) bool { return now-first >= T(OrphanGrace) || (c.store.Restarted() && first < c.store.OpenedAt()) } // recheckOrphans makes sure each orphan whose grace is over is still // nobody's before it is stopped: // // 1. Replay again, so a waiting intent whose lost launch reply made the VM // claims it through its client token. A controller with no fresh // passing audit (a fresh one has none until step 6) runs the audit // first (reaperAudit, so its result counts like step 6's), or Replay // would create nothing and so claim nothing. // 2. The final check, holding the ownership lock for writing until the // last provider Stop (R23), so no dispatch saves a Ref or marks an // intent dispatched meanwhile: List again (it must be complete; // otherwise nothing is stopped), then read the saved Refs and count the // waiting intents that have been dispatched, after the List, so a Ref // saved while the List ran is seen. // // An orphan no longer listed, terminal, stopping or now matched is left. // While any waiting intent has been dispatched (last_dispatch_t set), the // rest are deferred, not stopped (R22): the table cannot tell which unlinked // VM such an intent's lost launch reply made. Each deferral is audited once // until the orphan is stopped or leaves the candidates. Abandoned intents // never defer: their VMs are orphans. A waiting intent is abandoned by its // stop time at the latest, so deferral ends within the job's lifetime. // Otherwise the orphan is stopped (stopOrphan). func (c *Controller) recheckOrphans(ctx context.Context, expired []orphan, rep *ReapReport) error { var errs []error if c.audit.check(c.store.Clock().Now()) != nil { errs = append(errs, c.reaperAudit(ctx)) } n, err := c.replayCounted(ctx) rep.Replayed += n errs = append(errs, err) return errors.Join(append(errs, c.finalOrphanCheck(ctx, expired, rep))...) } // finalOrphanCheck is step 2 of recheckOrphans, under the ownership lock. func (c *Controller) finalOrphanCheck(ctx context.Context, expired []orphan, rep *ReapReport) error { c.ownership.mu.Lock() defer c.ownership.mu.Unlock() vms, err := c.runner.List(ctx) if err != nil { rep.Skipped = true if errors.Is(err, isolatedjob.ErrIncomplete) { return nil } return fmt.Errorf("hostedctl: reap: list VMs for the ownership recheck: %w", err) } var saved map[isolatedjob.Ref]bool var dispatched int if err := c.store.Tx(ctx, func(tx *sql.Tx) error { var err error if saved, err = savedRefs(ctx, tx); err != nil { return err } if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs WHERE state = ? AND vm_ref IS NULL AND last_dispatch_t IS NOT NULL`, JobWaiting).Scan(&dispatched); err != nil { return fmt.Errorf("hostedctl: reap: count dispatched intents: %w", err) } return nil }); err != nil { return err } listed := make(map[isolatedjob.Ref]isolatedjob.State, len(vms)) for _, vm := range vms { listed[vm.Ref] = vm.State } var errs []error for _, o := range expired { st, ok := listed[o.ref] if !ok || st.Terminal() || st == isolatedjob.StateStopping || saved[o.ref] { continue } if dispatched > 0 { errs = append(errs, c.deferOrphan(ctx, o, dispatched, rep)) continue } delete(c.reap.orphanDeferred, o.ref) errs = append(errs, c.stopOrphan(ctx, o, rep)) } return errors.Join(errs...) } // deferOrphan counts an orphan left running because n waiting intents have // been dispatched (R22), and audits it once per run of deferrals. func (c *Controller) deferOrphan(ctx context.Context, o orphan, n int, rep *ReapReport) error { rep.OrphansDeferred++ c.logOrphanDeferred(o, c.store.Clock().Now(), n) if c.reap.orphanDeferred[o.ref] { return nil } if c.reap.orphanDeferred == nil { c.reap.orphanDeferred = map[isolatedjob.Ref]bool{} } c.reap.orphanDeferred[o.ref] = true return c.auditReaper(context.WithoutCancel(ctx), actionOrphanDeferred, fmt.Sprintf( "VM %s matches no job and its grace is over, but %d waiting launch intent(s) were dispatched and may own it; "+ "it is stopped once they hold a VM or are abandoned", o.ref, n)) } // stopOrphan sends the provider stop for an orphan, with the reason // "orphan", then audits it and raises one orphan_stopped alert per VM. No // job owns the VM, so no proof is recorded. A failed stop call is audited // and returned; the next pass rechecks and sends it again. func (c *Controller) stopOrphan(ctx context.Context, o orphan, rep *ReapReport) error { now := c.store.Clock().Now() why := fmt.Sprintf("matched no job for %v", time.Duration(now-o.firstSeen)) if now-o.firstSeen < T(OrphanGrace) { why = "matched no job since before the controller restarted (downtime unknown, so its grace counts as over)" } perr := c.runner.Stop(ctx, o.ref, reasonOrphan) rec := context.WithoutCancel(ctx) if perr != nil && !errors.Is(perr, isolatedjob.ErrNotFound) { c.logOrphanStopFailed(o) aerr := c.auditReaper(rec, actionOrphanStopFailed, fmt.Sprintf("VM %s %s; the provider stop call failed and is sent again next pass", o.ref, why)) return errors.Join(fmt.Errorf("hostedctl: reap: stop orphan VM %s: %w", o.ref, perr), aerr) } rep.OrphansStopped++ c.logOrphanStopped(o, now) reason := fmt.Sprintf("VM %s %s and was still unclaimed after a replay and a fresh list; provider stop sent", o.ref, why) if !c.reap.orphanAlerted[o.ref] { if c.reap.orphanAlerted == nil { c.reap.orphanAlerted = map[isolatedjob.Ref]bool{} } c.reap.orphanAlerted[o.ref] = true c.reap.raise(Alert{Kind: AlertOrphanStopped, Detail: reason, At: now}) } return c.auditReaper(rec, actionOrphanStopped, reason) } // reaperAudit runs every audit the reaper triggers: step 6, and the // recheck's when no fresh passing audit is held. It calls RunAudit, which // records the result the launch gates read, and tracks runs of failures // across both: when a run begins it audits the failure and raises one // audit_failed alert; the first passing audit after it ends the run and is // audited. A failing audit is returned. An audit cut short by ctx starts no // run. func (c *Controller) reaperAudit(ctx context.Context) error { err := c.RunAudit(ctx) rec := context.WithoutCancel(ctx) switch { case err == nil && !c.reap.auditFailing: return nil case err == nil: c.reap.auditFailing = false return c.auditReaper(rec, actionNetworkAuditPassed, "network audit passes again; launches may go ahead") case c.reap.auditFailing || ctx.Err() != nil: return err } c.reap.auditFailing = true c.reap.raise(Alert{Kind: AlertAuditFailed, At: c.store.Clock().Now(), Detail: "network audit failed; launches are refused until it passes: " + err.Error()}) return errors.Join(err, c.auditReaper(rec, actionNetworkAuditFailed, "launches refused: "+err.Error())) } // sendAlerts delivers the queued alerts in order. One the Alerter refuses // stays queued for the next pass, and its error is returned. func (c *Controller) sendAlerts(ctx context.Context) error { var errs []error keep := c.reap.queued[:0] for _, a := range c.reap.queued { if err := c.alerter.Alert(ctx, a); err != nil { keep = append(keep, a) errs = append(errs, fmt.Errorf("hostedctl: deliver %s alert: %w", a.Kind, err)) } } clear(c.reap.queued[len(keep):]) c.reap.queued = keep return errors.Join(errs...) } // auditReaper writes one audit row by the controller about no attempt. func (c *Controller) auditReaper(ctx context.Context, action, reason string) error { return c.store.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Action: action, Reason: reason, At: c.store.Clock().Now()}) }) } // savedRefs reads every VM Ref saved on a job, proven or not. func savedRefs(ctx context.Context, tx *sql.Tx) (map[isolatedjob.Ref]bool, error) { ids, err := textColumn(ctx, tx, `SELECT vm_ref FROM jobs WHERE vm_ref IS NOT NULL`) if err != nil { return nil, err } out := make(map[isolatedjob.Ref]bool, len(ids)) for _, r := range ids { out[isolatedjob.Ref(r)] = true } return out, nil } // unmatchedVMs reads unmatched_vms. func unmatchedVMs(ctx context.Context, tx *sql.Tx) (map[isolatedjob.Ref]T, error) { rows, err := tx.QueryContext(ctx, `SELECT vm_ref, first_seen_t FROM unmatched_vms`) if err != nil { return nil, fmt.Errorf("hostedctl: read unmatched VMs: %w", err) } defer rows.Close() out := map[isolatedjob.Ref]T{} for rows.Next() { var ref string var first int64 if err := rows.Scan(&ref, &first); err != nil { return nil, fmt.Errorf("hostedctl: read unmatched VMs: %w", err) } out[isolatedjob.Ref(ref)] = T(first) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("hostedctl: read unmatched VMs: %w", err) } return out, nil } // textColumn runs a query returning one text column and collects it. func textColumn(ctx context.Context, tx *sql.Tx, query string, args ...any) ([]string, error) { rows, err := tx.QueryContext(ctx, query, args...) if err != nil { return nil, fmt.Errorf("hostedctl: reap: query: %w", err) } defer rows.Close() var out []string for rows.Next() { var s string if err := rows.Scan(&s); err != nil { return nil, fmt.Errorf("hostedctl: reap: query: %w", err) } out = append(out, s) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("hostedctl: reap: query: %w", err) } return out, nil }