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
43 changes: 42 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 Down Expand Up @@ -60,8 +63,9 @@ with identical semantics upstream.

- [Nova main database API](https://github.com/openstack/nova/blob/master/nova/db/main/api.py): `instance_get_by_uuid`, `instance_get_all_by_filters`, `service_get_all`, `compute_node_get_all`.
- [Nova API database](https://github.com/openstack/nova/tree/master/nova/db/api) and [objects](https://github.com/openstack/nova/tree/master/nova/objects): flavor, aggregate, and quota data.
- [Cinder DB API](https://github.com/openstack/cinder/blob/master/cinder/db/api.py): `volume_get`, `volume_get_all`, `volume_type_get_all`, `service_get_all`.
- [Cinder DB API](https://github.com/openstack/cinder/blob/master/cinder/db/api.py): `volume_get`, `volume_get_all`, `volume_type_get_all`, `service_get_all`, `quota_get_all_by_project`, `quota_usage_get_all_by_project`, `quota_class_get_defaults`.
- [Glance DB API](https://github.com/openstack/glance/blob/master/glance/db/sqlalchemy/api.py): `image_get`, `image_get_all`.
- [Designate storage](https://github.com/openstack/designate/blob/master/designate/storage/sqlalchemy/__init__.py): `find_zones`, `find_recordsets`, `count_recordsets`. The library also follows [Designate's UUID conversion](https://github.com/openstack/designate/blob/master/designate/storage/sqlalchemy/types.py) and [recordset status precedence](https://github.com/openstack/designate/blob/master/designate/objects/recordset.py).
- [Ironic DB API](https://github.com/openstack/ironic/blob/master/ironic/db/api.py) and [Magnum DB API](https://github.com/openstack/magnum/blob/master/magnum/db/api.py): `get_node_list`, `get_cluster_list`.
- [Heat DB API](https://github.com/openstack/heat/blob/master/heat/db/api.py): `stack_get_all`.
- [Manila DB API](https://github.com/openstack/manila/blob/master/manila/db/api.py): share operations; the instance join is an explicit extension.
Expand All @@ -77,6 +81,8 @@ with identical semantics upstream.
- Current exporter queries retain their existing deleted/hidden/status predicates; they are not full upstream administrative listings.
- Errors are Go/database errors; absent single resources return `sql.ErrNoRows` rather than Python service-specific exceptions.
- Aggregate queries such as `QuotaGetAllWithUsage`, `GetResourceProviderInventories`, and `GetResourceCountsByProject` are explicitly library extensions.
- Designate returns canonical zone and recordset UUIDs and excludes soft-deleted zones. `RecordsetCountByZone` includes zero-count zones and can run without reading individual records. `RecordsetGetAllWithStatus` uses the child precedence `ERROR`, `PENDING`, `ACTIVE`, `DELETED` and returns `ACTIVE` for an empty recordset. Recordsets with a NULL `zone_id` have no visible zone and are omitted.
- Cinder quota queries exclude NULL and empty project IDs because Cinder quota rows belong to Keystone projects. The older Cinder exporter quota queries are unchanged.
- No cross-cell routing or historic schema negotiation is performed. Nova archive access is explicitly selected with `InstanceFilters.Archive`.

## Resource lifecycle and metadata reads
Expand All @@ -94,3 +100,38 @@ lifecycle metadata. Their fixed current-resource queries remain unchanged for
exporter consumers. Deleted volume types and legacy type tables are only read
when explicitly requested. Legacy table availability is a caller/deployment
concern; errors are propagated rather than hidden.

### Cinder quota accounting

| Go operation | Upstream naming source | Scope |
| --- | --- | --- |
| `QuotaGetAllByProject` | [Cinder `quota_get_all_by_project`](https://github.com/openstack/cinder/blob/master/cinder/db/api.py) | Reads `quotas` for every project at once; raw rows instead of a per-project dictionary. |
| `QuotaUsageGetAllByProject` | [Cinder `quota_usage_get_all_by_project`](https://github.com/openstack/cinder/blob/master/cinder/db/api.py) | Reads `quota_usages` for every project at once; raw `in_use`/`reserved` rows. Usage is Cinder's cached accounting. |
| `QuotaClassGetDefaults` | [Cinder `quota_class_get_defaults`](https://github.com/openstack/cinder/blob/master/cinder/db/api.py) | Reads the `default` class from `quota_classes`; raw rows instead of a dictionary. |
| `ParseQuotaResource` | Cinder `VolumeTypeResource` key format in [`cinder/quota.py`](https://github.com/openstack/cinder/blob/master/cinder/quota.py) | Splits `<part>_<volume type name>` keys. Hand-written; re-check the global resource list on Cinder upgrades. |

Rows with a NULL or empty project ID are excluded: Cinder quota rows belong to
Keystone projects. Results are ordered by project, resource and row ID, so
callers that collapse duplicates get a stable result. Duplicate active rows,
NULL limits, zero limits and `-1` (unlimited) are returned as stored. The
existing exporter queries `QuotaGetProjectLimits`, `QuotaUsageGetAll` and
`QuotaGetAllWithUsage` keep their behavior.

Limits and usage are read separately, so usage also covers projects that have
no limit overrides. Usage is Cinder's cached accounting, not a live count of
volumes and snapshots. It can drift from the real resources until Cinder
refreshes it. `reserved` already counts open reservations.

Resource keys are either global (`volumes`, `gigabytes`, `snapshots`, `backups`,
`backup_gigabytes`, `per_volume_gigabytes`, `groups`) or per volume type, built
as `<part>_<volume type name>` where the part is `volumes`, `gigabytes` or
`snapshots`. Per-type and global accounting describe the same allocations, so
never add them together. Use `ParseQuotaResource` to split a key. Don't split
on the first underscore: that misreads `backup_gigabytes` and type names that
contain underscores. Keys hold the volume type's name, not its ID. Cinder
rewrites them when a type is renamed, but keeps them after a type is deleted,
so a parsed name may not match any type from `VolumeTypeGetAll`.

Callers resolve effective limits: a project override, then the `default` class,
then service configuration. The `quota_classes` schema is a test and
code-generation fixture, not a production migration.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ repository objects. Placement queries live under `placement/objects`.
| --- | --- |
| `nova/db/main` | `InstanceGetAllByFilters`, `InstanceGetByUUID`, `ServiceGetAll`, `ComputeNodeGetAll` |
| `nova/db/api` | `FlavorGetAll`, `AggregateGetAll`, quota projections |
| `cinder/db` | `ServiceGetAll`, `QuotaGetProjectLimits`, `QuotaUsageGetAll` |
| `cinder/db` | `ServiceGetAll`, `QuotaGetProjectLimits`, `QuotaUsageGetAll`, `QuotaGetAllByProject`, `QuotaUsageGetAllByProject`, `QuotaClassGetDefaults` |
| `glance/db` | `ImageGetAll` |
| `designate/db` | `ZoneGetAll`, `RecordsetCountByZone`, `RecordsetGetAllWithStatus` |
| `keystone/db` | `ListProjects`, `ListDomains`, `ListUsers` |
| `heat/db` | `StackGetAll` |
| `ironic/db` | `GetNodeList` |
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
11 changes: 11 additions & 0 deletions cinder/db/models.go

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

29 changes: 29 additions & 0 deletions cinder/db/queries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,32 @@ WHERE
-- name: VolumeGetAll :many
SELECT id, project_id, size, volume_type_id, status, created_at, deleted_at
FROM volumes WHERE deleted = 0;

-- name: QuotaGetAllByProject :many
-- Upstream quota_get_all_by_project for every project. The table holds both
-- aggregate resources (volumes, gigabytes, ...) and per-volume-type resources
-- (volumes_<type name>, ...). See ParseQuotaResource. Rows with a NULL or empty
-- project ID are excluded.
SELECT project_id, resource, hard_limit
FROM quotas
WHERE deleted = 0 AND project_id <> ''
ORDER BY project_id, resource, id;

-- name: QuotaUsageGetAllByProject :many
-- Upstream quota_usage_get_all_by_project for every project. These are Cinder's
-- cached usage counters, not a live count of volumes and snapshots, and can
-- drift until Cinder refreshes them. reserved already counts open reservations.
-- Aggregate and per-volume-type resources describe the same allocations, so
-- never add them together.
SELECT project_id, resource, in_use, reserved
FROM quota_usages
WHERE deleted = 0 AND project_id <> ''
ORDER BY project_id, resource, id;

-- name: QuotaClassGetDefaults :many
-- Upstream quota_class_get_defaults. The persisted 'default' class overrides
-- service configuration defaults.
SELECT resource, hard_limit
FROM quota_classes
WHERE deleted = 0 AND class_name = 'default'
ORDER BY resource, id;
124 changes: 124 additions & 0 deletions cinder/db/queries.sql.go

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

44 changes: 44 additions & 0 deletions cinder/db/quota_resources.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package cinder

import "strings"

// quotaGlobalResources are the resource keys Cinder registers without a
// volume type: VolumeTypeQuotaEngine's global quotas plus GroupQuotaEngine's
// groups, which share the same tables.
var quotaGlobalResources = map[string]bool{
"volumes": true,
"per_volume_gigabytes": true,
"snapshots": true,
"gigabytes": true,
"backups": true,
"backup_gigabytes": true,
"groups": true,
}

// quotaVolumeTypeParts are the only resources Cinder tracks per volume type.
var quotaVolumeTypeParts = []string{"volumes", "gigabytes", "snapshots"}

// ParseQuotaResource splits a Cinder quota resource key into its base resource
// and volume type name.
//
// Cinder builds per-volume-type keys as "<part>_<volume type name>", where part
// is volumes, gigabytes or snapshots. A global key such as "backup_gigabytes"
// returns an empty volumeType. Volume type names may contain underscores, so
// "gigabytes_fast_ssd" returns ("gigabytes", "fast_ssd").
//
// The key holds the volume type's name, not its ID. Cinder rewrites keys when a
// type is renamed, but keeps them after a type is deleted, so a parsed name
// may not match any current volume type.
//
// ok is false for keys Cinder does not register. base is then the whole key.
func ParseQuotaResource(key string) (base, volumeType string, ok bool) {
if quotaGlobalResources[key] {
return key, "", true
}
for _, part := range quotaVolumeTypeParts {
if name, found := strings.CutPrefix(key, part+"_"); found && name != "" {
return part, name, true
}
}
return key, "", false
}
36 changes: 36 additions & 0 deletions cinder/db/quota_resources_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package cinder

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestParseQuotaResource(t *testing.T) {
for _, tc := range []struct {
key, base, volumeType string
ok bool
}{
{"volumes", "volumes", "", true},
{"gigabytes", "gigabytes", "", true},
{"snapshots", "snapshots", "", true},
{"backups", "backups", "", true},
{"backup_gigabytes", "backup_gigabytes", "", true},
{"per_volume_gigabytes", "per_volume_gigabytes", "", true},
{"groups", "groups", "", true},
{"volumes_lvm", "volumes", "lvm", true},
{"gigabytes_fast_ssd", "gigabytes", "fast_ssd", true},
{"snapshots___DEFAULT__", "snapshots", "__DEFAULT__", true},
{"volumes_backup_gigabytes", "volumes", "backup_gigabytes", true},
{"backups_lvm", "backups_lvm", "", false},
{"volumes_", "volumes_", "", false},
{"", "", "", false},
} {
t.Run(tc.key, func(t *testing.T) {
base, volumeType, ok := ParseQuotaResource(tc.key)
require.Equal(t, tc.base, base)
require.Equal(t, tc.volumeType, volumeType)
require.Equal(t, tc.ok, ok)
})
}
}
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)
}
Loading