Persist Floating IP UUIDs for direct Neutron operations
This commit is contained in:
1 parent
89ac4d5bcd
commit
94124747ce
24 files changed
+918
-116
No files matched your search
@@ -62,6 +62,9 @@ var inboundTLSChecksSchema string
|
||||
//go:embed migrations/0016_diagnostic_operations.sql
|
||||
var diagnosticOperationsSchema string
|
||||
|
||||
//go:embed migrations/0017_floating_ips.sql
|
||||
var floatingIPsSchema 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
|
||||
@@ -86,6 +89,7 @@ var migrations = []struct {
|
||||
{14, diagnosticHoldsSchema},
|
||||
{15, inboundTLSChecksSchema},
|
||||
{16, diagnosticOperationsSchema},
|
||||
{17, floatingIPsSchema},
|
||||
}
|
||||
|
||||
// connPragmas are applied to every new connection. A larger WAL checkpoint
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
CREATE TABLE floating_ip_mappings (
|
||||
project_id TEXT NOT NULL,
|
||||
region TEXT NOT NULL,
|
||||
address TEXT NOT NULL,
|
||||
fip_id TEXT NOT NULL,
|
||||
confirmed_at INTEGER NOT NULL, -- Unix nanoseconds
|
||||
PRIMARY KEY (project_id, region, address)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
-- Older records had no project or region. Use them as hints until Neutron
|
||||
-- has confirmed the address and its ownership in the configured scope.
|
||||
CREATE TABLE floating_ip_legacy_candidates (
|
||||
address TEXT PRIMARY KEY,
|
||||
fip_id TEXT NOT NULL
|
||||
) WITHOUT ROWID;
|
||||
|
||||
WITH relevant_events AS (
|
||||
SELECT e.id, e.occurred_at, e.event_type, r.ip_address,
|
||||
CASE WHEN json_valid(e.payload) THEN e.payload ELSE '{}' END AS payload
|
||||
FROM events e
|
||||
LEFT JOIN ip_registry r ON r.id = e.registry_id
|
||||
WHERE e.event_type IN ('fip_associated', 'fip_occupied', 'diagnostic_attached', 'diagnostic_detached')
|
||||
), candidates AS (
|
||||
SELECT ip_address AS address, fip_id, COALESCE(fip_associated_at, updated_at) AS observed_at, 3 AS source, id
|
||||
FROM ip_queue
|
||||
WHERE fip_id <> ''
|
||||
UNION ALL
|
||||
SELECT address, fip_id, created_at, 4, id FROM diagnostic_holds WHERE fip_id <> ''
|
||||
UNION ALL
|
||||
SELECT i.address, i.fip_id, o.created_at, 2, i.id
|
||||
FROM diagnostic_operation_items i
|
||||
JOIN diagnostic_operations o ON o.id = i.operation_id
|
||||
WHERE i.fip_id <> ''
|
||||
UNION ALL
|
||||
SELECT CASE WHEN event_type IN ('diagnostic_attached', 'diagnostic_detached')
|
||||
THEN json_extract(payload, '$.address') ELSE ip_address END,
|
||||
json_extract(payload, '$.fip_id'), occurred_at, 1, id
|
||||
FROM relevant_events
|
||||
WHERE json_type(payload, '$.fip_id') = 'text'
|
||||
), ranked AS (
|
||||
SELECT address, fip_id, ROW_NUMBER() OVER (
|
||||
PARTITION BY address ORDER BY julianday(observed_at) DESC, source DESC, id DESC
|
||||
) AS rank
|
||||
FROM candidates
|
||||
WHERE typeof(address) = 'text' AND address <> '' AND fip_id <> ''
|
||||
)
|
||||
INSERT INTO floating_ip_legacy_candidates (address, fip_id)
|
||||
SELECT address, fip_id FROM ranked WHERE rank = 1;
|
||||
|
||||
ALTER TABLE diagnostic_holds ADD COLUMN port_id TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- Pending holds already have an exact link to their reserved port.
|
||||
UPDATE diagnostic_holds
|
||||
SET port_id = COALESCE((SELECT port_id FROM diagnostic_operation_items WHERE id = pending_item_id), '')
|
||||
WHERE pending_item_id IS NOT NULL;
|
||||
@@ -12,6 +12,7 @@ type DiagnosticHold struct {
|
||||
Address string `json:"address"`
|
||||
ValidatorID string `json:"validator_id"`
|
||||
FIPID string `json:"fip_id"`
|
||||
PortID string `json:"-"`
|
||||
Note string `json:"note"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -20,10 +21,14 @@ 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)
|
||||
return d.ClaimDiagnosticAtPort(ctx, validatorID, "", address, fipID, note)
|
||||
}
|
||||
|
||||
func (d *DB) claimDiagnostic(ctx context.Context, validatorID, address, fipID, note string, item *DiagnosticOperationItem) error {
|
||||
func (d *DB) ClaimDiagnosticAtPort(ctx context.Context, validatorID, portID, address, fipID, note string) error {
|
||||
return d.claimDiagnostic(ctx, validatorID, portID, address, fipID, note, nil)
|
||||
}
|
||||
|
||||
func (d *DB) claimDiagnostic(ctx context.Context, validatorID, expectedPort, address, fipID, note string, item *DiagnosticOperationItem) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -49,10 +54,6 @@ func (d *DB) claimDiagnostic(ctx context.Context, validatorID, address, fipID, n
|
||||
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 AND (?='' OR os_port_id=?)
|
||||
@@ -81,9 +82,9 @@ func (d *DB) claimDiagnostic(ctx context.Context, validatorID, address, fipID, n
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at, pending_item_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`, address, validatorID, fipID, note, now, pendingID); err != nil {
|
||||
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at, pending_item_id, port_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, (SELECT os_port_id FROM validators WHERE validator_id=?))
|
||||
`, address, validatorID, fipID, note, now, pendingID, validatorID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
@@ -120,7 +121,7 @@ func resetDiagnosticValidator(ctx context.Context, tx *sql.Tx, validatorID strin
|
||||
return err
|
||||
}
|
||||
|
||||
const holdSelect = `SELECT address, validator_id, fip_id, note, created_at FROM diagnostic_holds`
|
||||
const holdSelect = `SELECT address, validator_id, fip_id, note, created_at, port_id FROM diagnostic_holds`
|
||||
|
||||
func (d *DB) HasDiagnosticHold(ctx context.Context, address string) (bool, error) {
|
||||
var exists bool
|
||||
@@ -131,7 +132,7 @@ func (d *DB) HasDiagnosticHold(ctx context.Context, address string) (bool, error
|
||||
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 {
|
||||
if err := row.Scan(&h.Address, &h.ValidatorID, &h.FIPID, &h.Note, &created, &h.PortID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var err error
|
||||
|
||||
@@ -12,16 +12,17 @@ type DiagnosticOperation struct {
|
||||
}
|
||||
|
||||
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"`
|
||||
ID int64 `json:"-"`
|
||||
OperationID string `json:"-"`
|
||||
Note string `json:"-"`
|
||||
CreatedAt time.Time `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 {
|
||||
@@ -91,6 +92,7 @@ func (d *DB) GetDiagnosticOperation(ctx context.Context, id string) (DiagnosticO
|
||||
// A retrying item blocks only the later addresses in its own operation.
|
||||
func (d *DB) NextDiagnosticOperationItem(ctx context.Context) (DiagnosticOperationItem, error) {
|
||||
var item DiagnosticOperationItem
|
||||
var createdAt string
|
||||
err := d.QueryRowContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET status='running'
|
||||
WHERE id=(
|
||||
@@ -104,14 +106,18 @@ func (d *DB) NextDiagnosticOperationItem(ctx context.Context) (DiagnosticOperati
|
||||
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)
|
||||
(SELECT note FROM diagnostic_operations WHERE id=diagnostic_operation_items.operation_id),
|
||||
(SELECT created_at 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)
|
||||
&item.ValidatorID, &item.PortID, &item.FIPID, &item.Note, &createdAt)
|
||||
if err == nil {
|
||||
item.CreatedAt, err = dbToTime(createdAt)
|
||||
}
|
||||
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)
|
||||
return d.claimDiagnostic(ctx, item.ValidatorID, item.PortID, item.Address, item.FIPID, item.Note, &item)
|
||||
}
|
||||
|
||||
func (d *DB) RetryDiagnosticOperationItem(ctx context.Context, id int64, reason string, delay time.Duration) error {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type FloatingIPScope struct {
|
||||
ProjectID string
|
||||
Region string
|
||||
}
|
||||
|
||||
type FloatingIPMapping struct {
|
||||
Address string
|
||||
FIPID string
|
||||
}
|
||||
|
||||
// FloatingIPCandidate prefers the confirmed scoped mapping to an unscoped
|
||||
// migration hint. The caller verifies either UUID against Neutron.
|
||||
func (d *DB) FloatingIPCandidate(ctx context.Context, scope FloatingIPScope, address string) (string, error) {
|
||||
var id string
|
||||
err := d.QueryRowContext(ctx, `
|
||||
SELECT COALESCE(
|
||||
(SELECT fip_id FROM floating_ip_mappings WHERE project_id=? AND region=? AND address=?),
|
||||
(SELECT fip_id FROM floating_ip_legacy_candidates WHERE address=?), '')
|
||||
`, scope.ProjectID, scope.Region, address, address).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
// ConfirmFloatingIPs persists one batch verified against the selected Neutron
|
||||
// endpoint. observedAt is when discovery started so a delayed scan cannot
|
||||
// overwrite a mapping discovered while that scan was in progress.
|
||||
func (d *DB) ConfirmFloatingIPs(ctx context.Context, scope FloatingIPScope, mappings []FloatingIPMapping, observedAt time.Time) error {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
stmt, err := tx.PrepareContext(ctx, `
|
||||
INSERT INTO floating_ip_mappings (project_id, region, address, fip_id, confirmed_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (project_id, region, address) DO UPDATE SET
|
||||
fip_id=excluded.fip_id, confirmed_at=excluded.confirmed_at
|
||||
WHERE excluded.confirmed_at >= floating_ip_mappings.confirmed_at
|
||||
`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stmt.Close()
|
||||
for _, m := range mappings {
|
||||
if _, err := stmt.ExecContext(ctx, scope.ProjectID, scope.Region, m.Address, m.FIPID, observedAt.UnixNano()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFloatingIPMigrationKeepsHoldsAndHistory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "v16.db")
|
||||
conn, err := sql.Open("sqlite", dsn(path))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn.SetMaxOpenConns(1)
|
||||
defer conn.Close()
|
||||
oldDB := &DB{DB: conn}
|
||||
for _, migration := range migrations {
|
||||
if migration.version > 16 {
|
||||
break
|
||||
}
|
||||
if _, err := oldDB.ExecContext(ctx, migration.sql); err != nil {
|
||||
t.Fatalf("migration %d: %v", migration.version, err)
|
||||
}
|
||||
}
|
||||
if _, err := oldDB.ExecContext(ctx, `PRAGMA user_version=16`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
active, historical, held, pending := "192.0.2.1", "192.0.2.2", "192.0.2.3", "192.0.2.4"
|
||||
if err := oldDB.SeedQueue(ctx, []string{active, historical}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := oldDB.ExecContext(ctx, `
|
||||
UPDATE ip_queue SET fip_id='queued-uuid' WHERE ip_address=?
|
||||
`, active); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, id := range []string{"held-validator", "pending-validator"} {
|
||||
if err := oldDB.RegisterValidator(ctx, id, "", id+"-port", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := oldDB.ExecContext(ctx, `
|
||||
UPDATE validators SET state='diagnostic' WHERE validator_id IN ('held-validator', 'pending-validator');
|
||||
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at)
|
||||
VALUES (?, 'held-validator', 'held-uuid', 'existing hold', ?);
|
||||
`, held, timeToDB(Now())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := oldDB.CreateDiagnosticOperation(ctx, "pending-operation", "", "hash", []DiagnosticOperationItem{
|
||||
{Address: pending, RequestedValidator: "pending-validator"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item, err := oldDB.NextDiagnosticOperationItem(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item.ValidatorID, item.PortID, item.FIPID = "pending-validator", "pending-validator-port", "pending-uuid"
|
||||
if _, err := oldDB.ExecContext(ctx, `
|
||||
UPDATE diagnostic_operation_items SET validator_id=?, port_id=?, fip_id=? WHERE id=?
|
||||
`, item.ValidatorID, item.PortID, item.FIPID, item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := oldDB.ExecContext(ctx, `
|
||||
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at, pending_item_id)
|
||||
VALUES (?, 'pending-validator', 'pending-uuid', '', ?, ?)
|
||||
`, pending, timeToDB(Now()), item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
history, err := oldDB.GetIPByAddress(ctx, historical)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
historicalEvent := Event{
|
||||
IPID: &history.ID, SourceType: "control-api", EventType: "fip_associated", Payload: `{"fip_id":"old-uuid"}`,
|
||||
OccurredAt: Now().Add(-time.Hour),
|
||||
}
|
||||
if err := oldDB.InsertEvent(ctx, historicalEvent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
historicalEvent.Payload, historicalEvent.OccurredAt = `{"fip_id":"history-uuid"}`, Now()
|
||||
if err := oldDB.InsertEvent(ctx, historicalEvent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
historicalEvent.Payload = "invalid legacy JSON"
|
||||
if err := oldDB.InsertEvent(ctx, historicalEvent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := oldDB.ExecContext(ctx, `
|
||||
INSERT INTO checks (registry_id, cycle_id, ip_id, ip_address, attempt_number, source, check_type, success, checked_at)
|
||||
VALUES (?, ?, ?, ?, 1, 'validator-agent', 'https', 1, ?)
|
||||
`, history.RegistryID, history.CycleID, history.ID, historical, timeToDB(Now())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := oldDB.DeleteIP(ctx, history.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := oldDB.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
d, err := Open(ctx, path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
scope := FloatingIPScope{ProjectID: "project", Region: "region"}
|
||||
for address, expected := range map[string]string{
|
||||
active: "queued-uuid", historical: "history-uuid", held: "held-uuid", pending: "pending-uuid",
|
||||
} {
|
||||
if got, err := d.FloatingIPCandidate(ctx, scope, address); err != nil || got != expected {
|
||||
t.Errorf("candidate for %s = %q, want %q, err=%v", address, got, expected, err)
|
||||
}
|
||||
}
|
||||
var mappings int
|
||||
if err := d.QueryRowContext(ctx, `SELECT COUNT(*) FROM floating_ip_mappings`).Scan(&mappings); err != nil || mappings != 0 {
|
||||
t.Errorf("confirmed mapping count = %d, err=%v", mappings, err)
|
||||
}
|
||||
holds, err := d.ListDiagnosticHolds(ctx)
|
||||
if err != nil || len(holds) != 1 || holds[0].FIPID != "held-uuid" || holds[0].Note != "existing hold" {
|
||||
t.Errorf("holds: %+v, err=%v", holds, err)
|
||||
}
|
||||
pendingItem, err := d.NextDiagnosticOperationItem(ctx)
|
||||
if err != nil || pendingItem.FIPID != "pending-uuid" || pendingItem.PortID != item.PortID {
|
||||
t.Errorf("pending item: %+v, err=%v", pendingItem, err)
|
||||
}
|
||||
var pendingPort string
|
||||
if err := d.QueryRowContext(ctx, `SELECT port_id FROM diagnostic_holds WHERE pending_item_id=?`, item.ID).Scan(&pendingPort); err != nil ||
|
||||
pendingPort != item.PortID {
|
||||
t.Errorf("backfilled pending hold port = %q, err=%v", pendingPort, err)
|
||||
}
|
||||
var checks int
|
||||
if err := d.QueryRowContext(ctx, `SELECT COUNT(*) FROM checks WHERE registry_id=? AND ip_id IS NULL`, history.RegistryID).
|
||||
Scan(&checks); err != nil || checks != 1 {
|
||||
t.Errorf("retained checks = %d, err=%v", checks, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFloatingIPMappingsAreScopedAndKeepNewestObservation(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
d, err := Open(ctx, filepath.Join(t.TempDir(), "mappings.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
address := "192.0.2.10"
|
||||
regions := []FloatingIPScope{
|
||||
{ProjectID: "a", Region: "west"}, {ProjectID: "a", Region: "east"}, {ProjectID: "b", Region: "west"},
|
||||
}
|
||||
ids := []string{"west-uuid", "east-uuid", "other-project-uuid"}
|
||||
now := time.Now()
|
||||
for i, scope := range regions {
|
||||
if err := d.ConfirmFloatingIPs(ctx, scope, []FloatingIPMapping{{Address: address, FIPID: ids[i]}}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := d.ConfirmFloatingIPs(ctx, regions[0], []FloatingIPMapping{{Address: address, FIPID: "old-scan-uuid"}}, now.Add(-time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, scope := range regions {
|
||||
if got, err := d.FloatingIPCandidate(ctx, scope, address); err != nil || got != ids[i] {
|
||||
t.Errorf("candidate for %+v = %q, want %q, err=%v", scope, got, ids[i], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user