control-api: reduce SQLite disk writes; add diagnostic mode
Disk writes: - SQLite pragmas in DSN: wal_autocheckpoint=10000, journal_size_limit=64MB, cache_size=64MB - migration 0013: drop redundant idx_checks_registry_cycle - results batched: UpsertChecksIfOpen in one transaction; agent flushes every 5s and before complete - heartbeat kept in memory, persisted on state change or every 60s; startup grace for stale sweeps Diagnostic mode: - POST /api/v1/admin/diagnostics/attach|detach, GET /api/v1/admin/diagnostics - migration 0014: diagnostic_holds; validator state "diagnostic" - held addresses are not queued, held validators skip sweeps, port release and delete Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d0ab6b94f9
commit
55d383bd34
41 files changed
+1214
-94
No files matched your search
+35
-12
@@ -8,6 +8,7 @@ import (
|
||||
"database/sql"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
@@ -49,6 +50,12 @@ var checkRunsSchema string
|
||||
//go:embed migrations/0012_self_check_failures.sql
|
||||
var selfCheckFailuresSchema string
|
||||
|
||||
//go:embed migrations/0013_drop_redundant_checks_index.sql
|
||||
var dropChecksIndexSchema string
|
||||
|
||||
//go:embed migrations/0014_diagnostic_holds.sql
|
||||
var diagnosticHoldsSchema string
|
||||
|
||||
// migrations is the ordered list of schema versions. Each entry's SQL is
|
||||
// applied, in order, for any version greater than the database's current
|
||||
// PRAGMA user_version — so a fresh database walks the whole list and an
|
||||
@@ -69,6 +76,28 @@ var migrations = []struct {
|
||||
{10, verdictIntegritySchema},
|
||||
{11, checkRunsSchema},
|
||||
{12, selfCheckFailuresSchema},
|
||||
{13, dropChecksIndexSchema},
|
||||
{14, diagnosticHoldsSchema},
|
||||
}
|
||||
|
||||
// connPragmas are applied to every new connection. A larger WAL checkpoint
|
||||
// interval and cache cut random writes on the HDD-backed volume.
|
||||
var connPragmas = []string{
|
||||
"busy_timeout(5000)",
|
||||
"journal_mode(WAL)",
|
||||
"synchronous(NORMAL)",
|
||||
"foreign_keys(ON)",
|
||||
"wal_autocheckpoint(10000)",
|
||||
"journal_size_limit(67108864)",
|
||||
"cache_size(-65536)",
|
||||
}
|
||||
|
||||
func dsn(path string) string {
|
||||
q := make([]string, len(connPragmas))
|
||||
for i, p := range connPragmas {
|
||||
q[i] = "_pragma=" + p
|
||||
}
|
||||
return path + "?" + strings.Join(q, "&")
|
||||
}
|
||||
|
||||
type DB struct {
|
||||
@@ -79,24 +108,18 @@ type DB struct {
|
||||
// pragmas suited to a single-writer WAL workload, and runs any pending
|
||||
// schema migrations.
|
||||
func Open(ctx context.Context, path string) (*DB, error) {
|
||||
sqlDB, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(5000)")
|
||||
sqlDB, err := sql.Open("sqlite", dsn(path))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open sqlite: %w", err)
|
||||
}
|
||||
// Control API is the sole writer; one connection avoids SQLITE_BUSY
|
||||
// entirely for writes while still allowing concurrent reads via WAL.
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
|
||||
for _, pragma := range []string{
|
||||
"PRAGMA journal_mode=WAL",
|
||||
"PRAGMA synchronous=NORMAL",
|
||||
"PRAGMA foreign_keys=ON",
|
||||
"PRAGMA busy_timeout=5000",
|
||||
} {
|
||||
if _, err := sqlDB.ExecContext(ctx, pragma); err != nil {
|
||||
sqlDB.Close()
|
||||
return nil, fmt.Errorf("apply pragma %q: %w", pragma, err)
|
||||
}
|
||||
// Pragmas are in the DSN, so they apply to every new connection; this
|
||||
// ping opens the first one and reports a bad pragma early.
|
||||
if err := sqlDB.PingContext(ctx); err != nil {
|
||||
sqlDB.Close()
|
||||
return nil, fmt.Errorf("open sqlite: %w", err)
|
||||
}
|
||||
|
||||
d := &DB{DB: sqlDB}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
-- (registry_id, cycle_id) are the first columns of the UNIQUE index on
|
||||
-- checks, which serves every lookup by them; the extra index only costs
|
||||
-- writes (see docs/changes/2026-11-03_00-19_control-api-disk-write-reduction-plan.md).
|
||||
DROP INDEX IF EXISTS idx_checks_registry_cycle;
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Addresses held on a validator for manual diagnostics (see
|
||||
-- docs/changes/2026-11-03_00-28_diagnostic-mode-plan.md). A hold lives until
|
||||
-- an explicit detach. No foreign keys on purpose, like the other history tables.
|
||||
CREATE TABLE diagnostic_holds (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
address TEXT NOT NULL UNIQUE,
|
||||
validator_id TEXT NOT NULL UNIQUE,
|
||||
fip_id TEXT NOT NULL DEFAULT '',
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMP NOT NULL
|
||||
);
|
||||
@@ -14,6 +14,9 @@ const (
|
||||
ValidatorAssigned = "assigned"
|
||||
ValidatorChecking = "checking"
|
||||
ValidatorUnreachable = "unreachable"
|
||||
// ValidatorDiagnostic: the validator holds an address for manual
|
||||
// diagnostics (see diagnostic_holds) and takes no queue work.
|
||||
ValidatorDiagnostic = "diagnostic"
|
||||
|
||||
// Site (prober) availability states — no assigned/checking equivalent,
|
||||
// since a prober isn't bound to one IP at a time.
|
||||
|
||||
@@ -28,8 +28,40 @@ func (d *DB) UpsertCheck(ctx context.Context, c Check) error {
|
||||
// false (and writes nothing) when the result was dropped. The state test and
|
||||
// the write are one statement, so they cannot interleave with SetAggregating.
|
||||
func (d *DB) UpsertCheckIfOpen(ctx context.Context, c Check) (bool, error) {
|
||||
return upsertCheckIfOpen(ctx, d, c)
|
||||
}
|
||||
|
||||
// UpsertChecksIfOpen stores a batch of results in one transaction, applying
|
||||
// the UpsertCheckIfOpen rule to each. written[i] reports whether checks[i] was
|
||||
// stored (false: dropped).
|
||||
func (d *DB) UpsertChecksIfOpen(ctx context.Context, checks []Check) ([]bool, error) {
|
||||
written := make([]bool, len(checks))
|
||||
if len(checks) == 0 {
|
||||
return written, nil
|
||||
}
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for i, c := range checks {
|
||||
if written[i], err = upsertCheckIfOpen(ctx, tx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return written, nil
|
||||
}
|
||||
|
||||
type execer interface {
|
||||
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
|
||||
}
|
||||
|
||||
func upsertCheckIfOpen(ctx context.Context, x execer, c Check) (bool, error) {
|
||||
now := timeToDB(Now())
|
||||
res, err := d.ExecContext(ctx, `
|
||||
res, err := x.ExecContext(ctx, `
|
||||
INSERT INTO checks (registry_id, cycle_id, ip_id, ip_address, attempt_number, validator_id,
|
||||
source, check_type, target, success, latency_ms, detail, checked_at, created_at, recorded_at, run_id)
|
||||
SELECT q.registry_id, q.cycle_id, q.id, ?, q.attempt_number, COALESCE(NULLIF(?, ''), q.owner_validator_id, ''),
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DiagnosticHold is an address held on a validator for manual diagnostics.
|
||||
type DiagnosticHold struct {
|
||||
Address string `json:"address"`
|
||||
ValidatorID string `json:"validator_id"`
|
||||
FIPID string `json:"fip_id"`
|
||||
Note string `json:"note"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ClaimDiagnostic moves an idle validator to the diagnostic state and records
|
||||
// the hold, in one transaction. ErrNotFound: no such validator; ErrBusy: the
|
||||
// validator is not idle; ErrConflict: the address or validator is already held.
|
||||
func (d *DB) ClaimDiagnostic(ctx context.Context, validatorID, address, fipID, note string) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
now := timeToDB(Now())
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
UPDATE validators SET state=?, updated_at=?
|
||||
WHERE validator_id=? AND state=? AND current_ip_id IS NULL
|
||||
`, ValidatorDiagnostic, now, validatorID, ValidatorIdle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n != 1 {
|
||||
var one int
|
||||
err := tx.QueryRowContext(ctx, `SELECT 1 FROM validators WHERE validator_id=?`, validatorID).Scan(&one)
|
||||
if err == sql.ErrNoRows {
|
||||
return fmt.Errorf("validator %q: %w", validatorID, ErrNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("validator %q is not idle: %w", validatorID, ErrBusy)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at) VALUES (?, ?, ?, ?, ?)
|
||||
`, address, validatorID, fipID, note, now); err != nil {
|
||||
return fmt.Errorf("address %q or validator %q is already held: %w", address, validatorID, ErrConflict)
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// ReleaseDiagnostic deletes the hold of an address and returns the validator
|
||||
// to idle. ErrNotFound if the address is not held.
|
||||
func (d *DB) ReleaseDiagnostic(ctx context.Context, address string) (*DiagnosticHold, error) {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
h, err := scanHold(tx.QueryRowContext(ctx, holdSelect+` WHERE address=?`, address))
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, fmt.Errorf("address %q is not on diagnostic: %w", address, ErrNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM diagnostic_holds WHERE address=?`, address); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE validators SET state=?, updated_at=? WHERE validator_id=? AND state=?
|
||||
`, ValidatorIdle, timeToDB(Now()), h.ValidatorID, ValidatorDiagnostic); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h, tx.Commit()
|
||||
}
|
||||
|
||||
const holdSelect = `SELECT address, validator_id, fip_id, note, created_at FROM diagnostic_holds`
|
||||
|
||||
func scanHold(row rowScanner) (*DiagnosticHold, error) {
|
||||
var h DiagnosticHold
|
||||
var created string
|
||||
if err := row.Scan(&h.Address, &h.ValidatorID, &h.FIPID, &h.Note, &created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var err error
|
||||
if h.CreatedAt, err = dbToTime(created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &h, nil
|
||||
}
|
||||
|
||||
// ListDiagnosticHolds returns all holds, oldest first.
|
||||
func (d *DB) ListDiagnosticHolds(ctx context.Context) ([]DiagnosticHold, error) {
|
||||
rows, err := d.QueryContext(ctx, holdSelect+` ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []DiagnosticHold{}
|
||||
for rows.Next() {
|
||||
h, err := scanHold(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *h)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -86,7 +86,9 @@ func (d *DB) ClaimNextQueued(ctx context.Context, validatorID string, leaseTTL t
|
||||
var item IPQueueItem
|
||||
err = tx.QueryRowContext(ctx, `
|
||||
SELECT q.id, q.ip_address, q.sequence, q.attempt_number, q.retry_count
|
||||
FROM ip_queue q WHERE q.state=? AND NOT EXISTS (
|
||||
FROM ip_queue q WHERE q.state=?
|
||||
AND NOT EXISTS (SELECT 1 FROM diagnostic_holds h WHERE h.address=q.ip_address)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM ip_self_check_failures f
|
||||
WHERE f.registry_id=q.registry_id AND f.validator_id=? AND f.cycle_id>=q.sc_round_start_cycle)
|
||||
ORDER BY q.sequence LIMIT 1
|
||||
|
||||
@@ -501,7 +501,7 @@ func registryLevelsQuery(ids []any, sl registrySlice) (string, []any) {
|
||||
// sums: the recorded checks of each address's newest cycle (the same cycle
|
||||
// whose time is LastCheckedAt), counted per level and per check family. It
|
||||
// runs one grouped query per chunk of addresses, not one per address, over
|
||||
// idx_checks_registry_cycle. With sl.RunID the cycle is the address's one in
|
||||
// the unique checks index (registry_id, cycle_id, ...). With sl.RunID the cycle is the address's one in
|
||||
// that run (over idx_checks_run) and sl.Level and sl.Family leave only the
|
||||
// matching checks, so the levels and types outside them stay empty. Checks
|
||||
// whose source is neither egress nor an inbound site are not counted. The
|
||||
|
||||
@@ -391,7 +391,7 @@ func TestMigration0011BuildsRunsFromExistingData(t *testing.T) {
|
||||
}
|
||||
var ver int
|
||||
d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver)
|
||||
if ver != 12 {
|
||||
if ver != 14 {
|
||||
t.Errorf("user_version = %d", ver)
|
||||
}
|
||||
}
|
||||
@@ -353,11 +353,11 @@ func TestMigration0009Indexes(t *testing.T) {
|
||||
|
||||
// TestRegistryLevelsQueryUsesIndex guards against a full scan of checks: the
|
||||
// per-address MAX(cycle_id) and the join back must go through
|
||||
// idx_checks_registry_cycle, the run's slice through idx_checks_run.
|
||||
// the unique checks index, the run's slice through idx_checks_run.
|
||||
func TestRegistryLevelsQueryUsesIndex(t *testing.T) {
|
||||
d, ctx := newTestDB(t)
|
||||
for sl, index := range map[registrySlice]string{
|
||||
{}: "idx_checks_registry_cycle",
|
||||
{}: "sqlite_autoindex_checks_1",
|
||||
{RunID: 1, Level: LevelIngress, Family: "tls"}: "idx_checks_run",
|
||||
} {
|
||||
q, args := registryLevelsQuery([]any{1, 2, 3}, sl)
|
||||
|
||||
@@ -259,6 +259,13 @@ func (d *DB) DeleteValidator(ctx context.Context, validatorID string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var held int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM diagnostic_holds WHERE validator_id=?`, validatorID).Scan(&held); err != nil {
|
||||
return err
|
||||
}
|
||||
if held > 0 {
|
||||
return fmt.Errorf("validator %q is on diagnostic: %w", validatorID, ErrBusy)
|
||||
}
|
||||
if currentIPID.Valid {
|
||||
return fmt.Errorf("validator %q owns ip_id %d: %w", validatorID, currentIPID.Int64, ErrBusy)
|
||||
}
|
||||
|
||||
@@ -240,7 +240,32 @@ func TestMigration0010MarksRowsAfterVerdict(t *testing.T) {
|
||||
t.Errorf("ssh: after_verdict=%d recorded=%s created=%s", a, rec, cr)
|
||||
}
|
||||
var ver int
|
||||
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != 12 {
|
||||
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != 14 {
|
||||
t.Errorf("user_version=%d err=%v", ver, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A batch is written in one transaction; a row for a finished address is
|
||||
// dropped without affecting the others.
|
||||
func TestUpsertChecksIfOpenBatch(t *testing.T) {
|
||||
d, ctx := newTestDB(t)
|
||||
open := checkingIP(t, d, "1.2.3.4")
|
||||
done := checkingIP(t, d, "5.6.7.8")
|
||||
if _, err := d.ExecContext(ctx, `UPDATE ip_queue SET state='done' WHERE id=?`, done.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
written, err := d.UpsertChecksIfOpen(ctx, []Check{
|
||||
checkOf(open, "icmp", true), checkOf(open, "ssh", false), checkOf(done, "icmp", true),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(written) != 3 || !written[0] || !written[1] || written[2] {
|
||||
t.Fatalf("written = %v, want [true true false]", written)
|
||||
}
|
||||
var n int
|
||||
d.QueryRowContext(ctx, `SELECT COUNT(*) FROM checks`).Scan(&n)
|
||||
if n != 2 {
|
||||
t.Fatalf("%d rows stored, want 2", n)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user