From c8ef246b0c20a3fbdb33e4903ee2f3c5c61295fd Mon Sep 17 00:00:00 2001 From: Timon Schnell Date: Tue, 10 Nov 2026 08:00:41 +0100 Subject: [PATCH 1/4] Add Open for a pool without the startup ping ConnectContext pings and closes the pool when the database does not answer, so a caller that starts during a database outage has no pool at all. The OpenStack database exporter then reports its services as down until it is restarted, even after the database is back. Open does the parsing and pool setup without contacting the server, and ConnectContext becomes Open plus the ping, so existing callers behave as before. The pool connects on first use and reconnects after a lost connection. Tested with go test -race, go vet, gofmt and the integration suite. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Timon Schnell --- README.md | 2 ++ connect_test.go | 26 ++++++++++++++++++++++++++ db.go | 24 ++++++++++++++++++------ 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4a5e3b0..e31787b 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,8 @@ func instanceCount(ctx context.Context, databaseURL, projectID string) (int, err } ``` +`Open` returns the same pool without the ping, for callers that must start +before the database is reachable; the pool connects on first use. Existing `*sql.DB` and `*sql.Tx` values can also be passed to service constructors. Generated query sets support `WithTx`. Callers own pools, deadlines, region/cell selection, credentials, and authorization. Use database accounts with SELECT access. diff --git a/connect_test.go b/connect_test.go index fd293f1..d8b240c 100644 --- a/connect_test.go +++ b/connect_test.go @@ -4,6 +4,7 @@ import ( "context" "github.com/stretchr/testify/require" "testing" + "time" ) func TestConnectInvalidURLs(t *testing.T) { @@ -22,3 +23,28 @@ func TestConnectInvalidOptions(t *testing.T) { _, err := ConnectContext(context.Background(), "mysql://user:pass@localhost/db", ConnectionOptions{MaxOpenConns: -1}) require.Error(t, err) } +func TestOpenInvalidURLs(t *testing.T) { + for _, u := range []string{"", "postgresql://user:pass@localhost/db"} { + _, err := Open(u, ConnectionOptions{}) + require.Error(t, err) + } +} +func TestOpenInvalidOptions(t *testing.T) { + _, err := Open("mysql://user:pass@localhost/db", ConnectionOptions{MaxOpenConns: -1}) + require.Error(t, err) +} +func TestOpenUnreachableServer(t *testing.T) { + db, err := Open("mysql://user:pass@127.0.0.1:1/db", ConnectionOptions{}) + require.NoError(t, err) + defer db.Close() + require.Equal(t, 5, db.Stats().MaxOpenConnections) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.Error(t, db.PingContext(ctx)) +} +func TestOpenOptions(t *testing.T) { + db, err := Open("mysql://user:pass@localhost/db", ConnectionOptions{MaxOpenConns: 7}) + require.NoError(t, err) + defer db.Close() + require.Equal(t, 7, db.Stats().MaxOpenConnections) +} diff --git a/db.go b/db.go index 30ef2c3..99d6641 100644 --- a/db.go +++ b/db.go @@ -24,9 +24,25 @@ func Connect(connectionString string) (*sql.DB, error) { return ConnectContext(ctx, connectionString, ConnectionOptions{}) } -// ConnectContext opens a pool from an oslo.db-style MySQL URL and verifies it -// within ctx's deadline. It does not grant or enforce database permissions. +// ConnectContext opens a pool with Open and verifies it within ctx's deadline. +// It does not grant or enforce database permissions. func ConnectContext(ctx context.Context, connectionString string, opts ConnectionOptions) (*sql.DB, error) { + db, err := Open(connectionString, opts) + if err != nil { + return nil, err + } + if err := db.PingContext(ctx); err != nil { + _ = db.Close() + return nil, fmt.Errorf("failed to ping database: %w", err) + } + return db, nil +} + +// Open creates a pool from an oslo.db-style MySQL URL without contacting the +// server. The pool connects on first use and again after a lost connection, so +// a caller can hold a pool for a database that is not reachable yet. +// The caller owns the returned pool and must close it. +func Open(connectionString string, opts ConnectionOptions) (*sql.DB, error) { if opts.MaxOpenConns < 0 || opts.MaxIdleConns < 0 || opts.ConnMaxLifetime < 0 { return nil, fmt.Errorf("connection options must not be negative") } @@ -47,9 +63,5 @@ func ConnectContext(ctx context.Context, connectionString string, opts Connectio db.SetMaxOpenConns(opts.MaxOpenConns) db.SetMaxIdleConns(opts.MaxIdleConns) db.SetConnMaxLifetime(opts.ConnMaxLifetime) - if err := db.PingContext(ctx); err != nil { - _ = db.Close() - return nil, fmt.Errorf("failed to ping database: %w", err) - } return db, nil } From 1586227912bd106411160690f5ea1fd9c16e0362 Mon Sep 17 00:00:00 2001 From: Mohammed Naser Date: Fri, 20 Nov 2026 22:47:35 +0000 Subject: [PATCH 2/4] Document that a pool from Open needs call deadlines Open adds no dial timeout, so a pool held through a database outage does not fail fast. Say so in the Open doc comment and the README, and move the Open note into its own README paragraph. Signed-off-by: Mohammed Naser --- README.md | 4 +++- db.go | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e31787b..5a2eddf 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,9 @@ func instanceCount(ctx context.Context, databaseURL, projectID string) (int, err ``` `Open` returns the same pool without the ping, for callers that must start -before the database is reachable; the pool connects on first use. +before the database is reachable; the pool connects on first use. It does not +fail fast during an outage, so give each query a context deadline. + Existing `*sql.DB` and `*sql.Tx` values can also be passed to service constructors. Generated query sets support `WithTx`. Callers own pools, deadlines, region/cell selection, credentials, and authorization. Use database accounts with SELECT access. diff --git a/db.go b/db.go index 99d6641..3731330 100644 --- a/db.go +++ b/db.go @@ -41,6 +41,9 @@ func ConnectContext(ctx context.Context, connectionString string, opts Connectio // Open creates a pool from an oslo.db-style MySQL URL without contacting the // server. The pool connects on first use and again after a lost connection, so // a caller can hold a pool for a database that is not reachable yet. +// The pool does not fail fast while the database is unreachable: Open adds +// no dial timeout of its own, so bound each call with a context deadline, for +// example with QueryContext or PingContext. // The caller owns the returned pool and must close it. func Open(connectionString string, opts ConnectionOptions) (*sql.DB, error) { if opts.MaxOpenConns < 0 || opts.MaxIdleConns < 0 || opts.ConnMaxLifetime < 0 { From c8f44b199b3c315245386bed2066079b9562226b Mon Sep 17 00:00:00 2001 From: Tadas Sutkaitis Date: Tue, 1 Dec 2026 17:52:54 +0200 Subject: [PATCH 3/4] Add Designate zone and recordset queries (#9) Add three read-only Designate queries for openstack_database_exporter: - ZoneGetAll: non-deleted zones with status and type. - RecordsetCountByZone: recordset count per non-deleted zone, including zones with no recordsets, without reading individual records. - RecordsetGetAllWithStatus: recordsets with the status the Designate API reports (worst child record status in the order ERROR, PENDING, ACTIVE, DELETED; ACTIVE when a recordset has no records). Zone and recordset IDs are returned as dashed UUIDs, matching the API. Splitting the queries lets the exporter skip the per-recordset status query when that metric is disabled. Signed-off-by: Tadas Sutkaitis --- API.md | 5 ++ README.md | 1 + designate/db/db.go | 31 +++++++ designate/db/designate.go | 51 +++++++++++ designate/db/models.go | 31 +++++++ designate/db/queries.sql | 44 ++++++++++ designate/db/queries.sql.go | 170 ++++++++++++++++++++++++++++++++++++ go.mod | 2 +- schema/designate/schema.sql | 23 +++++ sqlc.yaml | 8 ++ tests/queries_test.go | 86 ++++++++++++++++++ 11 files changed, 451 insertions(+), 1 deletion(-) create mode 100644 designate/db/db.go create mode 100644 designate/db/designate.go create mode 100644 designate/db/models.go create mode 100644 designate/db/queries.sql create mode 100644 designate/db/queries.sql.go create mode 100644 schema/designate/schema.sql diff --git a/API.md b/API.md index f264cfe..af8487d 100644 --- a/API.md +++ b/API.md @@ -25,6 +25,9 @@ with identical semantics upstream. | `cinder/db` | `GetSnapshotCount` | `SnapshotCount` | | `cinder/db` | `GetAllVolumes` | `VolumeGetAllWithAttachments` | | `glance/db` | `GetAllImages` | `ImageGetAll` | +| `designate/db` | `ListZonesAndRecordsets` (zone details) | `ZoneGetAll` | +| `designate/db` | `ListZonesAndRecordsets` (per-zone counts) | `RecordsetCountByZone` | +| `designate/db` | `ListZonesAndRecordsets` (recordset details) | `RecordsetGetAllWithStatus` | | `heat/db` | `GetStackMetrics` | `StackGetAll` | | `ironic/db` | `GetNodeMetrics` | `GetNodeList` | | `keystone/db` | `GetProjectMetrics` | `ListProjects` | @@ -62,6 +65,7 @@ with identical semantics upstream. - [Nova API database](https://github.com/openstack/nova/tree/master/nova/db/api) and [objects](https://github.com/openstack/nova/tree/master/nova/objects): flavor, aggregate, and quota data. - [Cinder DB API](https://github.com/openstack/cinder/blob/master/cinder/db/api.py): `volume_get`, `volume_get_all`, `volume_type_get_all`, `service_get_all`. - [Glance DB API](https://github.com/openstack/glance/blob/master/glance/db/sqlalchemy/api.py): `image_get`, `image_get_all`. +- [Designate storage](https://github.com/openstack/designate/blob/master/designate/storage/sqlalchemy/__init__.py): `find_zones`, `find_recordsets`, `count_recordsets`. The library also follows [Designate's UUID conversion](https://github.com/openstack/designate/blob/master/designate/storage/sqlalchemy/types.py) and [recordset status precedence](https://github.com/openstack/designate/blob/master/designate/objects/recordset.py). - [Ironic DB API](https://github.com/openstack/ironic/blob/master/ironic/db/api.py) and [Magnum DB API](https://github.com/openstack/magnum/blob/master/magnum/db/api.py): `get_node_list`, `get_cluster_list`. - [Heat DB API](https://github.com/openstack/heat/blob/master/heat/db/api.py): `stack_get_all`. - [Manila DB API](https://github.com/openstack/manila/blob/master/manila/db/api.py): share operations; the instance join is an explicit extension. @@ -77,6 +81,7 @@ with identical semantics upstream. - Current exporter queries retain their existing deleted/hidden/status predicates; they are not full upstream administrative listings. - Errors are Go/database errors; absent single resources return `sql.ErrNoRows` rather than Python service-specific exceptions. - Aggregate queries such as `QuotaGetAllWithUsage`, `GetResourceProviderInventories`, and `GetResourceCountsByProject` are explicitly library extensions. +- Designate returns canonical zone and recordset UUIDs and excludes soft-deleted zones. `RecordsetCountByZone` includes zero-count zones and can run without reading individual records. `RecordsetGetAllWithStatus` uses the child precedence `ERROR`, `PENDING`, `ACTIVE`, `DELETED` and returns `ACTIVE` for an empty recordset. Recordsets with a NULL `zone_id` have no visible zone and are omitted. - No cross-cell routing or historic schema negotiation is performed. Nova archive access is explicitly selected with `InstanceFilters.Archive`. ## Resource lifecycle and metadata reads diff --git a/README.md b/README.md index 5a2eddf..46520c4 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ repository objects. Placement queries live under `placement/objects`. | `nova/db/api` | `FlavorGetAll`, `AggregateGetAll`, quota projections | | `cinder/db` | `ServiceGetAll`, `QuotaGetProjectLimits`, `QuotaUsageGetAll` | | `glance/db` | `ImageGetAll` | +| `designate/db` | `ZoneGetAll`, `RecordsetCountByZone`, `RecordsetGetAllWithStatus` | | `keystone/db` | `ListProjects`, `ListDomains`, `ListUsers` | | `heat/db` | `StackGetAll` | | `ironic/db` | `GetNodeList` | diff --git a/designate/db/db.go b/designate/db/db.go new file mode 100644 index 0000000..ea582ad --- /dev/null +++ b/designate/db/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 + +package designate + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/designate/db/designate.go b/designate/db/designate.go new file mode 100644 index 0000000..2e9a2c8 --- /dev/null +++ b/designate/db/designate.go @@ -0,0 +1,51 @@ +package designate + +import ( + "context" + + "github.com/google/uuid" +) + +type ( + ZoneGetAllRow = zoneGetAllRow + RecordsetCountByZoneRow = recordsetCountByZoneRow + RecordsetGetAllWithStatusRow = recordsetGetAllWithStatusRow +) + +// ZoneGetAll returns non-deleted zones with API-format UUIDs. +func (q *Queries) ZoneGetAll(ctx context.Context) ([]ZoneGetAllRow, error) { + rows, err := q.zoneGetAll(ctx) + for i := range rows { + rows[i].ID = formatUUID(rows[i].ID) + } + return rows, err +} + +// RecordsetCountByZone returns counts for non-deleted zones, including empty zones. +func (q *Queries) RecordsetCountByZone(ctx context.Context) ([]RecordsetCountByZoneRow, error) { + rows, err := q.recordsetCountByZone(ctx) + for i := range rows { + rows[i].ZoneID = formatUUID(rows[i].ZoneID) + } + return rows, err +} + +// RecordsetGetAllWithStatus returns recordsets in non-deleted zones. +// Status follows Designate's child record precedence and defaults to ACTIVE. +func (q *Queries) RecordsetGetAllWithStatus(ctx context.Context) ([]RecordsetGetAllWithStatusRow, error) { + rows, err := q.recordsetGetAllWithStatus(ctx) + for i := range rows { + rows[i].ID = formatUUID(rows[i].ID) + rows[i].ZoneID = formatUUID(rows[i].ZoneID) + } + return rows, err +} + +// Designate stores compact UUIDs and returns canonical UUIDs through its API. +func formatUUID(value string) string { + id, err := uuid.Parse(value) + if err != nil { + return value + } + return id.String() +} diff --git a/designate/db/models.go b/designate/db/models.go new file mode 100644 index 0000000..94c4ac7 --- /dev/null +++ b/designate/db/models.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 + +package designate + +import ( + "database/sql" +) + +type Record struct { + ID string + RecordsetID string + Status string +} + +type Recordset struct { + ID string + ZoneID string + Name string + Type string +} + +type Zone struct { + ID string + Name string + TenantID sql.NullString + Status string + Type string + Deleted string +} diff --git a/designate/db/queries.sql b/designate/db/queries.sql new file mode 100644 index 0000000..03f7c33 --- /dev/null +++ b/designate/db/queries.sql @@ -0,0 +1,44 @@ +-- name: zoneGetAll :many +SELECT id, name, tenant_id, status, type +FROM zones +WHERE deleted = '0'; + +-- name: recordsetCountByZone :many +SELECT + z.id AS zone_id, + z.name AS zone_name, + z.tenant_id, + COUNT(rs.id) AS recordset_count +FROM zones z +LEFT JOIN recordsets rs ON rs.zone_id = z.id +WHERE z.deleted = '0' +GROUP BY z.id, z.name, z.tenant_id; + +-- name: recordsetGetAllWithStatus :many +SELECT + rs.id, + rs.name, + rs.type, + z.id AS zone_id, + z.name AS zone_name, + CASE rs_status.severity + WHEN 1 THEN 'ERROR' + WHEN 2 THEN 'PENDING' + WHEN 3 THEN 'ACTIVE' + WHEN 4 THEN 'DELETED' + ELSE 'ACTIVE' + END AS status +FROM recordsets rs +JOIN zones z ON z.id = rs.zone_id +LEFT JOIN ( + SELECT recordset_id, + MIN(CASE status + WHEN 'ERROR' THEN 1 + WHEN 'PENDING' THEN 2 + WHEN 'ACTIVE' THEN 3 + WHEN 'DELETED' THEN 4 + END) AS severity + FROM records + GROUP BY recordset_id +) rs_status ON rs_status.recordset_id = rs.id +WHERE z.deleted = '0'; diff --git a/designate/db/queries.sql.go b/designate/db/queries.sql.go new file mode 100644 index 0000000..963c2f9 --- /dev/null +++ b/designate/db/queries.sql.go @@ -0,0 +1,170 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 +// source: queries.sql + +package designate + +import ( + "context" + "database/sql" +) + +const RecordsetCountByZone = `-- name: recordsetCountByZone :many +SELECT + z.id AS zone_id, + z.name AS zone_name, + z.tenant_id, + COUNT(rs.id) AS recordset_count +FROM zones z +LEFT JOIN recordsets rs ON rs.zone_id = z.id +WHERE z.deleted = '0' +GROUP BY z.id, z.name, z.tenant_id +` + +type recordsetCountByZoneRow struct { + ZoneID string + ZoneName string + TenantID sql.NullString + RecordsetCount int64 +} + +func (q *Queries) recordsetCountByZone(ctx context.Context) ([]recordsetCountByZoneRow, error) { + rows, err := q.db.QueryContext(ctx, RecordsetCountByZone) + if err != nil { + return nil, err + } + defer rows.Close() + var items []recordsetCountByZoneRow + for rows.Next() { + var i recordsetCountByZoneRow + if err := rows.Scan( + &i.ZoneID, + &i.ZoneName, + &i.TenantID, + &i.RecordsetCount, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const RecordsetGetAllWithStatus = `-- name: recordsetGetAllWithStatus :many +SELECT + rs.id, + rs.name, + rs.type, + z.id AS zone_id, + z.name AS zone_name, + CASE rs_status.severity + WHEN 1 THEN 'ERROR' + WHEN 2 THEN 'PENDING' + WHEN 3 THEN 'ACTIVE' + WHEN 4 THEN 'DELETED' + ELSE 'ACTIVE' + END AS status +FROM recordsets rs +JOIN zones z ON z.id = rs.zone_id +LEFT JOIN ( + SELECT recordset_id, + MIN(CASE status + WHEN 'ERROR' THEN 1 + WHEN 'PENDING' THEN 2 + WHEN 'ACTIVE' THEN 3 + WHEN 'DELETED' THEN 4 + END) AS severity + FROM records + GROUP BY recordset_id +) rs_status ON rs_status.recordset_id = rs.id +WHERE z.deleted = '0' +` + +type recordsetGetAllWithStatusRow struct { + ID string + Name string + Type string + ZoneID string + ZoneName string + Status string +} + +func (q *Queries) recordsetGetAllWithStatus(ctx context.Context) ([]recordsetGetAllWithStatusRow, error) { + rows, err := q.db.QueryContext(ctx, RecordsetGetAllWithStatus) + if err != nil { + return nil, err + } + defer rows.Close() + var items []recordsetGetAllWithStatusRow + for rows.Next() { + var i recordsetGetAllWithStatusRow + if err := rows.Scan( + &i.ID, + &i.Name, + &i.Type, + &i.ZoneID, + &i.ZoneName, + &i.Status, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ZoneGetAll = `-- name: zoneGetAll :many +SELECT id, name, tenant_id, status, type +FROM zones +WHERE deleted = '0' +` + +type zoneGetAllRow struct { + ID string + Name string + TenantID sql.NullString + Status string + Type string +} + +func (q *Queries) zoneGetAll(ctx context.Context) ([]zoneGetAllRow, error) { + rows, err := q.db.QueryContext(ctx, ZoneGetAll) + if err != nil { + return nil, err + } + defer rows.Close() + var items []zoneGetAllRow + for rows.Next() { + var i zoneGetAllRow + if err := rows.Scan( + &i.ID, + &i.Name, + &i.TenantID, + &i.Status, + &i.Type, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/go.mod b/go.mod index 0e2fae3..904b683 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.25.5 require ( github.com/DATA-DOG/go-sqlmock v1.5.2 github.com/go-sql-driver/mysql v1.9.3 + github.com/google/uuid v1.6.0 github.com/stretchr/testify v1.11.1 github.com/testcontainers/testcontainers-go v0.40.0 github.com/testcontainers/testcontainers-go/modules/mariadb v0.40.0 @@ -31,7 +32,6 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.2.6 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.8 // indirect github.com/klauspost/compress v1.18.0 // indirect github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect diff --git a/schema/designate/schema.sql b/schema/designate/schema.sql new file mode 100644 index 0000000..525f0fa --- /dev/null +++ b/schema/designate/schema.sql @@ -0,0 +1,23 @@ +CREATE TABLE zones ( + id CHAR(32) NOT NULL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + tenant_id VARCHAR(36), + status VARCHAR(16) NOT NULL, + type VARCHAR(16) NOT NULL, + deleted CHAR(32) NOT NULL DEFAULT '0' +); + +CREATE TABLE recordsets ( + id CHAR(32) NOT NULL PRIMARY KEY, + zone_id CHAR(32) NOT NULL, + name VARCHAR(255) NOT NULL, + type VARCHAR(16) NOT NULL, + CONSTRAINT recordsets_zone_fk FOREIGN KEY (zone_id) REFERENCES zones(id) ON DELETE CASCADE +); + +CREATE TABLE records ( + id CHAR(32) NOT NULL PRIMARY KEY, + recordset_id CHAR(32) NOT NULL, + status VARCHAR(16) NOT NULL, + FOREIGN KEY (recordset_id) REFERENCES recordsets(id) ON DELETE CASCADE +); diff --git a/sqlc.yaml b/sqlc.yaml index a04754c..6ca7f91 100644 --- a/sqlc.yaml +++ b/sqlc.yaml @@ -32,6 +32,14 @@ sql: package: glance out: glance/db emit_exported_queries: true +- engine: mysql + schema: schema/designate/schema.sql + queries: designate/db/queries.sql + gen: + go: + package: designate + out: designate/db + emit_exported_queries: true - engine: mysql schema: schema/keystone/schema.sql queries: keystone/db/queries.sql diff --git a/tests/queries_test.go b/tests/queries_test.go index e350060..ee83701 100644 --- a/tests/queries_test.go +++ b/tests/queries_test.go @@ -4,8 +4,10 @@ package tests import ( "context" + "database/sql" "github.com/stretchr/testify/require" cinder "github.com/vexxhost/openstackdb/cinder/db" + designate "github.com/vexxhost/openstackdb/designate/db" glance "github.com/vexxhost/openstackdb/glance/db" heat "github.com/vexxhost/openstackdb/heat/db" "github.com/vexxhost/openstackdb/internal/testutil" @@ -99,6 +101,90 @@ func TestGlanceQueries(t *testing.T) { _, err = q.ImageGetAll(ctx) require.NoError(t, err, "ImageGetAll") } + +func TestDesignateZonesWithRecordsets(t *testing.T) { + conn := testutil.NewMySQLContainer(t, "designate", "../sql/designate/schema.sql") + queries := designate.New(conn) + ctx := context.Background() + + zones, err := queries.ZoneGetAll(ctx) + require.NoError(t, err) + require.Empty(t, zones) + counts, err := queries.RecordsetCountByZone(ctx) + require.NoError(t, err) + require.Empty(t, counts) + recordsets, err := queries.RecordsetGetAllWithStatus(ctx) + require.NoError(t, err) + require.Empty(t, recordsets) + + testutil.SeedSQL(t, conn, + `INSERT INTO zones (id, name, tenant_id, status, type, deleted) VALUES + ('a86dba5800434cc6a1bb69d5e86f3ca3', 'example.org.', 'project-1', 'ACTIVE', 'PRIMARY', '0'), + ('2150b1bfdee242219d8511f7886fb15f', 'empty.example.', NULL, 'PENDING', 'SECONDARY', '0'), + ('23527f480fa04efc82264f2468c7c40e', 'deleted.example.', 'project-1', 'DELETED', 'PRIMARY', '23527f480fa04efc82264f2468c7c40e')`, + `INSERT INTO recordsets (id, zone_id, name, type) VALUES + ('10000000000040008000000000000001', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'error.example.org.', 'A'), + ('10000000000040008000000000000002', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'pending.example.org.', 'A'), + ('10000000000040008000000000000003', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'active.example.org.', 'A'), + ('10000000000040008000000000000004', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'deleted.example.org.', 'A'), + ('10000000000040008000000000000005', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'empty.example.org.', 'TXT'), + ('10000000000040008000000000000006', '23527f480fa04efc82264f2468c7c40e', 'deleted.example.', 'NS')`, + `INSERT INTO records (id, recordset_id, status) VALUES + ('1', '10000000000040008000000000000001', 'PENDING'), ('2', '10000000000040008000000000000001', 'ERROR'), + ('3', '10000000000040008000000000000002', 'ACTIVE'), ('4', '10000000000040008000000000000002', 'PENDING'), + ('5', '10000000000040008000000000000003', 'DELETED'), ('6', '10000000000040008000000000000003', 'ACTIVE'), + ('7', '10000000000040008000000000000004', 'DELETED')`, + ) + + checkVisibleRows := func(t *testing.T) { + t.Helper() + const zoneID = "a86dba58-0043-4cc6-a1bb-69d5e86f3ca3" + const emptyZoneID = "2150b1bf-dee2-4221-9d85-11f7886fb15f" + tenantID := sql.NullString{String: "project-1", Valid: true} + zones, err := queries.ZoneGetAll(ctx) + require.NoError(t, err) + require.ElementsMatch(t, []designate.ZoneGetAllRow{ + {ID: zoneID, Name: "example.org.", TenantID: tenantID, Status: "ACTIVE", Type: "PRIMARY"}, + {ID: emptyZoneID, Name: "empty.example.", Status: "PENDING", Type: "SECONDARY"}, + }, zones) + + counts, err := queries.RecordsetCountByZone(ctx) + require.NoError(t, err) + require.ElementsMatch(t, []designate.RecordsetCountByZoneRow{ + {ZoneID: zoneID, ZoneName: "example.org.", TenantID: tenantID, RecordsetCount: 5}, + {ZoneID: emptyZoneID, ZoneName: "empty.example.", RecordsetCount: 0}, + }, counts) + + recordsets, err := queries.RecordsetGetAllWithStatus(ctx) + require.NoError(t, err) + require.Len(t, recordsets, 5) + statuses := make(map[string]string, len(recordsets)) + for _, row := range recordsets { + require.Equal(t, zoneID, row.ZoneID) + require.Equal(t, "example.org.", row.ZoneName) + statuses[row.ID] = row.Status + } + require.Equal(t, map[string]string{ + "10000000-0000-4000-8000-000000000001": "ERROR", + "10000000-0000-4000-8000-000000000002": "PENDING", + "10000000-0000-4000-8000-000000000003": "ACTIVE", + "10000000-0000-4000-8000-000000000004": "DELETED", + "10000000-0000-4000-8000-000000000005": "ACTIVE", + }, statuses) + } + t.Run("non-null zone ID", checkVisibleRows) + t.Run("nullable zone ID", func(t *testing.T) { + testutil.SeedSQL(t, conn, + `ALTER TABLE recordsets DROP FOREIGN KEY recordsets_zone_fk`, + `ALTER TABLE recordsets MODIFY zone_id CHAR(32) NULL`, + `ALTER TABLE recordsets ADD CONSTRAINT recordsets_zone_fk FOREIGN KEY (zone_id) REFERENCES zones(id) ON DELETE CASCADE`, + `INSERT INTO recordsets (id, zone_id, name, type) VALUES + ('10000000000040008000000000000007', NULL, 'orphan.example.', 'A')`, + ) + checkVisibleRows(t) + }) +} + func TestKeystoneQueries(t *testing.T) { ctx := context.Background() conn := testutil.NewMySQLContainer(t, "keystone", "../sql/keystone/schema.sql") From d0c9d4893eb7928b53ca732272917e664fcbff20 Mon Sep 17 00:00:00 2001 From: Jeremy Lee Date: Thu, 3 Dec 2026 17:36:24 +0000 Subject: [PATCH 4/4] Add Octavia quota limit and usage queries Add two read-only Octavia quota queries and a QuotaRepository that wraps them: - QuotaGetAll (QuotaRepository.GetAll): one row per project from the quotas table, with the stored limits for all seven quota resources and Octavia's cached in_use_* counters, which check_quota_met and decrement_quota enforce against. Limits and counters are nullable; NULL, zero and -1 limits are returned as stored. - QuotaUsageGetAll (QuotaRepository.GetUsage): recounts load balancers, listeners, pools, members, health monitors, L7 policies and L7 rules per project with check_quota_met's predicate (the object's own project_id and provisioning_status != 'DELETED'). Each table is counted independently, so no parent join can multiply or drop counts, and projects without quota rows are included. Comparing the two reads shows counter drift. Octavia defines no index on project_id or provisioning_status, so the recount scans all seven object tables and suits a less frequent drift check rather than every scrape. Both reads exclude empty project IDs, which Octavia rejects. Add the quota and object tables to the Octavia schema fixture, unit tests, a MariaDB integration test with a fixture covering matching and drifted counters, smoke calls in TestOctaviaQueries, and API.md documentation. Co-authored-by: David Hulick Signed-off-by: David Hulick Signed-off-by: Jeremy Lee --- API.md | 41 +++++- README.md | 2 +- octavia/db/repositories/models.go | 56 ++++++++ octavia/db/repositories/queries.sql | 70 ++++++++++ octavia/db/repositories/queries.sql.go | 140 ++++++++++++++++++++ octavia/db/repositories/quota_usage_test.go | 107 +++++++++++++++ octavia/db/repositories/repositories.go | 18 +++ schema/octavia/schema.sql | 68 ++++++++++ tests/fixtures/octavia_quota_usage.sql | 86 ++++++++++++ tests/octavia_quotas_test.go | 56 ++++++++ tests/queries_test.go | 4 + 11 files changed, 646 insertions(+), 2 deletions(-) create mode 100644 octavia/db/repositories/quota_usage_test.go create mode 100644 tests/fixtures/octavia_quota_usage.sql create mode 100644 tests/octavia_quotas_test.go diff --git a/API.md b/API.md index af8487d..d0fcbe3 100644 --- a/API.md +++ b/API.md @@ -53,6 +53,8 @@ with identical semantics upstream. | `octavia/db/repositories` | `GetAllPools` | `PoolGetAll` | | `octavia/db/repositories` | `GetAllLoadBalancersWithVip` | `LoadBalancerGetAllWithVIP` | | `octavia/db/repositories` | `GetAllAmphora` | `AmphoraGetAll` | +| `octavia/db/repositories` | — | `QuotaGetAll` (`QuotaRepository.GetAll`) | +| `octavia/db/repositories` | — | `QuotaUsageGetAll` (`QuotaRepository.GetUsage`) | | `placement/objects` | `GetResourceMetrics` | `GetResourceProviderInventories` | | `placement/objects` | `GetAllocationsByProject` | `GetAllocationsByProject` | | `placement/objects` | `GetConsumerCountByProject` | `GetConsumerCountByProject` | @@ -80,7 +82,8 @@ with identical semantics upstream. - The filtered APIs support exact membership and lifetime overlap, not every upstream regex, pagination, eager-loading, or authorization option. - Current exporter queries retain their existing deleted/hidden/status predicates; they are not full upstream administrative listings. - Errors are Go/database errors; absent single resources return `sql.ErrNoRows` rather than Python service-specific exceptions. -- Aggregate queries such as `QuotaGetAllWithUsage`, `GetResourceProviderInventories`, and `GetResourceCountsByProject` are explicitly library extensions. +- Aggregate queries such as `QuotaGetAllWithUsage`, `GetResourceProviderInventories`, `GetResourceCountsByProject`, and Octavia `QuotaUsageGetAll` are explicitly library extensions. Octavia `QuotaUsageGetAll` recounts objects with `check_quota_met`'s predicate; Octavia itself enforces against the cached `in_use_*` counters that `QuotaGetAll` returns. +- Owner filtering follows each service: Neutron keeps empty-string project IDs because Neutron creates real objects with them (for example L3 HA networks and ports), while Octavia excludes them because it rejects empty project IDs. - Designate returns canonical zone and recordset UUIDs and excludes soft-deleted zones. `RecordsetCountByZone` includes zero-count zones and can run without reading individual records. `RecordsetGetAllWithStatus` uses the child precedence `ERROR`, `PENDING`, `ACTIVE`, `DELETED` and returns `ACTIVE` for an empty recordset. Recordsets with a NULL `zone_id` have no visible zone and are omitted. - No cross-cell routing or historic schema negotiation is performed. Nova archive access is explicitly selected with `InstanceFilters.Archive`. @@ -99,3 +102,39 @@ lifecycle metadata. Their fixed current-resource queries remain unchanged for exporter consumers. Deleted volume types and legacy type tables are only read when explicitly requested. Legacy table availability is a caller/deployment concern; errors are propagated rather than hidden. + +### Octavia quotas + +| Go operation | Upstream naming source | Scope | +| --- | --- | --- | +| `QuotaGetAll` (`QuotaRepository.GetAll`) | [Octavia `QuotasRepository`](https://github.com/openstack/octavia/blob/master/octavia/db/repositories.py) | Stored limits and cached `in_use_*` counters for every project at once; NULL and empty project IDs excluded. | +| `QuotaUsageGetAll` (`QuotaRepository.GetUsage`) | Octavia `Repositories.check_quota_met` recount predicate | Library extension: recounts all seven quota resources for every project; scans seven unindexed object tables. | + +`NewQuotaRepository(db).GetAll(ctx)` / `QuotaGetAll` returns one `Quota` row per +project with the stored limits for load balancers, listeners, pools, health +monitors, members, L7 policies and L7 rules, plus Octavia's cached `in_use_*` +counters. Each value is a `sql.NullInt32`. A NULL limit means no explicit +override, and zero and -1 remain distinct values; the caller resolves configured +defaults. The `in_use_*` counters are what Octavia's `check_quota_met` and +`decrement_quota` enforce against. A NULL or zero counter means Octavia will +recount on its next quota check for that project. + +`QuotaRepository.GetUsage` / `QuotaUsageGetAll` rebuilds project counts for all +seven quota resources independently, using the same predicate Octavia uses when +it recounts: the object's own `project_id` and `provisioning_status != 'DELETED'`. +Counts include ERROR and pending statuses. Each object uses its own project and +status, including children of deleted parents or parents owned by another project, +and there are no parent joins to multiply counts. Results contain only nonzero +project/resource groups, including projects without quota rows, with int64 usage. + +The two reads answer different questions. `in_use_*` is what Octavia enforces +today, and `GetUsage` is what those counters should be. Compare them to detect +counter drift, which persists until Octavia reconciles it. Octavia defines no +index on `project_id` or `provisioning_status`, so `GetUsage` scans all seven +object tables. `GetAll` reads only the `quotas` table and is cheap enough for +every scrape. Run `GetUsage` as a less frequent drift check on large deployments. + +Both reads exclude NULL and empty project IDs. Octavia rejects empty project IDs +(`MissingProjectID`), so such rows can never hold quota. The schema fixtures +contain only fields needed for these tests, not a complete OpenStack migration. +The MariaDB integration test is `TestOctaviaQuotas` in `tests/` and requires Docker. diff --git a/README.md b/README.md index 46520c4..523f72f 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ repository objects. Placement queries live under `placement/objects`. | `magnum/db` | `GetClusterList` | | `manila/db` | `ShareGetAllWithInstances` | | `neutron/db` | `GetAgents`, `GetHARouterAgentPortBindingsWithAgents`, `GetRouters` | -| `octavia/db/repositories` | `PoolRepository`, `LoadBalancerRepository`, `AmphoraRepository` | +| `octavia/db/repositories` | `PoolRepository`, `LoadBalancerRepository`, `AmphoraRepository`, `QuotaRepository` | | `placement/objects` | Resource provider inventory and allocation projections | ## Example diff --git a/octavia/db/repositories/models.go b/octavia/db/repositories/models.go index 3c5c214..8cfa883 100644 --- a/octavia/db/repositories/models.go +++ b/octavia/db/repositories/models.go @@ -31,6 +31,37 @@ type Amphora struct { ComputeFlavor sql.NullString } +type HealthMonitor struct { + ID string + ProjectID sql.NullString + PoolID sql.NullString + ProvisioningStatus string +} + +type L7policy struct { + ID string + ProjectID sql.NullString + ListenerID sql.NullString + ProvisioningStatus string +} + +type L7rule struct { + ID string + ProjectID sql.NullString + L7policyID sql.NullString + ProvisioningStatus string +} + +type Listener struct { + ID string + ProjectID sql.NullString + Name sql.NullString + Protocol string + ProtocolPort int32 + LoadBalancerID sql.NullString + ProvisioningStatus string +} + type LoadBalancer struct { ProjectID sql.NullString ID string @@ -48,6 +79,13 @@ type LoadBalancer struct { AvailabilityZone sql.NullString } +type Member struct { + ID string + ProjectID sql.NullString + PoolID sql.NullString + ProvisioningStatus string +} + type Pool struct { ProjectID sql.NullString ID string @@ -70,6 +108,24 @@ type Pool struct { AlpnProtocols sql.NullString } +type Quota struct { + ProjectID string + HealthMonitor sql.NullInt32 + Listener sql.NullInt32 + LoadBalancer sql.NullInt32 + Member sql.NullInt32 + Pool sql.NullInt32 + L7policy sql.NullInt32 + L7rule sql.NullInt32 + InUseHealthMonitor sql.NullInt32 + InUseListener sql.NullInt32 + InUseLoadBalancer sql.NullInt32 + InUseMember sql.NullInt32 + InUsePool sql.NullInt32 + InUseL7policy sql.NullInt32 + InUseL7rule sql.NullInt32 +} + type Vip struct { LoadBalancerID string IpAddress sql.NullString diff --git a/octavia/db/repositories/queries.sql b/octavia/db/repositories/queries.sql index 7a598a4..22d69ae 100644 --- a/octavia/db/repositories/queries.sql +++ b/octavia/db/repositories/queries.sql @@ -42,3 +42,73 @@ FROM amphora WHERE status != 'DELETED'; + +-- name: QuotaGetAll :many +-- Per-project Octavia quota limits and the cached in_use_* counters that +-- Octavia's check_quota_met and decrement_quota enforce against. NULL limit +-- means no explicit override; a NULL or 0 counter is recounted by Octavia on +-- the next quota check. Octavia rejects empty project IDs (MissingProjectID), +-- so empty-string rows are excluded, matching QuotaUsageGetAll. +SELECT + project_id, + health_monitor, + listener, + load_balancer, + member, + pool, + l7policy, + l7rule, + in_use_health_monitor, + in_use_listener, + in_use_load_balancer, + in_use_member, + in_use_pool, + in_use_l7policy, + in_use_l7rule +FROM + quotas +WHERE + project_id != '' +ORDER BY + project_id; + +-- name: QuotaUsageGetAll :many +-- Rebuild counts using Octavia check_quota_met's project/status predicate. +-- Each table is counted independently: no parent join can multiply rows. +-- Upstream defines no index on project_id or provisioning_status, so this +-- scans all seven tables; compare against QuotaGetAll's in_use_* counters to +-- detect drift rather than calling it on every scrape. +SELECT project_id, 'load_balancer' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM load_balancer +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'listener' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM listener +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'pool' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM pool +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'member' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM member +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'health_monitor' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM health_monitor +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'l7policy' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM l7policy +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'l7rule' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM l7rule +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id; diff --git a/octavia/db/repositories/queries.sql.go b/octavia/db/repositories/queries.sql.go index 604d8ea..108683b 100644 --- a/octavia/db/repositories/queries.sql.go +++ b/octavia/db/repositories/queries.sql.go @@ -184,3 +184,143 @@ func (q *Queries) PoolGetAll(ctx context.Context) ([]PoolGetAllRow, error) { } return items, nil } + +const QuotaGetAll = `-- name: QuotaGetAll :many +SELECT + project_id, + health_monitor, + listener, + load_balancer, + member, + pool, + l7policy, + l7rule, + in_use_health_monitor, + in_use_listener, + in_use_load_balancer, + in_use_member, + in_use_pool, + in_use_l7policy, + in_use_l7rule +FROM + quotas +WHERE + project_id != '' +ORDER BY + project_id +` + +// Per-project Octavia quota limits and the cached in_use_* counters that +// Octavia's check_quota_met and decrement_quota enforce against. NULL limit +// means no explicit override; a NULL or 0 counter is recounted by Octavia on +// the next quota check. Octavia rejects empty project IDs (MissingProjectID), +// so empty-string rows are excluded, matching QuotaUsageGetAll. +func (q *Queries) QuotaGetAll(ctx context.Context) ([]Quota, error) { + rows, err := q.db.QueryContext(ctx, QuotaGetAll) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Quota + for rows.Next() { + var i Quota + if err := rows.Scan( + &i.ProjectID, + &i.HealthMonitor, + &i.Listener, + &i.LoadBalancer, + &i.Member, + &i.Pool, + &i.L7policy, + &i.L7rule, + &i.InUseHealthMonitor, + &i.InUseListener, + &i.InUseLoadBalancer, + &i.InUseMember, + &i.InUsePool, + &i.InUseL7policy, + &i.InUseL7rule, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const QuotaUsageGetAll = `-- name: QuotaUsageGetAll :many +SELECT project_id, 'load_balancer' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM load_balancer +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'listener' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM listener +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'pool' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM pool +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'member' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM member +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'health_monitor' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM health_monitor +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'l7policy' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM l7policy +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +UNION ALL +SELECT project_id, 'l7rule' AS resource, CAST(COUNT(*) AS SIGNED) AS in_use +FROM l7rule +WHERE provisioning_status != 'DELETED' AND project_id IS NOT NULL AND project_id != '' +GROUP BY project_id +` + +type QuotaUsageGetAllRow struct { + ProjectID sql.NullString + Resource string + InUse int64 +} + +// Rebuild counts using Octavia check_quota_met's project/status predicate. +// Each table is counted independently: no parent join can multiply rows. +// Upstream defines no index on project_id or provisioning_status, so this +// scans all seven tables; compare against QuotaGetAll's in_use_* counters to +// detect drift rather than calling it on every scrape. +func (q *Queries) QuotaUsageGetAll(ctx context.Context) ([]QuotaUsageGetAllRow, error) { + rows, err := q.db.QueryContext(ctx, QuotaUsageGetAll) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuotaUsageGetAllRow + for rows.Next() { + var i QuotaUsageGetAllRow + if err := rows.Scan(&i.ProjectID, &i.Resource, &i.InUse); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/octavia/db/repositories/quota_usage_test.go b/octavia/db/repositories/quota_usage_test.go new file mode 100644 index 0000000..fcbe887 --- /dev/null +++ b/octavia/db/repositories/quota_usage_test.go @@ -0,0 +1,107 @@ +package octavia + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "regexp" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/require" +) + +func TestQuotaUsageRepository(t *testing.T) { + for _, scenario := range []string{"rows", "empty", "query error", "scan error", "iteration error"} { + t.Run(scenario, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + query := mock.ExpectQuery(regexp.QuoteMeta(QuotaUsageGetAll)) + rows := sqlmock.NewRows([]string{"project_id", "resource", "in_use"}) + readErr := errors.New("read failed") + switch scenario { + case "rows": + rows.AddRow("project-a", "member", int64(1)<<33) + query.WillReturnRows(rows).RowsWillBeClosed() + case "empty": + query.WillReturnRows(rows).RowsWillBeClosed() + case "query error": + query.WillReturnError(sql.ErrConnDone) + case "scan error": + rows.AddRow("project-a", "member", "invalid integer") + query.WillReturnRows(rows).RowsWillBeClosed() + case "iteration error": + rows.AddRow("project-a", "member", 4).RowError(0, readErr) + query.WillReturnRows(rows).RowsWillBeClosed() + } + got, err := NewQuotaRepository(db).GetUsage(context.Background()) + if scenario == "rows" { + require.NoError(t, err) + require.Equal(t, []QuotaUsageGetAllRow{{ProjectID: sql.NullString{String: "project-a", Valid: true}, Resource: "member", InUse: int64(1) << 33}}, got) + } else if scenario == "empty" { + require.NoError(t, err) + require.Empty(t, got) + } else { + require.Error(t, err) + if scenario == "query error" { + require.ErrorIs(t, err, sql.ErrConnDone) + } else if scenario == "iteration error" { + require.ErrorIs(t, err, readErr) + } + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} + +func TestQuotaLimitsRepository(t *testing.T) { + n := func(v int32) sql.NullInt32 { return sql.NullInt32{Int32: v, Valid: true} } + columns := []string{"project_id", "health_monitor", "listener", "load_balancer", "member", "pool", "l7policy", "l7rule", + "in_use_health_monitor", "in_use_listener", "in_use_load_balancer", "in_use_member", "in_use_pool", "in_use_l7policy", "in_use_l7rule"} + values := []driver.Value{"project-a", nil, -1, 0, 0, 17, nil, 23, nil, nil, 4, 999, nil, nil, nil} + want := []Quota{{ProjectID: "project-a", Listener: n(-1), LoadBalancer: n(0), Member: n(0), Pool: n(17), L7rule: n(23), + InUseLoadBalancer: n(4), InUseMember: n(999)}} + for _, scenario := range []string{"rows", "empty", "query error", "scan error", "iteration error"} { + t.Run(scenario, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + query := mock.ExpectQuery(regexp.QuoteMeta(QuotaGetAll)) + rows := sqlmock.NewRows(columns) + readErr := errors.New("read failed") + switch scenario { + case "rows": + rows.AddRow(values...) + case "query error": + query.WillReturnError(sql.ErrConnDone) + case "scan error": + bad := append([]driver.Value(nil), values...) + bad[11] = "invalid integer" + rows.AddRow(bad...) + case "iteration error": + rows.AddRow(values...).RowError(0, readErr) + } + if scenario != "query error" { + query.WillReturnRows(rows).RowsWillBeClosed() + } + got, err := NewQuotaRepository(db).GetAll(context.Background()) + switch scenario { + case "rows": + require.NoError(t, err) + require.Equal(t, want, got) + case "empty": + require.NoError(t, err) + require.Empty(t, got) + case "query error": + require.ErrorIs(t, err, sql.ErrConnDone) + case "scan error": + require.ErrorContains(t, err, "invalid integer") + case "iteration error": + require.ErrorIs(t, err, readErr) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/octavia/db/repositories/repositories.go b/octavia/db/repositories/repositories.go index f3adae7..c00b371 100644 --- a/octavia/db/repositories/repositories.go +++ b/octavia/db/repositories/repositories.go @@ -27,3 +27,21 @@ func NewAmphoraRepository(db DBTX) *AmphoraRepository { return &AmphoraRepositor func (r *AmphoraRepository) GetAll(ctx context.Context) ([]AmphoraGetAllRow, error) { return r.queries.AmphoraGetAll(ctx) } + +// QuotaRepository provides read operations for project quotas. +type QuotaRepository struct{ queries *Queries } + +func NewQuotaRepository(db DBTX) *QuotaRepository { return &QuotaRepository{queries: New(db)} } + +// GetAll returns per-project limits and Octavia's cached in_use_* counters, +// which are what Octavia enforces quota against. +func (r *QuotaRepository) GetAll(ctx context.Context) ([]Quota, error) { + return r.queries.QuotaGetAll(ctx) +} + +// GetUsage rebuilds project counts from non-DELETED objects, independently +// of the cached in_use_* counters. It includes usage-only projects. It scans +// every quota resource table; compare it with GetAll to detect counter drift. +func (r *QuotaRepository) GetUsage(ctx context.Context) ([]QuotaUsageGetAllRow, error) { + return r.queries.QuotaUsageGetAll(ctx) +} diff --git a/schema/octavia/schema.sql b/schema/octavia/schema.sql index b77b9a6..1f6affd 100644 --- a/schema/octavia/schema.sql +++ b/schema/octavia/schema.sql @@ -74,3 +74,71 @@ CREATE TABLE `octavia_owned` tinyint (1) DEFAULT NULL, `vnic_type` varchar(64) NOT NULL DEFAULT 'normal' ); + +-- Octavia quotas: one row per project (octavia/db/models.py Quotas). +-- Integer columns are limits; NULL means the deployment default applies. +-- in_use_* are Octavia's cached usage counters, which check_quota_met and +-- decrement_quota maintain and enforce against. +CREATE TABLE + `quotas` ( + `project_id` varchar(36) NOT NULL PRIMARY KEY, + `health_monitor` int DEFAULT NULL, + `listener` int DEFAULT NULL, + `load_balancer` int DEFAULT NULL, + `member` int DEFAULT NULL, + `pool` int DEFAULT NULL, + `l7policy` int DEFAULT NULL, + `l7rule` int DEFAULT NULL, + `in_use_health_monitor` int DEFAULT NULL, + `in_use_listener` int DEFAULT NULL, + `in_use_load_balancer` int DEFAULT NULL, + `in_use_member` int DEFAULT NULL, + `in_use_pool` int DEFAULT NULL, + `in_use_l7policy` int DEFAULT NULL, + `in_use_l7rule` int DEFAULT NULL + ); + +-- Minimal listener rows for QuotaUsageGetAll's recount, which follows +-- check_quota_met's project_id and provisioning_status predicate. +CREATE TABLE + `listener` ( + `id` varchar(36) NOT NULL PRIMARY KEY, + `project_id` varchar(36) DEFAULT NULL, + `name` varchar(255) DEFAULT NULL, + `protocol` varchar(16) NOT NULL, + `protocol_port` int NOT NULL, + `load_balancer_id` varchar(36) DEFAULT NULL, + `provisioning_status` varchar(16) NOT NULL + ); + +-- Minimal quota-count fixture; fields follow Octavia 2025.2 db/models.py. +CREATE TABLE `member` ( + `id` varchar(36) NOT NULL PRIMARY KEY, + `project_id` varchar(36) DEFAULT NULL, + `pool_id` varchar(36) DEFAULT NULL, + `provisioning_status` varchar(16) NOT NULL +); + +-- Minimal quota-count fixture; fields follow Octavia 2025.2 db/models.py. +CREATE TABLE `health_monitor` ( + `id` varchar(36) NOT NULL PRIMARY KEY, + `project_id` varchar(36) DEFAULT NULL, + `pool_id` varchar(36) DEFAULT NULL UNIQUE, + `provisioning_status` varchar(16) NOT NULL +); + +-- Minimal quota-count fixture; fields follow Octavia 2025.2 db/models.py. +CREATE TABLE `l7policy` ( + `id` varchar(36) NOT NULL PRIMARY KEY, + `project_id` varchar(36) DEFAULT NULL, + `listener_id` varchar(36) DEFAULT NULL, + `provisioning_status` varchar(16) NOT NULL +); + +-- Minimal quota-count fixture; fields follow Octavia 2025.2 db/models.py. +CREATE TABLE `l7rule` ( + `id` varchar(36) NOT NULL PRIMARY KEY, + `project_id` varchar(36) DEFAULT NULL, + `l7policy_id` varchar(36) DEFAULT NULL, + `provisioning_status` varchar(16) NOT NULL +); diff --git a/tests/fixtures/octavia_quota_usage.sql b/tests/fixtures/octavia_quota_usage.sql new file mode 100644 index 0000000..2009a4e --- /dev/null +++ b/tests/fixtures/octavia_quota_usage.sql @@ -0,0 +1,86 @@ +-- Deliberately shared parent IDs catch aggregate join multiplication. +-- Live children of DELETED parents still count by their own project and status. +INSERT INTO load_balancer (id, project_id, provisioning_status, operating_status, enabled) VALUES ('load_balancer-a-0', 'project-a', 'ACTIVE', 'ONLINE', 1); +INSERT INTO load_balancer (id, project_id, provisioning_status, operating_status, enabled) VALUES ('load_balancer-a-1', 'project-a', 'ERROR', 'ONLINE', 1); +INSERT INTO load_balancer (id, project_id, provisioning_status, operating_status, enabled) VALUES ('load_balancer-a-2', 'project-a', 'PENDING_CREATE', 'ONLINE', 1); +INSERT INTO load_balancer (id, project_id, provisioning_status, operating_status, enabled) VALUES ('load_balancer-a-3', 'project-a', 'PENDING_DELETE', 'ONLINE', 1); +INSERT INTO load_balancer (id, project_id, provisioning_status, operating_status, enabled) VALUES ('load_balancer-a-4', 'project-a', 'DELETED', 'ONLINE', 1); +INSERT INTO load_balancer (id, project_id, provisioning_status, operating_status, enabled) VALUES ('load_balancer-b', 'project-b', 'ACTIVE', 'ONLINE', 1); +INSERT INTO load_balancer (id, project_id, provisioning_status, operating_status, enabled) VALUES ('load_balancer-null', NULL, 'ACTIVE', 'ONLINE', 1); +INSERT INTO load_balancer (id, project_id, provisioning_status, operating_status, enabled) VALUES ('load_balancer-empty', '', 'ACTIVE', 'ONLINE', 1); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-a-0', 'project-a', 'ACTIVE', 'HTTP', 80, 'load_balancer-a-4'); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-a-1', 'project-a', 'ERROR', 'HTTP', 80, 'load_balancer-a-0'); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-a-2', 'project-a', 'PENDING_CREATE', 'HTTP', 80, 'load_balancer-a-0'); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-a-3', 'project-a', 'PENDING_DELETE', 'HTTP', 80, 'load_balancer-a-0'); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-a-4', 'project-a', 'DELETED', 'HTTP', 80, 'load_balancer-a-0'); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-b', 'project-b', 'ACTIVE', 'HTTP', 80, 'load_balancer-a-0'); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-null', NULL, 'ACTIVE', 'HTTP', 80, 'load_balancer-a-0'); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-empty', '', 'ACTIVE', 'HTTP', 80, 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-a-0', 'project-a', 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-4'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-a-1', 'project-a', 'ERROR', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-a-2', 'project-a', 'PENDING_CREATE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-a-3', 'project-a', 'PENDING_DELETE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-a-4', 'project-a', 'DELETED', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-b', 'project-b', 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-null', NULL, 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-empty', '', 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-a-0', 'project-a', 'ACTIVE', 'pool-a-4'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-a-1', 'project-a', 'ERROR', 'pool-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-a-2', 'project-a', 'PENDING_CREATE', 'pool-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-a-3', 'project-a', 'PENDING_DELETE', 'pool-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-a-4', 'project-a', 'DELETED', 'pool-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-b', 'project-b', 'ACTIVE', 'pool-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-null', NULL, 'ACTIVE', 'pool-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-empty', '', 'ACTIVE', 'pool-a-0'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-a-0', 'project-a', 'ACTIVE', 'pool-a-4'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-a-1', 'project-a', 'ERROR', 'pool-a-1'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-a-2', 'project-a', 'PENDING_CREATE', 'pool-a-2'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-a-3', 'project-a', 'PENDING_DELETE', 'pool-a-3'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-a-4', 'project-a', 'DELETED', 'pool-a-0'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-b', 'project-b', 'ACTIVE', 'pool-b'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-null', NULL, 'ACTIVE', 'pool-null'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-empty', '', 'ACTIVE', 'pool-empty'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-a-0', 'project-a', 'ACTIVE', 'listener-a-4'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-a-1', 'project-a', 'ERROR', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-a-2', 'project-a', 'PENDING_CREATE', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-a-3', 'project-a', 'PENDING_DELETE', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-a-4', 'project-a', 'DELETED', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-b', 'project-b', 'ACTIVE', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-null', NULL, 'ACTIVE', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-empty', '', 'ACTIVE', 'listener-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-a-0', 'project-a', 'ACTIVE', 'l7policy-a-4'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-a-1', 'project-a', 'ERROR', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-a-2', 'project-a', 'PENDING_CREATE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-a-3', 'project-a', 'PENDING_DELETE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-a-4', 'project-a', 'DELETED', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-b', 'project-b', 'ACTIVE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-null', NULL, 'ACTIVE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-empty', '', 'ACTIVE', 'l7policy-a-0'); +-- Cached counters: in_use_load_balancer matches the recount (4), in_use_member +-- has drifted (999 vs 7). The rest are NULL, as before Octavia's first quota check. +INSERT INTO quotas (project_id, health_monitor, listener, load_balancer, member, pool, l7policy, l7rule, in_use_load_balancer, in_use_member) VALUES ('project-a', NULL, -1, 0, 0, 17, NULL, 23, 4, 999); +INSERT INTO listener (id, project_id, provisioning_status, protocol, protocol_port, load_balancer_id) VALUES ('listener-extra-0', 'project-a', 'ACTIVE', 'HTTP', 80, 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-extra-0', 'project-a', 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-extra-1', 'project-a', 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-extra-0', 'project-a', 'ACTIVE', 'pool-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-extra-1', 'project-a', 'ACTIVE', 'pool-a-0'); +INSERT INTO member (id, project_id, provisioning_status, pool_id) VALUES ('member-extra-2', 'project-a', 'ACTIVE', 'pool-a-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-hm-extra-0', NULL, 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-extra-0', 'project-a', 'ACTIVE', 'pool-hm-extra-0'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-hm-extra-1', NULL, 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-extra-1', 'project-a', 'ACTIVE', 'pool-hm-extra-1'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-hm-extra-2', NULL, 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-extra-2', 'project-a', 'ACTIVE', 'pool-hm-extra-2'); +INSERT INTO pool (id, project_id, provisioning_status, operating_status, enabled, protocol, lb_algorithm, load_balancer_id) VALUES ('pool-hm-extra-3', NULL, 'ACTIVE', 'ONLINE', 1, 'HTTP', 'ROUND_ROBIN', 'load_balancer-a-0'); +INSERT INTO health_monitor (id, project_id, provisioning_status, pool_id) VALUES ('health_monitor-extra-3', 'project-a', 'ACTIVE', 'pool-hm-extra-3'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-extra-0', 'project-a', 'ACTIVE', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-extra-1', 'project-a', 'ACTIVE', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-extra-2', 'project-a', 'ACTIVE', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-extra-3', 'project-a', 'ACTIVE', 'listener-a-0'); +INSERT INTO l7policy (id, project_id, provisioning_status, listener_id) VALUES ('l7policy-extra-4', 'project-a', 'ACTIVE', 'listener-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-extra-0', 'project-a', 'ACTIVE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-extra-1', 'project-a', 'ACTIVE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-extra-2', 'project-a', 'ACTIVE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-extra-3', 'project-a', 'ACTIVE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-extra-4', 'project-a', 'ACTIVE', 'l7policy-a-0'); +INSERT INTO l7rule (id, project_id, provisioning_status, l7policy_id) VALUES ('l7rule-extra-5', 'project-a', 'ACTIVE', 'l7policy-a-0'); diff --git a/tests/octavia_quotas_test.go b/tests/octavia_quotas_test.go new file mode 100644 index 0000000..be05a91 --- /dev/null +++ b/tests/octavia_quotas_test.go @@ -0,0 +1,56 @@ +//go:build integration + +package tests + +import ( + "database/sql" + "os" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/vexxhost/openstackdb/internal/testutil" + octavia "github.com/vexxhost/openstackdb/octavia/db/repositories" +) + +// The fixture includes DELETED rows, NULL and empty project IDs, and cached +// in_use_* counters that both match and drift from the recount. +func TestOctaviaQuotas(t *testing.T) { + ctx := t.Context() + db := testutil.NewMySQLContainer(t, "octavia-quotas", "../sql/octavia/schema.sql") + fixture, err := os.ReadFile("fixtures/octavia_quota_usage.sql") + require.NoError(t, err) + testutil.SeedSQL(t, db, string(fixture), "INSERT INTO quotas (project_id) VALUES ('')") + r := octavia.NewQuotaRepository(db) + + usage, err := r.GetUsage(ctx) + require.NoError(t, err) + expected := map[string]int64{} + for index, resource := range strings.Fields("load_balancer listener pool member health_monitor l7policy l7rule") { + expected["project-a/"+resource] = int64(index + 4) + expected["project-b/"+resource] = 1 + } + got := map[string]int64{} + for _, row := range usage { + require.True(t, row.ProjectID.Valid) + key := row.ProjectID.String + "/" + row.Resource + require.NotContains(t, got, key) + got[key] = row.InUse + } + require.Equal(t, expected, got) + + // Limits and cached counters come back as stored. The empty-string row is + // excluded, matching GetUsage, because Octavia rejects empty project IDs. + quotas, err := r.GetAll(ctx) + require.NoError(t, err) + n := func(v int32) sql.NullInt32 { return sql.NullInt32{Int32: v, Valid: true} } + require.Equal(t, []octavia.Quota{{ + ProjectID: "project-a", + Listener: n(-1), LoadBalancer: n(0), Member: n(0), Pool: n(17), L7rule: n(23), + InUseLoadBalancer: n(4), InUseMember: n(999), + }}, quotas) + + // Drift is visible by comparing the cached counter with the recount. + require.Equal(t, int64(quotas[0].InUseLoadBalancer.Int32), got["project-a/load_balancer"]) + require.NotEqual(t, int64(quotas[0].InUseMember.Int32), got["project-a/member"]) +} diff --git a/tests/queries_test.go b/tests/queries_test.go index ee83701..f2a3542 100644 --- a/tests/queries_test.go +++ b/tests/queries_test.go @@ -276,6 +276,10 @@ func TestOctaviaQueries(t *testing.T) { require.NoError(t, err, "LoadBalancerGetAllWithVIP") _, err = q.AmphoraGetAll(ctx) require.NoError(t, err, "AmphoraGetAll") + _, err = q.QuotaGetAll(ctx) + require.NoError(t, err, "QuotaGetAll") + _, err = q.QuotaUsageGetAll(ctx) + require.NoError(t, err, "QuotaUsageGetAll") } func TestPlacementQueries(t *testing.T) { ctx := context.Background()