Persist Floating IP UUIDs for direct Neutron operations

This commit is contained in:
ayurishchev committed 2026-11-22 21:26:19 +03:00
1 parent 89ac4d5bcd
commit 94124747ce
24 files changed
+918 -116

No files matched your search

+2 -2
View File
@@ -1,4 +1,4 @@
891ec11d493f031e5c06d66dff45c31cfb9ce440e684d5c17617b744ffbb2126 control-api 69a60a3ba48e83640b6d8b122401e7204cfaac6c5d60976e19904c81eb37f838 control-api
ec6959ae151d8ad1ad5b68faca420159ca6ca6b3dd1359b7f9b0d8489ac0a27b validator-agent ec6959ae151d8ad1ad5b68faca420159ca6ca6b3dd1359b7f9b0d8489ac0a27b validator-agent
7ef8785769d946d81c338f53928bbe18f243ec5b96ab8b874846504b8ac4e98c prober 7ef8785769d946d81c338f53928bbe18f243ec5b96ab8b874846504b8ac4e98c prober
76059951436e37f5fc8f87a882f6fa6f7c362ed5718722495dc0caf6a7b781de admin-dashboard dd3fcccf595608f477726d4818abe4e4fb9c7212ab6df73c68fdc346222ab047 admin-dashboard
Binary file not shown.
BIN
View File
Binary file not shown.
+3
View File
@@ -59,6 +59,9 @@ func run(configPath string, log *slog.Logger) error {
} }
orch := orchestrator.New(database, osClient, cfg, log) 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 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 // 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. // as long as the HTTP request or loop iteration that started them.
@@ -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 и время привязки и отвязки от запроса до результата.
@@ -100,10 +100,12 @@
hx-swap="outerHTML"> hx-swap="outerHTML">
<h2 class="section-title">Удерживаемые адреса</h2> <h2 class="section-title">Удерживаемые адреса</h2>
{{if .Rows}} {{if .Rows}}
<form id="diag-list" hx-post="/diagnostics/detach" hx-target="#diagnostics-action-result" hx-swap="innerHTML" hx-confirm="Отвязать выбранные адреса?"> <form id="diag-list" hx-post="/diagnostics/detach" hx-target="#diagnostics-action-result" hx-swap="innerHTML"
hx-confirm="Отвязать выбранные адреса?" hx-indicator="#diagnostics-detaching" hx-disabled-elt="#diag-list button">
<div class="actions" style="margin-bottom:8px"> <div class="actions" style="margin-bottom:8px">
<button type="submit" class="btn btn-ghost btn-sm">Отвязать выбранные</button> <button type="submit" class="btn btn-ghost btn-sm">Отвязать выбранные</button>
<button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/diagnostics/detach" hx-vals='{"all":"1"}' hx-target="#diagnostics-action-result" hx-swap="innerHTML" hx-confirm="Отвязать все адреса ({{len .Rows}})?">Отвязать все</button> <button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/diagnostics/detach" hx-vals='{"all":"1"}' hx-target="#diagnostics-action-result" hx-swap="innerHTML" hx-confirm="Отвязать все адреса ({{len .Rows}})?">Отвязать все</button>
<span id="diagnostics-detaching" class="htmx-indicator" role="status">Отвязываем…</span>
</div> </div>
<div class="panel"> <div class="panel">
<div class="table-scroll"> <div class="table-scroll">
+4
View File
@@ -62,6 +62,9 @@ var inboundTLSChecksSchema string
//go:embed migrations/0016_diagnostic_operations.sql //go:embed migrations/0016_diagnostic_operations.sql
var diagnosticOperationsSchema string 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 // 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 // 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 // PRAGMA user_version — so a fresh database walks the whole list and an
@@ -86,6 +89,7 @@ var migrations = []struct {
{14, diagnosticHoldsSchema}, {14, diagnosticHoldsSchema},
{15, inboundTLSChecksSchema}, {15, inboundTLSChecksSchema},
{16, diagnosticOperationsSchema}, {16, diagnosticOperationsSchema},
{17, floatingIPsSchema},
} }
// connPragmas are applied to every new connection. A larger WAL checkpoint // 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 -11
View File
@@ -12,6 +12,7 @@ type DiagnosticHold struct {
Address string `json:"address"` Address string `json:"address"`
ValidatorID string `json:"validator_id"` ValidatorID string `json:"validator_id"`
FIPID string `json:"fip_id"` FIPID string `json:"fip_id"`
PortID string `json:"-"`
Note string `json:"note"` Note string `json:"note"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
} }
@@ -20,10 +21,14 @@ type DiagnosticHold struct {
// the hold, in one transaction. ErrNotFound: no such validator; ErrBusy: the // the hold, in one transaction. ErrNotFound: no such validator; ErrBusy: the
// validator is not idle; ErrConflict: the address or validator is already held. // 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 { 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) tx, err := d.BeginTx(ctx, nil)
if err != nil { if err != nil {
return err return err
@@ -49,10 +54,6 @@ func (d *DB) claimDiagnostic(ctx context.Context, validatorID, address, fipID, n
if held { if held {
return fmt.Errorf("address %q or validator %q is already held: %w", address, validatorID, ErrConflict) 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, ` res, err := tx.ExecContext(ctx, `
UPDATE validators SET state=?, updated_at=? UPDATE validators SET state=?, updated_at=?
WHERE validator_id=? AND state=? AND current_ip_id IS NULL AND (?='' OR os_port_id=?) 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, ` if _, err := tx.ExecContext(ctx, `
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at, pending_item_id) INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at, pending_item_id, port_id)
VALUES (?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, (SELECT os_port_id FROM validators WHERE validator_id=?))
`, address, validatorID, fipID, note, now, pendingID); err != nil { `, address, validatorID, fipID, note, now, pendingID, validatorID); err != nil {
return err return err
} }
return tx.Commit() return tx.Commit()
@@ -120,7 +121,7 @@ func resetDiagnosticValidator(ctx context.Context, tx *sql.Tx, validatorID strin
return err 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) { func (d *DB) HasDiagnosticHold(ctx context.Context, address string) (bool, error) {
var exists bool var exists bool
@@ -131,7 +132,7 @@ func (d *DB) HasDiagnosticHold(ctx context.Context, address string) (bool, error
func scanHold(row rowScanner) (*DiagnosticHold, error) { func scanHold(row rowScanner) (*DiagnosticHold, error) {
var h DiagnosticHold var h DiagnosticHold
var created string 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 return nil, err
} }
var err error var err error
+19 -13
View File
@@ -12,16 +12,17 @@ type DiagnosticOperation struct {
} }
type DiagnosticOperationItem struct { type DiagnosticOperationItem struct {
ID int64 `json:"-"` ID int64 `json:"-"`
OperationID string `json:"-"` OperationID string `json:"-"`
Note string `json:"-"` Note string `json:"-"`
Address string `json:"address"` CreatedAt time.Time `json:"-"`
RequestedValidator string `json:"-"` Address string `json:"address"`
Status string `json:"status"` RequestedValidator string `json:"-"`
ValidatorID string `json:"validator_id,omitempty"` Status string `json:"status"`
PortID string `json:"-"` ValidatorID string `json:"validator_id,omitempty"`
FIPID string `json:"fip_id,omitempty"` PortID string `json:"-"`
Reason string `json:"reason,omitempty"` 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 { 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. // A retrying item blocks only the later addresses in its own operation.
func (d *DB) NextDiagnosticOperationItem(ctx context.Context) (DiagnosticOperationItem, error) { func (d *DB) NextDiagnosticOperationItem(ctx context.Context) (DiagnosticOperationItem, error) {
var item DiagnosticOperationItem var item DiagnosticOperationItem
var createdAt string
err := d.QueryRowContext(ctx, ` err := d.QueryRowContext(ctx, `
UPDATE diagnostic_operation_items SET status='running' UPDATE diagnostic_operation_items SET status='running'
WHERE id=( WHERE id=(
@@ -104,14 +106,18 @@ func (d *DB) NextDiagnosticOperationItem(ctx context.Context) (DiagnosticOperati
ORDER BY i.id LIMIT 1 ORDER BY i.id LIMIT 1
) )
RETURNING id, operation_id, address, requested_validator, validator_id, port_id, fip_id, 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, `, 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 return item, err
} }
func (d *DB) ReserveDiagnosticOperationItem(ctx context.Context, item DiagnosticOperationItem) error { 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 { func (d *DB) RetryDiagnosticOperationItem(ctx context.Context, id int64, reason string, delay time.Duration) error {
+56
View File
@@ -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()
}
+170
View File
@@ -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)
}
}
}
+61 -17
View File
@@ -68,6 +68,8 @@ type ClientConfig struct {
type Client struct { type Client struct {
networking *gophercloud.ServiceClient networking *gophercloud.ServiceClient
retry pageRetry retry pageRetry
projectID string
region string
} }
// buildAuthOptions translates ClientConfig into gophercloud.AuthOptions. It // buildAuthOptions translates ClientConfig into gophercloud.AuthOptions. It
@@ -152,11 +154,25 @@ func NewClient(ctx context.Context, cfg ClientConfig) (*Client, error) {
if retries < 0 { if retries < 0 {
retries = DefaultListPageRetries 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) { 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 { if err != nil {
return nil, fmt.Errorf("openstack: list floating ips: %w", err) 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 { if err != nil {
return nil, fmt.Errorf("openstack: extract floating ips: %w", err) 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) return nil, ErrNotFound(address)
} }
f := list[0] return found, nil
return &FloatingIP{ID: f.ID, Address: f.FloatingIP, PortID: f.PortID, ProjectID: f.TenantID}, 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: // 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. // a proxy that link may point at an internal host.
func (c *Client) fetchPage(ctx context.Context, marker string, limit int) ([]FloatingIP, error) { func (c *Client) fetchPage(ctx context.Context, marker string, limit int) ([]FloatingIP, error) {
opts := pagedListOpts{ opts := pagedListOpts{
ListOpts: floatingips.ListOpts{Limit: limit, Marker: marker}, ListOpts: floatingips.ListOpts{Limit: limit, Marker: marker, ProjectID: c.projectID},
fields: fipListFields, fields: fipListFields,
} }
var out []FloatingIP 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)) out = make([]FloatingIP, 0, len(list))
for _, f := range list { for _, f := range list {
proj := f.TenantID out = append(out, extractFloatingIP(f))
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})
} }
return false, nil // one page per request 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. // ListFloatingIPsByPort asks Neutron for the floating IPs attached to portID.
func (c *Client) ListFloatingIPsByPort(ctx context.Context, portID string) ([]FloatingIP, error) { 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 { if err != nil {
return nil, fmt.Errorf("openstack: list floating ips of port %s: %w", portID, err) 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) return nil, fmt.Errorf("openstack: extract floating ips: %w", err)
} }
out := make([]FloatingIP, 0, len(list)) out := make([]FloatingIP, 0, len(list))
for _, f := range list { for _, raw := range list {
proj := f.TenantID f := extractFloatingIP(raw)
if proj == "" { if f.PortID == portID && (c.projectID == "" || f.ProjectID == c.projectID) {
proj = f.ProjectID out = append(out, f)
} }
out = append(out, FloatingIP{ID: f.ID, Address: f.FloatingIP, PortID: f.PortID, ProjectID: proj})
} }
return out, nil 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{ _, err := floatingips.Update(ctx, c.networking, fipID, floatingips.UpdateOpts{
PortID: &empty, PortID: &empty,
}).Extract() }).Extract()
if gophercloud.ResponseCodeIs(err, 404) {
return ErrNotFound(fipID)
}
if err != nil { if err != nil {
return fmt.Errorf("openstack: disassociate floating ip %s: %w", fipID, err) return fmt.Errorf("openstack: disassociate floating ip %s: %w", fipID, err)
} }
+9 -3
View File
@@ -4,7 +4,10 @@
// mock via config alone. // mock via config alone.
package openstack package openstack
import "context" import (
"context"
"errors"
)
type FloatingIP struct { type FloatingIP struct {
ID string ID string
@@ -24,6 +27,9 @@ type FloatingIPClient interface {
// is registered in the service project. // is registered in the service project.
GetFloatingIPByAddress(ctx context.Context, address string) (*FloatingIP, error) 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 // ListFloatingIPs returns every floating IP registered in the service
// project, both associated and free — filtering to the free pool (empty // project, both associated and free — filtering to the free pool (empty
// PortID) is the caller's job. Used to discover addresses to feed into // PortID) is the caller's job. Used to discover addresses to feed into
@@ -64,8 +70,8 @@ func ErrNotFound(address string) error { return &notFoundError{address} }
// IsNotFound reports whether err indicates the address has no matching // IsNotFound reports whether err indicates the address has no matching
// Neutron floating-ip resource. // Neutron floating-ip resource.
func IsNotFound(err error) bool { func IsNotFound(err error) bool {
_, ok := err.(*notFoundError) var notFound *notFoundError
return ok return errors.As(err, &notFound)
} }
// listAll collects every page of c.ListFreeFloatingIPs into one slice; it is // listAll collects every page of c.ListFreeFloatingIPs into one slice; it is
+11
View File
@@ -81,6 +81,17 @@ func (m *MockClient) GetFloatingIPByAddress(ctx context.Context, address string)
return &f, nil 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 &copy, nil
}
// SeedMany registers n free floating IPs with IDs "<prefix>-00000"… and // SeedMany registers n free floating IPs with IDs "<prefix>-00000"… and
// ascending addresses starting at 198.18.0.1 (TEST-NET benchmarking range), // ascending addresses starting at 198.18.0.1 (TEST-NET benchmarking range),
// returning the addresses in seed order. // returning the addresses in seed order.
+68 -30
View File
@@ -6,6 +6,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"time"
"cloudipvalidator/internal/db" "cloudipvalidator/internal/db"
"cloudipvalidator/internal/openstack" "cloudipvalidator/internal/openstack"
@@ -47,30 +48,37 @@ var activeQueueStates = map[string]bool{
// there until DiagnosticDetach. Partial success is normal: every address gets // there until DiagnosticDetach. Partial success is normal: every address gets
// its own result. // its own result.
func (o *Orchestrator) DiagnosticAttach(ctx context.Context, items []DiagnosticItem, note string) []DiagnosticResult { func (o *Orchestrator) DiagnosticAttach(ctx context.Context, items []DiagnosticItem, note string) []DiagnosticResult {
start := time.Now()
out := make([]DiagnosticResult, 0, len(items)) out := make([]DiagnosticResult, 0, len(items))
for _, it := range items { for _, it := range items {
out = append(out, o.diagnosticAttachOne(ctx, it, note)) 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 return out
} }
func (o *Orchestrator) diagnosticAttachOne(ctx context.Context, it DiagnosticItem, note string) DiagnosticResult { func (o *Orchestrator) diagnosticAttachOne(ctx context.Context, it DiagnosticItem, note string) DiagnosticResult {
addr := it.Address addr := it.Address
v, fip, reason, err := o.prepareDiagnosticAttach(ctx, it, "") v, fip, reason, err := o.prepareDiagnosticAttach(ctx, it, "")
if err != nil {
return rejected(addr, "internal error: "+err.Error())
}
if reason != "" { if reason != "" {
return rejected(addr, 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()) return rejected(addr, "validator "+v.ValidatorID+" cannot be claimed: "+err.Error())
} }
if err := o.OS.AssociateFloatingIP(ctx, fip.ID, v.OSPortID); err != nil { if fip.PortID == "" {
if _, rerr := o.DB.ReleaseDiagnostic(ctx, addr); rerr != nil { start := time.Now()
o.Log.Error("roll back diagnostic hold", "ip", addr, "err", rerr) 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.diagnosticEvent(ctx, "diagnostic_attached", addr, v.ValidatorID, fip.ID, note)
o.Log.Info("diagnostic hold attached", "ip", addr, "validator", v.ValidatorID) 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] { if item, err := o.DB.GetIPByAddress(ctx, addr); err == nil && activeQueueStates[item.State] {
return nil, nil, "address is being checked (" + item.State + ")", nil 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 err != nil {
if openstack.IsNotFound(err) { if openstack.IsNotFound(err) {
return nil, nil, "floating ip not found in the project", nil 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) 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 // 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. // 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 { func (o *Orchestrator) DiagnosticDetach(ctx context.Context, addresses []string, all bool) []DiagnosticResult {
start := time.Now()
holds, err := o.DB.ListDiagnosticHolds(ctx) 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 { if err != nil {
o.Log.Error("list holds for diagnostic detach", "err", err)
return []DiagnosticResult{rejected("", "internal error: "+err.Error())} return []DiagnosticResult{rejected("", "internal error: "+err.Error())}
} }
byAddr := make(map[string]db.DiagnosticHold, len(holds)) 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] h, ok := byAddr[addr]
if !ok { if !ok {
out = append(out, rejected(addr, "address is not on diagnostic")) 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 continue
} }
fipID := h.FIPID out = append(out, o.diagnosticDetachOne(ctx, h))
if fip, err := o.OS.GetFloatingIPByAddress(ctx, addr); err == nil {
fipID = fip.ID
if fip.PortID != "" {
if err := o.OS.DisassociateFloatingIP(ctx, fipID); err != nil {
out = append(out, rejected(addr, "disassociate floating ip: "+err.Error()))
continue
}
}
} else if !openstack.IsNotFound(err) {
out = append(out, rejected(addr, "cloud lookup failed: "+err.Error()))
continue
}
if _, err := o.DB.ReleaseDiagnostic(ctx, addr); err != nil {
out = append(out, rejected(addr, "release: "+err.Error()))
continue
}
o.diagnosticEvent(ctx, "diagnostic_detached", addr, h.ValidatorID, fipID, h.Note)
o.Log.Info("diagnostic hold detached", "ip", addr, "validator", h.ValidatorID)
out = append(out, DiagnosticResult{Address: addr, Status: DiagDetached, ValidatorID: h.ValidatorID, FIPID: fipID})
} }
return out 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. // DiagnosticList returns the current holds.
func (o *Orchestrator) DiagnosticList(ctx context.Context) ([]db.DiagnosticHold, error) { func (o *Orchestrator) DiagnosticList(ctx context.Context) ([]db.DiagnosticHold, error) {
return o.DB.ListDiagnosticHolds(ctx) return o.DB.ListDiagnosticHolds(ctx)
+23 -18
View File
@@ -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) { 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) 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, Address: item.Address, ValidatorID: item.RequestedValidator,
}, item.OperationID) }, item.OperationID)
if err != nil { if err != nil {
if openstack.IsRetryableRequestError(err) {
return o.retryDiagnosticVerification(ctx, item)
}
return err return err
} }
if reason != "" { if reason != "" {
return o.DB.FinishDiagnosticOperationItem(ctx, item, reason, nil) return o.finishDiagnosticOperationItem(ctx, item, reason, nil)
} }
reserved := item reserved := item
reserved.ValidatorID, reserved.PortID, reserved.FIPID = validator.ValidatorID, validator.OSPortID, found.ID 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) err = o.DB.ReserveDiagnosticOperationItem(ctx, reserved)
o.logDiagnosticStage(item.OperationID, item.Address, "reserve", start, err) 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) { 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 { if err != nil {
return err return err
@@ -79,18 +75,18 @@ func (o *Orchestrator) applyDiagnosticOperationItem(ctx context.Context, item db
item, fip = reserved, found item, fip = reserved, found
} else { } else {
// A previous process could have exited after Neutron applied the PUT. // 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 err != nil {
if openstack.IsNotFound(err) { 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) return o.retryDiagnosticVerification(ctx, item)
} }
fip = found fip = found
} }
if fip.ID != item.FIPID || (fip.PortID != "" && fip.PortID != item.PortID) { if fip.PortID != "" && fip.PortID != item.PortID {
return o.DB.FinishDiagnosticOperationItem(ctx, item, "floating ip changed or is attached to another port", nil) return o.finishDiagnosticOperationItem(ctx, item, "floating ip is attached to another port", nil)
} }
if fip.PortID != item.PortID { if fip.PortID != item.PortID {
start := time.Now() start := time.Now()
@@ -100,15 +96,15 @@ func (o *Orchestrator) applyDiagnosticOperationItem(ctx context.Context, item db
if ctx.Err() != nil { if ctx.Err() != nil {
return ctx.Err() 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) { if lookupErr != nil && !openstack.IsNotFound(lookupErr) {
return o.retryDiagnosticVerification(ctx, item) 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) return o.retryDiagnosticVerification(ctx, item)
} }
if lookupErr != nil || found.ID != item.FIPID || found.PortID != item.PortID { if lookupErr != nil || found.PortID != item.PortID {
return o.DB.FinishDiagnosticOperationItem(ctx, item, "associate floating ip: "+err.Error(), nil) 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", SourceType: "control-api", SourceID: item.ValidatorID, EventType: "diagnostic_attached",
Payload: diagnosticPayload(item.Address, item.ValidatorID, item.FIPID, item.Note), OccurredAt: db.Now(), 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 return err
} }
o.Log.Info("diagnostic hold attached", "operation_id", item.OperationID, "ip", item.Address, "validator", item.ValidatorID) o.Log.Info("diagnostic hold attached", "operation_id", item.OperationID, "ip", item.Address, "validator", item.ValidatorID)
return nil 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 { func (o *Orchestrator) retryDiagnosticVerification(ctx context.Context, item db.DiagnosticOperationItem) error {
return o.DB.RetryDiagnosticOperationItem(ctx, item.ID, "Проверяем состояние привязки в OpenStack", 2*time.Second) return o.DB.RetryDiagnosticOperationItem(ctx, item.ID, "Проверяем состояние привязки в OpenStack", 2*time.Second)
} }
@@ -42,16 +42,22 @@ func TestDiagnosticOperationPartialSuccess(t *testing.T) {
type diagnosticLostResponse struct { type diagnosticLostResponse struct {
*openstack.MockClient *openstack.MockClient
lookups int addressReads int
uuidReads int
associations int associations int
} }
func (c *diagnosticLostResponse) GetFloatingIPByAddress(ctx context.Context, addr string) (*openstack.FloatingIP, error) { func (c *diagnosticLostResponse) GetFloatingIPByAddress(ctx context.Context, addr string) (*openstack.FloatingIP, error) {
c.lookups++ c.addressReads++
if c.lookups == 2 { 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 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 { func (c *diagnosticLostResponse) AssociateFloatingIP(ctx context.Context, fipID, portID string) error {
@@ -103,8 +109,10 @@ func TestDiagnosticOperationRecoversAppliedReservationAfterRestart(t *testing.T)
t.Fatal(err) t.Fatal(err)
} }
op, err = d.GetDiagnosticOperation(ctx, id) op, err = d.GetDiagnosticOperation(ctx, id)
if err != nil || len(op.Items) != 1 || op.Items[0].Status != DiagAttached || cloud.associations != 1 { if err != nil || len(op.Items) != 1 || op.Items[0].Status != DiagAttached ||
t.Fatalf("operation was %+v, PUT count=%d, err=%v", op, cloud.associations, err) 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) events, err := d.ListRecentEvents(ctx, 10)
if err != nil || len(events) != 1 || events[0].EventType != "diagnostic_attached" { if err != nil || len(events) != 1 || events[0].EventType != "diagnostic_attached" {
+31
View File
@@ -189,3 +189,34 @@ func mustParse(t *testing.T, s string) time.Time {
} }
return tm 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)
}
}
+64
View File
@@ -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)
}
+209
View File
@@ -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)
}
}
+44 -11
View File
@@ -49,6 +49,7 @@ type Orchestrator struct {
// ScanPageSize is the Neutron page size used by the floating-IP scan // ScanPageSize is the Neutron page size used by the floating-IP scan
// (config openstack.list_page_size); 0 means openstack.DefaultListPageSize. // (config openstack.list_page_size); 0 means openstack.DefaultListPageSize.
ScanPageSize int ScanPageSize int
FIPScope db.FloatingIPScope
// scan is the background floating-IP scan job (see scanjob.go); its zero // scan is the background floating-IP scan job (see scanjob.go); its zero
// value is ready to use. // 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 // .IPAddresses are only consulted once, at process startup, by
// db.BootstrapFromConfig. // db.BootstrapFromConfig.
func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI, log *slog.Logger) *Orchestrator { func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI, log *slog.Logger) *Orchestrator {
return &Orchestrator{ o := &Orchestrator{
DB: d, DB: d,
OS: osClient, OS: osClient,
Cfg: cfg.Orchestrator, Cfg: cfg.Orchestrator,
@@ -110,6 +111,10 @@ func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI,
diagnosticWake: make(chan struct{}, 1), diagnosticWake: make(chan struct{}, 1),
hb: heartbeatState{startedAt: time.Now()}, 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 { func (o *Orchestrator) leaseTTL() time.Duration {
@@ -178,8 +183,19 @@ func (o *Orchestrator) assignIdleValidators(ctx context.Context) error {
return nil return nil
} }
func (o *Orchestrator) associateFIP(ctx context.Context, validatorID, osPortID string, item *db.IPQueueItem) error { func (o *Orchestrator) associateFIP(ctx context.Context, validatorID, osPortID string, item *db.IPQueueItem) (resultErr error) {
fip, err := o.OS.GetFloatingIPByAddress(ctx, item.IPAddress) 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 { if err != nil {
o.requeueOrFail(ctx, item.ID, validatorID, fmt.Sprintf("lookup floating ip: %v", err)) o.requeueOrFail(ctx, item.ID, validatorID, fmt.Sprintf("lookup floating ip: %v", err))
return 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) "ip", item.IPAddress, "fip_port_id", fip.PortID)
return nil return nil
} }
if err := o.OS.AssociateFloatingIP(ctx, fip.ID, osPortID); err != nil { if fip.PortID == "" {
o.requeueOrFail(ctx, item.ID, validatorID, fmt.Sprintf("associate floating ip: %v", err)) start := time.Now()
return err 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 err := o.DB.SetFIPAssociated(ctx, item.ID, fip.ID, o.leaseTTL()); err != nil {
if errors.Is(err, db.ErrInvalidState) { 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 // 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 // fip_id yet) or that was lost earlier. Floating IPs this system never
// queued are left alone. Ports are processed in parallel. // 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 var wg sync.WaitGroup
for _, v := range validators { for _, v := range validators {
if v.OSPortID == "" || v.State == db.ValidatorDiagnostic { if v.OSPortID == "" || v.State == db.ValidatorDiagnostic {
@@ -456,6 +481,12 @@ func (o *Orchestrator) releaseValidatorPorts(ctx context.Context, validators []d
return return
} }
for _, f := range fips { 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] { if !known[f.Address] {
o.Log.Warn("floating ip on validator port was not queued by this system, left attached", o.Log.Warn("floating ip on validator port was not queued by this system, left attached",
"validator", v.ValidatorID, "ip", f.Address) "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 { if err := o.DB.FreeValidator(ctx, *item.OwnerValidatorID, item.ID); err != nil {
return fmt.Errorf("free validator: %w", err) 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", "") 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 { if err := o.DB.DeleteIP(ctx, item.ID); err != nil {
return err 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)) o.event(ctx, "control-api", "", nil, "ip_deleted", fmt.Sprintf(`{"ip_address":%q}`, ipAddress))
return nil return nil
@@ -598,7 +631,7 @@ func (o *Orchestrator) DeleteIPs(ctx context.Context, addresses []string) (db.De
if err != nil { if err != nil {
return result, err return result, err
} }
o.releaseValidatorPorts(ctx, owners) o.releaseValidatorPorts(ctx, owners, refs...)
o.event(ctx, "control-api", "", nil, "ips_deleted", deletedAddressesPayload(result.Deleted)) o.event(ctx, "control-api", "", nil, "ips_deleted", deletedAddressesPayload(result.Deleted))
return result, nil 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 { if validators, err := o.DB.ListValidators(ctx); err != nil {
o.Log.Error("list validators to release ports", "err", err) o.Log.Error("list validators to release ports", "err", err)
} else { } else {
o.releaseValidatorPorts(ctx, validators) o.releaseValidatorPorts(ctx, validators, refs...)
} }
o.event(ctx, "control-api", "", nil, "queue_cleared", deletedAddressesPayload(deleted)) o.event(ctx, "control-api", "", nil, "queue_cleared", deletedAddressesPayload(deleted))
return db.DeleteIPsResult{Deleted: deleted}, nil return db.DeleteIPsResult{Deleted: deleted}, nil
+32 -4
View File
@@ -49,8 +49,7 @@ type ScanOptions struct {
// ClearFirst clears the whole queue before scanning (auto-cycle step 1). // ClearFirst clears the whole queue before scanning (auto-cycle step 1).
// Ignored together with DryRun: a dry run never touches the queue. // Ignored together with DryRun: a dry run never touches the queue.
ClearFirst bool ClearFirst bool
// DryRun only discovers and counts the free floating IPs; the queue is // DryRun only discovers and counts the free floating IPs.
// left untouched.
DryRun bool 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 // 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) { func (o *Orchestrator) doScan(ctx context.Context, opts ScanOptions) (scanResult, error) {
j := &o.scan j := &o.scan
var res scanResult 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 // Read everything first: a read error after retries must leave the queue
// untouched, so nothing is enqueued until discovery is complete. // untouched, so nothing is enqueued until discovery is complete.
var free []string var free []string
var observed map[string]string
if !opts.DryRun {
observed = make(map[string]string)
}
seen := map[string]struct{}{} seen := map[string]struct{}{}
start := time.Now()
pages, err := o.OS.ListFreeFloatingIPs(ctx, o.ScanPageSize, func(page []openstack.FloatingIP) error { pages, err := o.OS.ListFreeFloatingIPs(ctx, o.ScanPageSize, func(page []openstack.FloatingIP) error {
nFree := 0 nFree := 0
for _, f := range page { 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 continue
} }
if _, dup := seen[f.Address]; dup { if _, dup := seen[f.Address]; dup {
@@ -275,6 +290,19 @@ func (o *Orchestrator) doScan(ctx context.Context, opts ScanOptions) (scanResult
res.free = len(free) res.free = len(free)
sortAddressesAscending(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 { if !opts.DryRun && len(free) > 0 {
j.update(func(s *ScanStatus) { s.State = ScanEnqueuing }) j.update(func(s *ScanStatus) { s.State = ScanEnqueuing })
for off := 0; off < len(free); off += scanChunkSize { for off := 0; off < len(free); off += scanChunkSize {
+4
View File
@@ -131,6 +131,10 @@ func TestScanJobDryRunLeavesQueueUntouched(t *testing.T) {
if countEvents(t, d, "fip_scan") != 0 || countEvents(t, d, "queue_cleared") != 0 { if countEvents(t, d, "fip_scan") != 0 || countEvents(t, d, "queue_cleared") != 0 {
t.Fatalf("dry run must not emit scan/clear events") 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) { func TestScanJobReadErrorLeavesQueueUntouched(t *testing.T) {