// Package hostedctl is the core of equipo-hosted-controller: the job table, // controller time, launch intents, stop proof, pause generations, resume // epochs and the reaper. It talks to VMs only through isolatedjob.Runner. package hostedctl import ( "context" "database/sql" "database/sql/driver" "embed" "errors" "fmt" "math" "net/url" "sync" "sync/atomic" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" "modernc.org/sqlite" ) // ErrSchemaNewer: the database was written by a newer controller. Open // refuses it rather than guess what the newer columns mean. var ErrSchemaNewer = errors.New("hostedctl: database schema is newer than this controller") // ErrStoreInUse: another Store, in this process or another, has the // database open. One controller owns a database at a time. var ErrStoreInUse = errors.New("hostedctl: database is open in another controller") // ErrNoncePruned: the nonce's validity window reaches back into a window // whose nonces were already pruned, which happens when the wall clock went // back. A replay there could not be told from a new request, so Remember // denies it. var ErrNoncePruned = errors.New("hostedctl: nonce window already pruned (wall clock went back)") // ErrStoreLost: the Store's one connection, and with it the exclusive lock, // is gone. The Store stays failed and never reconnects, because another // controller may own the database since. Close it and Open afresh, which // takes the lock again and restores controller time. var ErrStoreLost = errors.New("hostedctl: store connection lost; close and reopen") // AlertClockRollback is the alert kind, and the audit action, raised when // Open finds the wall clock behind the last checkpoint. const AlertClockRollback = "clock_rollback" //go:embed schema/*.sql var schemaFS embed.FS // migrations are applied in order; version n is migrations[n-1]. Add a file, // never edit one. var migrations = []string{"schema/0001_jobs.sql"} // schemaVersion is the newest schema this code knows. func schemaVersion() int { return len(migrations) } // Store is the controller's SQLite database and its controller time. type Store struct { db *sql.DB conn *sql.Conn // the one connection, pinned at Open; it holds the exclusive lock txMu sync.Mutex // one transaction at a time on conn lost atomic.Bool host isolatedjob.Clock clock *CtlClock restarted bool mu sync.Mutex pending []outboxAlert // undelivered rows of alert_outbox, oldest first closed bool } // outboxAlert is one undelivered alert_outbox row. type outboxAlert struct { id int64 alert Alert } // Audit is one audit row. Actor is the verified key that asked, or empty for // the controller itself. Reason never holds credentials. type Audit struct { Actor hostedwire.KeyID Account, Task, Attempt, Action, Reason string At T } // Open opens or creates the store at path, applies any missing schema // migrations, and restores controller time from the last checkpoint. // // Open holds SQLite's exclusive lock on the database file for the Store's // whole life, so a second Open of the same file, by any name (a symlink or // a hard link included), fails at once with ErrStoreInUse until the first is // closed. // // On a fresh database controller time starts at 0 and Restarted is false. // Otherwise T starts at the checkpoint's T plus the wall time since the // checkpoint, or the checkpoint's T alone when the wall clock is behind it; // Restarted is true; and a wall clock behind the checkpoint is audited and // queued in alert_outbox, in the same transaction, for New to deliver. // Either way Open writes a fresh checkpoint, so T never falls below a T // already restored, and loads every undelivered alert. func Open(ctx context.Context, path string, c isolatedjob.Clock) (*Store, error) { if path == "" { return nil, errors.New("hostedctl: store path is empty") } if isNil(c) { return nil, errors.New("hostedctl: store needs a clock") } // _txlock=immediate makes every transaction BEGIN IMMEDIATE: it takes the // write lock up front, so a read-check-write sequence is never // interleaved with another writer. recursive_triggers makes the implicit // delete of INSERT OR REPLACE fire jobs_never_deleted. // // locking_mode(EXCLUSIVE) makes the connection keep SQLite's lock on the // database file, taken at Open's first write, until it closes. The lock // follows the file, not the name, and is SQLite's own, so it cannot clash // with SQLite's locking the way a separate flock on the file can (BSD, // NFS). No other connection may touch the database while a Store holds // it, so busy_timeout is 0: a second Open fails at once instead of // waiting. (modernc runs busy_timeout first and the other pragmas in name // order, so WAL is entered before EXCLUSIVE; SQLite allows that switch.) dsn := (&url.URL{Scheme: "file", Path: path}).String() + "?_pragma=busy_timeout(0)&_pragma=journal_mode(WAL)&_pragma=locking_mode(EXCLUSIVE)" + "&_pragma=synchronous(FULL)&_pragma=foreign_keys(1)&_pragma=recursive_triggers(1)&_txlock=immediate" db, err := sql.Open("sqlite", dsn) if err != nil { return nil, fmt.Errorf("hostedctl: open store: %w", err) } // One connection, pinned for the Store's life: it takes the exclusive // lock at Open's first write and every Store operation runs on it. If // database/sql discards it, nothing reconnects (see ErrStoreLost). db.SetMaxOpenConns(1) conn, err := db.Conn(ctx) if err != nil { _ = db.Close() return nil, inUse(fmt.Errorf("hostedctl: open store: %w", err), path) } s := &Store{db: db, conn: conn, host: c} if err := s.migrate(ctx); err != nil { _ = s.release() return nil, inUse(err, path) } if err := s.restoreClock(ctx); err != nil { _ = s.release() return nil, err } return s, nil } // inUse turns SQLite's "busy" or "locked" at Open into ErrStoreInUse: // another connection holds the database. func inUse(err error, path string) error { var e *sqlite.Error if errors.As(err, &e) { switch e.Code() & 0xff { case 5, 6: // SQLITE_BUSY, SQLITE_LOCKED return fmt.Errorf("%w: %s: %w", ErrStoreInUse, path, err) } } return err } // migrate applies the missing migrations in one transaction. The version is // read inside the transaction, so two Opens racing apply each one once. func (s *Store) migrate(ctx context.Context) error { tx, err := s.conn.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("hostedctl: migrate: %w", err) } defer func() { _ = tx.Rollback() }() var version int if err := tx.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&version); err != nil { return fmt.Errorf("hostedctl: read schema version: %w", err) } if version > schemaVersion() { return fmt.Errorf("%w: database at version %d, this controller knows %d", ErrSchemaNewer, version, schemaVersion()) } if version == schemaVersion() { return nil } for v := version; v < schemaVersion(); v++ { body, err := schemaFS.ReadFile(migrations[v]) if err != nil { return fmt.Errorf("hostedctl: read migration %s: %w", migrations[v], err) } if _, err := tx.ExecContext(ctx, string(body)); err != nil { return fmt.Errorf("hostedctl: apply migration %s: %w", migrations[v], err) } if _, err := tx.ExecContext(ctx, fmt.Sprintf(`PRAGMA user_version = %d`, v+1)); err != nil { return fmt.Errorf("hostedctl: record schema version %d: %w", v+1, err) } } if err := tx.Commit(); err != nil { return fmt.Errorf("hostedctl: migrate: %w", err) } return nil } // restoreClock sets controller time from the last checkpoint and writes a // new one, in one transaction with any clock_rollback audit row. func (s *Store) restoreClock(ctx context.Context) error { tx, err := s.conn.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("hostedctl: restore clock: %w", err) } defer func() { _ = tx.Rollback() }() wallNow := s.host.Wall().UnixNano() monoNow := s.host.Mono() var cpT, cpWall int64 var base T var rollback time.Duration restarted := false err = tx.QueryRowContext(ctx, `SELECT t_ns, wall_unix_ns FROM clock WHERE id = 1`).Scan(&cpT, &cpWall) switch { case errors.Is(err, sql.ErrNoRows): // a fresh database: T starts at 0 case err != nil: return fmt.Errorf("hostedctl: read clock checkpoint: %w", err) default: restarted = true if base, rollback, err = restoreBase(T(cpT), cpWall, wallNow); err != nil { return err } } if rollback > 0 { detail := fmt.Sprintf("wall clock %v behind the last checkpoint at start; controller time kept at %v", rollback, time.Duration(base)) if err := appendAudit(tx, Audit{Action: AlertClockRollback, Reason: detail, At: base}); err != nil { return err } if _, err := tx.ExecContext(ctx, `INSERT INTO alert_outbox (kind, detail, at_t) VALUES (?, ?, ?)`, AlertClockRollback, detail, int64(base)); err != nil { return fmt.Errorf("hostedctl: queue %s alert: %w", AlertClockRollback, err) } } if _, err := tx.ExecContext(ctx, `INSERT INTO clock (id, t_ns, wall_unix_ns) VALUES (1, ?, ?) ON CONFLICT (id) DO UPDATE SET t_ns = excluded.t_ns, wall_unix_ns = excluded.wall_unix_ns`, int64(base), wallNow); err != nil { return fmt.Errorf("hostedctl: write clock checkpoint: %w", err) } pending, err := undeliveredAlerts(ctx, tx) if err != nil { return err } if err := tx.Commit(); err != nil { return fmt.Errorf("hostedctl: restore clock: %w", err) } s.clock = &CtlClock{base: base, monoAtOpen: monoNow, c: s.host} s.restarted = restarted s.pending = pending return nil } // undeliveredAlerts reads alert_outbox rows not yet delivered, oldest first. // Each alert's detail starts with its stable event ID, "alert : ". func undeliveredAlerts(ctx context.Context, tx *sql.Tx) ([]outboxAlert, error) { rows, err := tx.QueryContext(ctx, `SELECT id, kind, detail, at_t FROM alert_outbox WHERE delivered = 0 ORDER BY id`) if err != nil { return nil, fmt.Errorf("hostedctl: read alert outbox: %w", err) } defer rows.Close() var out []outboxAlert for rows.Next() { var o outboxAlert var detail string var at int64 if err := rows.Scan(&o.id, &o.alert.Kind, &detail, &at); err != nil { return nil, fmt.Errorf("hostedctl: read alert outbox: %w", err) } o.alert.Detail = fmt.Sprintf("alert %d: %s", o.id, detail) o.alert.At = T(at) out = append(out, o) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("hostedctl: read alert outbox: %w", err) } return out, nil } // Close checkpoints controller time, closes the database and releases the // exclusive lock. A second Close does nothing. A lost Store skips the // checkpoint (it no longer owns the database) and just lets go. func (s *Store) Close() error { s.mu.Lock() if s.closed { s.mu.Unlock() return nil } s.closed = true s.mu.Unlock() var cpErr error if !s.lost.Load() { cpErr = s.Checkpoint(context.Background()) } return errors.Join(cpErr, s.release()) } // release closes the pinned connection and the database, which drops the // exclusive lock. func (s *Store) release() error { err := s.conn.Close() if errors.Is(err, sql.ErrConnDone) { err = nil // already discarded } return errors.Join(err, s.db.Close()) } // Clock returns the store's controller clock. func (s *Store) Clock() *CtlClock { return s.clock } // Restarted reports whether Open found state from an earlier run. When it // is true, the time that passed while the controller was down is unknown. // The wall delta Open added to T is untrusted in either direction: the // downtime may be longer or shorter, so it is never proof of how long a job // has lived. func (s *Store) Restarted() bool { return s.restarted } // OpenedAt returns controller time at Open. Every T stored before Open is at // or below it, so after a restart a job launched at or before OpenedAt // existed before this process opened the store. func (s *Store) OpenedAt() T { return s.clock.base } // StartupAlerts returns the undelivered alerts from alert_outbox, as loaded // by Open and not yet delivered by New, oldest first. func (s *Store) StartupAlerts() []Alert { s.mu.Lock() defer s.mu.Unlock() out := make([]Alert, 0, len(s.pending)) for _, p := range s.pending { out = append(out, p.alert) } return out } // deliverStartupAlerts sends each undelivered alert, in order, and marks its // outbox row delivered. It stops at the first failure; that alert stays // queued, in memory and in the database, and is tried again by the next New // or after a restart. Delivery is at least once: a crash, or a failed mark, // after the Alerter accepted an alert sends it again with the same ID. func (s *Store) deliverStartupAlerts(ctx context.Context, a Alerter) error { s.mu.Lock() defer s.mu.Unlock() for len(s.pending) > 0 { p := s.pending[0] if err := a.Alert(ctx, p.alert); err != nil { return fmt.Errorf("hostedctl: deliver %s alert %d: %w", p.alert.Kind, p.id, err) } if err := s.Tx(ctx, func(tx *sql.Tx) error { _, err := tx.ExecContext(ctx, `UPDATE alert_outbox SET delivered = 1 WHERE id = ?`, p.id) return err }); err != nil { return fmt.Errorf("hostedctl: mark alert %d delivered: %w", p.id, err) } s.pending = s.pending[1:] } return nil } // bindProvider binds the database to provider namespace ns, with an audit // row, when it has no binding yet, and returns ErrProviderMismatch when it is // bound to another (ruling R28). func (s *Store) bindProvider(ctx context.Context, ns string) error { return s.Tx(ctx, func(tx *sql.Tx) error { var bound string err := tx.QueryRowContext(ctx, `SELECT namespace FROM provider_binding WHERE id = 1`).Scan(&bound) switch { case errors.Is(err, sql.ErrNoRows): if _, err := tx.ExecContext(ctx, `INSERT INTO provider_binding (id, namespace) VALUES (1, ?)`, ns); err != nil { return fmt.Errorf("hostedctl: bind provider namespace: %w", err) } return appendAudit(tx, Audit{Action: "provider_bound", Reason: "database bound to provider namespace " + ns, At: s.clock.Now()}) case err != nil: return fmt.Errorf("hostedctl: read provider binding: %w", err) case bound != ns: return fmt.Errorf("%w: bound to %q, configured for %q", ErrProviderMismatch, bound, ns) } return nil }) } // Tx runs fn in one write transaction, which holds SQLite's write lock from // the start. It rolls back when fn returns an error (returned as is) or // panics, and otherwise checkpoints controller time and commits. Use the tx // handle for every statement inside fn, audit rows included. Never call Tx, // Checkpoint or Remember from inside fn: transactions run one at a time on // the one connection, so the inner call would wait forever. Do provider // calls outside fn. // // When a call fails and the pinned connection turns out to be gone (the // error says so, or a ping on it fails), the Store is marked lost: this and // every later call returns ErrStoreLost. // // The checkpoint is sampled after fn returns, so it is at least every T fn // read or wrote, and it commits with fn's writes: no committed row holds a T // later than the checkpoint, so T after any restart is at least every // stored T even when the wall clock went back. A T only read and never // stored may appear to step back after a crash (ruling R10). func (s *Store) Tx(ctx context.Context, fn func(*sql.Tx) error) error { s.txMu.Lock() defer s.txMu.Unlock() if s.lost.Load() { return ErrStoreLost } err := s.runTx(ctx, fn) if err != nil && s.connGone(ctx, err) { s.lost.Store(true) return fmt.Errorf("%w: %w", ErrStoreLost, err) } return err } // connGone reports whether err, or a ping on the pinned connection, shows // the connection was discarded. func (s *Store) connGone(ctx context.Context, err error) bool { if errors.Is(err, driver.ErrBadConn) || errors.Is(err, sql.ErrConnDone) { return true } return s.conn.PingContext(context.WithoutCancel(ctx)) != nil } // runTx is one transaction on the pinned connection; see Tx. func (s *Store) runTx(ctx context.Context, fn func(*sql.Tx) error) error { tx, err := s.conn.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("hostedctl: begin: %w", err) } done := false defer func() { if !done { _ = tx.Rollback() } }() if err := fn(tx); err != nil { return err } if err := s.checkpoint(ctx, tx); err != nil { return err } if err := tx.Commit(); err != nil { return fmt.Errorf("hostedctl: commit: %w", err) } done = true return nil } // Checkpoint records (controller time, wall time) so a restart can carry T // on. The reaper calls it every pass; every Tx commit does it too. func (s *Store) Checkpoint(ctx context.Context) error { return s.Tx(ctx, func(*sql.Tx) error { return nil }) } func (s *Store) checkpoint(ctx context.Context, tx *sql.Tx) error { res, err := tx.ExecContext(ctx, `UPDATE clock SET t_ns = ?, wall_unix_ns = ? WHERE id = 1`, int64(s.clock.Now()), s.host.Wall().UnixNano()) if err != nil { return fmt.Errorf("hostedctl: clock checkpoint: %w", err) } if n, err := res.RowsAffected(); err != nil || n != 1 { return fmt.Errorf("hostedctl: clock checkpoint row missing (%d rows, %v)", n, err) } return nil } // Remember implements hostedwire.NonceStore. It records (id, nonce) until the // given wall time. In one transaction it: // 1. reports false (a replay) when a row for the pair exists, whatever its // expiry, before anything is pruned; // 2. finds the bound: the larger of the durable pruned-through mark and the // latest expiry this call is about to prune (by this host's wall clock); // 3. denies with ErrNoncePruned when until <= bound + 2*hostedwire.MaxSkew. // The wall clock moved past this window, forward between Verify and // Remember or back after a prune, and a forgotten nonce's replay could // pass the skew check there. The margin covers a replay sent up to // 2 MaxSkew later than the original; // 4. prunes the expired rows, raises the mark, and inserts the nonce. // // Any database error returns false with the error, so the request is denied. func (s *Store) Remember(ctx context.Context, id hostedwire.KeyID, nonce string, until time.Time) (bool, error) { if id == "" || nonce == "" { return false, errors.New("hostedctl: nonce needs a key ID and a value") } untilNs := until.UnixNano() fresh := false err := s.Tx(ctx, func(tx *sql.Tx) error { var held int if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM nonces WHERE key_id = ? AND nonce = ?`, string(id), nonce).Scan(&held); err != nil { return fmt.Errorf("hostedctl: look up nonce: %w", err) } if held > 0 { return nil // a replay } var through sql.NullInt64 err := tx.QueryRowContext(ctx, `SELECT through_unix_ns FROM nonce_pruned WHERE id = 1`).Scan(&through) if err != nil && !errors.Is(err, sql.ErrNoRows) { return fmt.Errorf("hostedctl: read nonce prune mark: %w", err) } wallNow := s.host.Wall().UnixNano() var pruned sql.NullInt64 if err := tx.QueryRowContext(ctx, `SELECT max(until_unix_ns) FROM nonces WHERE until_unix_ns < ?`, wallNow).Scan(&pruned); err != nil { return fmt.Errorf("hostedctl: find expired nonces: %w", err) } bound := through if pruned.Valid && (!bound.Valid || pruned.Int64 > bound.Int64) { bound = pruned } if bound.Valid && (bound.Int64 > math.MaxInt64-int64(2*hostedwire.MaxSkew) || untilNs <= bound.Int64+int64(2*hostedwire.MaxSkew)) { return fmt.Errorf("%w: until %d, pruned through %d", ErrNoncePruned, untilNs, bound.Int64) } if pruned.Valid { if _, err := tx.ExecContext(ctx, `DELETE FROM nonces WHERE until_unix_ns < ?`, wallNow); err != nil { return fmt.Errorf("hostedctl: prune nonces: %w", err) } if _, err := tx.ExecContext(ctx, `INSERT INTO nonce_pruned (id, through_unix_ns) VALUES (1, ?) ON CONFLICT (id) DO UPDATE SET through_unix_ns = max(through_unix_ns, excluded.through_unix_ns)`, pruned.Int64); err != nil { return fmt.Errorf("hostedctl: record nonce prune mark: %w", err) } } res, err := tx.ExecContext(ctx, `INSERT INTO nonces (key_id, nonce, until_unix_ns) VALUES (?, ?, ?) ON CONFLICT (key_id, nonce) DO NOTHING`, string(id), nonce, untilNs) if err != nil { return fmt.Errorf("hostedctl: remember nonce: %w", err) } n, err := res.RowsAffected() if err != nil { return fmt.Errorf("hostedctl: remember nonce: %w", err) } fresh = n == 1 return nil }) if err != nil { return false, err } return fresh, nil } // appendAudit adds one audit row inside tx, so it commits or rolls back with // the change it records. a must name an action and must not hold // credentials. func appendAudit(tx *sql.Tx, a Audit) error { if a.Action == "" { return errors.New("hostedctl: audit row needs an action") } _, err := tx.Exec(`INSERT INTO audit (actor_key, account_id, task_id, attempt_id, action, reason, at_t) VALUES (?, ?, ?, ?, ?, ?, ?)`, string(a.Actor), a.Account, a.Task, a.Attempt, a.Action, a.Reason, int64(a.At)) if err != nil { return fmt.Errorf("hostedctl: append audit: %w", err) } return nil }