package hostedctl import ( "context" "database/sql" "errors" "fmt" "sync" "time" "amadan.net/oficina/equipo/internal/isolatedjob" ) // ReflessProofDelay is how long, in controller time, a List must start after // the stop request, the last launch dispatch and this process's Open before // it can prove that a job with no VM Ref has no VM (R19). A launch whose // reply was lost may still be landing until then. const ReflessProofDelay = 2 * time.Minute // ProviderLaunchTimeout bounds every provider Launch call (Launch and // Replay dispatch) (ruling R21). It is shorter than ReflessProofDelay, so a // call that this process dispatched has returned or given up before a List // can prove its job has no VM. const ProviderLaunchTimeout = 60 * time.Second // ProviderCallTimeout bounds every other provider call (Get, List, Stop, // Suspend, Resume and the network audit), retries included (ruling R27), so // no stalled call holds an attempt lock or a reaper pass for longer. const ProviderCallTimeout = 30 * time.Second // RestartGetTries is how many Refresh passes in a row may fail to read a // pre-restart job's VM before the controller stops it as elapsed_unknown // (R20). const RestartGetTries = 3 // rebasedSet holds the jobs whose elapsed time Refresh has settled since this // controller started: re-based on the provider's age, or stopped because the // provider gave none. Each pre-restart job is settled once per process. type rebasedSet struct { mu sync.Mutex done map[string]bool fails map[string]int // consecutive Refresh passes whose Get failed } // failGet counts one more failed Get for attempt and returns the count. func (s *rebasedSet) failGet(attempt string) int { s.mu.Lock() defer s.mu.Unlock() if s.fails == nil { s.fails = map[string]int{} } s.fails[attempt]++ return s.fails[attempt] } // readOK ends attempt's run of failed Gets. func (s *rebasedSet) readOK(attempt string) { s.mu.Lock() defer s.mu.Unlock() delete(s.fails, attempt) } func (s *rebasedSet) has(attempt string) bool { s.mu.Lock() defer s.mu.Unlock() return s.done[attempt] } func (s *rebasedSet) add(attempt string) { s.mu.Lock() defer s.mu.Unlock() if s.done == nil { s.done = map[string]bool{} } s.done[attempt] = true } // Refresh reconciles the job table with the provider. One failing job does // not stop the others; Refresh returns their errors joined. No transaction // is held across a provider call. // // Every job with a VM Ref and no proof is read with Runner.Get: // // - a terminal state is proof and is saved. isolatedjob.ErrNotFound is // proof only when confirmed by a second not-found NotFoundConfirm later // with no live Get between (see notFound); the first is recorded and the // job left pending. A job with no stop request ended on its own and gets // the stop reason "ended", so replacements may go ahead; // - a live state is saved as the job's state first, which also clears // any first not-found (before anything below can return); // - after a restart, a job launched at or before Store.OpenedAt has an // untrusted elapsed time (the wall delta Open used says nothing about // the real downtime). Once per process, with a provider age, its // launched_t becomes min(launched_t, T before the Get minus the age) and // its deadline, drain and stop times are recomputed with Deadlines, each // only ever moved earlier. With no age, the controller stops it with the // reason "elapsed_unknown". A Get that fails leaves it unsettled for the // next pass; after RestartGetTries failed passes in a row it is stopped // as elapsed_unknown too (R20), the Get error still returned; // - an unknown state is left as it is; // - a job with a stop request whose VM is not known to be stopping (live, // unknown, or unreadable because Get failed) gets the provider stop // again on every pass, whatever its restart state. // // Each job is reconciled under its attempt lock (R18), so the restart // check and its settling are one step, and no other operation on the job // interleaves with its provider calls. // // Then, when a job with no VM Ref is abandoned and has a stop request, one // List: if it is complete, started at least ReflessProofDelay after the // latest of that request, the job's last launch dispatch and OpenedAt, and // shows no VM that is not terminal and not a saved Ref of some // job, the job gets proof with an empty VMRef and state stopped. Until then // it stays pending; the orphan reaper stops any such VM. func (c *Controller) Refresh(ctx context.Context) error { var withRef []string refless := false err := c.store.Tx(ctx, func(tx *sql.Tx) error { withRef, refless = withRef[:0], false rows, err := tx.QueryContext(ctx, `SELECT attempt_id, vm_ref IS NOT NULL FROM jobs WHERE stop_proof_json IS NULL AND (vm_ref IS NOT NULL OR (state = ? AND stop_requested_t IS NOT NULL)) ORDER BY launched_t, attempt_id`, JobAbandoned) if err != nil { return fmt.Errorf("hostedctl: list jobs to refresh: %w", err) } defer rows.Close() for rows.Next() { var id string var hasRef bool if err := rows.Scan(&id, &hasRef); err != nil { return fmt.Errorf("hostedctl: list jobs to refresh: %w", err) } if hasRef { withRef = append(withRef, id) } else { refless = true } } return rows.Err() }) if err != nil { return err } var errs []error for _, id := range withRef { if err := ctx.Err(); err != nil { return errors.Join(append(errs, err)...) } if err := c.refreshOne(ctx, id); err != nil { errs = append(errs, err) } } if refless { if err := c.proveRefless(ctx); err != nil { errs = append(errs, err) } } return errors.Join(errs...) } // refreshOne reconciles one job with a VM Ref; see Refresh. func (c *Controller) refreshOne(ctx context.Context, attempt string) error { defer c.lockAttempt(attempt)() var j jobRow var reason sql.NullString found := false err := c.store.Tx(ctx, func(tx *sql.Tx) error { var err error if j, found, err = loadJob(ctx, tx, attempt); err != nil || !found { return err } return tx.QueryRowContext(ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, attempt).Scan(&reason) }) if err != nil { return err } if !found || !j.ref.Valid || j.stopProof.Valid { return nil } ref := isolatedjob.Ref(j.ref.String) untrusted := c.store.Restarted() && T(j.launchedT) <= c.store.OpenedAt() && !c.rebased.has(attempt) before := c.store.Clock().Now() job, gerr := c.runner.Get(ctx, ref) at := c.store.Clock().Now() c.reap.observeGet(attempt, job.State, gerr) // for the reaper's unknown-state count rec := context.WithoutCancel(ctx) switch { case errors.Is(gerr, isolatedjob.ErrNotFound): _, _, err := c.notFound(rec, "", attempt, ref, before, at, "refresh: provider holds no such VM") return err case gerr != nil: err := fmt.Errorf("hostedctl: refresh %s: read VM %s: %w", attempt, ref, gerr) if untrusted && c.rebased.failGet(attempt) >= RestartGetTries { return errors.Join(err, c.stopElapsedUnknown(ctx, attempt)) } if j.stopRequested.Valid { // A pending stop is sent again whatever the VM read and the // restart state say: the provider's Stop is idempotent. return errors.Join(err, c.resendStop(ctx, j, ref, reason.String)) } return err case job.State.Terminal(): _, err := c.recordProof(rec, "", attempt, StopProof{AttemptID: attempt, VMRef: ref, State: job.State, ObservedAt: at}, "refresh: provider reports the VM "+string(job.State)) return err } c.rebased.readOK(attempt) if job.State.Live() { // First, so a live sighting clears any first not-found even when // the restart handling below stops the job. It gets ctx, not rec: // its provider calls must end when the caller does (R27). if err := c.mirrorLive(ctx, j, job.State); err != nil { return err } } if untrusted { if !job.AgeKnown || job.ProviderAge < 0 { return c.stopElapsedUnknown(ctx, attempt) } if err := c.rebase(rec, attempt, before-T(job.ProviderAge), job.ProviderAge); err != nil { return err } c.rebased.add(attempt) } if j.stopRequested.Valid && job.State != isolatedjob.StateStopping { // Live and not yet stopping, or unknown (it may be live). return c.resendStop(ctx, j, ref, reason.String) } return nil } // resendStop sends the provider stop again for j, whose stop was asked for // and is not proven. A failure is audited with a fixed reason and returned; // the next Refresh sends it again. func (c *Controller) resendStop(ctx context.Context, j jobRow, ref isolatedjob.Ref, reason string) error { perr := c.runner.Stop(ctx, ref, reason) if perr == nil || errors.Is(perr, isolatedjob.ErrNotFound) { return nil } r := stopReq{attempt: j.attempt, account: j.account, task: j.task, ref: ref} aerr := c.auditStop(context.WithoutCancel(ctx), "", r, actionStopFailed, "refresh: provider stop call failed; it is sent again on the next refresh") return errors.Join(fmt.Errorf("hostedctl: refresh %s: stop VM %s: %w", j.attempt, ref, perr), aerr) } // stopElapsedUnknown is the controller's own stop of a pre-restart job the // provider gave no age for, or whose VM it could not read RestartGetTries // passes in a row. The caller holds the attempt's lock. Once the request is recorded the job counts as // settled; a pending or unknown result is left for the next Refresh. func (c *Controller) stopElapsedUnknown(ctx context.Context, attempt string) error { r, err := c.requestStop(context.WithoutCancel(ctx), "", attempt, reasonElapsedUnknown, false) if err != nil { return err } c.logElapsedUnknown(attempt) c.rebased.add(attempt) if r.proof != nil { return nil } _, err = c.driveStop(ctx, "", r) if errors.Is(err, ErrStopPending) || errors.Is(err, ErrStateUnknown) { return nil } return err } // rebase moves a pre-restart job's launch time back to cand when cand is // earlier, and its deadline, drain and stop times to those Deadlines gives // for it, each only when earlier than the stored one. It is audited even // when nothing moves. func (c *Controller) rebase(ctx context.Context, attempt string, cand T, age time.Duration) error { var launchedBy, stopBy time.Duration moved := false err := c.store.Tx(ctx, func(tx *sql.Tx) error { moved = false j, found, err := loadJob(ctx, tx, attempt) if err != nil || !found || j.stopProof.Valid { return err } spec, err := decodeSpec(j.specJSON, attempt) if err != nil { return err } launched := min(T(j.launchedT), cand) deadline, drain, stop := Deadlines(launched, spec.MaxLifetime) deadline, drain, stop = min(deadline, T(j.deadlineT)), min(drain, T(j.drainT)), min(stop, T(j.stopT)) if _, err := tx.ExecContext(ctx, `UPDATE jobs SET launched_t = ?, deadline_t = ?, drain_t = ?, stop_t = ?, revision = revision + 1 WHERE attempt_id = ?`, int64(launched), int64(deadline), int64(drain), int64(stop), attempt); err != nil { return fmt.Errorf("hostedctl: re-base %s: %w", attempt, err) } launchedBy, stopBy, moved = time.Duration(T(j.launchedT)-launched), time.Duration(T(j.stopT)-stop), true return appendAudit(tx, Audit{Account: j.account, Task: j.task, Attempt: attempt, Action: actionRestartRebased, Reason: fmt.Sprintf("after a restart the provider reports age %v; launched moved back by %v, stop time by %v", age, launchedBy, stopBy), At: c.store.Clock().Now()}) }) if err == nil && moved { c.logRebased(attempt, age, launchedBy, stopBy) } return err } // proveRefless issues proof for abandoned, stop-requested jobs with no VM // Ref; see Refresh. An incomplete List proves nothing and is not an error. // The List and the check for unlinked VMs come first; then each job is // settled under its attempt lock in a transaction of its own. func (c *Controller) proveRefless(ctx context.Context) error { start := c.store.Clock().Now() vms, err := c.runner.List(ctx) at := c.store.Clock().Now() if errors.Is(err, isolatedjob.ErrIncomplete) { return nil } if err != nil { return fmt.Errorf("hostedctl: list VMs for stop proof: %w", err) } ctx = context.WithoutCancel(ctx) // record what the list showed even if the caller has gone var ids []string err = c.store.Tx(ctx, func(tx *sql.Tx) error { ids = ids[:0] saved := map[isolatedjob.Ref]bool{} rows, err := tx.QueryContext(ctx, `SELECT vm_ref FROM jobs WHERE vm_ref IS NOT NULL`) if err != nil { return fmt.Errorf("hostedctl: read saved VM refs: %w", err) } for rows.Next() { var ref string if err := rows.Scan(&ref); err != nil { _ = rows.Close() return fmt.Errorf("hostedctl: read saved VM refs: %w", err) } saved[isolatedjob.Ref(ref)] = true } if err := errors.Join(rows.Err(), rows.Close()); err != nil { return fmt.Errorf("hostedctl: read saved VM refs: %w", err) } for _, vm := range vms { // An unknown state may be a live VM, so only terminal ones pass. if !vm.State.Terminal() && !saved[vm.Ref] { return nil // ids stays empty: no proof this pass } } rows, err = tx.QueryContext(ctx, `SELECT attempt_id FROM jobs WHERE vm_ref IS NULL AND state = ? AND stop_requested_t IS NOT NULL AND stop_proof_json IS NULL ORDER BY attempt_id`, JobAbandoned) if err != nil { return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err) } for rows.Next() { var id string if err := rows.Scan(&id); err != nil { _ = rows.Close() return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err) } ids = append(ids, id) } if err := errors.Join(rows.Err(), rows.Close()); err != nil { return fmt.Errorf("hostedctl: list jobs without a VM ref: %w", err) } return nil }) if err != nil { return err } var errs []error for _, id := range ids { if err := c.proveReflessOne(ctx, id, start, at); err != nil { errs = append(errs, err) } } return errors.Join(errs...) } // proveReflessOne saves proof for one Ref-less job when the List that began // at start began at least ReflessProofDelay after the latest of its stop // request, its last launch dispatch and OpenedAt. func (c *Controller) proveReflessOne(ctx context.Context, attempt string, start, at T) error { defer c.lockAttempt(attempt)() return c.store.Tx(ctx, func(tx *sql.Tx) error { j, found, err := loadJob(ctx, tx, attempt) if err != nil { return err } if !found || j.ref.Valid || j.state != JobAbandoned || !j.stopRequested.Valid || j.stopProof.Valid { return nil } var dispatched sql.NullInt64 if err := tx.QueryRowContext(ctx, `SELECT last_dispatch_t FROM jobs WHERE attempt_id = ?`, attempt).Scan(&dispatched); err != nil { return fmt.Errorf("hostedctl: read last_dispatch_t of %s: %w", attempt, err) } since := max(T(j.stopRequested.Int64), c.store.OpenedAt()) if dispatched.Valid { since = max(since, T(dispatched.Int64)) } if start-since < T(ReflessProofDelay) { return nil } p := StopProof{AttemptID: attempt, State: isolatedjob.StateStopped, ObservedAt: at} return writeProof(ctx, tx, "", j, p, fmt.Sprintf( "a complete list begun %v after the stop request, the last dispatch and the controller start shows no VM outside the job table", time.Duration(start-since))) }) } // markDispatch records, just before a provider launch call, that one is // about to be made for attempt (R19). Ref-less proof waits // ReflessProofDelay past it, so a VM the call creates late is still seen. func (c *Controller) markDispatch(ctx context.Context, attempt string) error { return c.store.Tx(ctx, func(tx *sql.Tx) error { res, err := tx.ExecContext(ctx, `UPDATE jobs SET last_dispatch_t = ?, revision = revision + 1 WHERE attempt_id = ?`, int64(c.store.Clock().Now()), attempt) if err != nil { return fmt.Errorf("hostedctl: record dispatch of %s: %w", attempt, err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: record dispatch of %s: %d rows (%v)", attempt, n, err) } return nil }) }