diff --git a/API.md b/API.md index f264cfe..33d70fa 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` | @@ -34,6 +37,7 @@ with identical semantics upstream. | `keystone/db` | `GetGroupMetrics` | `ListGroups` | | `magnum/db` | `GetClusterMetrics` | `GetClusterList` | | `manila/db` | `GetShareMetrics` | `ShareGetAllWithInstances` | +| `manila/db` | — | `ShareGetInventory` | | `neutron/db` | `GetAgents` | `GetAgents` | | `neutron/db` | `GetHARouterAgentPortBindingsWithAgents` | `GetHARouterAgentPortBindingsWithAgents` | | `neutron/db` | `GetRouters` | `GetRouters` | @@ -62,9 +66,10 @@ with identical semantics upstream. - [Nova API database](https://github.com/openstack/nova/tree/master/nova/db/api) and [objects](https://github.com/openstack/nova/tree/master/nova/objects): flavor, aggregate, and quota data. - [Cinder DB API](https://github.com/openstack/cinder/blob/master/cinder/db/api.py): `volume_get`, `volume_get_all`, `volume_type_get_all`, `service_get_all`. - [Glance DB API](https://github.com/openstack/glance/blob/master/glance/db/sqlalchemy/api.py): `image_get`, `image_get_all`. +- [Designate storage](https://github.com/openstack/designate/blob/master/designate/storage/sqlalchemy/__init__.py): `find_zones`, `find_recordsets`, `count_recordsets`. The library also follows [Designate's UUID conversion](https://github.com/openstack/designate/blob/master/designate/storage/sqlalchemy/types.py) and [recordset status precedence](https://github.com/openstack/designate/blob/master/designate/objects/recordset.py). - [Ironic DB API](https://github.com/openstack/ironic/blob/master/ironic/db/api.py) and [Magnum DB API](https://github.com/openstack/magnum/blob/master/magnum/db/api.py): `get_node_list`, `get_cluster_list`. - [Heat DB API](https://github.com/openstack/heat/blob/master/heat/db/api.py): `stack_get_all`. -- [Manila DB API](https://github.com/openstack/manila/blob/master/manila/db/api.py): share operations; the instance join is an explicit extension. +- [Manila DB API](https://github.com/openstack/manila/blob/master/manila/db/api.py): share operations and quota, quota usage and quota class reads; the instance join is an explicit extension. [`Share.instance`](https://github.com/openstack/manila/blob/master/manila/db/sqlalchemy/models.py) defines the representative-instance rules that `ShareGetInventory` follows. - [Keystone backends](https://github.com/openstack/keystone/tree/master/keystone): `list_*` resource, identity, and catalog operations are grouped into a single read projection package here. - [Neutron database plugins](https://github.com/openstack/neutron/tree/master/neutron/db): `get_*` resource operations; capacity/count queries are extensions. - [Octavia repositories](https://github.com/openstack/octavia/blob/master/octavia/db/repositories.py): resource repositories with `get_all` operations. @@ -77,6 +82,7 @@ with identical semantics upstream. - Current exporter queries retain their existing deleted/hidden/status predicates; they are not full upstream administrative listings. - Errors are Go/database errors; absent single resources return `sql.ErrNoRows` rather than Python service-specific exceptions. - Aggregate queries such as `QuotaGetAllWithUsage`, `GetResourceProviderInventories`, and `GetResourceCountsByProject` are explicitly library extensions. +- Designate returns canonical zone and recordset UUIDs and excludes soft-deleted zones. `RecordsetCountByZone` includes zero-count zones and can run without reading individual records. `RecordsetGetAllWithStatus` uses the child precedence `ERROR`, `PENDING`, `ACTIVE`, `DELETED` and returns `ACTIVE` for an empty recordset. Recordsets with a NULL `zone_id` have no visible zone and are omitted. - No cross-cell routing or historic schema negotiation is performed. Nova archive access is explicitly selected with `InstanceFilters.Archive`. ## Resource lifecycle and metadata reads @@ -94,3 +100,78 @@ 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. + +### Manila share inventory + +| Go operation | Upstream naming source | Scope | +| --- | --- | --- | +| `ShareGetInventory` | [Manila `Share.instance`](https://github.com/openstack/manila/blob/master/manila/db/sqlalchemy/models.py) | One row per logical share with its representative instance. Status ranking copies `constants.TRANSITIONAL_STATUSES` and must be re-checked on Manila upgrades. | + +`ShareGetInventory` returns exactly one row per nondeleted logical share, +including shares without instances. It follows Manila's `Share.instance`: +status precedence, active-replica preference, and the replication-change +exception. Instance ID resolves otherwise unspecified ties (including writable +replication with multiple active replicas). Status, AZ and type all come from +the same representative instance, chosen in one pass with window functions. +The status ranking copies Manila's `constants.TRANSITIONAL_STATUSES`; re-check +it against `manila/common/constants.py` and `Share.instance` in +`manila/db/sqlalchemy/models.py` when moving to a new Manila release, because a +missing transitional status would be preferred over the listed ones. Retained +`is_soft_deleted` shares remain in inventory, preserving the existing deletion +scope; row-soft-deleted shares and instances are excluded. This is inventory, +not quota accounting. + +The MariaDB integration test is `TestManilaInventory` in `tests/` and requires Docker. + +### Manila quota accounting + +The Manila quota queries are named after Manila's DB API functions. Each one +reads every project at once rather than one project, and returns raw rows +rather than a per-project dictionary: + +| Go operation | Upstream naming source | Table | +| --- | --- | --- | +| `QuotaGetAllByProject` | [Manila `quota_get_all_by_project`](https://github.com/openstack/manila/blob/master/manila/db/sqlalchemy/api.py) | `quotas` | +| `QuotaGetAllByProjectAndUser` | [Manila `quota_get_all_by_project_and_user`](https://github.com/openstack/manila/blob/master/manila/db/sqlalchemy/api.py) | `project_user_quotas` | +| `QuotaGetAllByProjectAndShareType` | [Manila `quota_get_all_by_project_and_share_type`](https://github.com/openstack/manila/blob/master/manila/db/sqlalchemy/api.py) | `project_share_type_quotas` | +| `QuotaClassGetDefault` | [Manila `quota_class_get_default`](https://github.com/openstack/manila/blob/master/manila/db/sqlalchemy/api.py) | `quota_classes` | +| `QuotaUsageGetAllByProject` | [Manila `quota_usage_get_all_by_project`](https://github.com/openstack/manila/blob/master/manila/db/sqlalchemy/api.py) | `quota_usages`, `share_type_id IS NULL` | +| `QuotaUsageGetAllByProjectAndShareType` | [Manila `quota_usage_get_all_by_project_and_share_type`](https://github.com/openstack/manila/blob/master/manila/db/sqlalchemy/api.py) | `quota_usages`, `share_type_id IS NOT NULL` | + +Rows with a NULL or empty project ID are excluded. Results are ordered by their +identifying columns and row ID, so callers that collapse duplicates get a +stable result. + +Usage rows are not aggregated. `in_use` and `reserved` are returned as stored, +including NULL, so callers can tell malformed rows from zero usage. To get +Manila's project totals, sum `QuotaUsageGetAllByProject` rows by project and +resource; this matches `_quota_usage_get_all`, which sums users (including +legacy NULL-user rows) and excludes share-type rows. Share-type accounting +describes the same allocations: read it with +`QuotaUsageGetAllByProjectAndShareType` and never add it to project totals. +`reserved` already counts open reservations; do not add `reservations` again. + +The share-type queries left-join `share_types`. When a share type is deleted or +missing, its limits and usage are still returned with a NULL `ShareTypeName`, so +per-type totals reconcile with project totals. + +The generated quota models use `sql.NullInt32` for integer `Deleted` fields: +active rows have `0`, and soft-deleted rows store their row ID. The fixture has +no database default for these columns; Manila supplies `0` through SQLAlchemy. +Share and instance deletion markers retain their existing string representation. + +User overrides live in `project_user_quotas`, separately from project overrides +in `quotas` and type overrides in `project_share_type_quotas`. Never sum limits +or substitute user limits for project limits. A NULL hard limit is preserved +so callers can detect invalid or legacy data; Manila enforces numeric limits, +using `-1` for unlimited. The caller supplies service configuration defaults +and resolves missing limits: share-type override → project override → +persisted `default` class → service configuration. Non-default classes need +request-context information that these database tables do not provide. + +These queries read Manila's quota accounting, not rebuilt object counts or +physical storage use. Stale accounting, including usage left after object +removal, remains visible until Manila reconciles it. No writes or reconciliation +are performed. The schema files are test fixtures, not production migrations. + +The MariaDB integration test is `TestManilaQuotas` in `tests/` and requires Docker. diff --git a/README.md b/README.md index 4a5e3b0..e4f559d 100644 --- a/README.md +++ b/README.md @@ -16,11 +16,12 @@ repository objects. Placement queries live under `placement/objects`. | `nova/db/api` | `FlavorGetAll`, `AggregateGetAll`, quota projections | | `cinder/db` | `ServiceGetAll`, `QuotaGetProjectLimits`, `QuotaUsageGetAll` | | `glance/db` | `ImageGetAll` | +| `designate/db` | `ZoneGetAll`, `RecordsetCountByZone`, `RecordsetGetAllWithStatus` | | `keystone/db` | `ListProjects`, `ListDomains`, `ListUsers` | | `heat/db` | `StackGetAll` | | `ironic/db` | `GetNodeList` | | `magnum/db` | `GetClusterList` | -| `manila/db` | `ShareGetAllWithInstances` | +| `manila/db` | `ShareGetAllWithInstances`, `ShareGetInventory`, `QuotaGetAllByProject`, `QuotaUsageGetAllByProject` | | `neutron/db` | `GetAgents`, `GetHARouterAgentPortBindingsWithAgents`, `GetRouters` | | `octavia/db/repositories` | `PoolRepository`, `LoadBalancerRepository`, `AmphoraRepository` | | `placement/objects` | Resource provider inventory and allocation projections | @@ -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/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/internal/testutil/integration.go b/internal/testutil/integration.go index 693a07e..8658fd1 100644 --- a/internal/testutil/integration.go +++ b/internal/testutil/integration.go @@ -11,6 +11,7 @@ import ( "testing" "time" + _ "github.com/go-sql-driver/mysql" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/mariadb" "github.com/vexxhost/openstackdb/schema" diff --git a/manila/db/inventory_test.go b/manila/db/inventory_test.go new file mode 100644 index 0000000..084bfb3 --- /dev/null +++ b/manila/db/inventory_test.go @@ -0,0 +1,77 @@ +package manila + +import ( + "context" + "database/sql" + "regexp" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/require" +) + +func TestShareInventoryScansValues(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + mock.ExpectQuery(regexp.QuoteMeta(ShareGetInventory)).WillReturnRows( + sqlmock.NewRows([]string{"id", "name", "project_id", "size", "share_proto", "status", "share_type", "share_type_name", "availability_zone"}). + AddRow("no-instance", nil, nil, nil, nil, nil, "", "", ""). + AddRow("share", "name", "project", 10, "NFS", "available", "type", "gold", "zone"), + ).RowsWillBeClosed() + rows, err := New(db).ShareGetInventory(context.Background()) + require.NoError(t, err) + require.Equal(t, []ShareGetInventoryRow{ + {ID: "no-instance"}, + { + ID: "share", Name: sql.NullString{String: "name", Valid: true}, + ProjectID: sql.NullString{String: "project", Valid: true}, + Size: sql.NullInt32{Int32: 10, Valid: true}, + ShareProto: sql.NullString{String: "NFS", Valid: true}, + Status: sql.NullString{String: "available", Valid: true}, + ShareType: "type", ShareTypeName: "gold", AvailabilityZone: "zone", + }, + }, rows) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestShareInventoryErrors(t *testing.T) { + for _, scenario := range []string{"empty", "query", "scan", "iteration", "canceled"} { + t.Run(scenario, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if scenario == "canceled" { + cancel() + } else { + query := mock.ExpectQuery(regexp.QuoteMeta(ShareGetInventory)) + rows := sqlmock.NewRows([]string{"id", "name", "project_id", "size", "share_proto", "status", "share_type", "share_type_name", "availability_zone"}) + switch scenario { + case "query": + query.WillReturnError(sql.ErrConnDone) + case "scan": + query.WillReturnRows(rows.AddRow("s", nil, nil, "invalid integer", nil, nil, "", "", "")).RowsWillBeClosed() + case "iteration": + query.WillReturnRows(rows.AddRow("s", nil, nil, nil, nil, nil, "", "", "").RowError(0, sql.ErrConnDone)).RowsWillBeClosed() + default: + query.WillReturnRows(rows).RowsWillBeClosed() + } + } + rows, err := New(db).ShareGetInventory(ctx) + switch scenario { + case "empty": + require.NoError(t, err) + require.Empty(t, rows) + case "query", "iteration": + require.ErrorIs(t, err, sql.ErrConnDone) + case "canceled": + require.ErrorIs(t, err, context.Canceled) + default: + require.Error(t, err) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/manila/db/models.go b/manila/db/models.go index a7bbf1d..026cce1 100644 --- a/manila/db/models.go +++ b/manila/db/models.go @@ -17,6 +17,67 @@ type AvailabilityZone struct { Name sql.NullString } +type ProjectShareTypeQuota struct { + CreatedAt sql.NullTime + UpdatedAt sql.NullTime + DeletedAt sql.NullTime + Deleted sql.NullInt32 + ID int32 + ProjectID string + ShareTypeID string + Resource string + HardLimit sql.NullInt32 +} + +type ProjectUserQuota struct { + CreatedAt sql.NullTime + UpdatedAt sql.NullTime + DeletedAt sql.NullTime + Deleted sql.NullInt32 + ID int32 + ProjectID string + UserID string + Resource string + HardLimit sql.NullInt32 +} + +type Quota struct { + CreatedAt sql.NullTime + UpdatedAt sql.NullTime + DeletedAt sql.NullTime + Deleted sql.NullInt32 + ID int32 + ProjectID sql.NullString + Resource sql.NullString + HardLimit sql.NullInt32 +} + +type QuotaClass struct { + CreatedAt sql.NullTime + UpdatedAt sql.NullTime + DeletedAt sql.NullTime + Deleted sql.NullInt32 + ID int32 + ClassName sql.NullString + Resource sql.NullString + HardLimit sql.NullInt32 +} + +type QuotaUsage struct { + CreatedAt sql.NullTime + UpdatedAt sql.NullTime + DeletedAt sql.NullTime + Deleted sql.NullInt32 + ID int32 + ProjectID sql.NullString + UserID sql.NullString + ShareTypeID sql.NullString + Resource sql.NullString + InUse sql.NullInt32 + Reserved sql.NullInt32 + UntilRefresh sql.NullInt32 +} + type Share struct { CreatedAt sql.NullTime UpdatedAt sql.NullTime diff --git a/manila/db/queries.sql b/manila/db/queries.sql index 6560c37..296ccbc 100644 --- a/manila/db/queries.sql +++ b/manila/db/queries.sql @@ -1,6 +1,6 @@ -- name: ShareGetAllWithInstances :many --- Get share metrics for openstack_sharev2_share_gb and openstack_sharev2_share_status --- This joins shares with share_instances to get current status and availability zone info +-- Multi-instance view: returns one row per nondeleted instance (or a NULL +-- instance for shares with none). Use ShareGetInventory for logical shares. SELECT s.id, s.display_name as name, @@ -17,3 +17,145 @@ LEFT JOIN share_types st ON si.share_type_id = st.id AND st.deleted = 'False' LEFT JOIN availability_zones az ON si.availability_zone_id = az.id AND az.deleted = 'False' WHERE s.deleted = 'False' ORDER BY s.created_at; + +-- name: ShareGetInventory :many +-- One row per nondeleted logical share, including shares with no instances. +-- Mirrors Manila Share.instance (manila/db/sqlalchemy/models.py): sort by +-- status, then prefer active replicas unless the first sorted status is +-- replication_change. Reverting sorts before replication_change, so its +-- presence restores active-replica preference. Upstream leaves equal or +-- unknown-status ties to relationship order; instance ID is the stable tie +-- break. All instance metadata comes from the same winner. +-- The transitional ranks copy constants.TRANSITIONAL_STATUSES in order +-- (manila/common/constants.py, checked against master 2026-11-18). Re-check both +-- files when moving to a new Manila release: a missing transitional status +-- falls into the unlisted bucket and would be preferred over transitional ones. +-- Retain the existing inventory deletion scope, including retained shares with +-- is_soft_deleted set; that flag is distinct from the row's deleted marker. +SELECT + s.id, + s.display_name as name, + s.project_id, + s.size, + s.share_proto, + si.status, + COALESCE(si.share_type_id, '') as share_type, + COALESCE(st.name, '') as share_type_name, + COALESCE(az.name, '') as availability_zone +FROM shares s +LEFT JOIN ( + SELECT + flagged.share_id, + flagged.status, + flagged.share_type_id, + flagged.availability_zone_id, + ROW_NUMBER() OVER ( + PARTITION BY flagged.share_id + ORDER BY + CASE + WHEN flagged.has_reverting = 1 OR flagged.has_replication_change = 0 + THEN CASE WHEN flagged.replica_state = 'active' THEN 0 ELSE 1 END + ELSE 0 + END, + CASE flagged.status + WHEN 'reverting' THEN 0 + WHEN 'replication_change' THEN 1 + WHEN 'migrating' THEN 2 + WHEN 'server_migrating' THEN 3 + WHEN 'available' THEN 4 + WHEN 'error' THEN 5 + -- Unlisted, nontransitional statuses (6) precede transitional ones. + WHEN 'creating' THEN 7 + WHEN 'deleting' THEN 8 + WHEN 'manage_starting' THEN 9 + WHEN 'unmanage_starting' THEN 10 + WHEN 'extending' THEN 11 + WHEN 'shrinking' THEN 12 + WHEN 'migrating_to' THEN 13 + WHEN 'restoring' THEN 14 + WHEN 'server_migrating_to' THEN 15 + WHEN 'backup_restoring' THEN 16 + WHEN 'backup_creating' THEN 17 + WHEN 'ensuring' THEN 18 + WHEN 'reverting_to_snapshot' THEN 19 + ELSE 6 + END, + flagged.id + ) AS preference + FROM ( + SELECT + candidate.id, + candidate.share_id, + candidate.status, + candidate.replica_state, + candidate.share_type_id, + candidate.availability_zone_id, + MAX(CASE WHEN candidate.status = 'reverting' THEN 1 ELSE 0 END) + OVER (PARTITION BY candidate.share_id) AS has_reverting, + MAX(CASE WHEN candidate.status = 'replication_change' THEN 1 ELSE 0 END) + OVER (PARTITION BY candidate.share_id) AS has_replication_change + FROM share_instances candidate + WHERE candidate.deleted = 'False' + ) flagged +) si ON si.share_id = s.id AND si.preference = 1 +LEFT JOIN share_types st ON si.share_type_id = st.id AND st.deleted = 'False' +LEFT JOIN availability_zones az ON si.availability_zone_id = az.id AND az.deleted = 'False' +WHERE s.deleted = 'False' +ORDER BY s.created_at, s.id; + +-- name: QuotaGetAllByProject :many +-- Upstream quota_get_all_by_project for every project. Quota tables use +-- integer soft deletion: active = 0, soft-deleted = the row's id. +SELECT project_id, resource, hard_limit +FROM quotas +WHERE deleted = 0 AND project_id <> '' +ORDER BY project_id, resource, id; + +-- name: QuotaGetAllByProjectAndUser :many +-- Upstream quota_get_all_by_project_and_user for every project and user. +-- User overrides are independent of project and share-type overrides. +SELECT project_id, user_id, resource, hard_limit +FROM project_user_quotas +WHERE deleted = 0 AND project_id <> '' +ORDER BY project_id, user_id, resource, id; + +-- name: QuotaGetAllByProjectAndShareType :many +-- Upstream quota_get_all_by_project_and_share_type for every project and type. +-- share_type_name is NULL when the share type is deleted or missing; the +-- override row is still returned. +SELECT q.project_id, q.share_type_id, st.name AS share_type_name, + q.resource, q.hard_limit +FROM project_share_type_quotas q +LEFT JOIN share_types st ON st.id = q.share_type_id AND st.deleted = 'False' +WHERE q.deleted = 0 AND q.project_id <> '' +ORDER BY q.project_id, q.share_type_id, q.resource, q.id; + +-- name: QuotaClassGetDefault :many +-- Upstream quota_class_get_default. 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; + +-- name: QuotaUsageGetAllByProject :many +-- Upstream quota_usage_get_all_by_project for every project: raw per-user rows +-- with share_type_id IS NULL. Share-type accounting describes the same +-- allocations and is excluded; it is read by QuotaUsageGetAllByProjectAndShareType. +-- A NULL user_id is a legacy project-level row. in_use and reserved are +-- returned as stored, including NULL. +SELECT project_id, user_id, resource, in_use, reserved +FROM quota_usages +WHERE deleted = 0 AND project_id <> '' AND share_type_id IS NULL +ORDER BY project_id, resource, user_id, id; + +-- name: QuotaUsageGetAllByProjectAndShareType :many +-- Upstream quota_usage_get_all_by_project_and_share_type for every project and +-- type: raw rows with a share_type_id. share_type_name is NULL when the share +-- type is deleted or missing; the accounting row is still returned. +SELECT u.project_id, u.share_type_id, st.name AS share_type_name, u.user_id, + u.resource, u.in_use, u.reserved +FROM quota_usages u +LEFT JOIN share_types st ON st.id = u.share_type_id AND st.deleted = 'False' +WHERE u.deleted = 0 AND u.project_id <> '' AND u.share_type_id IS NOT NULL +ORDER BY u.project_id, u.share_type_id, u.resource, u.user_id, u.id; diff --git a/manila/db/queries.sql.go b/manila/db/queries.sql.go index ea13a21..8d55cb0 100644 --- a/manila/db/queries.sql.go +++ b/manila/db/queries.sql.go @@ -10,6 +10,276 @@ import ( "database/sql" ) +const QuotaClassGetDefault = `-- name: QuotaClassGetDefault :many +SELECT resource, hard_limit +FROM quota_classes +WHERE deleted = 0 AND class_name = 'default' +ORDER BY resource, id +` + +type QuotaClassGetDefaultRow struct { + Resource sql.NullString + HardLimit sql.NullInt32 +} + +// Upstream quota_class_get_default. The persisted 'default' class overrides +// service configuration defaults. +func (q *Queries) QuotaClassGetDefault(ctx context.Context) ([]QuotaClassGetDefaultRow, error) { + rows, err := q.db.QueryContext(ctx, QuotaClassGetDefault) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuotaClassGetDefaultRow + for rows.Next() { + var i QuotaClassGetDefaultRow + 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 sql.NullString + HardLimit sql.NullInt32 +} + +// Upstream quota_get_all_by_project for every project. Quota tables use +// integer soft deletion: active = 0, soft-deleted = the row's id. +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 QuotaGetAllByProjectAndShareType = `-- name: QuotaGetAllByProjectAndShareType :many +SELECT q.project_id, q.share_type_id, st.name AS share_type_name, + q.resource, q.hard_limit +FROM project_share_type_quotas q +LEFT JOIN share_types st ON st.id = q.share_type_id AND st.deleted = 'False' +WHERE q.deleted = 0 AND q.project_id <> '' +ORDER BY q.project_id, q.share_type_id, q.resource, q.id +` + +type QuotaGetAllByProjectAndShareTypeRow struct { + ProjectID string + ShareTypeID string + ShareTypeName sql.NullString + Resource string + HardLimit sql.NullInt32 +} + +// Upstream quota_get_all_by_project_and_share_type for every project and type. +// share_type_name is NULL when the share type is deleted or missing; the +// override row is still returned. +func (q *Queries) QuotaGetAllByProjectAndShareType(ctx context.Context) ([]QuotaGetAllByProjectAndShareTypeRow, error) { + rows, err := q.db.QueryContext(ctx, QuotaGetAllByProjectAndShareType) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuotaGetAllByProjectAndShareTypeRow + for rows.Next() { + var i QuotaGetAllByProjectAndShareTypeRow + if err := rows.Scan( + &i.ProjectID, + &i.ShareTypeID, + &i.ShareTypeName, + &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 QuotaGetAllByProjectAndUser = `-- name: QuotaGetAllByProjectAndUser :many +SELECT project_id, user_id, resource, hard_limit +FROM project_user_quotas +WHERE deleted = 0 AND project_id <> '' +ORDER BY project_id, user_id, resource, id +` + +type QuotaGetAllByProjectAndUserRow struct { + ProjectID string + UserID string + Resource string + HardLimit sql.NullInt32 +} + +// Upstream quota_get_all_by_project_and_user for every project and user. +// User overrides are independent of project and share-type overrides. +func (q *Queries) QuotaGetAllByProjectAndUser(ctx context.Context) ([]QuotaGetAllByProjectAndUserRow, error) { + rows, err := q.db.QueryContext(ctx, QuotaGetAllByProjectAndUser) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuotaGetAllByProjectAndUserRow + for rows.Next() { + var i QuotaGetAllByProjectAndUserRow + if err := rows.Scan( + &i.ProjectID, + &i.UserID, + &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 QuotaUsageGetAllByProject = `-- name: QuotaUsageGetAllByProject :many +SELECT project_id, user_id, resource, in_use, reserved +FROM quota_usages +WHERE deleted = 0 AND project_id <> '' AND share_type_id IS NULL +ORDER BY project_id, resource, user_id, id +` + +type QuotaUsageGetAllByProjectRow struct { + ProjectID sql.NullString + UserID sql.NullString + Resource sql.NullString + InUse sql.NullInt32 + Reserved sql.NullInt32 +} + +// Upstream quota_usage_get_all_by_project for every project: raw per-user rows +// with share_type_id IS NULL. Share-type accounting describes the same +// allocations and is excluded; it is read by QuotaUsageGetAllByProjectAndShareType. +// A NULL user_id is a legacy project-level row. in_use and reserved are +// returned as stored, including NULL. +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.UserID, + &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 QuotaUsageGetAllByProjectAndShareType = `-- name: QuotaUsageGetAllByProjectAndShareType :many +SELECT u.project_id, u.share_type_id, st.name AS share_type_name, u.user_id, + u.resource, u.in_use, u.reserved +FROM quota_usages u +LEFT JOIN share_types st ON st.id = u.share_type_id AND st.deleted = 'False' +WHERE u.deleted = 0 AND u.project_id <> '' AND u.share_type_id IS NOT NULL +ORDER BY u.project_id, u.share_type_id, u.resource, u.user_id, u.id +` + +type QuotaUsageGetAllByProjectAndShareTypeRow struct { + ProjectID sql.NullString + ShareTypeID sql.NullString + ShareTypeName sql.NullString + UserID sql.NullString + Resource sql.NullString + InUse sql.NullInt32 + Reserved sql.NullInt32 +} + +// Upstream quota_usage_get_all_by_project_and_share_type for every project and +// type: raw rows with a share_type_id. share_type_name is NULL when the share +// type is deleted or missing; the accounting row is still returned. +func (q *Queries) QuotaUsageGetAllByProjectAndShareType(ctx context.Context) ([]QuotaUsageGetAllByProjectAndShareTypeRow, error) { + rows, err := q.db.QueryContext(ctx, QuotaUsageGetAllByProjectAndShareType) + if err != nil { + return nil, err + } + defer rows.Close() + var items []QuotaUsageGetAllByProjectAndShareTypeRow + for rows.Next() { + var i QuotaUsageGetAllByProjectAndShareTypeRow + if err := rows.Scan( + &i.ProjectID, + &i.ShareTypeID, + &i.ShareTypeName, + &i.UserID, + &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 ShareGetAllWithInstances = `-- name: ShareGetAllWithInstances :many SELECT s.id, @@ -41,8 +311,8 @@ type ShareGetAllWithInstancesRow struct { AvailabilityZone string } -// Get share metrics for openstack_sharev2_share_gb and openstack_sharev2_share_status -// This joins shares with share_instances to get current status and availability zone info +// Multi-instance view: returns one row per nondeleted instance (or a NULL +// instance for shares with none). Use ShareGetInventory for logical shares. func (q *Queries) ShareGetAllWithInstances(ctx context.Context) ([]ShareGetAllWithInstancesRow, error) { rows, err := q.db.QueryContext(ctx, ShareGetAllWithInstances) if err != nil { @@ -75,3 +345,134 @@ func (q *Queries) ShareGetAllWithInstances(ctx context.Context) ([]ShareGetAllWi } return items, nil } + +const ShareGetInventory = `-- name: ShareGetInventory :many +SELECT + s.id, + s.display_name as name, + s.project_id, + s.size, + s.share_proto, + si.status, + COALESCE(si.share_type_id, '') as share_type, + COALESCE(st.name, '') as share_type_name, + COALESCE(az.name, '') as availability_zone +FROM shares s +LEFT JOIN ( + SELECT + flagged.share_id, + flagged.status, + flagged.share_type_id, + flagged.availability_zone_id, + ROW_NUMBER() OVER ( + PARTITION BY flagged.share_id + ORDER BY + CASE + WHEN flagged.has_reverting = 1 OR flagged.has_replication_change = 0 + THEN CASE WHEN flagged.replica_state = 'active' THEN 0 ELSE 1 END + ELSE 0 + END, + CASE flagged.status + WHEN 'reverting' THEN 0 + WHEN 'replication_change' THEN 1 + WHEN 'migrating' THEN 2 + WHEN 'server_migrating' THEN 3 + WHEN 'available' THEN 4 + WHEN 'error' THEN 5 + -- Unlisted, nontransitional statuses (6) precede transitional ones. + WHEN 'creating' THEN 7 + WHEN 'deleting' THEN 8 + WHEN 'manage_starting' THEN 9 + WHEN 'unmanage_starting' THEN 10 + WHEN 'extending' THEN 11 + WHEN 'shrinking' THEN 12 + WHEN 'migrating_to' THEN 13 + WHEN 'restoring' THEN 14 + WHEN 'server_migrating_to' THEN 15 + WHEN 'backup_restoring' THEN 16 + WHEN 'backup_creating' THEN 17 + WHEN 'ensuring' THEN 18 + WHEN 'reverting_to_snapshot' THEN 19 + ELSE 6 + END, + flagged.id + ) AS preference + FROM ( + SELECT + candidate.id, + candidate.share_id, + candidate.status, + candidate.replica_state, + candidate.share_type_id, + candidate.availability_zone_id, + MAX(CASE WHEN candidate.status = 'reverting' THEN 1 ELSE 0 END) + OVER (PARTITION BY candidate.share_id) AS has_reverting, + MAX(CASE WHEN candidate.status = 'replication_change' THEN 1 ELSE 0 END) + OVER (PARTITION BY candidate.share_id) AS has_replication_change + FROM share_instances candidate + WHERE candidate.deleted = 'False' + ) flagged +) si ON si.share_id = s.id AND si.preference = 1 +LEFT JOIN share_types st ON si.share_type_id = st.id AND st.deleted = 'False' +LEFT JOIN availability_zones az ON si.availability_zone_id = az.id AND az.deleted = 'False' +WHERE s.deleted = 'False' +ORDER BY s.created_at, s.id +` + +type ShareGetInventoryRow struct { + ID string + Name sql.NullString + ProjectID sql.NullString + Size sql.NullInt32 + ShareProto sql.NullString + Status sql.NullString + ShareType string + ShareTypeName string + AvailabilityZone string +} + +// One row per nondeleted logical share, including shares with no instances. +// Mirrors Manila Share.instance (manila/db/sqlalchemy/models.py): sort by +// status, then prefer active replicas unless the first sorted status is +// replication_change. Reverting sorts before replication_change, so its +// presence restores active-replica preference. Upstream leaves equal or +// unknown-status ties to relationship order; instance ID is the stable tie +// break. All instance metadata comes from the same winner. +// The transitional ranks copy constants.TRANSITIONAL_STATUSES in order +// (manila/common/constants.py, checked against master 2026-11-18). Re-check both +// files when moving to a new Manila release: a missing transitional status +// falls into the unlisted bucket and would be preferred over transitional ones. +// Retain the existing inventory deletion scope, including retained shares with +// is_soft_deleted set; that flag is distinct from the row's deleted marker. +func (q *Queries) ShareGetInventory(ctx context.Context) ([]ShareGetInventoryRow, error) { + rows, err := q.db.QueryContext(ctx, ShareGetInventory) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ShareGetInventoryRow + for rows.Next() { + var i ShareGetInventoryRow + if err := rows.Scan( + &i.ID, + &i.Name, + &i.ProjectID, + &i.Size, + &i.ShareProto, + &i.Status, + &i.ShareType, + &i.ShareTypeName, + &i.AvailabilityZone, + ); 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/manila/db/quotas_test.go b/manila/db/quotas_test.go new file mode 100644 index 0000000..e6dd3cd --- /dev/null +++ b/manila/db/quotas_test.go @@ -0,0 +1,120 @@ +package manila + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "regexp" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/require" +) + +func TestQuotaQueriesPropagateErrors(t *testing.T) { + for _, tc := range []struct { + name, query string + columns []string + read func(context.Context, *Queries) (any, error) + }{ + {"defaults", QuotaClassGetDefault, []string{"resource", "hard_limit"}, func(ctx context.Context, q *Queries) (any, error) { return q.QuotaClassGetDefault(ctx) }}, + {"projects", QuotaGetAllByProject, []string{"project_id", "resource", "hard_limit"}, func(ctx context.Context, q *Queries) (any, error) { return q.QuotaGetAllByProject(ctx) }}, + {"users", QuotaGetAllByProjectAndUser, []string{"project_id", "user_id", "resource", "hard_limit"}, func(ctx context.Context, q *Queries) (any, error) { return q.QuotaGetAllByProjectAndUser(ctx) }}, + {"share types", QuotaGetAllByProjectAndShareType, []string{"project_id", "share_type_id", "share_type_name", "resource", "hard_limit"}, func(ctx context.Context, q *Queries) (any, error) { return q.QuotaGetAllByProjectAndShareType(ctx) }}, + {"project usage", QuotaUsageGetAllByProject, []string{"project_id", "user_id", "resource", "in_use", "reserved"}, func(ctx context.Context, q *Queries) (any, error) { return q.QuotaUsageGetAllByProject(ctx) }}, + {"share type usage", QuotaUsageGetAllByProjectAndShareType, []string{"project_id", "share_type_id", "share_type_name", "user_id", "resource", "in_use", "reserved"}, func(ctx context.Context, q *Queries) (any, error) { + return q.QuotaUsageGetAllByProjectAndShareType(ctx) + }}, + } { + for _, scenario := range []string{"empty", "query error", "scan error", "iteration error", "canceled"} { + t.Run(tc.name+"/"+scenario, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if scenario == "canceled" { + cancel() + } else { + query := mock.ExpectQuery(regexp.QuoteMeta(tc.query)) + rows := sqlmock.NewRows(tc.columns) + switch scenario { + case "query error": + query.WillReturnError(sql.ErrConnDone) + case "scan error": + values := make([]driver.Value, len(tc.columns)) + for i := range values { + values[i] = "invalid integer" + } + query.WillReturnRows(rows.AddRow(values...)).RowsWillBeClosed() + case "iteration error": + // Fail before scanning; the generated query must return rows.Err. + values := make([]driver.Value, len(tc.columns)) + for i, column := range tc.columns { + switch column { + case "hard_limit", "in_use", "reserved": + values[i] = 1 + default: + values[i] = "x" + } + } + rows.AddRow(values...).RowError(0, errors.New("iteration failed")) + query.WillReturnRows(rows).RowsWillBeClosed() + default: + query.WillReturnRows(rows).RowsWillBeClosed() + } + } + got, err := tc.read(ctx, New(db)) + if scenario == "empty" { + require.NoError(t, err) + require.Empty(t, got) + } else { + require.Error(t, err) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } + } +} + +// Usage rows are returned raw: NULL amounts stay NULL rather than becoming zero, +// and a deleted share type surfaces as a NULL name instead of a dropped row. +func TestQuotaUsageScansRawValues(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + q := New(db) + ctx := context.Background() + str := func(s string) sql.NullString { return sql.NullString{String: s, Valid: true} } + num := func(n int32) sql.NullInt32 { return sql.NullInt32{Int32: n, Valid: true} } + + mock.ExpectQuery(regexp.QuoteMeta(QuotaUsageGetAllByProject)).WillReturnRows( + sqlmock.NewRows([]string{"project_id", "user_id", "resource", "in_use", "reserved"}). + AddRow("p", "u", "shares", 3, 1). + AddRow("p", nil, "shares", nil, nil)) + usage, err := q.QuotaUsageGetAllByProject(ctx) + require.NoError(t, err) + require.Equal(t, []QuotaUsageGetAllByProjectRow{ + {ProjectID: str("p"), UserID: str("u"), Resource: str("shares"), InUse: num(3), Reserved: num(1)}, + {ProjectID: str("p"), Resource: str("shares")}, + }, usage) + + mock.ExpectQuery(regexp.QuoteMeta(QuotaUsageGetAllByProjectAndShareType)).WillReturnRows( + sqlmock.NewRows([]string{"project_id", "share_type_id", "share_type_name", "user_id", "resource", "in_use", "reserved"}). + AddRow("p", "t", "gold", nil, "shares", 8, 2). + AddRow("p", "t-deleted", nil, nil, "shares", 5, 0)) + typed, err := q.QuotaUsageGetAllByProjectAndShareType(ctx) + require.NoError(t, err) + require.Equal(t, []QuotaUsageGetAllByProjectAndShareTypeRow{ + {ProjectID: str("p"), ShareTypeID: str("t"), ShareTypeName: str("gold"), Resource: str("shares"), InUse: num(8), Reserved: num(2)}, + {ProjectID: str("p"), ShareTypeID: str("t-deleted"), Resource: str("shares"), InUse: num(5), Reserved: num(0)}, + }, typed) + + mock.ExpectQuery(regexp.QuoteMeta(QuotaClassGetDefault)).WillReturnRows( + sqlmock.NewRows([]string{"resource", "hard_limit"}).AddRow("shares", nil)) + defaults, err := q.QuotaClassGetDefault(ctx) + require.NoError(t, err) + require.Equal(t, []QuotaClassGetDefaultRow{{Resource: str("shares")}}, defaults) + require.NoError(t, mock.ExpectationsWereMet()) +} 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/schema/manila/schema.sql b/schema/manila/schema.sql index 23f57f8..2026877 100644 --- a/schema/manila/schema.sql +++ b/schema/manila/schema.sql @@ -87,3 +87,72 @@ CREATE TABLE CONSTRAINT `si_share_fk` FOREIGN KEY (`share_id`) REFERENCES `shares` (`id`), CONSTRAINT `si_st_id_fk` FOREIGN KEY (`share_type_id`) REFERENCES `share_types` (`id`) ); + +-- Manila project quota overrides (manila/db/sqlalchemy/models.py Quota). +-- Quota tables inherit integer SoftDeleteMixin: active = 0, soft-deleted = id. +-- Manila 2025.2 migrations use SQLAlchemy default=0, not server_default; +-- raw SQL inserts must supply deleted explicitly for active rows. +CREATE TABLE + `quotas` ( + `created_at` datetime(6) DEFAULT NULL, + `updated_at` datetime(6) DEFAULT NULL, + `deleted_at` datetime(6) DEFAULT NULL, + `deleted` INTEGER, + `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, + `project_id` varchar(255) DEFAULT NULL, + `resource` varchar(255) DEFAULT NULL, + `hard_limit` int DEFAULT NULL + ); + +CREATE TABLE + `quota_usages` ( + `created_at` datetime(6) DEFAULT NULL, + `updated_at` datetime(6) DEFAULT NULL, + `deleted_at` datetime(6) DEFAULT NULL, + `deleted` INTEGER, + `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, + `project_id` varchar(255) DEFAULT NULL, + `user_id` varchar(255) DEFAULT NULL, + `share_type_id` varchar(36) DEFAULT NULL, + `resource` varchar(255) DEFAULT NULL, + `in_use` int DEFAULT NULL, + `reserved` int DEFAULT NULL, + `until_refresh` int DEFAULT NULL + ); + +-- Manila 2025.2 keeps user and share-type overrides in separate tables. +CREATE TABLE `project_user_quotas` ( + `created_at` datetime(6) DEFAULT NULL, + `updated_at` datetime(6) DEFAULT NULL, + `deleted_at` datetime(6) DEFAULT NULL, + `deleted` INTEGER, + `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, + `project_id` varchar(255) NOT NULL, + `user_id` varchar(255) NOT NULL, + `resource` varchar(255) NOT NULL, + `hard_limit` int DEFAULT NULL +); + +CREATE TABLE `project_share_type_quotas` ( + `created_at` datetime(6) DEFAULT NULL, + `updated_at` datetime(6) DEFAULT NULL, + `deleted_at` datetime(6) DEFAULT NULL, + `deleted` INTEGER, + `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, + `project_id` varchar(255) NOT NULL, + `share_type_id` varchar(36) NOT NULL, + `resource` varchar(255) NOT NULL, + `hard_limit` int DEFAULT NULL, + CONSTRAINT `pstq_share_type_fk` FOREIGN KEY (`share_type_id`) REFERENCES `share_types` (`id`) +); + +CREATE TABLE `quota_classes` ( + `created_at` datetime(6) DEFAULT NULL, + `updated_at` datetime(6) DEFAULT NULL, + `deleted_at` datetime(6) DEFAULT NULL, + `deleted` INTEGER, + `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, + `class_name` varchar(255) DEFAULT NULL, + `resource` varchar(255) DEFAULT NULL, + `hard_limit` int DEFAULT NULL +); 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/fixtures/manila_inventory.sql b/tests/fixtures/manila_inventory.sql new file mode 100644 index 0000000..1c79371 --- /dev/null +++ b/tests/fixtures/manila_inventory.sql @@ -0,0 +1,60 @@ +-- Disposable inventory fixture: no production use. +INSERT INTO share_types(id,name,deleted) VALUES('type-1','gold','False'),('type-2','silver','False'),('type-deleted','old','type-deleted'); +INSERT INTO availability_zones(id,name,deleted) VALUES('az-1','zone-1','False'),('az-2','zone-2','False'),('az-deleted','old','az-deleted'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('zero','zero','project-1','10','NFS','False','0',NULL,NULL); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('single','single','project-2','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('single-0','single','available',NULL,'type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('identical','identical','project-1','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('identical-0','identical','available',NULL,'type-1','az-1','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('identical-1','identical','available',NULL,'type-2','az-2','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('different','different','project-2','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('different-0','different','error',NULL,'type-2','az-2','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('different-1','different','available',NULL,'type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('replicated','replicated','project-1','10','NFS','False','0','readable',NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('replicated-0','replicated','available','in_sync','type-2','az-2','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('replicated-1','replicated','error','active','type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('promotion','promotion','project-2','10','NFS','False','0','readable',NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('promotion-0','promotion','available','active','type-2','az-2','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('promotion-1','promotion','replication_change','in_sync','type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('reverting-promotion','reverting-promotion','project-1','10','NFS','False','0','readable',NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('reverting-promotion-0','reverting-promotion','available','active','type-1','az-1','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('reverting-promotion-1','reverting-promotion','replication_change','in_sync','type-2','az-2','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('reverting-promotion-2','reverting-promotion','reverting','in_sync','type-2','az-2','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('reverting','reverting','project-2','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('reverting-0','reverting','reverting',NULL,'type-1','az-1','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('reverting-1','reverting','replication_change',NULL,'type-2','az-2','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('writable','writable','project-1','10','NFS','False','0','writable',NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('writable-0','writable','available','active','type-1','az-1','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('writable-1','writable','available','active','type-2','az-2','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('migration','migration','project-2','10','NFS','False','0',NULL,'migration_in_progress'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('migration-0','migration','migrating_to',NULL,'type-2','az-2','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('migration-1','migration','migrating',NULL,'type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('server-migration','server-migration','project-1','10','NFS','False','0',NULL,'migration_in_progress'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('server-migration-0','server-migration','server_migrating_to',NULL,'type-2','az-2','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('server-migration-1','server-migration','server_migrating',NULL,'type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('fallback','fallback','project-2','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('fallback-0','fallback','creating',NULL,'type-1','az-1','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('fallback-1','fallback','deleting',NULL,'type-2','az-2','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('unknown','unknown','project-1','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('unknown-0','unknown','ensuring',NULL,'type-2','az-2','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('unknown-1','unknown','inactive',NULL,'type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('unknown-tie','unknown-tie','project-2','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('unknown-tie-0','unknown-tie','unknown_z',NULL,'type-1','az-1','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('unknown-tie-1','unknown-tie','unknown_a',NULL,'type-2','az-2','False','0'); +-- reverting_to_snapshot is transitional and ranks after creating. +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('snapshot-revert','snapshot-revert','project-2','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('snapshot-revert-0','snapshot-revert','reverting_to_snapshot',NULL,'type-1','az-1','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('snapshot-revert-1','snapshot-revert','creating',NULL,'type-2','az-2','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('deleted-instance','deleted-instance','project-1','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('deleted-instance-0','deleted-instance','available',NULL,'type-1','az-1','False','0'); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('deleted-instance-1','deleted-instance','reverting',NULL,'type-2','az-2','removed','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('deleted-only','deleted-only','project-2','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('deleted-only-0','deleted-only','available',NULL,'type-2','az-2','removed','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('deleted-metadata','deleted-metadata','project-1','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('deleted-metadata-0','deleted-metadata','available',NULL,'type-deleted','az-deleted','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('soft-retained','soft-retained','project-2','10','NFS','False','1',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('soft-retained-0','soft-retained','available',NULL,'type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('null-status','null-status','project-1','10','NFS','False','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('null-status-0','null-status',NULL,NULL,'type-1','az-1','False','0'); +INSERT INTO shares(id,display_name,project_id,size,share_proto,deleted,is_soft_deleted,replication_type,task_state) VALUES('deleted-share','deleted-share','project-2','10','NFS','deleted-share','0',NULL,NULL); +INSERT INTO share_instances(id,share_id,status,replica_state,share_type_id,availability_zone_id,deleted,cast_rules_to_readonly) VALUES('deleted-share-0','deleted-share','available',NULL,'type-2','az-2','False','0'); diff --git a/tests/fixtures/manila_inventory_expected.json b/tests/fixtures/manila_inventory_expected.json new file mode 100644 index 0000000..5774547 --- /dev/null +++ b/tests/fixtures/manila_inventory_expected.json @@ -0,0 +1,22 @@ +{ + "zero": ["zero", "zero", "project-1", 10, "NFS", null, "", "", ""], + "single": ["single", "single", "project-2", 10, "NFS", "available", "type-1", "gold", "zone-1"], + "identical": ["identical", "identical", "project-1", 10, "NFS", "available", "type-1", "gold", "zone-1"], + "different": ["different", "different", "project-2", 10, "NFS", "available", "type-1", "gold", "zone-1"], + "replicated": ["replicated", "replicated", "project-1", 10, "NFS", "error", "type-1", "gold", "zone-1"], + "promotion": ["promotion", "promotion", "project-2", 10, "NFS", "replication_change", "type-1", "gold", "zone-1"], + "reverting-promotion": ["reverting-promotion", "reverting-promotion", "project-1", 10, "NFS", "available", "type-1", "gold", "zone-1"], + "reverting": ["reverting", "reverting", "project-2", 10, "NFS", "reverting", "type-1", "gold", "zone-1"], + "writable": ["writable", "writable", "project-1", 10, "NFS", "available", "type-1", "gold", "zone-1"], + "migration": ["migration", "migration", "project-2", 10, "NFS", "migrating", "type-1", "gold", "zone-1"], + "server-migration": ["server-migration", "server-migration", "project-1", 10, "NFS", "server_migrating", "type-1", "gold", "zone-1"], + "fallback": ["fallback", "fallback", "project-2", 10, "NFS", "creating", "type-1", "gold", "zone-1"], + "unknown": ["unknown", "unknown", "project-1", 10, "NFS", "inactive", "type-1", "gold", "zone-1"], + "unknown-tie": ["unknown-tie", "unknown-tie", "project-2", 10, "NFS", "unknown_z", "type-1", "gold", "zone-1"], + "snapshot-revert": ["snapshot-revert", "snapshot-revert", "project-2", 10, "NFS", "creating", "type-2", "silver", "zone-2"], + "deleted-instance": ["deleted-instance", "deleted-instance", "project-1", 10, "NFS", "available", "type-1", "gold", "zone-1"], + "deleted-only": ["deleted-only", "deleted-only", "project-2", 10, "NFS", null, "", "", ""], + "deleted-metadata": ["deleted-metadata", "deleted-metadata", "project-1", 10, "NFS", "available", "type-deleted", "", ""], + "soft-retained": ["soft-retained", "soft-retained", "project-2", 10, "NFS", "available", "type-1", "gold", "zone-1"], + "null-status": ["null-status", "null-status", "project-1", 10, "NFS", null, "type-1", "gold", "zone-1"] +} diff --git a/tests/fixtures/manila_quotas.sql b/tests/fixtures/manila_quotas.sql new file mode 100644 index 0000000..20320ba --- /dev/null +++ b/tests/fixtures/manila_quotas.sql @@ -0,0 +1,44 @@ +-- Synthetic Manila 2025.2 accounting: users and share types overlap. +INSERT INTO share_types (id, name, deleted) VALUES ('type-a', 'gold', 'False'), ('type-b', 'silver', 'False'), ('type-deleted', 'retired', 'deleted-uuid'); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'shares', 20, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'gigabytes', NULL, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'snapshots', -1, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'snapshot_gigabytes', 23, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'share_networks', 0, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'share_replicas', 25, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'replica_gigabytes', 26, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'share_groups', 27, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'share_group_snapshots', 28, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'backups', 29, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'backup_gigabytes', 30, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'per_share_gigabytes', 31, 0); +INSERT INTO quotas (project_id, resource, hard_limit, deleted) VALUES ('project-a', 'shares', 999, -1), ('deleted-only', 'shares', 999, -1), (NULL, 'shares', 999, 0), ('', 'shares', 999, 0); +INSERT INTO quota_classes (class_name, resource, hard_limit, deleted) VALUES ('default', 'shares', 99, 0), ('default', 'snapshot_gigabytes', 777, 0), ('default', 'backups', NULL, 0), ('other', 'shares', 12345, 0), ('default', 'shares', 888, -1); +INSERT INTO project_user_quotas (project_id, user_id, resource, hard_limit, deleted) VALUES ('project-a', 'user-a', 'shares', 1, 0), ('project-a', 'user-b', 'shares', 2, 0), ('user-only', 'user-c', 'shares', 3, 0), ('deleted-only', 'user-a', 'shares', 999, -1); +INSERT INTO project_share_type_quotas (project_id, share_type_id, resource, hard_limit, deleted) VALUES ('project-a', 'type-a', 'shares', 7, 0), ('project-a', 'type-a', 'gigabytes', NULL, 0), ('project-a', 'type-b', 'shares', 0, 0), ('type-limit-only', 'type-b', 'snapshots', -1, 0), ('project-a', 'type-a', 'shares', 999, -1), ('deleted-only', 'type-deleted', 'shares', 999, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'shares', 1, 1, 0), ('project-a', 'user-b', NULL, 'shares', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'gigabytes', 2, 1, 0), ('project-a', 'user-b', NULL, 'gigabytes', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'snapshots', 3, 1, 0), ('project-a', 'user-b', NULL, 'snapshots', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'snapshot_gigabytes', 4, 1, 0), ('project-a', 'user-b', NULL, 'snapshot_gigabytes', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'share_networks', 5, 1, 0), ('project-a', 'user-b', NULL, 'share_networks', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'share_replicas', 6, 1, 0), ('project-a', 'user-b', NULL, 'share_replicas', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'replica_gigabytes', 7, 1, 0), ('project-a', 'user-b', NULL, 'replica_gigabytes', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'share_groups', 8, 1, 0), ('project-a', 'user-b', NULL, 'share_groups', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'share_group_snapshots', 9, 1, 0), ('project-a', 'user-b', NULL, 'share_group_snapshots', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'backups', 10, 1, 0), ('project-a', 'user-b', NULL, 'backups', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', 'user-a', NULL, 'backup_gigabytes', 11, 1, 0), ('project-a', 'user-b', NULL, 'backup_gigabytes', 10, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', NULL, 'type-a', 'shares', 4, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', NULL, 'type-a', 'gigabytes', 5, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', NULL, 'type-a', 'snapshots', 6, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', NULL, 'type-a', 'snapshot_gigabytes', 7, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', NULL, 'type-a', 'share_replicas', 8, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', NULL, 'type-a', 'replica_gigabytes', 9, 2, 0); +INSERT INTO quota_usages (project_id, user_id, share_type_id, resource, in_use, reserved, deleted) VALUES ('project-a', NULL, NULL, 'shares', 2, 4, 0), ('project-a', 'legacy-a', 'type-b', 'shares', 3, 1, 0), ('project-a', 'legacy-b', 'type-b', 'shares', 5, 2, 0), ('project-a', NULL, '', 'shares', 10000, 1000, 0), ('project-a', 'user-a', NULL, 'shares', 9999, 9999, -1), ('project-a', NULL, 'type-deleted', 'shares', 9999, 9999, 0), ('usage-only', 'user-c', NULL, 'shares', 5, 2, 0), ('usage-only', 'user-c', NULL, 'gigabytes', 2000000000, 0, 0), ('usage-only', 'user-d', NULL, 'gigabytes', 2000000000, 0, 0), ('type-usage-only', NULL, 'type-a', 'snapshots', 1, 2, 0), ('null-usage', NULL, NULL, 'shares', NULL, NULL, 0), ('deleted-only', NULL, NULL, 'shares', 999, 999, -1), ('', NULL, NULL, 'shares', 999, 999, 0), (NULL, NULL, NULL, 'shares', 999, 999, 0); +-- Object rows deliberately disagree with quota accounting. Queries use the latter. +INSERT INTO shares (id, project_id, size, deleted) VALUES ('share-live', 'project-a', 100, 'False'), ('share-deleted', 'project-a', 9999, 'deleted-uuid'); +-- Manila soft deletion stores the row primary key, not a boolean. +UPDATE project_share_type_quotas SET deleted = id WHERE deleted = -1; +UPDATE project_user_quotas SET deleted = id WHERE deleted = -1; +UPDATE quota_classes SET deleted = id WHERE deleted = -1; +UPDATE quota_usages SET deleted = id WHERE deleted = -1; +UPDATE quotas SET deleted = id WHERE deleted = -1; diff --git a/tests/manila_inventory_test.go b/tests/manila_inventory_test.go new file mode 100644 index 0000000..d3d8655 --- /dev/null +++ b/tests/manila_inventory_test.go @@ -0,0 +1,71 @@ +//go:build integration + +package tests + +import ( + "context" + "database/sql" + "encoding/json" + "os" + "sort" + "testing" + + "github.com/stretchr/testify/require" + "github.com/vexxhost/openstackdb/internal/testutil" + manila "github.com/vexxhost/openstackdb/manila/db" +) + +// Uses only a disposable MariaDB container; never reads a production DSN. +func TestManilaInventory(t *testing.T) { + db := testutil.NewMySQLContainer(t, "manila-inventory", "../sql/manila/prereqs.sql", "../sql/manila/schema.sql") + q := manila.New(db) + rows, err := q.ShareGetInventory(context.Background()) + require.NoError(t, err) + require.Empty(t, rows) + fixture, err := os.ReadFile("fixtures/manila_inventory.sql") + require.NoError(t, err) + testutil.SeedSQL(t, db, string(fixture)) + rows, err = q.ShareGetInventory(context.Background()) + require.NoError(t, err) + expectedJSON, err := os.ReadFile("fixtures/manila_inventory_expected.json") + require.NoError(t, err) + var expected map[string][]any + require.NoError(t, json.Unmarshal(expectedJSON, &expected)) + got := map[string][]any{} + nullable := func(s sql.NullString) any { + if !s.Valid { + return nil + } + return s.String + } + var capacity int32 + var ids []string + for _, row := range rows { + require.NotContains(t, got, row.ID) + ids = append(ids, row.ID) + got[row.ID] = []any{row.ID, nullable(row.Name), nullable(row.ProjectID), float64(row.Size.Int32), nullable(row.ShareProto), nullable(row.Status), row.ShareType, row.ShareTypeName, row.AvailabilityZone} + capacity += row.Size.Int32 + } + require.Equal(t, expected, got) + require.EqualValues(t, 10*len(expected), capacity) + // All fixture created_at values are NULL, so IDs break the ordering tie. + require.True(t, sort.StringsAreSorted(ids)) + legacy, err := q.ShareGetAllWithInstances(context.Background()) + require.NoError(t, err) + require.Len(t, legacy, 34) + counts := map[string]int{} + for _, row := range legacy { + counts[row.ID]++ + } + require.Len(t, counts, len(expected)) + for id := range expected { + require.Positive(t, counts[id], id) + } + require.Equal(t, 2, counts["identical"]) + require.Equal(t, 3, counts["reverting-promotion"]) + require.Equal(t, 2, counts["snapshot-revert"]) + require.Equal(t, 1, counts["zero"]) + require.Equal(t, 1, counts["deleted-only"]) + require.Equal(t, 1, counts["soft-retained"]) + require.Zero(t, counts["deleted-share"]) +} diff --git a/tests/manila_quotas_test.go b/tests/manila_quotas_test.go new file mode 100644 index 0000000..598d82d --- /dev/null +++ b/tests/manila_quotas_test.go @@ -0,0 +1,130 @@ +//go:build integration + +package tests + +import ( + "context" + "database/sql" + "os" + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/vexxhost/openstackdb/internal/testutil" + manila "github.com/vexxhost/openstackdb/manila/db" +) + +func TestManilaQuotas(t *testing.T) { + db := testutil.NewMySQLContainer(t, "manila", "../sql/manila/prereqs.sql", "../sql/manila/schema.sql") + fixture, err := os.ReadFile("fixtures/manila_quotas.sql") + require.NoError(t, err) + testutil.SeedSQL(t, db, string(fixture)) + for _, table := range strings.Fields("quotas quota_usages quota_classes project_user_quotas project_share_type_quotas") { + var dataType string + var noDefault bool + err := db.QueryRow("SELECT DATA_TYPE, (COLUMN_DEFAULT IS NULL OR COLUMN_DEFAULT = 'NULL') FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = 'deleted'", table).Scan(&dataType, &noDefault) + require.NoError(t, err) + require.Equal(t, "int", dataType, table) + require.True(t, noDefault, table) + var invalid, deleted int + err = db.QueryRow("SELECT COUNT(*) FROM " + table + " WHERE deleted <> 0 AND deleted <> id").Scan(&invalid) + require.NoError(t, err) + require.Zero(t, invalid, table) + err = db.QueryRow("SELECT COUNT(*) FROM " + table + " WHERE deleted = id").Scan(&deleted) + require.NoError(t, err) + require.Positive(t, deleted, table) + } + q := manila.New(db) + ctx := context.Background() + + // Usage rows come back raw. Summing them the way a caller would must + // reproduce Manila's _quota_usage_get_all totals for project accounting. + usage, err := q.QuotaUsageGetAllByProject(ctx) + require.NoError(t, err) + got := map[string][2]int64{} + nullUsage := 0 + for _, row := range usage { + require.True(t, row.ProjectID.Valid) + require.NotEmpty(t, row.ProjectID.String) + require.NotEqual(t, "deleted-only", row.ProjectID.String) + if !row.InUse.Valid || !row.Reserved.Valid { + require.Equal(t, "null-usage", row.ProjectID.String) + nullUsage++ + continue + } + key := row.ProjectID.String + "/" + row.Resource.String + total := got[key] + got[key] = [2]int64{total[0] + int64(row.InUse.Int32), total[1] + int64(row.Reserved.Int32)} + } + require.Equal(t, 1, nullUsage, "NULL usage must stay NULL, not become zero") + expected := map[string][2]int64{} + for i, resource := range strings.Fields("shares gigabytes snapshots snapshot_gigabytes share_networks share_replicas replica_gigabytes share_groups share_group_snapshots backups backup_gigabytes") { + expected["project-a/"+resource] = [2]int64{int64(i + 11), 3} + } + expected["project-a/shares"] = [2]int64{13, 7} + expected["usage-only/shares"] = [2]int64{5, 2} + expected["usage-only/gigabytes"] = [2]int64{4000000000, 0} + require.Equal(t, expected, got) + + // Share-type accounting is separate, and rows for deleted or missing + // share types stay visible with a NULL name. + types, err := q.QuotaUsageGetAllByProjectAndShareType(ctx) + require.NoError(t, err) + typed := map[string][2]int64{} + for _, row := range types { + key := row.ProjectID.String + "/" + row.ShareTypeID.String + "/" + row.Resource.String + switch row.ShareTypeID.String { + case "type-a": + require.Equal(t, sql.NullString{String: "gold", Valid: true}, row.ShareTypeName) + case "type-b": + require.Equal(t, sql.NullString{String: "silver", Valid: true}, row.ShareTypeName) + default: + require.False(t, row.ShareTypeName.Valid, key) + } + total := typed[key] + typed[key] = [2]int64{total[0] + int64(row.InUse.Int32), total[1] + int64(row.Reserved.Int32)} + } + expectedTypes := map[string][2]int64{} + for i, resource := range strings.Fields("shares gigabytes snapshots snapshot_gigabytes share_replicas replica_gigabytes") { + expectedTypes["project-a/type-a/"+resource] = [2]int64{int64(i + 4), 2} + } + expectedTypes["project-a/type-b/shares"] = [2]int64{8, 3} + expectedTypes["type-usage-only/type-a/snapshots"] = [2]int64{1, 2} + expectedTypes["project-a/type-deleted/shares"] = [2]int64{9999, 9999} + expectedTypes["project-a//shares"] = [2]int64{10000, 1000} + require.Equal(t, expectedTypes, typed) + + limits, err := q.QuotaGetAllByProjectAndShareType(ctx) + require.NoError(t, err) + require.Len(t, limits, 5) + for _, row := range limits { + require.Equal(t, row.ShareTypeID != "type-deleted", row.ShareTypeName.Valid, row.ShareTypeID) + } + users, err := q.QuotaGetAllByProjectAndUser(ctx) + require.NoError(t, err) + require.Len(t, users, 3) + defaults, err := q.QuotaClassGetDefault(ctx) + require.NoError(t, err) + require.Len(t, defaults, 3) + projectLimits, err := q.QuotaGetAllByProject(ctx) + require.NoError(t, err) + require.Len(t, projectLimits, 12) + for _, row := range projectLimits { + require.True(t, row.ProjectID.Valid) + require.Equal(t, "project-a", row.ProjectID.String) + switch row.Resource.String { + case "gigabytes": + require.False(t, row.HardLimit.Valid) + case "snapshots": + require.Equal(t, sql.NullInt32{Int32: -1, Valid: true}, row.HardLimit) + case "share_networks": + require.Equal(t, sql.NullInt32{Valid: true}, row.HardLimit) + } + } + _, err = db.ExecContext(ctx, "DROP TABLE quota_usages") + require.NoError(t, err) + _, err = q.QuotaUsageGetAllByProject(ctx) + require.Error(t, err) + _, err = q.QuotaUsageGetAllByProjectAndShareType(ctx) + require.Error(t, err) +} diff --git a/tests/queries_test.go b/tests/queries_test.go index e350060..99f7440 100644 --- a/tests/queries_test.go +++ b/tests/queries_test.go @@ -4,8 +4,10 @@ package tests import ( "context" + "database/sql" "github.com/stretchr/testify/require" cinder "github.com/vexxhost/openstackdb/cinder/db" + designate "github.com/vexxhost/openstackdb/designate/db" glance "github.com/vexxhost/openstackdb/glance/db" heat "github.com/vexxhost/openstackdb/heat/db" "github.com/vexxhost/openstackdb/internal/testutil" @@ -99,6 +101,90 @@ func TestGlanceQueries(t *testing.T) { _, err = q.ImageGetAll(ctx) require.NoError(t, err, "ImageGetAll") } + +func TestDesignateZonesWithRecordsets(t *testing.T) { + conn := testutil.NewMySQLContainer(t, "designate", "../sql/designate/schema.sql") + queries := designate.New(conn) + ctx := context.Background() + + zones, err := queries.ZoneGetAll(ctx) + require.NoError(t, err) + require.Empty(t, zones) + counts, err := queries.RecordsetCountByZone(ctx) + require.NoError(t, err) + require.Empty(t, counts) + recordsets, err := queries.RecordsetGetAllWithStatus(ctx) + require.NoError(t, err) + require.Empty(t, recordsets) + + testutil.SeedSQL(t, conn, + `INSERT INTO zones (id, name, tenant_id, status, type, deleted) VALUES + ('a86dba5800434cc6a1bb69d5e86f3ca3', 'example.org.', 'project-1', 'ACTIVE', 'PRIMARY', '0'), + ('2150b1bfdee242219d8511f7886fb15f', 'empty.example.', NULL, 'PENDING', 'SECONDARY', '0'), + ('23527f480fa04efc82264f2468c7c40e', 'deleted.example.', 'project-1', 'DELETED', 'PRIMARY', '23527f480fa04efc82264f2468c7c40e')`, + `INSERT INTO recordsets (id, zone_id, name, type) VALUES + ('10000000000040008000000000000001', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'error.example.org.', 'A'), + ('10000000000040008000000000000002', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'pending.example.org.', 'A'), + ('10000000000040008000000000000003', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'active.example.org.', 'A'), + ('10000000000040008000000000000004', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'deleted.example.org.', 'A'), + ('10000000000040008000000000000005', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'empty.example.org.', 'TXT'), + ('10000000000040008000000000000006', '23527f480fa04efc82264f2468c7c40e', 'deleted.example.', 'NS')`, + `INSERT INTO records (id, recordset_id, status) VALUES + ('1', '10000000000040008000000000000001', 'PENDING'), ('2', '10000000000040008000000000000001', 'ERROR'), + ('3', '10000000000040008000000000000002', 'ACTIVE'), ('4', '10000000000040008000000000000002', 'PENDING'), + ('5', '10000000000040008000000000000003', 'DELETED'), ('6', '10000000000040008000000000000003', 'ACTIVE'), + ('7', '10000000000040008000000000000004', 'DELETED')`, + ) + + checkVisibleRows := func(t *testing.T) { + t.Helper() + const zoneID = "a86dba58-0043-4cc6-a1bb-69d5e86f3ca3" + const emptyZoneID = "2150b1bf-dee2-4221-9d85-11f7886fb15f" + tenantID := sql.NullString{String: "project-1", Valid: true} + zones, err := queries.ZoneGetAll(ctx) + require.NoError(t, err) + require.ElementsMatch(t, []designate.ZoneGetAllRow{ + {ID: zoneID, Name: "example.org.", TenantID: tenantID, Status: "ACTIVE", Type: "PRIMARY"}, + {ID: emptyZoneID, Name: "empty.example.", Status: "PENDING", Type: "SECONDARY"}, + }, zones) + + counts, err := queries.RecordsetCountByZone(ctx) + require.NoError(t, err) + require.ElementsMatch(t, []designate.RecordsetCountByZoneRow{ + {ZoneID: zoneID, ZoneName: "example.org.", TenantID: tenantID, RecordsetCount: 5}, + {ZoneID: emptyZoneID, ZoneName: "empty.example.", RecordsetCount: 0}, + }, counts) + + recordsets, err := queries.RecordsetGetAllWithStatus(ctx) + require.NoError(t, err) + require.Len(t, recordsets, 5) + statuses := make(map[string]string, len(recordsets)) + for _, row := range recordsets { + require.Equal(t, zoneID, row.ZoneID) + require.Equal(t, "example.org.", row.ZoneName) + statuses[row.ID] = row.Status + } + require.Equal(t, map[string]string{ + "10000000-0000-4000-8000-000000000001": "ERROR", + "10000000-0000-4000-8000-000000000002": "PENDING", + "10000000-0000-4000-8000-000000000003": "ACTIVE", + "10000000-0000-4000-8000-000000000004": "DELETED", + "10000000-0000-4000-8000-000000000005": "ACTIVE", + }, statuses) + } + t.Run("non-null zone ID", checkVisibleRows) + t.Run("nullable zone ID", func(t *testing.T) { + testutil.SeedSQL(t, conn, + `ALTER TABLE recordsets DROP FOREIGN KEY recordsets_zone_fk`, + `ALTER TABLE recordsets MODIFY zone_id CHAR(32) NULL`, + `ALTER TABLE recordsets ADD CONSTRAINT recordsets_zone_fk FOREIGN KEY (zone_id) REFERENCES zones(id) ON DELETE CASCADE`, + `INSERT INTO recordsets (id, zone_id, name, type) VALUES + ('10000000000040008000000000000007', NULL, 'orphan.example.', 'A')`, + ) + checkVisibleRows(t) + }) +} + func TestKeystoneQueries(t *testing.T) { ctx := context.Background() conn := testutil.NewMySQLContainer(t, "keystone", "../sql/keystone/schema.sql") @@ -146,6 +232,20 @@ func TestManilaQueries(t *testing.T) { var err error _, err = q.ShareGetAllWithInstances(ctx) require.NoError(t, err, "ShareGetAllWithInstances") + _, err = q.ShareGetInventory(ctx) + require.NoError(t, err, "ShareGetInventory") + _, err = q.QuotaGetAllByProject(ctx) + require.NoError(t, err, "QuotaGetAllByProject") + _, err = q.QuotaClassGetDefault(ctx) + require.NoError(t, err, "QuotaClassGetDefault") + _, err = q.QuotaGetAllByProjectAndUser(ctx) + require.NoError(t, err, "QuotaGetAllByProjectAndUser") + _, err = q.QuotaGetAllByProjectAndShareType(ctx) + require.NoError(t, err, "QuotaGetAllByProjectAndShareType") + _, err = q.QuotaUsageGetAllByProject(ctx) + require.NoError(t, err, "QuotaUsageGetAllByProject") + _, err = q.QuotaUsageGetAllByProjectAndShareType(ctx) + require.NoError(t, err, "QuotaUsageGetAllByProjectAndShareType") } func TestNeutronQueries(t *testing.T) { ctx := context.Background()