From 75cf35c45adc7ffde4a1accd4f61c8025bc4b48e Mon Sep 17 00:00:00 2001 From: Jeremy Lee Date: Thu, 3 Dec 2026 18:07:49 +0000 Subject: [PATCH] Add Neutron quota reservations query and order GetQuotas Add GetReservationsForResources, which follows Neutron's get_reservations_for_resources(expired=False) for every project at once. It returns one row per active reservation delta (reservation ID, project ID, expiration, resource and amount), ordered by project, resource and reservation ID. Amounts are returned as stored, including NULL and negative values, rather than summed. A reservation is active when expiration >= UTC_TIMESTAMP(), the same inclusive boundary Neutron uses. The comparison runs on the database clock in UTC, so caller clock skew and session time zones do not affect the result. The resources to read are a positional argument; an empty list matches nothing, as upstream. NULL owners are excluded and empty-string owners are kept, matching GetQuotas and GetResourceCountsByProject, so limits, usage and reservations join on project ID without special cases. GetResourceCountsByProject is unchanged. GetQuotas now orders by project, resource and quota ID so callers that collapse duplicate rows get a stable result. Add the reservations and resourcedeltas tables to the Neutron schema fixture, without indexes on expiration or project_id as upstream. Add unit tests, MariaDB integration tests for reservations and quota owner handling and ordering, and API.md documentation. Co-authored-by: David Hulick Signed-off-by: David Hulick Signed-off-by: Jeremy Lee --- API.md | 42 ++++++++ README.md | 2 +- neutron/db/models.go | 12 +++ neutron/db/queries.sql | 24 ++++- neutron/db/queries.sql.go | 71 ++++++++++++++ neutron/db/quotas_test.go | 97 +++++++++++++++++++ schema/neutron/schema.sql | 16 ++++ tests/neutron_quotas_integration_test.go | 117 +++++++++++++++++++++++ 8 files changed, 379 insertions(+), 2 deletions(-) create mode 100644 neutron/db/quotas_test.go create mode 100644 tests/neutron_quotas_integration_test.go diff --git a/API.md b/API.md index af8487d..d4866d5 100644 --- a/API.md +++ b/API.md @@ -99,3 +99,45 @@ 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. + +### Neutron quota reservations + +| Go operation | Upstream naming source | Scope | +| --- | --- | --- | +| `GetReservationsForResources` | [Neutron `get_reservations_for_resources(..., expired=False)`](https://github.com/openstack/neutron/blob/master/neutron/db/quota/api.py) | All projects instead of one; raw per-delta rows instead of a per-resource sum. | + +`neutron/db.Queries.GetReservationsForResources(ctx, resources)` returns one row +per active reservation delta: `ReservationID`, `ProjectID`, `Expiration`, +`Resource`, and `Amount`. Rows are ordered by project, resource, and reservation +ID. Amounts are returned as stored, including NULL and negative values; summing +them and deciding how to treat malformed amounts is the caller's job. + +A reservation is active when `expiration >= UTC_TIMESTAMP()`, the same inclusive +boundary Neutron uses. The comparison runs on the database clock, so skew +between the caller and the Neutron servers does not change the result. Neutron +writes expirations in UTC, so the comparison uses `UTC_TIMESTAMP()` rather than +the session-time-zone `NOW()`. NULL expirations are never active. + +`resources` is a positional argument, not a `...Filters` struct, and follows +upstream: a nil or empty list matches nothing rather than every resource. Pass +the resources to monitor explicitly, for example `floatingip`, `network`, `port`, +`rbac_policy`, `router`, `security_group`, `security_group_rule`, `subnet`, and +`subnetpool`. + +NULL owners are excluded and empty-string owners are kept. `GetQuotas` and +`GetResourceCountsByProject` use the same owner policy, so limits, usage, and +reservations can be joined on `ProjectID` without special cases. `GetQuotas` +returns rows ordered by project, resource, and quota ID, so callers that collapse +duplicate project/resource rows get a stable result. + +Upstream Neutron defines no index on `reservations.expiration` or +`reservations.project_id`; the schema fixture mirrors that. Each call therefore +scans `reservations` and joins `resourcedeltas` through the index InnoDB creates +for its `reservation_id` foreign key. This is the same access path Neutron's own +quota engine uses, and the table stays small while Neutron's expired-reservation +cleanup runs. If cleanup stalls, the table and this query's cost grow together. + +The schema tables are local fixtures, not production migrations. Separate reads +do not share a snapshot unless the caller uses `WithTx` with a suitable isolation +level. Query, scan, row-iteration, and context errors propagate through the +generated API; an error must never be treated as zero reservations. diff --git a/README.md b/README.md index 46520c4..00fd694 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ repository objects. Placement queries live under `placement/objects`. | `ironic/db` | `GetNodeList` | | `magnum/db` | `GetClusterList` | | `manila/db` | `ShareGetAllWithInstances` | -| `neutron/db` | `GetAgents`, `GetHARouterAgentPortBindingsWithAgents`, `GetRouters` | +| `neutron/db` | `GetAgents`, `GetHARouterAgentPortBindingsWithAgents`, `GetRouters`, `GetQuotas`, `GetReservationsForResources` | | `octavia/db/repositories` | `PoolRepository`, `LoadBalancerRepository`, `AmphoraRepository` | | `placement/objects` | Resource provider inventory and allocation projections | diff --git a/neutron/db/models.go b/neutron/db/models.go index c0ab6c9..d1a4eb3 100644 --- a/neutron/db/models.go +++ b/neutron/db/models.go @@ -309,6 +309,18 @@ type Quota struct { Limit sql.NullInt32 } +type Reservation struct { + ID string + ProjectID sql.NullString + Expiration sql.NullTime +} + +type Resourcedelta struct { + Resource string + ReservationID string + Amount sql.NullInt32 +} + type Router struct { ProjectID sql.NullString ID string diff --git a/neutron/db/queries.sql b/neutron/db/queries.sql index 40c8361..ff0b223 100644 --- a/neutron/db/queries.sql +++ b/neutron/db/queries.sql @@ -218,7 +218,11 @@ SELECT FROM quotas q WHERE - q.project_id IS NOT NULL; + q.project_id IS NOT NULL +ORDER BY + q.project_id, + q.resource, + q.id; -- name: GetResourceCountsByProject :many SELECT @@ -274,3 +278,21 @@ SELECT 'subnetpool' as resource, CAST(COUNT(*) AS SIGNED) as cnt FROM subnetpools WHERE project_id IS NOT NULL GROUP BY project_id; + +-- name: GetReservationsForResources :many +-- Mirrors neutron.db.quota.api.get_reservations_for_resources(expired=False): +-- active means expiration >= now, evaluated on the database clock in UTC +-- because Neutron writes expirations with utcnow(). Rows are returned per +-- reservation delta, unaggregated, for every project with a non-NULL owner. +SELECT + r.id AS reservation_id, + r.project_id, + r.expiration, + d.resource, + d.amount +FROM reservations r +JOIN resourcedeltas d ON d.reservation_id = r.id +WHERE r.expiration >= UTC_TIMESTAMP() + AND r.project_id IS NOT NULL + AND d.resource IN (sqlc.slice('resources')) +ORDER BY r.project_id, d.resource, r.id; diff --git a/neutron/db/queries.sql.go b/neutron/db/queries.sql.go index 23e36e4..7eeda26 100644 --- a/neutron/db/queries.sql.go +++ b/neutron/db/queries.sql.go @@ -8,6 +8,7 @@ package neutron import ( "context" "database/sql" + "strings" ) const GetAgents = `-- name: GetAgents :many @@ -476,6 +477,10 @@ FROM quotas q WHERE q.project_id IS NOT NULL +ORDER BY + q.project_id, + q.resource, + q.id ` type GetQuotasRow struct { @@ -507,6 +512,72 @@ func (q *Queries) GetQuotas(ctx context.Context) ([]GetQuotasRow, error) { return items, nil } +const GetReservationsForResources = `-- name: GetReservationsForResources :many +SELECT + r.id AS reservation_id, + r.project_id, + r.expiration, + d.resource, + d.amount +FROM reservations r +JOIN resourcedeltas d ON d.reservation_id = r.id +WHERE r.expiration >= UTC_TIMESTAMP() + AND r.project_id IS NOT NULL + AND d.resource IN (/*SLICE:resources*/?) +ORDER BY r.project_id, d.resource, r.id +` + +type GetReservationsForResourcesRow struct { + ReservationID string + ProjectID sql.NullString + Expiration sql.NullTime + Resource string + Amount sql.NullInt32 +} + +// Mirrors neutron.db.quota.api.get_reservations_for_resources(expired=False): +// active means expiration >= now, evaluated on the database clock in UTC +// because Neutron writes expirations with utcnow(). Rows are returned per +// reservation delta, unaggregated, for every project with a non-NULL owner. +func (q *Queries) GetReservationsForResources(ctx context.Context, resources []string) ([]GetReservationsForResourcesRow, error) { + query := GetReservationsForResources + var queryParams []interface{} + if len(resources) > 0 { + for _, v := range resources { + queryParams = append(queryParams, v) + } + query = strings.Replace(query, "/*SLICE:resources*/?", strings.Repeat(",?", len(resources))[1:], 1) + } else { + query = strings.Replace(query, "/*SLICE:resources*/?", "NULL", 1) + } + rows, err := q.db.QueryContext(ctx, query, queryParams...) + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetReservationsForResourcesRow + for rows.Next() { + var i GetReservationsForResourcesRow + if err := rows.Scan( + &i.ReservationID, + &i.ProjectID, + &i.Expiration, + &i.Resource, + &i.Amount, + ); 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 GetResourceCountsByProject = `-- name: GetResourceCountsByProject :many SELECT project_id, diff --git a/neutron/db/quotas_test.go b/neutron/db/quotas_test.go new file mode 100644 index 0000000..5ef7327 --- /dev/null +++ b/neutron/db/quotas_test.go @@ -0,0 +1,97 @@ +package neutron + +import ( + "context" + "database/sql" + "errors" + "regexp" + "strings" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/require" +) + +var reservationColumns = []string{"reservation_id", "project_id", "expiration", "resource", "amount"} + +func reservationQuery(placeholders string) string { + return regexp.QuoteMeta(strings.Replace(GetReservationsForResources, "/*SLICE:resources*/?", placeholders, 1)) +} + +func TestGetReservationsForResourcesScansRawRows(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { mock.ExpectClose(); require.NoError(t, db.Close()) }) + + expiration := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC) + mock.ExpectQuery(reservationQuery("?,?")). + WithArgs("port", "network"). + WillReturnRows(sqlmock.NewRows(reservationColumns). + AddRow("r1", "p", expiration, "port", 3). + AddRow("r2", "", expiration, "network", -2). + AddRow("r3", "p", expiration, "port", nil)). + RowsWillBeClosed() + + rows, err := New(db).GetReservationsForResources(context.Background(), []string{"port", "network"}) + require.NoError(t, err) + require.Equal(t, []GetReservationsForResourcesRow{ + {ReservationID: "r1", ProjectID: sql.NullString{String: "p", Valid: true}, Expiration: sql.NullTime{Time: expiration, Valid: true}, Resource: "port", Amount: sql.NullInt32{Int32: 3, Valid: true}}, + {ReservationID: "r2", ProjectID: sql.NullString{Valid: true}, Expiration: sql.NullTime{Time: expiration, Valid: true}, Resource: "network", Amount: sql.NullInt32{Int32: -2, Valid: true}}, + {ReservationID: "r3", ProjectID: sql.NullString{String: "p", Valid: true}, Expiration: sql.NullTime{Time: expiration, Valid: true}, Resource: "port"}, + }, rows) + require.NoError(t, mock.ExpectationsWereMet()) +} + +// An empty resource list matches nothing, like upstream Neutron's +// get_reservations_for_resources, instead of widening to every resource. +func TestGetReservationsForResourcesEmptyListMatchesNothing(t *testing.T) { + for name, resources := range map[string][]string{"nil": nil, "empty": {}} { + t.Run(name, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { mock.ExpectClose(); require.NoError(t, db.Close()) }) + mock.ExpectQuery(reservationQuery("NULL")).WithoutArgs(). + WillReturnRows(sqlmock.NewRows(reservationColumns)).RowsWillBeClosed() + + rows, err := New(db).GetReservationsForResources(context.Background(), resources) + require.NoError(t, err) + require.Empty(t, rows) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} + +func TestGetReservationsForResourcesPropagatesErrors(t *testing.T) { + for _, kind := range []string{"query", "scan", "iteration", "timeout"} { + t.Run(kind, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { mock.ExpectClose(); require.NoError(t, db.Close()) }) + + exp := mock.ExpectQuery(reservationQuery("?")).WithArgs("port") + rows := sqlmock.NewRows(reservationColumns) + switch kind { + case "query": + exp.WillReturnError(errors.New("read failure")) + case "scan": + exp.WillReturnRows(rows.AddRow("r", "p", time.Now(), "port", "malformed")).RowsWillBeClosed() + case "iteration": + exp.WillReturnRows(rows.AddRow("r", "p", time.Now(), "port", 1).RowError(0, errors.New("interrupted"))).RowsWillBeClosed() + case "timeout": + exp.WillDelayFor(time.Second).WillReturnRows(rows) + } + timeout := time.Second + if kind == "timeout" { + timeout = 10 * time.Millisecond + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + got, err := New(db).GetReservationsForResources(ctx, []string{"port"}) + require.Error(t, err) + require.Nil(t, got) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/schema/neutron/schema.sql b/schema/neutron/schema.sql index e4c3146..c9777ae 100644 --- a/schema/neutron/schema.sql +++ b/schema/neutron/schema.sql @@ -242,3 +242,19 @@ CREATE TABLE `tag` varchar(255) NOT NULL, PRIMARY KEY (`standard_attr_id`, `tag`) ); + +-- Neutron quota reservation storage (local query fixture, not a migration). +-- Mirrors upstream neutron/db/quota/models.py: no index on expiration or +-- project_id (HasProjectNoIndex); InnoDB indexes reservation_id for the FK. +CREATE TABLE `reservations` ( + `id` varchar(36) NOT NULL PRIMARY KEY, + `project_id` varchar(255) DEFAULT NULL, + `expiration` datetime DEFAULT NULL +); +CREATE TABLE `resourcedeltas` ( + `resource` varchar(255) NOT NULL, + `reservation_id` varchar(36) NOT NULL, + `amount` int DEFAULT NULL, + PRIMARY KEY (`resource`, `reservation_id`), + FOREIGN KEY (`reservation_id`) REFERENCES `reservations` (`id`) ON DELETE CASCADE +); diff --git a/tests/neutron_quotas_integration_test.go b/tests/neutron_quotas_integration_test.go new file mode 100644 index 0000000..b254efb --- /dev/null +++ b/tests/neutron_quotas_integration_test.go @@ -0,0 +1,117 @@ +//go:build integration + +package tests + +import ( + "database/sql" + "fmt" + "testing" + + "github.com/stretchr/testify/require" + "github.com/vexxhost/openstackdb/internal/testutil" + neutron "github.com/vexxhost/openstackdb/neutron/db" +) + +func TestNeutronReservationsForResources(t *testing.T) { + ctx := t.Context() + db := testutil.NewMySQLContainer(t, "neutron-reservations", "../sql/neutron/schema.sql") + + // Expirations are relative to the database clock, which is what the query + // compares against, so the test does not depend on the runner's clock. + testutil.SeedSQL(t, db, + "INSERT INTO reservations VALUES ('active-a', 'a', UTC_TIMESTAMP() + INTERVAL 1 HOUR)", + "INSERT INTO reservations VALUES ('active-empty', '', UTC_TIMESTAMP() + INTERVAL 1 HOUR)", + "INSERT INTO reservations VALUES ('active-null-owner', NULL, UTC_TIMESTAMP() + INTERVAL 1 HOUR)", + "INSERT INTO reservations VALUES ('expired', 'a', UTC_TIMESTAMP() - INTERVAL 1 HOUR)", + "INSERT INTO reservations VALUES ('null-expiration', 'a', NULL)", + "INSERT INTO resourcedeltas VALUES ('port', 'active-a', 3)", + "INSERT INTO resourcedeltas VALUES ('network', 'active-a', -2)", + "INSERT INTO resourcedeltas VALUES ('router', 'active-a', 1)", + "INSERT INTO resourcedeltas VALUES ('port', 'active-empty', NULL)", + "INSERT INTO resourcedeltas VALUES ('port', 'active-null-owner', 5)", + "INSERT INTO resourcedeltas VALUES ('port', 'expired', 7)", + "INSERT INTO resourcedeltas VALUES ('port', 'null-expiration', 9)", + ) + + q := neutron.New(db) + rows, err := q.GetReservationsForResources(ctx, []string{"port", "network"}) + require.NoError(t, err) + + type delta struct { + ID, Project, Resource string + Amount sql.NullInt32 + } + var got []delta + for _, r := range rows { + require.True(t, r.ProjectID.Valid) + require.True(t, r.Expiration.Valid) + got = append(got, delta{r.ReservationID, r.ProjectID.String, r.Resource, r.Amount}) + } + // Ordered by project, resource, reservation. Expired, NULL-expiration, + // NULL-owner and unrequested-resource rows are excluded; empty-string + // owners are kept, matching GetQuotas and GetResourceCountsByProject. + require.Equal(t, []delta{ + {"active-empty", "", "port", sql.NullInt32{}}, + {"active-a", "a", "network", sql.NullInt32{Int32: -2, Valid: true}}, + {"active-a", "a", "port", sql.NullInt32{Int32: 3, Valid: true}}, + }, got) + + rows, err = q.GetReservationsForResources(ctx, nil) + require.NoError(t, err) + require.Empty(t, rows) +} + +func TestNeutronQuotaOwnersAndOrdering(t *testing.T) { + ctx := t.Context() + db := testutil.NewMySQLContainer(t, "neutron-quotas", "../sql/neutron/schema.sql") + + // Each table owns its counts without requiring parent rows or quota overrides. + inserts := map[string]string{ + "floatingip": "INSERT INTO floatingips (id, project_id, floating_ip_address, floating_network_id, floating_port_id, status, standard_attr_id) VALUES (?, ?, '192.0.2.1', 'parent-network', 'parent-port', 'DOWN', 1)", + "network": "INSERT INTO networks (id, project_id, status, standard_attr_id) VALUES (?, ?, 'DOWN', 1)", + "port": "INSERT INTO ports (id, project_id, network_id, mac_address, admin_state_up, status, device_id, device_owner, standard_attr_id) VALUES (?, ?, 'parent-network', '00:00:00:00:00:01', 0, 'DOWN', '', '', 1)", + "router": "INSERT INTO routers (id, project_id, status, standard_attr_id) VALUES (?, ?, 'DOWN', 1)", + "security_group": "INSERT INTO securitygroups (id, project_id, standard_attr_id) VALUES (?, ?, 1)", + "security_group_rule": "INSERT INTO securitygrouprules (id, project_id, security_group_id, standard_attr_id) VALUES (?, ?, 'parent-group', 1)", + "subnet": "INSERT INTO subnets (id, project_id, network_id, ip_version, cidr, standard_attr_id) VALUES (?, ?, 'parent-network', 4, '192.0.2.0/24', 1)", + "rbac_policy": "INSERT INTO networkrbacs (id, project_id, object_id, target_project, action) VALUES (?, ?, 'parent-network', 'target-owner', 'access_as_shared')", + "subnetpool": "INSERT INTO subnetpools (id, project_id, ip_version, default_prefixlen, min_prefixlen, max_prefixlen, standard_attr_id) VALUES (?, ?, 4, 24, 8, 32, 1)", + } + var expected []neutron.GetResourceCountsByProjectRow + for resource, insert := range inserts { + for j, owner := range []any{"a", "a", "b", "", nil} { + _, err := db.ExecContext(ctx, insert, fmt.Sprintf("%s-%d", resource, j), owner) + require.NoError(t, err) + } + expected = append(expected, + neutron.GetResourceCountsByProjectRow{ProjectID: sql.NullString{String: "a", Valid: true}, Resource: resource, Cnt: 2}, + neutron.GetResourceCountsByProjectRow{ProjectID: sql.NullString{String: "b", Valid: true}, Resource: resource, Cnt: 1}, + // Empty-string owners (for example L3 HA networks and ports) are kept. + neutron.GetResourceCountsByProjectRow{ProjectID: sql.NullString{Valid: true}, Resource: resource, Cnt: 1}) + } + q := neutron.New(db) + usage, err := q.GetResourceCountsByProject(ctx) + require.NoError(t, err) + require.ElementsMatch(t, expected, usage) + + // Duplicate project/resource rows are kept and ordered by id, so callers + // that collapse duplicates see a stable result. + testutil.SeedSQL(t, db, + "INSERT INTO quotas VALUES ('q3', 'b', 'port', 10)", + "INSERT INTO quotas VALUES ('q2', 'a', 'port', 42)", + "INSERT INTO quotas VALUES ('q1', 'a', 'port', -1)", + "INSERT INTO quotas VALUES ('q4', 'a', 'network', NULL)", + "INSERT INTO quotas VALUES ('q5', '', 'port', 0)", + "INSERT INTO quotas VALUES ('q6', NULL, 'port', 5)", + ) + limits, err := q.GetQuotas(ctx) + require.NoError(t, err) + port := sql.NullString{String: "port", Valid: true} + require.Equal(t, []neutron.GetQuotasRow{ + {ProjectID: sql.NullString{Valid: true}, Resource: port, Limit: sql.NullInt32{Valid: true}}, + {ProjectID: sql.NullString{String: "a", Valid: true}, Resource: sql.NullString{String: "network", Valid: true}}, + {ProjectID: sql.NullString{String: "a", Valid: true}, Resource: port, Limit: sql.NullInt32{Int32: -1, Valid: true}}, + {ProjectID: sql.NullString{String: "a", Valid: true}, Resource: port, Limit: sql.NullInt32{Int32: 42, Valid: true}}, + {ProjectID: sql.NullString{String: "b", Valid: true}, Resource: port, Limit: sql.NullInt32{Int32: 10, Valid: true}}, + }, limits) +}