Run manual diagnostic attachments in the background
This commit is contained in:
1 parent
d845a5e4b6
commit
89ac4d5bcd
40 files changed
+1560
-58
No files matched your search
@@ -59,6 +59,9 @@ var diagnosticHoldsSchema string
|
||||
//go:embed migrations/0015_inbound_tls_checks.sql
|
||||
var inboundTLSChecksSchema string
|
||||
|
||||
//go:embed migrations/0016_diagnostic_operations.sql
|
||||
var diagnosticOperationsSchema 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
|
||||
@@ -82,6 +85,7 @@ var migrations = []struct {
|
||||
{13, dropChecksIndexSchema},
|
||||
{14, diagnosticHoldsSchema},
|
||||
{15, inboundTLSChecksSchema},
|
||||
{16, diagnosticOperationsSchema},
|
||||
}
|
||||
|
||||
// connPragmas are applied to every new connection. A larger WAL checkpoint
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
CREATE TABLE diagnostic_operations (
|
||||
id TEXT PRIMARY KEY,
|
||||
note TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE diagnostic_operation_items (
|
||||
id INTEGER PRIMARY KEY,
|
||||
operation_id TEXT NOT NULL REFERENCES diagnostic_operations(id),
|
||||
address TEXT NOT NULL,
|
||||
requested_validator TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'queued' CHECK(status IN ('queued', 'running', 'attached', 'rejected')),
|
||||
validator_id TEXT NOT NULL DEFAULT '',
|
||||
port_id TEXT NOT NULL DEFAULT '',
|
||||
fip_id TEXT NOT NULL DEFAULT '',
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
retry_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX idx_diagnostic_operation_items ON diagnostic_operation_items(operation_id, id);
|
||||
CREATE INDEX idx_diagnostic_pending ON diagnostic_operation_items(id) WHERE status IN ('queued', 'running');
|
||||
ALTER TABLE diagnostic_holds ADD COLUMN pending_item_id INTEGER REFERENCES diagnostic_operation_items(id);
|
||||
CREATE UNIQUE INDEX idx_diagnostic_pending_hold ON diagnostic_holds(pending_item_id) WHERE pending_item_id IS NOT NULL;
|
||||
@@ -20,16 +20,43 @@ type DiagnosticHold struct {
|
||||
// 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 {
|
||||
return d.claimDiagnostic(ctx, validatorID, address, fipID, note, nil)
|
||||
}
|
||||
|
||||
func (d *DB) claimDiagnostic(ctx context.Context, validatorID, address, fipID, note string, item *DiagnosticOperationItem) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
now := timeToDB(Now())
|
||||
var active bool
|
||||
err = tx.QueryRowContext(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM ip_queue WHERE ip_address=? AND state IN (?, ?, ?, ?))
|
||||
`, address, IPAssigningFIP, IPAwaitingSelfCheck, IPChecking, IPAggregating).Scan(&active)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if active {
|
||||
return fmt.Errorf("address %q is being checked: %w", address, ErrBusy)
|
||||
}
|
||||
var held bool
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM diagnostic_holds WHERE address=? OR validator_id=?)
|
||||
`, address, validatorID).Scan(&held); err != nil {
|
||||
return err
|
||||
}
|
||||
if held {
|
||||
return fmt.Errorf("address %q or validator %q is already held: %w", address, validatorID, ErrConflict)
|
||||
}
|
||||
var expectedPort string
|
||||
if item != nil {
|
||||
expectedPort = item.PortID
|
||||
}
|
||||
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)
|
||||
WHERE validator_id=? AND state=? AND current_ip_id IS NULL AND (?='' OR os_port_id=?)
|
||||
`, ValidatorDiagnostic, now, validatorID, ValidatorIdle, expectedPort, expectedPort)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -42,12 +69,22 @@ func (d *DB) ClaimDiagnostic(ctx context.Context, validatorID, address, fipID, n
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("validator %q is not idle: %w", validatorID, ErrBusy)
|
||||
return fmt.Errorf("validator %q is no longer idle on the selected port: %w", validatorID, ErrBusy)
|
||||
}
|
||||
var pendingID *int64
|
||||
if item != nil {
|
||||
pendingID = &item.ID
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET validator_id=?, port_id=?, fip_id=? WHERE id=? AND status='running'
|
||||
`, validatorID, item.PortID, fipID, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
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)
|
||||
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at, pending_item_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`, address, validatorID, fipID, note, now, pendingID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -60,26 +97,37 @@ func (d *DB) ReleaseDiagnostic(ctx context.Context, address string) (*Diagnostic
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
h, err := scanHold(tx.QueryRowContext(ctx, holdSelect+` WHERE address=?`, address))
|
||||
h, err := scanHold(tx.QueryRowContext(ctx, holdSelect+` WHERE address=? AND pending_item_id IS NULL`, 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 {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM diagnostic_holds WHERE address=? AND pending_item_id IS NULL`, 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 {
|
||||
if err := resetDiagnosticValidator(ctx, tx, h.ValidatorID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h, tx.Commit()
|
||||
}
|
||||
|
||||
func resetDiagnosticValidator(ctx context.Context, tx *sql.Tx, validatorID string) error {
|
||||
_, err := tx.ExecContext(ctx, `
|
||||
UPDATE validators SET state=?, updated_at=? WHERE validator_id=? AND state=?
|
||||
`, ValidatorIdle, timeToDB(Now()), validatorID, ValidatorDiagnostic)
|
||||
return err
|
||||
}
|
||||
|
||||
const holdSelect = `SELECT address, validator_id, fip_id, note, created_at FROM diagnostic_holds`
|
||||
|
||||
func (d *DB) HasDiagnosticHold(ctx context.Context, address string) (bool, error) {
|
||||
var exists bool
|
||||
err := d.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM diagnostic_holds WHERE address=?)`, address).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
func scanHold(row rowScanner) (*DiagnosticHold, error) {
|
||||
var h DiagnosticHold
|
||||
var created string
|
||||
@@ -93,9 +141,9 @@ func scanHold(row rowScanner) (*DiagnosticHold, error) {
|
||||
return &h, nil
|
||||
}
|
||||
|
||||
// ListDiagnosticHolds returns all holds, oldest first.
|
||||
// ListDiagnosticHolds returns confirmed holds, oldest first.
|
||||
func (d *DB) ListDiagnosticHolds(ctx context.Context) ([]DiagnosticHold, error) {
|
||||
rows, err := d.QueryContext(ctx, holdSelect+` ORDER BY id`)
|
||||
rows, err := d.QueryContext(ctx, holdSelect+` WHERE pending_item_id IS NULL ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DiagnosticOperation struct {
|
||||
ID string `json:"id"`
|
||||
Items []DiagnosticOperationItem `json:"items"`
|
||||
}
|
||||
|
||||
type DiagnosticOperationItem struct {
|
||||
ID int64 `json:"-"`
|
||||
OperationID string `json:"-"`
|
||||
Note string `json:"-"`
|
||||
Address string `json:"address"`
|
||||
RequestedValidator string `json:"-"`
|
||||
Status string `json:"status"`
|
||||
ValidatorID string `json:"validator_id,omitempty"`
|
||||
PortID string `json:"-"`
|
||||
FIPID string `json:"fip_id,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
func (d *DB) CreateDiagnosticOperation(ctx context.Context, id, note, requestHash string, items []DiagnosticOperationItem) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO diagnostic_operations (id, note, request_hash, created_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(id) DO NOTHING
|
||||
`, id, note, requestHash, timeToDB(Now()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
var storedHash string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT request_hash FROM diagnostic_operations WHERE id=?`, id).Scan(&storedHash); err != nil {
|
||||
return err
|
||||
}
|
||||
if storedHash != requestHash {
|
||||
return fmt.Errorf("operation ID already used for a different request: %w", ErrConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, item := range items {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO diagnostic_operation_items (operation_id, address, requested_validator) VALUES (?, ?, ?)
|
||||
`, id, item.Address, item.RequestedValidator); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (d *DB) GetDiagnosticOperation(ctx context.Context, id string) (DiagnosticOperation, error) {
|
||||
op := DiagnosticOperation{ID: id}
|
||||
rows, err := d.QueryContext(ctx, `
|
||||
SELECT address, status, validator_id, fip_id, reason FROM diagnostic_operation_items
|
||||
WHERE operation_id=? ORDER BY id
|
||||
`, id)
|
||||
if err != nil {
|
||||
return op, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var item DiagnosticOperationItem
|
||||
if err := rows.Scan(&item.Address, &item.Status, &item.ValidatorID, &item.FIPID, &item.Reason); err != nil {
|
||||
return op, err
|
||||
}
|
||||
op.Items = append(op.Items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return op, err
|
||||
}
|
||||
if len(op.Items) == 0 {
|
||||
return op, ErrNotFound
|
||||
}
|
||||
return op, nil
|
||||
}
|
||||
|
||||
// NextDiagnosticOperationItem is called by the Control API's single worker.
|
||||
// A retrying item blocks only the later addresses in its own operation.
|
||||
func (d *DB) NextDiagnosticOperationItem(ctx context.Context) (DiagnosticOperationItem, error) {
|
||||
var item DiagnosticOperationItem
|
||||
err := d.QueryRowContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET status='running'
|
||||
WHERE id=(
|
||||
SELECT i.id FROM diagnostic_operation_items i
|
||||
WHERE i.status IN ('queued', 'running') AND i.retry_at<=?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM diagnostic_operation_items earlier
|
||||
WHERE earlier.operation_id=i.operation_id AND earlier.id<i.id
|
||||
AND earlier.status IN ('queued', 'running')
|
||||
)
|
||||
ORDER BY i.id LIMIT 1
|
||||
)
|
||||
RETURNING id, operation_id, address, requested_validator, validator_id, port_id, fip_id,
|
||||
(SELECT note FROM diagnostic_operations WHERE id=diagnostic_operation_items.operation_id)
|
||||
`, Now().UnixMilli()).Scan(&item.ID, &item.OperationID, &item.Address, &item.RequestedValidator,
|
||||
&item.ValidatorID, &item.PortID, &item.FIPID, &item.Note)
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (d *DB) ReserveDiagnosticOperationItem(ctx context.Context, item DiagnosticOperationItem) error {
|
||||
return d.claimDiagnostic(ctx, item.ValidatorID, item.Address, item.FIPID, item.Note, &item)
|
||||
}
|
||||
|
||||
func (d *DB) RetryDiagnosticOperationItem(ctx context.Context, id int64, reason string, delay time.Duration) error {
|
||||
_, err := d.ExecContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET reason=?, retry_at=? WHERE id=? AND status='running'
|
||||
`, reason, Now().Add(delay).UnixMilli(), id)
|
||||
return err
|
||||
}
|
||||
|
||||
// FinishDiagnosticOperationItem commits the outcome together with its hold
|
||||
// and audit event, so recovery cannot publish a success twice.
|
||||
func (d *DB) FinishDiagnosticOperationItem(ctx context.Context, item DiagnosticOperationItem, reason string, event *Event) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
status := "rejected"
|
||||
if event != nil {
|
||||
status = "attached"
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE diagnostic_holds SET pending_item_id=NULL WHERE pending_item_id=?`, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := insertEvent(ctx, tx, *event); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if item.FIPID != "" {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM diagnostic_holds WHERE pending_item_id=?`, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := resetDiagnosticValidator(ctx, tx, item.ValidatorID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET status=?, reason=?, retry_at=0 WHERE id=? AND status='running'
|
||||
`, status, reason, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -10,7 +10,13 @@ import (
|
||||
// event stays traceable to its address (via registry_id) and prunable at
|
||||
// the right cycle boundary even after the ip_queue row itself is deleted.
|
||||
func (d *DB) InsertEvent(ctx context.Context, e Event) error {
|
||||
_, err := d.ExecContext(ctx, `
|
||||
return insertEvent(ctx, d, e)
|
||||
}
|
||||
|
||||
func insertEvent(ctx context.Context, q interface {
|
||||
ExecContext(context.Context, string, ...any) (sql.Result, error)
|
||||
}, e Event) error {
|
||||
_, err := q.ExecContext(ctx, `
|
||||
INSERT INTO events (source_type, source_id, ip_id, registry_id, cycle_id, event_type, payload, occurred_at, created_at)
|
||||
VALUES (?, ?, ?, (SELECT registry_id FROM ip_queue WHERE id=?), COALESCE((SELECT cycle_id FROM ip_queue WHERE id=?), 0), ?, ?, ?, ?)
|
||||
`, e.SourceType, e.SourceID, e.IPID, e.IPID, e.IPID, e.EventType, e.Payload, timeToDB(e.OccurredAt), timeToDB(Now()))
|
||||
|
||||
@@ -391,7 +391,7 @@ func TestMigration0011BuildsRunsFromExistingData(t *testing.T) {
|
||||
}
|
||||
var ver int
|
||||
d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver)
|
||||
if ver != 15 {
|
||||
if ver != migrations[len(migrations)-1].version {
|
||||
t.Errorf("user_version = %d", ver)
|
||||
}
|
||||
}
|
||||
@@ -240,7 +240,7 @@ 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 != 15 {
|
||||
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != migrations[len(migrations)-1].version {
|
||||
t.Errorf("user_version=%d err=%v", ver, err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user