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
47 changes: 47 additions & 0 deletions 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 Down Expand Up @@ -62,6 +65,7 @@ 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.
Expand All @@ -77,6 +81,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 +99,45 @@ lifecycle metadata. Their fixed current-resource queries remain unchanged for
exporter consumers. Deleted volume types and legacy type tables are only read
when explicitly requested. Legacy table availability is a caller/deployment
concern; errors are propagated rather than hidden.

### Neutron quota reservations

| Go operation | Upstream naming source | Scope |
| --- | --- | --- |
| `GetReservationsForResources` | [Neutron `get_reservations_for_resources(..., expired=False)`](https://github.com/openstack/neutron/blob/master/neutron/db/quota/api.py) | All projects instead of one; raw per-delta rows instead of a per-resource sum. |

`neutron/db.Queries.GetReservationsForResources(ctx, resources)` returns one row
per active reservation delta: `ReservationID`, `ProjectID`, `Expiration`,
`Resource`, and `Amount`. Rows are ordered by project, resource, and reservation
ID. Amounts are returned as stored, including NULL and negative values; summing
them and deciding how to treat malformed amounts is the caller's job.

A reservation is active when `expiration >= UTC_TIMESTAMP()`, the same inclusive
boundary Neutron uses. The comparison runs on the database clock, so skew
between the caller and the Neutron servers does not change the result. Neutron
writes expirations in UTC, so the comparison uses `UTC_TIMESTAMP()` rather than
the session-time-zone `NOW()`. NULL expirations are never active.

`resources` is a positional argument, not a `...Filters` struct, and follows
upstream: a nil or empty list matches nothing rather than every resource. Pass
the resources to monitor explicitly, for example `floatingip`, `network`, `port`,
`rbac_policy`, `router`, `security_group`, `security_group_rule`, `subnet`, and
`subnetpool`.

NULL owners are excluded and empty-string owners are kept. `GetQuotas` and
`GetResourceCountsByProject` use the same owner policy, so limits, usage, and
reservations can be joined on `ProjectID` without special cases. `GetQuotas`
returns rows ordered by project, resource, and quota ID, so callers that collapse
duplicate project/resource rows get a stable result.

Upstream Neutron defines no index on `reservations.expiration` or
`reservations.project_id`; the schema fixture mirrors that. Each call therefore
scans `reservations` and joins `resourcedeltas` through the index InnoDB creates
for its `reservation_id` foreign key. This is the same access path Neutron's own
quota engine uses, and the table stays small while Neutron's expired-reservation
cleanup runs. If cleanup stalls, the table and this query's cost grow together.

The schema tables are local fixtures, not production migrations. Separate reads
do not share a snapshot unless the caller uses `WithTx` with a suitable isolation
level. Query, scan, row-iteration, and context errors propagate through the
generated API; an error must never be treated as zero reservations.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@ 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` |
| `neutron/db` | `GetAgents`, `GetHARouterAgentPortBindingsWithAgents`, `GetRouters` |
| `neutron/db` | `GetAgents`, `GetHARouterAgentPortBindingsWithAgents`, `GetRouters`, `GetQuotas`, `GetReservationsForResources` |
| `octavia/db/repositories` | `PoolRepository`, `LoadBalancerRepository`, `AmphoraRepository` |
| `placement/objects` | Resource provider inventory and allocation projections |

Expand Down 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