diff --git a/cmd/galactic-vrf/root.go b/cmd/galactic-vrf/root.go index 994b920e1..c690ab957 100644 --- a/cmd/galactic-vrf/root.go +++ b/cmd/galactic-vrf/root.go @@ -16,7 +16,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" bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" @@ -34,6 +33,37 @@ const ( Find more information at: https://www.datum.net/docs` ) +// sidecarMetrics are the sidecar's metrics, all on the instrumentation +// library's registry. +type sidecarMetrics struct { + store *ingresssidecar.Metrics + lifecycle *ingresssidecar.LifecycleMetrics + convergence *ingresssidecar.ConvergenceMetrics + inputs *ingresssidecar.InputMetrics + datapath *ingresssidecar.DatapathMetrics + nodeSource *ingresssidecar.NodeSourceMetrics + gateway *ingresssidecar.GatewayMetrics +} + +// newSidecarMetrics creates every metric the sidecar serves, configured from +// cfg, and registers the collectors among them. runCmd calls it once. +func newSidecarMetrics(cfg *config.VRFConfig) sidecarMetrics { + m := sidecarMetrics{ + store: ingresssidecar.NewMetrics(), + lifecycle: ingresssidecar.NewLifecycleMetrics(cfg.SweepInterval, cfg.TeardownGracePeriod), + convergence: ingresssidecar.NewConvergenceMetrics(), + inputs: ingresssidecar.NewInputMetrics(), + datapath: ingresssidecar.NewDatapathMetrics(), + nodeSource: ingresssidecar.NewNodeSourceMetrics(), + gateway: ingresssidecar.NewGatewayMetrics(cfg.NodeName != "", + cfg.NodeName != "" && cfg.GatewayPrefix != ""), + } + m.lifecycle.MustRegister() + m.datapath.MustRegister() + m.nodeSource.MustRegister() + return m +} + // runCmd is the application startup: it registers the ingress sidecar's // reconciler against a cluster-scoped EndpointSlice watch, then seeds the store // from live API state and runs its startup inventory and periodic sweep. @@ -63,25 +93,14 @@ func runCmd(cfg *config.VRFConfig) error { // Pre-flight RBAC check. checkWatchPermissions(mgr) - metrics := ingresssidecar.NewMetrics() - metrics.MustRegister(ctrlmetrics.Registry) - lifecycle := ingresssidecar.NewLifecycleMetrics(cfg.SweepInterval, cfg.TeardownGracePeriod) - lifecycle.MustRegister(ctrlmetrics.Registry) + m := newSidecarMetrics(cfg) backend := ingresssidecar.NewKernelBackend() - store := ingresssidecar.NewStore(backend, cfg.TeardownGracePeriod, metrics) - convergence := ingresssidecar.NewConvergenceMetrics() - convergence.MustRegister(ctrlmetrics.Registry) - store.SetConvergenceMetrics(convergence) - inputs := ingresssidecar.NewInputMetrics() - inputs.MustRegister(ctrlmetrics.Registry) - store.SetInputMetrics(inputs) - datapath := ingresssidecar.NewDatapathMetrics() - datapath.MustRegister(ctrlmetrics.Registry) - store.SetDatapathMetrics(datapath) - nodeSourceMetrics := ingresssidecar.NewNodeSourceMetrics() - nodeSourceMetrics.MustRegister(ctrlmetrics.Registry) - store.SetNodeSourceMetrics(nodeSourceMetrics) + store := ingresssidecar.NewStore(backend, cfg.TeardownGracePeriod, m.store) + store.SetConvergenceMetrics(m.convergence) + store.SetInputMetrics(m.inputs) + store.SetDatapathMetrics(m.datapath) + store.SetNodeSourceMetrics(m.nodeSource) // Return-path gateway advertisement is opt-in on the node name alone, // and leaving it unset is fully inert. The cached client is fine here: @@ -127,9 +146,7 @@ func runCmd(cfg *config.VRFConfig) error { "return-path gateway advertisement publishing is disabled", config.EnvVRFNodeName) } - gateway := ingresssidecar.NewGatewayMetrics(cfg.NodeName != "", cfg.NodeName != "" && cfg.GatewayPrefix != "") - gateway.MustRegister(ctrlmetrics.Registry) - store.SetGatewayMetrics(gateway) + store.SetGatewayMetrics(m.gateway) if err := (&ingresssidecar.Reconciler{Store: store}).SetupWithManager(mgr); err != nil { return fmt.Errorf("setup EndpointSlice controller: %w", err) @@ -145,7 +162,7 @@ func runCmd(cfg *config.VRFConfig) error { // controller's own reconciles have drained the workqueue that list // fed, so on a busy node at boot the two race. Seeding uses the // manager's uncached reader, which depends on neither. - go ingresssidecar.RunStartup(ctx, mgr.GetAPIReader(), store, cfg.SweepInterval, lifecycle) + go ingresssidecar.RunStartup(ctx, mgr.GetAPIReader(), store, cfg.SweepInterval, m.lifecycle) if err := mgr.Start(ctx); err != nil { return fmt.Errorf("manager exited: %w", err) diff --git a/cmd/galactic-vrf/scrape_test.go b/cmd/galactic-vrf/scrape_test.go index 557990fa6..7e6948fae 100644 --- a/cmd/galactic-vrf/scrape_test.go +++ b/cmd/galactic-vrf/scrape_test.go @@ -5,15 +5,28 @@ package main import ( + "sync" "testing" "go.miloapis.com/instrumentation/instrumenttest" "go.miloapis.com/instrumentation/metrics" + + "go.datum.net/galactic/internal/config" ) -// 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. +// startup creates the series once per test process, as runCmd 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 newSidecarMetrics has created +// every series the sidecar serves, and lints them. func TestMetricsScrape(t *testing.T) { + startup.Do(func() { + cfg := config.NewVRFConfig() + cfg.NodeName = "node-a" + newSidecarMetrics(cfg) + }) instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/internal/ingresssidecar/convergence_metrics.go b/internal/ingresssidecar/convergence_metrics.go index 74134e971..5bcbfd889 100644 --- a/internal/ingresssidecar/convergence_metrics.go +++ b/internal/ingresssidecar/convergence_metrics.go @@ -8,6 +8,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) // Backend operations, as operations_total labels them. @@ -52,41 +53,47 @@ type ConvergenceMetrics struct { operations *prometheus.CounterVec } -// NewConvergenceMetrics builds unregistered convergence metrics, every series -// at zero. +// NewConvergenceMetrics creates convergence metrics on the instrumentation +// library's registry, every series at zero. The registry keeps the series +// across calls, so each call sets them back to zero. func NewConvergenceMetrics() *ConvergenceMetrics { m := &ConvergenceMetrics{ - desired: prometheus.NewGauge(prometheus.GaugeOpts{ + desired: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "route_claims_desired", Help: "Route claims, one per selected and ready EndpointSlice, that this sidecar wants installed, " + "including any whose install failed.", }), - applyPending: prometheus.NewGauge(prometheus.GaugeOpts{ + applyPending: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "route_claims_apply_pending", Help: "Desired route claims whose latest update is not applied yet, whether or not an earlier " + "version of the route is installed.", }), - oldest: prometheus.NewGauge(prometheus.GaugeOpts{ + oldest: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "route_apply_oldest_pending_timestamp_seconds", Help: "Unix time the longest-pending desired claim stopped being applied; 0 when none is pending. " + "Retries and newer updates of a pending claim do not reset it.", }), - overdue: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + overdue: metrics.NewGaugeVec(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "teardown_overdue", Help: "Routes or VRFs, by resource, whose own grace period has run out but whose removal has not " + "completed, as of the last sweep.", }, []string{"resource"}), - operations: prometheus.NewCounterVec(prometheus.CounterOpts{ + operations: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "operations_total", Help: "Completed backend operations, by operation (ensure_vrf, ensure_route, remove_vrf, " + "remove_route, reapply_vrf, reapply_route) and result (success, error).", }, []string{"operation", resultLabel}), } + for _, g := range []prometheus.Gauge{m.desired, m.applyPending, m.oldest} { + g.Set(0) + } + m.overdue.Reset() + m.operations.Reset() for _, r := range teardownResources { m.overdue.WithLabelValues(r) } @@ -98,12 +105,6 @@ func NewConvergenceMetrics() *ConvergenceMetrics { return m } -// MustRegister registers every convergence metric against reg, panicking on a -// duplicate. Call it once per process. -func (m *ConvergenceMetrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.desired, m.applyPending, m.oldest, m.overdue, m.operations) -} - // operation records one completed backend operation. func (m *ConvergenceMetrics) operation(op string, err error) { if m == nil { diff --git a/internal/ingresssidecar/convergence_metrics_test.go b/internal/ingresssidecar/convergence_metrics_test.go index 82227915f..01baa1bf6 100644 --- a/internal/ingresssidecar/convergence_metrics_test.go +++ b/internal/ingresssidecar/convergence_metrics_test.go @@ -61,9 +61,9 @@ func newConvergenceStore(t *testing.T, grace time.Duration) *convergenceStore { t.Helper() reg := prometheus.NewPedanticRegistry() m := NewConvergenceMetrics() - m.MustRegister(reg) + reg.MustRegister(m.collectors()...) legacy := NewMetrics() - legacy.MustRegister(reg) + reg.MustRegister(legacy.collectors()...) backend := newFakeBackend() store := NewStore(backend, grace, legacy) clock := &stepClock{t: t0} @@ -134,7 +134,7 @@ func route(t *testing.T, prefix, sid string) *DesiredRoute { func TestConvergenceMetricsInitialState(t *testing.T) { reg := prometheus.NewPedanticRegistry() - NewConvergenceMetrics().MustRegister(reg) + reg.MustRegister(NewConvergenceMetrics().collectors()...) families, err := reg.Gather() if err != nil { t.Fatal(err) diff --git a/internal/ingresssidecar/datapath_metrics.go b/internal/ingresssidecar/datapath_metrics.go index c4599b8c9..958806fb4 100644 --- a/internal/ingresssidecar/datapath_metrics.go +++ b/internal/ingresssidecar/datapath_metrics.go @@ -9,6 +9,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) // Datapath checks each sweep makes: reading the shared eBPF datapath's @@ -72,35 +73,41 @@ type DatapathMetrics struct { now func() time.Time } -// NewDatapathMetrics builds unregistered datapath metrics, every check's -// status unknown. +// NewDatapathMetrics creates datapath metrics on the instrumentation +// library's registry, every check's status unknown. The registry keeps the +// series across calls, so each call starts them over. MustRegister exports +// the check statuses. func NewDatapathMetrics() *DatapathMetrics { m := &DatapathMetrics{ - checks: prometheus.NewCounterVec(prometheus.CounterOpts{ + checks: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "datapath_checks_total", Help: "Completed datapath checks, by check (generation, registration_rows) and result (ok, " + "missing for registration_rows, error when the read failed).", }, []string{checkLabel, resultLabel}), status: newCheckStatusCollector(), - lastCompleted: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + lastCompleted: metrics.NewGaugeVec(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "datapath_check_last_completed_timestamp_seconds", Help: "Unix time each check last completed, whatever its result; 0 before the first.", }, []string{checkLabel}), - reapplies: prometheus.NewCounterVec(prometheus.CounterOpts{ + reapplies: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "datapath_reapply_total", Help: "Reapply passes over every tracked VRF and route, by reason (generation_changed, " + "rows_missing, retry of a failed pass) and result (success when every reapply succeeded).", }, []string{"reason", resultLabel}), - pending: prometheus.NewGauge(prometheus.GaugeOpts{ + pending: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "datapath_reapply_pending", Help: "1 while a reapply pass left something unapplied, until a later pass succeeds.", }), now: time.Now, } + m.checks.Reset() + m.lastCompleted.Reset() + m.reapplies.Reset() + m.pending.Set(0) for _, check := range datapathChecks { m.lastCompleted.WithLabelValues(check) for _, result := range checkResults[check] { @@ -115,10 +122,10 @@ func NewDatapathMetrics() *DatapathMetrics { return m } -// MustRegister registers every datapath metric against reg, panicking on a -// duplicate. Call it once per process. -func (m *DatapathMetrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.checks, m.status, m.lastCompleted, m.reapplies, m.pending) +// MustRegister registers m's check status collector on the instrumentation +// library's registry. Call it once per process. +func (m *DatapathMetrics) MustRegister() { + metrics.MustRegister(m.status) } // checked records a completed check of check with result. The counter, diff --git a/internal/ingresssidecar/datapath_metrics_test.go b/internal/ingresssidecar/datapath_metrics_test.go index 6083d7ac9..6738616bf 100644 --- a/internal/ingresssidecar/datapath_metrics_test.go +++ b/internal/ingresssidecar/datapath_metrics_test.go @@ -37,7 +37,7 @@ func newDatapathStore(t *testing.T) *datapathStore { m := NewDatapathMetrics() m.now = func() time.Time { return time.Unix(testCheckTime, 0) } reg := prometheus.NewPedanticRegistry() - m.MustRegister(reg) + reg.MustRegister(m.collectors()...) backend := newFakeBackend() backend.generation = testGenLoaded store := NewStore(backend, time.Hour, nil) diff --git a/internal/ingresssidecar/gateway_metrics.go b/internal/ingresssidecar/gateway_metrics.go index f2e051a0e..1785e3d22 100644 --- a/internal/ingresssidecar/gateway_metrics.go +++ b/internal/ingresssidecar/gateway_metrics.go @@ -8,6 +8,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) // A desired VRF's return-path gateway state, as gateway_vrfs counts them. @@ -55,34 +56,36 @@ type GatewayMetrics struct { now func() time.Time } -// NewGatewayMetrics builds unregistered gateway metrics for a sidecar whose -// gateway publication and gateway address assignment are enabled as given. +// NewGatewayMetrics creates gateway metrics on the instrumentation library's +// registry for a sidecar whose gateway publication and gateway address +// assignment are enabled as given. The registry keeps the series across +// calls, so each call starts them over. func NewGatewayMetrics(publicationEnabled, addressAssignmentEnabled bool) *GatewayMetrics { m := &GatewayMetrics{ - publicationEnabled: prometheus.NewGauge(prometheus.GaugeOpts{ + publicationEnabled: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "gateway_publication_enabled", Help: "1 when this sidecar publishes a return-path gateway advertisement per VPC.", }), - addressAssignmentEnabled: prometheus.NewGauge(prometheus.GaugeOpts{ + addressAssignmentEnabled: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "gateway_address_assignment_enabled", Help: "1 when this sidecar assigns each VPC's gateway address itself, from its gateway prefix.", }), - vrfs: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + vrfs: metrics.NewGaugeVec(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "gateway_vrfs", Help: "Installed, non-draining VRFs by return-path gateway state: awaiting_address, " + "awaiting_publication, or published (locally, not proof any peer has the route). " + "All zero while publication is disabled.", }, []string{"state"}), - oldest: prometheus.NewGauge(prometheus.GaugeOpts{ + oldest: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "gateway_oldest_pending_timestamp_seconds", Help: "Unix time the longest-unpublished desired VRF started waiting; 0 when none is waiting. " + "Retries do not reset it.", }), - operations: prometheus.NewCounterVec(prometheus.CounterOpts{ + operations: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "gateway_operations_total", Help: "Gateway operations by operation and result: resolve (success, error, not_provisioned), " + @@ -90,6 +93,9 @@ func NewGatewayMetrics(publicationEnabled, addressAssignmentEnabled bool) *Gatew }, []string{"operation", resultLabel}), now: time.Now, } + m.oldest.Set(0) + m.vrfs.Reset() + m.operations.Reset() m.publicationEnabled.Set(boolGauge(publicationEnabled)) m.addressAssignmentEnabled.Set(boolGauge(addressAssignmentEnabled)) for _, s := range gatewayStates { @@ -103,12 +109,6 @@ func NewGatewayMetrics(publicationEnabled, addressAssignmentEnabled bool) *Gatew return m } -// MustRegister registers every gateway metric against reg, panicking on a -// duplicate. Call it once per process. -func (m *GatewayMetrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.publicationEnabled, m.addressAssignmentEnabled, m.vrfs, m.oldest, m.operations) -} - func (m *GatewayMetrics) operation(op, result string) { if m != nil { m.operations.WithLabelValues(op, result).Inc() diff --git a/internal/ingresssidecar/gateway_metrics_test.go b/internal/ingresssidecar/gateway_metrics_test.go index a74891144..29d7d507e 100644 --- a/internal/ingresssidecar/gateway_metrics_test.go +++ b/internal/ingresssidecar/gateway_metrics_test.go @@ -53,7 +53,7 @@ func newGatewayStore(t *testing.T, enabled bool) *gatewayStore { defer g.mu.Unlock() return g.now } - m.MustRegister(g.reg) + g.reg.MustRegister(m.collectors()...) g.Store = NewStore(g.backend, time.Minute, nil) if enabled { g.SetGatewayPublisher(g.pub, g.resolver) @@ -263,7 +263,7 @@ func TestSetGatewayMetricsCountsExistingVRFs(t *testing.T) { } m := NewGatewayMetrics(true, true) reg := prometheus.NewPedanticRegistry() - m.MustRegister(reg) + reg.MustRegister(m.collectors()...) store.SetGatewayMetrics(m) if v := testutil.ToFloat64(m.vrfs.WithLabelValues(GatewayAwaitingAddress)); v != 1 { t.Errorf("gateway_vrfs{state=awaiting_address} = %v, want the existing VRF counted", v) diff --git a/internal/ingresssidecar/input_metrics.go b/internal/ingresssidecar/input_metrics.go index e6e69cae7..ebaa698e8 100644 --- a/internal/ingresssidecar/input_metrics.go +++ b/internal/ingresssidecar/input_metrics.go @@ -8,6 +8,7 @@ import ( "sync" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" discoveryv1 "k8s.io/api/discovery/v1" ) @@ -77,16 +78,18 @@ type InputMetrics struct { watched map[string]struct{} } -// NewInputMetrics builds unregistered input metrics with no slices seen. +// NewInputMetrics creates input metrics on the instrumentation library's +// registry with no slices seen. The registry keeps the series across calls, +// so each call starts them over. func NewInputMetrics() *InputMetrics { m := &InputMetrics{ - slices: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + slices: metrics.NewGaugeVec(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "endpoint_slices", Help: "Selected EndpointSlices, by state: ready (parses into a route), waiting_sid (no SID " + "annotation yet) or invalid (cannot be parsed; any route it had is kept).", }, []string{"state"}), - evaluations: prometheus.NewCounterVec(prometheus.CounterOpts{ + evaluations: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "endpoint_slice_evaluations_total", Help: "EndpointSlice evaluations, by source (seed, watch) and result (ready, waiting_sid, " + @@ -96,6 +99,8 @@ func NewInputMetrics() *InputMetrics { state: map[string]string{}, counts: map[string]int{}, } + m.slices.Reset() + m.evaluations.Reset() for _, s := range inputStates { m.slices.WithLabelValues(s) } @@ -107,12 +112,6 @@ func NewInputMetrics() *InputMetrics { return m } -// MustRegister registers every input metric against reg, panicking on a -// duplicate. Call it once per process. -func (m *InputMetrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.slices, m.evaluations) -} - // beginSeed marks the start of a seed attempt. Call it before the seed lists // slices, so any watch observation from then on takes precedence. func (m *InputMetrics) beginSeed() { diff --git a/internal/ingresssidecar/input_metrics_test.go b/internal/ingresssidecar/input_metrics_test.go index ac423b795..866720683 100644 --- a/internal/ingresssidecar/input_metrics_test.go +++ b/internal/ingresssidecar/input_metrics_test.go @@ -33,7 +33,7 @@ func inputRegistry(t *testing.T) (*InputMetrics, *prometheus.Registry) { t.Helper() m := NewInputMetrics() reg := prometheus.NewPedanticRegistry() - m.MustRegister(reg) + reg.MustRegister(m.collectors()...) return m, reg } diff --git a/internal/ingresssidecar/lifecycle_metrics.go b/internal/ingresssidecar/lifecycle_metrics.go index 5e04d6a98..d8c347bea 100644 --- a/internal/ingresssidecar/lifecycle_metrics.go +++ b/internal/ingresssidecar/lifecycle_metrics.go @@ -9,6 +9,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" ) // Startup stages, in the order RunStartup runs them. @@ -66,68 +67,72 @@ type LifecycleMetrics struct { now func() time.Time } -// NewLifecycleMetrics builds unregistered lifecycle metrics for a sidecar that -// sweeps every interval and delays teardown by grace, with every startup -// stage pending and no sweep completed. +// NewLifecycleMetrics creates lifecycle metrics on the instrumentation +// library's registry for a sidecar that sweeps every interval and delays +// teardown by grace, with every startup stage pending and no sweep completed. +// The registry keeps the series across calls, so each call starts them over. +// MustRegister exports the stage statuses. func NewLifecycleMetrics(interval, grace time.Duration) *LifecycleMetrics { m := &LifecycleMetrics{ stageStatus: newStageCollector(), - attempts: prometheus.NewCounterVec(prometheus.CounterOpts{ + attempts: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "startup_attempts_total", Help: "Completed startup stage attempts, by stage and result (success, error).", }, []string{"stage", resultLabel}), - complete: prometheus.NewGauge(prometheus.GaugeOpts{ + complete: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "startup_complete", Help: "1 once the seed succeeded, inventory and prune were handled and the sweep started. " + "Startup procedure only: a failed inventory or prune still reports 1, and it says nothing " + "about routes or traffic.", }), - sweepLast: prometheus.NewGauge(prometheus.GaugeOpts{ + sweepLast: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "sweep_last_completed_timestamp_seconds", Help: "Unix time the last sweep finished, whatever its operations' results; 0 before the first.", }), - sweepDuration: prometheus.NewHistogram(prometheus.HistogramOpts{ + sweepDuration: newHistogram(prometheus.HistogramOpts{ Namespace: metricsNamespace, Name: "sweep_duration_seconds", Help: "Time each sweep took, including waiting for the store's lock. A sweep outlasting the " + "interval absorbs the ticks it missed rather than queueing them.", Buckets: sweepBucketsSec, }), - sweepInterval: prometheus.NewGauge(prometheus.GaugeOpts{ + sweepInterval: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "sweep_interval_seconds", Help: "Configured time between sweeps.", }), - grace: prometheus.NewGauge(prometheus.GaugeOpts{ + grace: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "teardown_grace_seconds", Help: "Configured teardown grace period, applied to a route and then to its VRF.", }), - prunedRows: prometheus.NewCounter(prometheus.CounterOpts{ + prunedRows: newCounter(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "pruned_rows_total", Help: "Shared eBPF map rows the startup prune removed, including those removed before it failed.", }), now: time.Now, } + m.attempts.Reset() for _, stage := range startupStages { for _, result := range attemptResults { m.attempts.WithLabelValues(stage, result) } } + m.complete.Set(0) + m.sweepLast.Set(0) m.sweepInterval.Set(interval.Seconds()) m.grace.Set(grace.Seconds()) return m } -// MustRegister registers every lifecycle metric against reg, panicking on a -// duplicate. Call it once per process. -func (m *LifecycleMetrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.stageStatus, m.attempts, m.complete, m.sweepLast, m.sweepDuration, - m.sweepInterval, m.grace, m.prunedRows) +// MustRegister registers m's stage status collector on the instrumentation +// library's registry. Call it once per process. +func (m *LifecycleMetrics) MustRegister() { + metrics.MustRegister(m.stageStatus) } // setStage makes status the one current status of stage. diff --git a/internal/ingresssidecar/lifecycle_metrics_test.go b/internal/ingresssidecar/lifecycle_metrics_test.go index b5bc9190c..c3e193582 100644 --- a/internal/ingresssidecar/lifecycle_metrics_test.go +++ b/internal/ingresssidecar/lifecycle_metrics_test.go @@ -75,7 +75,7 @@ func newLifecycleRegistry(t *testing.T) (*LifecycleMetrics, *prometheus.Registry t.Helper() m := NewLifecycleMetrics(5*time.Second, 30*time.Second) reg := prometheus.NewPedanticRegistry() - m.MustRegister(reg) + reg.MustRegister(m.collectors()...) return m, reg } @@ -428,7 +428,7 @@ func TestRunSweepsRecordsEverySweep(t *testing.T) { func TestScrapeDuringBlockedSweep(t *testing.T) { m, reg := newLifecycleRegistry(t) legacy := NewMetrics() - legacy.MustRegister(reg) + reg.MustRegister(legacy.collectors()...) store := NewStore(newFakeBackend(), time.Hour, legacy) const blocked = 100 * time.Millisecond diff --git a/internal/ingresssidecar/metrics.go b/internal/ingresssidecar/metrics.go index 820299531..a99a771ac 100644 --- a/internal/ingresssidecar/metrics.go +++ b/internal/ingresssidecar/metrics.go @@ -4,13 +4,16 @@ package ingresssidecar -import "github.com/prometheus/client_golang/prometheus" +import ( + "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" +) const metricsNamespace = "galactic_ingress_sidecar" // Metrics is this sidecar's Prometheus surface: active VRF and route counts, -// reconcile error rate and latency, and teardown queue depth. Build it once, -// register it once at startup, then pass it into the store. +// reconcile error rate and latency, and teardown queue depth. Build it once at +// startup, then pass it into the store. type Metrics struct { VRFActive prometheus.Gauge RouteActive prometheus.Gauge @@ -21,59 +24,73 @@ type Metrics struct { Reapplies prometheus.Counter } -// NewMetrics builds a fresh, unregistered Metrics. Call MustRegister once -// at process startup. +// NewMetrics creates Metrics on the instrumentation library's registry. +// The registry keeps the series across calls, so each call starts them over. func NewMetrics() *Metrics { - return &Metrics{ - VRFActive: prometheus.NewGauge(prometheus.GaugeOpts{ + m := &Metrics{ + VRFActive: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "vrf_active", Help: "Per-VPC VRF devices this sidecar tracks as installed, including those draining " + "through their teardown grace period. Store state, not a check of the kernel.", }), - RouteActive: prometheus.NewGauge(prometheus.GaugeOpts{ + RouteActive: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "route_active", Help: "Installed route claims, one per EndpointSlice, including those draining. Claims sharing " + "a prefix share one kernel route, so this can exceed the routes installed.", }), - VRFPending: prometheus.NewGauge(prometheus.GaugeOpts{ + VRFPending: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "vrf_teardown_pending", Help: "VRF devices past their last route as of the last sweep: those within their grace period " + "and those whose removal failed.", }), - RoutePending: prometheus.NewGauge(prometheus.GaugeOpts{ + RoutePending: metrics.NewGauge(prometheus.GaugeOpts{ Namespace: metricsNamespace, Name: "route_teardown_pending", Help: "Route claims whose EndpointSlice is gone as of the last sweep: those within their grace " + "period and those whose removal failed.", }), - ReconcileErrs: prometheus.NewCounterVec(prometheus.CounterOpts{ + ReconcileErrs: metrics.NewCounterVec(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "reconcile_errors_total", Help: "Backend errors, by kind (ensure_vrf, ensure_route, remove_vrf, remove_route, " + "reapply_vrf, reapply_route, prune_datapath).", }, []string{"kind"}), - ReconcileTime: prometheus.NewHistogram(prometheus.HistogramOpts{ + ReconcileTime: newHistogram(prometheus.HistogramOpts{ Namespace: metricsNamespace, Name: "reconcile_duration_seconds", Help: "Time each desired-state update took to apply, including waiting for the store's lock. " + "Does not cover sweeps.", Buckets: prometheus.DefBuckets, }), - Reapplies: prometheus.NewCounter(prometheus.CounterOpts{ + Reapplies: newCounter(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "reapply_total", Help: "Reapply passes over every tracked VRF and route: after the shared eBPF datapath was " + "reloaded, after this sidecar's rows went missing from it, and retries of a pass that failed.", }), } + for _, g := range []prometheus.Gauge{m.VRFActive, m.RouteActive, m.VRFPending, m.RoutePending} { + g.Set(0) + } + m.ReconcileErrs.Reset() + return m +} + +// newCounter creates a counter with no labels on the instrumentation +// library's registry, at zero even when an earlier call created it. The +// registry holds it as a vector, so each call can replace its one series. +func newCounter(opts prometheus.CounterOpts) prometheus.Counter { + v := metrics.NewCounterVec(opts, nil) + v.Reset() + return v.WithLabelValues() } -// MustRegister registers every metric this type owns against reg, panicking on -// a duplicate. Callers do this once per process, at startup. -func (m *Metrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.VRFActive, m.RouteActive, m.VRFPending, m.RoutePending, - m.ReconcileErrs, m.ReconcileTime, m.Reapplies) +// newHistogram is newCounter for a histogram. +func newHistogram(opts prometheus.HistogramOpts) prometheus.Histogram { + v := metrics.NewHistogramVec(opts, nil) + v.Reset() + return v.WithLabelValues().(prometheus.Histogram) } diff --git a/internal/ingresssidecar/metrics_registry_test.go b/internal/ingresssidecar/metrics_registry_test.go new file mode 100644 index 000000000..396790e7e --- /dev/null +++ b/internal/ingresssidecar/metrics_registry_test.go @@ -0,0 +1,41 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ingresssidecar + +import "github.com/prometheus/client_golang/prometheus" + +// The collectors methods below list every collector a metrics type exports, so +// a test can register them on its own registry and read them apart from the +// rest of the process. The library's registry holds the same collectors. + +func (m *Metrics) collectors() []prometheus.Collector { + return []prometheus.Collector{m.VRFActive, m.RouteActive, m.VRFPending, m.RoutePending, + m.ReconcileErrs, m.ReconcileTime, m.Reapplies} +} + +func (m *LifecycleMetrics) collectors() []prometheus.Collector { + return []prometheus.Collector{m.stageStatus, m.attempts, m.complete, m.sweepLast, m.sweepDuration, + m.sweepInterval, m.grace, m.prunedRows} +} + +func (m *ConvergenceMetrics) collectors() []prometheus.Collector { + return []prometheus.Collector{m.desired, m.applyPending, m.oldest, m.overdue, m.operations} +} + +func (m *InputMetrics) collectors() []prometheus.Collector { + return []prometheus.Collector{m.slices, m.evaluations} +} + +func (m *DatapathMetrics) collectors() []prometheus.Collector { + return []prometheus.Collector{m.checks, m.status, m.lastCompleted, m.reapplies, m.pending} +} + +func (m *NodeSourceMetrics) collectors() []prometheus.Collector { + return []prometheus.Collector{m.check, m.repairs} +} + +func (m *GatewayMetrics) collectors() []prometheus.Collector { + return []prometheus.Collector{m.publicationEnabled, m.addressAssignmentEnabled, m.vrfs, m.oldest, m.operations} +} diff --git a/internal/ingresssidecar/nodesource_metrics.go b/internal/ingresssidecar/nodesource_metrics.go index 95d221241..876112c33 100644 --- a/internal/ingresssidecar/nodesource_metrics.go +++ b/internal/ingresssidecar/nodesource_metrics.go @@ -13,6 +13,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/plumbing/ebpf/egressroutemap" ) @@ -147,8 +148,10 @@ func (c *nodeSourceCheckCollector) Collect(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric(c.at, prometheus.GaugeValue, at) } -// NewNodeSourceMetrics builds unregistered node source address metrics, with -// the status unknown. +// NewNodeSourceMetrics creates node source address metrics with the status +// unknown and no repairs. The repair count is on the instrumentation +// library's registry, which keeps it across calls, so each call starts it +// over; MustRegister exports the status. func NewNodeSourceMetrics() *NodeSourceMetrics { check := &nodeSourceCheckCollector{ status: prometheus.NewDesc( @@ -167,7 +170,7 @@ func NewNodeSourceMetrics() *NodeSourceMetrics { check.last.Store(&nodeSourceCheck{status: NodeSourceUnknown}) return &NodeSourceMetrics{ check: check, - repairs: prometheus.NewCounter(prometheus.CounterOpts{ + repairs: newCounter(prometheus.CounterOpts{ Namespace: metricsNamespace, Name: "node_source_address_repairs_total", Help: "Sweeps that found node_src_addr_table unset or holding another address and wrote this " + @@ -176,10 +179,10 @@ func NewNodeSourceMetrics() *NodeSourceMetrics { } } -// MustRegister registers every node source address metric against reg, -// panicking on a duplicate. Call it once per process. -func (m *NodeSourceMetrics) MustRegister(reg prometheus.Registerer) { - reg.MustRegister(m.check, m.repairs) +// MustRegister registers m's status collector on the instrumentation +// library's registry. Call it once per process. +func (m *NodeSourceMetrics) MustRegister() { + metrics.MustRegister(m.check) } // observe records one check at now. diff --git a/internal/ingresssidecar/nodesource_metrics_test.go b/internal/ingresssidecar/nodesource_metrics_test.go index 1cf49e349..8782a83fc 100644 --- a/internal/ingresssidecar/nodesource_metrics_test.go +++ b/internal/ingresssidecar/nodesource_metrics_test.go @@ -199,7 +199,7 @@ func TestSweepRestoresNodeSourceAddress(t *testing.T) { func TestNodeSourceMetricsSeries(t *testing.T) { reg := prometheus.NewPedanticRegistry() - NewNodeSourceMetrics().MustRegister(reg) + reg.MustRegister(NewNodeSourceMetrics().collectors()...) n, err := testutil.GatherAndCount(reg) if err != nil { t.Fatal(err) diff --git a/internal/instrumentation/adoption_test.go b/internal/instrumentation/adoption_test.go index 6f17c31c2..1382b6c03 100644 --- a/internal/instrumentation/adoption_test.go +++ b/internal/instrumentation/adoption_test.go @@ -33,14 +33,12 @@ var pending = []string{ "cmd/fabric-router-controller", "cmd/galactic-controller", "cmd/galactic-edge", - "cmd/galactic-vrf", // #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", - "internal/ingresssidecar", } // 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 97736c137..18cafdfd3 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/gateway" + _ "go.datum.net/galactic/internal/ingresssidecar" _ "go.datum.net/galactic/internal/plumbing/ebpf/metrics" _ "go.datum.net/galactic/internal/plumbing/ebpf/natattach" _ "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch"