From 1240a8cbc5b80bfd4d7194985acdfa2a275b783d Mon Sep 17 00:00:00 2001 From: David Hulick Date: Wed, 18 Nov 2026 14:19:37 +0000 Subject: [PATCH] fix(cinder): emit volume inventory once per volume Group attachment rows by volume ID for inventory and status counts. Retain distinct nonempty server IDs in sorted order while preserving GiB capacity and existing labels. Cover duplicate and reordered attachments with pedantic gathering and repeated HTTP exposition alongside Heat metrics. Signed-off-by: David Hulick --- README.md | 15 ++ internal/collector/cinder/volumes.go | 32 ++++- internal/collector/cinder/volumes_test.go | 161 ++++++++++++++++++++++ 3 files changed, 204 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b54bb82e..ac9bcf1e 100644 --- a/README.md +++ b/README.md @@ -30,3 +30,18 @@ go build ./cmd/openstack-database-exporter Integration tests load embedded fixtures from the pinned openstackdb module. Database URLs and exporter configuration remain the same. + +## Cinder volumes + +`openstack_cinder_volume_gb` and `openstack_cinder_volume_status` emit one +sample per volume. Capacity remains in GiB, and the status metric's `size` label +retains the raw GiB value. The `server_id` label is empty for no known server, +a single server UUID for one server, or a comma-separated, lexically sorted set +of distinct server UUIDs for multiple servers. This retains multiattachment +metadata without counting capacity more than once. Queries matching a single +`server_id` exactly will not match volumes with multiple servers. + +The attachment query excludes soft-deleted attachments. It does not expose +attachment status or timestamps, so nondeleted historical records still +contribute their server IDs. Duplicate join rows do not affect samples, volume +counts, or status counts. Volume and status counts count distinct volume IDs. diff --git a/internal/collector/cinder/volumes.go b/internal/collector/cinder/volumes.go index f1fe4027..feeb25dc 100644 --- a/internal/collector/cinder/volumes.go +++ b/internal/collector/cinder/volumes.go @@ -4,7 +4,9 @@ import ( "context" "database/sql" "log/slog" + "slices" "strconv" + "strings" "github.com/prometheus/client_golang/prometheus" "github.com/vexxhost/openstack_database_exporter/internal/util" @@ -106,6 +108,21 @@ func (c *VolumesCollector) Collect(ch chan<- prometheus.Metric) { return } + // The attachment join can return multiple rows per volume. Keep one volume + // for capacity and counts, and retain every distinct nonempty server ID. + // All other projected fields come from the volume and its volume type. + byID := make(map[string]cinderdb.VolumeGetAllWithAttachmentsRow, len(volumes)) + servers := make(map[string]map[string]struct{}, len(volumes)) + for _, volume := range volumes { + byID[volume.ID] = volume + if servers[volume.ID] == nil { + servers[volume.ID] = make(map[string]struct{}) + } + if volume.ServerID.String != "" { + servers[volume.ID][volume.ServerID.String] = struct{}{} + } + } + volume_status_counter := map[string]int{ "creating": 0, "available": 0, @@ -129,7 +146,14 @@ func (c *VolumesCollector) Collect(ch chan<- prometheus.Metric) { "extending": 0, } - for _, volume := range volumes { + for id, volume := range byID { + serverIDs := make([]string, 0, len(servers[id])) + for serverID := range servers[id] { + serverIDs = append(serverIDs, serverID) + } + slices.Sort(serverIDs) + serverID := strings.Join(serverIDs, ",") + volume_status_counter[volume.Status.String]++ ch <- prometheus.MustNewConstMetric( @@ -144,7 +168,7 @@ func (c *VolumesCollector) Collect(ch chan<- prometheus.Metric) { volume.ProjectID.String, volume.UserID.String, volume.VolumeType.String, - volume.ServerID.String, + serverID, ) ch <- prometheus.MustNewConstMetric( @@ -179,7 +203,7 @@ func (c *VolumesCollector) Collect(ch chan<- prometheus.Metric) { volume.ProjectID.String, strconv.Itoa(int(volume.Size.Int32)), volume.VolumeType.String, - volume.ServerID.String, + serverID, ) } @@ -195,7 +219,7 @@ func (c *VolumesCollector) Collect(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric( volumesDesc, prometheus.GaugeValue, - float64(len(volumes)), + float64(len(byID)), ) ch <- prometheus.MustNewConstMetric(volumesUpDesc, prometheus.GaugeValue, 1) diff --git a/internal/collector/cinder/volumes_test.go b/internal/collector/cinder/volumes_test.go index 76edb079..2c4182e2 100644 --- a/internal/collector/cinder/volumes_test.go +++ b/internal/collector/cinder/volumes_test.go @@ -1,13 +1,26 @@ package cinder import ( + "bytes" "database/sql" + "io" + "log/slog" + "net/http" + "net/http/httptest" "regexp" + "slices" "testing" "github.com/DATA-DOG/go-sqlmock" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + dto "github.com/prometheus/client_model/go" + "github.com/prometheus/common/expfmt" + "github.com/stretchr/testify/require" + "github.com/vexxhost/openstack_database_exporter/internal/collector/heat" "github.com/vexxhost/openstack_database_exporter/internal/testutil" cinderdb "github.com/vexxhost/openstackdb/cinder/db" + heatdb "github.com/vexxhost/openstackdb/heat/db" ) func TestVolumesCollector(t *testing.T) { @@ -77,3 +90,151 @@ openstack_cinder_volumes 2 testutil.RunCollectorTests(t, tests, NewVolumesCollector) } + +func TestVolumesCollectorAttachmentRows(t *testing.T) { + tests := []struct { + name string + servers []any + want string + }{ + {name: "unattached", servers: []any{nil}, want: ""}, + {name: "one attachment", servers: []any{"server-a"}, want: "server-a"}, + // Soft-deleted history is excluded by the SQL join. Nondeleted historical + // rows cannot be distinguished from current attachments in this projection; + // retain their server IDs rather than choosing an arbitrary attachment. + {name: "nondeleted historical attachments", servers: []any{"old-server", "server-a", "old-server"}, want: "old-server,server-a"}, + {name: "multiple active attachments", servers: []any{"server-b", "server-a"}, want: "server-a,server-b"}, + {name: "four identical join rows", servers: []any{"server-a", "server-a", "server-a", "server-a"}, want: "server-a"}, + {name: "duplicate multiattachment rows", servers: []any{"server-b", "server-a", "server-b", "server-a"}, want: "server-a,server-b"}, + {name: "unknown servers alongside known servers", servers: []any{nil, "", "server-b", "server-a", nil}, want: "server-a,server-b"}, + {name: "duplicate unknown servers", servers: []any{nil, "", nil, ""}, want: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var baseline string + // Rotate and reverse the rows, also changing where a different volume + // appears, to catch first/last-row selection. + for order := 0; order < 2*len(tt.servers); order++ { + servers := slices.Clone(tt.servers) + if order%2 != 0 { + slices.Reverse(servers) + } + offset := order / 2 + servers = append(servers[offset:], servers[:offset]...) + db, mock, err := sqlmock.New() + require.NoError(t, err) + // Both collectors share one mock connection and one close expectation. + db.SetMaxOpenConns(1) + t.Cleanup(func() { + mock.ExpectClose() + if err := db.Close(); err != nil { + t.Errorf("close db: %v", err) + } + }) + mock.MatchExpectationsInOrder(false) + // Supply the same fixture for a pedantic gather and two HTTP scrapes. + for scrape := 0; scrape < 3; scrape++ { + rows := sqlmock.NewRows([]string{ + "id", "name", "size", "status", "availability_zone", + "bootable", "project_id", "user_id", "volume_type", "server_id", + }) + for i, server := range servers { + rows.AddRow("volume", "test", 7, "in-use", "nova", true, "project", "user", "fast", server) + if i == order%len(servers) { + rows.AddRow("unattached", "other", 3, "available", "nova", false, "project", "user", "fast", nil) + } + } + mock.ExpectQuery(regexp.QuoteMeta(cinderdb.VolumeGetAllWithAttachments)).WillReturnRows(rows) + mock.ExpectQuery(regexp.QuoteMeta(heatdb.StackGetAll)).WillReturnRows( + sqlmock.NewRows([]string{"id", "name", "status", "action", "tenant"}). + AddRow("stack", "test", "CREATE_COMPLETE", "CREATE", "project")) + } + registry := prometheus.NewPedanticRegistry() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + registry.MustRegister(NewVolumesCollector(db, logger), heat.NewStacksCollector(db, logger)) + families, err := registry.Gather() + require.NoError(t, err, "duplicate series must not break gathering") + require.Len(t, families, 7) + var output bytes.Buffer + for _, family := range families { + require.Equal(t, dto.MetricType_GAUGE, family.GetType()) + _, err := expfmt.MetricFamilyToText(&output, family) + require.NoError(t, err) + switch family.GetName() { + case "openstack_cinder_volume_gb", "openstack_cinder_volume_status": + require.Len(t, family.Metric, 2) + var total float64 + for _, metric := range family.Metric { + labels := map[string]string{} + for _, label := range metric.Label { + labels[label.GetName()] = label.GetValue() + } + if labels["id"] == "volume" { + require.Equal(t, tt.want, labels["server_id"]) + if family.GetName() == "openstack_cinder_volume_status" { + require.Equal(t, "7", labels["size"], "size label must remain in GiB") + require.Equal(t, float64(5), metric.GetGauge().GetValue()) + } else { + require.Equal(t, float64(7), metric.GetGauge().GetValue(), "capacity must remain in GiB") + } + } else { + require.Equal(t, "unattached", labels["id"]) + require.Empty(t, labels["server_id"]) + if family.GetName() == "openstack_cinder_volume_status" { + require.Equal(t, "3", labels["size"]) + require.Equal(t, float64(1), metric.GetGauge().GetValue()) + } else { + require.Equal(t, float64(3), metric.GetGauge().GetValue()) + } + } + total += metric.GetGauge().GetValue() + } + if family.GetName() == "openstack_cinder_volume_gb" { + require.Equal(t, float64(10), total, "capacity must count each volume once") + } + case "openstack_cinder_volumes": + require.Equal(t, float64(2), family.Metric[0].GetGauge().GetValue()) + case "openstack_cinder_volume_status_counter": + var total float64 + for _, metric := range family.Metric { + want := float64(0) + status := metric.Label[0].GetValue() + if status == "in-use" || status == "available" { + want = 1 + } + require.Equal(t, want, metric.GetGauge().GetValue()) + total += metric.GetGauge().GetValue() + } + require.Equal(t, float64(2), total) + case "openstack_cinder_up", "openstack_heat_up": + require.Equal(t, float64(1), family.Metric[0].GetGauge().GetValue()) + case "openstack_heat_stack_status_counter": + for _, metric := range family.Metric { + want := float64(0) + if metric.Label[0].GetValue() == "CREATE_COMPLETE" { + want = 1 + } + require.Equal(t, want, metric.GetGauge().GetValue()) + } + } + } + mux := http.NewServeMux() + mux.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{})) + for scrape := 0; scrape < 2; scrape++ { + request := httptest.NewRequest(http.MethodGet, "/metrics", nil) + request.Header.Set("Accept", "text/plain; version=0.0.4") + response := httptest.NewRecorder() + mux.ServeHTTP(response, request) + require.Equal(t, http.StatusOK, response.Code, response.Body.String()) + require.Equal(t, output.String(), response.Body.String(), "HTTP must preserve all gathered metrics across scrapes") + } + require.NoError(t, mock.ExpectationsWereMet()) + if order == 0 { + baseline = output.String() + } else { + require.Equal(t, baseline, output.String(), "row order must not change exposition") + } + } + }) + } +}