Skip to content
Open
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
86 changes: 86 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,89 @@ go build ./cmd/openstack-database-exporter

Integration tests load embedded fixtures from the pinned openstackdb module.
Database URLs and exporter configuration remain the same.

## Octavia project quotas

The Octavia collector exports `openstack_loadbalancer_quota_{loadbalancer,listener,pool,member,healthmonitor,l7policy,l7rule}`
as gauges with `tenant`, `tenant_id`, `domain_id` and `type` labels. Every
resource has `type="limit"` and `type="in_use"`; no reserved values are emitted.
Usage counts objects in each resource table with a nonempty project ID,
excluding `provisioning_status='DELETED'`. ERROR and transitional states count.
These are project counts, not per-load-balancer counts or traffic statistics.

Object counts can differ from Octavia's cached `quotas.in_use_*` values, which
Octavia normally uses for quota enforcement. Drift can persist until corrected;
these metrics do not guarantee that Octavia will accept another creation.
Before enabling quota alerts, compare representative per-project counts with
the service API, the cached accounting values and effective service defaults
on a representative database snapshot. Investigate persistent differences rather
than assuming they will resolve. Gate usage alerts on
`openstack_loadbalancer_quota_up == 1`. For utilization ratios, filter limits
with `limit > 0`: `-1` represents unlimited and `0` prohibits allocation.
Zero-limit violations need a separate `in_use > 0` check.

Configure `--octavia.database-url` / `OCTAVIA_DATABASE_URL` and, for project names,
domains and idle projects, `--keystone.database-url` / `KEYSTONE_DATABASE_URL`.
Without available project metadata, observed project IDs are retained as `tenant`
and `tenant_id`, and `domain_id` is empty. Idle projects cannot be discovered from
Octavia alone. The project cache retains last successful metadata on a refresh
failure; cached names/domains can therefore be stale. Orphaned projects in Octavia
remain visible. Every known project has 14 quota samples; the success gauge has
no labels.

Octavia configuration defaults are not stored in its database. The optional
`--quota.defaults-file` / `QUOTA_DEFAULTS_FILE` supplies all seven effective
`[quotas]` defaults. With no path, the exporter starts and logs a warning that
it assumes Octavia 2025.2 upstream unlimited (`-1`) defaults for every resource.
If service defaults are customized, generate this file from the same values
that render `octavia.conf` and update both together to avoid configuration drift.
Only the Octavia section is read; unrelated service sections are ignored:

```json
{
"octavia": {
"loadbalancer": -1,
"listener": -1,
"pool": -1,
"member": -1,
"healthmonitor": -1,
"l7policy": -1,
"l7rule": -1
}
}
```

Map `loadbalancer` and `healthmonitor` to service settings
`default_load_balancer_quota` and `default_health_monitor_quota`; the other five
map to `default_<resource>_quota`. An explicit project value always wins over
the configured default; a NULL or missing override uses that default. Zero
and `-1` are preserved. An explicitly supplied unreadable, malformed or
incomplete file fails startup with a configuration error when Octavia is enabled.
When Octavia is disabled, the file is ignored. Unknown Octavia resource names,
NULLs, fractions, overflow and values below `-1` are rejected.
Programmatic `collector.Config` callers may omit `OctaviaQuotaDefaults` (nil)
to use upstream defaults with a warning, or supply a complete map.

`openstack_loadbalancer_quota_up` is an unlabeled gauge: `1` when quota
collection succeeds (including an empty database), `0` when it fails. Both
quota queries must succeed and resource identifiers must be recognized before
any quota limit or usage sample is emitted. Failures log the operation and
safe error classification, omit all quota samples and preserve unrelated
metrics and a successful HTTP scrape. A failed initial Octavia connection also
reports quota success as `0`; when Octavia is disabled this gauge is absent.
Existing `openstack_loadbalancer_up` inventory health remains separate from quota health.
The two quota database reads share a 5-second context deadline, configurable via
`--octavia.quota-query-timeout` / `OCTAVIA_QUOTA_QUERY_TIMEOUT` (a positive Go
duration, for example `4s`). Set this below your scrape timeout with room for
other collection work and response delivery. The default assumes a scrape budget
longer than five seconds; the exporter does not discover Prometheus settings.
Other collectors and the existing Keystone metadata refresh retain their own
behavior, so this is not a global scrape deadline. No schema indexes or
migrations are added.

Measure query plans and latency on a representative snapshot before rollout.

These metrics require the public [openstackdb Octavia quota APIs](https://github.com/samaritanark/openstackdb/pull/2).
That contribution is awaiting acceptance upstream; the tracked v0.2.1 dependency
does not contain these APIs. Builds and tests currently require a temporary Go
workspace selecting that public library source alongside this exporter.
57 changes: 44 additions & 13 deletions cmd/openstack-database-exporter/main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package main

import (
"fmt"
"net/http"
"os"
"time"

"github.com/alecthomas/kingpin/v2"
"github.com/prometheus/client_golang/prometheus/promhttp"
Expand All @@ -13,9 +15,13 @@ import (
webflag "github.com/prometheus/exporter-toolkit/web/kingpinflag"

"github.com/vexxhost/openstack_database_exporter/internal/collector"
"github.com/vexxhost/openstack_database_exporter/internal/collector/octavia"
)

var (
quotaQueryTimeout = kingpin.Flag("octavia.quota-query-timeout", "Shared deadline for Octavia quota database queries; must be positive and shorter than the scrape timeout.").Default("5s").Envar("OCTAVIA_QUOTA_QUERY_TIMEOUT").Duration()
quotaDefaultsFile = kingpin.Flag("quota.defaults-file", "Optional JSON file containing all seven Octavia quota defaults; otherwise upstream unlimited defaults are assumed.").Envar("QUOTA_DEFAULTS_FILE").String()

metricsPath = kingpin.Flag(
"web.telemetry-path",
"Path under which to expose metrics.",
Expand Down Expand Up @@ -90,20 +96,30 @@ func main() {
logger.Info("Starting openstack_database_exporter", "version", version.Info())
logger.Info("Build context", "build_context", version.BuildContext())

quotaDefaults, err := loadOctaviaQuotaConfig(*octaviaDatabaseURL, *quotaDefaultsFile, *quotaQueryTimeout)
if err != nil {
logger.Error("Invalid Octavia quota configuration", "error", err)
os.Exit(1)
}
if *octaviaDatabaseURL != "" && *quotaDefaultsFile == "" {
logger.Warn("No Octavia quota defaults file configured; assuming Octavia 2025.2 upstream unlimited (-1) defaults")
}
reg := collector.NewRegistry(collector.Config{
CinderDatabaseURL: *cinderDatabaseURL,
GlanceDatabaseURL: *glanceDatabaseURL,
HeatDatabaseURL: *heatDatabaseURL,
IronicDatabaseURL: *ironicDatabaseURL,
KeystoneDatabaseURL: *keystoneDatabaseURL,
MagnumDatabaseURL: *magnumDatabaseURL,
ManilaDatabaseURL: *manilaDatabaseURL,
NeutronDatabaseURL: *neutronDatabaseURL,
OctaviaDatabaseURL: *octaviaDatabaseURL,
PlacementDatabaseURL: *placementDatabaseURL,
NovaDatabaseURL: *novaDatabaseURL,
NovaAPIDatabaseURL: *novaAPIDatabaseURL,
ProjectCacheTTL: *projectCacheTTL,
CinderDatabaseURL: *cinderDatabaseURL,
GlanceDatabaseURL: *glanceDatabaseURL,
HeatDatabaseURL: *heatDatabaseURL,
IronicDatabaseURL: *ironicDatabaseURL,
KeystoneDatabaseURL: *keystoneDatabaseURL,
MagnumDatabaseURL: *magnumDatabaseURL,
ManilaDatabaseURL: *manilaDatabaseURL,
NeutronDatabaseURL: *neutronDatabaseURL,
OctaviaDatabaseURL: *octaviaDatabaseURL,
OctaviaQuotaDefaults: quotaDefaults,
OctaviaQuotaQueryTimeout: *quotaQueryTimeout,
PlacementDatabaseURL: *placementDatabaseURL,
NovaDatabaseURL: *novaDatabaseURL,
NovaAPIDatabaseURL: *novaAPIDatabaseURL,
ProjectCacheTTL: *projectCacheTTL,
}, logger)

http.Handle(*metricsPath, promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
Expand All @@ -130,3 +146,18 @@ func main() {
os.Exit(1)
}
}

// Disabled Octavia must not read or validate configuration for its collectors.
func loadOctaviaQuotaConfig(databaseURL, defaultsFile string, timeout time.Duration) (octavia.QuotaDefaults, error) {
if databaseURL == "" {
return nil, nil
}
if timeout <= 0 {
return nil, fmt.Errorf("octavia quota query timeout must be positive")
}
defaults, err := octavia.LoadQuotaDefaults(defaultsFile)
if err != nil {
return nil, fmt.Errorf("octavia quota defaults file %q: %w", defaultsFile, err)
}
return defaults, nil
}
97 changes: 86 additions & 11 deletions cmd/openstack-database-exporter/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,19 +162,53 @@ func TestIntegration_E2E_FullExporter(t *testing.T) {
('sub-sp01', 'pool-subnet', 'net-001', 4, '10.200.0.0/26', '10.200.0.1', 1, 'proj-001', 'sp-001', 11)`,
)

// Octavia: amphorae, load balancers, VIPs, pools (including soft-deleted resources that should be filtered out)
// Distinct counts catch swapped resource labels. Every child has an existing
// parent, including deleted rows; health monitors use distinct pools.
itest.SeedSQL(t, octaviaRes.DB,
`INSERT INTO amphora (id, compute_id, status, load_balancer_id, lb_network_ip, ha_ip, role, cert_expiration, cert_busy) VALUES
('amp-001', 'compute-001', 'READY', 'lb-001', '10.0.0.1', '10.0.0.2', 'MASTER', '2025-12-31 23:59:59', 0),
('amp-del', 'compute-del', 'DELETED', 'lb-del', '10.0.0.99', '10.0.0.98', 'MASTER', '2024-01-01 00:00:00', 0)`,
`INSERT INTO load_balancer (id, project_id, name, provisioning_status, operating_status, enabled, provider) VALUES
('lb-001', 'proj-abc', 'web-lb', 'ACTIVE', 'ONLINE', 1, 'octavia'),
('lb-del', 'proj-abc', 'deleted-lb', 'DELETED', 'OFFLINE', 0, 'octavia')`,
`INSERT INTO vip (load_balancer_id, ip_address) VALUES ('lb-001', '203.0.113.50')`,
`INSERT INTO pool (id, project_id, name, protocol, lb_algorithm, operating_status, enabled, load_balancer_id, provisioning_status) VALUES
('pool-001', 'proj-abc', 'http-pool', 'HTTP', 'ROUND_ROBIN', 'ONLINE', 1, 'lb-001', 'ACTIVE'),
('pool-del', 'proj-abc', 'deleted-pool', 'TCP', 'ROUND_ROBIN', 'OFFLINE', 0, 'lb-del', 'DELETED')`,
('lb-001','proj-abc','web-lb','ACTIVE','ONLINE',1,'octavia'),
('lb-del','proj-abc','deleted-lb','DELETED','OFFLINE',0,'octavia')`,
`INSERT INTO amphora (id, compute_id, status, load_balancer_id, lb_network_ip, ha_ip, role, cert_expiration, cert_busy) VALUES
('amp-001', 'compute-001', 'READY', 'lb-001', '10.0.0.1', '10.0.0.2', 'MASTER', '2025-12-31 23:59:59', 0),
('amp-del', 'compute-del', 'DELETED', 'lb-del', '10.0.0.99', '10.0.0.98', 'MASTER', '2024-01-01 00:00:00', 0)`,
`INSERT INTO vip (load_balancer_id, ip_address) VALUES ('lb-001','203.0.113.50')`,
`INSERT INTO quotas (project_id,load_balancer,listener,pool,member,health_monitor,l7policy,l7rule)
VALUES ('proj-abc',10,0,NULL,-1,30,60,70)`,
)
for i := 1; i <= 5; i++ {
itest.SeedSQL(t, octaviaRes.DB, fmt.Sprintf(`INSERT INTO pool (id,project_id,name,protocol,lb_algorithm,operating_status,enabled,load_balancer_id,provisioning_status)
VALUES ('pool-%d','proj-abc','pool-%d','HTTP','ROUND_ROBIN','ONLINE',1,'lb-001','ACTIVE')`, i, i))
}
itest.SeedSQL(t, octaviaRes.DB, `INSERT INTO pool (id,project_id,protocol,lb_algorithm,operating_status,enabled,load_balancer_id,provisioning_status)
VALUES ('pool-del','proj-abc','HTTP','ROUND_ROBIN','OFFLINE',0,'lb-del','DELETED')`)
for i := 1; i <= 2; i++ {
itest.SeedSQL(t, octaviaRes.DB, fmt.Sprintf(`INSERT INTO listener (id,project_id,protocol,protocol_port,load_balancer_id,provisioning_status)
VALUES ('listener-%d','proj-abc','HTTP',%d,'lb-001','ACTIVE')`, i, 80+i))
}
itest.SeedSQL(t, octaviaRes.DB, `INSERT INTO listener (id,project_id,protocol,protocol_port,load_balancer_id,provisioning_status)
VALUES ('listener-del','proj-abc','HTTP',80,'lb-del','DELETED')`)
for _, resource := range []struct {
table, parentTable, parentColumn string
count int
}{
{"member", "pool", "pool_id", 4},
{"health_monitor", "pool", "pool_id", 3},
{"l7policy", "listener", "listener_id", 6},
{"l7rule", "l7policy", "l7policy_id", 7},
} {
for i := 1; i <= resource.count; i++ {
parent := resource.parentTable + "-1"
if resource.table == "health_monitor" {
parent = fmt.Sprintf("pool-%d", i)
}
status := "ACTIVE"
if i == resource.count {
status = "ERROR"
} // Non-DELETED states still consume quota.
itest.SeedSQL(t, octaviaRes.DB, fmt.Sprintf("INSERT INTO %s (id,project_id,%s,provisioning_status) VALUES ('%s-%d','proj-abc','%s','%s')", resource.table, resource.parentColumn, resource.table, i, parent, status))
}
itest.SeedSQL(t, octaviaRes.DB, fmt.Sprintf("INSERT INTO %s (id,project_id,%s,provisioning_status) VALUES ('%s-del','proj-abc','%s-del','DELETED')", resource.table, resource.parentColumn, resource.table, resource.parentTable))
}

// Placement: resource providers, classes, inventories, allocations, projects, users, consumers
itest.SeedSQL(t, placementRes.DB,
Expand Down Expand Up @@ -360,9 +394,24 @@ func TestIntegration_E2E_FullExporter(t *testing.T) {
assertMetricExists(t, families, "openstack_neutron_quota_network")

// Octavia
assertGaugeValue(t, families, "openstack_loadbalancer_quota_up", 1)
for _, quota := range []struct {
resource string
usage, limit float64
}{
{"loadbalancer", 1, 10}, {"listener", 2, 0}, {"pool", 5, -1}, {"member", 4, -1},
{"healthmonitor", 3, 30}, {"l7policy", 6, 60}, {"l7rule", 7, 70},
} {
name := "openstack_loadbalancer_quota_" + quota.resource
assertQuotaValue(t, families, name, "proj-abc", "in_use", quota.usage)
assertQuotaValue(t, families, name, "proj-abc", "limit", quota.limit)
// The Keystone project is idle in Octavia and has upstream defaults.
assertQuotaValue(t, families, name, "proj-001", "in_use", 0)
assertQuotaValue(t, families, name, "proj-001", "limit", -1)
}
assertGaugeValue(t, families, "openstack_loadbalancer_total_amphorae", 1)
assertGaugeValue(t, families, "openstack_loadbalancer_total_loadbalancers", 1)
assertGaugeValue(t, families, "openstack_loadbalancer_total_pools", 1)
assertGaugeValue(t, families, "openstack_loadbalancer_total_pools", 5)
assertMetricExists(t, families, "openstack_loadbalancer_amphora_status")
assertMetricExists(t, families, "openstack_loadbalancer_loadbalancer_status")
assertMetricExists(t, families, "openstack_loadbalancer_pool_status")
Expand Down Expand Up @@ -756,3 +805,29 @@ func assertGaugeValue(t *testing.T, families map[string]*dto.MetricFamily, name
t.Errorf("metric %s: expected value %v, got %v", name, expected, actual)
}
}

// Match the project and measurement so another project's value cannot pass.
func assertQuotaValue(t *testing.T, families map[string]*dto.MetricFamily, name, projectID, kind string, expected float64) {
t.Helper()
family, ok := families[name]
if !ok {
t.Errorf("missing metric %s", name)
return
}
matches := 0
for _, metric := range family.Metric {
labels := map[string]string{}
for _, label := range metric.Label {
labels[label.GetName()] = label.GetValue()
}
if labels["tenant_id"] == projectID && labels["type"] == kind {
matches++
if metric.Gauge == nil || metric.GetGauge().GetValue() != expected {
t.Errorf("%s project=%s type=%s: got %v, want %v", name, projectID, kind, metric.GetGauge(), expected)
}
}
}
if matches != 1 {
t.Errorf("%s project=%s type=%s: got %d samples, want 1", name, projectID, kind, matches)
}
}
75 changes: 75 additions & 0 deletions cmd/openstack-database-exporter/startup_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package main

import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"

"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/stretchr/testify/require"
"github.com/vexxhost/openstack_database_exporter/internal/collector"
)

func TestOctaviaQuotaStartup(t *testing.T) {
valid := `{"octavia":{"loadbalancer":0,"listener":1,"pool":2,"member":-1,"healthmonitor":3,"l7policy":4,"l7rule":5},"nova":{"unrelated":"value"}}`
for _, enabled := range []bool{false, true} {
for name, content := range map[string]string{"absent path": "", "missing file": "missing", "malformed": "{", "incomplete": `{"octavia":{"member":1}}`, "unrelated only": `{"nova":{}}`, "valid": valid} {
t.Run(name+map[bool]string{false: " disabled", true: " enabled"}[enabled], func(t *testing.T) {
path := ""
if name != "absent path" {
path = filepath.Join(t.TempDir(), "defaults.json")
if name != "missing file" {
require.NoError(t, os.WriteFile(path, []byte(content), 0600))
}
}
url := ""
if enabled {
url = "unsupported://octavia/test"
}
defaults, err := loadOctaviaQuotaConfig(url, path, 5*time.Second)
if enabled && name != "valid" && name != "absent path" {
require.ErrorContains(t, err, "octavia quota defaults file")
return
}
require.NoError(t, err)
if enabled {
require.NoError(t, defaults.Validate())
if name == "absent path" {
for _, value := range defaults {
require.EqualValues(t, -1, value)
}
} else {
require.EqualValues(t, 0, defaults["loadbalancer"])
require.EqualValues(t, -1, defaults["member"])
}
} else {
require.Nil(t, defaults)
}
// Unsupported synthetic URLs cannot connect to any database. The Nova
// down gauge proves its collector was registered despite irrelevant files.
reg := collector.NewRegistry(collector.Config{NovaDatabaseURL: "unsupported://nova/test", NovaAPIDatabaseURL: "unsupported://nova-api/test", OctaviaDatabaseURL: url, OctaviaQuotaDefaults: defaults}, slog.New(slog.NewTextHandler(io.Discard, nil)))
response := httptest.NewRecorder()
promhttp.HandlerFor(reg, promhttp.HandlerOpts{}).ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
require.Equal(t, http.StatusOK, response.Code)
require.Contains(t, response.Body.String(), "openstack_nova_up 0\n")
if !enabled {
require.NotContains(t, response.Body.String(), "openstack_loadbalancer_quota_up")
}
})
}
}
}

func TestOctaviaQuotaStartupTimeout(t *testing.T) {
for _, timeout := range []time.Duration{0, -time.Second} {
_, err := loadOctaviaQuotaConfig("unsupported://octavia/test", "", timeout)
require.ErrorContains(t, err, "timeout must be positive")
_, err = loadOctaviaQuotaConfig("", "irrelevant", timeout)
require.NoError(t, err)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.26.0
require (
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/alecthomas/kingpin/v2 v2.4.0
github.com/go-sql-driver/mysql v1.9.3
github.com/prometheus/client_golang v1.25.0
github.com/prometheus/client_model v0.6.3
github.com/prometheus/common v0.73.1
Expand Down Expand Up @@ -42,7 +43,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.3.0 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jpillora/backoff v1.0.0 // indirect
Expand Down
Loading
Loading