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
96 changes: 96 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,99 @@ These metrics require the public [openstackdb Octavia quota APIs](https://github
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.

### Neutron project quotas


The existing `openstack_neutron_quota_floatingip`, `quota_router`,
`quota_network`, `quota_port`, `quota_security_group`, and
`quota_security_group_rule` families report `type="limit|used|reserved"` (each
suffix has the `openstack_neutron_` prefix). All quota families now have
`tenant,tenant_id,domain_id,type` labels. The original Neutron `type="used"`
convention is preserved for all nine families, without aliases. Additional
identity labels change series identity: review exact label matching, joins,
aggregations and recording rules, even where existing `type="used"` selectors
still work. Group by `tenant_id` for project identity and `domain_id` for domain
attribution. Names are not unique. Unknown Keystone owners retain their project
ID as `tenant` and an empty `domain_id`; no domain is inferred from a name.

This implementation assumes **Neutron 2025.2 DbQuotaNoLockDriver**. Usage counts
rows owned directly by each project; reservations sum active joined
`reservations`/`resourcedeltas` rows with `expiration >=` one UTC database-clock cutoff per scrape.
Expired and NULL-expiration reservations are excluded. Multiple expiration
groups contribute to the same total, matching corrected 27.0.4 aggregation.
It does not use `quotausages` or support legacy/null/custom driver accounting.
Separate SQL reads can race with mutations.

Extend the shared `--quota.defaults-file` JSON with:

```json
{"neutron":{"floatingip":50,"router":10,"network":100,"port":500,"security_group":10,"security_group_rule":100}}
```

A supplied `neutron` section requires these six integer values and optionally
accepts `subnet`, `subnetpool`, and `rbac_policy`. When omitted, these optional
defaults are `100`, `-1` (the upstream global `default_quota`), and `10`,
respectively. Existing six-key files remain valid. NULLs, missing required keys,
duplicate keys, trailing content, unknown resources and non-integers are
invalid. Zero is valid; negative configured defaults normalize to unlimited `-1`
as in Neutron. If no section/file is supplied, the collector logs its upstream
2025.2 default assumption (values shown above). Project overrides take
precedence, including zero and recorded negative limits. These defaults are
independent of other services. SQL alone cannot discover deployment
configuration.

`--neutron.quota-query-timeout` (`NEUTRON_QUOTA_QUERY_TIMEOUT`, default `5s`)
provides a positive shared deadline for quota SQL reads. Optional metadata
refresh is bounded by the remaining time in that deadline. Set it below the
scrape timeout. `openstack_neutron_quota_up` is 1 only after required SQL reads
succeed; query, timeout or global configuration failures emit only quota health
0. Isolated malformed records omit affected scopes with health 1. It remains
registered after a connection failure, separately from inventory
`openstack_neutron_up`. Missing metadata uses cached data or project-ID
fallback; refresh failures are logged without database error text. Metadata
freshness is not certified by quota health. A metadata refresh that exhausts the
remaining deadline does not discard valid quota samples or set quota health to
0. Invalid defaults or timeout settings are logged once at startup with
structured source, known key and reason fields; raw configuration, file paths,
unknown key text and driver errors are not logged. Invalid Neutron-section
defaults or timeout settings leave unrelated metrics operational. Shared-file
parsing failures may still prevent startup when another service rejects the
file.

Supported-resource NULL overrides, duplicate project/resource quota or usage records, duplicate reservation
deltas, invalid reservation amounts and negative usage/reservation values omit all three
measurements for the affected `(project_id, resource)`. Neutron applies stored
NULL overrides directly; they do not imply inheritance. Zero and negative
(unlimited) limits remain valid. Missing owners conservatively omit the affected
resource across projects; missing resources omit that owner's resources. If
neither identifier is usable, all quota scopes are omitted. Later records cannot
restore invalidated scopes. Unknown extension resources are ignored for accounting
but their owners are discovered. Successful empty SQL results establish legitimate
zero usage/reservations. All nine resources, including `subnet`, `subnetpool` and
`rbac_policy`, report actual active reservations (27 series per healthy project).

`openstack_neutron_quota_skipped_records` is an unlabeled gauge emitted on
successful SQL collection, including zero on clean scrapes. It counts returned
records that fail validation, including each extra duplicate row; an invalid
usage aggregate counts once; each malformed raw reservation delta counts once. The first
otherwise valid row in an ambiguous group is not counted again. It does not count
omitted metric samples, SQL-filtered records, metadata failures or unsupported
extensions. It is absent when collection fails globally. Warnings use controlled
reasons, allowlisted resource names and hashed owner identifiers, with at most one
warning per reason per scrape.

Neutron stores naive UTC expiration timestamps. The reservation query uses
`UTC_TIMESTAMP()` once per statement, independently of the exporter clock and
connection location. Explicitly empty usage and reservation owners are
system-owned and are skipped. NULL and whitespace owners returned by SQL
remain invalid; SQL-filtered records are not counted as skipped.

Metadata fallback can temporarily change series identity until Keystone enrichment
succeeds. Validate dashboard queries and alerts against the new identity labels
before production rollout.

Before rollout, confirm the deployed driver, effective defaults, enabled resource
plugins, reservation schema, Keystone access, query plans and API patch version.
Do not sum unlimited limits as finite capacity. Use one authoritative quota
exporter target to avoid double counting overlapping API/database metrics.
24 changes: 22 additions & 2 deletions cmd/openstack-database-exporter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"log/slog"
"net/http"
"os"
"time"
Expand All @@ -15,12 +16,14 @@ 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/neutron"
"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()
neutronQuotaQueryTimeout = kingpin.Flag("neutron.quota-query-timeout", "Shared deadline for Neutron quota reads; must be positive and shorter than the scrape timeout.").Default("5s").Envar("NEUTRON_QUOTA_QUERY_TIMEOUT").Duration()
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 quota defaults for enabled Octavia and Neutron services; otherwise service defaults are assumed.").Envar("QUOTA_DEFAULTS_FILE").String()

metricsPath = kingpin.Flag(
"web.telemetry-path",
Expand Down Expand Up @@ -104,6 +107,7 @@ func main() {
if *octaviaDatabaseURL != "" && *quotaDefaultsFile == "" {
logger.Warn("No Octavia quota defaults file configured; assuming Octavia 2025.2 upstream unlimited (-1) defaults")
}
neutronOptions := loadNeutronQuotaConfig(*neutronDatabaseURL, *quotaDefaultsFile, *neutronQuotaQueryTimeout, logger)
reg := collector.NewRegistry(collector.Config{
CinderDatabaseURL: *cinderDatabaseURL,
GlanceDatabaseURL: *glanceDatabaseURL,
Expand All @@ -113,6 +117,7 @@ func main() {
MagnumDatabaseURL: *magnumDatabaseURL,
ManilaDatabaseURL: *manilaDatabaseURL,
NeutronDatabaseURL: *neutronDatabaseURL,
NeutronQuotaOptions: neutronOptions,
OctaviaDatabaseURL: *octaviaDatabaseURL,
OctaviaQuotaDefaults: quotaDefaults,
OctaviaQuotaQueryTimeout: *quotaQueryTimeout,
Expand Down Expand Up @@ -161,3 +166,18 @@ func loadOctaviaQuotaConfig(databaseURL, defaultsFile string, timeout time.Durat
}
return defaults, nil
}

// Invalid Neutron configuration leaves the exporter running with quota_up=0.
func loadNeutronQuotaConfig(databaseURL, defaultsFile string, timeout time.Duration, logger *slog.Logger) neutron.QuotaOptions {
opts := neutron.QuotaOptions{QueryTimeout: timeout}
if databaseURL == "" {
return opts
}
if timeout <= 0 {
opts.ConfigError = fmt.Errorf("neutron quota query timeout must be positive")
logger.Error("Invalid Neutron quota configuration", "service", "neutron", "source", "neutron.quota-query-timeout", "reason", "must be positive")
return opts
}
opts.Defaults, opts.ConfigError = neutron.LoadQuotaDefaults(defaultsFile, logger)
return opts
}
108 changes: 105 additions & 3 deletions cmd/openstack-database-exporter/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,8 @@ func TestIntegration_E2E_FullExporter(t *testing.T) {
)

// Neutron: agents, router bindings, routers, floating IPs, networks, subnets, ports, security groups, quotas
now := time.Now().Format("2006-01-02 15:04:05")
itest.SeedSQL(t, neutronRes.DB,
fmt.Sprintf("INSERT INTO agents (id, agent_type, `binary`, topic, host, admin_state_up, created_at, started_at, heartbeat_timestamp, configurations) VALUES ('agent-001', 'L3 agent', 'neutron-l3-agent', 'l3_agent', 'ctrl-01', 1, '%s', '%s', '%s', '{}')", now, now, now),
"INSERT INTO agents (id, agent_type, `binary`, topic, host, admin_state_up, created_at, started_at, heartbeat_timestamp, configurations) VALUES ('agent-001', 'L3 agent', 'neutron-l3-agent', 'l3_agent', 'ctrl-01', 1, NOW(), NOW(), NOW(), '{}')",
`INSERT INTO ha_router_agent_port_bindings (port_id, router_id, l3_agent_id, state) VALUES
('port-001', 'router-001', 'agent-001', 'active')`,
`INSERT INTO standardattributes (id, resource_type, created_at) VALUES
Expand Down Expand Up @@ -391,7 +390,13 @@ func TestIntegration_E2E_FullExporter(t *testing.T) {
assertMetricExists(t, families, "openstack_neutron_subnets_total")
assertMetricExists(t, families, "openstack_neutron_subnets_free")
assertMetricExists(t, families, "openstack_neutron_subnets_used")
assertMetricExists(t, families, "openstack_neutron_quota_network")
assertGaugeValue(t, families, "openstack_neutron_quota_up", 1)
assertGaugeValue(t, families, "openstack_neutron_quota_skipped_records", 0)
for _, resource := range []string{"floatingip", "network", "port", "rbac_policy", "router", "security_group", "security_group_rule", "subnet", "subnetpool"} {
assertQuotaValue(t, families, "openstack_neutron_quota_"+resource, "proj-001", "reserved", 0)
}
assertQuotaValue(t, families, "openstack_neutron_quota_network", "proj-001", "limit", 200)
assertQuotaValue(t, families, "openstack_neutron_quota_network", "proj-001", "used", 2)

// Octavia
assertGaugeValue(t, families, "openstack_loadbalancer_quota_up", 1)
Expand Down Expand Up @@ -831,3 +836,100 @@ func assertQuotaValue(t *testing.T, families map[string]*dto.MetricFamily, name,
t.Errorf("%s project=%s type=%s: got %d samples, want 1", name, projectID, kind, matches)
}
}

// Exercise raw reservation accounting through the production registry and HTTP
// handler. Expirations use the database clock, with a wide deterministic margin.
func TestIntegration_E2E_NeutronReservations(t *testing.T) {
itest.SkipIfNoDocker(t)
res := itest.NewMySQLContainerWithURL(t, "neutron-reservations", "../../sql/neutron/schema.sql")
resources := []string{"floatingip", "network", "port", "rbac_policy", "router", "security_group", "security_group_rule", "subnet", "subnetpool"}
itest.SeedSQL(t, res.DB,
`INSERT INTO networks (id,project_id,status,standard_attr_id) VALUES ('usage','usage-only','ACTIVE',1)`,
`INSERT INTO reservations (id,project_id,expiration) VALUES
('active-a','reservation-only',UTC_TIMESTAMP() + INTERVAL 1 HOUR),
('active-b','reservation-only',UTC_TIMESTAMP() + INTERVAL 2 HOUR),
('expired','reservation-only',UTC_TIMESTAMP() - INTERVAL 1 HOUR),
('expired-owner','expired-only',UTC_TIMESTAMP() - INTERVAL 1 HOUR),
('no-expiration','null-expiration-only',NULL),
('system','',UTC_TIMESTAMP() + INTERVAL 1 HOUR)`,
`INSERT INTO resourcedeltas (resource,reservation_id,amount) VALUES
('port','expired-owner',101),('port','no-expiration',103),('port','system',NULL)`,
)
for i, resource := range resources {
_, err := res.DB.Exec(`INSERT INTO resourcedeltas (resource,reservation_id,amount) VALUES (?, 'active-a', ?),(?, 'active-b', ?),(?, 'expired', 100)`, resource, i+1, resource, i+2, resource)
if err != nil {
t.Fatal(err)
}
}
reg := collector.NewRegistry(collector.Config{NeutronDatabaseURL: res.URL}, promslog.New(&promslog.Config{}))
ts := httptest.NewServer(promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
defer ts.Close()
for range 2 {
families := scrapeAndParse(t, ts.URL)
assertGaugeValue(t, families, "openstack_neutron_up", 1)
assertGaugeValue(t, families, "openstack_neutron_quota_up", 1)
assertGaugeValue(t, families, "openstack_neutron_quota_skipped_records", 0)
assertGaugeValue(t, families, "openstack_neutron_networks", 1)
for i, resource := range resources {
name := "openstack_neutron_quota_" + resource
family := families[name]
if family == nil {
t.Fatalf("missing %s", name)
}
if family.GetType() != dto.MetricType_GAUGE || family.GetHelp() != "quota_"+resource || len(family.Metric) != 6 {
t.Fatalf("unexpected family contract: %s", family)
}
assertQuotaValue(t, families, name, "reservation-only", "reserved", float64(2*i+3))
assertQuotaValue(t, families, name, "reservation-only", "used", 0)
used := float64(0)
if resource == "network" {
used = 1
}
assertQuotaValue(t, families, name, "usage-only", "used", used)
assertQuotaValue(t, families, name, "usage-only", "reserved", 0)
for _, metric := range family.Metric {
labels := map[string]string{}
for _, label := range metric.Label {
labels[label.GetName()] = label.GetValue()
}
if len(labels) != 4 || labels["tenant"] != labels["tenant_id"] || labels["domain_id"] != "" || (labels["tenant_id"] != "reservation-only" && labels["tenant_id"] != "usage-only") {
t.Fatalf("unexpected identity labels: %v", labels)
}
}
}
}

// A later valid delta must not repair an earlier NULL or negative delta.
itest.SeedSQL(t, res.DB,
`INSERT INTO reservations VALUES ('bad-a','reservation-only',UTC_TIMESTAMP() + INTERVAL 1 HOUR),('bad-b','reservation-only',UTC_TIMESTAMP() + INTERVAL 1 HOUR)`,
`INSERT INTO resourcedeltas VALUES ('port','bad-a',-1),('port','bad-b',NULL)`,
)
families := scrapeAndParse(t, ts.URL)
assertGaugeValue(t, families, "openstack_neutron_quota_up", 1)
assertGaugeValue(t, families, "openstack_neutron_quota_skipped_records", 2)
for _, metric := range families["openstack_neutron_quota_port"].Metric {
for _, label := range metric.Label {
if label.GetName() == "tenant_id" && label.GetValue() == "reservation-only" {
t.Fatal("poisoned port scope was emitted")
}
}
}
assertQuotaValue(t, families, "openstack_neutron_quota_network", "reservation-only", "reserved", 5)

// A failed required reservation read cannot become reserved=0, and the
// inventory and HTTP endpoint must remain available.
itest.SeedSQL(t, res.DB, `RENAME TABLE reservations TO unavailable_reservations`)
families = scrapeAndParse(t, ts.URL)
assertGaugeValue(t, families, "openstack_neutron_quota_up", 0)
assertGaugeValue(t, families, "openstack_neutron_networks", 1)
assertGaugeValue(t, families, "openstack_neutron_up", 1)
for name := range families {
if strings.HasPrefix(name, "openstack_neutron_quota_") && name != "openstack_neutron_quota_up" {
t.Errorf("failed quota read emitted %s", name)
}
}
itest.SeedSQL(t, res.DB, `RENAME TABLE unavailable_reservations TO reservations`, `DELETE FROM resourcedeltas WHERE reservation_id IN ('bad-a','bad-b')`)
families = scrapeAndParse(t, ts.URL)
assertGaugeValue(t, families, "openstack_neutron_quota_skipped_records", 0)
assertQuotaValue(t, families, "openstack_neutron_quota_port", "reservation-only", "reserved", 7)
}
60 changes: 60 additions & 0 deletions cmd/openstack-database-exporter/neutron_config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"bytes"
"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 TestNeutronQuotaConfig(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
disabled := loadNeutronQuotaConfig("", "missing", -time.Second, logger)
require.NoError(t, disabled.ConfigError)
for _, timeout := range []time.Duration{0, -time.Second} {
opts := loadNeutronQuotaConfig("configured", "", timeout, logger)
require.Error(t, opts.ConfigError)
}
opts := loadNeutronQuotaConfig("configured", "missing", time.Second, logger)
require.Error(t, opts.ConfigError)
opts = loadNeutronQuotaConfig("configured", "", time.Second, logger)
require.NoError(t, opts.ConfigError)
require.NoError(t, opts.Defaults.Validate())
}

func TestNeutronInvalidConfigurationKeepsExporterOperational(t *testing.T) {
for _, timeout := range []time.Duration{-time.Second, time.Second} {
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
path := filepath.Join(t.TempDir(), "defaults.json")
require.NoError(t, os.WriteFile(path, []byte(`{"neutron":{"port":"mysql://secret:password@host"}}`), 0600))
opts := loadNeutronQuotaConfig("configured", path, timeout, logger)
require.Error(t, opts.ConfigError)
reg := collector.NewRegistry(collector.Config{
NeutronDatabaseURL: "unsupported://neutron/test", NeutronQuotaOptions: opts,
NovaDatabaseURL: "unsupported://nova/test", NovaAPIDatabaseURL: "unsupported://nova-api/test",
}, logger)
before := logs.String()
for range 2 {
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_neutron_quota_up 0\n")
require.Contains(t, response.Body.String(), "openstack_nova_up 0\n")
}
require.Equal(t, before, logs.String())
require.Contains(t, logs.String(), "Invalid Neutron quota configuration")
for _, secret := range []string{"secret", "password", "mysql://"} {
require.NotContains(t, logs.String(), secret)
}
}
}
Loading
Loading