57 lines
1.7 KiB
Go
57 lines
1.7 KiB
Go
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()
|
|
}
|