From dace9b6a71eeefb0b80c9ca6f75c494d52bf88be Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 09:58:28 -0400 Subject: [PATCH 1/2] refactor(fabric): Create fabric routing metrics with the library fabric-config-agent served a private registry holding the next-hop guard's and the activation path's metrics, and fabric-router-controller registered its fleet collector on controller-runtime's registry directly. The instrumentation library's checks saw neither. - NewNextHopMetrics and NewAgentMetrics create their series with the library's constructors. The library's registry keeps a series across calls, so each call starts its vectors over. NextHopMetrics no longer carries a registry or a handler. - fabric-config-agent serves metrics.Handler at /metrics. The endpoint keeps every series it had and adds instrumentation_build_info. - The fleet collector registers through metrics.MustRegister. The agent's scrape test creates its series first and lints them. The controller's test registers the fleet collector, which emits nothing until it leads, to check that its descriptors fit beside the rest. Refs: #1149 Co-Authored-By: Claude Opus 5.5 --- cmd/fabric-config-agent/main.go | 10 ++++---- cmd/fabric-config-agent/scrape_test.go | 10 +++++--- cmd/fabric-router-controller/run.go | 6 ++--- cmd/fabric-router-controller/scrape_test.go | 10 +++++--- docs/observability/README.md | 10 ++++---- internal/fabricconfig/metrics.go | 25 +++++++++++------- internal/fabricconfig/metrics_test.go | 13 +++++----- internal/fabricconfig/nexthop.go | 28 ++++++++------------- internal/instrumentation/adoption_test.go | 2 -- internal/instrumentation/lint_test.go | 1 + 10 files changed, 61 insertions(+), 54 deletions(-) diff --git a/cmd/fabric-config-agent/main.go b/cmd/fabric-config-agent/main.go index cf07e855d..691eb3ff4 100644 --- a/cmd/fabric-config-agent/main.go +++ b/cmd/fabric-config-agent/main.go @@ -28,6 +28,7 @@ import ( "time" "github.com/spf13/cobra" + instmetrics "go.miloapis.com/instrumentation/metrics" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -375,11 +376,10 @@ func writerLock(opts *options, metrics *fabricconfig.AgentMetrics, writer string return fabricconfig.TimedLock{Locker: lock, Metrics: metrics, Writer: writer} } -// newMetrics builds the registry served at /metrics, holding the next-hop -// guard's and the activation path's metrics. +// newMetrics creates the next-hop guard's and the activation path's metrics, +// which /metrics serves from the instrumentation library's registry. func newMetrics() (*fabricconfig.NextHopMetrics, *fabricconfig.AgentMetrics) { - m := fabricconfig.NewNextHopMetrics() - return m, fabricconfig.NewAgentMetrics(m.Registry) + return fabricconfig.NewNextHopMetrics(), fabricconfig.NewAgentMetrics() } // watchWithGuard runs a.Watch alongside a NextHopGuard over the same FRR @@ -421,7 +421,7 @@ func watchWithGuard(ctx context.Context, a *fabricconfig.Agent, opts *options) e if opts.metricsBindAddress != "" { mux := http.NewServeMux() - mux.Handle("/metrics", metrics.Handler()) + mux.Handle("/metrics", instmetrics.Handler()) srv := &http.Server{ Addr: opts.metricsBindAddress, Handler: mux, diff --git a/cmd/fabric-config-agent/scrape_test.go b/cmd/fabric-config-agent/scrape_test.go index c6cb3c1bf..febe2186e 100644 --- a/cmd/fabric-config-agent/scrape_test.go +++ b/cmd/fabric-config-agent/scrape_test.go @@ -8,10 +8,14 @@ import ( "testing" "go.miloapis.com/instrumentation/instrumenttest" + "go.miloapis.com/instrumentation/metrics" ) -// TestMetricsScrape scrapes the registry the agent serves at /metrics. +// TestMetricsScrape scrapes what the agent serves at /metrics, the +// instrumentation library's registry, once newMetrics has created the +// agent's series, and lints them. func TestMetricsScrape(t *testing.T) { - m, _ := newMetrics() - instrumenttest.AssertScrapes(t, m.Handler()) + newMetrics() + instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/cmd/fabric-router-controller/run.go b/cmd/fabric-router-controller/run.go index 8242a1ef6..ba9731365 100644 --- a/cmd/fabric-router-controller/run.go +++ b/cmd/fabric-router-controller/run.go @@ -7,12 +7,12 @@ import ( "fmt" "github.com/spf13/cobra" + "go.miloapis.com/instrumentation/metrics" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/healthz" - ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" networkv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" @@ -98,9 +98,7 @@ metrics on the metrics address.`, // The leader exports the fleet's state from its cache beside // controller-runtime's own metrics. fleet := &routingmetrics.Collector{Reader: mgr.GetClient(), Rollout: rolloutEnabled} - if err := ctrlmetrics.Registry.Register(fleet); err != nil { - return fmt.Errorf("register fleet metrics: %w", err) - } + metrics.MustRegister(fleet) if err := mgr.Add(fleet); err != nil { return fmt.Errorf("add fleet metrics: %w", err) } diff --git a/cmd/fabric-router-controller/scrape_test.go b/cmd/fabric-router-controller/scrape_test.go index 557990fa6..18b801732 100644 --- a/cmd/fabric-router-controller/scrape_test.go +++ b/cmd/fabric-router-controller/scrape_test.go @@ -9,11 +9,15 @@ import ( "go.miloapis.com/instrumentation/instrumenttest" "go.miloapis.com/instrumentation/metrics" + + routingmetrics "go.datum.net/galactic/internal/fabric/routing/metrics" ) -// 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, with the fleet collector run +// registers. Only the leader's collector emits series, so this one, never +// started, checks that its descriptors fit beside the others. func TestMetricsScrape(t *testing.T) { + metrics.MustRegister(&routingmetrics.Collector{}) instrumenttest.AssertScrapes(t, metrics.Handler()) } diff --git a/docs/observability/README.md b/docs/observability/README.md index 8db274fde..0d1be7bdd 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 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: +which every controller-runtime manager serves and `galactic-cni` and +`fabric-config-agent` serve with the library's `metrics.Handler`. The +fabric-api node sidecar serves only its own registry, so a library metric +linked into it is not exported until it serves 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. diff --git a/internal/fabricconfig/metrics.go b/internal/fabricconfig/metrics.go index 9da393860..b3b37e830 100644 --- a/internal/fabricconfig/metrics.go +++ b/internal/fabricconfig/metrics.go @@ -14,6 +14,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) // Activation outcomes the agent counts. @@ -127,7 +128,7 @@ func ReadBootRecord(path string) (BootRecord, error) { } // AgentMetrics is the activation path's and the writer lock's -// instrumentation. Register it on the registry the watch container serves. +// instrumentation. type AgentMetrics struct { activations *prometheus.CounterVec duration *prometheus.HistogramVec @@ -136,39 +137,45 @@ type AgentMetrics struct { boot *prometheus.GaugeVec } -// NewAgentMetrics builds the agent's metrics and registers them on reg. -func NewAgentMetrics(reg prometheus.Registerer) *AgentMetrics { +// NewAgentMetrics creates the agent's metrics on the instrumentation +// library's registry. The registry keeps the series across calls, so each +// call starts them over. +func NewAgentMetrics() *AgentMetrics { m := &AgentMetrics{ - activations: prometheus.NewCounterVec(prometheus.CounterOpts{ + activations: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_router_activations_total", Help: "Activations by outcome. committed, recovered, degraded and refused count each epoch once " + "per agent process, so a restarted agent may count an epoch it meets again; error counts every " + "failed attempt.", }, []string{"outcome"}), - duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ + duration: metrics.NewHistogramVec(prometheus.HistogramOpts{ Name: "fabric_router_activation_duration_seconds", Help: "Time the agent took to commit, recover or degrade an activation, its stabilization window " + "included.", Buckets: []float64{1, 5, 10, 30, 60, 120, 300, 600, 1200, 1800, 3600}, }, []string{"outcome"}), - staging: prometheus.NewCounterVec(prometheus.CounterOpts{ + staging: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_router_staging_runs_total", Help: "Candidate revisions the agent validated and diffed without applying, by result: staged, " + "rejected or revision_not_found.", }, []string{"result"}), - lockWait: prometheus.NewHistogramVec(prometheus.HistogramOpts{ + lockWait: metrics.NewHistogramVec(prometheus.HistogramOpts{ Name: "fabric_router_writer_lock_wait_seconds", Help: "Time each FRR writer waited for the node's writer lock, by result: acquired, timeout or " + "error. The lock is retried every 100ms.", Buckets: []float64{.1, .5, 1, 5, 10, 30, 60, 120, 300, 900}, }, []string{"writer", "result"}), - boot: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + boot: metrics.NewGaugeVec(prometheus.GaugeOpts{ Name: "fabric_router_boot_source", Help: "1 for where the pod's init container took the configuration FRR started with: configmap, " + "checkpoint_offline, checkpoint_online or active_revision.", }, []string{"source"}), } - reg.MustRegister(m.activations, m.duration, m.staging, m.lockWait, m.boot) + m.activations.Reset() + m.duration.Reset() + m.staging.Reset() + m.lockWait.Reset() + m.boot.Reset() return m } diff --git a/internal/fabricconfig/metrics_test.go b/internal/fabricconfig/metrics_test.go index 7183f62fb..e6a45eacc 100644 --- a/internal/fabricconfig/metrics_test.go +++ b/internal/fabricconfig/metrics_test.go @@ -33,7 +33,7 @@ func activations(m *AgentMetrics, outcome string) float64 { // often the agent sees the epoch again. func TestAgentMetricsActivations(t *testing.T) { h := newHarness(t, deployment(networkv1alpha1.FabricConfigSourceCRD)) - m := NewAgentMetrics(prometheus.NewRegistry()) + m := NewAgentMetrics() h.agent.Metrics = m if err := h.client.Create(context.Background(), release(h.revs[0], h.revs[1])); err != nil { t.Fatal(err) @@ -121,7 +121,7 @@ func TestErrorOutcome(t *testing.T) { // validates a candidate, not each sync that finds it already staged. func TestAgentMetricsStaging(t *testing.T) { h := newHarness(t, deployment(networkv1alpha1.FabricConfigSourceShadow)) - m := NewAgentMetrics(prometheus.NewRegistry()) + m := NewAgentMetrics() h.agent.Metrics = m h.frr.running = rendered(t, h.revs[0]) h.update(func(d *networkv1alpha1.FabricRouterDeployment) { @@ -157,8 +157,9 @@ func (l slowLock) Lock(context.Context) (func(), error) { // TestTimedLock observes every wait under its writer and how it ended: // acquired, ended by its deadline, or failed otherwise. func TestTimedLock(t *testing.T) { - reg := prometheus.NewRegistry() - m := NewAgentMetrics(reg) + m := NewAgentMetrics() + reg := prometheus.NewPedanticRegistry() + reg.MustRegister(m.lockWait) for _, l := range []struct { writer string err error @@ -207,7 +208,7 @@ func TestTimedLock(t *testing.T) { // TestActivationCounterOnce counts a finished or refused epoch once per // process, and every failed attempt. func TestActivationCounterOnce(t *testing.T) { - m := NewAgentMetrics(prometheus.NewRegistry()) + m := NewAgentMetrics() d := &DeploymentAgent{Metrics: m} for range 3 { d.count("uid", 1, OutcomeRefused, 0) @@ -250,7 +251,7 @@ func TestBootRecord(t *testing.T) { t.Errorf("ClearBootRecord of nothing = %v", err) } - m := NewAgentMetrics(prometheus.NewRegistry()) + m := NewAgentMetrics() m.SetBoot(BootConfigMap) m.SetBoot(got.Source) if n := testutil.CollectAndCount(m.boot); n != 1 { diff --git a/internal/fabricconfig/nexthop.go b/internal/fabricconfig/nexthop.go index 0d69bbb1b..a629dad65 100644 --- a/internal/fabricconfig/nexthop.go +++ b/internal/fabricconfig/nexthop.go @@ -9,13 +9,12 @@ import ( "encoding/json" "fmt" "log/slog" - "net/http" "net/netip" "sort" "time" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" + "go.miloapis.com/instrumentation/metrics" corev1 "k8s.io/api/core/v1" "k8s.io/client-go/tools/events" ) @@ -49,43 +48,38 @@ type BGP interface { ResetNeighbor(ctx context.Context, neighbor string) error } -// NextHopMetrics holds NextHopGuard's Prometheus instrumentation in a private -// registry. +// NextHopMetrics holds NextHopGuard's Prometheus instrumentation. type NextHopMetrics struct { - Registry *prometheus.Registry - mapped *prometheus.GaugeVec resets *prometheus.CounterVec uninstalled *prometheus.GaugeVec } -// NewNextHopMetrics builds a NextHopMetrics with every metric registered. +// NewNextHopMetrics creates NextHopMetrics on the instrumentation library's +// registry. The registry keeps the series across calls, so each call starts +// them over. func NewNextHopMetrics() *NextHopMetrics { m := &NextHopMetrics{ - Registry: prometheus.NewRegistry(), - mapped: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + mapped: metrics.NewGaugeVec(prometheus.GaugeOpts{ Name: "fabric_router_bgp_mapped_nexthop", Help: "1 when an established session sourced from a global IPv6 address announces an IPv4-mapped " + "next hop, 0 when it announces a usable one.", }, []string{"peer"}), - resets: prometheus.NewCounterVec(prometheus.CounterOpts{ + resets: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_router_bgp_mapped_nexthop_resets_total", Help: "Hard resets of sessions that announced an IPv4-mapped next hop.", }, []string{"peer"}), - uninstalled: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + uninstalled: metrics.NewGaugeVec(prometheus.GaugeOpts{ Name: "fabric_router_bgp_uninstalled_routes", Help: "Prefixes with a BGP route in zebra and no route of any protocol installed in the kernel.", }, []string{"afi"}), } - m.Registry.MustRegister(m.mapped, m.resets, m.uninstalled) + m.mapped.Reset() + m.resets.Reset() + m.uninstalled.Reset() return m } -// Handler returns the http.Handler serving the registry. -func (m *NextHopMetrics) Handler() http.Handler { - return promhttp.HandlerFor(m.Registry, promhttp.HandlerOpts{}) -} - // NextHopGuard finds IPv6 sessions announcing an IPv4-mapped next hop and // hard-resets them, and counts BGP routes zebra failed to install. // diff --git a/internal/instrumentation/adoption_test.go b/internal/instrumentation/adoption_test.go index c7433beb1..680678c4c 100644 --- a/internal/instrumentation/adoption_test.go +++ b/internal/instrumentation/adoption_test.go @@ -30,12 +30,10 @@ const moduleRoot = "../.." var pending = []string{ // #1149: serve controller-runtime's registry through library metrics. "cmd/fabric-api", - "cmd/fabric-router-controller", // #1149: create metrics with the library's constructors instead of a // registry parameter or a private registry. "internal/fabric/gateway", "internal/fabric/node", - "internal/fabricconfig", } // 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 247650195..dd9319af8 100644 --- a/internal/instrumentation/lint_test.go +++ b/internal/instrumentation/lint_test.go @@ -21,6 +21,7 @@ import ( // Every package that creates a metric through the library, so Lint sees // it. TestLintLinksEveryMetric keeps this list complete. _ "go.datum.net/galactic/internal/edge/diag" + _ "go.datum.net/galactic/internal/fabricconfig" _ "go.datum.net/galactic/internal/gateway" _ "go.datum.net/galactic/internal/ingresssidecar" _ "go.datum.net/galactic/internal/plumbing/ebpf/metrics" From 01c4d9d890c7e0af1b67e0a85d2f5b3322df9a23 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 10:14:09 -0400 Subject: [PATCH 2/2] test(fabric): Register the scrape test's collector once per process The fleet 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/fabric-router-controller/scrape_test.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cmd/fabric-router-controller/scrape_test.go b/cmd/fabric-router-controller/scrape_test.go index 18b801732..d2d095da8 100644 --- a/cmd/fabric-router-controller/scrape_test.go +++ b/cmd/fabric-router-controller/scrape_test.go @@ -5,6 +5,7 @@ package main import ( + "sync" "testing" "go.miloapis.com/instrumentation/instrumenttest" @@ -13,11 +14,15 @@ import ( routingmetrics "go.datum.net/galactic/internal/fabric/routing/metrics" ) +// startup registers the collector once per test process, as run does once +// per process, so repeated runs of TestMetricsScrape share it. +var startup sync.Once + // TestMetricsScrape scrapes what the manager serves at /metrics, the // instrumentation library's registry, with the fleet collector run // registers. Only the leader's collector emits series, so this one, never // started, checks that its descriptors fit beside the others. func TestMetricsScrape(t *testing.T) { - metrics.MustRegister(&routingmetrics.Collector{}) + startup.Do(func() { metrics.MustRegister(&routingmetrics.Collector{}) }) instrumenttest.AssertScrapes(t, metrics.Handler()) }