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:
ayurishchevandClaude Opus 5.5 committed 2026-11-03 07:01:24 +03:00
1 parent d0ab6b94f9
commit 55d383bd34
41 files changed
+1214 -94

No files matched your search

+41 -5
View File
@@ -402,8 +402,42 @@ func fetchIPEcho(ctx context.Context, url string) (string, error) {
}
func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
var results []checkResultDTO
var traces sync.WaitGroup
// Results are sent in batches every results_flush_seconds and before
// complete, instead of one request (and one control-api commit) each.
var (
bufMu sync.Mutex
buf []checkResultDTO
)
flush := func() {
bufMu.Lock()
batch := buf
buf = nil
bufMu.Unlock()
if len(batch) > 0 {
a.postResults(ctx, batch)
}
}
stopFlush := make(chan struct{})
var flusher sync.WaitGroup
flusher.Add(1)
go func() {
defer flusher.Done()
every := time.Duration(a.cfg.Checks.ResultsFlushSeconds) * time.Second
if every <= 0 {
every = 5 * time.Second
}
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-t.C:
flush()
case <-stopFlush:
return
}
}
}()
for _, ct := range assignment.CheckConfig {
for _, target := range ct.Targets {
var fn func(context.Context) checkrunner.Result
@@ -432,14 +466,13 @@ func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
// loopback-only local e2e harness) would collide on the
// checks table's UNIQUE(ip_id, attempt, source, type,
// target) key and silently overwrite each other.
results = append(results, checkResultDTO{
bufMu.Lock()
buf = append(buf, checkResultDTO{
IPID: assignment.IPID, CheckType: res.CheckType, Target: target,
Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail,
CheckedAt: res.CheckedAt.Format(time.RFC3339Nano),
})
// Report progressively rather than batching until the end, so
// a crash mid-run doesn't lose already-completed check results.
a.postResults(ctx, []checkResultDTO{results[len(results)-1]})
bufMu.Unlock()
if ct.Type == "https" && !res.Success && a.cfg.Checks.Traceroute.IsEnabled() {
traces.Add(1)
@@ -455,6 +488,9 @@ func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
// detaches the floating IP and the trace would leave from another address.
traces.Wait()
close(stopFlush)
flusher.Wait()
flush()
a.postComplete(ctx, assignment.IPID)
a.lastHandledIPID = assignment.IPID
}
+7
View File
@@ -270,6 +270,10 @@ type AgentChecks struct {
HTTPSAttempts int `yaml:"https_attempts"`
HTTPSRetryDelaySeconds int `yaml:"https_retry_delay_seconds"`
// ResultsFlushSeconds is how often buffered check results are sent to
// control-api (they are always sent before the completion signal).
ResultsFlushSeconds int `yaml:"results_flush_seconds"`
Traceroute TracerouteCfg `yaml:"traceroute"`
}
@@ -330,6 +334,9 @@ func LoadValidatorAgent(path string) (*ValidatorAgent, error) {
if c.Checks.HTTPSRetryDelaySeconds <= 0 {
c.Checks.HTTPSRetryDelaySeconds = 2
}
if c.Checks.ResultsFlushSeconds <= 0 {
c.Checks.ResultsFlushSeconds = 5
}
if c.Checks.Traceroute.TimeoutSeconds <= 0 {
c.Checks.Traceroute.TimeoutSeconds = 90
}
+2
View File
@@ -60,6 +60,8 @@ func validatorBadge(state string) Badge {
return Badge{"pill-danger", "unreachable"}
case "unregistered":
return Badge{"pill-neutral", "unregistered"}
case "diagnostic":
return Badge{"pill-warning", "diagnostic"}
default:
return Badge{"pill-info", state} // assigned / checking
}
+35 -12
View File
@@ -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
);
+3
View File
@@ -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.
+33 -1
View File
@@ -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, ''),
+112
View File
@@ -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()
}
+3 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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)
}
}
+2 -2
View File
@@ -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)
+7
View File
@@ -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)
}
+26 -1
View File
@@ -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)
}
}
+2 -2
View File
@@ -97,8 +97,8 @@ func TestRouteTableIsClassified(t *testing.T) {
t.Fatalf("admin route %q is %s, want admin", rt.Pattern, rt.Access)
}
}
if counts["admin"] != 46 || counts["agent"] != 5 || counts["open"] != 8 {
t.Fatalf("access counts = %v, want admin=46 agent=5 open=8", counts)
if counts["admin"] != 49 || counts["agent"] != 5 || counts["open"] != 8 {
t.Fatalf("access counts = %v, want admin=49 agent=5 open=8", counts)
}
}
+3
View File
@@ -203,6 +203,9 @@ func (s *Server) handleAdminValidators(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
for i := range validators {
s.Orch.OverlayValidatorHeartbeat(&validators[i])
}
writeJSON(w, http.StatusOK, validators)
}
+13 -9
View File
@@ -42,7 +42,7 @@ func (s *Server) handleAgentHeartbeat(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
var req heartbeatRequest
_ = readJSON(r, &req) // heartbeat body is informational only; tolerate empty/missing
if err := s.DB.Heartbeat(r.Context(), id); err != nil {
if err := s.Orch.ValidatorHeartbeat(r.Context(), id); err != nil {
writeError(w, http.StatusNotFound, "unknown validator: "+id)
return
}
@@ -149,7 +149,7 @@ func (s *Server) handleAgentResults(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
dropped := map[int64]int{}
checks := make([]db.Check, 0, len(req.Results))
for _, res := range req.Results {
item, err := s.DB.GetIP(r.Context(), res.IPID)
if err != nil {
@@ -160,17 +160,21 @@ func (s *Server) handleAgentResults(w http.ResponseWriter, r *http.Request) {
if err != nil {
checkedAt = db.Now()
}
written, err := s.Orch.RecordCheckIfOpen(r.Context(), db.Check{
checks = append(checks, db.Check{
IPID: item.ID, IPAddress: item.IPAddress, AttemptNumber: item.AttemptNumber,
ValidatorID: id, Source: db.SourceEgress, CheckType: res.CheckType, Target: res.Target,
Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, CheckedAt: checkedAt,
})
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
if !written {
dropped[item.ID]++
}
written, err := s.Orch.RecordChecksIfOpen(r.Context(), checks)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
dropped := map[int64]int{}
for i, ok := range written {
if !ok {
dropped[checks[i].IPID]++
}
}
writeJSON(w, http.StatusOK, s.reportDropped(r.Context(), "validator-agent", id, db.SourceEgress, dropped))
+2
View File
@@ -18,6 +18,7 @@ func (s *Server) handleConfigListValidators(w http.ResponseWriter, r *http.Reque
}
out := make([]validatorDTO, len(validators))
for i, v := range validators {
s.Orch.OverlayValidatorHeartbeat(&v)
out[i] = validatorDTO{
ValidatorID: v.ValidatorID, Hostname: v.Hostname, OSPortID: v.OSPortID,
State: v.State, LastHeartbeatAt: v.LastHeartbeatAt,
@@ -76,6 +77,7 @@ func (s *Server) handleConfigListSites(w http.ResponseWriter, r *http.Request) {
}
out := make([]siteDTO, len(sites))
for i, site := range sites {
s.Orch.OverlaySiteHeartbeat(&site)
out[i] = siteDTO{
Index: site.Index, SiteID: site.SiteID, Hostname: site.Hostname,
State: site.State, LastHeartbeatAt: site.LastHeartbeatAt,
+1
View File
@@ -46,6 +46,7 @@ func newConfigTestHarness(t *testing.T) (*fakeClient, *db.DB, *orchestrator.Orch
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
orch := orchestrator.New(d, mock, cfg, log)
orch.EndStartupGrace()
// A background scan must never outlive the database it writes to.
t.Cleanup(func() { orch.CancelScan() })
srv := New(d, orch, log)
+69
View File
@@ -0,0 +1,69 @@
package httpapi
import (
"net/http"
"strings"
"cloudipvalidator/internal/orchestrator"
)
type diagnosticAttachRequest struct {
Items []struct {
Address string `json:"address"`
ValidatorID string `json:"validator_id"`
} `json:"items"`
Note string `json:"note"`
}
type diagnosticDetachRequest struct {
Addresses []string `json:"addresses"`
All bool `json:"all"`
}
type diagnosticResultsResponse struct {
Results []orchestrator.DiagnosticResult `json:"results"`
}
func (s *Server) handleAdminDiagnosticAttach(w http.ResponseWriter, r *http.Request) {
var req diagnosticAttachRequest
if err := readJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
if len(req.Items) == 0 {
writeError(w, http.StatusBadRequest, "items must not be empty")
return
}
items := make([]orchestrator.DiagnosticItem, len(req.Items))
for i, it := range req.Items {
addr := strings.TrimSpace(it.Address)
if addr == "" {
writeError(w, http.StatusBadRequest, "address must not be empty")
return
}
items[i] = orchestrator.DiagnosticItem{Address: addr, ValidatorID: strings.TrimSpace(it.ValidatorID)}
}
writeJSON(w, http.StatusOK, diagnosticResultsResponse{Results: s.Orch.DiagnosticAttach(r.Context(), items, req.Note)})
}
func (s *Server) handleAdminDiagnosticDetach(w http.ResponseWriter, r *http.Request) {
var req diagnosticDetachRequest
if err := readJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
if !req.All && len(req.Addresses) == 0 {
writeError(w, http.StatusBadRequest, "addresses or all=true is required")
return
}
writeJSON(w, http.StatusOK, diagnosticResultsResponse{Results: s.Orch.DiagnosticDetach(r.Context(), req.Addresses, req.All)})
}
func (s *Server) handleAdminDiagnosticList(w http.ResponseWriter, r *http.Request) {
holds, err := s.Orch.DiagnosticList(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, holds)
}
+17 -14
View File
@@ -36,7 +36,7 @@ func (s *Server) handleProberHeartbeat(w http.ResponseWriter, r *http.Request) {
siteID := r.PathValue("site_id")
var req heartbeatRequest
_ = readJSON(r, &req) // heartbeat body is informational only; tolerate empty/missing
if err := s.DB.SiteHeartbeat(r.Context(), siteID); err != nil {
if err := s.Orch.SiteHeartbeat(r.Context(), siteID); err != nil {
writeError(w, http.StatusNotFound, "unknown site_id: "+siteID)
return
}
@@ -97,8 +97,7 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
return
}
completed := map[int64]bool{}
dropped := map[int64]int{}
checks := make([]db.Check, 0, len(req.Results))
for _, res := range req.Results {
item, err := s.DB.GetIP(r.Context(), res.IPID)
if err != nil {
@@ -109,21 +108,25 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
if err != nil {
checkedAt = db.Now()
}
written, err := s.Orch.RecordCheckIfOpen(r.Context(), db.Check{
checks = append(checks, db.Check{
IPID: item.ID, IPAddress: item.IPAddress, AttemptNumber: item.AttemptNumber,
Source: db.InboundSource(siteIndex), CheckType: res.CheckType, Target: res.IPAddress,
Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, CheckedAt: checkedAt,
})
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
if !written {
dropped[item.ID]++
continue
}
if res.Complete {
completed[res.IPID] = true
}
written, err := s.Orch.RecordChecksIfOpen(r.Context(), checks)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
completed := map[int64]bool{}
dropped := map[int64]int{}
for i, ok := range written {
switch {
case !ok:
dropped[checks[i].IPID]++
case req.Results[i].Complete:
completed[checks[i].IPID] = true
}
}
for ipID := range completed {
+3
View File
@@ -59,6 +59,9 @@ func (s *Server) routeTable() []route {
{"POST /api/v1/admin/ips/delete", s.handleAdminDeleteIPs, accessAdmin},
{"POST /api/v1/admin/ips/clear", s.handleAdminClearQueue, accessAdmin},
{"GET /api/v1/admin/validators", s.handleAdminValidators, accessAdmin},
{"POST /api/v1/admin/diagnostics/attach", s.handleAdminDiagnosticAttach, accessAdmin},
{"POST /api/v1/admin/diagnostics/detach", s.handleAdminDiagnosticDetach, accessAdmin},
{"GET /api/v1/admin/diagnostics", s.handleAdminDiagnosticList, accessAdmin},
{"GET /api/v1/admin/auto-cycle", s.handleAdminGetAutoCycle, accessAdmin},
{"PUT /api/v1/admin/auto-cycle", s.handleAdminPutAutoCycle, accessAdmin},
{"POST /api/v1/admin/auto-cycle/start", s.handleAdminStartAutoCycle, accessAdmin},
+187
View File
@@ -0,0 +1,187 @@
package orchestrator
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/openstack"
)
// Diagnostic hold results (per address).
const (
DiagAttached = "attached"
DiagDetached = "detached"
DiagRejected = "rejected"
)
// DiagnosticItem is one address to attach; ValidatorID is optional (an idle
// validator is picked when empty).
type DiagnosticItem struct {
Address string
ValidatorID string
}
// DiagnosticResult is the outcome for one address.
type DiagnosticResult struct {
Address string `json:"address"`
Status string `json:"status"`
ValidatorID string `json:"validator_id,omitempty"`
FIPID string `json:"fip_id,omitempty"`
Reason string `json:"reason,omitempty"`
}
func rejected(address, reason string) DiagnosticResult {
return DiagnosticResult{Address: address, Status: DiagRejected, Reason: reason}
}
// activeQueueStates are the states in which an address is being checked.
var activeQueueStates = map[string]bool{
db.IPAssigningFIP: true, db.IPAwaitingSelfCheck: true, db.IPChecking: true, db.IPAggregating: true,
}
// DiagnosticAttach binds each address to a validator's port and holds it
// there until DiagnosticDetach. Partial success is normal: every address gets
// its own result.
func (o *Orchestrator) DiagnosticAttach(ctx context.Context, items []DiagnosticItem, note string) []DiagnosticResult {
out := make([]DiagnosticResult, 0, len(items))
for _, it := range items {
out = append(out, o.diagnosticAttachOne(ctx, it, note))
}
return out
}
func (o *Orchestrator) diagnosticAttachOne(ctx context.Context, it DiagnosticItem, note string) DiagnosticResult {
addr := it.Address
holds, err := o.DB.ListDiagnosticHolds(ctx)
if err != nil {
return rejected(addr, "internal error: "+err.Error())
}
for _, h := range holds {
if h.Address == addr {
return rejected(addr, "address is already on diagnostic")
}
}
if item, err := o.DB.GetIPByAddress(ctx, addr); err == nil && activeQueueStates[item.State] {
return rejected(addr, "address is being checked ("+item.State+")")
}
fip, err := o.OS.GetFloatingIPByAddress(ctx, addr)
if err != nil {
if openstack.IsNotFound(err) {
return rejected(addr, "floating ip not found in the project")
}
return rejected(addr, "cloud lookup failed: "+err.Error())
}
v, reason := o.pickDiagnosticValidator(ctx, it.ValidatorID)
if v == nil {
return rejected(addr, reason)
}
if fip.PortID != "" && fip.PortID != v.OSPortID {
return rejected(addr, "floating ip is attached to another port")
}
if err := o.DB.ClaimDiagnostic(ctx, v.ValidatorID, addr, fip.ID, note); err != nil {
return rejected(addr, "validator "+v.ValidatorID+" cannot be claimed: "+err.Error())
}
if err := o.OS.AssociateFloatingIP(ctx, fip.ID, v.OSPortID); err != nil {
if _, rerr := o.DB.ReleaseDiagnostic(ctx, addr); rerr != nil {
o.Log.Error("roll back diagnostic hold", "ip", addr, "err", rerr)
}
return rejected(addr, "associate floating ip: "+err.Error())
}
o.diagnosticEvent(ctx, "diagnostic_attached", addr, v.ValidatorID, fip.ID, note)
o.Log.Info("diagnostic hold attached", "ip", addr, "validator", v.ValidatorID)
return DiagnosticResult{Address: addr, Status: DiagAttached, ValidatorID: v.ValidatorID, FIPID: fip.ID}
}
// pickDiagnosticValidator returns the requested validator if it is idle, or
// the first idle one with a port when none is requested.
func (o *Orchestrator) pickDiagnosticValidator(ctx context.Context, id string) (*db.Validator, string) {
if id != "" {
v, err := o.DB.GetValidator(ctx, id)
if errors.Is(err, sql.ErrNoRows) {
return nil, "validator not found"
}
if err != nil {
return nil, "internal error: " + err.Error()
}
if v.State != db.ValidatorIdle {
return nil, fmt.Sprintf("validator is not idle (%s)", v.State)
}
if v.OSPortID == "" {
return nil, "validator has no port"
}
return v, ""
}
idle, err := o.DB.ListIdleValidators(ctx)
if err != nil {
return nil, "internal error: " + err.Error()
}
for i := range idle {
if idle[i].OSPortID != "" {
return &idle[i], ""
}
}
return nil, "no idle validators left"
}
// DiagnosticDetach unbinds the given addresses (all holds when all is true)
// and returns their validators to idle. A floating ip that is already free in
// the cloud is not an error; a cloud failure keeps the hold so it can be retried.
func (o *Orchestrator) DiagnosticDetach(ctx context.Context, addresses []string, all bool) []DiagnosticResult {
holds, err := o.DB.ListDiagnosticHolds(ctx)
if err != nil {
return []DiagnosticResult{rejected("", "internal error: "+err.Error())}
}
byAddr := make(map[string]db.DiagnosticHold, len(holds))
for _, h := range holds {
byAddr[h.Address] = h
if all {
addresses = append(addresses, h.Address)
}
}
out := make([]DiagnosticResult, 0, len(addresses))
for _, addr := range addresses {
h, ok := byAddr[addr]
if !ok {
out = append(out, rejected(addr, "address is not on diagnostic"))
continue
}
fipID := h.FIPID
if fip, err := o.OS.GetFloatingIPByAddress(ctx, addr); err == nil {
fipID = fip.ID
if fip.PortID != "" {
if err := o.OS.DisassociateFloatingIP(ctx, fipID); err != nil {
out = append(out, rejected(addr, "disassociate floating ip: "+err.Error()))
continue
}
}
} else if !openstack.IsNotFound(err) {
out = append(out, rejected(addr, "cloud lookup failed: "+err.Error()))
continue
}
if _, err := o.DB.ReleaseDiagnostic(ctx, addr); err != nil {
out = append(out, rejected(addr, "release: "+err.Error()))
continue
}
o.diagnosticEvent(ctx, "diagnostic_detached", addr, h.ValidatorID, fipID, h.Note)
o.Log.Info("diagnostic hold detached", "ip", addr, "validator", h.ValidatorID)
out = append(out, DiagnosticResult{Address: addr, Status: DiagDetached, ValidatorID: h.ValidatorID, FIPID: fipID})
}
return out
}
// DiagnosticList returns the current holds.
func (o *Orchestrator) DiagnosticList(ctx context.Context) ([]db.DiagnosticHold, error) {
return o.DB.ListDiagnosticHolds(ctx)
}
func (o *Orchestrator) diagnosticEvent(ctx context.Context, typ, addr, validatorID, fipID, note string) {
payload, _ := json.Marshal(map[string]string{
"address": addr, "validator_id": validatorID, "fip_id": fipID, "note": note,
})
o.event(ctx, "control-api", validatorID, nil, typ, string(payload))
}
+191
View File
@@ -0,0 +1,191 @@
package orchestrator
import (
"context"
"errors"
"testing"
"time"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/openstack"
)
func diagSetup(t *testing.T) (*Orchestrator, *db.DB, context.Context, *openstack.MockClient) {
t.Helper()
ctx := context.Background()
o, d, mock := newTestOrchestrator(t, 180)
mock.Seed("fip-a", "1.1.1.1", "svc")
mock.Seed("fip-b", "2.2.2.2", "svc")
_ = d.RegisterValidator(ctx, "validator-1", "host", "port-1", "v")
_ = d.RegisterValidator(ctx, "validator-2", "host", "port-2", "v")
return o, d, ctx, mock
}
func validatorState(t *testing.T, d *db.DB, id string) string {
t.Helper()
v, err := d.GetValidator(context.Background(), id)
if err != nil {
t.Fatal(err)
}
return v.State
}
func TestDiagnosticAttachDetach(t *testing.T) {
o, d, ctx, _ := diagSetup(t)
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
t.Fatal(err)
}
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "trace")
if len(res) != 1 || res[0].Status != DiagAttached || res[0].ValidatorID != "validator-1" {
t.Fatalf("attach: %+v", res)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
t.Fatalf("state = %s, want diagnostic", s)
}
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 1 {
t.Fatalf("fips on port-1 = %v", fips)
}
// The held address is queued but never handed out; the other validator stays idle.
o.Tick(ctx)
if ip, _ := d.GetIPByAddress(ctx, "1.1.1.1"); ip.State != db.IPQueued {
t.Fatalf("held address state = %s, want queued", ip.State)
}
// Reconcile and heartbeat leave the diagnostic state alone.
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
t.Fatal(err)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
t.Fatalf("after heartbeat/reconcile state = %s", s)
}
if list, _ := o.DiagnosticList(ctx); len(list) != 1 || list[0].Note != "trace" {
t.Fatalf("list: %+v", list)
}
res = o.DiagnosticDetach(ctx, nil, true)
if len(res) != 1 || res[0].Status != DiagDetached {
t.Fatalf("detach: %+v", res)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
t.Fatalf("state = %s, want idle", s)
}
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 0 {
t.Fatalf("fip still attached: %v", fips)
}
o.Tick(ctx)
if ip, _ := d.GetIPByAddress(ctx, "1.1.1.1"); ip.State == db.IPQueued {
t.Fatal("released address was not claimed")
}
}
func TestDiagnosticRejections(t *testing.T) {
o, d, ctx, _ := diagSetup(t)
// Busy validator.
if _, err := d.ExecContext(ctx, `UPDATE validators SET state='assigned' WHERE validator_id='validator-1'`); err != nil {
t.Fatal(err)
}
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "")
if res[0].Status != DiagRejected {
t.Fatalf("busy validator: %+v", res)
}
// Unknown address and a cloud error roll back the claim.
res = o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "9.9.9.9"}}, "")
if res[0].Status != DiagRejected {
t.Fatalf("unknown fip: %+v", res)
}
}
func TestDiagnosticCloudErrorRollsBack(t *testing.T) {
o, d, ctx, mock := diagSetup(t)
mock.AssociateFailures = map[string]error{"fip-a": errors.New("neutron down")}
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "")
if res[0].Status != DiagRejected {
t.Fatalf("attach: %+v", res)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
t.Fatalf("state = %s, want idle after rollback", s)
}
if list, _ := o.DiagnosticList(ctx); len(list) != 0 {
t.Fatalf("hold left behind: %+v", list)
}
}
func TestSweepAndReleasePortsSkipDiagnosticValidator(t *testing.T) {
o, d, ctx, _ := diagSetup(t)
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
t.Fatal(err)
}
if res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, ""); res[0].Status != DiagAttached {
t.Fatalf("attach: %+v", res)
}
old := db.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano)
if _, err := d.ExecContext(ctx, `UPDATE validators SET last_heartbeat_at=?`, old); err != nil {
t.Fatal(err)
}
o.EndStartupGrace()
if err := o.SweepStaleHeartbeats(ctx); err != nil {
t.Fatal(err)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
t.Fatalf("sweep changed diagnostic validator to %s", s)
}
if s := validatorState(t, d, "validator-2"); s != db.ValidatorUnreachable {
t.Fatalf("validator-2 = %s, want unreachable", s)
}
vs := o.validatorsByID(ctx, "validator-1")
o.releaseValidatorPorts(ctx, vs)
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 1 {
t.Fatalf("releaseValidatorPorts detached a held fip: %v", fips)
}
}
func TestHeartbeatPersistThrottle(t *testing.T) {
o, d, ctx, _ := diagSetup(t)
stored := func() string {
var s string
d.QueryRowContext(ctx, `SELECT COALESCE(last_heartbeat_at,'') FROM validators WHERE validator_id='validator-1'`).Scan(&s)
return s
}
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
t.Fatal(err)
}
first := stored()
if first == "" {
t.Fatal("first heartbeat was not written")
}
time.Sleep(5 * time.Millisecond)
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
t.Fatal(err)
}
if stored() != first {
t.Fatal("second heartbeat within the interval was written to the database")
}
// Memory is newer, and the admin overlay shows it.
v, _ := d.GetValidator(ctx, "validator-1")
o.OverlayValidatorHeartbeat(v)
if !v.LastHeartbeatAt.After(mustParse(t, first)) {
t.Fatal("overlay did not show the in-memory heartbeat")
}
// A state change is written at once.
_ = d.MarkValidatorUnreachable(ctx, "validator-1")
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
t.Fatal(err)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
t.Fatalf("state = %s, want idle", s)
}
if err := o.ValidatorHeartbeat(ctx, "nobody"); err == nil {
t.Fatal("unknown validator must fail")
}
}
func mustParse(t *testing.T, s string) time.Time {
t.Helper()
tm, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
t.Fatal(err)
}
return tm
}
+181
View File
@@ -0,0 +1,181 @@
package orchestrator
import (
"context"
"database/sql"
"fmt"
"sync"
"time"
"cloudipvalidator/internal/db"
)
// heartbeatPersistInterval is how often a steady heartbeat is written to the
// database. Between writes the last signal lives in memory only.
const heartbeatPersistInterval = 60 * time.Second
// heartbeatState keeps the last signal of every validator and site in memory,
// so a heartbeat does not cost a database commit.
type heartbeatState struct {
mu sync.Mutex
startedAt time.Time
seen map[string]time.Time // key "v:<id>" or "s:<id>": last signal
persisted map[string]time.Time // key: last database write
}
// touch records a signal now and reports whether it must be written to the
// database (forced by a state change, or the last write is old enough).
func (h *heartbeatState) touch(key string, force bool) bool {
now := time.Now()
h.mu.Lock()
defer h.mu.Unlock()
if h.seen == nil {
h.seen = map[string]time.Time{}
h.persisted = map[string]time.Time{}
}
h.seen[key] = now
if last, ok := h.persisted[key]; !force && ok && now.Sub(last) < heartbeatPersistInterval {
return false
}
h.persisted[key] = now
return true
}
func (h *heartbeatState) lastSeen(key string) (time.Time, bool) {
h.mu.Lock()
defer h.mu.Unlock()
t, ok := h.seen[key]
return t, ok
}
// newest returns the later of the in-memory signal and the stored one.
func (h *heartbeatState) newest(key string, stored *time.Time) *time.Time {
t, ok := h.lastSeen(key)
if !ok {
return stored
}
t = t.UTC().Truncate(time.Millisecond)
if stored != nil && !t.After(*stored) {
return stored
}
return &t
}
// ValidatorHeartbeat handles a validator's sign of life. It returns
// sql.ErrNoRows for an unknown validator. The database is written only when
// the validator is unreachable (state change) or the last write is older than
// heartbeatPersistInterval.
func (o *Orchestrator) ValidatorHeartbeat(ctx context.Context, id string) error {
v, err := o.DB.GetValidator(ctx, id)
if err != nil {
return err
}
if !o.hb.touch("v:"+id, v.State == db.ValidatorUnreachable) {
return nil
}
return o.DB.Heartbeat(ctx, id)
}
// SiteHeartbeat is ValidatorHeartbeat for prober sites.
func (o *Orchestrator) SiteHeartbeat(ctx context.Context, siteID string) error {
state, err := o.siteState(ctx, siteID)
if err != nil {
return err
}
if !o.hb.touch("s:"+siteID, state == db.SiteUnreachable) {
return nil
}
return o.DB.SiteHeartbeat(ctx, siteID)
}
func (o *Orchestrator) siteState(ctx context.Context, siteID string) (string, error) {
sites, err := o.DB.ListSites(ctx)
if err != nil {
return "", err
}
for _, s := range sites {
if s.SiteID == siteID {
return s.State, nil
}
}
return "", sql.ErrNoRows
}
// OverlayValidatorHeartbeat replaces v.LastHeartbeatAt with the in-memory
// value when it is newer.
func (o *Orchestrator) OverlayValidatorHeartbeat(v *db.Validator) {
v.LastHeartbeatAt = o.hb.newest("v:"+v.ValidatorID, v.LastHeartbeatAt)
}
// OverlaySiteHeartbeat is OverlayValidatorHeartbeat for sites.
func (o *Orchestrator) OverlaySiteHeartbeat(s *db.Site) {
s.LastHeartbeatAt = o.hb.newest("s:"+s.SiteID, s.LastHeartbeatAt)
}
// EndStartupGrace ends the post-start sweep delay early (for tests).
func (o *Orchestrator) EndStartupGrace() { o.hb.startedAt = time.Time{} }
// inStartupGrace is true during the first HeartbeatTimeoutSeconds after
// start: agents have not had time to report in memory yet.
func (o *Orchestrator) inStartupGrace() bool {
return time.Since(o.hb.startedAt) < time.Duration(o.Cfg.HeartbeatTimeoutSeconds)*time.Second
}
// SweepStaleHeartbeats marks validators unreachable if they haven't
// heartbeated within HeartbeatTimeoutSeconds (the later of the in-memory and
// stored signal counts). It does not itself reclaim their in-flight IP — that
// happens independently via lease expiry. Validators on a diagnostic hold are
// never touched, and nothing is marked in the startup grace period.
func (o *Orchestrator) SweepStaleHeartbeats(ctx context.Context) error {
if o.inStartupGrace() {
return nil
}
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
all, err := o.DB.ListValidators(ctx)
if err != nil {
return err
}
for _, v := range all {
if v.State == db.ValidatorUnreachable || v.State == db.ValidatorDiagnostic {
continue
}
last := o.hb.newest("v:"+v.ValidatorID, v.LastHeartbeatAt)
if last == nil || !last.Before(cutoff) {
continue
}
if err := o.DB.MarkValidatorUnreachable(ctx, v.ValidatorID); err != nil {
o.Log.Error("mark validator unreachable", "validator", v.ValidatorID, "err", err)
continue
}
o.event(ctx, "control-api", "", nil, "validator_unreachable", fmt.Sprintf(`{"validator_id":%q}`, v.ValidatorID))
}
return nil
}
// SweepStaleSiteHeartbeats marks prober sites unreachable if they haven't
// heartbeated within HeartbeatTimeoutSeconds — mirrors SweepStaleHeartbeats.
func (o *Orchestrator) SweepStaleSiteHeartbeats(ctx context.Context) error {
if o.inStartupGrace() {
return nil
}
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
all, err := o.DB.ListSites(ctx)
if err != nil {
return err
}
for _, s := range all {
if s.State == db.SiteUnreachable {
continue
}
last := o.hb.newest("s:"+s.SiteID, s.LastHeartbeatAt)
if last == nil || !last.Before(cutoff) {
continue
}
if err := o.DB.MarkSiteUnreachable(ctx, s.SiteID); err != nil {
o.Log.Error("mark site unreachable", "site_id", s.SiteID, "err", err)
continue
}
o.event(ctx, "control-api", "", nil, "site_unreachable", fmt.Sprintf(`{"site_id":%q}`, s.SiteID))
}
return nil
}
+12 -42
View File
@@ -62,6 +62,9 @@ type Orchestrator struct {
// next Tick does not start the same work twice.
inflight sync.Map
wg sync.WaitGroup
// hb is the in-memory heartbeat state (see heartbeat.go).
hb heartbeatState
}
// Wait blocks until all background work started by Tick has finished.
@@ -99,6 +102,7 @@ func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI,
Log: log,
ScanPageSize: cfg.OpenStack.ListPageSize,
hb: heartbeatState{startedAt: time.Now()},
}
}
@@ -395,6 +399,12 @@ func (o *Orchestrator) RecordCheckIfOpen(ctx context.Context, c db.Check) (bool,
return o.DB.UpsertCheckIfOpen(ctx, c)
}
// RecordChecksIfOpen is RecordCheckIfOpen for a batch, written in one
// transaction; written[i] reports whether checks[i] was stored.
func (o *Orchestrator) RecordChecksIfOpen(ctx context.Context, checks []db.Check) ([]bool, error) {
return o.DB.UpsertChecksIfOpen(ctx, checks)
}
// RecordCheck is RecordCheckIfOpen for callers that do not need to know
// whether the result was dropped.
func (o *Orchestrator) RecordCheck(ctx context.Context, c db.Check) error {
@@ -419,8 +429,8 @@ func (o *Orchestrator) MarkSiteComplete(ctx context.Context, ipID int64, siteInd
func (o *Orchestrator) releaseValidatorPorts(ctx context.Context, validators []db.Validator) {
var wg sync.WaitGroup
for _, v := range validators {
if v.OSPortID == "" {
continue
if v.OSPortID == "" || v.State == db.ValidatorDiagnostic {
continue // a diagnostic hold keeps its floating ip attached
}
wg.Add(1)
go func(v db.Validator) {
@@ -893,46 +903,6 @@ func (o *Orchestrator) sweepExpiredLeases(ctx context.Context) error {
return nil
}
// sweepStaleHeartbeats marks validators unreachable if they haven't
// heartbeated within HeartbeatTimeoutSeconds. It does not itself reclaim
// their in-flight IP — that happens independently via lease expiry, so a
// validator that stops heartbeating but whose lease hasn't yet expired
// still finishes its current check window if it recovers in time.
func (o *Orchestrator) SweepStaleHeartbeats(ctx context.Context) error {
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
stale, err := o.DB.ListStaleHeartbeats(ctx, cutoff)
if err != nil {
return err
}
for _, v := range stale {
if err := o.DB.MarkValidatorUnreachable(ctx, v.ValidatorID); err != nil {
o.Log.Error("mark validator unreachable", "validator", v.ValidatorID, "err", err)
continue
}
o.event(ctx, "control-api", "", nil, "validator_unreachable", fmt.Sprintf(`{"validator_id":%q}`, v.ValidatorID))
}
return nil
}
// SweepStaleSiteHeartbeats marks prober sites unreachable if they haven't
// heartbeated within HeartbeatTimeoutSeconds — mirrors SweepStaleHeartbeats
// exactly, for sites instead of validators.
func (o *Orchestrator) SweepStaleSiteHeartbeats(ctx context.Context) error {
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
stale, err := o.DB.ListStaleSiteHeartbeats(ctx, cutoff)
if err != nil {
return err
}
for _, s := range stale {
if err := o.DB.MarkSiteUnreachable(ctx, s.SiteID); err != nil {
o.Log.Error("mark site unreachable", "site_id", s.SiteID, "err", err)
continue
}
o.event(ctx, "control-api", "", nil, "site_unreachable", fmt.Sprintf(`{"site_id":%q}`, s.SiteID))
}
return nil
}
// RecordEvent is the exported entry point httpapi uses to log
// agent/prober-reported audit events (config_received, fip_changed,
// error, etc.) through the same path as internally generated events