From 199ff59d565d384d6989e0dbc4ae2fc94cff16ff Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 26 Oct 2026 16:48:53 -0400 Subject: [PATCH] feat(fabric-api): Report Looking Glass throttling and limiter health Nothing reported why Looking Glass requests were refused, how the cell's aggregate limiter was doing, whether its clock was trusted or why a node refused a probe permit, and no alert covered any of it. The gateway now exports service requests by operation and reason, router outcomes and omissions, request duration, admission refusals by traffic class (service, operator, fabricquery), limiter scope and reason, charged packets by traffic class, the service switch's state, live streams, limiter state and key counts, and clock health. The node exports permit decisions by outcome (accepted, or invalid, malformed, mismatch, expired, starting, clock, lease, epoch, replayed, full) and its clock health. Labels come from fixed sets: no project, request or service ID, node name or target is a label. A follower counts only the requests it refused itself, and the leader counts the rest, including forwarded requests it refused before executing them, so each request is counted once. The leader logs one line per request it ran with the service, project, request ID, operation, reason, router counts and duration, never targets, results or node error text; a request refused before its snapshot is logged at debug level. A test runs requests and throttling and checks the registry and the logs for each. The fabric-api rule group gains FabricAPILimiterUnavailable (no ready limiter in a cell for 10 minutes), FabricAPIClockUnsynchronized, FabricAPIServiceThrottled (most of at least 20 requests in 30 minutes refused by a budget, queue or the limiter) and FabricAPIServiceExecutionFailing (most of at least 10 executed requests returned no router result), each unit-tested with promtool, including idle and disabled cells that must not fire. Related to #1047 --- cmd/fabric-api/gateway.go | 4 + cmd/fabric-api/node.go | 9 +- config/monitoring/prometheusrule.yaml | 93 +++++++++ config/monitoring/tests/rules-test.yaml | 128 ++++++++++++ internal/fabric/gateway/admission.go | 26 ++- internal/fabric/gateway/metrics.go | 186 +++++++++++++++++- internal/fabric/gateway/permit.go | 4 +- internal/fabric/gateway/runner.go | 5 +- internal/fabric/gateway/service.go | 125 ++++++++++-- internal/fabric/gateway/serviceswitch_test.go | 135 +++++++++++++ internal/fabric/node/metrics.go | 32 ++- internal/fabric/node/permit.go | 55 ++++-- internal/fabric/node/permit_test.go | 84 ++++++-- 13 files changed, 818 insertions(+), 68 deletions(-) diff --git a/cmd/fabric-api/gateway.go b/cmd/fabric-api/gateway.go index 827f3119d..8dcb85159 100644 --- a/cmd/fabric-api/gateway.go +++ b/cmd/fabric-api/gateway.go @@ -272,10 +272,13 @@ func runGateway(parent context.Context, o *gatewayOptions) error { if err != nil { return fmt.Errorf("--aggregate-budgets: %w", err) } + admission.Metrics = metrics + metrics.RegisterAdmission(admission, limit.KernelClock) executor.PrincipalSlots, executor.PrincipalQueue = o.limits.PrincipalSlots, o.limits.PrincipalQueue go admission.Authority.Watch(ctx, limit.WatchInterval) } serviceSwitch := &gateway.ServiceSwitch{} + metrics.RegisterService(serviceSwitch) if o.serviceConfigMap != "" { go serviceSwitch.Watch(ctx, mgr.GetAPIReader(), o.namespace, o.serviceConfigMap, gateway.ServiceSwitchInterval) } @@ -360,6 +363,7 @@ func runGateway(parent context.Context, o *gatewayOptions) error { service := &gateway.Service{ Cell: o.cell, Switch: serviceSwitch, + Metrics: metrics, Allowlist: allowlist, Elected: debug.Elected, Leader: debug, diff --git a/cmd/fabric-api/node.go b/cmd/fabric-api/node.go index 9b3effa78..7e52fba00 100644 --- a/cmd/fabric-api/node.go +++ b/cmd/fabric-api/node.go @@ -200,7 +200,7 @@ func runNode(parent context.Context, o *nodeOptions) error { return fmt.Errorf("--search-source must be index or frr, not %q", o.searchSource) } - permits, err := nodePermits(o, creds) + permits, err := nodePermits(o, creds, metrics) if err != nil { return err } @@ -275,8 +275,8 @@ func runNode(parent context.Context, o *nodeOptions) error { // nodePermits returns the probe permit checker the flags select, or nil // without --probe-permits. Its permits are refused while the kernel clock -// is unsynchronised. -func nodePermits(o *nodeOptions, creds *identity.Credentials) (*node.Permits, error) { +// is unsynchronised, which metrics reports. +func nodePermits(o *nodeOptions, creds *identity.Credentials, metrics *node.Metrics) (*node.Permits, error) { switch { case !o.probePermits && (o.requirePermits || o.gatewayAddress != ""): return nil, errors.New("--require-probe-permits and --gateway-address need --probe-permits") @@ -295,8 +295,9 @@ func nodePermits(o *nodeOptions, creds *identity.Credentials) (*node.Permits, er } p := &node.Permits{ Reader: reader, Namespace: o.namespace, LeaseName: o.gatewayLease, Require: o.requirePermits, - Started: time.Now(), Clock: limit.KernelClock, + Started: time.Now(), Clock: limit.KernelClock, Metrics: metrics, } + metrics.RegisterClock(limit.KernelClock) if o.gatewayAddress != "" { conn, err := grpc.NewClient(o.gatewayAddress, grpc.WithTransportCredentials(credentials.NewTLS(creds.ClientConfig(identity.Gateway(o.cell)))), diff --git a/config/monitoring/prometheusrule.yaml b/config/monitoring/prometheusrule.yaml index f1229cada..223da2db9 100644 --- a/config/monitoring/prometheusrule.yaml +++ b/config/monitoring/prometheusrule.yaml @@ -1135,6 +1135,99 @@ spec: description: >- Prometheus cannot scrape {{ $labels.job }} on {{ $labels.pod }}, so the other fabric-api alerts cannot fire for it. + # The leader's aggregate limiter admits nothing during its 125 s + # recovery hold after a start, failover or failed Lease read; ten + # minutes without a ready replica is no ordinary hold. The series + # exist only on gateways run with --aggregate-budgets, and the max + # over replicas keeps a leader change from resetting the alert. + - alert: FabricAPILimiterUnavailable + expr: >- + max without (pod, instance, state) (fabric_api_gateway_limiter_state{job="fabric-api-gateway",state="ready"}) == 0 + for: 10m + labels: + severity: warning + service: galactic + team: connect + annotations: + summary: "fabric-api's aggregate limiter in {{ $labels.namespace }} has admitted nothing for 10 minutes" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#fabricapilimiterunavailable" + description: >- + No fabric-api gateway replica in {{ $labels.namespace }} has had a ready aggregate limiter for 10 + minutes, so every probe in the cell, operator, FabricQuery and Looking Glass alike, is refused with + LimiterUnavailable; route lookups and BGP summaries are unaffected. The leader cannot read its + election Lease, keeps losing the election, or its clock is unsynchronised + (fabric_api_gateway_clock_synchronized). Check the leader's logs and Lease. + # The limiter and each node's permit check trust the clock only while + # the kernel reports it synchronised within 500 ms. The gauges exist + # only where that trust is in use: a gateway with --aggregate-budgets + # and a node with --probe-permits. + - alert: FabricAPIClockUnsynchronized + expr: >- + fabric_api_gateway_clock_synchronized{job="fabric-api-gateway"} == 0 + or + fabric_api_node_clock_synchronized{job="fabric-api-node"} == 0 + for: 10m + labels: + severity: warning + service: galactic + team: connect + annotations: + summary: "fabric-api on {{ $labels.pod }} runs on an unsynchronised clock" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#fabricapiclockunsynchronized" + description: >- + The kernel clock under {{ $labels.pod }} has not been synchronised within 500 ms for 10 minutes. A + gateway on it admits no probe and no Looking Glass request; a node on it refuses every probe permit. + Check the host's time daemon (chrony, ntpd, systemd-timesyncd or Talos timed). + # More than half of at least 20 Looking Glass requests in 30 minutes + # were refused by a budget, a queue or the limiter. Throttling is the + # limits working; sustained throttling means the cell's limits or the + # service's own admission need attention. Disabled or idle cells never + # fire. + - alert: FabricAPIServiceThrottled + expr: >- + ( + sum without (pod, instance, operation, reason) (increase(fabric_api_gateway_service_requests_total{job="fabric-api-gateway",reason=~"Throttled|QueueFull|LimiterUnavailable"}[30m])) + / + sum without (pod, instance, operation, reason) (increase(fabric_api_gateway_service_requests_total{job="fabric-api-gateway"}[30m])) + ) > 0.5 + and + sum without (pod, instance, operation, reason) (increase(fabric_api_gateway_service_requests_total{job="fabric-api-gateway"}[30m])) >= 20 + for: 15m + labels: + severity: warning + service: galactic + team: connect + annotations: + summary: "Most Looking Glass requests in {{ $labels.namespace }} are refused by the cell's limits" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#fabricapiservicethrottled" + description: >- + {{ $value | humanizePercentage }} of Looking Glass requests in {{ $labels.namespace }} in the last 30 + minutes were refused with Throttled, QueueFull or LimiterUnavailable. fabric_api_gateway_admission_refusals_total + names the scope (cell, project, destination or queue) that refused them. + # More than half of at least 10 Looking Glass requests that reached + # execution in 30 minutes produced no router result: every selected + # router failed, none was selectable, or the leader lost the election. + - alert: FabricAPIServiceExecutionFailing + expr: >- + ( + sum without (pod, instance, operation, reason) (increase(fabric_api_gateway_service_requests_total{job="fabric-api-gateway",reason=~"ExecutionFailed|NoNodesAvailable|OwnershipLost|Internal"}[30m])) + / + sum without (pod, instance, operation, reason) (increase(fabric_api_gateway_service_requests_total{job="fabric-api-gateway",reason=~"Succeeded|PartialResults|ExecutionFailed|NoNodesAvailable|OwnershipLost|Internal"}[30m])) + ) > 0.5 + and + sum without (pod, instance, operation, reason) (increase(fabric_api_gateway_service_requests_total{job="fabric-api-gateway",reason=~"Succeeded|PartialResults|ExecutionFailed|NoNodesAvailable|OwnershipLost|Internal"}[30m])) >= 10 + for: 15m + labels: + severity: warning + service: galactic + team: connect + annotations: + summary: "Most Looking Glass requests in {{ $labels.namespace }} return no router result" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#fabricapiserviceexecutionfailing" + description: >- + {{ $value | humanizePercentage }} of the Looking Glass requests {{ $labels.namespace }} executed in the + last 30 minutes ended ExecutionFailed, NoNodesAvailable, OwnershipLost or Internal. + fabric_api_gateway_service_router_outcomes_total gives each router's failure or omission reason. # The Galactic Edge foundation: galactic-controller --edge (job # galactic-controller, port 9184) exports attachment, route and service # state from every replica's cache, so the state rules take the max over diff --git a/config/monitoring/tests/rules-test.yaml b/config/monitoring/tests/rules-test.yaml index 301abc212..9c911c383 100644 --- a/config/monitoring/tests/rules-test.yaml +++ b/config/monitoring/tests/rules-test.yaml @@ -2459,3 +2459,131 @@ tests: description: >- Prometheus cannot scrape galactic-edge on galactic-edge-abcde, so the other Galactic Edge alerts cannot fire for it. + + # No ready limiter in a cell for 10m fires; a cell whose leader serves an + # ordinary 2-minute recovery hold after a failover, across two replicas, + # does not. + - interval: 30s + input_series: + - series: 'fabric_api_gateway_limiter_state{job="fabric-api-gateway",namespace="galactic-system",pod="gw-a",state="ready"}' + values: "0x40" + - series: 'fabric_api_gateway_limiter_state{job="fabric-api-gateway",namespace="galactic-system",pod="gw-a",state="recovering"}' + values: "1x40" + - series: 'fabric_api_gateway_limiter_state{job="fabric-api-gateway",namespace="galactic-system",pod="gw-b",state="ready"}' + values: "0x40" + - series: 'fabric_api_gateway_limiter_state{job="fabric-api-gateway",namespace="fabric-lab",pod="gw-c",state="ready"}' + values: "1x10 0x30" + - series: 'fabric_api_gateway_limiter_state{job="fabric-api-gateway",namespace="fabric-lab",pod="gw-d",state="ready"}' + values: "0x14 1x26" + alert_rule_test: + - eval_time: 9m + alertname: FabricAPILimiterUnavailable + exp_alerts: [] + - eval_time: 11m + alertname: FabricAPILimiterUnavailable + exp_alerts: + - exp_labels: + severity: warning + service: galactic + team: connect + job: fabric-api-gateway + namespace: galactic-system + exp_annotations: + summary: "fabric-api's aggregate limiter in galactic-system has admitted nothing for 10 minutes" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#fabricapilimiterunavailable" + description: >- + No fabric-api gateway replica in galactic-system has had a ready aggregate limiter for 10 + minutes, so every probe in the cell, operator, FabricQuery and Looking Glass alike, is refused with + LimiterUnavailable; route lookups and BGP summaries are unaffected. The leader cannot read its + election Lease, keeps losing the election, or its clock is unsynchronised + (fabric_api_gateway_clock_synchronized). Check the leader's logs and Lease. + + # An unsynchronised gateway clock for 10m fires; a node whose clock lost + # sync for 2 minutes does not. + - interval: 30s + input_series: + - series: 'fabric_api_gateway_clock_synchronized{job="fabric-api-gateway",namespace="galactic-system",pod="gw-a"}' + values: "0x30" + - series: 'fabric_api_node_clock_synchronized{job="fabric-api-node",node="dfw-worker",pod="fabric-router-a"}' + values: "1x10 0x4 1x16" + alert_rule_test: + - eval_time: 11m + alertname: FabricAPIClockUnsynchronized + exp_alerts: + - exp_labels: + severity: warning + service: galactic + team: connect + job: fabric-api-gateway + namespace: galactic-system + pod: gw-a + exp_annotations: + summary: "fabric-api on gw-a runs on an unsynchronised clock" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#fabricapiclockunsynchronized" + description: >- + The kernel clock under gw-a has not been synchronised within 500 ms for 10 minutes. A + gateway on it admits no probe and no Looking Glass request; a node on it refuses every probe permit. + Check the host's time daemon (chrony, ntpd, systemd-timesyncd or Talos timed). + + # Two thirds of a busy cell's Looking Glass requests throttled fires; a + # cell refusing as large a share of too few requests does not. + - interval: 30s + input_series: + - series: 'fabric_api_gateway_service_requests_total{job="fabric-api-gateway",namespace="galactic-system",pod="gw-a",operation="Ping",reason="Throttled"}' + values: "0+2x60" + - series: 'fabric_api_gateway_service_requests_total{job="fabric-api-gateway",namespace="galactic-system",pod="gw-a",operation="Ping",reason="Succeeded"}' + values: "0+1x60" + - series: 'fabric_api_gateway_service_requests_total{job="fabric-api-gateway",namespace="fabric-lab",pod="gw-c",operation="Ping",reason="QueueFull"}' + values: "0 1 2 3 4 5 6 7 8 9 10x50" + alert_rule_test: + - eval_time: 15m + alertname: FabricAPIServiceThrottled + exp_alerts: [] + - eval_time: 25m + alertname: FabricAPIServiceThrottled + exp_alerts: + - exp_labels: + severity: warning + service: galactic + team: connect + job: fabric-api-gateway + namespace: galactic-system + exp_annotations: + summary: "Most Looking Glass requests in galactic-system are refused by the cell's limits" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#fabricapiservicethrottled" + description: >- + 66.67% of Looking Glass requests in galactic-system in the last 30 + minutes were refused with Throttled, QueueFull or LimiterUnavailable. fabric_api_gateway_admission_refusals_total + names the scope (cell, project, destination or queue) that refused them. + + # Every executed request failing fires; a cell where a quarter fail, and + # one whose requests were all refused before execution, do not. + - interval: 30s + input_series: + - series: 'fabric_api_gateway_service_requests_total{job="fabric-api-gateway",namespace="galactic-system",pod="gw-a",operation="Ping",reason="ExecutionFailed"}' + values: "0+1x60" + - series: 'fabric_api_gateway_service_requests_total{job="fabric-api-gateway",namespace="galactic-system",pod="gw-a",operation="Ping",reason="Succeeded"}' + values: "0x60" + - series: 'fabric_api_gateway_service_requests_total{job="fabric-api-gateway",namespace="fabric-lab",pod="gw-c",operation="Ping",reason="PartialResults"}' + values: "0+3x60" + - series: 'fabric_api_gateway_service_requests_total{job="fabric-api-gateway",namespace="fabric-lab",pod="gw-c",operation="Ping",reason="ExecutionFailed"}' + values: "0+1x60" + - series: 'fabric_api_gateway_service_requests_total{job="fabric-api-gateway",namespace="fabric-edge",pod="gw-e",operation="Ping",reason="Throttled"}' + values: "0+5x60" + alert_rule_test: + - eval_time: 25m + alertname: FabricAPIServiceExecutionFailing + exp_alerts: + - exp_labels: + severity: warning + service: galactic + team: connect + job: fabric-api-gateway + namespace: galactic-system + exp_annotations: + summary: "Most Looking Glass requests in galactic-system return no router result" + runbook_url: "https://github.com/datum-cloud/infra/blob/main/docs/runbooks/galactic/README.md#fabricapiserviceexecutionfailing" + description: >- + 100% of the Looking Glass requests galactic-system executed in the + last 30 minutes ended ExecutionFailed, NoNodesAvailable, OwnershipLost or Internal. + fabric_api_gateway_service_router_outcomes_total gives each router's failure or omission reason. diff --git a/internal/fabric/gateway/admission.go b/internal/fabric/gateway/admission.go index 6a2e39b8e..f8e70fc57 100644 --- a/internal/fabric/gateway/admission.go +++ b/internal/fabric/gateway/admission.go @@ -37,6 +37,8 @@ type Admission struct { Buckets *limit.Buckets Attempts *limit.Attempts Authority *limit.Authority + // Metrics, when set, counts refusals and charged packets. + Metrics *Metrics // Now returns the current time; nil selects time.Now. Now func() time.Time @@ -80,8 +82,10 @@ func (a *Admission) openStream(project string) (func(), error) { a.projectStreams = map[string]int{} } if a.streams >= a.Limits.Streams || a.projectStreams[project] >= a.Limits.ProjectStreams { - return nil, errcode.Retry(errcode.QueueFull, "the live stream limit is reached", string(limit.ScopeQueue), + err := errcode.Retry(errcode.QueueFull, "the live stream limit is reached", string(limit.ScopeQueue), time.Second) + a.Metrics.refused(project, err) + return nil, err } a.streams++ a.projectStreams[project]++ @@ -95,6 +99,13 @@ func (a *Admission) openStream(project string) (func(), error) { }, nil } +// liveStreams returns the live service streams. +func (a *Admission) liveStreams() int { + a.mu.Lock() + defer a.mu.Unlock() + return a.streams +} + // admit admits a service request before its discovery: it confirms the // election, charges the cell's and the project's request tokens, registers // the attempt key and opens a live stream. It returns the epoch's context @@ -103,16 +114,20 @@ func (a *Admission) admit( ctx context.Context, caller identity.ID, req *servicev1.RunDiagnosticRequest, ) (context.Context, func(), error) { project := req.GetProjectId() + refuse := func(err error) (context.Context, func(), error) { + a.Metrics.refused(project, err) + return nil, nil, err + } _, epochCtx, err := a.Authority.Check(ctx) if err != nil { - return nil, nil, err + return refuse(err) } if err := a.Buckets.ChargeRequest(project, a.now()); err != nil { - return nil, nil, err + return refuse(err) } if err := a.Attempts.Register(attemptKey(caller, req), requestDigest(req), req.GetExpiresAt().AsTime(), a.now()); err != nil { - return nil, nil, err + return refuse(err) } closeStream, err := a.openStream(project) if err != nil { @@ -137,6 +152,7 @@ func (a *Admission) permit( ) (*fabricv1.ProbePermit, error) { epoch, _, err := a.Authority.Check(ctx) if err != nil { + a.Metrics.refused(principal, err) return nil, err } dst, err := query.ResolvedProbe(q) @@ -145,8 +161,10 @@ func (a *Admission) permit( } cost := probeCost(q.Type) if err := a.Buckets.ChargePackets(principal, dst, cost, a.now()); err != nil { + a.Metrics.refused(principal, err) return nil, err } + a.Metrics.charged(principal, cost) return &fabricv1.ProbePermit{ Id: newPermitID(), Epoch: epoch.String(), diff --git a/internal/fabric/gateway/metrics.go b/internal/fabric/gateway/metrics.go index e6cf7d6f9..a10584633 100644 --- a/internal/fabric/gateway/metrics.go +++ b/internal/fabric/gateway/metrics.go @@ -5,16 +5,38 @@ package gateway import ( + "strings" + "github.com/prometheus/client_golang/prometheus" + + servicev1 "go.datum.net/galactic/api/fabric/service/v1" + "go.datum.net/galactic/internal/fabric/errcode" + "go.datum.net/galactic/internal/fabric/gateway/limit" ) -// labelOutcome is the metric label carrying an operation's outcome. -const labelOutcome = "outcome" +// labelOutcome is the metric label carrying an operation's outcome, +// labelOperation the one carrying a Looking Glass request's operation, and +// labelReason the one carrying why something ended or was refused. +const ( + labelOutcome = "outcome" + labelOperation = "operation" + labelReason = "reason" +) // Metrics is the gateway's instrumentation, registered with the // controller-runtime registry so it is served with the manager's metrics. -// Request IDs and targets are never labels. +// 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 + admissionRefusals *prometheus.CounterVec + packetsCharged *prometheus.CounterVec + queries *prometheus.CounterVec nodes *prometheus.CounterVec rpcDuration *prometheus.HistogramVec @@ -33,6 +55,34 @@ type Metrics struct { // NewMetrics builds the gateway metrics; depth reports the executor's queue. func NewMetrics(reg prometheus.Registerer, depth func() float64) *Metrics { m := &Metrics{ + reg: reg, + serviceRequests: prometheus.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{ + 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{ + 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{ + 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{ + 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{ Name: "fabric_api_gateway_queries_total", Help: "FabricQuery executions finished, by query type and terminal reason.", @@ -93,10 +143,101 @@ func NewMetrics(reg prometheus.Registerer, depth func() float64) *Metrics { }), } 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.truncated, m.stageLatency, m.inFlight, m.staleObjects, m.certExpiry, m.credentialsOK, m.serviceRequests, + m.serviceOutcomes, m.serviceDuration, m.admissionRefusals, m.packetsCharged) 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) + })) +} + +// 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) { + for _, state := range []string{limit.StateReady, limit.StateRecovering, limit.StateUnavailable} { + m.reg.MustRegister(prometheus.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) })) + } + keys := func(kind string, n func() int) prometheus.Collector { + return prometheus.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()) }) + } + 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) }), + ) +} + +func boolGauge(b bool) float64 { + if b { + return 1 + } + return 0 +} + +// trafficClass is the traffic class of a budget principal. +func trafficClass(principal string) string { + switch { + case strings.HasPrefix(principal, "operator/"): + return "operator" + case strings.HasPrefix(principal, "fabricquery/"): + return "fabricquery" + } + return "service" +} + +// refused counts an admission refusal of principal's work. Only the +// limiter's own refusals count: Throttled, QueueFull and +// LimiterUnavailable. +func (m *Metrics) refused(principal string, err error) { + if m == nil { + return + } + switch code := errcode.Of(err); code { + case errcode.Throttled, errcode.QueueFull, errcode.LimiterUnavailable: + scope := errcode.Metadata(err)[errcode.MetadataScope] + if scope == "" { + scope = string(limit.ScopeCell) + } + m.admissionRefusals.WithLabelValues(trafficClass(principal), scope, string(code)).Inc() + } +} + +// charged counts packets charged to principal. +func (m *Metrics) charged(principal string, packets int) { + if m != nil { + m.packetsCharged.WithLabelValues(trafficClass(principal)).Add(float64(packets)) + } +} + // QueueWait records a granted wait. func (m *Metrics) QueueWait(seconds float64) { m.queueWait.Observe(seconds) } @@ -104,10 +245,37 @@ func (m *Metrics) QueueWait(seconds float64) { m.queueWait.Observe(seconds) } func (m *Metrics) CertificateExpiry(unix float64) { m.certExpiry.Set(unix) } // CredentialsLoaded records whether credentials are loaded. -func (m *Metrics) CredentialsLoaded(ok bool) { - if ok { - m.credentialsOK.Set(1) - } else { - m.credentialsOK.Set(0) +func (m *Metrics) CredentialsLoaded(ok bool) { m.credentialsOK.Set(boolGauge(ok)) } + +// serviceRequest counts a service request that ended with reason. +func (m *Metrics) serviceRequest(req *servicev1.RunDiagnosticRequest, reason errcode.Code) { + if m != nil { + m.serviceRequests.WithLabelValues(serviceOperation(req), string(reason)).Inc() + } +} + +// serviceOutcome counts a selected router of a service request: OK, or its +// failure's reason. +func (m *Metrics) serviceOutcome(op string, err error) { + if m == nil { + return + } + outcome := "OK" + if err != nil { + outcome = string(errcode.Of(err)) + } + m.serviceOutcomes.WithLabelValues(op, outcome).Inc() +} + +// serviceOmitted counts each router a service request omitted, by its +// reason. +func (m *Metrics) serviceOmitted(op string, routers []Node) { + if m == nil { + return + } + for _, r := range routers { + if !r.Selected { + m.serviceOutcomes.WithLabelValues(op, r.OmittedReason).Inc() + } } } diff --git a/internal/fabric/gateway/permit.go b/internal/fabric/gateway/permit.go index 5d901ea28..6d72329ca 100644 --- a/internal/fabric/gateway/permit.go +++ b/internal/fabric/gateway/permit.go @@ -156,8 +156,10 @@ func (p *Permits) RequestPermit( release, err := p.Executor.Acquire(actx, principal, false) switch { case errors.Is(err, ErrQueueFull): - return nil, errcode.Retry(errcode.QueueFull, "the cell's execution queue is full", string(limit.ScopeQueue), + err := errcode.Retry(errcode.QueueFull, "the cell's execution queue is full", string(limit.ScopeQueue), time.Second) + p.Admission.Metrics.refused(principal, err) + return nil, err case err != nil: return nil, errcode.Status(errcode.QueueTimeout, "waited too long for a cell execution slot") } diff --git a/internal/fabric/gateway/runner.go b/internal/fabric/gateway/runner.go index f1a6567fc..9d26b5411 100644 --- a/internal/fabric/gateway/runner.go +++ b/internal/fabric/gateway/runner.go @@ -288,8 +288,10 @@ func (r *Runner) one(ctx context.Context, project, requestID string, wire *fabri if err != nil { if errors.Is(err, ErrQueueFull) { if r.Admission != nil { - return nil, errcode.Retry(errcode.QueueFull, "the cell's execution queue is full", + err := errcode.Retry(errcode.QueueFull, "the cell's execution queue is full", string(limit.ScopeQueue), time.Second) + r.Admission.Metrics.refused(project, err) + return nil, err } return nil, errcode.Status(errcode.NodeBusy, "cell execution queue is full") } @@ -323,6 +325,7 @@ func (r *Runner) one(ctx context.Context, project, requestID string, wire *fabri } case opts.checkOwnership: if _, _, err := a.Authority.Check(ctx); err != nil { + a.Metrics.refused(project, err) return nil, err } } diff --git a/internal/fabric/gateway/service.go b/internal/fabric/gateway/service.go index 916df2a12..9a79982be 100644 --- a/internal/fabric/gateway/service.go +++ b/internal/fabric/gateway/service.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" "io" + "log/slog" "regexp" "slices" "strings" @@ -244,6 +245,8 @@ type Service struct { Elected func() bool // Leader connects a follower to the leader. Leader LeaderDialer + // Metrics, when set, counts requests and their routers' outcomes. + Metrics *Metrics // Now, when set, replaces the wall clock. Now func() time.Time @@ -367,6 +370,7 @@ func (s *Service) RunDiagnostic( received := s.now() canonical, deadline, err := s.validate(ctx, req, received, received) if err != nil { + s.Metrics.serviceRequest(req, errcode.Of(err)) return err } if !s.Elected() { @@ -390,39 +394,58 @@ type forwarder struct { func (f *forwarder) ForwardDiagnostic( env *forwardv1.ForwardDiagnosticRequest, stream grpc.ServerStreamingServer[servicev1.DiagnosticEvent], ) error { - s := f.s ctx := stream.Context() + svc, canonical, deadline, err := f.accept(ctx, env) + if err != nil { + // A follower counts only what it refused itself, so the leader + // counts the forwarded requests it refuses before executing them. + f.s.Metrics.serviceRequest(env.GetRequest(), errcode.Of(err)) + return err + } + return f.s.execute(ctx, svc, canonical, deadline, stream.Send) +} + +// accept checks a forwarded request's caller, election, envelope and +// request, and returns its service identity, canonical request and +// effective deadline. +func (f *forwarder) accept(ctx context.Context, env *forwardv1.ForwardDiagnosticRequest, +) (identity.ID, *servicev1.RunDiagnosticRequest, time.Time, error) { + s := f.s + fail := func(err error) (identity.ID, *servicev1.RunDiagnosticRequest, time.Time, error) { + return identity.ID{}, nil, time.Time{}, err + } if id, ok := node.CallerFrom(ctx); !ok || id.Role != identity.RoleGateway { - return errcode.Status(errcode.Unauthorized, "only the gateway may forward diagnostics") + return fail(errcode.Status(errcode.Unauthorized, "only the gateway may forward diagnostics")) } if !s.Elected() { - return errcode.Status(errcode.OwnershipLost, "this replica does not lead; forwarded requests are not forwarded again") + return fail(errcode.Status(errcode.OwnershipLost, + "this replica does not lead; forwarded requests are not forwarded again")) } svc, err := identity.Parse(env.GetService()) if err != nil || svc.Role != identity.RoleService || svc.Cell != s.Cell { - return errcode.Status(errcode.Unauthorized, "forwarded request names no service identity of this cell") + return fail(errcode.Status(errcode.Unauthorized, "forwarded request names no service identity of this cell")) } if err := s.Allowlist.Check(svc); err != nil { - return err + return fail(err) } now := s.now() if !env.GetReceivedAt().IsValid() || env.GetReceivedAt().AsTime().After(now.Add(maxForwardSkew)) { - return errcode.Status(errcode.InvalidQuery, "forwarded request has no valid receipt time") + return fail(errcode.Status(errcode.InvalidQuery, "forwarded request has no valid receipt time")) } if !env.GetDeadline().IsValid() { - return errcode.Status(errcode.InvalidQuery, "forwarded request has no deadline") + return fail(errcode.Status(errcode.InvalidQuery, "forwarded request has no deadline")) } canonical, deadline, err := s.validate(ctx, env.GetRequest(), env.GetReceivedAt().AsTime(), now) if err != nil { - return err + return fail(err) } if d := env.GetDeadline().AsTime(); d.Before(deadline) { deadline = d } if !now.Before(deadline) { - return errcode.Status(errcode.DeadlineExceeded, "forwarded request's deadline has passed") + return fail(errcode.Status(errcode.DeadlineExceeded, "forwarded request's deadline has passed")) } - return s.execute(ctx, svc, canonical, deadline, stream.Send) + return svc, canonical, deadline, nil } // serviceCaller returns the authenticated service identity of a call. @@ -550,16 +573,20 @@ func checkFeatures(required, served []string) error { // forward hands a validated request to the leader once, with this replica's // gateway identity, and relays its events under the same write bound as the -// leader's. A forwarded call that fails is never forwarded again. +// leader's. A forwarded call that fails is never forwarded again. The +// leader counts the request; this replica counts it only when no leader +// could be reached. func (s *Service) forward( ctx context.Context, caller identity.ID, req *servicev1.RunDiagnosticRequest, received, deadline time.Time, stream grpc.ServerStreamingServer[servicev1.DiagnosticEvent], ) error { if s.Leader == nil { + s.Metrics.serviceRequest(req, errcode.OwnershipLost) return errcode.Status(errcode.OwnershipLost, "this replica does not lead and cannot forward") } conn, err := s.Leader.LeaderConn(ctx) if err != nil { + s.Metrics.serviceRequest(req, errcode.OwnershipLost) return errcode.Status(errcode.OwnershipLost, err.Error()) } ctx, cancel := context.WithDeadline(ctx, deadline) @@ -603,7 +630,9 @@ func (s *Service) forward( func (s *Service) execute( ctx context.Context, caller identity.ID, req *servicev1.RunDiagnosticRequest, deadline time.Time, send func(*servicev1.DiagnosticEvent) error, -) error { +) (err error) { + rec := serviceRecord{started: s.now()} + defer func() { s.finish(caller, req, &rec, err) }() if !s.now().Before(deadline) { return errcode.Status(errcode.DeadlineExceeded, "request's deadline has passed") } @@ -656,8 +685,10 @@ func (s *Service) execute( } res, err := s.Runner.Executor.Reserve(project, selectedCount(inv.Routers)) if err != nil { - return errcode.Retry(errcode.QueueFull, "the cell's execution queue cannot take this request", + err := errcode.Retry(errcode.QueueFull, "the cell's execution queue cannot take this request", string(limit.ScopeQueue), time.Second) + adm.Metrics.refused(project, err) + return err } defer res.Release() w := newEventWriter(send) @@ -674,6 +705,9 @@ func (s *Service) execute( if err != nil { return err } + rec.inventory = &inv + op := serviceOperation(req) + s.Metrics.serviceOmitted(op, inv.Routers) q := node.QueryFromProto(req.GetQuery()) budgets := req.GetBudgets() @@ -726,13 +760,72 @@ func (s *Service) execute( } ev := out.fit(o, func() { lose(errOutputLimit) }) tally.add(ev) + s.Metrics.serviceOutcome(op, ev.Err) if err := next(outcomeEvent(ev)); err != nil { return stop(err) } } - return next(&servicev1.DiagnosticEvent{Event: &servicev1.DiagnosticEvent_Complete{ - Complete: tally.complete(inv, s.now()), - }}) + rec.complete = tally.complete(inv, s.now()) + return next(&servicev1.DiagnosticEvent{Event: &servicev1.DiagnosticEvent_Complete{Complete: rec.complete}}) +} + +// serviceRecord is what finish reports about a request the leader ran. +type serviceRecord struct { + started time.Time + // inventory is set once the snapshot is delivered. + inventory *Inventory + // complete is the terminal coverage, set before it is sent. + complete *servicev1.Complete +} + +// reasonDeliveryFailed is the reason a request whose stream broke is +// counted and logged with. +const reasonDeliveryFailed = "DeliveryFailed" + +// finish counts a request the leader ran and, once its snapshot was +// delivered, logs it: who asked, for which project, its operation, reason +// and coverage counts and how long it took. The log carries no target, +// observation or node error text. A request refused before its snapshot is +// logged only at debug level. +func (s *Service) finish(caller identity.ID, req *servicev1.RunDiagnosticRequest, rec *serviceRecord, err error) { + reason := reasonDeliveryFailed + switch { + case err == nil && rec.complete != nil: + reason = rec.complete.GetReason() + case errcode.Typed(err): + reason = string(errcode.Of(err)) + } + op := serviceOperation(req) + elapsed := s.now().Sub(rec.started) + s.Metrics.serviceRequest(req, errcode.Code(reason)) + if rec.inventory == nil { + slog.Debug("Looking Glass request refused", "service", caller.Name, "project", req.GetProjectId(), + "requestID", req.GetRequestId(), labelOperation, op, labelReason, reason) + return + } + if s.Metrics != nil { + s.Metrics.serviceDuration.WithLabelValues(op).Observe(elapsed.Seconds()) + } + attrs := []any{ + "service", caller.Name, "project", req.GetProjectId(), "requestID", req.GetRequestId(), + labelOperation, op, labelReason, reason, "routers", len(rec.inventory.Routers), + "selected", selectedCount(rec.inventory.Routers), "duration", elapsed, + } + if c := rec.complete; c != nil { + attrs = append(attrs, "successful", c.GetSuccessful(), "failed", c.GetFailed(), "omitted", c.GetOmitted(), + "truncated", c.GetTruncatedRouters()) + } + slog.Info("Looking Glass request finished", attrs...) +} + +// serviceOperation is a request's operation as a metric label: its query +// type, or Unsupported for one the service does not serve. +func serviceOperation(req *servicev1.RunDiagnosticRequest) string { + t := node.QueryFromProto(req.GetQuery()).Type + if !serviceQueryTypes[t] { + return "Unsupported" + } + return string(t) } func (s *Service) streamLimit() int { diff --git a/internal/fabric/gateway/serviceswitch_test.go b/internal/fabric/gateway/serviceswitch_test.go index 6e93c4fd9..9863369ab 100644 --- a/internal/fabric/gateway/serviceswitch_test.go +++ b/internal/fabric/gateway/serviceswitch_test.go @@ -5,12 +5,17 @@ package gateway import ( + "bytes" "context" "errors" + "log/slog" + "strings" "sync" "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" "k8s.io/apimachinery/pkg/runtime" @@ -19,9 +24,12 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + forwardv1 "go.datum.net/galactic/api/fabric/forward/v1" servicev1 "go.datum.net/galactic/api/fabric/service/v1" "go.datum.net/galactic/internal/fabric/errcode" "go.datum.net/galactic/internal/fabric/gateway/limit" + "go.datum.net/galactic/internal/fabric/identity" + "go.datum.net/galactic/internal/fabric/node" "go.datum.net/galactic/internal/fabric/query" ) @@ -185,3 +193,130 @@ func TestServiceDisableCancelsRunningWork(t *testing.T) { t.Fatalf("operator probe while the service is off: %v", out) } } + +// Routine telemetry carries attribution and counts, never a target, a +// result or node error text, and no metric label names a project, +// request, node or target. +func TestServiceTelemetryCarriesNoPayload(t *testing.T) { + var logs bytes.Buffer + prev := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))) + t.Cleanup(func() { slog.SetDefault(prev) }) + + 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.RegisterService(svc.Switch) + m.RegisterAdmission(adm, func() error { return nil }) + svc.Metrics, svc.Runner.Metrics, adm.Metrics = m, m, m + + ping := string(query.TypePing) + // The project's request burst is 2: the third is throttled. + for i := range 3 { + events, err := collect(t, svc, requestFor(testProject, i+1, nil)) + if i < 2 { + if err != nil { + t.Fatalf("request %d: %v", i, err) + } + if r := events[len(events)-1].GetComplete().GetReason(); r != CompletePartialResults { + t.Fatalf("request %d reason = %q", i, r) + } + continue + } + wantRetry(t, err, errcode.Throttled, string(limit.ScopeProject)) + } + + for labels, want := range map[[2]string]float64{ + {ping, CompletePartialResults}: 2, + {ping, string(errcode.Throttled)}: 1, + } { + if got := testutil.ToFloat64(m.serviceRequests.WithLabelValues(labels[0], labels[1])); got != want { + t.Errorf("service requests %v = %g, want %g", labels, got, want) + } + } + for labels, want := range map[[2]string]float64{ + {ping, "OK"}: 2, + {ping, string(errcode.FRRUnavailable)}: 2, + } { + if got := testutil.ToFloat64(m.serviceOutcomes.WithLabelValues(labels[0], labels[1])); got != want { + t.Errorf("router outcomes %v = %g, want %g", labels, got, want) + } + } + if got := testutil.ToFloat64(m.admissionRefusals.WithLabelValues("service", "project", "Throttled")); got != 1 { + t.Errorf("throttled refusals = %g", got) + } + if got := testutil.ToFloat64(m.packetsCharged.WithLabelValues("service")); got != 4*limit.PingPackets { + t.Errorf("charged packets = %g", got) + } + + forbidden := []string{testProject, testRequestID[:8], "2001:db8", routerA, routerB, podA, "raw failure", + testService} + families, err := reg.Gather() + if err != nil { + t.Fatal(err) + } + for _, f := range families { + for _, metric := range f.GetMetric() { + for _, l := range metric.GetLabel() { + for _, bad := range forbidden { + if strings.Contains(l.GetValue(), bad) { + t.Errorf("%s label %s=%q names %q", f.GetName(), l.GetName(), l.GetValue(), bad) + } + } + } + } + } + + out := logs.String() + for _, bad := range []string{"2001:db8", "raw failure", "replies", "192.0.2.1"} { + if strings.Contains(out, bad) { + t.Errorf("logs carry %q:\n%s", bad, out) + } + } + if strings.Count(out, `"msg":"Looking Glass request finished"`) != 2 || + !strings.Contains(out, `"project":"project-a"`) || !strings.Contains(out, `"reason":"PartialResults"`) || + !strings.Contains(out, `"msg":"Looking Glass request refused"`) { + t.Errorf("logs lack the requests' attribution:\n%s", out) + } +} + +// 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 }) + svc := &Service{Cell: testSite, Allowlist: testAllowlist, Elected: func() bool { return false }, Metrics: m} + bad := validRequest(time.Now()) + bad.ApiMajor = 2 + if _, err := collect(t, svc, bad); errcode.Of(err) != errcode.VersionUnsupported { + t.Fatalf("err = %v", err) + } + if _, err := collect(t, svc, validRequest(time.Now())); errcode.Of(err) != errcode.OwnershipLost { + t.Fatalf("err = %v", err) + } + ping := string(query.TypePing) + + // The leader counts a forwarded request it refuses before executing it. + leader := &Service{Cell: testSite, Allowlist: testAllowlist, Elected: elected, Metrics: m} + gw := node.WithCaller(t.Context(), identity.Gateway(testSite)) + for _, env := range []*forwardv1.ForwardDiagnosticRequest{ + {Service: identity.Service(testSite, testService).URI(), Request: validRequest(time.Now())}, + {Service: "spiffe://fabric-api.datumapis.com/cell/other/service/x", Request: validRequest(time.Now())}, + } { + stream := &chanStream{ctx: gw, events: make(chan *servicev1.DiagnosticEvent, 1)} + if err := leader.Forwarder().ForwardDiagnostic(env, stream); err == nil { + t.Fatal("an invalid forwarded request was accepted") + } + } + for labels, want := range map[[2]string]float64{ + {ping, string(errcode.VersionUnsupported)}: 1, + {ping, string(errcode.OwnershipLost)}: 1, + {ping, string(errcode.InvalidQuery)}: 1, + {ping, string(errcode.Unauthorized)}: 1, + } { + if got := testutil.ToFloat64(m.serviceRequests.WithLabelValues(labels[0], labels[1])); got != want { + t.Errorf("service requests %v = %g, want %g", labels, got, want) + } + } +} diff --git a/internal/fabric/node/metrics.go b/internal/fabric/node/metrics.go index 8b3fffbb0..7ad841049 100644 --- a/internal/fabric/node/metrics.go +++ b/internal/fabric/node/metrics.go @@ -14,8 +14,12 @@ import ( "go.datum.net/galactic/internal/fabric/index" ) -// labelType is the query type label every per-request collector carries. -const labelType = "type" +// labelType is the query type label every per-request collector carries, +// and labelOutcome the label carrying an operation's outcome. +const ( + labelType = "type" + labelOutcome = "outcome" +) // Metrics is the node sidecar's Prometheus instrumentation in a private // registry. Request IDs and targets are never labels. @@ -37,6 +41,7 @@ type Metrics struct { credentialsOK prometheus.Gauge identityRefresh *prometheus.CounterVec bmpMessages prometheus.Counter + permits *prometheus.CounterVec } // NewMetrics builds Metrics with every collector registered. @@ -46,7 +51,7 @@ func NewMetrics() *Metrics { requests: prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_node_requests_total", Help: "Execute calls by query type and outcome (OK or the error code).", - }, []string{labelType, "outcome"}), + }, []string{labelType, labelOutcome}), duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Name: "fabric_api_node_request_duration_seconds", Help: "Execute call duration by query type, including queueing.", @@ -104,14 +109,31 @@ func NewMetrics() *Metrics { identityRefresh: prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "fabric_api_node_identity_refreshes_total", Help: "Reads of FRR version, router ID and ASN, by outcome.", - }, []string{"outcome"}), + }, []string{labelOutcome}), + permits: prometheus.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, collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) + m.identityRefresh, m.permits, collectors.NewGoCollector(), + collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) return m } +// 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) })) +} + // Handler serves the registry. func (m *Metrics) Handler() http.Handler { return promhttp.HandlerFor(m.Registry, promhttp.HandlerOpts{}) diff --git a/internal/fabric/node/permit.go b/internal/fabric/node/permit.go index df40d4266..5a4027f89 100644 --- a/internal/fabric/node/permit.go +++ b/internal/fabric/node/permit.go @@ -77,6 +77,8 @@ type Permits struct { // Clock, when set, reports an error while this host's clock cannot be // trusted within limit.MaxClockError; every permit is then refused. Clock func() error + // Metrics, when set, counts each permit decision. + Metrics *Metrics mu sync.Mutex consumed map[string]consumedPermit @@ -94,51 +96,80 @@ type grant struct { deadline time.Time } +// Permit decisions, as fabric_api_node_permits_total's outcome label +// reports them. +const ( + PermitAccepted = "accepted" + permitInvalid = "invalid" + permitMalformed = "malformed" + permitMismatch = "mismatch" + permitExpired = "expired" + permitStarting = "starting" + permitClock = "clock" + permitLease = "lease" + permitEpoch = "epoch" + permitReplayed = "replayed" + permitFull = "full" +) + // consume verifies p for q on node and records it consumed. func (p *Permits) consume(ctx context.Context, pm *fabricv1.ProbePermit, node, requestID string, q query.Query, now time.Time) (grant, error) { - refuse := func(msg string) (grant, error) { + refuse := func(outcome, msg string) (grant, error) { + p.observe(outcome) return grant{}, errcode.Status(errcode.LimiterUnavailable, msg) } dst, err := query.ResolvedProbe(q) if err != nil { + p.observe(permitInvalid) return grant{}, errcode.FromError(err) } deadline := pm.GetDeadline().AsTime() switch { case pm.GetId() == "" || !pm.GetDeadline().IsValid(): - return refuse("the probe permit is malformed") + return refuse(permitMalformed, "the probe permit is malformed") case pm.GetNode() != node || pm.GetRequestId() != requestID || pm.GetOperation() != QueryToProto(q).GetType() || pm.GetDestination() != dst.String(): - return refuse("the probe permit does not match this probe") + return refuse(permitMismatch, "the probe permit does not match this probe") case !now.Before(deadline) || deadline.Sub(now) > MaxPermitLifetime: - return refuse("the probe permit has expired or is too long-lived") + return refuse(permitExpired, "the probe permit has expired or is too long-lived") case p.starting(now): - return refuse("this node accepts no probe permit until its startup refusal ends") + return refuse(permitStarting, "this node accepts no probe permit until its startup refusal ends") case p.Clock != nil && p.Clock() != nil: - return refuse("this node's clock is not synchronised") + return refuse(permitClock, "this node's clock is not synchronised") } epoch, err := limit.ReadEpoch(ctx, p.Reader, p.Namespace, p.LeaseName, now) if err != nil { + p.observe(permitLease) return grant{}, err } if epoch.String() != pm.GetEpoch() { + p.observe(permitEpoch) return grant{}, errcode.Status(errcode.OwnershipLost, "the probe permit is from another gateway epoch") } - if err := p.record(pm.GetId(), deadline.Add(PermitGrace), now); err != nil { + if outcome, err := p.record(pm.GetId(), deadline.Add(PermitGrace), now); err != nil { + p.observe(outcome) return grant{}, err } + p.observe(PermitAccepted) return grant{packets: int(pm.GetPackets()), deadline: deadline}, nil } +func (p *Permits) observe(outcome string) { + if p.Metrics != nil { + p.Metrics.permits.WithLabelValues(outcome).Inc() + } +} + // starting reports whether the node is still in its startup refusal. func (p *Permits) starting(now time.Time) bool { return now.Before(p.Started.Add(PermitStartupRefusal)) } // record adds id to the consumed set, refusing a consumed ID and failing -// closed when the set is full of live entries. -func (p *Permits) record(id string, until, now time.Time) error { +// closed when the set is full of live entries. A refusal returns its +// outcome. +func (p *Permits) record(id string, until, now time.Time) (string, error) { maxN, maxBytes := p.MaxConsumed, p.MaxConsumedBytes if maxN <= 0 { maxN = DefaultConsumedPermits @@ -152,7 +183,7 @@ func (p *Permits) record(id string, until, now time.Time) error { p.consumed = map[string]consumedPermit{} } if c, ok := p.consumed[id]; ok && now.Before(c.until) { - return errcode.Status(errcode.LimiterUnavailable, "the probe permit was already used") + return permitReplayed, errcode.Status(errcode.LimiterUnavailable, "the probe permit was already used") } size := len(id) + consumedOverhead if len(p.consumed) >= maxN || p.bytes+size > maxBytes { @@ -164,11 +195,11 @@ func (p *Permits) record(id string, until, now time.Time) error { } } if len(p.consumed) >= maxN || p.bytes+size > maxBytes { - return errcode.Status(errcode.LimiterUnavailable, "this node's consumed-permit set is full") + return permitFull, errcode.Status(errcode.LimiterUnavailable, "this node's consumed-permit set is full") } p.consumed[id] = consumedPermit{until: until, size: size} p.bytes += size - return nil + return "", nil } // obtain asks the gateway for a permit for a direct operator's probe. A diff --git a/internal/fabric/node/permit_test.go b/internal/fabric/node/permit_test.go index 9d58aa9b3..94baa0bc2 100644 --- a/internal/fabric/node/permit_test.go +++ b/internal/fabric/node/permit_test.go @@ -14,6 +14,7 @@ import ( "testing" "time" + "github.com/prometheus/client_golang/prometheus/testutil" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/timestamppb" coordinationv1 "k8s.io/api/coordination/v1" @@ -115,7 +116,8 @@ func permitFor(req *fabricv1.ExecuteRequest) *fabricv1.ProbePermit { func TestPermitConsumedOnce(t *testing.T) { prober := &packetProber{packets: 3} - s := permitServer(t, prober, nil) + metrics := NewMetrics() + s := permitServer(t, prober, func(p *Permits) { p.Metrics = metrics }) ctx := WithCaller(t.Context(), identity.Gateway("dfw")) req := request(query.Query{Type: query.TypePing, Target: testPingDst}) @@ -133,6 +135,11 @@ func TestPermitConsumedOnce(t *testing.T) { if n := prober.sent.Load(); n != 3 { t.Errorf("sent %d packets, want 3", n) } + for outcome, want := range map[string]float64{PermitAccepted: 1, permitReplayed: 1} { + if n := testutil.ToFloat64(metrics.permits.WithLabelValues(outcome)); n != want { + t.Errorf("%s permits = %g, want %g", outcome, n, want) + } + } if info, _ := s.Info(ctx, &fabricv1.InfoRequest{}); !info.GetProbePermits() { t.Error("Info does not report probe permits") } @@ -141,45 +148,64 @@ func TestPermitConsumedOnce(t *testing.T) { func TestPermitRefusals(t *testing.T) { ctx := WithCaller(t.Context(), identity.Gateway("dfw")) cases := map[string]struct { - mod func(*fabricv1.ProbePermit) - perm func(*Permits) - code errcode.Code + mod func(*fabricv1.ProbePermit) + perm func(*Permits) + code errcode.Code + outcome string }{ "other epoch": { mod: func(p *fabricv1.ProbePermit) { p.Epoch = "lease-uid/gateway-1_b" }, - code: errcode.OwnershipLost, + code: errcode.OwnershipLost, outcome: permitEpoch, + }, + "other node": { + mod: func(p *fabricv1.ProbePermit) { p.Node = "other" }, + code: errcode.LimiterUnavailable, outcome: permitMismatch, + }, + "other request": { + mod: func(p *fabricv1.ProbePermit) { p.RequestId = "x" }, + code: errcode.LimiterUnavailable, outcome: permitMismatch, }, - "other node": {mod: func(p *fabricv1.ProbePermit) { p.Node = "other" }, code: errcode.LimiterUnavailable}, - "other request": {mod: func(p *fabricv1.ProbePermit) { p.RequestId = "x" }, code: errcode.LimiterUnavailable}, "other dest": { mod: func(p *fabricv1.ProbePermit) { p.Destination = "9.9.9.9" }, - code: errcode.LimiterUnavailable, + code: errcode.LimiterUnavailable, outcome: permitMismatch, }, "other operation": { mod: func(p *fabricv1.ProbePermit) { p.Operation = fabricv1.QueryType_QUERY_TYPE_TRACEROUTE }, - code: errcode.LimiterUnavailable, + code: errcode.LimiterUnavailable, outcome: permitMismatch, }, "expired": {mod: func(p *fabricv1.ProbePermit) { p.Deadline = timestamppb.New(time.Now().Add(-time.Second)) - }, code: errcode.LimiterUnavailable}, + }, code: errcode.LimiterUnavailable, outcome: permitExpired}, "too long-lived": {mod: func(p *fabricv1.ProbePermit) { p.Deadline = timestamppb.New(time.Now().Add(time.Minute)) - }, code: errcode.LimiterUnavailable}, - "no id": {mod: func(p *fabricv1.ProbePermit) { p.Id = "" }, code: errcode.LimiterUnavailable}, - "startup refusal": {perm: func(p *Permits) { p.Started = time.Now() }, code: errcode.LimiterUnavailable}, + }, code: errcode.LimiterUnavailable, outcome: permitExpired}, + "no id": { + mod: func(p *fabricv1.ProbePermit) { p.Id = "" }, + code: errcode.LimiterUnavailable, outcome: permitMalformed, + }, + "startup refusal": { + perm: func(p *Permits) { p.Started = time.Now() }, + code: errcode.LimiterUnavailable, outcome: permitStarting, + }, "clock unsynchronised": { perm: func(p *Permits) { p.Clock = func() error { return errors.New("unsynchronised") } }, - code: errcode.LimiterUnavailable, + code: errcode.LimiterUnavailable, outcome: permitClock, }, "lease unreadable": {perm: func(p *Permits) { p.Reader = leaseReader(t, "gateway-0_a") p.LeaseName = "missing" - }, code: errcode.OwnershipLost}, + }, code: errcode.OwnershipLost, outcome: permitLease}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { prober := &packetProber{packets: 3} - s := permitServer(t, prober, tc.perm) + metrics := NewMetrics() + s := permitServer(t, prober, func(p *Permits) { + p.Metrics = metrics + if tc.perm != nil { + tc.perm(p) + } + }) req := request(query.Query{Type: query.TypePing, Target: testPingDst}) req.Permit = permitFor(req) if tc.mod != nil { @@ -190,6 +216,12 @@ func TestPermitRefusals(t *testing.T) { if prober.sent.Load() != 0 { t.Error("a refused permit sent packets") } + if n := testutil.ToFloat64(metrics.permits.WithLabelValues(tc.outcome)); n != 1 { + t.Errorf("%s refusals counted %g times", tc.outcome, n) + } + if n := testutil.ToFloat64(metrics.permits.WithLabelValues(PermitAccepted)); n != 0 { + t.Errorf("a refused permit counted as accepted") + } }) } } @@ -364,3 +396,23 @@ func TestDirectOperatorPermit(t *testing.T) { t.Error("a starting node requested a permit") } } + +// A probe whose target is not a probe destination is counted as invalid, +// not as a permit that does not match. +func TestPermitInvalidTarget(t *testing.T) { + metrics := NewMetrics() + p := &Permits{Reader: leaseReader(t, "gateway-0_a"), Namespace: leaseNS, LeaseName: leaseName, + Started: time.Now().Add(-time.Hour), Metrics: metrics} + q := query.Query{Type: query.TypePing, Target: "not-an-address"} + pm := &fabricv1.ProbePermit{Id: "permit", Epoch: leaseEpoch, Node: testNode, + Deadline: timestamppb.New(time.Now().Add(20 * time.Second))} + if _, err := p.consume(t.Context(), pm, testNode, "req", q, time.Now()); err == nil { + t.Fatal("a permit for an invalid target was accepted") + } + if n := testutil.ToFloat64(metrics.permits.WithLabelValues(permitInvalid)); n != 1 { + t.Errorf("invalid permits = %g", n) + } + if n := testutil.ToFloat64(metrics.permits.WithLabelValues(permitMismatch)); n != 0 { + t.Errorf("an invalid target counted as a mismatch") + } +}