From 48ca0438653f67e8a3044404d7220cedae6deb3e Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 09:43:05 -0400 Subject: [PATCH] refactor(router): Create router metrics with the instrumentation library galactic-router registered its service route metrics, its BMP station gauge and the traffic policy collector on controller-runtime's registry directly, so the instrumentation library's reserved-label check and lint skipped them. - The service route metrics are created by the library's constructors when run calls serviceroute.NewMetrics, as before. - galactic_router_bmp_station_up moves from package main to internal/runtime/gobgp, beside the route install gauge, because the lint can only link metrics defined outside a main package. The observer the BMP keeper calls moves with it. - The traffic policy collector registers through metrics.MustRegister. The lint linking check no longer counts metrics.MustRegister as creating a metric. Lint checks only what the library's constructors create, so a custom collector registered in a main package is never something it could see. The scrape test creates the service route metrics before scraping and lints them. The endpoint's series are unchanged. Refs: #1149 Co-Authored-By: Claude Opus 5.5 --- cmd/galactic-router/bmp.go | 30 +---------------------- cmd/galactic-router/root.go | 7 ++---- cmd/galactic-router/scrape_test.go | 11 ++++++--- internal/instrumentation/adoption_test.go | 2 -- internal/instrumentation/lint_test.go | 5 +++- internal/runtime/gobgp/bmp.go | 24 ++++++++++++++++++ internal/serviceroute/metrics.go | 20 ++++++--------- 7 files changed, 47 insertions(+), 52 deletions(-) diff --git a/cmd/galactic-router/bmp.go b/cmd/galactic-router/bmp.go index d41335467..b772475b2 100644 --- a/cmd/galactic-router/bmp.go +++ b/cmd/galactic-router/bmp.go @@ -7,38 +7,10 @@ package main import ( "fmt" - "github.com/prometheus/client_golang/prometheus" - ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" - "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/runtime/gobgp" ) -// bmpStationUp reports, per BGPRouter and BMP station, whether the router's -// session to that collector is established. A station that is configured but -// down, or whose host does not resolve, reads 0, so an alert can tell a -// collector this router has lost apart from one it was never told about. -var bmpStationUp = prometheus.NewGaugeVec(prometheus.GaugeOpts{ - Name: "galactic_router_bmp_station_up", - Help: "Whether the router's BMP session to a collector is established (1) or not (0).", -}, []string{"router", "station"}) - -func init() { - ctrlmetrics.Registry.MustRegister(bmpStationUp) -} - -// bmpGaugeObserver records each BMP station's state in bmpStationUp. -type bmpGaugeObserver struct{} - -// BMPStationState sets the station's gauge to 1 when up and 0 otherwise. -func (bmpGaugeObserver) BMPStationState(router, station string, up bool) { - v := 0.0 - if up { - v = 1 - } - bmpStationUp.WithLabelValues(router, station).Set(v) -} - // bmpConfigFromRouter builds the runtime's BMP configuration from cfg, naming // the router nodeName in each collector's Initiation message. It returns the // zero BMPConfig, which disables BMP, when no stations are configured, and an @@ -64,6 +36,6 @@ func bmpConfigFromRouter(cfg *config.RouterConfig, nodeName string) (gobgp.BMPCo Policy: policy, StatisticsInterval: cfg.BMPStatisticsInterval, SysName: nodeName, - Observer: bmpGaugeObserver{}, + Observer: gobgp.BMPStationGauge{}, }, nil } diff --git a/cmd/galactic-router/root.go b/cmd/galactic-router/root.go index 663c1281a..de0eefd83 100644 --- a/cmd/galactic-router/root.go +++ b/cmd/galactic-router/root.go @@ -16,6 +16,7 @@ import ( "time" "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" @@ -24,7 +25,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" @@ -120,7 +120,6 @@ func runCmd(cfg *config.RouterConfig) error { return fmt.Errorf("create manager: %w", err) } serviceRouteMetrics := serviceroute.NewMetrics() - serviceRouteMetrics.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 @@ -459,9 +458,7 @@ func setupTrafficPolicyController(mgr ctrl.Manager, nodeName string) error { if err := rec.SetupWithManager(mgr); err != nil { return fmt.Errorf("setup traffic policy controller: %w", err) } - if err := ctrlmetrics.Registry.Register(rec); err != nil { - return fmt.Errorf("register traffic policy metrics: %w", err) - } + metrics.MustRegister(rec) return nil } diff --git a/cmd/galactic-router/scrape_test.go b/cmd/galactic-router/scrape_test.go index 557990fa6..06ae0ec84 100644 --- a/cmd/galactic-router/scrape_test.go +++ b/cmd/galactic-router/scrape_test.go @@ -9,11 +9,16 @@ import ( "go.miloapis.com/instrumentation/instrumenttest" "go.miloapis.com/instrumentation/metrics" + + "go.datum.net/galactic/internal/serviceroute" ) -// 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 the service route metrics run +// creates at startup exist, and lints them. The traffic policy collector +// reads pinned eBPF maps, so it is left out. func TestMetricsScrape(t *testing.T) { + serviceroute.NewMetrics() instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/internal/instrumentation/adoption_test.go b/internal/instrumentation/adoption_test.go index c992be776..e18dbe7d5 100644 --- a/internal/instrumentation/adoption_test.go +++ b/internal/instrumentation/adoption_test.go @@ -35,7 +35,6 @@ var pending = []string{ "cmd/galactic-edge", "cmd/galactic-gateway", "cmd/galactic-nat", - "cmd/galactic-router", "cmd/galactic-vrf", // #1149: create metrics with the library's constructors instead of a // registry parameter or a private registry. @@ -46,7 +45,6 @@ var pending = []string{ "internal/gateway", "internal/ingresssidecar", "internal/plumbing/ebpf/xdpdispatch", - "internal/serviceroute", } // 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 19b4eb228..0d2e01c6b 100644 --- a/internal/instrumentation/lint_test.go +++ b/internal/instrumentation/lint_test.go @@ -23,6 +23,7 @@ import ( _ "go.datum.net/galactic/internal/plumbing/ebpf/metrics" _ "go.datum.net/galactic/internal/plumbing/nldump" _ "go.datum.net/galactic/internal/runtime/gobgp" + _ "go.datum.net/galactic/internal/serviceroute" ) const ( @@ -44,8 +45,10 @@ func TestLintLinksEveryMetric(t *testing.T) { linked := blankImports(t, "lint_test.go") fset := token.NewFileSet() walkSource(t, func(rel string, f *ast.File) { + // metrics.MustRegister doesn't count: Lint checks only the metrics + // the library's constructors create, never a custom collector. creates := slices.ContainsFunc(selectors(f, metricsPath), func(sel *ast.SelectorExpr) bool { - return strings.HasPrefix(sel.Sel.Name, "New") || sel.Sel.Name == "MustRegister" + return strings.HasPrefix(sel.Sel.Name, "New") }) if !creates { return diff --git a/internal/runtime/gobgp/bmp.go b/internal/runtime/gobgp/bmp.go index 368ea7757..bdea4ca8f 100644 --- a/internal/runtime/gobgp/bmp.go +++ b/internal/runtime/gobgp/bmp.go @@ -16,6 +16,8 @@ import ( api "github.com/osrg/gobgp/v4/api" gobgpserver "github.com/osrg/gobgp/v4/pkg/server" + "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) const ( @@ -69,6 +71,28 @@ func (s BMPStation) String() string { return net.JoinHostPort(s.Host, strconv.Itoa(int(s.Port))) } +// bmpStationUp reports, per BGPRouter and BMP station, whether the router's +// session to that collector is established. A station that is configured but +// down, or whose host does not resolve, reads 0, so an alert can tell a +// collector this router has lost apart from one it was never told about. +var bmpStationUp = metrics.NewGaugeVec(prometheus.GaugeOpts{ + Name: "galactic_router_bmp_station_up", + Help: "Whether the router's BMP session to a collector is established (1) or not (0).", +}, []string{labelRouter, "station"}) + +// BMPStationGauge is a BMPStateObserver recording each station's state in +// galactic_router_bmp_station_up. +type BMPStationGauge struct{} + +// BMPStationState sets the station's gauge to 1 when up and 0 otherwise. +func (BMPStationGauge) BMPStationState(router, station string, up bool) { + v := 0.0 + if up { + v = 1 + } + bmpStationUp.WithLabelValues(router, station).Set(v) +} + // BMPStateObserver is notified of each BMP station's session state every time // the keeper checks it. router is the BGPRouter key of the runtime streaming to // station; up reports whether its TCP session to the collector is established. diff --git a/internal/serviceroute/metrics.go b/internal/serviceroute/metrics.go index 2fbcf98aa..5975f77dd 100644 --- a/internal/serviceroute/metrics.go +++ b/internal/serviceroute/metrics.go @@ -8,6 +8,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) const metricsNamespace = "galactic_service_route" @@ -23,33 +24,33 @@ type Metrics struct { producers *prometheus.GaugeVec } -// NewMetrics creates the service-route metrics. Call MustRegister once during -// process startup. +// NewMetrics creates the service-route metrics on the instrumentation +// library's registry. func NewMetrics() *Metrics { - reconcileTime := prometheus.NewHistogram(prometheus.HistogramOpts{ + reconcileTime := metrics.NewHistogram(prometheus.HistogramOpts{ Namespace: metricsNamespace, Name: "reconcile_duration_seconds", Help: "Time spent reconciling a ServiceRoutePolicy.", Buckets: prometheus.DefBuckets, }) return &Metrics{ - reconciliations: prometheus.NewCounterVec(prometheus.CounterOpts{ + reconciliations: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "reconciliations_total", Help: "ServiceRoutePolicy reconciliations by outcome.", }, []string{"result"}), reconcileTime: reconcileTime, - operations: prometheus.NewCounterVec(prometheus.CounterOpts{ + operations: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "route_operations_total", Help: "Service route dataplane operations by operation and outcome.", }, []string{"operation", "result"}), - programmed: prometheus.NewGauge(prometheus.GaugeOpts{ + programmed: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "programmed_routes", Help: "Number of attachment-scoped eBPF service paths currently tracked by the controller.", }), - producers: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + producers: metrics.NewGaugeVec(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "producers", Help: "Producers of Spread ServiceEndpoints on this node, by health state. " + @@ -58,11 +59,6 @@ func NewMetrics() *Metrics { } } -// MustRegister registers all metrics owned by this package. -func (m *Metrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.reconciliations, m.reconcileTime, m.operations, m.programmed, m.producers) -} - func (m *Metrics) ObserveReconcile(result string, duration time.Duration) { if m == nil { return