diff --git a/bin/SHA256SUMS b/bin/SHA256SUMS index 37391ba..5c49ddf 100644 --- a/bin/SHA256SUMS +++ b/bin/SHA256SUMS @@ -1,4 +1,4 @@ -891ec11d493f031e5c06d66dff45c31cfb9ce440e684d5c17617b744ffbb2126 control-api +69a60a3ba48e83640b6d8b122401e7204cfaac6c5d60976e19904c81eb37f838 control-api ec6959ae151d8ad1ad5b68faca420159ca6ca6b3dd1359b7f9b0d8489ac0a27b validator-agent 7ef8785769d946d81c338f53928bbe18f243ec5b96ab8b874846504b8ac4e98c prober -76059951436e37f5fc8f87a882f6fa6f7c362ed5718722495dc0caf6a7b781de admin-dashboard +dd3fcccf595608f477726d4818abe4e4fb9c7212ab6df73c68fdc346222ab047 admin-dashboard diff --git a/bin/admin-dashboard b/bin/admin-dashboard index 8bda36e..f2102a1 100755 Binary files a/bin/admin-dashboard and b/bin/admin-dashboard differ diff --git a/bin/control-api b/bin/control-api index a1266bb..3780a09 100755 Binary files a/bin/control-api and b/bin/control-api differ diff --git a/cmd/control-api/main.go b/cmd/control-api/main.go index ac7effb..1ff16c4 100644 --- a/cmd/control-api/main.go +++ b/cmd/control-api/main.go @@ -59,6 +59,9 @@ func run(configPath string, log *slog.Logger) error { } orch := orchestrator.New(database, osClient, cfg, log) + if cfg.OpenStack.Mode != "real" { + orch.FIPScope = db.FloatingIPScope{ProjectID: "mock-project"} + } orch.Async = true // slow OpenStack calls run per address, Tick never waits for them // Background jobs (the floating-IP scan) live as long as the process, not // as long as the HTTP request or loop iteration that started them. diff --git a/docs/changes/2026-11-22_21-02_floating-ip-uuid-plan.md b/docs/changes/2026-11-22_21-02_floating-ip-uuid-plan.md new file mode 100644 index 0000000..e12489e --- /dev/null +++ b/docs/changes/2026-11-22_21-02_floating-ip-uuid-plan.md @@ -0,0 +1,24 @@ +# План хранения UUID Floating IP и прямого обращения к Neutron + +## Цель и исходное состояние + +Сохранять IPv4 и UUID ресурса Floating IP при первом обнаружении. Для дальнейших операций с известным ресурсом использовать его UUID. В боевом замере для одного Floating IP списочный запрос с фильтром по IPv4 занял 31,8 с, а прямое чтение по UUID — 334 мс. Это время чтения в Neutron, а не полное время привязки или отвязки. + +Сканирование уже получает IPv4 и UUID, но передаёт в очередь только IPv4. `ip_queue.fip_id` относится к текущей попытке и может очищаться при повторной постановке. В `diagnostic_holds.fip_id` и в записи начатой фоновой операции диагностики уже хранится UUID конкретной привязки. [Сканирование](../../internal/orchestrator/scanjob.go) · [Очередь](../../internal/db/queries_ipqueue.go) · [Фоновые операции диагностики](../../internal/orchestrator/diagnostic_operations.go) + +На момент составления плана в рабочем дереве есть проверенная локальная правка отвязки по сохранённому UUID и индикатор ожидания в панели. На боевых контейнерах работает поставка коммита `89ac4d5`. При возобновлении работы проверьте состояние ветки и наличие этой правки перед реализацией. [Отвязка](../../internal/orchestrator/diagnostic.go) + +## План + +1. **Хранение.** Добавить миграцию SQLite и отдельную таблицу соответствий. Ключ включает проект, регион и IPv4. Запись хранит UUID ресурса и время последнего подтверждения. Текущие поля `fip_id` в очереди и диагностике продолжают указывать на ресурс конкретной попытки или привязки. Начальное заполнение берёт доступные пары из БД. Перед использованием эти пары подтверждаются прямым чтением в Neutron. Миграция выполняется без сетевых вызовов. +2. **Обнаружение.** При обычном сканировании сохранять полученные пары IPv4 и UUID в БД пакетами. В очередь по-прежнему попадают только свободные адреса. Пробный скан сохраняет текущее поведение без записи результатов в БД. Для IPv4, введённого вручную или загруженного из конфигурации, выполнять один поиск при первой операции, если сохранённого соответствия ещё нет, и сохранять подтверждённую пару. Формат ввода адресов в UI и API сохраняется. +3. **Прямые операции.** Использовать `GET /v2.0/floatingips/{uuid}` при назначении валидатору, ручной привязке и сверке незавершённой диагностики. Проверять соответствие IPv4, проект и текущий порт там, где эти данные нужны для решения о привязке. Изменения и отвязка используют UUID ресурса. Для отмены, очистки очереди и освобождения адресов сохранить существующее использование UUID текущей попытки. Сверка по порту валидатора остаётся нужна для поиска привязок, которые ещё не успели записать в БД. +4. **Устаревшие соответствия.** Перед новой привязкой при `404` или несовпадении адреса выполнить один поиск по IPv4 в нужном проекте и обновить запись только после подтверждения ресурса. Временная ошибка Neutron обрабатывается по правилам повторов операции и не удаляет соответствие. При отвязке или восстановлении уже начатой привязки использовать только UUID, сохранённый у этой привязки. Если исходный ресурс исчез, обработать его отсутствие без изменений другого ресурса с тем же IPv4. +5. **Наблюдаемость и выкладка.** Различать в логах прямое чтение и резервный поиск по IPv4. Замерять отдельно время получения ресурса, изменения привязки и всего запроса. Перед выкладкой проверить миграцию на копии БД и убедиться, что текущие удержания и история проверок сохраняются. + +## Критерии приёмки + +- После обычного сканирования повторное назначение и ручная диагностика известного IPv4 обходятся без списочного запроса по адресу. После первого поиска вручную введённого IPv4 следующие операции используют сохранённый UUID, в том числе после очистки очереди и перезапуска. +- Тесты покрывают миграцию действующей БД, пробный скан без записи, смену UUID у того же IPv4, временные ошибки Neutron и восстановление привязки по сохранённому UUID без повторного `PUT`, если порт уже совпадает. +- Отвязка по UUID освобождает исходный ресурс и валидатор. Изменение соответствия IPv4 и UUID не влияет на ресурс, зафиксированный в существующей привязке. +- На стенде по логам или счётчикам запросов подтверждены отсутствие поиска по IPv4 в штатном сценарии с известным UUID и время привязки и отвязки от запроса до результата. diff --git a/internal/dashboard/templates/diagnostics.html b/internal/dashboard/templates/diagnostics.html index 662098e..2747adf 100644 --- a/internal/dashboard/templates/diagnostics.html +++ b/internal/dashboard/templates/diagnostics.html @@ -100,10 +100,12 @@ hx-swap="outerHTML">

Удерживаемые адреса

{{if .Rows}} -
+
+Отвязываем…
diff --git a/internal/db/db.go b/internal/db/db.go index 04edb99..79a2674 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -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 diff --git a/internal/db/migrations/0017_floating_ips.sql b/internal/db/migrations/0017_floating_ips.sql new file mode 100644 index 0000000..8b5445b --- /dev/null +++ b/internal/db/migrations/0017_floating_ips.sql @@ -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; diff --git a/internal/db/queries_diagnostic.go b/internal/db/queries_diagnostic.go index 175b93d..7f97825 100644 --- a/internal/db/queries_diagnostic.go +++ b/internal/db/queries_diagnostic.go @@ -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 diff --git a/internal/db/queries_diagnostic_operations.go b/internal/db/queries_diagnostic_operations.go index 7d1c678..ade17fc 100644 --- a/internal/db/queries_diagnostic_operations.go +++ b/internal/db/queries_diagnostic_operations.go @@ -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 { diff --git a/internal/db/queries_floating_ips.go b/internal/db/queries_floating_ips.go new file mode 100644 index 0000000..1f35c15 --- /dev/null +++ b/internal/db/queries_floating_ips.go @@ -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() +} diff --git a/internal/db/queries_floating_ips_test.go b/internal/db/queries_floating_ips_test.go new file mode 100644 index 0000000..d1c87a9 --- /dev/null +++ b/internal/db/queries_floating_ips_test.go @@ -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) + } + } +} diff --git a/internal/openstack/client.go b/internal/openstack/client.go index c721ad6..bc7c6ea 100644 --- a/internal/openstack/client.go +++ b/internal/openstack/client.go @@ -68,6 +68,8 @@ type ClientConfig struct { type Client struct { networking *gophercloud.ServiceClient retry pageRetry + projectID string + region string } // buildAuthOptions translates ClientConfig into gophercloud.AuthOptions. It @@ -152,11 +154,25 @@ func NewClient(ctx context.Context, cfg ClientConfig) (*Client, error) { if retries < 0 { retries = DefaultListPageRetries } - return &Client{networking: networking, retry: pageRetry{Retries: retries}}, nil + region := cfg.Region + if region == "" { + // Endpoint selection can fall back to a catalog entry with no region + // configured. Keep mappings for different endpoints isolated. + region = networking.Endpoint + } + return &Client{networking: networking, retry: pageRetry{Retries: retries}, projectID: cfg.ProjectID, region: region}, nil +} + +func (c *Client) FloatingIPScope() (projectID, region string) { + return c.projectID, c.region } func (c *Client) GetFloatingIPByAddress(ctx context.Context, address string) (*FloatingIP, error) { - pages, err := floatingips.List(c.networking, floatingips.ListOpts{FloatingIP: address}).AllPages(ctx) + opts := floatingips.ListOpts{FloatingIP: address, ProjectID: c.projectID} + pages, err := floatingips.List(c.networking, opts).AllPages(ctx) + if gophercloud.ResponseCodeIs(err, 404) { + return nil, ErrNotFound(address) + } if err != nil { return nil, fmt.Errorf("openstack: list floating ips: %w", err) } @@ -164,11 +180,41 @@ func (c *Client) GetFloatingIPByAddress(ctx context.Context, address string) (*F if err != nil { return nil, fmt.Errorf("openstack: extract floating ips: %w", err) } - if len(list) == 0 { + var found *FloatingIP + for _, raw := range list { + f := extractFloatingIP(raw) + if f.Address != address || f.ID == "" || (c.projectID != "" && f.ProjectID != c.projectID) { + continue + } + if found != nil && found.ID != f.ID { + return nil, fmt.Errorf("openstack: multiple floating ips match address %s in project %s", address, c.projectID) + } + found = &f + } + if found == nil { return nil, ErrNotFound(address) } - f := list[0] - return &FloatingIP{ID: f.ID, Address: f.FloatingIP, PortID: f.PortID, ProjectID: f.TenantID}, nil + return found, nil +} + +func (c *Client) GetFloatingIP(ctx context.Context, id string) (*FloatingIP, error) { + f, err := floatingips.Get(ctx, c.networking, id).Extract() + if gophercloud.ResponseCodeIs(err, 404) { + return nil, ErrNotFound(id) + } + if err != nil { + return nil, fmt.Errorf("openstack: get floating ip %s: %w", id, err) + } + ip := extractFloatingIP(*f) + return &ip, nil +} + +func extractFloatingIP(f floatingips.FloatingIP) FloatingIP { + projectID := f.ProjectID + if projectID == "" { + projectID = f.TenantID + } + return FloatingIP{ID: f.ID, Address: f.FloatingIP, PortID: f.PortID, ProjectID: projectID} } // fipListFields is the set of attributes requested from Neutron when listing: @@ -206,7 +252,7 @@ func (o pagedListOpts) ToFloatingIPListQuery() (string, error) { // a proxy that link may point at an internal host. func (c *Client) fetchPage(ctx context.Context, marker string, limit int) ([]FloatingIP, error) { opts := pagedListOpts{ - ListOpts: floatingips.ListOpts{Limit: limit, Marker: marker}, + ListOpts: floatingips.ListOpts{Limit: limit, Marker: marker, ProjectID: c.projectID}, fields: fipListFields, } var out []FloatingIP @@ -217,11 +263,7 @@ func (c *Client) fetchPage(ctx context.Context, marker string, limit int) ([]Flo } out = make([]FloatingIP, 0, len(list)) for _, f := range list { - proj := f.TenantID - if proj == "" { - proj = f.ProjectID // Neutron may return only project_id when `fields` is used - } - out = append(out, FloatingIP{ID: f.ID, Address: f.FloatingIP, PortID: f.PortID, ProjectID: proj}) + out = append(out, extractFloatingIP(f)) } return false, nil // one page per request }) @@ -241,7 +283,7 @@ func (c *Client) ListFreeFloatingIPs(ctx context.Context, pageSize int, onPage f // ListFloatingIPsByPort asks Neutron for the floating IPs attached to portID. func (c *Client) ListFloatingIPsByPort(ctx context.Context, portID string) ([]FloatingIP, error) { - pages, err := floatingips.List(c.networking, floatingips.ListOpts{PortID: portID}).AllPages(ctx) + pages, err := floatingips.List(c.networking, floatingips.ListOpts{PortID: portID, ProjectID: c.projectID}).AllPages(ctx) if err != nil { return nil, fmt.Errorf("openstack: list floating ips of port %s: %w", portID, err) } @@ -250,12 +292,11 @@ func (c *Client) ListFloatingIPsByPort(ctx context.Context, portID string) ([]Fl return nil, fmt.Errorf("openstack: extract floating ips: %w", err) } out := make([]FloatingIP, 0, len(list)) - for _, f := range list { - proj := f.TenantID - if proj == "" { - proj = f.ProjectID + for _, raw := range list { + f := extractFloatingIP(raw) + if f.PortID == portID && (c.projectID == "" || f.ProjectID == c.projectID) { + out = append(out, f) } - out = append(out, FloatingIP{ID: f.ID, Address: f.FloatingIP, PortID: f.PortID, ProjectID: proj}) } return out, nil } @@ -283,6 +324,9 @@ func (c *Client) DisassociateFloatingIP(ctx context.Context, fipID string) error _, err := floatingips.Update(ctx, c.networking, fipID, floatingips.UpdateOpts{ PortID: &empty, }).Extract() + if gophercloud.ResponseCodeIs(err, 404) { + return ErrNotFound(fipID) + } if err != nil { return fmt.Errorf("openstack: disassociate floating ip %s: %w", fipID, err) } diff --git a/internal/openstack/interface.go b/internal/openstack/interface.go index 731a359..a54faf1 100644 --- a/internal/openstack/interface.go +++ b/internal/openstack/interface.go @@ -4,7 +4,10 @@ // mock via config alone. package openstack -import "context" +import ( + "context" + "errors" +) type FloatingIP struct { ID string @@ -24,6 +27,9 @@ type FloatingIPClient interface { // is registered in the service project. GetFloatingIPByAddress(ctx context.Context, address string) (*FloatingIP, error) + // GetFloatingIP reads a known Neutron resource by ID. + GetFloatingIP(ctx context.Context, id string) (*FloatingIP, error) + // ListFloatingIPs returns every floating IP registered in the service // project, both associated and free — filtering to the free pool (empty // PortID) is the caller's job. Used to discover addresses to feed into @@ -64,8 +70,8 @@ func ErrNotFound(address string) error { return ¬FoundError{address} } // IsNotFound reports whether err indicates the address has no matching // Neutron floating-ip resource. func IsNotFound(err error) bool { - _, ok := err.(*notFoundError) - return ok + var notFound *notFoundError + return errors.As(err, ¬Found) } // listAll collects every page of c.ListFreeFloatingIPs into one slice; it is diff --git a/internal/openstack/mock.go b/internal/openstack/mock.go index 4c03952..4d6aee3 100644 --- a/internal/openstack/mock.go +++ b/internal/openstack/mock.go @@ -81,6 +81,17 @@ func (m *MockClient) GetFloatingIPByAddress(ctx context.Context, address string) return &f, nil } +func (m *MockClient) GetFloatingIP(ctx context.Context, id string) (*FloatingIP, error) { + m.mu.Lock() + defer m.mu.Unlock() + f, ok := m.fips[id] + if !ok { + return nil, ErrNotFound(id) + } + copy := *f + return ©, nil +} + // SeedMany registers n free floating IPs with IDs "-00000"… and // ascending addresses starting at 198.18.0.1 (TEST-NET benchmarking range), // returning the addresses in seed order. diff --git a/internal/orchestrator/diagnostic.go b/internal/orchestrator/diagnostic.go index ce6a5ba..9e77042 100644 --- a/internal/orchestrator/diagnostic.go +++ b/internal/orchestrator/diagnostic.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "time" "cloudipvalidator/internal/db" "cloudipvalidator/internal/openstack" @@ -47,30 +48,37 @@ var activeQueueStates = map[string]bool{ // 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 { + start := time.Now() out := make([]DiagnosticResult, 0, len(items)) for _, it := range items { out = append(out, o.diagnosticAttachOne(ctx, it, note)) } + o.Log.Info("diagnostic attach request", "items", len(out), "duration_ms", time.Since(start).Milliseconds()) return out } func (o *Orchestrator) diagnosticAttachOne(ctx context.Context, it DiagnosticItem, note string) DiagnosticResult { addr := it.Address v, fip, reason, err := o.prepareDiagnosticAttach(ctx, it, "") - if err != nil { - return rejected(addr, "internal error: "+err.Error()) - } if reason != "" { return rejected(addr, reason) } - if err := o.DB.ClaimDiagnostic(ctx, v.ValidatorID, addr, fip.ID, note); err != nil { + if err != nil { + return rejected(addr, "internal error: "+err.Error()) + } + if err := o.DB.ClaimDiagnosticAtPort(ctx, v.ValidatorID, v.OSPortID, 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) + if fip.PortID == "" { + start := time.Now() + err := o.OS.AssociateFloatingIP(ctx, fip.ID, v.OSPortID) + o.logDiagnosticStage("", addr, "associate", start, err) + if 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()) } - 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) @@ -89,12 +97,16 @@ func (o *Orchestrator) prepareDiagnosticAttach(ctx context.Context, it Diagnosti if item, err := o.DB.GetIPByAddress(ctx, addr); err == nil && activeQueueStates[item.State] { return nil, nil, "address is being checked (" + item.State + ")", nil } - fip, err := o.lookupDiagnosticFIP(ctx, operationID, addr) + fip, err := o.resolveFloatingIP(ctx, operationID, addr) if err != nil { if openstack.IsNotFound(err) { return nil, nil, "floating ip not found in the project", nil } - return nil, nil, "cloud lookup failed: " + err.Error(), nil + reason := "cloud lookup failed: " + err.Error() + if openstack.IsRetryableRequestError(err) { + return nil, nil, reason, err + } + return nil, nil, reason, nil } v, reason := o.pickDiagnosticValidator(ctx, it.ValidatorID) @@ -142,8 +154,13 @@ func (o *Orchestrator) pickDiagnosticValidator(ctx context.Context, id string) ( // 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 { + start := time.Now() holds, err := o.DB.ListDiagnosticHolds(ctx) + defer func() { + o.Log.Info("diagnostic detach request", "items", len(addresses), "duration_ms", time.Since(start).Milliseconds()) + }() if err != nil { + o.Log.Error("list holds for diagnostic detach", "err", err) return []DiagnosticResult{rejected("", "internal error: "+err.Error())} } byAddr := make(map[string]db.DiagnosticHold, len(holds)) @@ -158,32 +175,53 @@ func (o *Orchestrator) DiagnosticDetach(ctx context.Context, addresses []string, h, ok := byAddr[addr] if !ok { out = append(out, rejected(addr, "address is not on diagnostic")) + o.Log.Warn("diagnostic detach rejected", "ip", addr, "reason", "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}) + out = append(out, o.diagnosticDetachOne(ctx, h)) } return out } +func (o *Orchestrator) diagnosticDetachOne(ctx context.Context, hold db.DiagnosticHold) DiagnosticResult { + fipID := hold.FIPID + if fipID == "" { + return rejected(hold.Address, "diagnostic hold has no recorded floating ip UUID") + } + fip, err := o.readFloatingIP(ctx, "", hold.Address, fipID) + if err != nil && !openstack.IsNotFound(err) { + return rejected(hold.Address, "cloud lookup failed: "+err.Error()) + } + if err == nil && fip.PortID != "" { + expectedPort := hold.PortID + if expectedPort == "" { + validator, err := o.DB.GetValidator(ctx, hold.ValidatorID) + if err != nil { + return rejected(hold.Address, "cannot verify the diagnostic validator port: "+err.Error()) + } + expectedPort = validator.OSPortID + } + if fip.PortID != expectedPort { + return rejected(hold.Address, "floating ip is attached to another port") + } + start := time.Now() + err := o.OS.DisassociateFloatingIP(ctx, fipID) + o.logDiagnosticStage("", hold.Address, "disassociate", start, err) + if err != nil && !openstack.IsNotFound(err) { + return rejected(hold.Address, "disassociate floating ip: "+err.Error()) + } + } + start := time.Now() + _, err = o.DB.ReleaseDiagnostic(ctx, hold.Address) + o.logDiagnosticStage("", hold.Address, "detach_release", start, err) + if err != nil { + return rejected(hold.Address, "release: "+err.Error()) + } + o.diagnosticEvent(ctx, "diagnostic_detached", hold.Address, hold.ValidatorID, fipID, hold.Note) + o.Log.Info("diagnostic hold detached", "ip", hold.Address, "validator", hold.ValidatorID) + return DiagnosticResult{Address: hold.Address, Status: DiagDetached, ValidatorID: hold.ValidatorID, FIPID: fipID} +} + // DiagnosticList returns the current holds. func (o *Orchestrator) DiagnosticList(ctx context.Context) ([]db.DiagnosticHold, error) { return o.DB.ListDiagnosticHolds(ctx) diff --git a/internal/orchestrator/diagnostic_operations.go b/internal/orchestrator/diagnostic_operations.go index 6dc1ff7..cd90d58 100644 --- a/internal/orchestrator/diagnostic_operations.go +++ b/internal/orchestrator/diagnostic_operations.go @@ -42,13 +42,6 @@ func (o *Orchestrator) RunDiagnosticOperations(ctx context.Context) { } } -func (o *Orchestrator) lookupDiagnosticFIP(ctx context.Context, operationID, address string) (*openstack.FloatingIP, error) { - start := time.Now() - fip, err := o.OS.GetFloatingIPByAddress(ctx, address) - o.logDiagnosticStage(operationID, address, "lookup", start, err) - return fip, err -} - func (o *Orchestrator) logDiagnosticStage(operationID, address, stage string, start time.Time, err error) { o.Log.Info("diagnostic stage", "operation_id", operationID, "ip", address, "stage", stage, "duration_ms", time.Since(start).Milliseconds(), "err", err) } @@ -60,10 +53,13 @@ func (o *Orchestrator) applyDiagnosticOperationItem(ctx context.Context, item db Address: item.Address, ValidatorID: item.RequestedValidator, }, item.OperationID) if err != nil { + if openstack.IsRetryableRequestError(err) { + return o.retryDiagnosticVerification(ctx, item) + } return err } if reason != "" { - return o.DB.FinishDiagnosticOperationItem(ctx, item, reason, nil) + return o.finishDiagnosticOperationItem(ctx, item, reason, nil) } reserved := item reserved.ValidatorID, reserved.PortID, reserved.FIPID = validator.ValidatorID, validator.OSPortID, found.ID @@ -71,7 +67,7 @@ func (o *Orchestrator) applyDiagnosticOperationItem(ctx context.Context, item db err = o.DB.ReserveDiagnosticOperationItem(ctx, reserved) o.logDiagnosticStage(item.OperationID, item.Address, "reserve", start, err) if errors.Is(err, db.ErrBusy) || errors.Is(err, db.ErrConflict) || errors.Is(err, db.ErrNotFound) { - return o.DB.FinishDiagnosticOperationItem(ctx, item, err.Error(), nil) + return o.finishDiagnosticOperationItem(ctx, item, err.Error(), nil) } if err != nil { return err @@ -79,18 +75,18 @@ func (o *Orchestrator) applyDiagnosticOperationItem(ctx context.Context, item db item, fip = reserved, found } else { // A previous process could have exited after Neutron applied the PUT. - found, err := o.lookupDiagnosticFIP(ctx, item.OperationID, item.Address) + found, err := o.readFloatingIP(ctx, item.OperationID, item.Address, item.FIPID) if err != nil { if openstack.IsNotFound(err) { - return o.DB.FinishDiagnosticOperationItem(ctx, item, "floating ip no longer exists", nil) + return o.finishDiagnosticOperationItem(ctx, item, "floating ip no longer matches the reservation", nil) } return o.retryDiagnosticVerification(ctx, item) } fip = found } - if fip.ID != item.FIPID || (fip.PortID != "" && fip.PortID != item.PortID) { - return o.DB.FinishDiagnosticOperationItem(ctx, item, "floating ip changed or is attached to another port", nil) + if fip.PortID != "" && fip.PortID != item.PortID { + return o.finishDiagnosticOperationItem(ctx, item, "floating ip is attached to another port", nil) } if fip.PortID != item.PortID { start := time.Now() @@ -100,15 +96,15 @@ func (o *Orchestrator) applyDiagnosticOperationItem(ctx context.Context, item db if ctx.Err() != nil { return ctx.Err() } - found, lookupErr := o.lookupDiagnosticFIP(ctx, item.OperationID, item.Address) + found, lookupErr := o.readFloatingIP(ctx, item.OperationID, item.Address, item.FIPID) if lookupErr != nil && !openstack.IsNotFound(lookupErr) { return o.retryDiagnosticVerification(ctx, item) } - if lookupErr == nil && found.ID == item.FIPID && found.PortID == "" && openstack.IsRetryableRequestError(err) { + if lookupErr == nil && found.PortID == "" && openstack.IsRetryableRequestError(err) { return o.retryDiagnosticVerification(ctx, item) } - if lookupErr != nil || found.ID != item.FIPID || found.PortID != item.PortID { - return o.DB.FinishDiagnosticOperationItem(ctx, item, "associate floating ip: "+err.Error(), nil) + if lookupErr != nil || found.PortID != item.PortID { + return o.finishDiagnosticOperationItem(ctx, item, "associate floating ip: "+err.Error(), nil) } } } @@ -117,13 +113,22 @@ func (o *Orchestrator) applyDiagnosticOperationItem(ctx context.Context, item db SourceType: "control-api", SourceID: item.ValidatorID, EventType: "diagnostic_attached", Payload: diagnosticPayload(item.Address, item.ValidatorID, item.FIPID, item.Note), OccurredAt: db.Now(), } - if err := o.DB.FinishDiagnosticOperationItem(ctx, item, "", &event); err != nil { + if err := o.finishDiagnosticOperationItem(ctx, item, "", &event); err != nil { return err } o.Log.Info("diagnostic hold attached", "operation_id", item.OperationID, "ip", item.Address, "validator", item.ValidatorID) return nil } +func (o *Orchestrator) finishDiagnosticOperationItem(ctx context.Context, item db.DiagnosticOperationItem, reason string, event *db.Event) error { + if err := o.DB.FinishDiagnosticOperationItem(ctx, item, reason, event); err != nil { + return err + } + o.Log.Info("diagnostic attach result", "operation_id", item.OperationID, "ip", item.Address, + "duration_ms", time.Since(item.CreatedAt).Milliseconds(), "reason", reason) + return nil +} + func (o *Orchestrator) retryDiagnosticVerification(ctx context.Context, item db.DiagnosticOperationItem) error { return o.DB.RetryDiagnosticOperationItem(ctx, item.ID, "Проверяем состояние привязки в OpenStack", 2*time.Second) } diff --git a/internal/orchestrator/diagnostic_operations_test.go b/internal/orchestrator/diagnostic_operations_test.go index 3337e2b..7ab78e3 100644 --- a/internal/orchestrator/diagnostic_operations_test.go +++ b/internal/orchestrator/diagnostic_operations_test.go @@ -42,16 +42,22 @@ func TestDiagnosticOperationPartialSuccess(t *testing.T) { type diagnosticLostResponse struct { *openstack.MockClient - lookups int + addressReads int + uuidReads int associations int } func (c *diagnosticLostResponse) GetFloatingIPByAddress(ctx context.Context, addr string) (*openstack.FloatingIP, error) { - c.lookups++ - if c.lookups == 2 { + c.addressReads++ + return c.MockClient.GetFloatingIPByAddress(ctx, addr) +} + +func (c *diagnosticLostResponse) GetFloatingIP(ctx context.Context, id string) (*openstack.FloatingIP, error) { + c.uuidReads++ + if c.uuidReads == 1 { return nil, errors.New("Neutron temporarily unreachable") } - return c.MockClient.GetFloatingIPByAddress(ctx, addr) + return c.MockClient.GetFloatingIP(ctx, id) } func (c *diagnosticLostResponse) AssociateFloatingIP(ctx context.Context, fipID, portID string) error { @@ -103,8 +109,10 @@ func TestDiagnosticOperationRecoversAppliedReservationAfterRestart(t *testing.T) t.Fatal(err) } op, err = d.GetDiagnosticOperation(ctx, id) - if err != nil || len(op.Items) != 1 || op.Items[0].Status != DiagAttached || cloud.associations != 1 { - t.Fatalf("operation was %+v, PUT count=%d, err=%v", op, cloud.associations, err) + if err != nil || len(op.Items) != 1 || op.Items[0].Status != DiagAttached || + cloud.associations != 1 || cloud.addressReads != 1 || cloud.uuidReads != 2 { + t.Fatalf("operation was %+v, PUT count=%d, address reads=%d, UUID reads=%d, err=%v", + op, cloud.associations, cloud.addressReads, cloud.uuidReads, err) } events, err := d.ListRecentEvents(ctx, 10) if err != nil || len(events) != 1 || events[0].EventType != "diagnostic_attached" { diff --git a/internal/orchestrator/diagnostic_test.go b/internal/orchestrator/diagnostic_test.go index 005cacf..ac9d9b8 100644 --- a/internal/orchestrator/diagnostic_test.go +++ b/internal/orchestrator/diagnostic_test.go @@ -189,3 +189,34 @@ func mustParse(t *testing.T, s string) time.Time { } return tm } + +type diagnosticDetachCloud struct { + *openstack.MockClient +} + +func (c diagnosticDetachCloud) GetFloatingIPByAddress(context.Context, string) (*openstack.FloatingIP, error) { + return nil, errors.New("slow address search unavailable") +} + +func TestDiagnosticDetachUsesStoredFloatingIPID(t *testing.T) { + o, d, ctx, mock := diagSetup(t) + if err := d.ClaimDiagnostic(ctx, "validator-1", "1.1.1.1", "fip-a", "trace"); err != nil { + t.Fatal(err) + } + if err := mock.AssociateFloatingIP(ctx, "fip-a", "port-1"); err != nil { + t.Fatal(err) + } + o.OS = diagnosticDetachCloud{MockClient: mock} + + results := o.DiagnosticDetach(ctx, []string{"1.1.1.1"}, false) + if len(results) != 1 || results[0].Status != DiagDetached || results[0].FIPID != "fip-a" { + t.Fatalf("detach: %+v", results) + } + fip, err := mock.GetFloatingIP(ctx, "fip-a") + if err != nil || fip.PortID != "" { + t.Fatalf("floating IP: %+v, %v", fip, err) + } + if state := validatorState(t, d, "validator-1"); state != db.ValidatorIdle { + t.Fatalf("validator: %s", state) + } +} diff --git a/internal/orchestrator/floating_ips.go b/internal/orchestrator/floating_ips.go new file mode 100644 index 0000000..6430f69 --- /dev/null +++ b/internal/orchestrator/floating_ips.go @@ -0,0 +1,64 @@ +package orchestrator + +import ( + "context" + "fmt" + "time" + + "cloudipvalidator/internal/db" + "cloudipvalidator/internal/openstack" +) + +func (o *Orchestrator) matchesFloatingIP(fip *openstack.FloatingIP, address string) bool { + return fip != nil && fip.ID != "" && fip.Address == address && + (o.FIPScope.ProjectID == "" || fip.ProjectID == o.FIPScope.ProjectID) +} + +func (o *Orchestrator) readFloatingIP(ctx context.Context, operationID, address, id string) (*openstack.FloatingIP, error) { + start := time.Now() + fip, err := o.OS.GetFloatingIP(ctx, id) + if err == nil && (!o.matchesFloatingIP(fip, address) || fip.ID != id) { + fip = nil + err = fmt.Errorf("resource %s does not match the expected address and project: %w", id, openstack.ErrNotFound(address)) + } + o.logFloatingIPStage(operationID, address, id, "get_by_uuid", start, err) + return fip, err +} + +// resolveFloatingIP is for new attachments. Existing attachments and +// reservations use readFloatingIP with their own recorded UUID. +func (o *Orchestrator) resolveFloatingIP(ctx context.Context, operationID, address string) (*openstack.FloatingIP, error) { + id, err := o.DB.FloatingIPCandidate(ctx, o.FIPScope, address) + if err != nil { + return nil, fmt.Errorf("read floating ip mapping: %w", err) + } + var fip *openstack.FloatingIP + start := time.Now() + if id != "" { + fip, err = o.readFloatingIP(ctx, operationID, address, id) + if err != nil && !openstack.IsNotFound(err) { + return nil, err + } + } + if fip == nil { + start = time.Now() + fip, err = o.OS.GetFloatingIPByAddress(ctx, address) + if err == nil && !o.matchesFloatingIP(fip, address) { + err = openstack.ErrNotFound(address) + } + o.logFloatingIPStage(operationID, address, "", "find_by_address", start, err) + if err != nil { + return nil, err + } + } + mapping := db.FloatingIPMapping{Address: address, FIPID: fip.ID} + if err := o.DB.ConfirmFloatingIPs(ctx, o.FIPScope, []db.FloatingIPMapping{mapping}, start); err != nil { + return nil, fmt.Errorf("record floating ip mapping: %w", err) + } + return fip, nil +} + +func (o *Orchestrator) logFloatingIPStage(operationID, address, id, stage string, start time.Time, err error) { + o.Log.Info("floating ip stage", "operation_id", operationID, "ip", address, "fip_id", id, + "stage", stage, "duration_ms", time.Since(start).Milliseconds(), "err", err) +} diff --git a/internal/orchestrator/floating_ips_test.go b/internal/orchestrator/floating_ips_test.go new file mode 100644 index 0000000..a19e98a --- /dev/null +++ b/internal/orchestrator/floating_ips_test.go @@ -0,0 +1,209 @@ +package orchestrator + +import ( + "context" + "fmt" + "net/http" + "path/filepath" + "slices" + "testing" + "time" + + "cloudipvalidator/internal/config" + "cloudipvalidator/internal/db" + "cloudipvalidator/internal/openstack" +) + +type floatingIPReadRecorder struct { + *openstack.MockClient + addressReads []string + uuidReads []string + uuidErrors map[string]error +} + +func (c *floatingIPReadRecorder) GetFloatingIPByAddress(ctx context.Context, address string) (*openstack.FloatingIP, error) { + c.addressReads = append(c.addressReads, address) + return c.MockClient.GetFloatingIPByAddress(ctx, address) +} + +func (c *floatingIPReadRecorder) GetFloatingIP(ctx context.Context, id string) (*openstack.FloatingIP, error) { + c.uuidReads = append(c.uuidReads, id) + if err := c.uuidErrors[id]; err != nil { + return nil, err + } + return c.MockClient.GetFloatingIP(ctx, id) +} + +func TestScannedFloatingIPsAreReadByUUID(t *testing.T) { + o, d, ctx, mock := diagSetup(t) + o.FIPScope = db.FloatingIPScope{ProjectID: "svc", Region: "region"} + cloud := &floatingIPReadRecorder{MockClient: mock} + o.OS = cloud + mock.SeedWithPort("fip-occupied", "3.3.3.3", "svc", "port-x") + mock.Seed("fip-other-project", "4.4.4.4", "other") + mock.Seed("fip-ambiguous-a", "5.5.5.5", "svc") + mock.Seed("fip-ambiguous-b", "5.5.5.5", "svc") + if _, _, err := o.ScanFloatingIPs(ctx); err != nil { + t.Fatal(err) + } + for address, want := range map[string]string{"3.3.3.3": "fip-occupied", "4.4.4.4": "", "5.5.5.5": ""} { + if id, err := d.FloatingIPCandidate(ctx, o.FIPScope, address); err != nil || id != want { + t.Fatalf("mapping for %s: %q, err=%v, want %q", address, id, err, want) + } + } + got := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "") + if got[0].FIPID != "fip-a" || got[0].Status != DiagAttached { + t.Fatalf("attach: %+v", got) + } + // The held first address is skipped, so Tick assigns the other scanned + // address to the second validator. + o.Tick(ctx) + item, err := d.GetIPByAddress(ctx, "2.2.2.2") + if err != nil || item.FIPID != "fip-b" || item.State != db.IPAwaitingSelfCheck { + t.Fatalf("assignment: %+v, err=%v", item, err) + } + if len(cloud.addressReads) != 0 || !slices.Equal(cloud.uuidReads, []string{"fip-a", "fip-b"}) { + t.Fatalf("lookups: by address %v, by UUID %v", cloud.addressReads, cloud.uuidReads) + } +} + +func TestManuallyDiscoveredUUIDSurvivesQueueClearAndRestart(t *testing.T) { + ctx := context.Background() + path := filepath.Join(t.TempDir(), "reopen.db") + o, _, mock := newTestOrchestrator(t, 180) + d, err := db.Open(ctx, path) + if err != nil { + t.Fatal(err) + } + defer d.Close() + o.DB = d + o.FIPScope = db.FloatingIPScope{ProjectID: "svc", Region: "region"} + cloud := &floatingIPReadRecorder{MockClient: mock} + o.OS = cloud + const address = "1.1.1.1" + mock.Seed("fip", address, "svc") + if err := d.RegisterValidator(ctx, "validator", "", "port", ""); err != nil { + t.Fatal(err) + } + if err := d.SeedQueue(ctx, []string{address}); err != nil { + t.Fatal(err) + } + items := []DiagnosticItem{{Address: address, ValidatorID: "validator"}} + if got := o.DiagnosticAttach(ctx, items, ""); got[0].Status != DiagAttached { + t.Fatalf("initial attach: %+v", got) + } + if got := o.DiagnosticDetach(ctx, []string{address}, false); got[0].Status != DiagDetached { + t.Fatalf("detach: %+v", got) + } + if _, err := o.ClearQueue(ctx); err != nil { + t.Fatal(err) + } + if err := d.Close(); err != nil { + t.Fatal(err) + } + reopened, err := db.Open(ctx, path) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + restarted := New(reopened, cloud, &config.ControlAPI{}, o.Log) + restarted.FIPScope = o.FIPScope + if got := restarted.DiagnosticAttach(ctx, items, ""); got[0].Status != DiagAttached { + t.Fatalf("attach after restart: %+v", got) + } + if !slices.Equal(cloud.addressReads, []string{address}) || !slices.Equal(cloud.uuidReads, []string{"fip", "fip"}) { + t.Fatalf("lookups: by address %v, by UUID %v", cloud.addressReads, cloud.uuidReads) + } +} + +type neutronStatus int + +func (e neutronStatus) GetStatusCode() int { return int(e) } +func (e neutronStatus) Error() string { return fmt.Sprintf("Neutron returned HTTP %d", e) } + +func TestFloatingIPStaleMappingAndTransientErrors(t *testing.T) { + for _, tc := range []struct { + name string + address string + project string + deleted bool + }{ + {name: "404", deleted: true}, + {name: "wrong_address", address: "3.3.3.3", project: "svc"}, + {name: "wrong_project", address: "1.1.1.1", project: "other"}, + } { + t.Run(tc.name, func(t *testing.T) { + o, d, ctx, mock := diagSetup(t) + o.FIPScope = db.FloatingIPScope{ProjectID: "svc", Region: "region"} + address := "1.1.1.1" + if !tc.deleted { + mock.Seed("old-fip", tc.address, tc.project) + } + mock.Seed("new-fip", address, "svc") + cloud := &floatingIPReadRecorder{ + MockClient: mock, uuidErrors: map[string]error{"old-fip": neutronStatus(http.StatusServiceUnavailable)}, + } + o.OS = cloud + if err := d.ConfirmFloatingIPs(ctx, o.FIPScope, []db.FloatingIPMapping{{Address: address, FIPID: "old-fip"}}, time.Now()); err != nil { + t.Fatal(err) + } + items := []DiagnosticItem{{Address: address, ValidatorID: "validator-1"}} + if got := o.DiagnosticAttach(ctx, items, ""); got[0].Status != DiagRejected { + t.Fatalf("attach during outage: %+v", got) + } + if got, err := d.FloatingIPCandidate(ctx, o.FIPScope, address); err != nil || got != "old-fip" || len(cloud.addressReads) != 0 { + t.Fatalf("candidate after 503=%q, err=%v, by-address lookups=%v", got, err, cloud.addressReads) + } + delete(cloud.uuidErrors, "old-fip") + if got := o.DiagnosticAttach(ctx, items, ""); got[0].Status != DiagAttached || got[0].FIPID != "new-fip" { + t.Fatalf("attach after stale UUID: %+v", got) + } + if got, err := d.FloatingIPCandidate(ctx, o.FIPScope, address); err != nil || got != "new-fip" || + !slices.Equal(cloud.addressReads, []string{address}) || !slices.Equal(cloud.uuidReads, []string{"old-fip", "old-fip"}) { + t.Fatalf("candidate after refresh=%q, err=%v, by address=%v, by UUID=%v", + got, err, cloud.addressReads, cloud.uuidReads) + } + }) + } +} + +func TestDiagnosticDetachDoesNotChangeReplacementOrAnotherPort(t *testing.T) { + o, d, ctx, mock := diagSetup(t) + const address = "1.1.1.1" + cloud := &floatingIPReadRecorder{MockClient: mock, uuidErrors: make(map[string]error)} + o.OS = cloud + if got := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: address, ValidatorID: "validator-1"}}, ""); got[0].Status != DiagAttached { + t.Fatalf("attach: %+v", got) + } + if err := mock.AssociateFloatingIP(ctx, "fip-a", "other-port"); err != nil { + t.Fatal(err) + } + if got := o.DiagnosticDetach(ctx, []string{address}, false); got[0].Status != DiagRejected { + t.Fatalf("detach moved FIP: %+v", got) + } + cloud.uuidErrors["fip-a"] = neutronStatus(http.StatusServiceUnavailable) + if got := o.DiagnosticDetach(ctx, []string{address}, false); got[0].Status != DiagRejected { + t.Fatalf("detach during outage: %+v", got) + } + if state := validatorState(t, d, "validator-1"); state != db.ValidatorDiagnostic { + t.Fatalf("validator state after unsuccessful detach: %s", state) + } + mock.SeedWithPort("replacement", address, "svc", "replacement-port") + cloud.uuidErrors["fip-a"] = openstack.ErrNotFound("fip-a") + if err := d.ConfirmFloatingIPs(ctx, o.FIPScope, []db.FloatingIPMapping{{Address: address, FIPID: "replacement"}}, time.Now()); err != nil { + t.Fatal(err) + } + if got := o.DiagnosticDetach(ctx, []string{address}, false); got[0].Status != DiagDetached || got[0].FIPID != "fip-a" { + t.Fatalf("detach removed FIP: %+v", got) + } + fip, err := mock.GetFloatingIP(ctx, "replacement") + if err != nil || fip.PortID != "replacement-port" { + t.Fatalf("replacement FIP changed: %+v, %v", fip, err) + } + if state := validatorState(t, d, "validator-1"); state != db.ValidatorIdle { + t.Fatalf("validator state after removed FIP: %s", state) + } + if !slices.Equal(cloud.addressReads, []string{address}) || !slices.Equal(cloud.uuidReads, []string{"fip-a", "fip-a", "fip-a"}) { + t.Fatalf("lookups: by address %v, by UUID %v", cloud.addressReads, cloud.uuidReads) + } +} diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go index 4a52af8..f7f37ed 100644 --- a/internal/orchestrator/orchestrator.go +++ b/internal/orchestrator/orchestrator.go @@ -49,6 +49,7 @@ type Orchestrator struct { // ScanPageSize is the Neutron page size used by the floating-IP scan // (config openstack.list_page_size); 0 means openstack.DefaultListPageSize. ScanPageSize int + FIPScope db.FloatingIPScope // scan is the background floating-IP scan job (see scanjob.go); its zero // value is ready to use. @@ -99,7 +100,7 @@ func (o *Orchestrator) spawn(key string, fn func()) { // .IPAddresses are only consulted once, at process startup, by // db.BootstrapFromConfig. func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI, log *slog.Logger) *Orchestrator { - return &Orchestrator{ + o := &Orchestrator{ DB: d, OS: osClient, Cfg: cfg.Orchestrator, @@ -110,6 +111,10 @@ func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI, diagnosticWake: make(chan struct{}, 1), hb: heartbeatState{startedAt: time.Now()}, } + if client, ok := osClient.(*openstack.Client); ok { + o.FIPScope.ProjectID, o.FIPScope.Region = client.FloatingIPScope() + } + return o } func (o *Orchestrator) leaseTTL() time.Duration { @@ -178,8 +183,19 @@ func (o *Orchestrator) assignIdleValidators(ctx context.Context) error { return nil } -func (o *Orchestrator) associateFIP(ctx context.Context, validatorID, osPortID string, item *db.IPQueueItem) error { - fip, err := o.OS.GetFloatingIPByAddress(ctx, item.IPAddress) +func (o *Orchestrator) associateFIP(ctx context.Context, validatorID, osPortID string, item *db.IPQueueItem) (resultErr error) { + start := time.Now() + defer func() { + o.Log.Info("floating ip assignment", "ip", item.IPAddress, "validator", validatorID, + "duration_ms", time.Since(start).Milliseconds(), "err", resultErr) + }() + var fip *openstack.FloatingIP + var err error + if item.FIPID == "" { + fip, err = o.resolveFloatingIP(ctx, "", item.IPAddress) + } else { + fip, err = o.readFloatingIP(ctx, "", item.IPAddress, item.FIPID) + } if err != nil { o.requeueOrFail(ctx, item.ID, validatorID, fmt.Sprintf("lookup floating ip: %v", err)) return err @@ -205,9 +221,14 @@ func (o *Orchestrator) associateFIP(ctx context.Context, validatorID, osPortID s "ip", item.IPAddress, "fip_port_id", fip.PortID) return nil } - if err := o.OS.AssociateFloatingIP(ctx, fip.ID, osPortID); err != nil { - o.requeueOrFail(ctx, item.ID, validatorID, fmt.Sprintf("associate floating ip: %v", err)) - return err + if fip.PortID == "" { + start := time.Now() + err := o.OS.AssociateFloatingIP(ctx, fip.ID, osPortID) + o.logFloatingIPStage("", item.IPAddress, fip.ID, "associate", start, err) + if err != nil { + o.requeueOrFail(ctx, item.ID, validatorID, fmt.Sprintf("associate floating ip: %v", err)) + return err + } } if err := o.DB.SetFIPAssociated(ctx, item.ID, fip.ID, o.leaseTTL()); err != nil { if errors.Is(err, db.ErrInvalidState) { @@ -432,7 +453,11 @@ func (o *Orchestrator) MarkSiteComplete(ctx context.Context, ipID int64, siteInd // about an attachment that is still being created (state assigning_fip has no // fip_id yet) or that was lost earlier. Floating IPs this system never // queued are left alone. Ports are processed in parallel. -func (o *Orchestrator) releaseValidatorPorts(ctx context.Context, validators []db.Validator) { +func (o *Orchestrator) releaseValidatorPorts(ctx context.Context, validators []db.Validator, refs ...db.FIPRef) { + pinned := make(map[string]string, len(refs)) + for _, ref := range refs { + pinned[ref.IPAddress] = ref.FIPID + } var wg sync.WaitGroup for _, v := range validators { if v.OSPortID == "" || v.State == db.ValidatorDiagnostic { @@ -456,6 +481,12 @@ func (o *Orchestrator) releaseValidatorPorts(ctx context.Context, validators []d return } for _, f := range fips { + if f.PortID != v.OSPortID || !o.matchesFloatingIP(&f, f.Address) { + continue + } + if id := pinned[f.Address]; id != "" && id != f.ID { + continue + } if !known[f.Address] { o.Log.Warn("floating ip on validator port was not queued by this system, left attached", "validator", v.ValidatorID, "ip", f.Address) @@ -538,7 +569,8 @@ func (o *Orchestrator) ForceCancel(ctx context.Context, ipAddress string) error if err := o.DB.FreeValidator(ctx, *item.OwnerValidatorID, item.ID); err != nil { return fmt.Errorf("free validator: %w", err) } - o.releaseValidatorPorts(ctx, o.validatorsByID(ctx, *item.OwnerValidatorID)) + ref := db.FIPRef{IPAddress: item.IPAddress, FIPID: item.FIPID} + o.releaseValidatorPorts(ctx, o.validatorsByID(ctx, *item.OwnerValidatorID), ref) } o.event(ctx, "control-api", "", &item.ID, "force_cancel", "") @@ -574,7 +606,8 @@ func (o *Orchestrator) DeleteIP(ctx context.Context, ipAddress string) error { if err := o.DB.DeleteIP(ctx, item.ID); err != nil { return err } - o.releaseValidatorPorts(ctx, owners) + ref := db.FIPRef{IPAddress: item.IPAddress, FIPID: item.FIPID} + o.releaseValidatorPorts(ctx, owners, ref) o.event(ctx, "control-api", "", nil, "ip_deleted", fmt.Sprintf(`{"ip_address":%q}`, ipAddress)) return nil @@ -598,7 +631,7 @@ func (o *Orchestrator) DeleteIPs(ctx context.Context, addresses []string) (db.De if err != nil { return result, err } - o.releaseValidatorPorts(ctx, owners) + o.releaseValidatorPorts(ctx, owners, refs...) o.event(ctx, "control-api", "", nil, "ips_deleted", deletedAddressesPayload(result.Deleted)) return result, nil } @@ -650,7 +683,7 @@ func (o *Orchestrator) ClearQueue(ctx context.Context) (db.DeleteIPsResult, erro if validators, err := o.DB.ListValidators(ctx); err != nil { o.Log.Error("list validators to release ports", "err", err) } else { - o.releaseValidatorPorts(ctx, validators) + o.releaseValidatorPorts(ctx, validators, refs...) } o.event(ctx, "control-api", "", nil, "queue_cleared", deletedAddressesPayload(deleted)) return db.DeleteIPsResult{Deleted: deleted}, nil diff --git a/internal/orchestrator/scanjob.go b/internal/orchestrator/scanjob.go index fe794b9..3a6420a 100644 --- a/internal/orchestrator/scanjob.go +++ b/internal/orchestrator/scanjob.go @@ -49,8 +49,7 @@ type ScanOptions struct { // ClearFirst clears the whole queue before scanning (auto-cycle step 1). // Ignored together with DryRun: a dry run never touches the queue. ClearFirst bool - // DryRun only discovers and counts the free floating IPs; the queue is - // left untouched. + // DryRun only discovers and counts the free floating IPs. DryRun bool } @@ -232,7 +231,7 @@ func (o *Orchestrator) runScan(ctx context.Context, run *scanRun, opts ScanOptio } // doScan is the scan algorithm: optional clear -> read every page into memory -// -> sort -> (unless dry run) enqueue in chunks -> one fip_scan event. +// -> sort -> (unless dry run) save mappings and enqueue in chunks -> one fip_scan event. func (o *Orchestrator) doScan(ctx context.Context, opts ScanOptions) (scanResult, error) { j := &o.scan var res scanResult @@ -247,11 +246,27 @@ func (o *Orchestrator) doScan(ctx context.Context, opts ScanOptions) (scanResult // Read everything first: a read error after retries must leave the queue // untouched, so nothing is enqueued until discovery is complete. var free []string + var observed map[string]string + if !opts.DryRun { + observed = make(map[string]string) + } seen := map[string]struct{}{} + start := time.Now() pages, err := o.OS.ListFreeFloatingIPs(ctx, o.ScanPageSize, func(page []openstack.FloatingIP) error { nFree := 0 for _, f := range page { - if f.PortID != "" || f.Address == "" { + if f.Address == "" || !o.matchesFloatingIP(&f, f.Address) { + continue + } + if !opts.DryRun { + if id, exists := observed[f.Address]; !exists { + observed[f.Address] = f.ID + } else if id != f.ID { + // A later listing by address could not choose one either. + observed[f.Address] = "" + } + } + if f.PortID != "" { continue } if _, dup := seen[f.Address]; dup { @@ -275,6 +290,19 @@ func (o *Orchestrator) doScan(ctx context.Context, opts ScanOptions) (scanResult res.free = len(free) sortAddressesAscending(free) + var mappings []db.FloatingIPMapping + for address, id := range observed { + if id != "" { + mappings = append(mappings, db.FloatingIPMapping{Address: address, FIPID: id}) + } + } + for off := 0; off < len(mappings); off += scanChunkSize { + chunk := mappings[off:min(off+scanChunkSize, len(mappings))] + if err := o.DB.ConfirmFloatingIPs(ctx, o.FIPScope, chunk, start); err != nil { + return res, fmt.Errorf("save scanned floating ips: %w", err) + } + } + if !opts.DryRun && len(free) > 0 { j.update(func(s *ScanStatus) { s.State = ScanEnqueuing }) for off := 0; off < len(free); off += scanChunkSize { diff --git a/internal/orchestrator/scanjob_test.go b/internal/orchestrator/scanjob_test.go index 040a35f..4e6ffaf 100644 --- a/internal/orchestrator/scanjob_test.go +++ b/internal/orchestrator/scanjob_test.go @@ -131,6 +131,10 @@ func TestScanJobDryRunLeavesQueueUntouched(t *testing.T) { if countEvents(t, d, "fip_scan") != 0 || countEvents(t, d, "queue_cleared") != 0 { t.Fatalf("dry run must not emit scan/clear events") } + var mappings int + if err := d.QueryRowContext(ctx, `SELECT COUNT(*) FROM floating_ip_mappings`).Scan(&mappings); err != nil || mappings != 0 { + t.Fatalf("dry run stored %d floating ip mappings, err=%v", mappings, err) + } } func TestScanJobReadErrorLeavesQueueUntouched(t *testing.T) {