From 8d84041fa1f0a3d4a601e92c39e4d389a461c1e8 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 09:56:00 -0400 Subject: [PATCH 1/2] refactor(edge): Create edge metrics with the instrumentation library The Edge foundation's failure counters and the core and node collectors were registered on controller-runtime's registry directly, so the instrumentation library's checks skipped them. The failure counters carried a component constant label naming the emitting role. The collection pipeline sets component on every series from the pod's labels, so the library refuses it. The label is now edge_role, with the same values: core from galactic-controller and node from galactic-edge. No shipped alert rule or rule test reads it. - diag.NewMetrics takes only the role and creates the counters with the library's constructors. The library's registry keeps a series across calls, so each call starts the role's counters over. - The state and node collectors register through metrics.MustRegister. - diagtest.New returns a Gatherer reading back only that role's counters from the library's registry, in place of a private registry. The scrape tests create the series run creates and lint them, and the controller's test includes the state collector over an empty cluster. Refs: #1149 Co-Authored-By: Claude Opus 5.5 --- cmd/galactic-controller/main.go | 8 ++-- cmd/galactic-controller/scrape_test.go | 18 ++++++-- cmd/galactic-edge/main.go | 8 ++-- cmd/galactic-edge/scrape_test.go | 11 +++-- docs/observability/edge.md | 8 ++-- internal/edge/agent/fixture_test.go | 2 +- .../attachment/reconciler_envtest_test.go | 4 +- internal/edge/diag/diag.go | 46 +++++++++++++------ internal/edge/diag/diagtest/diagtest.go | 41 +++++++++++++++-- internal/edge/diag/testdata/recorder.prom | 6 +-- internal/instrumentation/adoption_test.go | 3 -- internal/instrumentation/lint_test.go | 1 + 12 files changed, 109 insertions(+), 47 deletions(-) diff --git a/cmd/galactic-controller/main.go b/cmd/galactic-controller/main.go index edab8c994..567d78e96 100644 --- a/cmd/galactic-controller/main.go +++ b/cmd/galactic-controller/main.go @@ -20,6 +20,7 @@ import ( nadv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1" "github.com/spf13/cobra" + "go.miloapis.com/instrumentation/metrics" _ "golang.org/x/crypto/x509roots/fallback" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" @@ -28,7 +29,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/healthz" - ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" ctrlwebhook "sigs.k8s.io/controller-runtime/pkg/webhook" @@ -177,11 +177,9 @@ func run(parent context.Context, o *options) error { if o.edge { rec := &edgediag.Recorder{ Events: mgr.GetEventRecorder("galactic-controller"), - Metrics: edgediag.NewMetrics(ctrlmetrics.Registry, "core"), - } - if err := ctrlmetrics.Registry.Register(&edgediag.StateCollector{Reader: mgr.GetClient()}); err != nil { - return fmt.Errorf("register edge state metrics: %w", err) + Metrics: edgediag.NewMetrics(edgediag.RoleCore), } + metrics.MustRegister(&edgediag.StateCollector{Reader: mgr.GetClient()}) if err := edgeattachment.Setup(mgr, &edgeattachment.Reconciler{ Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), Authority: admission.NewAuthority(o.edgeMaxSkew), MaxSkew: o.edgeMaxSkew, Diag: rec, diff --git a/cmd/galactic-controller/scrape_test.go b/cmd/galactic-controller/scrape_test.go index 557990fa6..d6326b509 100644 --- a/cmd/galactic-controller/scrape_test.go +++ b/cmd/galactic-controller/scrape_test.go @@ -9,11 +9,23 @@ import ( "go.miloapis.com/instrumentation/instrumenttest" "go.miloapis.com/instrumentation/metrics" + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + edgediag "go.datum.net/galactic/internal/edge/diag" ) -// 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 what run adds with +// --edge: the failure counters and the state collector, here reading an +// empty cluster. It lints them too. func TestMetricsScrape(t *testing.T) { + scheme := runtime.NewScheme() + utilruntime.Must(galacticv1alpha1.AddToScheme(scheme)) + edgediag.NewMetrics(edgediag.RoleCore) + metrics.MustRegister(&edgediag.StateCollector{Reader: fake.NewClientBuilder().WithScheme(scheme).Build()}) instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/cmd/galactic-edge/main.go b/cmd/galactic-edge/main.go index f0e7802c1..3b4949b8b 100644 --- a/cmd/galactic-edge/main.go +++ b/cmd/galactic-edge/main.go @@ -25,6 +25,7 @@ import ( "time" "github.com/spf13/cobra" + "go.miloapis.com/instrumentation/metrics" _ "golang.org/x/crypto/x509roots/fallback" coordinationv1 "k8s.io/api/coordination/v1" "k8s.io/apimachinery/pkg/runtime" @@ -32,7 +33,6 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/healthz" - ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" @@ -174,12 +174,10 @@ func run(parent context.Context, o *options) error { BootID: strings.TrimSpace(string(bootID)), Diag: &diag.Recorder{ Events: mgr.GetEventRecorder("galactic-edge"), - Metrics: diag.NewMetrics(ctrlmetrics.Registry, "node"), + Metrics: diag.NewMetrics(diag.RoleNode), }, } - if err := ctrlmetrics.Registry.Register(agent.Collector{Agent: a}); err != nil { - return fmt.Errorf("register edge node metrics: %w", err) - } + metrics.MustRegister(agent.Collector{Agent: a}) if err := a.SetupWithManager(mgr); err != nil { return err } diff --git a/cmd/galactic-edge/scrape_test.go b/cmd/galactic-edge/scrape_test.go index 557990fa6..15936dbde 100644 --- a/cmd/galactic-edge/scrape_test.go +++ b/cmd/galactic-edge/scrape_test.go @@ -9,11 +9,16 @@ import ( "go.miloapis.com/instrumentation/instrumenttest" "go.miloapis.com/instrumentation/metrics" + + "go.datum.net/galactic/internal/edge/diag" ) -// 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 failure counters run +// creates, and lints them. The node collector reads the agent's pinned gate +// maps, so it is left out. func TestMetricsScrape(t *testing.T) { + diag.NewMetrics(diag.RoleNode) instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/docs/observability/edge.md b/docs/observability/edge.md index 649de9e52..4358e54fb 100644 --- a/docs/observability/edge.md +++ b/docs/observability/edge.md @@ -19,9 +19,9 @@ objects behind a series with the Events and `kubectl` queries in | `galactic_edge_foundation_routes` | gauge | core | `provider`, `state`, `reason` | Routes by claim state, and the condition reason holding them | | `galactic_edge_foundation_services` | gauge | core | `provider`, `policy`, `reason` | Services whose traffic policy is `Resolved` or `Unresolved`, with the reason when unresolved | | `galactic_edge_foundation_state_collect_errors` | gauge | core | none | Kinds the last scrape could not list and left out | -| `galactic_edge_foundation_failures_total` | counter | both | `component`, `stage`, `reason` | Transitions into a failed stage, counted once per transition, not per retry. Each also records an Event | -| `galactic_edge_foundation_gate_closures_total` | counter | node | `component`, `cause` | Open forwarding gates the agent closed, by cause. Each also records an Event on the route | -| `galactic_edge_foundation_cleanup_failures_total` | counter | node | `component` | Host state releases and gate sweeps that failed and are retried | +| `galactic_edge_foundation_failures_total` | counter | both | `edge_role`, `stage`, `reason` | Transitions into a failed stage, counted once per transition, not per retry. Each also records an Event | +| `galactic_edge_foundation_gate_closures_total` | counter | node | `edge_role`, `cause` | Open forwarding gates the agent closed, by cause. Each also records an Event on the route | +| `galactic_edge_foundation_cleanup_failures_total` | counter | node | `edge_role` | Host state releases and gate sweeps that failed and are retried | | `galactic_edge_foundation_links` | gauge | node | none | Host links registered with the node's forwarding gate | | `galactic_edge_foundation_gates` | gauge | node | `state` (`open`, `expired`, `closed`) | Gates on the node. `expired` passed its deadline before the agent closed it | | `galactic_edge_foundation_gate_drops_total` | counter | node | `check` (`ingress`, `egress`, `deliver`) | Packets dropped on an edge link because no open gate covered the address | @@ -34,6 +34,8 @@ objects behind a series with the Events and `kubectl` queries in `NotReady` for `Ready`, whose own reason the provider writes. - Route `state`: `Unclaimed`, `Pending`, `Accepted` (with the `Published` condition's reason), `Published`, `Revoked` or `Released`. +- `edge_role`: `core` from `galactic-controller`, `node` from + `galactic-edge`. - `stage`: `Admission`, `Allocation`, `Programming`, `Policy`, `Route`. - `cause`: `Expired` (no renewal extended the gate), `Released`, `Revoked`, `InstanceGone`, `AuthorityEnded`, `GrantCeiling`, diff --git a/internal/edge/agent/fixture_test.go b/internal/edge/agent/fixture_test.go index 99d9f1249..a50590dc6 100644 --- a/internal/edge/agent/fixture_test.go +++ b/internal/edge/agent/fixture_test.go @@ -348,7 +348,7 @@ type fixture struct { // metrics. diag *diag.Recorder events *diagtest.Recorder - metrics *prometheus.Registry + metrics prometheus.Gatherer } func newFixture(t *testing.T) *fixture { diff --git a/internal/edge/attachment/reconciler_envtest_test.go b/internal/edge/attachment/reconciler_envtest_test.go index adec5391a..6644753f1 100644 --- a/internal/edge/attachment/reconciler_envtest_test.go +++ b/internal/edge/attachment/reconciler_envtest_test.go @@ -64,7 +64,7 @@ type fixture struct { vpc *cloudv1alpha1.VPC // events and metrics are what the controller's diagnostics recorded. events *diagtest.Recorder - metrics *prometheus.Registry + metrics prometheus.Gatherer } func startFixture(t *testing.T) *fixture { @@ -675,7 +675,7 @@ func expectCorrelation(t *testing.T, e diagtest.Event, want map[string]string) { } } -func expectFailures(t *testing.T, reg *prometheus.Registry, stage, reason string, want float64) { +func expectFailures(t *testing.T, reg prometheus.Gatherer, stage, reason string, want float64) { t.Helper() families, err := reg.Gather() if err != nil { diff --git a/internal/edge/diag/diag.go b/internal/edge/diag/diag.go index 926e98e69..2974ffac4 100644 --- a/internal/edge/diag/diag.go +++ b/internal/edge/diag/diag.go @@ -23,6 +23,7 @@ import ( "strings" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -179,37 +180,54 @@ func Note(message string, c Correlation) string { return message + correlationSeparator + corr } -// Metrics are the foundation's failure counters. Each process registers its -// own. +// LabelRole is the constant label naming the role of the process emitting +// the failure counters: RoleCore or RoleNode. +const LabelRole = "edge_role" + +// The process roles LabelRole names. +const ( + // RoleCore is galactic-controller's Edge controllers. + RoleCore = "core" + // RoleNode is the galactic-edge node agent. + RoleNode = "node" +) + +// Metrics are the foundation's failure counters. type Metrics struct { failures *prometheus.CounterVec gateClosures *prometheus.CounterVec cleanup prometheus.Counter } -// NewMetrics registers the counters with reg. component is the emitting -// process's role, core or node, and becomes a constant label. -func NewMetrics(reg prometheus.Registerer, component string) *Metrics { - labels := prometheus.Labels{"component": component} +// NewMetrics creates the counters on the instrumentation library's registry. +// role is the emitting process's role, RoleCore or RoleNode, and becomes the +// LabelRole constant label. The registry keeps role's series across calls, so +// each call starts them over. +func NewMetrics(role string) *Metrics { + labels := prometheus.Labels{LabelRole: role} + // A vector with no labels, so it can be reset like the others. + cleanup := metrics.NewCounterVec(prometheus.CounterOpts{ + Name: "galactic_edge_foundation_cleanup_failures_total", + Help: "Host state releases or gate sweeps that failed and are retried on the next pass.", + ConstLabels: labels, + }, nil) m := &Metrics{ - failures: prometheus.NewCounterVec(prometheus.CounterOpts{ + failures: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "galactic_edge_foundation_failures_total", Help: "Transitions of an attachment, route or service into a failed lifecycle stage, by stage and " + "condition reason. Counted once per transition, not per retry.", ConstLabels: labels, }, []string{"stage", labelReason}), - gateClosures: prometheus.NewCounterVec(prometheus.CounterOpts{ + gateClosures: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "galactic_edge_foundation_gate_closures_total", Help: "Forwarding gates the node agent closed while they were open, by cause.", ConstLabels: labels, }, []string{"cause"}), - cleanup: prometheus.NewCounter(prometheus.CounterOpts{ - Name: "galactic_edge_foundation_cleanup_failures_total", - Help: "Host state releases or gate sweeps that failed and are retried on the next pass.", - ConstLabels: labels, - }), } - reg.MustRegister(m.failures, m.gateClosures, m.cleanup) + m.failures.Reset() + m.gateClosures.Reset() + cleanup.Reset() + m.cleanup = cleanup.WithLabelValues() return m } diff --git a/internal/edge/diag/diagtest/diagtest.go b/internal/edge/diag/diagtest/diagtest.go index 4b5ee8562..eb003ec3b 100644 --- a/internal/edge/diag/diagtest/diagtest.go +++ b/internal/edge/diag/diagtest/diagtest.go @@ -8,12 +8,15 @@ package diagtest import ( "fmt" + "slices" "strings" "sync" "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" + ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" "go.datum.net/galactic/internal/edge/diag" ) @@ -78,10 +81,38 @@ func (r *Recorder) Find(action diag.Stage, reason string) []Event { return out } -// New returns a diag.Recorder recording into a new Recorder and counting -// into a new registry. -func New(component string) (*diag.Recorder, *Recorder, *prometheus.Registry) { +// New returns a diag.Recorder for role recording into a new Recorder and +// counting from zero, and a Gatherer reading back only those counts. +func New(role string) (*diag.Recorder, *Recorder, prometheus.Gatherer) { events := &Recorder{} - reg := prometheus.NewRegistry() - return &diag.Recorder{Events: events, Metrics: diag.NewMetrics(reg, component)}, events, reg + rec := &diag.Recorder{Events: events, Metrics: diag.NewMetrics(role)} + return rec, events, prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) { + families, err := ctrlmetrics.Registry.Gather() + var out []*dto.MetricFamily + for _, f := range families { + if !slices.Contains(foundationCounters, f.GetName()) { + continue + } + var mine []*dto.Metric + for _, m := range f.GetMetric() { + if slices.ContainsFunc(m.GetLabel(), func(l *dto.LabelPair) bool { + return l.GetName() == diag.LabelRole && l.GetValue() == role + }) { + mine = append(mine, m) + } + } + if len(mine) > 0 { + f.Metric = mine + out = append(out, f) + } + } + return out, err + }) +} + +// foundationCounters are the series diag.Metrics exports. +var foundationCounters = []string{ + "galactic_edge_foundation_failures_total", + "galactic_edge_foundation_gate_closures_total", + "galactic_edge_foundation_cleanup_failures_total", } diff --git a/internal/edge/diag/testdata/recorder.prom b/internal/edge/diag/testdata/recorder.prom index a749629a3..86ffc3897 100644 --- a/internal/edge/diag/testdata/recorder.prom +++ b/internal/edge/diag/testdata/recorder.prom @@ -1,9 +1,9 @@ # HELP galactic_edge_foundation_failures_total Transitions of an attachment, route or service into a failed lifecycle stage, by stage and condition reason. Counted once per transition, not per retry. # TYPE galactic_edge_foundation_failures_total counter -galactic_edge_foundation_failures_total{component="core",reason="UnknownProvider",stage="Admission"} 1 +galactic_edge_foundation_failures_total{edge_role="core",reason="UnknownProvider",stage="Admission"} 1 # HELP galactic_edge_foundation_gate_closures_total Forwarding gates the node agent closed while they were open, by cause. # TYPE galactic_edge_foundation_gate_closures_total counter -galactic_edge_foundation_gate_closures_total{cause="Expired",component="core"} 1 +galactic_edge_foundation_gate_closures_total{cause="Expired",edge_role="core"} 1 # HELP galactic_edge_foundation_cleanup_failures_total Host state releases or gate sweeps that failed and are retried on the next pass. # TYPE galactic_edge_foundation_cleanup_failures_total counter -galactic_edge_foundation_cleanup_failures_total{component="core"} 1 +galactic_edge_foundation_cleanup_failures_total{edge_role="core"} 1 diff --git a/internal/instrumentation/adoption_test.go b/internal/instrumentation/adoption_test.go index 1382b6c03..c7433beb1 100644 --- a/internal/instrumentation/adoption_test.go +++ b/internal/instrumentation/adoption_test.go @@ -31,11 +31,8 @@ var pending = []string{ // #1149: serve controller-runtime's registry through library metrics. "cmd/fabric-api", "cmd/fabric-router-controller", - "cmd/galactic-controller", - "cmd/galactic-edge", // #1149: create metrics with the library's constructors instead of a // registry parameter or a private registry. - "internal/edge/diag", "internal/fabric/gateway", "internal/fabric/node", "internal/fabricconfig", diff --git a/internal/instrumentation/lint_test.go b/internal/instrumentation/lint_test.go index 18cafdfd3..247650195 100644 --- a/internal/instrumentation/lint_test.go +++ b/internal/instrumentation/lint_test.go @@ -20,6 +20,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/gateway" _ "go.datum.net/galactic/internal/ingresssidecar" _ "go.datum.net/galactic/internal/plumbing/ebpf/metrics" From 99f7136bf510054f406a889d0a87e1bb0b0bb954 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Wed, 28 Oct 2026 10:13:59 -0400 Subject: [PATCH 2/2] test(controller): Register the scrape test's collector once per process The Edge 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-controller/scrape_test.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/cmd/galactic-controller/scrape_test.go b/cmd/galactic-controller/scrape_test.go index d6326b509..6530091ff 100644 --- a/cmd/galactic-controller/scrape_test.go +++ b/cmd/galactic-controller/scrape_test.go @@ -5,6 +5,7 @@ package main import ( + "sync" "testing" "go.miloapis.com/instrumentation/instrumenttest" @@ -17,15 +18,21 @@ import ( edgediag "go.datum.net/galactic/internal/edge/diag" ) +// 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 what run adds with // --edge: the failure counters and the state collector, here reading an // empty cluster. It lints them too. func TestMetricsScrape(t *testing.T) { - scheme := runtime.NewScheme() - utilruntime.Must(galacticv1alpha1.AddToScheme(scheme)) - edgediag.NewMetrics(edgediag.RoleCore) - metrics.MustRegister(&edgediag.StateCollector{Reader: fake.NewClientBuilder().WithScheme(scheme).Build()}) + startup.Do(func() { + scheme := runtime.NewScheme() + utilruntime.Must(galacticv1alpha1.AddToScheme(scheme)) + edgediag.NewMetrics(edgediag.RoleCore) + metrics.MustRegister(&edgediag.StateCollector{Reader: fake.NewClientBuilder().WithScheme(scheme).Build()}) + }) instrumenttest.AssertScrapes(t, metrics.Handler()) instrumenttest.Lint(t) }