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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 82 additions & 1 deletion API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand All @@ -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` |
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions connect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"github.com/stretchr/testify/require"
"testing"
"time"
)

func TestConnectInvalidURLs(t *testing.T) {
Expand All @@ -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)
}
27 changes: 21 additions & 6 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand All @@ -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
}
31 changes: 31 additions & 0 deletions designate/db/db.go

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

51 changes: 51 additions & 0 deletions designate/db/designate.go
Original file line number Diff line number Diff line change
@@ -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()
}
31 changes: 31 additions & 0 deletions designate/db/models.go

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

44 changes: 44 additions & 0 deletions designate/db/queries.sql
Original file line number Diff line number Diff line change
@@ -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';
Loading