Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
12 changes: 12 additions & 0 deletions neutron/db/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 23 additions & 1 deletion neutron/db/queries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
71 changes: 71 additions & 0 deletions neutron/db/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

97 changes: 97 additions & 0 deletions neutron/db/quotas_test.go
Original file line number Diff line number Diff line change
@@ -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())
})
}
}
16 changes: 16 additions & 0 deletions schema/neutron/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
Loading