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
46 changes: 45 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 @@ -50,6 +53,8 @@ with identical semantics upstream.
| `octavia/db/repositories` | `GetAllPools` | `PoolGetAll` |
| `octavia/db/repositories` | `GetAllLoadBalancersWithVip` | `LoadBalancerGetAllWithVIP` |
| `octavia/db/repositories` | `GetAllAmphora` | `AmphoraGetAll` |
| `octavia/db/repositories` | — | `QuotaGetAll` (`QuotaRepository.GetAll`) |
| `octavia/db/repositories` | — | `QuotaUsageGetAll` (`QuotaRepository.GetUsage`) |
| `placement/objects` | `GetResourceMetrics` | `GetResourceProviderInventories` |
| `placement/objects` | `GetAllocationsByProject` | `GetAllocationsByProject` |
| `placement/objects` | `GetConsumerCountByProject` | `GetConsumerCountByProject` |
Expand All @@ -62,6 +67,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 @@ -76,7 +82,9 @@ with identical semantics upstream.
- The filtered APIs support exact membership and lifetime overlap, not every upstream regex, pagination, eager-loading, or authorization option.
- 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.
- Aggregate queries such as `QuotaGetAllWithUsage`, `GetResourceProviderInventories`, `GetResourceCountsByProject`, and Octavia `QuotaUsageGetAll` are explicitly library extensions. Octavia `QuotaUsageGetAll` recounts objects with `check_quota_met`'s predicate; Octavia itself enforces against the cached `in_use_*` counters that `QuotaGetAll` returns.
- Owner filtering follows each service: Neutron keeps empty-string project IDs because Neutron creates real objects with them (for example L3 HA networks and ports), while Octavia excludes them because it rejects empty project IDs.
- 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 +102,39 @@ 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.

### Octavia quotas

| Go operation | Upstream naming source | Scope |
| --- | --- | --- |
| `QuotaGetAll` (`QuotaRepository.GetAll`) | [Octavia `QuotasRepository`](https://github.com/openstack/octavia/blob/master/octavia/db/repositories.py) | Stored limits and cached `in_use_*` counters for every project at once; NULL and empty project IDs excluded. |
| `QuotaUsageGetAll` (`QuotaRepository.GetUsage`) | Octavia `Repositories.check_quota_met` recount predicate | Library extension: recounts all seven quota resources for every project; scans seven unindexed object tables. |

`NewQuotaRepository(db).GetAll(ctx)` / `QuotaGetAll` returns one `Quota` row per
project with the stored limits for load balancers, listeners, pools, health
monitors, members, L7 policies and L7 rules, plus Octavia's cached `in_use_*`
counters. Each value is a `sql.NullInt32`. A NULL limit means no explicit
override, and zero and -1 remain distinct values; the caller resolves configured
defaults. The `in_use_*` counters are what Octavia's `check_quota_met` and
`decrement_quota` enforce against. A NULL or zero counter means Octavia will
recount on its next quota check for that project.

`QuotaRepository.GetUsage` / `QuotaUsageGetAll` rebuilds project counts for all
seven quota resources independently, using the same predicate Octavia uses when
it recounts: the object's own `project_id` and `provisioning_status != 'DELETED'`.
Counts include ERROR and pending statuses. Each object uses its own project and
status, including children of deleted parents or parents owned by another project,
and there are no parent joins to multiply counts. Results contain only nonzero
project/resource groups, including projects without quota rows, with int64 usage.

The two reads answer different questions. `in_use_*` is what Octavia enforces
today, and `GetUsage` is what those counters should be. Compare them to detect
counter drift, which persists until Octavia reconciles it. Octavia defines no
index on `project_id` or `provisioning_status`, so `GetUsage` scans all seven
object tables. `GetAll` reads only the `quotas` table and is cheap enough for
every scrape. Run `GetUsage` as a less frequent drift check on large deployments.

Both reads exclude NULL and empty project IDs. Octavia rejects empty project IDs
(`MissingProjectID`), so such rows can never hold quota. The schema fixtures
contain only fields needed for these tests, not a complete OpenStack migration.
The MariaDB integration test is `TestOctaviaQuotas` 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,13 +16,14 @@ 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` |
| `octavia/db/repositories` | `PoolRepository`, `LoadBalancerRepository`, `AmphoraRepository` |
| `octavia/db/repositories` | `PoolRepository`, `LoadBalancerRepository`, `AmphoraRepository`, `QuotaRepository` |
| `placement/objects` | Resource provider inventory and allocation projections |

## Example
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