From 10d3b652e96e2c29ab1ce2fef1689570c23faef9 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 09:47:33 -0400 Subject: [PATCH 1/2] refactor(gateway,nat): Create metrics with the instrumentation library galactic-gateway and galactic-nat passed controller-runtime's registry down to their datapath setup, which created and registered metrics on it directly, so the instrumentation library's checks skipped them. - The edge telemetry counter and the dispatcher lease series are created by the library's constructors. Their Register methods are gone. - galactic_nat_uplink_resolve_errors_total moves from package main to natattach, next to the uplink resolution it counts, because the lint can only link metrics defined outside a main package. - The edge, NAT, NIC queue and shard state collectors register through metrics.MustRegister, so the setup functions no longer take a registry. A descriptor clash, which only a code change can cause, now panics at startup instead of returning an error. The scrape tests create the startup series that need no kernel before scraping, and lint them. Both endpoints export the same series as before. Refs: #1149 Co-Authored-By: Claude Opus 5.5 --- cmd/galactic-gateway/gateway.go | 21 ++++------- cmd/galactic-gateway/gateway_test.go | 4 +- cmd/galactic-gateway/root.go | 6 +-- cmd/galactic-gateway/scrape_test.go | 15 ++++++-- cmd/galactic-nat/nat.go | 37 ++++--------------- cmd/galactic-nat/root.go | 9 ++--- cmd/galactic-nat/scrape_test.go | 17 +++++++-- internal/gateway/telemetry.go | 14 ++----- internal/gateway/telemetry_test.go | 13 +++++-- internal/instrumentation/adoption_test.go | 4 -- internal/instrumentation/lint_test.go | 3 ++ internal/plumbing/ebpf/natattach/uplinks.go | 16 ++++++++ .../plumbing/ebpf/xdpdispatch/leasemetrics.go | 18 +++------ .../ebpf/xdpdispatch/leasemetrics_test.go | 8 ++-- 14 files changed, 87 insertions(+), 98 deletions(-) diff --git a/cmd/galactic-gateway/gateway.go b/cmd/galactic-gateway/gateway.go index 1b3dedadd..4a897ce0b 100644 --- a/cmd/galactic-gateway/gateway.go +++ b/cmd/galactic-gateway/gateway.go @@ -14,7 +14,7 @@ import ( "sync" "github.com/cilium/ebpf/link" - "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/gateway" @@ -63,14 +63,14 @@ var gatewayDatapathKeepAlive struct { // See installGateway for the attachment itself. func setupGatewayDatapath( ctx context.Context, publicInterface string, internalInterfaces []string, srv6Address, attachMode string, - ipv4 *ipv4Forwarding, metricsReg prometheus.Registerer, coverage *datapathCoverage, + ipv4 *ipv4Forwarding, coverage *datapathCoverage, ) (gateway.Datapath, error) { encapSrc, err := netip.ParseAddr(srv6Address) if err != nil { return nil, fmt.Errorf("parse gateway SRv6 address %q: %w", srv6Address, err) } var datapath *gateway.KernelDatapath - err = installGateway(ctx, publicInterface, internalInterfaces, attachMode, ipv4, metricsReg, coverage, + err = installGateway(ctx, publicInterface, internalInterfaces, attachMode, ipv4, coverage, func(objs *edgeprog.EdgedsrObjects) (edgemetrics.VPCAttribution, error) { dp, err := gateway.NewKernelDatapath(objs, encapSrc) if err != nil { @@ -94,10 +94,10 @@ func setupGatewayDatapath( // leased. See installGateway for the attachment itself. func setupReturnPath( ctx context.Context, internalInterfaces []string, attachMode string, ipv4 *ipv4Forwarding, - metricsReg prometheus.Registerer, coverage *datapathCoverage, + coverage *datapathCoverage, ) (*gateway.KernelReturnPath, error) { var returnPath *gateway.KernelReturnPath - err := installGateway(ctx, "", internalInterfaces, attachMode, ipv4, metricsReg, coverage, + err := installGateway(ctx, "", internalInterfaces, attachMode, ipv4, coverage, func(objs *edgeprog.EdgedsrObjects) (edgemetrics.VPCAttribution, error) { returnPath = gateway.NewKernelReturnPath(objs) return nil, nil @@ -137,7 +137,7 @@ func setupReturnPath( // leaves the packet path unchanged. func installGateway( ctx context.Context, publicInterface string, internalInterfaces []string, attachMode string, - ipv4 *ipv4Forwarding, metricsReg prometheus.Registerer, coverage *datapathCoverage, + ipv4 *ipv4Forwarding, coverage *datapathCoverage, build func(*edgeprog.EdgedsrObjects) (edgemetrics.VPCAttribution, error), ) error { withLB := publicInterface != "" @@ -217,10 +217,6 @@ func installGateway( leaseCtx, stopLeases := context.WithCancel(ctx) var leaseDone <-chan struct{} lease := xdpdispatch.NewLeaseMetrics(edgemetrics.Namespace) - if err := lease.Register(metricsReg); err != nil { - stopLeases() - return fmt.Errorf("register dispatcher lease metrics: %w", err) - } objs, dispatcher, publicSet, returnSet, leaseDone, err = joinDispatcher(leaseCtx, xdpdispatch.PinDir, edgeattach.PinDir, mode, withLB, len(returnTargets) > 0, lease) if err != nil { @@ -248,10 +244,7 @@ func installGateway( abandon() return err } - if err := metricsReg.Register(edgemetrics.NewCollectorFromObjects(objs, attribution)); err != nil { - abandon() - return fmt.Errorf("register edge gateway metrics collector: %w", err) - } + metrics.MustRegister(edgemetrics.NewCollectorFromObjects(objs, attribution)) gatewayDatapathKeepAlive.objs = objs gatewayDatapathKeepAlive.publicSet = publicSet diff --git a/cmd/galactic-gateway/gateway_test.go b/cmd/galactic-gateway/gateway_test.go index 55b147987..c25150260 100644 --- a/cmd/galactic-gateway/gateway_test.go +++ b/cmd/galactic-gateway/gateway_test.go @@ -7,8 +7,6 @@ package main import ( "context" "testing" - - "github.com/prometheus/client_golang/prometheus" ) // TestSetupGatewayDatapath_InvalidAddressIsError covers the address-parse @@ -19,7 +17,7 @@ import ( // PublicInterface/SRv6Address before setupGatewayDatapath is ever called. func TestSetupGatewayDatapath_InvalidAddressIsError(t *testing.T) { _, err := setupGatewayDatapath(context.Background(), "eth0", nil, "not-an-ip-address", "dispatch", nil, - prometheus.NewRegistry(), newDatapathCoverage(nil)) + newDatapathCoverage(nil)) if err == nil { t.Error("setupGatewayDatapath with an invalid SRv6 address: want an error, got nil") } diff --git a/cmd/galactic-gateway/root.go b/cmd/galactic-gateway/root.go index 69dba6d66..957f11756 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -20,7 +20,6 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" - ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" @@ -177,7 +176,7 @@ func runCmd(cfg *config.GatewayConfig) error { return err } gwDatapath, err = setupGatewayDatapath(ctx, cfg.PublicInterface, cfg.InternalInterfaces, encapSrc, - cfg.XDPAttach, ipv4, ctrlmetrics.Registry, coverage) + cfg.XDPAttach, ipv4, coverage) if err != nil { return fmt.Errorf("setup edge gateway eBPF datapath: %w", err) } @@ -186,7 +185,7 @@ func runCmd(cfg *config.GatewayConfig) error { // is load-balanced here, but backend nodes can still send replies // through it, which only edge_return lets past connection tracking. turnOffDatapath(ctx, xdpdispatch.PinDir, xdpdispatch.SlotGatewayLB) - rp, err := setupReturnPath(ctx, cfg.InternalInterfaces, cfg.XDPAttach, ipv4, ctrlmetrics.Registry, coverage) + rp, err := setupReturnPath(ctx, cfg.InternalInterfaces, cfg.XDPAttach, ipv4, coverage) if err != nil { return fmt.Errorf("setup edge gateway return path: %w", err) } @@ -205,7 +204,6 @@ func runCmd(cfg *config.GatewayConfig) error { // comments for what each does and does not cover. gwQuota := gateway.NewNodeQuotaEnforcer(gateway.DefaultMaxRulesPerTenant, gateway.DefaultMaxRuleTableEntries) gwTelemetry := gateway.NewPrometheusTelemetryEmitter() - gwTelemetry.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-gateway/scrape_test.go b/cmd/galactic-gateway/scrape_test.go index 557990fa6..fa730307b 100644 --- a/cmd/galactic-gateway/scrape_test.go +++ b/cmd/galactic-gateway/scrape_test.go @@ -9,11 +9,20 @@ import ( "go.miloapis.com/instrumentation/instrumenttest" "go.miloapis.com/instrumentation/metrics" + + "go.datum.net/galactic/internal/gateway" + "go.datum.net/galactic/internal/plumbing/ebpf/edgemetrics" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" ) -// TestMetricsScrape scrapes what the manager serves at /metrics: -// controller-runtime's registry, which metrics.Handler serves unchanged, -// holding every metric this command's packages register when linked. +// TestMetricsScrape scrapes what the manager serves at /metrics, the +// instrumentation library's registry, once it holds the series run creates +// at startup that need no kernel: the telemetry emitter's and the dispatcher +// lease's. It lints them too. The edge datapath collector reads loaded maps, +// so it is left out. func TestMetricsScrape(t *testing.T) { + gateway.NewPrometheusTelemetryEmitter() + xdpdispatch.NewLeaseMetrics(edgemetrics.Namespace) instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 051cf8b53..24d63a6a9 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -17,6 +17,7 @@ import ( "github.com/cilium/ebpf/link" "github.com/prometheus/client_golang/prometheus" "github.com/safchain/ethtool" + "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/controller" @@ -280,7 +281,7 @@ func (d *natDatapath) Programmed() (controller.EgressShardIdentity, bool) { // natDatapathKeepAlive rather than closed here: they, and the attachment // itself, must survive for the life of this process. func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, - metricsReg prometheus.Registerer, onCoverage func()) (*natDatapath, error) { + onCoverage func()) (*natDatapath, error) { uplinks, err := waitForUplinks(ctx, cfg.UplinkInterfaces) if err != nil { return nil, err @@ -345,10 +346,6 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, // The lease runs for the life of the process, so its done channel // is not needed here. lease := xdpdispatch.NewLeaseMetrics(metricsNamespace) - if err := lease.Register(metricsReg); err != nil { - _ = objs.Close() - return nil, fmt.Errorf("register dispatcher lease metrics: %w", err) - } if dispatcher, dispatchSet, _, err = joinDispatcher(ctx, xdpdispatch.PinDir, mode, objs.NatIngress, lease); err != nil { _ = objs.Close() @@ -372,26 +369,9 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, } } - collector := newNatCollector(objs) - if err := metricsReg.Register(collector); err != nil { - closeAll(xdpLinks) - _ = objs.Close() - return nil, fmt.Errorf("register egress shard metrics collector: %w", err) - } - - registerUplinkQueueStats(metricsReg, d) - - d.resolveErrors = prometheus.NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, - Name: "uplink_resolve_errors_total", - Help: "Times re-resolving this node's uplinks after a link or route change failed. The shard keeps " + - "its previous coverage, so a steady rise means uplinks that appeared since are not covered.", - }) - if err := metricsReg.Register(d.resolveErrors); err != nil { - closeAll(xdpLinks) - _ = objs.Close() - return nil, fmt.Errorf("register uplink resolve error metric: %w", err) - } + metrics.MustRegister(newNatCollector(objs)) + registerUplinkQueueStats(d) + d.resolveErrors = natattach.NewUplinkResolveErrors(metricsNamespace) natDatapathKeepAlive.objs = objs natDatapathKeepAlive.set = set @@ -413,16 +393,13 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, // before the datapath sees them, so drops_total stays flat through it (#673); // these counters are what show it. Failing to set them up costs only those // counters, so it is logged rather than failing the shard. -func registerUplinkQueueStats(metricsReg prometheus.Registerer, d *natDatapath) { +func registerUplinkQueueStats(d *natDatapath) { et, err := ethtool.NewEthtool() if err != nil { slog.Warn("Cannot open ethtool; uplink receive queue metrics are disabled", "err", err) return } - if err := metricsReg.Register(nicstats.NewCollector(metricsNamespace, et, d.Uplinks)); err != nil { - et.Close() - slog.Warn("Cannot register uplink receive queue metrics", "err", err) - } + metrics.MustRegister(nicstats.NewCollector(metricsNamespace, et, d.Uplinks)) } // joinDispatcher opens the node's XDP dispatcher, fills this shard's slot with diff --git a/cmd/galactic-nat/root.go b/cmd/galactic-nat/root.go index f300ed025..ca3f38c9c 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -13,6 +13,7 @@ import ( "strings" "github.com/spf13/cobra" + "go.miloapis.com/instrumentation/metrics" "google.golang.org/grpc" grpchealth "google.golang.org/grpc/health" "google.golang.org/grpc/health/grpc_health_v1" @@ -21,7 +22,6 @@ import ( clientgoscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/event" - ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" @@ -128,7 +128,7 @@ func runCmd(cfg *config.NATConfig) error { if err := sysctl.SetProcSysPath(cfg.ProcSysPath); err != nil { return err } - datapath, err = setupNatDatapath(ctx, cfg, ctrlmetrics.Registry, func() { + datapath, err = setupNatDatapath(ctx, cfg, func() { select { case coverageChanged <- struct{}{}: default: @@ -141,10 +141,7 @@ func runCmd(cfg *config.NATConfig) error { if err != nil { return fmt.Errorf("setup egress translation eBPF datapath: %w", err) } - if err := ctrlmetrics.Registry.Register( - newShardStateCollector(datapath, cfg.DatapathEnabled, cfg.XDPAttach)); err != nil { - return fmt.Errorf("register egress shard state metrics: %w", err) - } + metrics.MustRegister(newShardStateCollector(datapath, cfg.DatapathEnabled, cfg.XDPAttach)) coverageEvents := make(chan event.GenericEvent, 1) go followCoverage(ctx, datapath, healthSrv, coverageChanged, coverageEvents) diff --git a/cmd/galactic-nat/scrape_test.go b/cmd/galactic-nat/scrape_test.go index 557990fa6..fa2286a48 100644 --- a/cmd/galactic-nat/scrape_test.go +++ b/cmd/galactic-nat/scrape_test.go @@ -9,11 +9,22 @@ import ( "go.miloapis.com/instrumentation/instrumenttest" "go.miloapis.com/instrumentation/metrics" + + "go.datum.net/galactic/internal/config" + "go.datum.net/galactic/internal/plumbing/ebpf/natattach" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" ) -// TestMetricsScrape scrapes what the manager serves at /metrics: -// controller-runtime's registry, which metrics.Handler serves unchanged, -// holding every metric this command's packages register when linked. +// TestMetricsScrape scrapes what the manager serves at /metrics, the +// instrumentation library's registry, once it holds the series run creates +// at startup that need no kernel: the shard state collector of a disabled +// datapath, and the lease and uplink metrics setupNatDatapath creates. It +// lints them too. The map and NIC queue collectors read a loaded datapath, so +// they are left out. func TestMetricsScrape(t *testing.T) { + metrics.MustRegister(newShardStateCollector(disabledDatapath{}, false, config.NATXDPAttachDispatch)) + xdpdispatch.NewLeaseMetrics(metricsNamespace) + natattach.NewUplinkResolveErrors(metricsNamespace) instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/internal/gateway/telemetry.go b/internal/gateway/telemetry.go index b5e2cbfa8..2629d71bb 100644 --- a/internal/gateway/telemetry.go +++ b/internal/gateway/telemetry.go @@ -8,6 +8,7 @@ import ( "context" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) const telemetryNamespace = "galactic_edge" @@ -28,11 +29,11 @@ type PrometheusTelemetryEmitter struct { controlPlaneDrops *prometheus.CounterVec } -// NewPrometheusTelemetryEmitter builds a fresh, unregistered -// PrometheusTelemetryEmitter. Call MustRegister once at process startup. +// NewPrometheusTelemetryEmitter creates the emitter's counter on the +// instrumentation library's registry. func NewPrometheusTelemetryEmitter() *PrometheusTelemetryEmitter { return &PrometheusTelemetryEmitter{ - controlPlaneDrops: prometheus.NewCounterVec(prometheus.CounterOpts{ + controlPlaneDrops: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: telemetryNamespace, Name: "control_plane_drops_total", Help: "Rule applications rejected before ever reaching the datapath (e.g. quota_exceeded), " + @@ -42,13 +43,6 @@ func NewPrometheusTelemetryEmitter() *PrometheusTelemetryEmitter { } } -// MustRegister registers every metric this type owns against reg, panicking on -// a duplicate as the underlying registry does. Callers do this once per process, -// at startup. -func (e *PrometheusTelemetryEmitter) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(e.controlPlaneDrops) -} - // RuleApplied is a no-op: there is no per-rule placement fact left to record. // It is kept to satisfy the interface, and as the natural place for any future // call-site-only fact this engine learns. diff --git a/internal/gateway/telemetry_test.go b/internal/gateway/telemetry_test.go index 1b7cde9d9..e955337f6 100644 --- a/internal/gateway/telemetry_test.go +++ b/internal/gateway/telemetry_test.go @@ -56,6 +56,8 @@ func TestPrometheusTelemetryEmitter_RuleAppliedAndRemovedDoNotPanic(t *testing.T func TestPrometheusTelemetryEmitter_DropObservedIncrementsCounter(t *testing.T) { e := NewPrometheusTelemetryEmitter() + // The counter lives on the shared registry; start this test without any. + e.controlPlaneDrops.Reset() e.DropObserved(context.Background(), testRuleKeyR1, "quota_exceeded") e.DropObserved(context.Background(), testRuleKeyR1, "quota_exceeded") @@ -73,8 +75,11 @@ func TestPrometheusTelemetryEmitter_DropObservedIncrementsCounter(t *testing.T) } } -func TestPrometheusTelemetryEmitter_MustRegisterIsIdempotentPerInstance(t *testing.T) { - e := NewPrometheusTelemetryEmitter() - reg := prometheus.NewRegistry() - e.MustRegister(reg) // must not panic +// TestPrometheusTelemetryEmitter_EmittersShareTheCounter: a second emitter +// gets the counter the first created rather than panicking on a duplicate. +func TestPrometheusTelemetryEmitter_EmittersShareTheCounter(t *testing.T) { + first, second := NewPrometheusTelemetryEmitter(), NewPrometheusTelemetryEmitter() + if first.controlPlaneDrops != second.controlPlaneDrops { + t.Error("two emitters hold different counters") + } } diff --git a/internal/instrumentation/adoption_test.go b/internal/instrumentation/adoption_test.go index e18dbe7d5..6f17c31c2 100644 --- a/internal/instrumentation/adoption_test.go +++ b/internal/instrumentation/adoption_test.go @@ -33,8 +33,6 @@ var pending = []string{ "cmd/fabric-router-controller", "cmd/galactic-controller", "cmd/galactic-edge", - "cmd/galactic-gateway", - "cmd/galactic-nat", "cmd/galactic-vrf", // #1149: create metrics with the library's constructors instead of a // registry parameter or a private registry. @@ -42,9 +40,7 @@ var pending = []string{ "internal/fabric/gateway", "internal/fabric/node", "internal/fabricconfig", - "internal/gateway", "internal/ingresssidecar", - "internal/plumbing/ebpf/xdpdispatch", } // 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 0d2e01c6b..97736c137 100644 --- a/internal/instrumentation/lint_test.go +++ b/internal/instrumentation/lint_test.go @@ -20,7 +20,10 @@ import ( // Every package that creates a metric through the library, so Lint sees // it. TestLintLinksEveryMetric keeps this list complete. + _ "go.datum.net/galactic/internal/gateway" _ "go.datum.net/galactic/internal/plumbing/ebpf/metrics" + _ "go.datum.net/galactic/internal/plumbing/ebpf/natattach" + _ "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" _ "go.datum.net/galactic/internal/plumbing/nldump" _ "go.datum.net/galactic/internal/runtime/gobgp" _ "go.datum.net/galactic/internal/serviceroute" diff --git a/internal/plumbing/ebpf/natattach/uplinks.go b/internal/plumbing/ebpf/natattach/uplinks.go index 5dc10e7d2..c0e260f80 100644 --- a/internal/plumbing/ebpf/natattach/uplinks.go +++ b/internal/plumbing/ebpf/natattach/uplinks.go @@ -8,6 +8,9 @@ import ( "errors" "fmt" + "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" + "go.datum.net/galactic/internal/plumbing/ebpf/attach" ) @@ -64,3 +67,16 @@ func ResolveUplinks(override []string) ([]string, error) { } return targets, nil } + +// NewUplinkResolveErrors creates _uplink_resolve_errors_total on +// the instrumentation library's registry: how often re-resolving the uplinks +// after a link or route change failed. namespace is the caller's own metric +// prefix. +func NewUplinkResolveErrors(namespace string) prometheus.Counter { + return metrics.NewCounter(prometheus.CounterOpts{ + Namespace: namespace, + Name: "uplink_resolve_errors_total", + Help: "Times re-resolving this node's uplinks after a link or route change failed. The shard keeps " + + "its previous coverage, so a steady rise means uplinks that appeared since are not covered.", + }) +} diff --git a/internal/plumbing/ebpf/xdpdispatch/leasemetrics.go b/internal/plumbing/ebpf/xdpdispatch/leasemetrics.go index a49d14951..bf3e5a1e6 100644 --- a/internal/plumbing/ebpf/xdpdispatch/leasemetrics.go +++ b/internal/plumbing/ebpf/xdpdispatch/leasemetrics.go @@ -9,6 +9,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) // String names slot as its metrics label: "gateway_lb", "gateway_return", @@ -41,19 +42,20 @@ type LeaseMetrics struct { now func() time.Time } -// NewLeaseMetrics builds the lease series under namespace, the caller's own -// metric prefix: _dispatch_lease_renewals_total{slot, result} and +// NewLeaseMetrics creates the lease series on the instrumentation library's +// registry under namespace, the caller's own metric prefix: +// _dispatch_lease_renewals_total{slot, result} and // _dispatch_lease_expiry_timestamp_seconds{slot}. func NewLeaseMetrics(namespace string) *LeaseMetrics { return &LeaseMetrics{ - renewals: prometheus.NewCounterVec(prometheus.CounterOpts{ + renewals: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: namespace, Subsystem: "dispatch_lease", Name: "renewals_total", Help: "Renewals of this process's XDP dispatcher slot leases, by slot and result. A slot whose " + "renewals keep failing is skipped by the dispatcher once its lease expires.", }, []string{"slot", "result"}), - expiry: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + expiry: metrics.NewGaugeVec(prometheus.GaugeOpts{ Namespace: namespace, Subsystem: "dispatch_lease", Name: "expiry_timestamp_seconds", @@ -64,14 +66,6 @@ func NewLeaseMetrics(namespace string) *LeaseMetrics { } } -// Register registers m's series with reg. -func (m *LeaseMetrics) Register(reg prometheus.Registerer) error { - if err := reg.Register(m.renewals); err != nil { - return err - } - return reg.Register(m.expiry) -} - // Observe returns the onRenew callback for Lease on slot: it records each // renewal's result and then calls onError, which may be nil, with a failed // renewal's error. Both of slot's result series exist from this call on, at diff --git a/internal/plumbing/ebpf/xdpdispatch/leasemetrics_test.go b/internal/plumbing/ebpf/xdpdispatch/leasemetrics_test.go index 9c45936d8..4b73c8fce 100644 --- a/internal/plumbing/ebpf/xdpdispatch/leasemetrics_test.go +++ b/internal/plumbing/ebpf/xdpdispatch/leasemetrics_test.go @@ -9,16 +9,14 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" ) func TestLeaseMetricsObserve(t *testing.T) { m := NewLeaseMetrics("test") - reg := prometheus.NewPedanticRegistry() - if err := m.Register(reg); err != nil { - t.Fatalf("Register: %v", err) - } + // The series live on the shared registry; start this test without any. + m.renewals.Reset() + m.expiry.Reset() renewedAt := time.Unix(1_000_000, 0) m.now = func() time.Time { return renewedAt } From f2dddd236a83ef0298f0aacae6a56a1ced9cfaf7 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 10:13:40 -0400 Subject: [PATCH 2/2] test(nat): Register the scrape test's collector once per process The shard state collector can be registered once per process, as run does. TestMetricsScrape registered it on every run, so a second run in the same test process, such as go test -count=2, panicked on the duplicate. Its setup now runs once. Refs: #1149 Co-Authored-By: Claude Opus 5.5 --- cmd/galactic-nat/scrape_test.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/cmd/galactic-nat/scrape_test.go b/cmd/galactic-nat/scrape_test.go index fa2286a48..a036cd91f 100644 --- a/cmd/galactic-nat/scrape_test.go +++ b/cmd/galactic-nat/scrape_test.go @@ -5,6 +5,7 @@ package main import ( + "sync" "testing" "go.miloapis.com/instrumentation/instrumenttest" @@ -15,6 +16,10 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" ) +// startup registers the series once per test process, as run does once per +// process, so repeated runs of TestMetricsScrape share them. +var startup sync.Once + // TestMetricsScrape scrapes what the manager serves at /metrics, the // instrumentation library's registry, once it holds the series run creates // at startup that need no kernel: the shard state collector of a disabled @@ -22,9 +27,11 @@ import ( // lints them too. The map and NIC queue collectors read a loaded datapath, so // they are left out. func TestMetricsScrape(t *testing.T) { - metrics.MustRegister(newShardStateCollector(disabledDatapath{}, false, config.NATXDPAttachDispatch)) - xdpdispatch.NewLeaseMetrics(metricsNamespace) - natattach.NewUplinkResolveErrors(metricsNamespace) + startup.Do(func() { + metrics.MustRegister(newShardStateCollector(disabledDatapath{}, false, config.NATXDPAttachDispatch)) + xdpdispatch.NewLeaseMetrics(metricsNamespace) + natattach.NewUplinkResolveErrors(metricsNamespace) + }) instrumenttest.AssertScrapes(t, metrics.Handler()) instrumenttest.Lint(t) }