diff --git a/API.md b/API.md index f264cfe..faf34cf 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` | @@ -60,8 +63,9 @@ 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`. - [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,8 @@ 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. +- 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 @@ -94,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 4a5e3b0..cf2a8fd 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,9 @@ 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` | | `heat/db` | `StackGetAll` | | `ironic/db` | `GetNodeList` | @@ -51,6 +52,10 @@ 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. 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/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/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..3731330 100644 --- a/db.go +++ b/db.go @@ -24,9 +24,28 @@ 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 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 { return nil, fmt.Errorf("connection options must not be negative") } @@ -47,9 +66,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 } 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/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/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/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 e350060..4bfaa2d 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" @@ -64,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) @@ -99,6 +107,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")