diff --git a/cmd/galactic-cni/scrape_test.go b/cmd/galactic-cni/scrape_test.go index bcb009d60..694f08fea 100644 --- a/cmd/galactic-cni/scrape_test.go +++ b/cmd/galactic-cni/scrape_test.go @@ -8,11 +8,17 @@ import ( "testing" "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/installer" ) -// TestMetricsScrape scrapes the registry the run daemon serves at /metrics. +// TestMetricsScrape scrapes what the run daemon serves at /metrics, the +// instrumentation library's registry, once installer.NewMetrics has created +// its series, and lints them. The datapath collectors that read loaded eBPF +// maps need a kernel, so they are left out. func TestMetricsScrape(t *testing.T) { - instrumenttest.AssertScrapes(t, installer.NewMetrics().Handler()) + installer.NewMetrics() + instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/cmd/galactic-edge/main.go b/cmd/galactic-edge/main.go index 19563ff06..f0e7802c1 100644 --- a/cmd/galactic-edge/main.go +++ b/cmd/galactic-edge/main.go @@ -45,7 +45,6 @@ import ( "go.datum.net/galactic/internal/logging" "go.datum.net/galactic/internal/metadata" "go.datum.net/galactic/internal/plumbing/ebpf/attach" - "go.datum.net/galactic/internal/plumbing/nldump" ) type options struct { @@ -178,7 +177,6 @@ func run(parent context.Context, o *options) error { Metrics: diag.NewMetrics(ctrlmetrics.Registry, "node"), }, } - nldump.MustRegister(ctrlmetrics.Registry) if err := ctrlmetrics.Registry.Register(agent.Collector{Agent: a}); err != nil { return fmt.Errorf("register edge node metrics: %w", err) } diff --git a/cmd/galactic-gateway/root.go b/cmd/galactic-gateway/root.go index 7915efc7b..69dba6d66 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -31,7 +31,6 @@ import ( "go.datum.net/galactic/internal/logging" "go.datum.net/galactic/internal/metadata" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" - "go.datum.net/galactic/internal/plumbing/nldump" "go.datum.net/galactic/internal/plumbing/sysctl" ) @@ -207,7 +206,6 @@ func runCmd(cfg *config.GatewayConfig) error { gwQuota := gateway.NewNodeQuotaEnforcer(gateway.DefaultMaxRulesPerTenant, gateway.DefaultMaxRuleTableEntries) gwTelemetry := gateway.NewPrometheusTelemetryEmitter() gwTelemetry.MustRegister(ctrlmetrics.Registry) - nldump.MustRegister(ctrlmetrics.Registry) gwEngine := gateway.NewEngine(gwDatapath, gwQuota, gwTelemetry) // The gateway engine reconciler. No SRv6 address is passed: this datapath diff --git a/cmd/galactic-nat/root.go b/cmd/galactic-nat/root.go index 29f2cbe5b..f300ed025 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -30,7 +30,6 @@ import ( "go.datum.net/galactic/internal/logging" "go.datum.net/galactic/internal/metadata" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" - "go.datum.net/galactic/internal/plumbing/nldump" "go.datum.net/galactic/internal/plumbing/sysctl" ) @@ -142,7 +141,6 @@ func runCmd(cfg *config.NATConfig) error { if err != nil { return fmt.Errorf("setup egress translation eBPF datapath: %w", err) } - nldump.MustRegister(ctrlmetrics.Registry) if err := ctrlmetrics.Registry.Register( newShardStateCollector(datapath, cfg.DatapathEnabled, cfg.XDPAttach)); err != nil { return fmt.Errorf("register egress shard state metrics: %w", err) diff --git a/cmd/galactic-router/root.go b/cmd/galactic-router/root.go index 524df2292..663c1281a 100644 --- a/cmd/galactic-router/root.go +++ b/cmd/galactic-router/root.go @@ -41,7 +41,6 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/attach" "go.datum.net/galactic/internal/plumbing/ebpf/vipxlatmap" "go.datum.net/galactic/internal/plumbing/loaddr" - "go.datum.net/galactic/internal/plumbing/nldump" "go.datum.net/galactic/internal/reconcile" galacticruntime "go.datum.net/galactic/internal/runtime" "go.datum.net/galactic/internal/runtime/gobgp" @@ -122,7 +121,6 @@ func runCmd(cfg *config.RouterConfig) error { } serviceRouteMetrics := serviceroute.NewMetrics() serviceRouteMetrics.MustRegister(ctrlmetrics.Registry) - nldump.MustRegister(ctrlmetrics.Registry) // ctx carries a cause so an ordinary signal-triggered shutdown can be told // apart from the health server's own Serve failure below. See the cause diff --git a/cmd/galactic-vrf/root.go b/cmd/galactic-vrf/root.go index c1bf8c3a9..994b920e1 100644 --- a/cmd/galactic-vrf/root.go +++ b/cmd/galactic-vrf/root.go @@ -24,7 +24,6 @@ import ( "go.datum.net/galactic/internal/ingresssidecar" "go.datum.net/galactic/internal/logging" "go.datum.net/galactic/internal/metadata" - "go.datum.net/galactic/internal/plumbing/nldump" ) const ( @@ -66,7 +65,6 @@ func runCmd(cfg *config.VRFConfig) error { metrics := ingresssidecar.NewMetrics() metrics.MustRegister(ctrlmetrics.Registry) - nldump.MustRegister(ctrlmetrics.Registry) lifecycle := ingresssidecar.NewLifecycleMetrics(cfg.SweepInterval, cfg.TeardownGracePeriod) lifecycle.MustRegister(ctrlmetrics.Registry) diff --git a/docs/observability/README.md b/docs/observability/README.md index ddb49435c..8db274fde 100644 --- a/docs/observability/README.md +++ b/docs/observability/README.md @@ -21,11 +21,11 @@ Create every metric with the constructors in [`go.miloapis.com/instrumentation/metrics`](https://github.com/milo-os/instrumentation), and register a collector that reads state at scrape time with its `metrics.MustRegister`. Both put the metric on controller-runtime's registry, -which every controller-runtime manager serves. `galactic-cni`, -`fabric-config-agent` and the fabric-api node sidecar serve only their own -registries, so a library metric linked into them is not exported until they -serve the library's handler. The tests in `internal/instrumentation` enforce -the rule in the unit suite: +which every controller-runtime manager serves and `galactic-cni` serves with +the library's `metrics.Handler`. `fabric-config-agent` and the fabric-api node +sidecar serve only their own registries, so a library metric linked into them +is not exported until they serve the library's handler. The tests in +`internal/instrumentation` enforce the rule in the unit suite: - `TestAdopted` runs the library's adoption check, which fails on a metric registered outside the library and on a logger the library didn't build. @@ -39,7 +39,10 @@ the rule in the unit suite: - Each command that serves `/metrics` has a `TestMetricsScrape`, which fails when two registries export the same series. `TestEveryBinaryHasScrapeTest` requires one for every new command, but can't tell whether the test scrapes - the handler the command serves; reviewers check that. + the handler the command serves; reviewers check that. Where a command + creates its metrics at startup rather than when a package loads, its test + first creates them through the same function the command calls, and also + runs the library's lint, which `TestMetricsLint` can't reach. Both source checks skip the directories in `pending` in `internal/instrumentation/adoption_test.go`, which haven't moved to the diff --git a/internal/installer/egressgroup_test.go b/internal/installer/egressgroup_test.go index 91871ce15..f6490527e 100644 --- a/internal/installer/egressgroup_test.go +++ b/internal/installer/egressgroup_test.go @@ -15,7 +15,6 @@ import ( "testing" "github.com/cilium/ebpf" - "github.com/prometheus/client_golang/prometheus" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" @@ -990,8 +989,7 @@ func TestSweepHashed_EmptyMembershipKeepsRoutesOnGroups(t *testing.T) { t.Run(name, func(t *testing.T) { static := shardSIDFor(0x10) f := newFixture(t, testHashed, []string{static}, []netip.Prefix{testNSP}) - reg := prometheus.NewRegistry() - f.g.ctl = metrics.NewEgressControl(reg) + f.g.ctl = metrics.NewEgressControl() lister := &fakeLister{shards: []bgpv1alpha1.EgressShard{dual("dual", 0x10)}, synced: true} f.g.shards = lister @@ -1029,22 +1027,19 @@ func TestSweepHashed_EmptyMembershipKeepsRoutesOnGroups(t *testing.T) { } } want := map[string]float64{egressroutemap.NAT66Class.String(): 3, nat64NSP.String(): 1} - if got := groupRoutes(t, reg); !maps.Equal(got, want) { + if got := groupRoutes(t); !maps.Equal(got, want) { t.Errorf("group_routes = %v, want %v", got, want) } }) } } -// groupRoutes reads galactic_cni_egress_group_routes from reg, by class. -func groupRoutes(t *testing.T, reg *prometheus.Registry) map[string]float64 { +// groupRoutes reads galactic_cni_egress_group_routes from the instrumentation +// library's registry, by class. +func groupRoutes(t *testing.T) map[string]float64 { t.Helper() - families, err := reg.Gather() - if err != nil { - t.Fatal(err) - } got := map[string]float64{} - for _, mf := range families { + for _, mf := range gatherPrefixed(t, "galactic_cni_egress_group_routes") { if mf.GetName() != "galactic_cni_egress_group_routes" { continue } diff --git a/internal/installer/gather_test.go b/internal/installer/gather_test.go new file mode 100644 index 000000000..ca7c5d357 --- /dev/null +++ b/internal/installer/gather_test.go @@ -0,0 +1,41 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package installer + +import ( + "errors" + "strings" + "testing" + + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" + ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" +) + +// gatherPrefixed returns the families on the instrumentation library's +// registry whose names start with prefix. The registry is shared by the whole +// test process, and a test that ran Run against a real datapath leaves map +// collectors behind whose maps are closed, so collection errors from other +// families are ignored. An error from a family under prefix fails the test. +func gatherPrefixed(t *testing.T, prefix string) []*dto.MetricFamily { + t.Helper() + families, err := ctrlmetrics.Registry.Gather() + var errs prometheus.MultiError + if !errors.As(err, &errs) && err != nil { + errs = prometheus.MultiError{err} + } + for _, e := range errs { + if strings.Contains(e.Error(), `fqName: "`+prefix) { + t.Fatal(e) + } + } + var out []*dto.MetricFamily + for _, f := range families { + if strings.HasPrefix(f.GetName(), prefix) { + out = append(out, f) + } + } + return out +} diff --git a/internal/installer/installer.go b/internal/installer/installer.go index 03944cee3..949585b7a 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -20,6 +20,7 @@ import ( "time" "github.com/vishvananda/netlink" + instmetrics "go.miloapis.com/instrumentation/metrics" "golang.org/x/sys/unix" "google.golang.org/grpc" "google.golang.org/grpc/health" @@ -577,12 +578,8 @@ func startEBPFDatapath(ctx context.Context, m *metrics.Metrics) (ebpfDatapathSta if err := usidmap.NewRegistryFromObjects(objs).VRF.SyncTraffic(); err != nil { slog.Warn("Failed to create per-VRF traffic counter rows; the next GC sweep retries", "err", err) } - if err := m.RegisterDatapathCollector(objs); err != nil { - slog.Warn("Failed to register eBPF datapath metrics collector", "err", err) - } - if err := m.RegisterEgressShardCollector(objs, egressCfg.MinActive); err != nil { - slog.Warn("Failed to register egress shard metrics collector", "err", err) - } + m.RegisterDatapathCollector(objs) + m.RegisterEgressShardCollector(objs, egressCfg.MinActive) } // Best-effort setup for the eBPF map GC sweeps. Unlike the datapath start @@ -1075,12 +1072,11 @@ func radvActorFailed(actors *radvActorSet, failure radvActorFailure) { "err", failure.err, "hostInterface", failure.iface, "failures", p.failures, "retryIn", backoff) } -// NewMetrics builds the registry the run daemon serves at /metrics, before -// the datapath collectors that need loaded eBPF objects are added. +// NewMetrics creates the series the run daemon serves at /metrics, before the +// datapath collectors that need loaded eBPF objects are added. Run calls it +// once. func NewMetrics() *metrics.Metrics { - m := metrics.New() - nldump.MustRegister(m.Registry) - return m + return metrics.New() } // Run executes the CNI installer main container tasks: @@ -1149,7 +1145,7 @@ func Run(ctx context.Context, grpcHealthPort, metricsPort int) error { // Serve Prometheus metrics at the conventional /metrics scrape path. metricsMux := http.NewServeMux() - metricsMux.Handle("/metrics", m.Handler()) + metricsMux.Handle("/metrics", instmetrics.Handler()) metricsSrv := &http.Server{ Addr: fmt.Sprintf(":%d", metricsPort), Handler: metricsMux, diff --git a/internal/installer/sidecarreturn_metrics_test.go b/internal/installer/sidecarreturn_metrics_test.go index acd306234..5596e9920 100644 --- a/internal/installer/sidecarreturn_metrics_test.go +++ b/internal/installer/sidecarreturn_metrics_test.go @@ -7,12 +7,12 @@ package installer import ( "context" "errors" + "fmt" "net/netip" + "strings" "testing" "time" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/testutil" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -123,38 +123,46 @@ func twoGatewayAdvs() []client.Object { } } -// sidecarReturnSeries reads one series back from reg's text exposition. -func sidecarReturnSeries(t *testing.T, reg *prometheus.Registry, name string, labels ...string) float64 { +// sidecarReturnSeries returns every galactic_sidecar_return_ series on the +// instrumentation library's registry, keyed by seriesKey. +func sidecarReturnSeries(t *testing.T) map[string]float64 { t.Helper() - families, err := reg.Gather() - if err != nil { - t.Fatal(err) - } - for _, f := range families { - if f.GetName() != "galactic_sidecar_return_"+name { + out := map[string]float64{} + for _, f := range gatherPrefixed(t, "galactic_sidecar_return_") { + name, ok := strings.CutPrefix(f.GetName(), "galactic_sidecar_return_") + if !ok { continue } - next: for _, m := range f.GetMetric() { - for i := 0; i+1 < len(labels); i += 2 { - found := false - for _, lp := range m.GetLabel() { - if lp.GetName() == labels[i] && lp.GetValue() == labels[i+1] { - found = true - } - } - if !found { - continue next - } + labels := make([]string, 0, 2*len(m.GetLabel())) + for _, lp := range m.GetLabel() { + labels = append(labels, lp.GetName(), lp.GetValue()) } + v := m.GetCounter().GetValue() if m.GetGauge() != nil { - return m.GetGauge().GetValue() + v = m.GetGauge().GetValue() } - return m.GetCounter().GetValue() + out[seriesKey(name, labels...)] = v } } - t.Fatalf("no series galactic_sidecar_return_%s%v", name, labels) - return 0 + return out +} + +// seriesKey names the series name{labels}, the galactic_sidecar_return_ +// prefix left off, with labels as name, value pairs in label-name order. +func seriesKey(name string, labels ...string) string { + return name + fmt.Sprint(labels) +} + +// sidecarReturnValue returns the series in got that seriesKey names, failing +// the test when it is absent. +func sidecarReturnValue(t *testing.T, got map[string]float64, name string, labels ...string) float64 { + t.Helper() + v, ok := got[seriesKey(name, labels...)] + if !ok { + t.Fatalf("no series galactic_sidecar_return_%s%v", name, labels) + } + return v } // TestSidecarReturnPassAccounting: each pass's result and endpoint counts @@ -195,20 +203,24 @@ func TestSidecarReturnPassAccounting(t *testing.T) { if tc.setup != nil { tc.setup(h) } - reg := prometheus.NewPedanticRegistry() - rec := metrics.NewSidecarReturn(reg) + rec := metrics.NewSidecarReturn() + before := sidecarReturnSeries(t) err := ensureSidecarReturnPath(context.Background(), sidecarReturnClient(t, nil, tc.objs...), testNamespace, testSidecarNode, rec, clock) if (err != nil) != tc.wantErr { t.Fatalf("error = %v, want error %v", err, tc.wantErr) } + after := sidecarReturnSeries(t) + counted := func(name string, labels ...string) float64 { + return sidecarReturnValue(t, after, name, labels...) - sidecarReturnValue(t, before, name, labels...) + } for _, r := range []string{metrics.SidecarReturnSuccess, metrics.SidecarReturnPartial, metrics.SidecarReturnWaitingIdentity, metrics.SidecarReturnError} { want := 0.0 if r == tc.result { want = 1 } - if got := sidecarReturnSeries(t, reg, "reconcile_total", "result", r); got != want { + if got := counted("reconcile_total", "result", r); got != want { t.Errorf("reconcile_total{result=%q} = %v, want %v", r, got, want) } } @@ -220,7 +232,7 @@ func TestSidecarReturnPassAccounting(t *testing.T) { {"applied", tc.applied}, {"pending", tc.desired - tc.applied}, } { - if got := sidecarReturnSeries(t, reg, "endpoints", "state", c.label); got != c.want { + if got := sidecarReturnValue(t, after, "endpoints", "state", c.label); got != c.want { t.Errorf("endpoints{state=%q} = %v, want %v", c.label, got, c.want) } } @@ -234,11 +246,11 @@ func TestSidecarReturnPassAccounting(t *testing.T) { {metrics.SidecarReturnOpPrune, opError, tc.pruneErrs}, {metrics.SidecarReturnOpPrune, opSuccess, 1 - tc.pruneErrs}, } { - if got := sidecarReturnSeries(t, reg, "operations_total", "operation", c.op, "result", c.result); got != c.want { + if got := counted("operations_total", "operation", c.op, "result", c.result); got != c.want { t.Errorf("operations_total{%s,%s} = %v, want %v", c.op, c.result, got, c.want) } } - if got := sidecarReturnSeries(t, reg, "last_completed_timestamp_seconds"); got != float64(at.Unix()) { + if got := sidecarReturnValue(t, after, "last_completed_timestamp_seconds"); got != float64(at.Unix()) { t.Errorf("last completed = %v, want the pass's end", got) } }) @@ -250,8 +262,7 @@ func TestSidecarReturnPassAccounting(t *testing.T) { // and the timestamp stay at the last pass that listed them. func TestSidecarReturnFailedDiscoveryKeepsTheSnapshot(t *testing.T) { newSidecarReturnHarness(t) - reg := prometheus.NewPedanticRegistry() - rec := metrics.NewSidecarReturn(reg) + rec := metrics.NewSidecarReturn() first := time.Unix(1_700_000_000, 0) objs := append(twoGatewayAdvs(), router(testSidecarNode, testLocator, 6)) if err := ensureSidecarReturnPath(context.Background(), sidecarReturnClient(t, nil, objs...), @@ -259,36 +270,38 @@ func TestSidecarReturnFailedDiscoveryKeepsTheSnapshot(t *testing.T) { t.Fatal(err) } + before := sidecarReturnSeries(t) err := ensureSidecarReturnPath(context.Background(), sidecarReturnClient(t, errSidecarReturnTest, objs...), testNamespace, testSidecarNode, rec, func() time.Time { return first.Add(time.Minute) }) if err == nil { t.Fatal("a failed list returned no error") } - if got := sidecarReturnSeries(t, reg, "endpoints", "state", "desired"); got != 2 { + after := sidecarReturnSeries(t) + if got := sidecarReturnValue(t, after, "endpoints", "state", "desired"); got != 2 { t.Errorf("desired = %v after a failed list, want the last listed 2", got) } - if got := sidecarReturnSeries(t, reg, "last_completed_timestamp_seconds"); got != float64(first.Unix()) { + if got := sidecarReturnValue(t, after, "last_completed_timestamp_seconds"); got != float64(first.Unix()) { t.Errorf("last completed = %v, want the pass before the failure", got) } - if got := sidecarReturnSeries(t, reg, "reconcile_total", "result", metrics.SidecarReturnError); got != 1 { - t.Errorf("reconcile_total{error} = %v, want 1", got) + if got := sidecarReturnValue(t, after, "reconcile_total", "result", metrics.SidecarReturnError) - + sidecarReturnValue(t, before, "reconcile_total", "result", metrics.SidecarReturnError); got != 1 { + t.Errorf("reconcile_total{error} rose by %v, want 1", got) } } // TestSidecarReturnSeries: every series exists from the start, and the // total is fixed. func TestSidecarReturnSeries(t *testing.T) { - reg := prometheus.NewPedanticRegistry() - metrics.NewSidecarReturn(reg) - n, err := testutil.GatherAndCount(reg) - if err != nil { - t.Fatal(err) + metrics.NewSidecarReturn() + n := 0 + for _, f := range gatherPrefixed(t, "galactic_sidecar_return_") { + n += len(f.GetMetric()) } // 3 endpoint states, 1 timestamp, 4 results, 4 operations x 2 results. if n != 16 { t.Errorf("%d series, want 16", n) } - if got := sidecarReturnSeries(t, reg, "last_completed_timestamp_seconds"); got != 0 { + if got := sidecarReturnValue(t, sidecarReturnSeries(t), "last_completed_timestamp_seconds"); got != 0 { t.Errorf("last completed = %v before any pass, want 0", got) } var nilRec *metrics.SidecarReturn @@ -303,18 +316,21 @@ func TestSidecarReturnSeries(t *testing.T) { func TestSidecarReturnPruneFailureWhileWaiting(t *testing.T) { h := newSidecarReturnHarness(t) h.pruneErr = errSidecarReturnTest - reg := prometheus.NewPedanticRegistry() - rec := metrics.NewSidecarReturn(reg) + rec := metrics.NewSidecarReturn() + before := sidecarReturnSeries(t) if err := ensureSidecarReturnPath(context.Background(), sidecarReturnClient(t, nil, twoGatewayAdvs()...), testNamespace, testSidecarNode, rec, time.Now); err != nil { t.Fatal(err) } - if got := sidecarReturnSeries(t, reg, "reconcile_total", "result", metrics.SidecarReturnWaitingIdentity); got != 1 { - t.Errorf("reconcile_total{waiting_identity} = %v, want 1", got) + after := sidecarReturnSeries(t) + counted := func(name string, labels ...string) float64 { + return sidecarReturnValue(t, after, name, labels...) - sidecarReturnValue(t, before, name, labels...) } - if got := sidecarReturnSeries(t, reg, "operations_total", - "operation", metrics.SidecarReturnOpPrune, "result", opError); got != 1 { - t.Errorf("operations_total{prune,error} = %v, want 1", got) + if got := counted("reconcile_total", "result", metrics.SidecarReturnWaitingIdentity); got != 1 { + t.Errorf("reconcile_total{waiting_identity} rose by %v, want 1", got) + } + if got := counted("operations_total", "operation", metrics.SidecarReturnOpPrune, "result", opError); got != 1 { + t.Errorf("operations_total{prune,error} rose by %v, want 1", got) } } @@ -322,26 +338,28 @@ func TestSidecarReturnPruneFailureWhileWaiting(t *testing.T) { // reaper's outcome as well as the pass. func TestReconcileSidecarReturnPathCountsReap(t *testing.T) { newSidecarReturnHarness(t) - reg := prometheus.NewPedanticRegistry() st := ebpfDatapathState{ k8sClient: sidecarReturnClient(t, nil), namespace: testNamespace, nodeName: testSidecarNode, - sidecarReap: &sidecarReaper{}, sidecarReturn: metrics.NewSidecarReturn(reg), + sidecarReap: &sidecarReaper{}, sidecarReturn: metrics.NewSidecarReturn(), } + before := sidecarReturnSeries(t) reconcileSidecarReturnPath(context.Background(), st) - if got := sidecarReturnSeries(t, reg, "operations_total", - "operation", metrics.SidecarReturnOpReap, "result", opSuccess); got != 1 { - t.Errorf("operations_total{reap,success} = %v, want 1", got) + after := sidecarReturnSeries(t) + counted := func(name string, labels ...string) float64 { + return sidecarReturnValue(t, after, name, labels...) - sidecarReturnValue(t, before, name, labels...) + } + if got := counted("operations_total", "operation", metrics.SidecarReturnOpReap, "result", opSuccess); got != 1 { + t.Errorf("operations_total{reap,success} rose by %v, want 1", got) } - if got := sidecarReturnSeries(t, reg, "reconcile_total", "result", metrics.SidecarReturnSuccess); got != 1 { - t.Errorf("reconcile_total{success} = %v, want 1", got) + if got := counted("reconcile_total", "result", metrics.SidecarReturnSuccess); got != 1 { + t.Errorf("reconcile_total{success} rose by %v, want 1", got) } } // TestSidecarReturnScrapeSeesOnePass: a scrape during a run of passes always // reads counts that partition desired and come from one pass. func TestSidecarReturnScrapeSeesOnePass(t *testing.T) { - reg := prometheus.NewPedanticRegistry() - rec := metrics.NewSidecarReturn(reg) + rec := metrics.NewSidecarReturn() done := make(chan struct{}) go func() { defer close(done) @@ -356,10 +374,7 @@ func TestSidecarReturnScrapeSeesOnePass(t *testing.T) { return default: } - families, err := reg.Gather() - if err != nil { - t.Fatal(err) - } + families := gatherPrefixed(t, "galactic_sidecar_return_") vals := map[string]float64{} var ts float64 for _, f := range families { diff --git a/internal/instrumentation/adoption_test.go b/internal/instrumentation/adoption_test.go index 51f20f59f..c992be776 100644 --- a/internal/instrumentation/adoption_test.go +++ b/internal/instrumentation/adoption_test.go @@ -45,13 +45,8 @@ var pending = []string{ "internal/fabricconfig", "internal/gateway", "internal/ingresssidecar", - "internal/plumbing/ebpf/metrics", "internal/plumbing/ebpf/xdpdispatch", - "internal/plumbing/nldump", "internal/serviceroute", - // #1149: its manager disables metrics, which passes once any binary - // serves the library's handler. - "tests/psc/fixture", } // TestAdopted runs the instrumentation library's adoption check over the diff --git a/internal/instrumentation/lint_test.go b/internal/instrumentation/lint_test.go index 6251cfb7b..19b4eb228 100644 --- a/internal/instrumentation/lint_test.go +++ b/internal/instrumentation/lint_test.go @@ -20,6 +20,8 @@ import ( // Every package that creates a metric through the library, so Lint sees // it. TestLintLinksEveryMetric keeps this list complete. + _ "go.datum.net/galactic/internal/plumbing/ebpf/metrics" + _ "go.datum.net/galactic/internal/plumbing/nldump" _ "go.datum.net/galactic/internal/runtime/gobgp" ) diff --git a/internal/plumbing/ebpf/metrics/doc.go b/internal/plumbing/ebpf/metrics/doc.go index cdd3f2fd0..297420183 100644 --- a/internal/plumbing/ebpf/metrics/doc.go +++ b/internal/plumbing/ebpf/metrics/doc.go @@ -21,6 +21,7 @@ // ordinary counters incremented in place through the attach package's // hooks, wired once at process startup. // -// Metrics bundles both into one registry plus an HTTP handler, so the caller -// constructs it once and needs no Prometheus imports of its own. +// Both are created on the instrumentation library's registry, which the +// caller serves with that library's metrics.Handler. Metrics bundles them, so +// the caller constructs it once and needs no Prometheus imports of its own. package metrics diff --git a/internal/plumbing/ebpf/metrics/egresscontrol.go b/internal/plumbing/ebpf/metrics/egresscontrol.go index 9985a325d..cdb6ffa31 100644 --- a/internal/plumbing/ebpf/metrics/egresscontrol.go +++ b/internal/plumbing/ebpf/metrics/egresscontrol.go @@ -8,6 +8,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + instmetrics "go.miloapis.com/instrumentation/metrics" ) // egressSubsystem names galactic-cni's egress control-loop series. @@ -29,34 +30,34 @@ type EgressControl struct { lastSweep prometheus.Gauge } -// NewEgressControl builds the series and registers them with reg. -func NewEgressControl(reg prometheus.Registerer) *EgressControl { +// NewEgressControl creates the series on the instrumentation library's +// registry. +func NewEgressControl() *EgressControl { c := &EgressControl{ - mode: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + mode: instmetrics.NewGaugeVec(prometheus.GaugeOpts{ Namespace: egressNamespace, Subsystem: egressSubsystem, Name: "mode", Help: "1 for the egress mode galactic-cni is configured with (GALACTIC_CNI_EGRESS_MODE), 0 for the other.", }, []string{"mode"}), - watchSynced: prometheus.NewGauge(prometheus.GaugeOpts{ + watchSynced: instmetrics.NewGauge(prometheus.GaugeOpts{ Namespace: egressNamespace, Subsystem: egressSubsystem, Name: "shard_watch_synced", Help: "1 once galactic-cni's EgressShard watch has listed the cluster, else 0. Hashed mode keeps the " + "shard groups it last published until then.", }), - groupRoutes: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + groupRoutes: instmetrics.NewGaugeVec(prometheus.GaugeOpts{ Namespace: egressNamespace, Subsystem: egressSubsystem, Name: "group_routes", Help: "egress_route_table entries naming an egress shard group after the last successful sweep, by " + "translation class. Must be 0 before rolling back to a release that predates shard groups.", }, []string{labelClass}), - sweepErrors: prometheus.NewCounterVec(prometheus.CounterOpts{ + sweepErrors: instmetrics.NewCounterVec(prometheus.CounterOpts{ Namespace: egressNamespace, Subsystem: egressSubsystem, Name: "sweep_errors_total", Help: "Egress route sweep failures, by stage: apply (publishing a shard group), refresh (reading or " + "rewriting egress_route_table), watch (listing EgressShards), close and disable (retiring groups).", }, []string{"stage"}), - lastSweep: prometheus.NewGauge(prometheus.GaugeOpts{ + lastSweep: instmetrics.NewGauge(prometheus.GaugeOpts{ Namespace: egressNamespace, Subsystem: egressSubsystem, Name: "last_successful_sweep_timestamp_seconds", Help: "Unix time of the last egress route sweep that finished without an error.", }), } - reg.MustRegister(c.mode, c.watchSynced, c.groupRoutes, c.sweepErrors, c.lastSweep) for _, stage := range []string{"apply", "refresh", "watch", "close", "disable"} { c.sweepErrors.WithLabelValues(stage) } diff --git a/internal/plumbing/ebpf/metrics/egressshard.go b/internal/plumbing/ebpf/metrics/egressshard.go index f79d8abff..57caa0364 100644 --- a/internal/plumbing/ebpf/metrics/egressshard.go +++ b/internal/plumbing/ebpf/metrics/egressshard.go @@ -8,6 +8,7 @@ import ( "fmt" "github.com/prometheus/client_golang/prometheus" + instmetrics "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/plumbing/ebpf/egressroutemap" "go.datum.net/galactic/internal/plumbing/ebpf/prog" @@ -91,10 +92,11 @@ func NewEgressShardCollector( } // RegisterEgressShardCollector registers an EgressShardCollector reading objs' -// maps, with minActive as the pool's expected floor. -func (m *Metrics) RegisterEgressShardCollector(objs *prog.UsidObjects, minActive int) error { +// maps, with minActive as the pool's expected floor. Call it once, after the +// datapath is loaded. +func (m *Metrics) RegisterEgressShardCollector(objs *prog.UsidObjects, minActive int) { groups := egressroutemap.NewShardGroupTable(egressroutemap.NewKernelGroupStore(objs.EgressShardGroups)) - return m.Registry.Register( + instmetrics.MustRegister( NewEgressShardCollector(groups, objs.EgressShardCounters, objs.EgressShardStats, minActive)) } diff --git a/internal/plumbing/ebpf/metrics/egressshard_test.go b/internal/plumbing/ebpf/metrics/egressshard_test.go index fbe37a4a5..4b66503bc 100644 --- a/internal/plumbing/ebpf/metrics/egressshard_test.go +++ b/internal/plumbing/ebpf/metrics/egressshard_test.go @@ -12,6 +12,7 @@ import ( "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" + ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" "go.datum.net/galactic/internal/plumbing/ebpf/egressroutemap" "go.datum.net/galactic/internal/plumbing/ebpf/prog" @@ -113,23 +114,28 @@ func TestEgressShardCollectorReportsNothingUnpublished(t *testing.T) { } func TestEgressControlSeries(t *testing.T) { - reg := prometheus.NewRegistry() - c := NewEgressControl(reg) + c := NewEgressControl() + before := map[string]float64{} + for _, m := range collectNamed(t, gathererCollector{ctrlmetrics.Registry}) { + before[m.name] = m.value + } c.SetMode("hashed", "ordered", "hashed") c.SetWatchSynced(false) c.SetGroupRoutes(map[string]int{"nat66": 4}) c.SweepError("refresh") got := map[string]float64{} - for _, m := range collectNamed(t, registryCollector{reg}) { + for _, m := range collectNamed(t, gathererCollector{ctrlmetrics.Registry}) { got[m.name] = m.value } + const refreshErrors, applyErrors = `galactic_cni_egress_sweep_errors_total{stage="refresh"}`, + `galactic_cni_egress_sweep_errors_total{stage="apply"}` for name, value := range map[string]float64{ - `galactic_cni_egress_mode{mode="hashed"}`: 1, - `galactic_cni_egress_mode{mode="ordered"}`: 0, - `galactic_cni_egress_shard_watch_synced`: 0, - `galactic_cni_egress_group_routes{class="nat66"}`: 4, - `galactic_cni_egress_sweep_errors_total{stage="refresh"}`: 1, - `galactic_cni_egress_sweep_errors_total{stage="apply"}`: 0, + `galactic_cni_egress_mode{mode="hashed"}`: 1, + `galactic_cni_egress_mode{mode="ordered"}`: 0, + `galactic_cni_egress_shard_watch_synced`: 0, + `galactic_cni_egress_group_routes{class="nat66"}`: 4, + refreshErrors: before[refreshErrors] + 1, + applyErrors: before[applyErrors], } { if v, ok := got[name]; !ok || v != value { t.Errorf("%s = %v (present %v), want %v", name, v, ok, value) @@ -139,13 +145,14 @@ func TestEgressControlSeries(t *testing.T) { nilControl.SweepError("apply") // must not panic } -// registryCollector adapts a registry to prometheus.Collector for collectNamed. -type registryCollector struct{ reg *prometheus.Registry } +// gathererCollector adapts a gatherer to prometheus.Collector for +// collectNamed. +type gathererCollector struct{ g prometheus.Gatherer } -func (r registryCollector) Describe(chan<- *prometheus.Desc) {} +func (r gathererCollector) Describe(chan<- *prometheus.Desc) {} -func (r registryCollector) Collect(ch chan<- prometheus.Metric) { - families, _ := r.reg.Gather() +func (r gathererCollector) Collect(ch chan<- prometheus.Metric) { + families, _ := r.g.Gather() for _, f := range families { for _, m := range f.GetMetric() { labels := map[string]string{} diff --git a/internal/plumbing/ebpf/metrics/endpointslice_repair.go b/internal/plumbing/ebpf/metrics/endpointslice_repair.go index 338736d1e..66065976a 100644 --- a/internal/plumbing/ebpf/metrics/endpointslice_repair.go +++ b/internal/plumbing/ebpf/metrics/endpointslice_repair.go @@ -4,7 +4,10 @@ package metrics -import "github.com/prometheus/client_golang/prometheus" +import ( + "github.com/prometheus/client_golang/prometheus" + instmetrics "go.miloapis.com/instrumentation/metrics" +) // EndpointSliceRepair reports galactic-cni's per-pod EndpointSlice repair: how // many missing slices it recreated, each one a pod whose HTTP ingress was down @@ -15,23 +18,23 @@ type EndpointSliceRepair struct { failures prometheus.Counter } -// NewEndpointSliceRepair builds an EndpointSliceRepair registered in reg. -func NewEndpointSliceRepair(reg prometheus.Registerer) *EndpointSliceRepair { +// NewEndpointSliceRepair creates the counters on the instrumentation +// library's registry. +func NewEndpointSliceRepair() *EndpointSliceRepair { r := &EndpointSliceRepair{ - restored: prometheus.NewCounter(prometheus.CounterOpts{ + restored: instmetrics.NewCounter(prometheus.CounterOpts{ Namespace: "galactic", Subsystem: "endpointslice_repair", Name: "restored_total", Help: "Per-pod EndpointSlices the repair pass recreated after finding them missing.", }), - failures: prometheus.NewCounter(prometheus.CounterOpts{ + failures: instmetrics.NewCounter(prometheus.CounterOpts{ Namespace: "galactic", Subsystem: "endpointslice_repair", Name: "failures_total", Help: "EndpointSlice repair passes that could not list this node's pods or write a slice.", }), } - reg.MustRegister(r.restored, r.failures) return r } diff --git a/internal/plumbing/ebpf/metrics/events.go b/internal/plumbing/ebpf/metrics/events.go index f07c3f928..098b30fc8 100644 --- a/internal/plumbing/ebpf/metrics/events.go +++ b/internal/plumbing/ebpf/metrics/events.go @@ -6,6 +6,7 @@ package metrics import ( "github.com/prometheus/client_golang/prometheus" + instmetrics "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/plumbing/ebpf/attach" ) @@ -19,16 +20,17 @@ type EventCounters struct { attach *prometheus.CounterVec } -// NewEventCounters builds a fresh, unregistered set of event counters. +// NewEventCounters creates the event counters on the instrumentation +// library's registry. func NewEventCounters() *EventCounters { return &EventCounters{ - load: prometheus.NewCounterVec(prometheus.CounterOpts{ + load: instmetrics.NewCounterVec(prometheus.CounterOpts{ Namespace: namespace, Subsystem: "datapath", Name: "load_events_total", Help: "BPF program load attempts (internal/plumbing/ebpf/attach.Load), by result.", }, []string{labelResult}), - attach: prometheus.NewCounterVec(prometheus.CounterOpts{ + attach: instmetrics.NewCounterVec(prometheus.CounterOpts{ Namespace: namespace, Subsystem: "datapath", Name: "attach_events_total", @@ -38,13 +40,6 @@ func NewEventCounters() *EventCounters { } } -// MustRegister registers every counter this type owns against reg, panicking on -// a duplicate as the underlying registry does. Callers do this once per process, -// at startup. -func (c *EventCounters) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(c.load, c.attach) -} - // Hooks returns the attach.Hooks wiring these counters. Pass the result to // attach.SetHooks once at process startup, before starting the datapath. func (c *EventCounters) Hooks() attach.Hooks { diff --git a/internal/plumbing/ebpf/metrics/metrics.go b/internal/plumbing/ebpf/metrics/metrics.go index 64d07dbfc..438716e94 100644 --- a/internal/plumbing/ebpf/metrics/metrics.go +++ b/internal/plumbing/ebpf/metrics/metrics.go @@ -5,22 +5,16 @@ package metrics import ( - "net/http" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" + instmetrics "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/plumbing/ebpf/prog" ) -// Metrics bundles this datapath's Prometheus instrumentation into one private -// registry, plus an HTTP handler for the caller to serve so it needs no -// Prometheus imports of its own. A private registry rather than the global one, -// so constructing more than one in a process cannot panic on duplicate -// registration. +// Metrics bundles this datapath's Prometheus instrumentation, created on the +// instrumentation library's registry, which the caller serves with that +// library's metrics.Handler. type Metrics struct { - Registry *prometheus.Registry - Events *EventCounters + Events *EventCounters // Egress is galactic-cni's egress shard group control-loop state. Egress *EgressControl // SidecarReturn is the ingress sidecar's host-side return path. @@ -30,27 +24,18 @@ type Metrics struct { EndpointSliceRepair *EndpointSliceRepair } -// New builds a Metrics with the event counters already registered. Call +// New creates every series that does not read loaded eBPF objects. Call // RegisterDatapathCollector once the datapath is loaded to also expose live map -// state. +// state. A process calls New once. func New() *Metrics { - reg := prometheus.NewRegistry() - events := NewEventCounters() - events.MustRegister(reg) return &Metrics{ - Registry: reg, Events: events, Egress: NewEgressControl(reg), SidecarReturn: NewSidecarReturn(reg), - EndpointSliceRepair: NewEndpointSliceRepair(reg), + Events: NewEventCounters(), Egress: NewEgressControl(), SidecarReturn: NewSidecarReturn(), + EndpointSliceRepair: NewEndpointSliceRepair(), } } // RegisterDatapathCollector registers a collector reading live map state from // objs at every scrape. Call it once, after the datapath is loaded. -func (m *Metrics) RegisterDatapathCollector(objs *prog.UsidObjects) error { - return m.Registry.Register(NewCollectorFromObjects(objs)) -} - -// Handler returns the http.Handler serving this Metrics' registry in the -// Prometheus text exposition format. -func (m *Metrics) Handler() http.Handler { - return promhttp.HandlerFor(m.Registry, promhttp.HandlerOpts{}) +func (m *Metrics) RegisterDatapathCollector(objs *prog.UsidObjects) { + instmetrics.MustRegister(NewCollectorFromObjects(objs)) } diff --git a/internal/plumbing/ebpf/metrics/sidecarreturn.go b/internal/plumbing/ebpf/metrics/sidecarreturn.go index eb98c1b5a..e40fb3903 100644 --- a/internal/plumbing/ebpf/metrics/sidecarreturn.go +++ b/internal/plumbing/ebpf/metrics/sidecarreturn.go @@ -5,10 +5,12 @@ package metrics import ( + "sync" "sync/atomic" "time" "github.com/prometheus/client_golang/prometheus" + instmetrics "go.miloapis.com/instrumentation/metrics" ) // sidecarReturnNamespace and sidecarReturnSubsystem name galactic-cni's series @@ -108,9 +110,11 @@ func (c *sidecarReturnSnapshot) Collect(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric(c.completed, prometheus.GaugeValue, ts) } -// NewSidecarReturn builds the series and registers them with reg. -func NewSidecarReturn(reg prometheus.Registerer) *SidecarReturn { - snapshot := &sidecarReturnSnapshot{ +// sidecarReturnPasses is the snapshot every SidecarReturn reports through. +// A collector can be registered only once, so it is shared, and registered by +// the first NewSidecarReturn. +var ( + sidecarReturnPasses = &sidecarReturnSnapshot{ endpoints: prometheus.NewDesc( prometheus.BuildFQName(sidecarReturnNamespace, sidecarReturnSubsystem, "endpoints"), "Ingress sidecar gateway endpoints on this node as of the last pass that listed them: desired "+ @@ -123,21 +127,28 @@ func NewSidecarReturn(reg prometheus.Registerer) *SidecarReturn { "result; 0 before the first.", nil, nil), } - snapshot.last.Store(&sidecarReturnPass{}) + registerSidecarReturnPasses sync.Once +) + +// NewSidecarReturn creates the series on the instrumentation library's +// registry. The endpoint snapshot is process-wide and starts over with each +// call, so a process builds one SidecarReturn. +func NewSidecarReturn() *SidecarReturn { + registerSidecarReturnPasses.Do(func() { instmetrics.MustRegister(sidecarReturnPasses) }) + sidecarReturnPasses.last.Store(&sidecarReturnPass{}) m := &SidecarReturn{ - snapshot: snapshot, - reconciles: prometheus.NewCounterVec(prometheus.CounterOpts{ + snapshot: sidecarReturnPasses, + reconciles: instmetrics.NewCounterVec(prometheus.CounterOpts{ Namespace: sidecarReturnNamespace, Subsystem: sidecarReturnSubsystem, Name: "reconcile_total", Help: "Sidecar return path passes by result: success, partial (an endpoint or the prune failed), " + "waiting_identity (no SRv6 locator for this node yet) or error (nothing could be installed).", }, []string{"result"}), - operations: prometheus.NewCounterVec(prometheus.CounterOpts{ + operations: instmetrics.NewCounterVec(prometheus.CounterOpts{ Namespace: sidecarReturnNamespace, Subsystem: sidecarReturnSubsystem, Name: "operations_total", Help: "Sidecar return path steps by operation (install per endpoint, register per pass, prune, reap) " + "and result (success, error).", }, []string{"operation", "result"}), } - reg.MustRegister(m.snapshot, m.reconciles, m.operations) for _, r := range sidecarReturnResults { m.reconciles.WithLabelValues(r) } diff --git a/internal/plumbing/nldump/nldump.go b/internal/plumbing/nldump/nldump.go index 8f2529f20..671ef4c43 100644 --- a/internal/plumbing/nldump/nldump.go +++ b/internal/plumbing/nldump/nldump.go @@ -13,8 +13,8 @@ // dump a bounded number of times and never return a partial result: an entry // missing from an interrupted dump would look absent. Every interrupted // attempt, and every dump still interrupted on its last attempt, is counted -// in the metrics MustRegister exposes, so churn is visible before it fails a -// caller. +// in metrics created on the instrumentation library's registry when the +// package loads, so churn is visible before it fails a caller. // // Each package-level function opens its own netlink socket in the calling // thread's network namespace, with the same send and receive timeout, as the @@ -30,6 +30,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/vishvananda/netlink" + "go.miloapis.com/instrumentation/metrics" "golang.org/x/sys/unix" ) @@ -56,14 +57,14 @@ const ( ) var ( - interrupted = prometheus.NewCounterVec(prometheus.CounterOpts{ + interrupted = metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: "galactic", Subsystem: "netlink_dump", Name: "interrupted_total", Help: "Netlink listing attempts the kernel interrupted because the state they walked changed, " + "by kind. Each is discarded and retried.", }, []string{labelKind}) - failures = prometheus.NewCounterVec(prometheus.CounterOpts{ + failures = metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: "galactic", Subsystem: "netlink_dump", Name: "failures_total", @@ -78,13 +79,6 @@ func init() { } } -// MustRegister registers the interruption and failure counters against reg, -// panicking on a duplicate as the underlying registry does. The counters are -// process-wide, so a process registers them once, at startup. -func MustRegister(reg prometheus.Registerer) { - reg.MustRegister(interrupted, failures) -} - // sleep is time.Sleep, replaced by tests. var sleep = time.Sleep diff --git a/internal/plumbing/nldump/nldump_internal_test.go b/internal/plumbing/nldump/nldump_internal_test.go index a692e0f84..6597048d2 100644 --- a/internal/plumbing/nldump/nldump_internal_test.go +++ b/internal/plumbing/nldump/nldump_internal_test.go @@ -12,10 +12,10 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" + ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" ) // errInterrupted is how netlink reports a dump the kernel flagged interrupted. @@ -129,13 +129,11 @@ func TestRetry_ReturnsOtherErrorsAtOnce(t *testing.T) { } } -// TestMustRegister_ExposesEveryKind pins that a scrape shows both counters +// TestMetrics_ExposeEveryKind pins that a scrape shows both counters // for every listing kind from startup, before any listing is interrupted, so // a rate over them is defined from the first scrape. -func TestMustRegister_ExposesEveryKind(t *testing.T) { - reg := prometheus.NewRegistry() - MustRegister(reg) - families, err := reg.Gather() +func TestMetrics_ExposeEveryKind(t *testing.T) { + families, err := ctrlmetrics.Registry.Gather() if err != nil { t.Fatalf("gather: %v", err) } diff --git a/internal/plumbing/nldump/nldump_test.go b/internal/plumbing/nldump/nldump_test.go index 7595d1b48..6f925098b 100644 --- a/internal/plumbing/nldump/nldump_test.go +++ b/internal/plumbing/nldump/nldump_test.go @@ -14,10 +14,10 @@ import ( "testing" "github.com/containernetworking/plugins/pkg/ns" - "github.com/prometheus/client_golang/prometheus" "github.com/vishvananda/netlink" "github.com/vishvananda/netns" "golang.org/x/sys/unix" + ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" "go.datum.net/galactic/internal/plumbing/nldump" "go.datum.net/galactic/internal/plumbing/nldump/nldumptest" @@ -216,9 +216,7 @@ func TestLister_ListsTheHandlesNamespace(t *testing.T) { // label values the counters carry, so the helper never waits on a series // that does not exist. func TestNldumptest_KindsMatchMetricLabels(t *testing.T) { - reg := prometheus.NewRegistry() - nldump.MustRegister(reg) - families, err := reg.Gather() + families, err := ctrlmetrics.Registry.Gather() if err != nil { t.Fatalf("gather: %v", err) } diff --git a/internal/plumbing/nldump/nldumptest/nldumptest.go b/internal/plumbing/nldump/nldumptest/nldumptest.go index 85623174a..0bfbc2710 100644 --- a/internal/plumbing/nldump/nldumptest/nldumptest.go +++ b/internal/plumbing/nldump/nldumptest/nldumptest.go @@ -15,11 +15,12 @@ import ( "time" "github.com/containernetworking/plugins/pkg/ns" - "github.com/prometheus/client_golang/prometheus" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" + ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" - "go.datum.net/galactic/internal/plumbing/nldump" + // Creates the counters counts reads. + _ "go.datum.net/galactic/internal/plumbing/nldump" ) // Listing kinds, the kind label values of nldump's counters. @@ -138,12 +139,11 @@ func UntilInterrupted(t testing.TB, netns ns.NetNS, kinds []string, minPasses in return passes } -// counts returns metric's value per kind label. +// counts returns metric's value per kind label, from the instrumentation +// library's registry. func counts(t testing.TB, metric string) map[string]float64 { t.Helper() - reg := prometheus.NewRegistry() - nldump.MustRegister(reg) - families, err := reg.Gather() + families, err := ctrlmetrics.Registry.Gather() if err != nil { t.Fatalf("gather netlink dump metrics: %v", err) }