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

+68 -30
View File
@@ -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)
+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) {
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)
}
@@ -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" {
+31
View File
@@ -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)
}
}
+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
// (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
+32 -4
View File
@@ -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 {
+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 {
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) {