diff --git a/API.md b/API.md index af8487d..faf34cf 100644 --- a/API.md +++ b/API.md @@ -63,7 +63,7 @@ with identical semantics upstream. - [Nova main database API](https://github.com/openstack/nova/blob/master/nova/db/main/api.py): `instance_get_by_uuid`, `instance_get_all_by_filters`, `service_get_all`, `compute_node_get_all`. - [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`. +- [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`, `quota_get_all_by_project`, `quota_usage_get_all_by_project`, `quota_class_get_defaults`. - [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`. @@ -82,6 +82,7 @@ with identical semantics upstream. - 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. +- Cinder quota queries exclude NULL and empty project IDs because Cinder quota rows belong to Keystone projects. The older Cinder exporter quota queries are unchanged. - No cross-cell routing or historic schema negotiation is performed. Nova archive access is explicitly selected with `InstanceFilters.Archive`. ## Resource lifecycle and metadata reads @@ -99,3 +100,38 @@ 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. + +### Cinder quota accounting + +| Go operation | Upstream naming source | Scope | +| --- | --- | --- | +| `QuotaGetAllByProject` | [Cinder `quota_get_all_by_project`](https://github.com/openstack/cinder/blob/master/cinder/db/api.py) | Reads `quotas` for every project at once; raw rows instead of a per-project dictionary. | +| `QuotaUsageGetAllByProject` | [Cinder `quota_usage_get_all_by_project`](https://github.com/openstack/cinder/blob/master/cinder/db/api.py) | Reads `quota_usages` for every project at once; raw `in_use`/`reserved` rows. Usage is Cinder's cached accounting. | +| `QuotaClassGetDefaults` | [Cinder `quota_class_get_defaults`](https://github.com/openstack/cinder/blob/master/cinder/db/api.py) | Reads the `default` class from `quota_classes`; raw rows instead of a dictionary. | +| `ParseQuotaResource` | Cinder `VolumeTypeResource` key format in [`cinder/quota.py`](https://github.com/openstack/cinder/blob/master/cinder/quota.py) | Splits `_` keys. Hand-written; re-check the global resource list on Cinder upgrades. | + +Rows with a NULL or empty project ID are excluded: Cinder quota rows belong to +Keystone projects. Results are ordered by project, resource and row ID, so +callers that collapse duplicates get a stable result. Duplicate active rows, +NULL limits, zero limits and `-1` (unlimited) are returned as stored. The +existing exporter queries `QuotaGetProjectLimits`, `QuotaUsageGetAll` and +`QuotaGetAllWithUsage` keep their behavior. + +Limits and usage are read separately, so usage also covers projects that have +no limit overrides. Usage is Cinder's cached accounting, not a live count of +volumes and snapshots. It can drift from the real resources until Cinder +refreshes it. `reserved` already counts open reservations. + +Resource keys are either global (`volumes`, `gigabytes`, `snapshots`, `backups`, +`backup_gigabytes`, `per_volume_gigabytes`, `groups`) or per volume type, built +as `_` where the part is `volumes`, `gigabytes` or +`snapshots`. Per-type and global accounting describe the same allocations, so +never add them together. Use `ParseQuotaResource` to split a key. Don't split +on the first underscore: that misreads `backup_gigabytes` and type names that +contain underscores. Keys hold the volume type's name, not its ID. Cinder +rewrites them when a type is renamed, but keeps them after a type is deleted, +so a parsed name may not match any type from `VolumeTypeGetAll`. + +Callers resolve effective limits: a project override, then the `default` class, +then service configuration. The `quota_classes` schema is a test and +code-generation fixture, not a production migration. diff --git a/README.md b/README.md index 46520c4..cf2a8fd 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ repository objects. Placement queries live under `placement/objects`. | --- | --- | | `nova/db/main` | `InstanceGetAllByFilters`, `InstanceGetByUUID`, `ServiceGetAll`, `ComputeNodeGetAll` | | `nova/db/api` | `FlavorGetAll`, `AggregateGetAll`, quota projections | -| `cinder/db` | `ServiceGetAll`, `QuotaGetProjectLimits`, `QuotaUsageGetAll` | +| `cinder/db` | `ServiceGetAll`, `QuotaGetProjectLimits`, `QuotaUsageGetAll`, `QuotaGetAllByProject`, `QuotaUsageGetAllByProject`, `QuotaClassGetDefaults` | | `glance/db` | `ImageGetAll` | | `designate/db` | `ZoneGetAll`, `RecordsetCountByZone`, `RecordsetGetAllWithStatus` | | `keystone/db` | `ListProjects`, `ListDomains`, `ListUsers` | diff --git a/cinder/db/models.go b/cinder/db/models.go index 2b8fe37..434ae62 100644 --- a/cinder/db/models.go +++ b/cinder/db/models.go @@ -20,6 +20,17 @@ type Quota struct { Allocated sql.NullInt32 } +type QuotaClass struct { + ID int32 + CreatedAt sql.NullTime + UpdatedAt sql.NullTime + DeletedAt sql.NullTime + Deleted sql.NullBool + ClassName sql.NullString + Resource sql.NullString + HardLimit sql.NullInt32 +} + type QuotaUsage struct { CreatedAt sql.NullTime UpdatedAt sql.NullTime diff --git a/cinder/db/queries.sql b/cinder/db/queries.sql index cef8eef..fb95292 100644 --- a/cinder/db/queries.sql +++ b/cinder/db/queries.sql @@ -93,3 +93,32 @@ WHERE -- name: VolumeGetAll :many SELECT id, project_id, size, volume_type_id, status, created_at, deleted_at FROM volumes WHERE deleted = 0; + +-- name: QuotaGetAllByProject :many +-- Upstream quota_get_all_by_project for every project. The table holds both +-- aggregate resources (volumes, gigabytes, ...) and per-volume-type resources +-- (volumes_, ...). See ParseQuotaResource. Rows with a NULL or empty +-- project ID are excluded. +SELECT project_id, resource, hard_limit +FROM quotas +WHERE deleted = 0 AND project_id <> '' +ORDER BY project_id, resource, id; + +-- name: QuotaUsageGetAllByProject :many +-- Upstream quota_usage_get_all_by_project for every project. These are Cinder's +-- cached usage counters, not a live count of volumes and snapshots, and can +-- drift until Cinder refreshes them. reserved already counts open reservations. +-- Aggregate and per-volume-type resources describe the same allocations, so +-- never add them together. +SELECT project_id, resource, in_use, reserved +FROM quota_usages +WHERE deleted = 0 AND project_id <> '' +ORDER BY project_id, resource, id; + +-- name: QuotaClassGetDefaults :many +-- Upstream quota_class_get_defaults. The persisted 'default' class overrides +-- service configuration defaults. +SELECT resource, hard_limit +FROM quota_classes +WHERE deleted = 0 AND class_name = 'default' +ORDER BY resource, id; diff --git a/cinder/db/queries.sql.go b/cinder/db/queries.sql.go index d1f8e1b..ee3ff51 100644 --- a/cinder/db/queries.sql.go +++ b/cinder/db/queries.sql.go @@ -10,6 +10,83 @@ import ( "database/sql" ) +const QuotaClassGetDefaults = `-- name: QuotaClassGetDefaults :many +SELECT resource, hard_limit +FROM quota_classes +WHERE deleted = 0 AND class_name = 'default' +ORDER BY resource, id +` + +type QuotaClassGetDefaultsRow struct { + Resource sql.NullString + HardLimit sql.NullInt32 +} + +// Upstream quota_class_get_defaults. The persisted 'default' class overrides +// service configuration defaults. +func (q *Queries) QuotaClassGetDefaults(ctx context.Context) ([]QuotaClassGetDefaultsRow, error) { + rows, err := q.db.QueryContext(ctx, QuotaClassGetDefaults) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuotaClassGetDefaultsRow + for rows.Next() { + var i QuotaClassGetDefaultsRow + if err := rows.Scan(&i.Resource, &i.HardLimit); 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 QuotaGetAllByProject = `-- name: QuotaGetAllByProject :many +SELECT project_id, resource, hard_limit +FROM quotas +WHERE deleted = 0 AND project_id <> '' +ORDER BY project_id, resource, id +` + +type QuotaGetAllByProjectRow struct { + ProjectID sql.NullString + Resource string + HardLimit sql.NullInt32 +} + +// Upstream quota_get_all_by_project for every project. The table holds both +// aggregate resources (volumes, gigabytes, ...) and per-volume-type resources +// (volumes_, ...). See ParseQuotaResource. Rows with a NULL or empty +// project ID are excluded. +func (q *Queries) QuotaGetAllByProject(ctx context.Context) ([]QuotaGetAllByProjectRow, error) { + rows, err := q.db.QueryContext(ctx, QuotaGetAllByProject) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuotaGetAllByProjectRow + for rows.Next() { + var i QuotaGetAllByProjectRow + if err := rows.Scan(&i.ProjectID, &i.Resource, &i.HardLimit); 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 QuotaGetAllWithUsage = `-- name: QuotaGetAllWithUsage :many SELECT q.project_id, @@ -142,6 +219,53 @@ func (q *Queries) QuotaUsageGetAll(ctx context.Context) ([]QuotaUsageGetAllRow, return items, nil } +const QuotaUsageGetAllByProject = `-- name: QuotaUsageGetAllByProject :many +SELECT project_id, resource, in_use, reserved +FROM quota_usages +WHERE deleted = 0 AND project_id <> '' +ORDER BY project_id, resource, id +` + +type QuotaUsageGetAllByProjectRow struct { + ProjectID sql.NullString + Resource sql.NullString + InUse int32 + Reserved int32 +} + +// Upstream quota_usage_get_all_by_project for every project. These are Cinder's +// cached usage counters, not a live count of volumes and snapshots, and can +// drift until Cinder refreshes them. reserved already counts open reservations. +// Aggregate and per-volume-type resources describe the same allocations, so +// never add them together. +func (q *Queries) QuotaUsageGetAllByProject(ctx context.Context) ([]QuotaUsageGetAllByProjectRow, error) { + rows, err := q.db.QueryContext(ctx, QuotaUsageGetAllByProject) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuotaUsageGetAllByProjectRow + for rows.Next() { + var i QuotaUsageGetAllByProjectRow + if err := rows.Scan( + &i.ProjectID, + &i.Resource, + &i.InUse, + &i.Reserved, + ); 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 ServiceGetAll = `-- name: ServiceGetAll :many SELECT uuid, diff --git a/cinder/db/quota_resources.go b/cinder/db/quota_resources.go new file mode 100644 index 0000000..1bc9f65 --- /dev/null +++ b/cinder/db/quota_resources.go @@ -0,0 +1,44 @@ +package cinder + +import "strings" + +// quotaGlobalResources are the resource keys Cinder registers without a +// volume type: VolumeTypeQuotaEngine's global quotas plus GroupQuotaEngine's +// groups, which share the same tables. +var quotaGlobalResources = map[string]bool{ + "volumes": true, + "per_volume_gigabytes": true, + "snapshots": true, + "gigabytes": true, + "backups": true, + "backup_gigabytes": true, + "groups": true, +} + +// quotaVolumeTypeParts are the only resources Cinder tracks per volume type. +var quotaVolumeTypeParts = []string{"volumes", "gigabytes", "snapshots"} + +// ParseQuotaResource splits a Cinder quota resource key into its base resource +// and volume type name. +// +// Cinder builds per-volume-type keys as "_", where part +// is volumes, gigabytes or snapshots. A global key such as "backup_gigabytes" +// returns an empty volumeType. Volume type names may contain underscores, so +// "gigabytes_fast_ssd" returns ("gigabytes", "fast_ssd"). +// +// The key holds the volume type's name, not its ID. Cinder rewrites keys when a +// type is renamed, but keeps them after a type is deleted, so a parsed name +// may not match any current volume type. +// +// ok is false for keys Cinder does not register. base is then the whole key. +func ParseQuotaResource(key string) (base, volumeType string, ok bool) { + if quotaGlobalResources[key] { + return key, "", true + } + for _, part := range quotaVolumeTypeParts { + if name, found := strings.CutPrefix(key, part+"_"); found && name != "" { + return part, name, true + } + } + return key, "", false +} diff --git a/cinder/db/quota_resources_test.go b/cinder/db/quota_resources_test.go new file mode 100644 index 0000000..6b74384 --- /dev/null +++ b/cinder/db/quota_resources_test.go @@ -0,0 +1,36 @@ +package cinder + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestParseQuotaResource(t *testing.T) { + for _, tc := range []struct { + key, base, volumeType string + ok bool + }{ + {"volumes", "volumes", "", true}, + {"gigabytes", "gigabytes", "", true}, + {"snapshots", "snapshots", "", true}, + {"backups", "backups", "", true}, + {"backup_gigabytes", "backup_gigabytes", "", true}, + {"per_volume_gigabytes", "per_volume_gigabytes", "", true}, + {"groups", "groups", "", true}, + {"volumes_lvm", "volumes", "lvm", true}, + {"gigabytes_fast_ssd", "gigabytes", "fast_ssd", true}, + {"snapshots___DEFAULT__", "snapshots", "__DEFAULT__", true}, + {"volumes_backup_gigabytes", "volumes", "backup_gigabytes", true}, + {"backups_lvm", "backups_lvm", "", false}, + {"volumes_", "volumes_", "", false}, + {"", "", "", false}, + } { + t.Run(tc.key, func(t *testing.T) { + base, volumeType, ok := ParseQuotaResource(tc.key) + require.Equal(t, tc.base, base) + require.Equal(t, tc.volumeType, volumeType) + require.Equal(t, tc.ok, ok) + }) + } +} diff --git a/schema/cinder/schema.sql b/schema/cinder/schema.sql index 41b348d..82d8c56 100644 --- a/schema/cinder/schema.sql +++ b/schema/cinder/schema.sql @@ -151,3 +151,15 @@ CREATE TABLE `is_public` tinyint (1) DEFAULT NULL, `description` varchar(255) DEFAULT NULL ); + +-- Cinder 27.0.0 (2025.2) QuotaClass model; test/code-generation schema only. +CREATE TABLE `quota_classes` ( + `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, + `created_at` datetime DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + `deleted_at` datetime DEFAULT NULL, + `deleted` tinyint (1) DEFAULT NULL, + `class_name` varchar(255) DEFAULT NULL, + `resource` varchar(300) DEFAULT NULL, + `hard_limit` int DEFAULT NULL +); diff --git a/tests/cinder_quotas_test.go b/tests/cinder_quotas_test.go new file mode 100644 index 0000000..eb80a6c --- /dev/null +++ b/tests/cinder_quotas_test.go @@ -0,0 +1,79 @@ +//go:build integration + +package tests + +import ( + "database/sql" + "os" + "testing" + + "github.com/stretchr/testify/require" + cinder "github.com/vexxhost/openstackdb/cinder/db" + "github.com/vexxhost/openstackdb/internal/testutil" +) + +// The fixture includes soft-deleted rows, NULL and empty project IDs, a +// duplicate active limit, NULL limits, and usage for a deleted volume type. +func TestCinderQuotas(t *testing.T) { + ctx := t.Context() + db := testutil.NewMySQLContainer(t, "cinder-quotas", "../sql/cinder/schema.sql", "../sql/cinder/indexes.sql") + fixture, err := os.ReadFile("fixtures/cinder_quotas.sql") + require.NoError(t, err) + testutil.SeedSQL(t, db, string(fixture)) + q := cinder.New(db) + s := func(v string) sql.NullString { return sql.NullString{String: v, Valid: true} } + n := func(v int32) sql.NullInt32 { return sql.NullInt32{Int32: v, Valid: true} } + limit := func(project, resource string, hard sql.NullInt32) cinder.QuotaGetAllByProjectRow { + return cinder.QuotaGetAllByProjectRow{ProjectID: s(project), Resource: resource, HardLimit: hard} + } + use := func(project, resource string, inUse, reserved int32) cinder.QuotaUsageGetAllByProjectRow { + return cinder.QuotaUsageGetAllByProjectRow{ProjectID: s(project), Resource: s(resource), InUse: inUse, Reserved: reserved} + } + def := func(resource string, hard sql.NullInt32) cinder.QuotaClassGetDefaultsRow { + return cinder.QuotaClassGetDefaultsRow{Resource: s(resource), HardLimit: hard} + } + + // Raw rows in project, resource, id order. Duplicates are kept. + limits, err := q.QuotaGetAllByProject(ctx) + require.NoError(t, err) + require.Equal(t, []cinder.QuotaGetAllByProjectRow{ + limit("bad-null-limit", "volumes", sql.NullInt32{}), + limit("project-a", "gigabytes_fast_ssd", n(300)), + limit("project-a", "snapshots", n(-1)), + limit("project-a", "volumes", n(0)), + limit("project-a", "volumes", n(9)), + }, limits) + + usage, err := q.QuotaUsageGetAllByProject(ctx) + require.NoError(t, err) + require.Equal(t, []cinder.QuotaUsageGetAllByProjectRow{ + use("project-a", "gigabytes", 100, 15), + use("project-a", "gigabytes_fast_ssd", 80, 10), + use("project-a", "volumes", 2, 3), + use("project-a", "volumes_retired", 1, 0), + use("usage-only", "backups", 7, 4), + }, usage) + + defaults, err := q.QuotaClassGetDefaults(ctx) + require.NoError(t, err) + require.Equal(t, []cinder.QuotaClassGetDefaultsRow{ + def("backups", sql.NullInt32{}), + def("snapshots_fast_ssd", n(8)), + def("volumes", n(20)), + }, defaults) + + // Keys for deleted types parse, but match no current volume type. + types, err := q.VolumeTypeGetAll(ctx) + require.NoError(t, err) + current := map[string]bool{} + for _, vt := range types { + current[vt.Name.String] = true + } + matched := map[string]bool{} + for _, row := range usage { + if base, volumeType, ok := cinder.ParseQuotaResource(row.Resource.String); ok && volumeType != "" { + matched[base+"/"+volumeType] = current[volumeType] + } + } + require.Equal(t, map[string]bool{"gigabytes/fast_ssd": true, "volumes/retired": false}, matched) +} diff --git a/tests/fixtures/cinder_quotas.sql b/tests/fixtures/cinder_quotas.sql new file mode 100644 index 0000000..4f1cd74 --- /dev/null +++ b/tests/fixtures/cinder_quotas.sql @@ -0,0 +1,22 @@ +-- Cinder quota accounting. Type names are encoded whole in resource keys. +-- 'retired' is a deleted type whose keys remain. NULL and empty project IDs +-- are excluded by the quota queries. +INSERT INTO volume_types (id, name, deleted) VALUES + ('type-1', 'fast_ssd', 0), ('type-2', '__DEFAULT__', 0), + ('type-gone', 'retired', 1); +INSERT INTO quotas (id, project_id, resource, hard_limit, deleted) VALUES + (1, 'project-a', 'volumes', 0, 0), (2, 'project-a', 'snapshots', -1, 0), + (3, 'project-a', 'gigabytes_fast_ssd', 300, 0), + (4, 'project-a', 'volumes', 999, 1), (5, 'bad-null-limit', 'volumes', NULL, 0), + (6, NULL, 'volumes', 5, 0), (7, '', 'volumes', 6, 0), + (8, 'project-a', 'volumes', 9, 0); +INSERT INTO quota_usages (id, project_id, resource, in_use, reserved, deleted) VALUES + (1, 'project-a', 'volumes', 2, 3, 0), (2, 'project-a', 'gigabytes', 100, 15, 0), + (3, 'project-a', 'gigabytes_fast_ssd', 80, 10, 0), + (4, 'usage-only', 'backups', 7, 4, 0), (5, 'project-a', 'volumes', 999, 99, 1), + (6, 'project-a', 'volumes_retired', 1, 0, 0), + (7, NULL, 'volumes', 1, 1, 0), (8, '', 'volumes', 1, 1, 0); +INSERT INTO quota_classes (id, class_name, resource, hard_limit, deleted) VALUES + (1, 'default', 'volumes', 20, 0), (2, 'default', 'snapshots_fast_ssd', 8, 0), + (3, 'default', 'volumes', 999, 1), (4, 'custom', 'volumes', 1, 0), + (5, 'default', 'backups', NULL, 0); diff --git a/tests/queries_test.go b/tests/queries_test.go index ee83701..4bfaa2d 100644 --- a/tests/queries_test.go +++ b/tests/queries_test.go @@ -66,6 +66,12 @@ func TestCinderQueries(t *testing.T) { require.NoError(t, err, "QuotaUsageGetAll") _, err = q.QuotaGetAllWithUsage(ctx) require.NoError(t, err, "QuotaGetAllWithUsage") + _, err = q.QuotaGetAllByProject(ctx) + require.NoError(t, err, "QuotaGetAllByProject") + _, err = q.QuotaUsageGetAllByProject(ctx) + require.NoError(t, err, "QuotaUsageGetAllByProject") + _, err = q.QuotaClassGetDefaults(ctx) + require.NoError(t, err, "QuotaClassGetDefaults") _, err = q.VolumeTypeGetAll(ctx) require.NoError(t, err, "VolumeTypeGetAll") _, err = q.SnapshotCount(ctx)