diff --git a/cmd/fabric-api/gateway.go b/cmd/fabric-api/gateway.go index 7709c0809..278611248 100644 --- a/cmd/fabric-api/gateway.go +++ b/cmd/fabric-api/gateway.go @@ -29,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" fabricapi "go.datum.net/galactic/internal/fabric/api/v1alpha1" @@ -268,7 +267,7 @@ func runGateway(parent context.Context, o *gatewayOptions) error { } executor := gateway.NewExecutor(o.slots, o.expensiveSlots, o.queue) - metrics := gateway.NewMetrics(ctrlmetrics.Registry, func() float64 { return float64(executor.Depth()) }) + metrics := gateway.NewMetrics(func() float64 { return float64(executor.Depth()) }) var admission *gateway.Admission if o.aggregateBudgets { admission, err = gateway.NewAdmission(o.limits, &limit.Authority{ diff --git a/cmd/fabric-api/node.go b/cmd/fabric-api/node.go index d51469e90..f2721c954 100644 --- a/cmd/fabric-api/node.go +++ b/cmd/fabric-api/node.go @@ -17,6 +17,7 @@ import ( "time" "github.com/spf13/cobra" + instmetrics "go.miloapis.com/instrumentation/metrics" "google.golang.org/grpc" "google.golang.org/grpc/credentials" grpchealth "google.golang.org/grpc/health" @@ -250,7 +251,7 @@ func runNode(parent context.Context, o *nodeOptions) error { if metricsAddr == "" { metricsAddr = net.JoinHostPort(hostIP.String(), "9345") } - stopMetrics := serveMetrics(metricsAddr, metrics.Handler()) + stopMetrics := serveMetrics(metricsAddr, instmetrics.Handler()) defer stopMetrics() slog.Info("starting fabric-api node", "version", metadata.Version, "nodeName", o.nodeName, "site", o.site, @@ -318,12 +319,12 @@ func nodePermits(o *nodeOptions, creds *identity.Credentials, metrics *node.Metr func idleUnconfigured(parent context.Context, hostIP netip.Addr, o *nodeOptions) error { ctx, stop := signalContext(parent) defer stop() - metrics := node.NewMetrics() + node.NewMetrics() addr := o.metricsAddress if addr == "" { addr = net.JoinHostPort(hostIP.String(), "9345") } - stopMetrics := serveMetrics(addr, metrics.Handler()) + stopMetrics := serveMetrics(addr, instmetrics.Handler()) defer stopMetrics() slog.Error("fabric-api node is not configured: --cell (CELL) is empty; diagnostics are unavailable until it is set") <-ctx.Done() diff --git a/cmd/fabric-api/scrape_test.go b/cmd/fabric-api/scrape_test.go index f367ef1bf..9947ac31f 100644 --- a/cmd/fabric-api/scrape_test.go +++ b/cmd/fabric-api/scrape_test.go @@ -10,17 +10,22 @@ import ( "go.miloapis.com/instrumentation/instrumenttest" "go.miloapis.com/instrumentation/metrics" + "go.datum.net/galactic/internal/fabric/gateway" + "go.datum.net/galactic/internal/fabric/index" "go.datum.net/galactic/internal/fabric/node" ) -// TestMetricsScrape scrapes both roles' /metrics: the gateway's manager -// serves controller-runtime's registry, which metrics.Handler serves -// unchanged, and the node sidecar serves its own registry. +// TestMetricsScrape scrapes what both roles serve at /metrics, the +// instrumentation library's registry, once it holds the series each creates +// at startup, and lints them. Both roles define the certificate and +// credential gauges, so this also checks that their definitions agree. The +// gateway's admission and service switch gauges read a running cell, so they +// are left out. func TestMetricsScrape(t *testing.T) { - t.Run("gateway", func(t *testing.T) { - instrumenttest.AssertScrapes(t, metrics.Handler()) - }) - t.Run("node", func(t *testing.T) { - instrumenttest.AssertScrapes(t, node.NewMetrics().Handler()) - }) + gateway.NewMetrics(func() float64 { return 0 }) + m := node.NewMetrics() + m.RegisterClock(func() error { return nil }) + m.RegisterIndex(index.New()) + instrumenttest.AssertScrapes(t, metrics.Handler()) + instrumenttest.Lint(t) } diff --git a/docs/fabric-api/operations.md b/docs/fabric-api/operations.md index 244826000..cfecbf965 100644 --- a/docs/fabric-api/operations.md +++ b/docs/fabric-api/operations.md @@ -35,7 +35,7 @@ All are `severity: warning`, `service: galactic`, `team: connect`. A deployment evaluates its own copy of the rules changes them here first, with their tests, then updates that copy. -Node metrics (port 9345, a private registry with Go and process collectors): +Node metrics (port 9345, beside the Go runtime and process series): `fabric_api_node_requests_total{type,outcome}`, `fabric_api_node_request_duration_seconds{type}`, `fabric_api_node_response_bytes{type}`, diff --git a/docs/observability/README.md b/docs/observability/README.md index 0d1be7bdd..0637a939c 100644 --- a/docs/observability/README.md +++ b/docs/observability/README.md @@ -21,21 +21,28 @@ 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` 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: +which every controller-runtime manager serves. `galactic-cni`, +`fabric-config-agent` and the fabric-api node sidecar, which serve metrics +without a manager, serve that registry with the library's `metrics.Handler`. + +A metric created when its package loads is exported by every binary that +links the package. Where only some of them should export it, create it in a +constructor the binary calls at startup instead. The library's registry keeps +a series across calls, so a constructor that tests call repeatedly starts its +vectors over, and creates a function metric, which the library allows only +once per process, on its first call. + +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. - `TestNoMetricsOutsideLibrary` fails on any metric constructor or registry from `client_golang`'s `prometheus` package, including one passed in as a `prometheus.Registerer`. -- `TestMetricsLint` checks every library metric's name against Prometheus - conventions. It imports each package that defines one, and - `TestLintLinksEveryMetric` fails when a package is missing from that list - or defines its metrics in a command's `main` package. +- `TestMetricsLint` checks the name of every library metric created when a + package loads against Prometheus conventions. It imports each package that + defines one, and `TestLintLinksEveryMetric` fails when a package is missing + from that list or creates a metric in a command's `main` package. - Each command that serves `/metrics` has a `TestMetricsScrape`, which fails when two registries export the same series. `TestEveryBinaryHasScrapeTest` requires one for every new command, but can't tell whether the test scrapes @@ -44,10 +51,6 @@ tests in `internal/instrumentation` enforce the rule in the unit suite: first creates them through the same function the command calls, and also runs the library's lint, which `TestMetricsLint` can't reach. -Both source checks skip the directories in `pending` in -`internal/instrumentation/adoption_test.go`, which haven't moved to the -library yet. - ## Where the metrics come from The dataplane and fabric-router DaemonSets use `hostNetwork: true`, so diff --git a/internal/fabric/gateway/metrics.go b/internal/fabric/gateway/metrics.go index a10584633..440cb521e 100644 --- a/internal/fabric/gateway/metrics.go +++ b/internal/fabric/gateway/metrics.go @@ -6,8 +6,11 @@ package gateway import ( "strings" + "sync" + "sync/atomic" "github.com/prometheus/client_golang/prometheus" + "go.miloapis.com/instrumentation/metrics" servicev1 "go.datum.net/galactic/api/fabric/service/v1" "go.datum.net/galactic/internal/fabric/errcode" @@ -23,14 +26,12 @@ const ( labelReason = "reason" ) -// Metrics is the gateway's instrumentation, registered with the -// controller-runtime registry so it is served with the manager's metrics. +// Metrics is the gateway's instrumentation, created on the instrumentation +// library's registry so it is served with the manager's metrics. // Every label takes values from a fixed set: request IDs, project IDs, // service and operator names, nodes and targets are never labels. A nil // *Metrics records nothing. type Metrics struct { - reg prometheus.Registerer - serviceRequests *prometheus.CounterVec serviceOutcomes *prometheus.CounterVec serviceDuration *prometheus.HistogramVec @@ -40,7 +41,6 @@ type Metrics struct { queries *prometheus.CounterVec nodes *prometheus.CounterVec rpcDuration *prometheus.HistogramVec - queueDepth prometheus.GaugeFunc queueWait prometheus.Histogram statusWrites *prometheus.CounterVec statusBytes prometheus.Histogram @@ -52,148 +52,192 @@ type Metrics struct { credentialsOK prometheus.Gauge } -// NewMetrics builds the gateway metrics; depth reports the executor's queue. -func NewMetrics(reg prometheus.Registerer, depth func() float64) *Metrics { +// The function metrics read their values through these sources. The library +// creates a function metric only once per process, while NewMetrics and the +// Register methods can run again, as tests do: each creates its metrics on +// its first call and points them at the newest source on every call. +var ( + queueDepth funcSource[func() float64] + serviceState funcSource[ServiceSwitch] + admission funcSource[admissionSource] +) + +// admissionSource is what RegisterAdmission's metrics read. +type admissionSource struct { + a *Admission + clock func() error +} + +// funcSource holds the value a set of function metrics reads, and creates +// them the first time it is set. +type funcSource[T any] struct { + create sync.Once + v atomic.Pointer[T] +} + +// set makes v what the metrics read, creating them with create on the first +// call. +func (s *funcSource[T]) set(v *T, create func()) { + s.v.Store(v) + s.create.Do(create) +} + +// get returns what the metrics read. +func (s *funcSource[T]) get() *T { return s.v.Load() } + +// NewMetrics creates the gateway metrics on the instrumentation library's +// registry; depth reports the executor's queue. The registry keeps the series +// across calls, so each call starts the vectors over. +func NewMetrics(depth func() float64) *Metrics { m := &Metrics{ - reg: reg, - serviceRequests: prometheus.NewCounterVec(prometheus.CounterOpts{ + serviceRequests: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_gateway_service_requests_total", Help: "Looking Glass service requests that ended on this replica, by operation and reason: the " + "terminal coverage reason of a delivered stream, the refusal's reason before its snapshot, or " + "DeliveryFailed when its stream broke.", }, []string{labelOperation, labelReason}), - serviceOutcomes: prometheus.NewCounterVec(prometheus.CounterOpts{ + serviceOutcomes: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_gateway_service_router_outcomes_total", Help: "Routers of Looking Glass service requests, by operation and outcome: OK, a failure reason, or " + "the reason a router was omitted from the request.", }, []string{labelOperation, labelOutcome}), - serviceDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ + serviceDuration: metrics.NewHistogramVec(prometheus.HistogramOpts{ Name: "fabric_api_gateway_service_request_duration_seconds", Help: "Time from the leader's receipt of a Looking Glass service request to the end of its stream, " + "for requests whose snapshot was delivered.", Buckets: []float64{.05, .1, .25, .5, 1, 2.5, 5, 10, 30, 60, 120}, }, []string{labelOperation}), - admissionRefusals: prometheus.NewCounterVec(prometheus.CounterOpts{ + admissionRefusals: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_gateway_admission_refusals_total", Help: "Work the cell's aggregate admission refused, by traffic class (service, operator, fabricquery), " + "limiter scope (cell, project, destination, queue) and reason (Throttled, QueueFull, " + "LimiterUnavailable).", }, []string{"class", "scope", labelReason}), - packetsCharged: prometheus.NewCounterVec(prometheus.CounterOpts{ + packetsCharged: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_gateway_probe_packets_charged_total", Help: "Worst-case probe packets charged to the cell's budgets, by traffic class.", }, []string{"class"}), - queries: prometheus.NewCounterVec(prometheus.CounterOpts{ + queries: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_gateway_queries_total", Help: "FabricQuery executions finished, by query type and terminal reason.", }, []string{"type", "reason"}), - nodes: prometheus.NewCounterVec(prometheus.CounterOpts{ + nodes: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_gateway_node_outcomes_total", Help: "Per-node outcomes of executions: OK, an error code, or an omission reason.", }, []string{labelOutcome}), - rpcDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ + rpcDuration: metrics.NewHistogramVec(prometheus.HistogramOpts{ Name: "fabric_api_gateway_node_rpc_duration_seconds", Help: "Execute RPC duration to a node, by query type and outcome code.", Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 30}, }, []string{"type", "code"}), - queueDepth: prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_gateway_queue_depth", - Help: "Node RPCs waiting for a cell execution slot.", - }, depth), - queueWait: prometheus.NewHistogram(prometheus.HistogramOpts{ + queueWait: metrics.NewHistogram(prometheus.HistogramOpts{ Name: "fabric_api_gateway_queue_wait_seconds", Help: "Time node RPCs waited for a cell execution slot.", Buckets: []float64{.001, .01, .1, .5, 1, 5, 10, 30}, }), - statusWrites: prometheus.NewCounterVec(prometheus.CounterOpts{ + statusWrites: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_gateway_status_writes_total", Help: "FabricQuery status writes by kind (start, terminal) and outcome (ok, conflict, error).", }, []string{"kind", labelOutcome}), - statusBytes: prometheus.NewHistogram(prometheus.HistogramOpts{ + statusBytes: metrics.NewHistogram(prometheus.HistogramOpts{ Name: "fabric_api_gateway_status_bytes", Help: "Serialized size of terminal FabricQuery objects.", Buckets: prometheus.ExponentialBuckets(1024, 2, 10), }), - truncated: prometheus.NewCounter(prometheus.CounterOpts{ + truncated: metrics.NewCounter(prometheus.CounterOpts{ Name: "fabric_api_gateway_truncated_results_total", Help: "Terminal results shaped down to the object byte budget.", }), - stageLatency: prometheus.NewHistogramVec(prometheus.HistogramOpts{ + stageLatency: metrics.NewHistogramVec(prometheus.HistogramOpts{ Name: "fabric_api_gateway_stage_latency_seconds", Help: "Latency of each stage of a query's life as seen by the cell: receipt (creation to first " + "reconcile), execution (start marker to last node answer), completion (creation to terminal status).", Buckets: []float64{.05, .1, .25, .5, 1, 2.5, 5, 10, 30, 60, 120}, }, []string{"stage"}), - inFlight: prometheus.NewGauge(prometheus.GaugeOpts{ + inFlight: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_gateway_executions_in_flight", Help: "FabricQuery executions running on this gateway.", }), - staleObjects: prometheus.NewGauge(prometheus.GaugeOpts{ + staleObjects: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_gateway_stale_objects", Help: "FabricQuery objects in this cell past their expiration (or completion) plus retention and " + "cleanup grace, which neither the federation nor the janitor has deleted.", }), - certExpiry: prometheus.NewGauge(prometheus.GaugeOpts{ + certExpiry: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_certificate_expiry_timestamp_seconds", - Help: "NotAfter of the loaded client certificate.", + Help: "NotAfter of the loaded mTLS certificate: the gateway's client certificate or the node's " + + "serving certificate.", }), - credentialsOK: prometheus.NewGauge(prometheus.GaugeOpts{ + credentialsOK: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_credentials_loaded", Help: "1 when valid mTLS credentials are loaded.", }), } - reg.MustRegister(m.queries, m.nodes, m.rpcDuration, m.queueDepth, m.queueWait, m.statusWrites, m.statusBytes, - m.truncated, m.stageLatency, m.inFlight, m.staleObjects, m.certExpiry, m.credentialsOK, m.serviceRequests, - m.serviceOutcomes, m.serviceDuration, m.admissionRefusals, m.packetsCharged) + for _, v := range []interface{ Reset() }{m.serviceRequests, m.serviceOutcomes, m.serviceDuration, + m.admissionRefusals, m.packetsCharged, m.queries, m.nodes, m.rpcDuration, m.statusWrites, m.stageLatency} { + v.Reset() + } + queueDepth.set(&depth, func() { + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_gateway_queue_depth", + Help: "Node RPCs waiting for a cell execution slot.", + }, func() float64 { return (*queueDepth.get())() }) + }) return m } // RegisterService exports the Looking Glass switch's state as // fabric_api_gateway_service_enabled. func (m *Metrics) RegisterService(sw *ServiceSwitch) { - m.reg.MustRegister(prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_gateway_service_enabled", - Help: "1 while this replica's service switch lets the Looking Glass service execute.", - }, func() float64 { - on, _ := sw.State() - return boolGauge(on) - })) + serviceState.set(sw, func() { + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_gateway_service_enabled", + Help: "1 while this replica's service switch lets the Looking Glass service execute.", + }, func() float64 { + on, _ := serviceState.get().State() + return boolGauge(on) + }) + }) } // RegisterAdmission exports the leader's aggregate admission state: its // limiter state (one series per state, 1 for the current one), live service // streams, limiter keys by kind, and clock's health. func (m *Metrics) RegisterAdmission(a *Admission, clock func() error) { + admission.set(&admissionSource{a: a, clock: clock}, createAdmissionMetrics) +} + +// createAdmissionMetrics creates RegisterAdmission's metrics, reading +// admission. +func createAdmissionMetrics() { for _, state := range []string{limit.StateReady, limit.StateRecovering, limit.StateUnavailable} { - m.reg.MustRegister(prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + metrics.NewGaugeFunc(prometheus.GaugeOpts{ Name: "fabric_api_gateway_limiter_state", Help: "1 for the aggregate limiter's current state: ready, recovering (in its recovery hold) or " + "unavailable (not the leader, or unable to confirm the election or the clock).", ConstLabels: prometheus.Labels{"state": state}, - }, func() float64 { return boolGauge(a.Authority.State() == state) })) + }, func() float64 { return boolGauge(admission.get().a.Authority.State() == state) }) } - keys := func(kind string, n func() int) prometheus.Collector { - return prometheus.NewGaugeFunc(prometheus.GaugeOpts{ + keys := func(kind string, n func(*Admission) int) { + metrics.NewGaugeFunc(prometheus.GaugeOpts{ Name: "fabric_api_gateway_limiter_keys", Help: "Keys the aggregate limiter holds, by kind: project (project and principal buckets), " + "destination (host and prefix buckets) and attempt (live attempt keys).", ConstLabels: prometheus.Labels{"kind": kind}, - }, func() float64 { return float64(n()) }) + }, func() float64 { return float64(n(admission.get().a)) }) } - m.reg.MustRegister( - keys("project", func() int { p, _ := a.Buckets.Keys(); return p }), - keys("destination", func() int { _, d := a.Buckets.Keys(); return d }), - keys("attempt", a.Attempts.Len), - prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_gateway_service_streams", - Help: "Live Looking Glass service streams the leader holds, queued and draining ones included.", - }, func() float64 { return float64(a.liveStreams()) }), - prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_gateway_clock_synchronized", - Help: "1 while the kernel reports its clock synchronised within the limiter's bound; the limiter " + - "admits nothing otherwise.", - }, func() float64 { return boolGauge(clock() == nil) }), - ) + keys("project", func(a *Admission) int { p, _ := a.Buckets.Keys(); return p }) + keys("destination", func(a *Admission) int { _, d := a.Buckets.Keys(); return d }) + keys("attempt", func(a *Admission) int { return a.Attempts.Len() }) + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_gateway_service_streams", + Help: "Live Looking Glass service streams the leader holds, queued and draining ones included.", + }, func() float64 { return float64(admission.get().a.liveStreams()) }) + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_gateway_clock_synchronized", + Help: "1 while the kernel reports its clock synchronised within the limiter's bound; the limiter " + + "admits nothing otherwise.", + }, func() float64 { return boolGauge(admission.get().clock() == nil) }) } func boolGauge(b bool) float64 { diff --git a/internal/fabric/gateway/serviceswitch_test.go b/internal/fabric/gateway/serviceswitch_test.go index 24dfbbdc1..55ea4ed2f 100644 --- a/internal/fabric/gateway/serviceswitch_test.go +++ b/internal/fabric/gateway/serviceswitch_test.go @@ -14,7 +14,6 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -23,6 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" forwardv1 "go.datum.net/galactic/api/fabric/forward/v1" servicev1 "go.datum.net/galactic/api/fabric/service/v1" @@ -206,8 +206,7 @@ func TestServiceTelemetryCarriesNoPayload(t *testing.T) { nodes := &routerNodes{answers: map[string]routerAnswer{routerB: failAnswer(errcode.FRRUnavailable)}} svc := newService(t, routerPods(routerA, routerB), nodes, 8) adm := withAdmission(t, svc, limit.Defaults()) - reg := prometheus.NewRegistry() - m := NewMetrics(reg, func() float64 { return 0 }) + m := NewMetrics(func() float64 { return 0 }) m.RegisterService(svc.Switch) m.RegisterAdmission(adm, func() error { return nil }) svc.Metrics, svc.Runner.Metrics, adm.Metrics = m, m, m @@ -253,7 +252,7 @@ func TestServiceTelemetryCarriesNoPayload(t *testing.T) { forbidden := []string{testProject, testRequestID[:8], "2606:4700", routerA, routerB, podA, "raw failure", testService} - families, err := reg.Gather() + families, err := ctrlmetrics.Registry.Gather() if err != nil { t.Fatal(err) } @@ -285,7 +284,7 @@ func TestServiceTelemetryCarriesNoPayload(t *testing.T) { // A follower counts a request it refused itself, and the leader one it ran // or refused after forwarding, so each request is counted once in the cell. func TestServiceRequestCountedOnce(t *testing.T) { - m := NewMetrics(prometheus.NewRegistry(), func() float64 { return 0 }) + m := NewMetrics(func() float64 { return 0 }) svc := &Service{Cell: testSite, Allowlist: testAllowlist, Elected: func() bool { return false }, Metrics: m} bad := validRequest(time.Now()) bad.ApiMajor = 2 diff --git a/internal/fabric/node/metrics.go b/internal/fabric/node/metrics.go index 7ad841049..7a000506b 100644 --- a/internal/fabric/node/metrics.go +++ b/internal/fabric/node/metrics.go @@ -5,11 +5,11 @@ package node import ( - "net/http" + "sync" + "sync/atomic" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/collectors" - "github.com/prometheus/client_golang/prometheus/promhttp" + "go.miloapis.com/instrumentation/metrics" "go.datum.net/galactic/internal/fabric/index" ) @@ -21,11 +21,10 @@ const ( labelOutcome = "outcome" ) -// Metrics is the node sidecar's Prometheus instrumentation in a private -// registry. Request IDs and targets are never labels. +// Metrics is the node sidecar's Prometheus instrumentation, on the +// instrumentation library's registry, which the sidecar serves with that +// library's metrics.Handler. Request IDs and targets are never labels. type Metrics struct { - Registry *prometheus.Registry - requests *prometheus.CounterVec duration *prometheus.HistogramVec responseBytes *prometheus.HistogramVec @@ -44,148 +43,179 @@ type Metrics struct { permits *prometheus.CounterVec } -// NewMetrics builds Metrics with every collector registered. +// NewMetrics creates Metrics on the instrumentation library's registry. The +// registry keeps the series across calls, so each call starts the vectors +// over. func NewMetrics() *Metrics { m := &Metrics{ - Registry: prometheus.NewRegistry(), - requests: prometheus.NewCounterVec(prometheus.CounterOpts{ + requests: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_node_requests_total", Help: "Execute calls by query type and outcome (OK or the error code).", }, []string{labelType, labelOutcome}), - duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ + duration: metrics.NewHistogramVec(prometheus.HistogramOpts{ Name: "fabric_api_node_request_duration_seconds", Help: "Execute call duration by query type, including queueing.", Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 30}, }, []string{labelType}), - responseBytes: prometheus.NewHistogramVec(prometheus.HistogramOpts{ + responseBytes: metrics.NewHistogramVec(prometheus.HistogramOpts{ Name: "fabric_api_node_response_bytes", Help: "Serialized Execute response size by query type.", Buckets: prometheus.ExponentialBuckets(256, 4, 8), }, []string{labelType}), - truncated: prometheus.NewCounterVec(prometheus.CounterOpts{ + truncated: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_node_truncated_responses_total", Help: "Responses shaped down to budget, by query type.", }, []string{labelType}), - inFlight: prometheus.NewGauge(prometheus.GaugeOpts{ + inFlight: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_node_in_flight_requests", Help: "Execute calls currently running or queued.", }), - dedupHits: prometheus.NewCounter(prometheus.CounterOpts{ + dedupHits: metrics.NewCounter(prometheus.CounterOpts{ Name: "fabric_api_node_duplicate_requests_total", Help: "Execute calls answered from the duplicate-suppression cache.", }), - dedupEntries: prometheus.NewGauge(prometheus.GaugeOpts{ + dedupEntries: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_node_duplicate_cache_entries", Help: "Entries in the duplicate-suppression cache.", }), - available: prometheus.NewGauge(prometheus.GaugeOpts{ + available: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_node_diagnostics_available", Help: "1 when FRR is reachable at a supported version and credentials are loaded.", }), - frrInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{ + frrInfo: metrics.NewGaugeVec(prometheus.GaugeOpts{ Name: "fabric_api_node_frr_info", Help: "FRR version last read from bgpd, and whether it is supported.", }, []string{"version", "supported"}), - breakerOpen: prometheus.NewGauge(prometheus.GaugeOpts{ + breakerOpen: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_node_expensive_breaker_open", Help: "1 while expensive searches are suspended after an uncertain timed-out scan.", }), - probePackets: prometheus.NewCounter(prometheus.CounterOpts{ + probePackets: metrics.NewCounter(prometheus.CounterOpts{ Name: "fabric_api_node_probe_packets_total", Help: "ICMP probe packets sent.", }), - certExpiry: prometheus.NewGauge(prometheus.GaugeOpts{ + certExpiry: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_certificate_expiry_timestamp_seconds", - Help: "NotAfter of the loaded serving certificate.", + Help: "NotAfter of the loaded mTLS certificate: the gateway's client certificate or the node's " + + "serving certificate.", }), - credentialsOK: prometheus.NewGauge(prometheus.GaugeOpts{ + credentialsOK: metrics.NewGauge(prometheus.GaugeOpts{ Name: "fabric_api_credentials_loaded", Help: "1 when valid mTLS credentials are loaded.", }), - bmpMessages: prometheus.NewCounter(prometheus.CounterOpts{ - Name: "fabric_api_node_bmp_route_messages_total", - Help: "BMP Loc-RIB route monitoring messages applied to the search index.", - }), - identityRefresh: prometheus.NewCounterVec(prometheus.CounterOpts{ + identityRefresh: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_node_identity_refreshes_total", Help: "Reads of FRR version, router ID and ASN, by outcome.", }, []string{labelOutcome}), - permits: prometheus.NewCounterVec(prometheus.CounterOpts{ + permits: metrics.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_node_permits_total", Help: "Probe permits the node verified, by outcome: accepted, or why it refused one (invalid, " + "malformed, mismatch, expired, starting, clock, lease, epoch, replayed, full).", }, []string{labelOutcome}), } - m.Registry.MustRegister(m.requests, m.duration, m.responseBytes, m.truncated, m.inFlight, m.dedupHits, - m.dedupEntries, m.available, m.frrInfo, m.breakerOpen, m.probePackets, m.certExpiry, m.credentialsOK, - m.identityRefresh, m.permits, collectors.NewGoCollector(), - collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) + for _, v := range []interface{ Reset() }{m.requests, m.duration, m.responseBytes, m.truncated, m.frrInfo, + m.identityRefresh, m.permits} { + v.Reset() + } return m } +// The function metrics read their values through these sources. The library +// creates a function metric only once per process, while the Register +// methods can run again, as tests do: each creates its metrics on its first +// call and points them at the newest source on every call. +var ( + clockSource funcSource[func() error] + indexSource funcSource[index.Index] +) + +// funcSource holds the value a set of function metrics reads, and creates +// them the first time it is set. +type funcSource[T any] struct { + create sync.Once + v atomic.Pointer[T] +} + +// set makes v what the metrics read, creating them with create on the first +// call. +func (s *funcSource[T]) set(v *T, create func()) { + s.v.Store(v) + s.create.Do(create) +} + +// get returns what the metrics read. +func (s *funcSource[T]) get() *T { return s.v.Load() } + // RegisterClock exports clock's health as fabric_api_node_clock_synchronized, // read on every scrape. A node registers it only when it verifies probe // permits, the one place it trusts its clock. func (m *Metrics) RegisterClock(clock func() error) { - m.Registry.MustRegister(prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_node_clock_synchronized", - Help: "1 while the kernel reports its clock synchronised within the permit bound; probe permits are " + - "refused otherwise.", - }, func() float64 { return boolGauge(clock() == nil) })) + clockSource.set(&clock, func() { + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_node_clock_synchronized", + Help: "1 while the kernel reports its clock synchronised within the permit bound; probe permits are " + + "refused otherwise.", + }, func() float64 { return boolGauge((*clockSource.get())() == nil) }) + }) } -// Handler serves the registry. -func (m *Metrics) Handler() http.Handler { - return promhttp.HandlerFor(m.Registry, promhttp.HandlerOpts{}) +// RegisterIndex exports the search index's state and counts the BMP +// messages applied to it. +func (m *Metrics) RegisterIndex(ix *index.Index) { + m.bmpMessages = metrics.NewCounter(prometheus.CounterOpts{ + Name: "fabric_api_node_bmp_route_messages_total", + Help: "BMP Loc-RIB route monitoring messages applied to the search index.", + }) + indexSource.set(ix, createIndexMetrics) } -// RegisterIndex adds the search index's state to the registry. -func (m *Metrics) RegisterIndex(ix *index.Index) { - routes := func(v4 bool) func() float64 { - return func() float64 { - a, b, _, _ := ix.Stats() +// createIndexMetrics creates RegisterIndex's function metrics, reading +// indexSource. +func createIndexMetrics() { + routes := func(afi string, v4 bool) { + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_node_search_index_routes", Help: "Prefixes in the search index.", + ConstLabels: prometheus.Labels{"afi": afi}, + }, func() float64 { + a, b, _, _ := indexSource.get().Stats() if v4 { return float64(a) } return float64(b) - } + }) } - m.Registry.MustRegister( - prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_node_search_index_routes", Help: "Prefixes in the search index.", - ConstLabels: prometheus.Labels{"afi": "ipv4"}, - }, routes(true)), - prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_node_search_index_routes", Help: "Prefixes in the search index.", - ConstLabels: prometheus.Labels{"afi": "ipv6"}, - }, routes(false)), - prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_node_search_index_attribute_sets", - Help: "Distinct path attribute sets the search index holds.", - }, func() float64 { _, _, a, _ := ix.Stats(); return float64(a) }), - prometheus.NewCounterFunc(prometheus.CounterOpts{ - Name: "fabric_api_node_search_index_overflow_total", - Help: "Route announcements dropped because the search index was at its route ceiling.", - }, func() float64 { _, _, _, o := ix.Stats(); return float64(o) }), - prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_node_search_index_synced", - Help: "1 when the search index holds bgpd's full table and follows it over BMP.", - }, func() float64 { return boolGauge(ix.State().Synced) }), - prometheus.NewGaugeFunc(prometheus.GaugeOpts{ - Name: "fabric_api_node_search_index_last_update_timestamp_seconds", - Help: "When the search index last applied a route change.", - }, func() float64 { - if t := ix.State().LastUpdate; !t.IsZero() { - return float64(t.Unix()) - } - return 0 - }), - m.bmpMessages, - ) + routes("ipv4", true) + routes("ipv6", false) + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_node_search_index_attribute_sets", + Help: "Distinct path attribute sets the search index holds.", + }, func() float64 { _, _, a, _ := indexSource.get().Stats(); return float64(a) }) + metrics.NewCounterFunc(prometheus.CounterOpts{ + Name: "fabric_api_node_search_index_overflow_total", + Help: "Route announcements dropped because the search index was at its route ceiling.", + }, func() float64 { _, _, _, o := indexSource.get().Stats(); return float64(o) }) + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_node_search_index_synced", + Help: "1 when the search index holds bgpd's full table and follows it over BMP.", + }, func() float64 { return boolGauge(indexSource.get().State().Synced) }) + metrics.NewGaugeFunc(prometheus.GaugeOpts{ + Name: "fabric_api_node_search_index_last_update_timestamp_seconds", + Help: "When the search index last applied a route change.", + }, func() float64 { + if t := indexSource.get().State().LastUpdate; !t.IsZero() { + return float64(t.Unix()) + } + return 0 + }) } -// BMPMessage counts one applied BMP route monitoring message. -func (m *Metrics) BMPMessage() { m.bmpMessages.Inc() } +// BMPMessage counts one applied BMP route monitoring message. Only a node +// that called RegisterIndex counts them. +func (m *Metrics) BMPMessage() { + if m.bmpMessages != nil { + m.bmpMessages.Inc() + } +} // CertificateExpiry records a loaded certificate's expiry. func (m *Metrics) CertificateExpiry(unix float64) { m.certExpiry.Set(unix) } diff --git a/internal/instrumentation/adoption_test.go b/internal/instrumentation/adoption_test.go index 680678c4c..6319f1ecc 100644 --- a/internal/instrumentation/adoption_test.go +++ b/internal/instrumentation/adoption_test.go @@ -23,24 +23,11 @@ import ( // moduleRoot is the repository root, relative to this package. const moduleRoot = "../.." -// pending lists the directories, relative to the module root, that still -// create or register metrics outside the instrumentation library. Both -// adoption checks skip them. Remove a directory once it has moved; the -// checks then fail on anything left behind. -var pending = []string{ - // #1149: serve controller-runtime's registry through library metrics. - "cmd/fabric-api", - // #1149: create metrics with the library's constructors instead of a - // registry parameter or a private registry. - "internal/fabric/gateway", - "internal/fabric/node", -} - // TestAdopted runs the instrumentation library's adoption check over the // module: nothing registers a metric outside the library, and every logger // is built by it. func TestAdopted(t *testing.T) { - instrumenttest.AssertAdopted(t, instrumenttest.SkipDir(pending...)) + instrumenttest.AssertAdopted(t) } const promPath = "github.com/prometheus/client_golang/prometheus" @@ -63,20 +50,10 @@ var outsideLibrary = []string{ } // TestNoMetricsOutsideLibrary fails wherever the module's non-test source -// outside pending creates a metric or a registry with prometheus directly. +// creates a metric or a registry with prometheus directly. func TestNoMetricsOutsideLibrary(t *testing.T) { - skip := map[string]bool{} - for _, d := range pending { - if _, err := os.Stat(filepath.Join(moduleRoot, d)); err != nil { - t.Errorf("pending directory %s: %v", d, err) - } - skip[d] = true - } fset := token.NewFileSet() walkSource(t, func(rel string, f *ast.File) { - if skip[filepath.ToSlash(filepath.Dir(rel))] || underAny(rel, skip) { - return - } for _, imp := range f.Imports { if p, _ := strconv.Unquote(imp.Path.Value); p == promPath && imp.Name != nil && imp.Name.Name == "." { t.Errorf("%s:%d: dot import of %s hides its constructors from this check", @@ -93,17 +70,6 @@ func TestNoMetricsOutsideLibrary(t *testing.T) { }, fset) } -// underAny reports whether rel lies under one of dirs. -func underAny(rel string, dirs map[string]bool) bool { - rel = filepath.ToSlash(rel) - for d := range dirs { - if strings.HasPrefix(rel, d+"/") { - return true - } - } - return false -} - // walkSource parses every non-test Go file in the module, skipping nested // modules, testdata, hidden directories and files built only with the ignore // tag, and passes each to fn with its path relative to the module root. diff --git a/internal/instrumentation/lint_test.go b/internal/instrumentation/lint_test.go index dd9319af8..e9f71883b 100644 --- a/internal/instrumentation/lint_test.go +++ b/internal/instrumentation/lint_test.go @@ -19,8 +19,12 @@ import ( "go.miloapis.com/instrumentation/instrumenttest" // Every package that creates a metric through the library, so Lint sees - // it. TestLintLinksEveryMetric keeps this list complete. + // the ones a package creates when it loads; each command's scrape test + // lints the ones created at startup. TestLintLinksEveryMetric keeps this + // list complete. _ "go.datum.net/galactic/internal/edge/diag" + _ "go.datum.net/galactic/internal/fabric/gateway" + _ "go.datum.net/galactic/internal/fabric/node" _ "go.datum.net/galactic/internal/fabricconfig" _ "go.datum.net/galactic/internal/gateway" _ "go.datum.net/galactic/internal/ingresssidecar"