From 2200a7c44413a3a99252ebc795436de88eb20afe Mon Sep 17 00:00:00 2001 From: David Hulick Date: Wed, 18 Nov 2026 16:46:29 +0000 Subject: [PATCH] fix: expose Nova capacity metrics in bytes Convert RAM quota and memory limits from MiB, and server root disk capacity from GiB, while preserving labels, unlimited limits and signed usage. Add capacity regression coverage and document the breaking metric migration. Signed-off-by: David Hulick --- README.md | 38 ++++++ cmd/openstack-database-exporter/main_test.go | 40 +++++- .../collector/nova/capacity_units_test.go | 118 ++++++++++++++++++ .../nova/inventory_capacity_units_test.go | 68 ++++++++++ internal/collector/nova/limits.go | 13 +- internal/collector/nova/quotas.go | 12 +- internal/collector/nova/server.go | 12 +- 7 files changed, 287 insertions(+), 14 deletions(-) create mode 100644 internal/collector/nova/capacity_units_test.go create mode 100644 internal/collector/nova/inventory_capacity_units_test.go diff --git a/README.md b/README.md index b54bb82e..d9975127 100644 --- a/README.md +++ b/README.md @@ -30,3 +30,41 @@ go build ./cmd/openstack-database-exporter Integration tests load embedded fixtures from the pinned openstackdb module. Database URLs and exporter configuration remain the same. + +## Breaking Nova capacity metric migration + +Nova RAM, memory limits and server root-disk capacity gauges now use bytes. +Old names are removed, with no parallel legacy families. Labels, quota +calculations, defaults and scrape failure behavior are unchanged. The `ram` +resource key remains in its original OpenStack units; only emitted capacities +change. + +| Old metric name | New metric name | Source → bytes | +| --- | --- | --- | +| `openstack_nova_quota_ram` | `openstack_nova_quota_ram_bytes` | MiB × 2^20 | +| `openstack_nova_limits_memory_max` | `openstack_nova_limits_memory_max_bytes` | MiB × 2^20 | +| `openstack_nova_limits_memory_used` | `openstack_nova_limits_memory_used_bytes` | MiB × 2^20 | +| `openstack_nova_server_local_gb` | `openstack_nova_server_local_bytes` | GiB × 2^30 | + +Nova RAM and memory capacities are MiB × 1048576 (2^20). Only quota and memory +limits preserve `-1` as unlimited. Zero remains zero; signed usage, including +`-1`, is scaled. Server root-disk capacity uses GiB × 1073741824 (2^30), with +no unlimited sentinel. Conversion uses floating-point multiplication after +reading the source integer, avoiding integer overflow; Prometheus float64 +precision still applies. + +Quota RAM retains `domain_id`, `tenant`, `type` labels and +`limit`/`in_use`/`reserved` states. Memory limits retain `domain_id`, `tenant`, +`tenant_id`; server root-disk capacity retains `id`, `name`, `tenant_id`. +Usage still comes from Placement and quota reservations remain zero. +`server_local_bytes` still measures only `instances.root_gb`; it does not add +ephemeral disks, swap, or actual disk consumption. Server status, task-state, +CPU and count metrics are unchanged. + +Update dashboard queries, alert thresholds, recording rules, metric allowlists, +and remote consumers together. Remove any old GiB/MiB-to-byte multipliers; +scale thresholds expressed in source units by the matching factor. Filter +unlimited limits before arithmetic (for example, +`openstack_nova_quota_ram_bytes{type="limit"} >= 0`). Historical series retain +their old names and units and need explicit handling in queries spanning the +rollout. diff --git a/cmd/openstack-database-exporter/main_test.go b/cmd/openstack-database-exporter/main_test.go index 6dec8420..1bf29da9 100644 --- a/cmd/openstack-database-exporter/main_test.go +++ b/cmd/openstack-database-exporter/main_test.go @@ -380,7 +380,7 @@ func TestIntegration_E2E_FullExporter(t *testing.T) { assertMetricExists(t, families, "openstack_nova_server_status") assertMetricExists(t, families, "openstack_nova_server_task_state") assertGaugeValue(t, families, "openstack_nova_total_vms", 2) - assertMetricExists(t, families, "openstack_nova_server_local_gb") + assertMetricExists(t, families, "openstack_nova_server_local_bytes") assertMetricExists(t, families, "openstack_nova_running_vms") assertMetricExists(t, families, "openstack_nova_vcpus_available") assertMetricExists(t, families, "openstack_nova_vcpus_used") @@ -388,6 +388,44 @@ func TestIntegration_E2E_FullExporter(t *testing.T) { assertMetricExists(t, families, "openstack_nova_memory_used_bytes") assertMetricExists(t, families, "openstack_nova_quota_cores") assertMetricExists(t, families, "openstack_nova_limits_vcpus_max") + for _, name := range []string{ + "openstack_nova_quota_ram", + "openstack_nova_limits_memory_max", + "openstack_nova_limits_memory_used", + "openstack_nova_server_local_gb", + } { + if _, ok := families[name]; ok { + t.Errorf("replaced capacity metric %s is still emitted", name) + } + } + for _, capacity := range []struct { + name string + label string + want map[string]float64 + }{ + {"openstack_nova_quota_ram_bytes", "type", map[string]float64{"limit": 102400 * (1 << 20), "in_use": 8192 * (1 << 20), "reserved": 0}}, + {"openstack_nova_limits_memory_max_bytes", "", map[string]float64{"": 102400 * (1 << 20)}}, + {"openstack_nova_limits_memory_used_bytes", "", map[string]float64{"": 8192 * (1 << 20)}}, + {"openstack_nova_server_local_bytes", "id", map[string]float64{"inst-001": 20 * (1 << 30), "inst-002": 40 * (1 << 30)}}, + } { + assertMetricExists(t, families, capacity.name) + mf := families[capacity.name] + if mf.GetType() != dto.MetricType_GAUGE || len(mf.GetMetric()) != len(capacity.want) { + t.Errorf("%s: expected gauge with %d samples, got %v", capacity.name, len(capacity.want), mf) + } + for _, m := range mf.GetMetric() { + key := "" + for _, label := range m.GetLabel() { + if label.GetName() == capacity.label { + key = label.GetValue() + } + } + want, ok := capacity.want[key] + if !ok || m.GetGauge() == nil || m.GetGauge().GetValue() != want { + t.Errorf("%s{%s=%q}: expected %v, got %v", capacity.name, capacity.label, key, want, m) + } + } + } // Heat assertMetricExists(t, families, "openstack_heat_stack_status_counter") diff --git a/internal/collector/nova/capacity_units_test.go b/internal/collector/nova/capacity_units_test.go new file mode 100644 index 00000000..c6a117f5 --- /dev/null +++ b/internal/collector/nova/capacity_units_test.go @@ -0,0 +1,118 @@ +package nova + +import ( + "fmt" + "io" + "log/slog" + "regexp" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" + "github.com/vexxhost/openstack_database_exporter/internal/collector/project" + keystone "github.com/vexxhost/openstackdb/keystone/db" + novaapi "github.com/vexxhost/openstackdb/nova/db/api" + placement "github.com/vexxhost/openstackdb/placement/objects" +) + +func TestQuotaAndLimitsCapacityBytes(t *testing.T) { + for _, limits := range []bool{false, true} { + for _, raw := range []int64{-1, 0, 1, 20, 2147483647} { + t.Run(fmt.Sprintf("limits=%v/raw=%d", limits, raw), func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { + mock.ExpectClose() + if err := db.Close(); err != nil { + t.Errorf("close db: %v", err) + } + }() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + mock.ExpectQuery(regexp.QuoteMeta(keystone.ListProjects)).WillReturnRows(sqlmock.NewRows([]string{"id", "name", "description", "enabled", "domain_id", "parent_id", "is_domain", "tags"}).AddRow("p", "project", "", true, "d", "", false, "")) + resolver := project.NewResolver(logger, keystone.New(db), time.Hour) + mock.ExpectQuery(regexp.QuoteMeta(novaapi.QuotaGetAll)).WillReturnRows(sqlmock.NewRows([]string{"id", "project_id", "resource", "hard_limit"}).AddRow(1, "p", "ram", raw)) + usage := raw + if raw == 2147483647 { + usage = 1 << 44 + } + allocations := sqlmock.NewRows([]string{"project_id", "resource_type", "used"}).AddRow("p", "MEMORY_MB", usage).AddRow("p", "VCPU", 2) + consumers := sqlmock.NewRows([]string{"project_id", "instance_count"}).AddRow("p", 3) + defaults := sqlmock.NewRows([]string{"resource", "hard_limit"}) + if limits { + mock.ExpectQuery(regexp.QuoteMeta(novaapi.QuotaClassGetDefaults)).WillReturnRows(defaults) + } + mock.ExpectQuery(regexp.QuoteMeta(placement.GetAllocationsByProject)).WillReturnRows(allocations) + mock.ExpectQuery(regexp.QuoteMeta(placement.GetConsumerCountByProject)).WillReturnRows(consumers) + if !limits { + mock.ExpectQuery(regexp.QuoteMeta(novaapi.QuotaClassGetDefaults)).WillReturnRows(defaults) + } + reg := prometheus.NewPedanticRegistry() + if limits { + reg.MustRegister(&limitsCollectorWrapper{NewLimitsCollector(logger, nil, novaapi.New(db), placement.New(db), resolver)}) + } else { + reg.MustRegister("asCollectorWrapper{NewQuotasCollector(logger, nil, novaapi.New(db), placement.New(db), resolver)}) + } + families, err := reg.Gather() + require.NoError(t, err) + wantLimit := float64(raw) * (1 << 20) + if raw == -1 { + wantLimit = -1 + } + seen := map[string]bool{} + for _, f := range families { + name := f.GetName() + seen[name] = true + require.NotContains(t, []string{"openstack_nova_quota_ram", "openstack_nova_limits_memory_max", "openstack_nova_limits_memory_used"}, name) + for _, m := range f.Metric { + labels := map[string]string{} + for _, l := range m.Label { + labels[l.GetName()] = l.GetValue() + } + require.Equal(t, "d", labels["domain_id"]) + require.Equal(t, "project", labels["tenant"]) + require.Len(t, labels, 3) + switch name { + case "openstack_nova_quota_ram_bytes": + require.Equal(t, "RAM quota in bytes (source MiB multiplied by 2^20); -1 means unlimited only for limits.", f.GetHelp()) + require.Equal(t, dto.MetricType_GAUGE, f.GetType()) + require.NotNil(t, m.Gauge) + require.Contains(t, []string{"limit", "in_use", "reserved"}, labels["type"]) + require.Equal(t, map[string]string{"domain_id": "d", "tenant": "project", "type": labels["type"]}, labels) + require.Equal(t, map[string]float64{"limit": wantLimit, "in_use": float64(usage) * (1 << 20), "reserved": 0}[labels["type"]], m.GetGauge().GetValue()) + case "openstack_nova_limits_memory_max_bytes": + require.Equal(t, "Memory max in bytes (source MiB multiplied by 2^20); -1 means unlimited only for limits.", f.GetHelp()) + require.Equal(t, dto.MetricType_GAUGE, f.GetType()) + require.NotNil(t, m.Gauge) + require.Equal(t, wantLimit, m.GetGauge().GetValue()) + require.Equal(t, "p", labels["tenant_id"]) + case "openstack_nova_limits_memory_used_bytes": + require.Equal(t, "Memory used in bytes (source MiB multiplied by 2^20); -1 means unlimited only for limits.", f.GetHelp()) + require.Equal(t, dto.MetricType_GAUGE, f.GetType()) + require.NotNil(t, m.Gauge) + require.EqualValues(t, float64(usage)*(1<<20), m.GetGauge().GetValue()) + require.Equal(t, "p", labels["tenant_id"]) + case "openstack_nova_quota_cores": + require.Equal(t, map[string]float64{"limit": 20, "in_use": 2, "reserved": 0}[labels["type"]], m.GetGauge().GetValue()) + case "openstack_nova_quota_injected_file_content_bytes": + require.Equal(t, map[string]float64{"limit": 10240, "in_use": 0, "reserved": 0}[labels["type"]], m.GetGauge().GetValue()) + case "openstack_nova_limits_vcpus_used": + require.EqualValues(t, 2, m.GetGauge().GetValue()) + case "openstack_nova_limits_instances_used": + require.EqualValues(t, 3, m.GetGauge().GetValue()) + } + } + } + if limits { + require.True(t, seen["openstack_nova_limits_memory_max_bytes"]) + require.True(t, seen["openstack_nova_limits_memory_used_bytes"]) + } else { + require.True(t, seen["openstack_nova_quota_ram_bytes"]) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } + } +} diff --git a/internal/collector/nova/inventory_capacity_units_test.go b/internal/collector/nova/inventory_capacity_units_test.go new file mode 100644 index 00000000..0c7248c6 --- /dev/null +++ b/internal/collector/nova/inventory_capacity_units_test.go @@ -0,0 +1,68 @@ +package nova + +import ( + "fmt" + "io" + "log/slog" + "regexp" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" + api "github.com/vexxhost/openstackdb/nova/db/api" + queries "github.com/vexxhost/openstackdb/nova/db/main" +) + +func TestInventoryCapacityBytes(t *testing.T) { + for _, raw := range []int32{-1, 0, 1, 20, 2147483647} { + t.Run(fmt.Sprint(raw), func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { + mock.ExpectClose() + if err := db.Close(); err != nil { + t.Errorf("close db: %v", err) + } + }() + rows := sqlmock.NewRows([]string{"id", "uuid", "display_name", "user_id", "project_id", "host", "availability_zone", "vm_state", "power_state", "task_state", "memory_mb", "vcpus", "root_gb", "ephemeral_gb", "launched_at", "terminated_at", "instance_type_id", "deleted"}).AddRow(1, "id", "name", "u", "p", "host", "az", "active", 1, nil, 2048, 2, raw, 99, nil, nil, 1, 0) + mock.ExpectQuery(regexp.QuoteMeta(queries.InstanceGetAll)).WillReturnRows(rows) + mock.ExpectQuery(regexp.QuoteMeta(api.FlavorGetAll)).WillReturnRows(sqlmock.NewRows([]string{"id"})) + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + reg := prometheus.NewPedanticRegistry() + reg.MustRegister(&serverCollectorWrapper{NewServerCollector(logger, queries.New(db), api.New(db))}) + families, err := reg.Gather() + require.NoError(t, err) + seen := map[string]bool{} + for _, f := range families { + name := f.GetName() + seen[name] = true + require.NotEqual(t, "openstack_nova_server_local_gb", name) + if name == "openstack_nova_server_local_bytes" { + require.Len(t, f.Metric, 1) + require.Equal(t, "Server root disk capacity in bytes (source root_gb in GiB multiplied by 2^30).", f.GetHelp()) + require.Equal(t, dto.MetricType_GAUGE, f.GetType()) + m := f.Metric[0] + require.NotNil(t, m.Gauge) + require.Equal(t, float64(raw)*(1<<30), m.GetGauge().GetValue()) + labels := map[string]string{} + for _, l := range m.Label { + labels[l.GetName()] = l.GetValue() + } + require.Equal(t, map[string]string{"id": "id", "name": "name", "tenant_id": "p"}, labels) + } + if name == "openstack_nova_server_status" { + require.Len(t, f.Metric, 1) + } + if name == "openstack_nova_total_vms" { + require.EqualValues(t, 1, f.Metric[0].GetGauge().GetValue()) + } + } + require.True(t, seen["openstack_nova_server_local_bytes"]) + require.True(t, seen["openstack_nova_server_status"]) + require.True(t, seen["openstack_nova_total_vms"]) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/internal/collector/nova/limits.go b/internal/collector/nova/limits.go index aee4b2e0..acaae9c4 100644 --- a/internal/collector/nova/limits.go +++ b/internal/collector/nova/limits.go @@ -49,14 +49,14 @@ func NewLimitsCollector(logger *slog.Logger, novaDB *nova.Queries, novaAPIDB *no nil, ), "limits_memory_max": prometheus.NewDesc( - prometheus.BuildFQName(Namespace, Subsystem, "limits_memory_max"), - "limits_memory_max", + prometheus.BuildFQName(Namespace, Subsystem, "limits_memory_max_bytes"), + "Memory max in bytes (source MiB multiplied by 2^20); -1 means unlimited only for limits.", []string{"domain_id", "tenant", "tenant_id"}, nil, ), "limits_memory_used": prometheus.NewDesc( - prometheus.BuildFQName(Namespace, Subsystem, "limits_memory_used"), - "limits_memory_used", + prometheus.BuildFQName(Namespace, Subsystem, "limits_memory_used_bytes"), + "Memory used in bytes (source MiB multiplied by 2^20); -1 means unlimited only for limits.", []string{"domain_id", "tenant", "tenant_id"}, nil, ), @@ -209,6 +209,9 @@ func (c *LimitsCollector) collectLimitsMetrics(ch chan<- prometheus.Metric) erro memoryMax = limitsByProject[projectID]["ram"] } + if memoryMax != -1 { + memoryMax *= 1 << 20 + } ch <- prometheus.MustNewConstMetric( c.limitsMetrics["limits_memory_max"], prometheus.GaugeValue, @@ -218,7 +221,7 @@ func (c *LimitsCollector) collectLimitsMetrics(ch chan<- prometheus.Metric) erro ch <- prometheus.MustNewConstMetric( c.limitsMetrics["limits_memory_used"], prometheus.GaugeValue, - memoryUsedByProject[projectID], + memoryUsedByProject[projectID]*(1<<20), domainID, tenantName, projectID, ) diff --git a/internal/collector/nova/quotas.go b/internal/collector/nova/quotas.go index c324d725..efc9e86e 100644 --- a/internal/collector/nova/quotas.go +++ b/internal/collector/nova/quotas.go @@ -89,8 +89,8 @@ func NewQuotasCollector(logger *slog.Logger, novaDB *nova.Queries, novaAPIDB *no nil, ), "quota_ram": prometheus.NewDesc( - prometheus.BuildFQName(Namespace, Subsystem, "quota_ram"), - "quota_ram", + prometheus.BuildFQName(Namespace, Subsystem, "quota_ram_bytes"), + "RAM quota in bytes (source MiB multiplied by 2^20); -1 means unlimited only for limits.", []string{"domain_id", "tenant", "type"}, nil, ), @@ -263,6 +263,14 @@ func (c *QuotasCollector) collectQuotaMetrics(ch chan<- prometheus.Metric) error // Reserved is always 0 (placement doesn't track reservations this way) reserved := float64(0) + if quotaType == "ram" { + usage *= 1 << 20 + reserved *= 1 << 20 + if limit != -1 { + limit *= 1 << 20 + } + } + // Emit the three metrics (in_use, limit, reserved) for each quota type metricName := "quota_" + quotaType if desc, exists := c.quotaMetrics[metricName]; exists { diff --git a/internal/collector/nova/server.go b/internal/collector/nova/server.go index ff8a8237..7d5e3cb2 100644 --- a/internal/collector/nova/server.go +++ b/internal/collector/nova/server.go @@ -110,9 +110,9 @@ func NewServerCollector(logger *slog.Logger, novaDB *nova.Queries, novaAPIDB *no novaDB: novaDB, novaAPIDB: novaAPIDB, serverMetrics: map[string]*prometheus.Desc{ - "server_local_gb": prometheus.NewDesc( - prometheus.BuildFQName(Namespace, Subsystem, "server_local_gb"), - "server_local_gb", + "server_local_bytes": prometheus.NewDesc( + prometheus.BuildFQName(Namespace, Subsystem, "server_local_bytes"), + "Server root disk capacity in bytes (source root_gb in GiB multiplied by 2^30).", []string{"id", "name", "tenant_id"}, nil, ), @@ -183,11 +183,11 @@ func (c *ServerCollector) collectServerMetrics(ch chan<- prometheus.Metric) erro azSet[instance.AvailabilityZone.String] = true } - // Server local GB - using root_gb from instance + // Server root disk bytes - using root_gb from instance ch <- prometheus.MustNewConstMetric( - c.serverMetrics["server_local_gb"], + c.serverMetrics["server_local_bytes"], prometheus.GaugeValue, - float64(instance.RootGb.Int32), + float64(instance.RootGb.Int32)*(1<<30), instance.Uuid, instance.DisplayName.String, instance.ProjectID.String,