diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 061337012..c0bc96111 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -240,6 +240,27 @@ jobs: hack/service-api-bundle.sh ci dist cd dist && sha256sum -c SHA256SUMS + # The opt-in Kustomize Components that must be listed in order fail their + # build when one is missing; tests/manifests renders each composition. + manifests: + name: Manifests + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + + - uses: arduino/setup-task@v3.0.0 + with: + version: ${{ env.TASK_VERSION }} + repo-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Render the Component fixtures + run: task test:manifests + # Tier 2: Integration tests (every PR, main branch, and releases) test-e2e: name: E2E Tests diff --git a/AGENTS.md b/AGENTS.md index 8d1922349..e29471afe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,11 +99,11 @@ See [docs/node-labels.md](docs/node-labels.md) for the full strategy — why `ga - **`config/galactic-nat/`** — the sharded egress translation (NAT66/NAT64) control plane, one `galactic-nat` DaemonSet per cluster on every node labeled both `galactic.datumapis.com/node: edge` and `galactic.datumapis.com/nat: enabled`, alongside `galactic-vrf`. It is independent of `galactic-gateway`. A shard's identity (SID, masquerade addresses, NAT64 prefix) comes from the `EgressShard` targeting its node, not from the DaemonSet. The base leaves `GALACTIC_NAT_XDP_ATTACH` at its default, `direct`. On a node that also runs the gateway, set it to `dispatch`: an interface takes one native XDP program, so the shard and the gateway (which defaults to `GALACTIC_GATEWAY_XDP_ATTACH=dispatch`) each run from their own slot of the node's shared, pinned XDP dispatcher (`internal/plumbing/ebpf/xdpdispatch`), and either can restart or be turned off (`GALACTIC_*_DATAPATH_ENABLED=false`) without touching the other's traffic. `hack/xdp-dispatch-release.sh` detaches the dispatcher from a node. Compute nodes reach their own site's shards over SRv6: by default each VRF uses the first reachable shard in `GALACTIC_CNI_EGRESS_SHARD_SIDS`; with `GALACTIC_CNI_EGRESS_MODE=hashed` on `galactic-cni`, `usid_egress` spreads tenant addresses across the cluster's `EgressShard`s through one immutable Maglev snapshot per translation class (NAT66, and each NAT64 prefix, holding only the shards that can translate it) and per-address pins, and `spec.drain` takes a shard out of rotation without breaking its pinned sessions; delete a shard only after draining it (see [docs/nat/configuration.md](docs/nat/configuration.md#active-active-egress) and the rollout checklist [docs/nat/active-active-rollout.md](docs/nat/active-active-rollout.md)). `kubectl apply -k config/galactic-nat/` applies only the ServiceAccount/RBAC; `base/` is excluded because uplink auto-detection is deployment-specific (see `config/galactic-nat/kustomization.yaml`). Not part of the root `config/kustomization.yaml`. - **`config/fabric-router/`** — the FRR underlay eBGP DaemonSet (`fabric-router`; `galactic-router` needs a working underlay before it can start). Unlike `config/galactic-router/`, this is a single flat DaemonSet with no `default`/`rr`-style role split — its affinity matches any node labeled `galactic.datumapis.com/fabric: router` (a dedicated mode-enum label, independent of whatever `galactic.datumapis.com/node` role value or `galactic.datumapis.com/galactic` mode that node also carries) directly, since there's no env/config difference between running on a regular node vs. those roles — fabric-router itself is identical everywhere; only the per-node BGP underlay config it reads from the ConfigMap differs. That affinity can legitimately match more than one node per cluster, and BGP underlay config (hostname, router-id, interface addresses, remote-AS) inherently differs per physical node — so each node's config lives in its own `fabric-router.` ConfigMap (a `frr.conf` key, plus optional `daemons`/`vtysh.conf` overrides of the image defaults) rather than one shared ConfigMap for the whole DaemonSet. `fabric-config-agent` (`cmd/fabric-config-agent`, `internal/fabricconfig`, built into the `fabric-router` image) reads it from the API: as the `frr-init` init container it validates (`vtysh -C`) and installs it, holding the pod in `Init` until a valid one exists; as the `config-agent` sidecar it applies later changes live with `frr-reload.py`, so an edit to one node's ConfigMap neither restarts the pod nor touches other nodes, and reports `Applied`/`Rejected`/`ReloadFailed`/`RestartRequired` events on the ConfigMap. The sidecar also hard-resets any IPv6 session announcing an IPv4-mapped next hop (`internal/fabricconfig/nexthop.go`) and serves that check's metrics, with the activation path's (`internal/fabricconfig/metrics.go`), on the node's port `9343`. A third container, `frr-exporter` (upstream `tynany/frr_exporter`, pinned by digest), reads the daemons' vty sockets in the same pod-scoped `/run/frr` and serves BGP peer state, message counters and prefix counts for both underlay families on the node's port `9342` (`hostNetwork`); `task verify:fabric-metrics` in `deploy/containerlab/` checks it on every lab node. The image's default `daemons` loads bgpd's BMP module (`-M bmp`), so a node's `frr.conf` can stream to a BMP collector (`config/bmp-collector/`) with a `bmp targets` block; loading it alone streams nothing, and a change to the modules needs a pod restart rather than a reload. Every lab node's `frr.conf` streams its pre-policy Adj-RIB-In and Loc-RIB for both families, sourced from `lo` (`source-interface lo`), since the underlay carries loopbacks but not link subnets. Production `frr.conf`s come from infra's renderer, which has to emit the same block for production nodes to stream. A node with no ConfigMap of its own falls back, with a `DeprecatedConfigSource` warning, to key `frr.conf.` of the legacy shared `fabric-config` ConfigMap. **Not** part of the root `config/kustomization.yaml` and not covered by `kubectl apply -k config/` — unlike every other component here, it has no generic default: the deployer must hand-author one `fabric-router.` ConfigMap per matching node before applying `kubectl apply -k config/fabric-router/` (which also applies the agent's ServiceAccount and its namespaced Roles: `fabric-router` for events, `fabric-router-configmaps` for the ConfigMap reads). Once every node runs from the API (`config/fabric-router/components/activation`, see `config/fabric-router-controller/` below), the opt-in Component `config/fabric-router/components/configmap-retired`, listed after `components/activation` (the build fails otherwise), retires the ConfigMap path: it sets `FABRIC_CONFIGMAPS=false` on both agent containers and deletes the `fabric-router-configmaps` Role and RoleBinding, so the agent never reads, watches or raises events on a ConfigMap, `frr-init` starts a node only from its checkpoint or its deployment's active revision and never falls back to a ConfigMap, and a deployment asking to leave CRD is reported as `ConfigMapRetired` rather than handed off; applying or removing it restarts FRR like the activation Component (see [docs/fabric-routing/operations.md](docs/fabric-routing/operations.md#retiring-the-configmap-path)). The opt-in Component `config/fabric-router/components/fabric-api` adds the fabric-api sidecar to this DaemonSet's pod (see `config/fabric-api/` below); applying it, and every later fabric-api image change, recreates the pod and restarts FRR with it, so roll it out as a routing change. - **`config/bmp-collector/`** — a single-replica GoBMP Deployment and its `bmp-collector` Service (TCP `5000`), the BMP (RFC 7854) collector `galactic-router` and `fabric-router` stream to; `galactic-router` does so when `GALACTIC_ROUTER_BMP_STATIONS` names it (`bmp-collector.galactic-system.svc:5000`; see [docs/router/configuration.md](docs/router/configuration.md)). It parses every Peer Up/Down, route-monitoring and statistics message to JSON on stdout, so the cluster's log pipeline is its store; an overlay swapping `--dump=console` for `--kafka-server` publishes to Kafka instead. Opt-in, like `config/fabric-router/`: not part of the root `config/kustomization.yaml`, since nothing streams to it until a router is configured to. The containerlab lab runs one on `iad-worker3`'s host network (`deploy/containerlab/resources/bmp-collector/iad/`), because its three clusters cannot reach each other's Services, and points every node's `fabric-router` and the EVPN route reflector at it. Of the `galactic-router`s, only the reflector streams: its pre-policy Adj-RIB-In already holds every node's advertisements. -- **`config/fabric-api/`** — the fabric looking glass's cell-wide prerequisites and per-cell gateway. `kubectl apply -k config/fabric-api/` applies only the `fabric-api-gateway` and `fabric-api-janitor` ServiceAccounts and RBAC (the janitor's delete access is deliberately a separate identity from the gateway's, which can only read `FabricQuery` and write its status); safe and idempotent in any cell. `config/fabric-api/base/` (the 2-replica leader-elected gateway Deployment, its ClusterIP debug Service, a PodDisruptionBudget and the `*/15` janitor CronJob) is **not** included in that kustomization and is **not** applied as-is, for the same reason as `config/galactic-gateway/base/`: it needs per-cell values — a `fabric-api` ConfigMap (`site`, `cell`, `cluster-name`) and the cell name in its certificate's URI SAN — supplied by a per-cell overlay; see `deploy/containerlab/resources/fabric-api/gateway/` for a worked example. `config/fabric-api/crd/` is a generated `FabricQuery` CRD for the lab and tests only; infra owns the CRD (and the per-cell `fabric-api` cert-manager `Issuer`) in every cell. The node sidecar is the `config/fabric-router/components/fabric-api` Component, which also adds a `fabric-api-certs` DaemonSet (`fabric-api certsync`) that owns the cert-manager csi-driver volume and copies the certificate to the node's `/run/fabric-api/tls` for the sidecar: a csi volume blocks its pod until the certificate is issued, so keeping it out of the `fabric-router` pod means a broken Issuer stalls only the certs pod, never FRR. The overlay's `CELL_NAME` replacement applies to that DaemonSet's `fabric-api-csi` volume. Not part of the root `config/kustomization.yaml`: fabric-api is opt-in. See [docs/fabric-api/configuration.md](docs/fabric-api/configuration.md) and [docs/fabric-api/api.md](docs/fabric-api/api.md). +- **`config/fabric-api/`** — the fabric looking glass's cell-wide prerequisites and per-cell gateway. `kubectl apply -k config/fabric-api/` applies only the `fabric-api-gateway` and `fabric-api-janitor` ServiceAccounts and RBAC (the janitor's delete access is deliberately a separate identity from the gateway's, which can only read `FabricQuery` and write its status); safe and idempotent in any cell. `config/fabric-api/base/` (the 2-replica leader-elected gateway Deployment, its ClusterIP debug Service, a PodDisruptionBudget and the `*/15` janitor CronJob) is **not** included in that kustomization and is **not** applied as-is, for the same reason as `config/galactic-gateway/base/`: it needs per-cell values — a `fabric-api` ConfigMap (`site`, `cell`, `cluster-name`) and the cell name in its certificate's URI SAN — supplied by a per-cell overlay; see `deploy/containerlab/resources/fabric-api/gateway/` for a worked example. `config/fabric-api/crd/` is a generated `FabricQuery` CRD for the lab and tests only; infra owns the CRD (and the per-cell `fabric-api` cert-manager `Issuer`) in every cell. The node sidecar is the `config/fabric-router/components/fabric-api` Component, which also adds a `fabric-api-certs` DaemonSet (`fabric-api certsync`) that owns the cert-manager csi-driver volume and copies the certificate to the node's `/run/fabric-api/tls` for the sidecar: a csi volume blocks its pod until the certificate is issued, so keeping it out of the `fabric-router` pod means a broken Issuer stalls only the certs pod, never FRR. The overlay's `CELL_NAME` replacement applies to that DaemonSet's `fabric-api-csi` volume. Aggregate probe budgets and the Looking Glass service are opt-in Components, each failing the build without the one before it: `config/fabric-router/components/fabric-api-permits` (sidecar `--probe-permits`, its token and `get` on the gateway's Lease), `config/fabric-api/components/aggregate-budgets` (gateway `--aggregate-budgets`), `config/fabric-router/components/fabric-api-require-permits`, then `config/fabric-api/components/service`, whose `fabric-api-service` ConfigMap (`service: enabled|disabled`, created once by Flux and never overwritten) switches Looking Glass execution at run time, cancelling running requests within 2 s without touching operator or `FabricQuery` work. The gateway's limit flags may only lower the contract's defaults, and the leader and nodes fail closed while the kernel clock is unsynchronised; `task test:manifests` renders the Components from `tests/manifests/`. Not part of the root `config/kustomization.yaml`: fabric-api is opt-in. See [docs/fabric-api/configuration.md](docs/fabric-api/configuration.md) and [docs/fabric-api/api.md](docs/fabric-api/api.md). - **`config/fabric-router-controller/`** — `fabric-router-controller`, the fabric routing control plane. `kubectl apply -k config/fabric-router-controller/` applies only its ServiceAccount and RBAC; `base/` is its leader-elected Deployment, which compiles every fabric-class `BGPRouter` into immutable `FabricRouterRevision`s, and the `components/rollout` Component adds `--rollout` (one `FabricRouterDeployment` per router and the release-authorization controller). Its only Secret access is `get` in `galactic-system`, used to read the UID of each credential a released revision names, so a release refuses a revoked or missing one. The `components/topology` Component adds `--topology` and the only grant that lets it write `BGPPeer`s, a Role in `galactic-system` (the one namespace `--topology-namespace` serves): it generates each cell's fabric peers from `FabricTopology` relationships (mesh, route reflection, external) over `FabricEndpoint` records, one per router per transport network, which every cell of a routing domain holds for every cell's routers. Each cell generates only its own side from its copy of the records, so both ends agree only while every cell holds the same records and relationships (compare each topology's `status.recordsDigest` and `status.relationshipsDigest`). Generated peers carry labels and the topology's UID, never an owner reference, and a session is its router and address, so renames update a peer in place. It never touches a peer it did not create, and keeps a session it no longer generates until an end is retired, deleted (confirmed with the API server, after a settle period, and held when most of a topology's peers would go at once) or drained. Nothing writes the records but their authors today: there is no authoritative endpoint source (see [docs/fabric-routing/topology.md](docs/fabric-routing/topology.md)). The node side is the `config/fabric-router/components/activation` Component, which turns on `fabric-config-agent`'s activation path and mounts its host state directory. Opt-in, not part of the root `config/kustomization.yaml`. See [docs/fabric-routing/operations.md](docs/fabric-routing/operations.md). - **`config/crd/`** and **`config/galactic-controller/`** — the consolidated `galactic.datumapis.com` CRDs and controller deployments. `galactic-controller --role=cell` serves the traffic-policy and pod-injection webhooks and reconciles the cloud resources; `--role=fabric` runs the central identity allocator with its own hub credentials. Apply the CRDs before either controller and follow [the API group migration guide](docs/migration/galactic-api-consolidation.md) for existing clusters. The node side of traffic policy remains in `galactic-router` with `GALACTIC_ROUTER_TRAFFIC_POLICY=true`. - **`config/galactic-edge/`** — the Galactic Edge attachment lifecycle (see [the provider contract](docs/enhancements/networking/galactic-edge/contract.md)). Core is `galactic-controller --role=cell --edge` (`internal/edge/attachment`): it admits each `EdgeAttachment` from uncached reads of its `EdgeService`, `EdgeInstance`, Pod, VPC and `EdgeProvider`, allocates its address from the service's `clientPool` into the service's `status.allocations` with a resourceVersion precondition, drains it (`Draining`, deleted after `drainSeconds`) when its authority ends, and holds it with a finalizer until its node reports `Released`; missing tenant state refuses, never defaults. The node half is the `galactic-edge` DaemonSet (`cmd/galactic-edge`, `internal/edge/agent`) on nodes labeled `galactic.datumapis.com/node=edge` and `galactic.datumapis.com/edge=enabled`: it finds each provider pod's network namespace through the CRI socket, programs the attachment with `hostattach`, registering the host link under its VPC's existing uSID entry, with its traffic policy row, before the link comes up, reads it back, then reports `Programmed`; on deletion it releases only links stamped with that attachment's ID. It also keeps a local pass-through `egress_route_table` entry, owned by `egressroutemap.PassThroughEdge`, for each link's address, each prefix whose gate is open on it and each prefix of a route accepted on the node for its attachment and not released, so the VPC's workloads on the same node reach them, or are dropped at the VRF's unreachable default while the gate is closed, instead of matching the VPC's `::/0` shard route, and `galactic-router`'s withdrawals leave those entries; the address itself is never published. Every VPC on the node is one write-fence scope (`internal/edge/ownership`, host directory `/var/lib/galactic-edge/ownership`), taken over with Fence and Adopt on restart. An edge attachment joins its VPC's canonical host VRF, so `galactic-router`'s GC keeps that VRF and its `BGPVRFInstance` while an `EdgeAttachment` on the node is not `Released` or a stamped link remains, and deletes them only under the VPC's fence after checking again (`internal/edge/maintenance`); `galactic-router` mounts the same directory, and without it GC reclaims no VRF or `BGPVRFInstance`. `galactic-cni`'s `vrf_table` sweep keeps every entry a stamped edge link resolves to. No lab or end-to-end environment deploys the agent yet; the real-kernel unit tests run it. Forwarding beyond an attachment's own address is claimed per prefix: a provider renews its instance's lease, a `coordination.k8s.io/v1` Lease the `EdgeInstance` owns, and claims an `EdgeRoute` (`internal/edge/provider`), core accepts one holder per prefix through the VPC's `EdgeRouteIndex` (`internal/edge/route`), and the agent keeps that prefix's forwarding gate in the uSID datapath open only until the lease's deadline, so forwarding stops on time with the provider, agent or API server stalled; see the contract's Forwarding claim, Acceptance and Timing sections. A route is refused, or revoked, when it overlaps a workload subnet of the VPC, another service's client pool or another attachment's address, or when an earlier service's granted prefixes overlap its own service's: grants are exclusive in a VPC. Core publishes each accepted route as a `BGPAdvertisement` in `galactic-system` naming the holder's host link, and `galactic-router` advertises it only while that link's gate for the prefix is open on its node, polled every 250 ms from the pinned map (contract's Prefix conflicts and Publication sections). `galactic-router`'s traffic policy reconciler binds to each link the policies the attachment's `EdgeService` names in `spec.trafficPolicy`, resolved in the service's namespace (see [Edge attachments](docs/traffic-policy/node.md#edge-attachments)). Core also reports `Admitted` and `TrafficPolicyResolved` on each `EdgeService` and, per approved `EdgeProvider`, keeps a binding of the `galactic-edge-provider` ValidatingAdmissionPolicy (the provider as its parameter) and RoleBindings of the `galactic-edge-provider` ClusterRole for its listed ServiceAccounts, removed when approval is withdrawn. `kubectl apply -k config/galactic-edge/`, which must precede `--edge`, applies the agent's ServiceAccount and RBAC, the controller's edge role (with a Role in `galactic-system` for the route advertisements), that ClusterRole and the policies, which hold a provider ServiceAccount to its own `providerRef`, namespace and pod (a route to its claiming pod, which another pod may only replace at a higher epoch, and an instance's Lease to its pod), hold every writer of an instance Lease to the claim's ordering (`galactic-edge-lease`), and hold each `galactic-edge` status write to its own node (a route's only `closedEpoch`); `base/` needs a per-cell `--mtu` overlay. Opt-in, not part of the root `config/kustomization.yaml`. Diagnostics (`internal/edge/diag`): core and the agent record one Warning Event per transition into a failed stage (admission, allocation, programming, policy, route, and each open gate the agent closes, with its cause), whose note ends in fixed `key=value` correlation fields (provider, service, attachment and pod UIDs, node, route, prefix, epoch), and export `galactic_edge_foundation_*` state and failure metrics labeled only by approved provider, state, stage, cause and reason; [docs/edge/troubleshooting.md](docs/edge/troubleshooting.md) walks them. -- **`config/monitoring/`** — Prometheus Operator resources for BGP and NAT: a `fabric-router` PodMonitor (frr-exporter, port `frr-metrics`/`9342`, as `job=fabric-router`; fabric-config-agent, port `agent-metrics`/`9343`, as `job=fabric-config-agent`), a `galactic-router` PodMonitor covering both roles (port `metrics`/`9179`), a `galactic-nat` PodMonitor for the egress shards (port `metrics`/`9182`), each adding a `node` label, and the `galactic-bgp` PrometheusRule: underlay session down, administratively down for an hour, flapping, received prefixes halved, exporter collector or scrape failing, a session announcing an IPv4-mapped next hop, BGP routes not installed, the agent's metrics scrape down, a `galactic-router` BMP station or metrics scrape down, `galactic-router` routes failing to install, an egress shard's session table evicting live sessions, an egress shard out of masquerade ports, a stalled or persistently lossy NIC receive queue on a `galactic-nat` uplink (#673), and a `galactic-nat` metrics scrape down. For fabric routing through the API it adds a `fabric-router-controller` PodMonitor (port `metrics`/`9185`, `honorLabels` so the fleet series keep their objects' `namespace`), whose leader exports `galactic_fabric_routing_*` (each `FabricRouterDeployment`'s source, epochs, heartbeat, conditions and staged candidate, each outstanding release, each fabric router's compile result) beside the agent's activation, staging, writer-lock and boot-source metrics on `9343`, and a `fabric-routing` rule group (no eligible recovery, otherwise degraded, recovery conflict, agent heartbeat stale on Shadow/CRD, failed release blocking its domain, release Unknown, handoff pending, promotion refused by the agent, candidate rejected, revision refused, the leader unable to read a kind from its cache, controller scrape down — each reads the fleet series over 2 minutes and aggregates away only `pod` and `instance`, so a leader change does not reset it and an alert keeps its `cluster` and other external labels, and none fires on a cluster that keeps its nodes on ConfigMaps). For Galactic Edge it adds `galactic-controller` (port `metrics`/`9184`) and `galactic-edge` (port `metrics`/`9186`) PodMonitors and a `galactic-edge` rule group (attachments not programmed, service policy unresolved, ownership scope lost, cleanup failing, scrape down). For the opt-in fabric-api it adds the `fabric-router` PodMonitor's `api-metrics` endpoint (the sidecar, port `api-metrics`/`9345`, as `job=fabric-api-node`), a `fabric-api-gateway` PodMonitor (port `metrics`/`9347`) and a `fabric-api` rule group (stalled execution, node diagnostics unavailable, nodes unreachable, oversized results, cleanup backlog, certificate renewal failing, credentials missing, search index unsynced, scrape down — none fires merely because nobody ran a query). Requires the `monitoring.coreos.com` CRDs, which this repo does not install, so it is not part of the root `config/kustomization.yaml`. `task test:alerts` unit-tests the rules with `promtool` (`config/monitoring/tests/`). Every alert carries what infra's alerting standard checks for (`service: galactic`, `team: connect`, `runbook_url` into infra's `docs/runbooks/galactic/README.md`). The PrometheusRule here is the tested source, not where the rules run on Datum's infra: there the PodMonitors are converted and scraped on each edge cluster, but edge vmalert never notifies, so infra evaluates a copy of the rules centrally. Change the rules here first, with their tests, then update infra's copy. +- **`config/monitoring/`** — Prometheus Operator resources for BGP and NAT: a `fabric-router` PodMonitor (frr-exporter, port `frr-metrics`/`9342`, as `job=fabric-router`; fabric-config-agent, port `agent-metrics`/`9343`, as `job=fabric-config-agent`), a `galactic-router` PodMonitor covering both roles (port `metrics`/`9179`), a `galactic-nat` PodMonitor for the egress shards (port `metrics`/`9182`), each adding a `node` label, and the `galactic-bgp` PrometheusRule: underlay session down, administratively down for an hour, flapping, received prefixes halved, exporter collector or scrape failing, a session announcing an IPv4-mapped next hop, BGP routes not installed, the agent's metrics scrape down, a `galactic-router` BMP station or metrics scrape down, `galactic-router` routes failing to install, an egress shard's session table evicting live sessions, an egress shard out of masquerade ports, a stalled or persistently lossy NIC receive queue on a `galactic-nat` uplink (#673), and a `galactic-nat` metrics scrape down. For fabric routing through the API it adds a `fabric-router-controller` PodMonitor (port `metrics`/`9185`, `honorLabels` so the fleet series keep their objects' `namespace`), whose leader exports `galactic_fabric_routing_*` (each `FabricRouterDeployment`'s source, epochs, heartbeat, conditions and staged candidate, each outstanding release, each fabric router's compile result) beside the agent's activation, staging, writer-lock and boot-source metrics on `9343`, and a `fabric-routing` rule group (no eligible recovery, otherwise degraded, recovery conflict, agent heartbeat stale on Shadow/CRD, failed release blocking its domain, release Unknown, handoff pending, promotion refused by the agent, candidate rejected, revision refused, the leader unable to read a kind from its cache, controller scrape down — each reads the fleet series over 2 minutes and aggregates away only `pod` and `instance`, so a leader change does not reset it and an alert keeps its `cluster` and other external labels, and none fires on a cluster that keeps its nodes on ConfigMaps). For Galactic Edge it adds `galactic-controller` (port `metrics`/`9184`) and `galactic-edge` (port `metrics`/`9186`) PodMonitors and a `galactic-edge` rule group (attachments not programmed, service policy unresolved, ownership scope lost, cleanup failing, scrape down). For the opt-in fabric-api it adds the `fabric-router` PodMonitor's `api-metrics` endpoint (the sidecar, port `api-metrics`/`9345`, as `job=fabric-api-node`), a `fabric-api-gateway` PodMonitor (port `metrics`/`9347`) and a `fabric-api` rule group (stalled execution, node diagnostics unavailable, nodes unreachable, oversized results, cleanup backlog, certificate renewal failing, credentials missing, search index unsynced, scrape down, aggregate limiter unavailable, clock unsynchronised, Looking Glass requests mostly throttled or mostly failing — none fires merely because nobody ran a query). Requires the `monitoring.coreos.com` CRDs, which this repo does not install, so it is not part of the root `config/kustomization.yaml`. `task test:alerts` unit-tests the rules with `promtool` (`config/monitoring/tests/`). Every alert carries what infra's alerting standard checks for (`service: galactic`, `team: connect`, `runbook_url` into infra's `docs/runbooks/galactic/README.md`). The PrometheusRule here is the tested source, not where the rules run on Datum's infra: there the PodMonitors are converted and scraped on each edge cluster, but edge vmalert never notifies, so infra evaluates a copy of the rules centrally. Change the rules here first, with their tests, then update infra's copy. - **`deploy/containerlab/`** — ContainerLab topology (`gvpc.clab.yaml`) for three Kind clusters (dfw, iad, sjc) wired over an SRv6 transit mesh whose underlay is dual-stack — every transit link and loopback carries an IPv4 and an IPv6 address, with one BGP session per address family (the SRv6 data plane itself stays IPv6-only; tenant IPv4 rides inside the encapsulation). Each site has one `compute` worker and at least one `edge` worker (dfw has two); every worker has its own eBGP uplink to its site's transit router, with FRR running as a hostNetwork DaemonSet. `galactic-router` (plain mode) distributes EVPN paths over iBGP to one route reflector for the whole lab (`iad-worker3`, `config/galactic-router/overlays/control/`) — compute and edge nodes never peer directly. Every `edge` node runs an egress shard (`galactic-nat`) and a `galactic-gateway`, which share the node's uplinks through its XDP dispatcher (`GALACTIC_NAT_XDP_ATTACH=dispatch`). Each site's compute node egresses only through its own site's edge shards, and each site has its own VIP `/64`, served only through its own edge nodes to one `ns60` backend in that site. A standalone off-cluster host on the fourth transit router gives tenant egress a real destination and is the client for the VIP checks (`verify:gateway-ingress`, and `verify:gateway-ingress-ipv4` for each site's IPv4 VIP, which the IPv6-only backends serve through translation). The lab enforces interface traffic policy (production defaults to off): every tenant binds each attachment to a grant set in `resources/tenants/policies/`, and `verify:traffic-policy` proves each path's grant and denial. See `deploy/containerlab/README.md` and `deploy/containerlab/Taskfile.yaml` for bring-up commands. ## New Developer Entry Points diff --git a/Taskfile.yaml b/Taskfile.yaml index d6b4e2047..9f27d2d4b 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -9,9 +9,11 @@ vars: [ -n "$gobin" ] && echo "$gobin" || echo "$(go env GOPATH)/bin" GOLANGCI_LINT: '{{.LOCALBIN}}/golangci-lint' YAMLFMT: '{{.LOCALBIN}}/yamlfmt' + KUSTOMIZE: '{{.LOCALBIN}}/kustomize' GO_LICENSES: '{{.LOCALBIN}}/go-licenses' GOLANGCI_LINT_VERSION: v2.12.2 YAMLFMT_VERSION: v0.21.0 + KUSTOMIZE_VERSION: v5.8.1 GO_LICENSES_VERSION: v1.6.0 PROMETHEUS_VERSION: v3.15.0 @@ -229,6 +231,28 @@ tasks: - CGO_ENABLED=0 GOBIN={{.GOBGP_BIN}} go install github.com/osrg/gobgp/v4/cmd/gobgpd@v4.10.0 github.com/osrg/gobgp/v4/cmd/gobgp@v4.10.0 - go run ./hack/fabric-api-loadtest --mrt {{.MRT}} --gobgp-bin {{.GOBGP_BIN}} {{.CLI_ARGS}} + test:manifests: + desc: Render the opt-in Component fixtures in tests/manifests + # Every fixture under tests/manifests/fabric-api composes Components the + # way a cell overlay does and must build; every fixture under + # tests/manifests/invalid omits a Component another requires and must + # fail to build. + deps: [kustomize] + cmds: + - | + status=0 + for dir in tests/manifests/fabric-api/*/; do + if ! {{.KUSTOMIZE}} build "$dir" > /dev/null; then + echo "FAIL: $dir does not build"; status=1 + fi + done + for dir in tests/manifests/invalid/*/; do + if {{.KUSTOMIZE}} build "$dir" > /dev/null 2>&1; then + echo "FAIL: $dir builds, but omits a required Component"; status=1 + fi + done + exit $status + test:alerts: desc: Unit-test the alert rules in config/monitoring/ with promtool # promtool reads plain rule files, so the PrometheusRule's spec is @@ -285,6 +309,16 @@ tasks: PACKAGE: github.com/golangci/golangci-lint/v2/cmd/golangci-lint VERSION: '{{.GOLANGCI_LINT_VERSION}}' + kustomize: + desc: Download kustomize if needed + run: once + cmds: + - task: install-tool + vars: + TARGET: '{{.KUSTOMIZE}}' + PACKAGE: sigs.k8s.io/kustomize/kustomize/v5 + VERSION: '{{.KUSTOMIZE_VERSION}}' + yamlfmt: desc: Download yamlfmt if needed run: once diff --git a/cmd/fabric-api/gateway.go b/cmd/fabric-api/gateway.go index 139b7ceeb..8dcb85159 100644 --- a/cmd/fabric-api/gateway.go +++ b/cmd/fabric-api/gateway.go @@ -7,6 +7,7 @@ package main import ( "context" "crypto/x509" + "errors" "fmt" "log/slog" "net" @@ -15,6 +16,7 @@ import ( "github.com/go-logr/logr" "github.com/spf13/cobra" + "github.com/spf13/pflag" "google.golang.org/grpc" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" @@ -53,7 +55,9 @@ type gatewayOptions struct { maxInFlight int retention, cleanupGrace time.Duration serviceIdentities []string + serviceConfigMap string aggregateBudgets bool + limits limit.Limits } func newGatewayCommand() *cobra.Command { @@ -62,6 +66,11 @@ func newGatewayCommand() *cobra.Command { Use: "gateway", Short: "Execute this cell's FabricQuery objects and serve the operator debug service", RunE: func(cmd *cobra.Command, _ []string) error { + limits, err := gatewayLimits(cmd.Flags(), o) + if err != nil { + return err + } + o.limits = limits return runGateway(cmd.Context(), o) }, } @@ -99,13 +108,86 @@ func newGatewayCommand() *cobra.Command { f.StringSliceVar(&o.serviceIdentities, "service-identities", nil, "Names of the Looking Glass service identities (spiffe://fabric-api.datumapis.com/cell//service/) "+ "allowed to call this cell's gateway; empty allows none") + f.StringVar(&o.serviceConfigMap, "service-config-map", "", + "ConfigMap in --namespace whose key \"service\" turns Looking Glass execution on (\"enabled\") or off "+ + "(\"disabled\") while the gateway runs, read every second; empty, missing, unreadable or any other "+ + "value keeps it off. Execution also needs --aggregate-budgets") f.BoolVar(&o.aggregateBudgets, "aggregate-budgets", false, "Enforce the cell's aggregate admission and probe packet budgets on every caller, issue probe permits to "+ - "nodes, and bound each principal's share of --cell-slots and --cell-queue to the contract defaults; "+ - "every node must run with --probe-permits first") + "nodes, and bound each principal's share of --cell-slots and --cell-queue; every node must run with "+ + "--probe-permits first") + registerLimitFlags(f, &o.limits) return cmd } +// limitFlags are the aggregate limits an operator may lower, each +// defaulting to the contract's qualified value, which is also its ceiling. +var limitFlags = []string{ + "request-cell-rate", "request-cell-burst", "request-project-rate", "request-project-burst", + "packet-cell-rate", "packet-cell-burst", "packet-principal-rate", "packet-principal-burst", + "packet-host-rate", "packet-host-burst", "packet-prefix-rate", "packet-prefix-burst", + "principal-slots", "principal-queue", "service-streams", "project-streams", "queue-wait", +} + +func registerLimitFlags(f *pflag.FlagSet, l *limit.Limits) { + *l = limit.Defaults() + rate := func(name, what string, r *limit.Rate) { + f.Float64Var(&r.PerSecond, name+"-rate", r.PerSecond, what+" tokens per second; may only be lowered") + f.Float64Var(&r.Burst, name+"-burst", r.Burst, what+" bucket size; may only be lowered") + } + rate("request-cell", "Looking Glass requests admitted in the cell:", &l.RequestCell) + rate("request-project", "Looking Glass requests admitted per project:", &l.RequestProject) + rate("packet-cell", "Worst-case probe packets charged in the cell:", &l.PacketCell) + rate("packet-principal", "Worst-case probe packets charged per project, FabricQuery source or operator:", + &l.PacketPrincipal) + rate("packet-host", "Worst-case probe packets charged per destination address:", &l.PacketHost) + rate("packet-prefix", "Worst-case probe packets charged per destination IPv4 /24 or IPv6 /64:", &l.PacketPrefix) + f.IntVar(&l.PrincipalSlots, "principal-slots", l.PrincipalSlots, + "Of --cell-slots, node jobs one principal may run at once; may only be lowered") + f.IntVar(&l.PrincipalQueue, "principal-queue", l.PrincipalQueue, + "Of --cell-queue, node jobs one principal may queue; may only be lowered") + f.IntVar(&l.Streams, "service-streams", l.Streams, + "Live Looking Glass streams in the cell, queued and draining ones included; may only be lowered") + f.IntVar(&l.ProjectStreams, "project-streams", l.ProjectStreams, + "Live Looking Glass streams per project; may only be lowered") + f.DurationVar(&l.QueueWait, "queue-wait", l.QueueWait, + "How long a Looking Glass router job or a direct operator's permit may wait for a slot; may only be lowered") +} + +// gatewayLimits returns the aggregate limits the flags select, refusing +// limit flags or --service-config-map without --aggregate-budgets, a limit +// above its qualified ceiling and limits that break a cross-field rule. A +// principal's slots, queue and streams default to at most the cell's. +func gatewayLimits(f *pflag.FlagSet, o *gatewayOptions) (limit.Limits, error) { + if !o.aggregateBudgets { + if o.serviceConfigMap != "" { + return limit.Limits{}, errors.New("--service-config-map needs --aggregate-budgets: the service " + + "executes only under the cell's aggregate budgets") + } + for _, name := range limitFlags { + if f.Changed(name) { + return limit.Limits{}, fmt.Errorf("--%s needs --aggregate-budgets", name) + } + } + return limit.Limits{}, nil + } + l := o.limits + l.Slots, l.Queue = o.slots, o.queue + if !f.Changed("principal-slots") { + l.PrincipalSlots = min(l.PrincipalSlots, o.slots) + } + if !f.Changed("principal-queue") { + l.PrincipalQueue = min(l.PrincipalQueue, o.queue) + } + if !f.Changed("project-streams") { + l.ProjectStreams = min(l.ProjectStreams, l.Streams) + } + if err := errors.Join(l.Qualified(), l.Validate()); err != nil { + return limit.Limits{}, fmt.Errorf("--aggregate-budgets: %w", err) + } + return l, nil +} + func runGateway(parent context.Context, o *gatewayOptions) error { required := map[string]string{ "site": o.site, @@ -180,23 +262,26 @@ 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()) }) var admission *gateway.Admission if o.aggregateBudgets { - limits := limit.Defaults() - limits.Slots, limits.Queue = o.slots, o.queue - // A smaller cell lowers each principal's share with it. - limits.PrincipalSlots = min(limits.PrincipalSlots, o.slots) - limits.PrincipalQueue = min(limits.PrincipalQueue, o.queue) - admission, err = gateway.NewAdmission(limits, &limit.Authority{ + admission, err = gateway.NewAdmission(o.limits, &limit.Authority{ Reader: mgr.GetAPIReader(), Namespace: o.namespace, Name: o.leaseName, Identity: holder, + Clock: limit.KernelClock, }) if err != nil { return fmt.Errorf("--aggregate-budgets: %w", err) } - executor.PrincipalSlots, executor.PrincipalQueue = limits.PrincipalSlots, limits.PrincipalQueue + 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) } - metrics := gateway.NewMetrics(ctrlmetrics.Registry, func() float64 { return float64(executor.Depth()) }) + serviceSwitch := &gateway.ServiceSwitch{} + metrics.RegisterService(serviceSwitch) + if o.serviceConfigMap != "" { + go serviceSwitch.Watch(ctx, mgr.GetAPIReader(), o.namespace, o.serviceConfigMap, gateway.ServiceSwitchInterval) + } executor.ObserveWait = func(d time.Duration) { metrics.QueueWait(d.Seconds()) } creds := o.tls.credentials(identity.Gateway(o.cell)) creds.OnLoad(func(leaf *x509.Certificate) { metrics.CertificateExpiry(float64(leaf.NotAfter.Unix())) }) @@ -231,7 +316,8 @@ func runGateway(parent context.Context, o *gatewayOptions) error { discoverer := &gateway.Discoverer{ Reader: mgr.GetClient(), Namespace: o.namespace, Selector: sel, CertsSelector: certsSel, } - runner := &gateway.Runner{Clients: pool, Executor: executor, Metrics: metrics, Admission: admission} + runner := &gateway.Runner{Clients: pool, Executor: executor, Metrics: metrics, Admission: admission, + QueueWait: o.limits.QueueWait} rec := &gateway.Reconciler{ Client: mgr.GetClient(), APIReader: mgr.GetAPIReader(), @@ -271,10 +357,13 @@ func runGateway(parent context.Context, o *gatewayOptions) error { Cell: o.cell, DialOptions: []grpc.DialOption{clientStats()}, } - // Enabled is deliberately unset: the service authenticates, validates + // The service executes only while serviceSwitch is on and admission + // enforces the aggregate budgets; otherwise it authenticates, validates // and reports capabilities, and refuses execution with ServiceDisabled. service := &gateway.Service{ Cell: o.cell, + Switch: serviceSwitch, + Metrics: metrics, Allowlist: allowlist, Elected: debug.Elected, Leader: debug, diff --git a/cmd/fabric-api/gateway_test.go b/cmd/fabric-api/gateway_test.go new file mode 100644 index 000000000..ed687daa9 --- /dev/null +++ b/cmd/fabric-api/gateway_test.go @@ -0,0 +1,102 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "strings" + "testing" + "time" + + "github.com/spf13/pflag" + + "go.datum.net/galactic/internal/fabric/gateway/limit" +) + +// budgets is the flag every valid limit needs; qualified is in the error of +// a limit raised above its ceiling. +const ( + budgets = "--aggregate-budgets" + qualified = "qualified" +) + +// parseLimits parses args as the gateway's limit flags, with the cell slot, +// queue, budget and service switch flags they depend on. +func parseLimits(t *testing.T, args ...string) (limit.Limits, error) { + t.Helper() + o := &gatewayOptions{} + f := pflag.NewFlagSet("gateway", pflag.ContinueOnError) + f.IntVar(&o.slots, "cell-slots", 8, "") + f.IntVar(&o.queue, "cell-queue", 256, "") + f.BoolVar(&o.aggregateBudgets, "aggregate-budgets", false, "") + f.StringVar(&o.serviceConfigMap, "service-config-map", "", "") + registerLimitFlags(f, &o.limits) + if err := f.Parse(args); err != nil { + t.Fatal(err) + } + for _, name := range limitFlags { + if f.Lookup(name) == nil { + t.Fatalf("limit flag --%s is not registered", name) + } + } + return gatewayLimits(f, o) +} + +func TestGatewayLimits(t *testing.T) { + l, err := parseLimits(t, budgets) + if err != nil { + t.Fatal(err) + } + if l != limit.Defaults() { + t.Errorf("default limits = %+v, want the contract's", l) + } + + l, err = parseLimits(t, budgets, "--packet-host-rate=10", "--packet-host-burst=320", + "--principal-slots=1", "--project-streams=1", "--queue-wait=5s", "--request-cell-burst=4") + if err != nil { + t.Fatal(err) + } + if l.PacketHost != (limit.Rate{PerSecond: 10, Burst: 320}) || l.PrincipalSlots != 1 || l.ProjectStreams != 1 || + l.QueueWait != 5*time.Second || l.RequestCell.Burst != 4 { + t.Errorf("lowered limits = %+v", l) + } + + // A smaller cell lowers each principal's default share with it. + l, err = parseLimits(t, budgets, "--cell-slots=1", "--cell-queue=8", "--service-streams=1") + if err != nil { + t.Fatal(err) + } + if l.Slots != 1 || l.PrincipalSlots != 1 || l.Queue != 8 || l.PrincipalQueue != 8 || l.ProjectStreams != 1 { + t.Errorf("small cell limits = %+v", l) + } +} + +func TestGatewayLimitsRefused(t *testing.T) { + cases := map[string]struct { + args []string + want string + }{ + "limit without budgets": {[]string{"--packet-cell-rate=50"}, "needs --aggregate-budgets"}, + "service without budgets": {[]string{"--service-config-map=fabric-api-service"}, "needs --aggregate-budgets"}, + "raised rate": {[]string{budgets, "--packet-host-rate=21"}, qualified}, + "raised burst": {[]string{budgets, "--request-project-burst=3"}, qualified}, + "raised principal slots": {[]string{budgets, "--principal-slots=3"}, qualified}, + "raised project streams": {[]string{budgets, "--project-streams=3"}, qualified}, + "principal above cell": { + []string{budgets, "--cell-slots=1", "--principal-slots=2"}, "principal slots", + }, + "burst too long": {[]string{budgets, "--packet-host-rate=1"}, "burst/rate"}, + "short burst": {[]string{budgets, "--packet-prefix-burst=19"}, "cannot fund"}, + "zero rate": {[]string{budgets, "--request-cell-rate=0"}, "positive"}, + "queue wait raised": {[]string{budgets, "--queue-wait=11s"}, "queue wait"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + _, err := parseLimits(t, tc.args...) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want one mentioning %q", err, tc.want) + } + }) + } +} diff --git a/cmd/fabric-api/node.go b/cmd/fabric-api/node.go index 6150e9cff..7e52fba00 100644 --- a/cmd/fabric-api/node.go +++ b/cmd/fabric-api/node.go @@ -28,6 +28,7 @@ import ( permitv1 "go.datum.net/galactic/api/fabric/permit/v1" fabricv1 "go.datum.net/galactic/api/fabric/v1" "go.datum.net/galactic/internal/fabric/frr" + "go.datum.net/galactic/internal/fabric/gateway/limit" "go.datum.net/galactic/internal/fabric/identity" "go.datum.net/galactic/internal/fabric/index" "go.datum.net/galactic/internal/fabric/node" @@ -199,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 } @@ -273,8 +274,9 @@ func runNode(parent context.Context, o *nodeOptions) error { } // nodePermits returns the probe permit checker the flags select, or nil -// without --probe-permits. -func nodePermits(o *nodeOptions, creds *identity.Credentials) (*node.Permits, error) { +// without --probe-permits. Its permits are refused while the kernel clock +// 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") @@ -293,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(), + 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/fabric-api/components/aggregate-budgets/deployment-patch.yaml b/config/fabric-api/components/aggregate-budgets/deployment-patch.yaml new file mode 100644 index 000000000..019d25424 --- /dev/null +++ b/config/fabric-api/components/aggregate-budgets/deployment-patch.yaml @@ -0,0 +1,3 @@ +- op: add + path: /spec/template/spec/containers/0/args/- + value: --aggregate-budgets diff --git a/config/fabric-api/components/aggregate-budgets/kustomization.yaml b/config/fabric-api/components/aggregate-budgets/kustomization.yaml new file mode 100644 index 000000000..2676397db --- /dev/null +++ b/config/fabric-api/components/aggregate-budgets/kustomization.yaml @@ -0,0 +1,24 @@ +# Turns on the cell's aggregate admission and probe packet budgets in the +# fabric-api gateway (--aggregate-budgets). Include it from the per-cell +# gateway overlay of config/fabric-api/base: +# +# resources: +# - ../../config/fabric-api/base +# components: +# - ../../config/fabric-api/components/aggregate-budgets +# +# Apply it only once every node's sidecar verifies probe permits +# (config/fabric-router/components/fabric-api-permits): the gateway sends a +# probe to no other node. From then on every probe in the cell, operator, +# FabricQuery and Looking Glass, is charged to the cell's budgets, and each +# gateway start or failover refuses probes for 125 seconds while the leader +# serves its recovery hold. The limits are the contract's defaults; an +# overlay may lower any of them with the gateway's limit flags, never raise +# one. See docs/fabric-api/configuration.md#aggregate-probe-budgets. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +patches: + - path: deployment-patch.yaml + target: + kind: Deployment + name: fabric-api-gateway diff --git a/config/fabric-api/components/service/configmap.yaml b/config/fabric-api/components/service/configmap.yaml new file mode 100644 index 000000000..8878a1fa1 --- /dev/null +++ b/config/fabric-api/components/service/configmap.yaml @@ -0,0 +1,12 @@ +# The Looking Glass service switch. Only the exact value "enabled" turns +# execution on; "disabled", a missing key or ConfigMap, an unreadable one or +# any other value keeps it off. Each gateway replica reads it every second. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fabric-api-service + namespace: galactic-system + annotations: + kustomize.toolkit.fluxcd.io/ssa: IfNotPresent +data: + service: disabled diff --git a/config/fabric-api/components/service/deployment-patch.yaml b/config/fabric-api/components/service/deployment-patch.yaml new file mode 100644 index 000000000..8c7b19dd7 --- /dev/null +++ b/config/fabric-api/components/service/deployment-patch.yaml @@ -0,0 +1,12 @@ +# Tests that components/aggregate-budgets came first: the service executes +# only under the cell's aggregate budgets, and the gateway refuses +# --service-config-map without them. +- op: test + path: /spec/template/spec/containers/0/args/1 + value: --aggregate-budgets +- op: add + path: /spec/template/spec/containers/0/args/- + value: --service-config-map=fabric-api-service +- op: add + path: /spec/template/spec/containers/0/args/- + value: --service-identities=looking-glass diff --git a/config/fabric-api/components/service/kustomization.yaml b/config/fabric-api/components/service/kustomization.yaml new file mode 100644 index 000000000..bd154e405 --- /dev/null +++ b/config/fabric-api/components/service/kustomization.yaml @@ -0,0 +1,38 @@ +# Wires the Looking Glass service into the fabric-api gateway: the service +# identities it accepts and the fabric-api-service ConfigMap whose key +# "service" turns execution on ("enabled") or off ("disabled") while the +# gateway runs, without a restart. List it after +# components/aggregate-budgets, which it requires; the build fails without +# it: +# +# resources: +# - ../../config/fabric-api/base +# components: +# - ../../config/fabric-api/components/aggregate-budgets +# - ../../config/fabric-api/components/service +# +# The ConfigMap ships with execution off. Flux creates it once and never +# overwrites it (kustomize.toolkit.fluxcd.io/ssa: IfNotPresent), so the +# value in the cluster is the switch an operator turns with kubectl, and a +# reconcile never turns the service back on after an emergency stop. +# Each replica reads it every second. Once the leader reads "disabled", it +# cancels running Looking Glass requests within 2 seconds and refuses new +# ones with ServiceDisabled; operator and FabricQuery work and the +# limiter's state are untouched. See +# docs/fabric-api/configuration.md#operating-the-looking-glass-service. +# +# Prerequisites: every node requires probe permits +# (config/fabric-router/components/fabric-api-require-permits), so direct +# operator probes are charged too, and the cell's fabric-api Issuer issues +# the service certificate. Replace looking-glass in --service-identities +# when the service's certificate names another service. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - configmap.yaml + - rbac.yaml +patches: + - path: deployment-patch.yaml + target: + kind: Deployment + name: fabric-api-gateway diff --git a/config/fabric-api/components/service/rbac.yaml b/config/fabric-api/components/service/rbac.yaml new file mode 100644 index 000000000..437556312 --- /dev/null +++ b/config/fabric-api/components/service/rbac.yaml @@ -0,0 +1,26 @@ +# The gateway reads the service switch, and nothing else among the +# namespace's ConfigMaps. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fabric-api-gateway-service + namespace: galactic-system +rules: + - apiGroups: [""] + resources: ["configmaps"] + resourceNames: ["fabric-api-service"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fabric-api-gateway-service + namespace: galactic-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fabric-api-gateway-service +subjects: + - kind: ServiceAccount + name: fabric-api-gateway + namespace: galactic-system diff --git a/config/fabric-router/components/fabric-api-permits/daemonset-patch.yaml b/config/fabric-router/components/fabric-api-permits/daemonset-patch.yaml new file mode 100644 index 000000000..f49c6e678 --- /dev/null +++ b/config/fabric-router/components/fabric-api-permits/daemonset-patch.yaml @@ -0,0 +1,17 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: fabric-router + namespace: galactic-system +spec: + template: + spec: + containers: + - name: fabric-api + args: + - node + - --probe-permits + volumeMounts: + - name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true diff --git a/config/fabric-router/components/fabric-api-permits/kustomization.yaml b/config/fabric-router/components/fabric-api-permits/kustomization.yaml new file mode 100644 index 000000000..676000107 --- /dev/null +++ b/config/fabric-router/components/fabric-api-permits/kustomization.yaml @@ -0,0 +1,37 @@ +# Makes each node's fabric-api sidecar verify the cell gateway's probe +# permits (--probe-permits). List it after components/fabric-api, which it +# requires; the build fails without it: +# +# resources: +# - ../../config/fabric-router +# components: +# - ../../config/fabric-router/components/fabric-api +# - ../../config/fabric-router/components/fabric-api-permits +# +# The sidecar then reads the gateway's election Lease (fabric-api-gateway in +# galactic-system) to check each permit's epoch, so it gets the +# fabric-router ServiceAccount's token and a Role allowing get on that one +# Lease. It accepts a permit once, sends nothing past its packets or +# deadline, refuses every permit for 32 seconds after it starts and while +# its host's clock is unsynchronised, and reports probePermits in Info, +# which the gateway requires before it sends a node a probe under +# --aggregate-budgets. A probe without a permit still runs. +# +# Applying it changes the pod template, so every fabric-router pod restarts +# and FRR with it: roll it out as a routing change (one canary node, check +# underlay sessions and convergence, then paced expansion). See +# docs/fabric-api/configuration.md#enabling. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - rbac.yaml +patches: + - path: daemonset-patch.yaml + # Fails the build unless components/fabric-api, which adds this + # DaemonSet, came first; it changes nothing. + - patch: |- + apiVersion: apps/v1 + kind: DaemonSet + metadata: + name: fabric-api-certs + namespace: galactic-system diff --git a/config/fabric-router/components/fabric-api-permits/rbac.yaml b/config/fabric-router/components/fabric-api-permits/rbac.yaml new file mode 100644 index 000000000..50fec4747 --- /dev/null +++ b/config/fabric-router/components/fabric-api-permits/rbac.yaml @@ -0,0 +1,26 @@ +# The sidecar reads the gateway's election Lease, uncached, to check each +# probe permit's epoch, and reads nothing else. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fabric-api-node-lease + namespace: galactic-system +rules: + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + resourceNames: ["fabric-api-gateway"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fabric-api-node-lease + namespace: galactic-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fabric-api-node-lease +subjects: + - kind: ServiceAccount + name: fabric-router + namespace: galactic-system diff --git a/config/fabric-router/components/fabric-api-require-permits/daemonset-patch.yaml b/config/fabric-router/components/fabric-api-require-permits/daemonset-patch.yaml new file mode 100644 index 000000000..fae2b45ee --- /dev/null +++ b/config/fabric-router/components/fabric-api-require-permits/daemonset-patch.yaml @@ -0,0 +1,15 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: fabric-router + namespace: galactic-system +spec: + template: + spec: + containers: + - name: fabric-api + args: + - node + - --probe-permits + - --require-probe-permits + - --gateway-address=fabric-api-gateway.galactic-system.svc:9346 diff --git a/config/fabric-router/components/fabric-api-require-permits/kustomization.yaml b/config/fabric-router/components/fabric-api-require-permits/kustomization.yaml new file mode 100644 index 000000000..5a8a7db5d --- /dev/null +++ b/config/fabric-router/components/fabric-api-require-permits/kustomization.yaml @@ -0,0 +1,32 @@ +# Makes each node's fabric-api sidecar refuse a probe without a permit +# (--require-probe-permits). A probe an operator sends a node directly +# first obtains a permit from the cell gateway's Service, charged to that +# operator, so every probe in the cell counts against the aggregate budgets; +# the Looking Glass service must not be enabled before this. List it after +# components/fabric-api-permits, which it requires; the build fails without +# it: +# +# resources: +# - ../../config/fabric-router +# components: +# - ../../config/fabric-router/components/fabric-api +# - ../../config/fabric-router/components/fabric-api-permits +# - ../../config/fabric-router/components/fabric-api-require-permits +# +# Apply it only once the gateway runs with --aggregate-budgets +# (config/fabric-api/components/aggregate-budgets): without a gateway +# issuing permits, every probe on these nodes is refused. Like +# components/fabric-api-permits, applying it restarts FRR on every node: roll +# it out as a routing change. See docs/fabric-api/configuration.md#enabling. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +patches: + - path: daemonset-patch.yaml + # Fails the build unless components/fabric-api-permits, which adds this + # Role, came first; it changes nothing. + - patch: |- + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + metadata: + name: fabric-api-node-lease + namespace: galactic-system diff --git a/config/monitoring/prometheusrule.yaml b/config/monitoring/prometheusrule.yaml index ed230031d..19c8a08f8 100644 --- a/config/monitoring/prometheusrule.yaml +++ b/config/monitoring/prometheusrule.yaml @@ -1139,6 +1139,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 2506d9f49..9ee1af5e8 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/docs/agents/ARCHITECTURE-FABRIC-API.md b/docs/agents/ARCHITECTURE-FABRIC-API.md index d0885f530..b1695c163 100644 --- a/docs/agents/ARCHITECTURE-FABRIC-API.md +++ b/docs/agents/ARCHITECTURE-FABRIC-API.md @@ -120,7 +120,7 @@ internal/fabric/ identity/ URI SAN identities, reloading mTLS credentials, certificate sync errcode/ Typed error codes carried as gRPC ErrorInfo node/ FabricService implementation (the sidecar's logic) - gateway/ Reconciler, Runner, Executor, Pool, Discoverer, Debug, Service, Admission, Permits, Janitor + gateway/ Reconciler, Runner, Executor, Pool, Discoverer, Debug, Service, ServiceSwitch, Admission, Permits, Janitor gateway/limit/ Aggregate token buckets, attempt keys, election authority and limits testpki/ Throwaway CA for tests @@ -128,11 +128,17 @@ config/fabric-api/ serviceaccount.yaml, rbac.yaml Gateway and janitor identities and RBAC kustomization.yaml Applies only the two files above base/ Gateway Deployment, Service, PDB, janitor CronJob + components/aggregate-budgets/ Opt-in: --aggregate-budgets on the gateway + components/service/ Opt-in, after aggregate-budgets: the service switch ConfigMap, its Role, identities crd/ Generated FabricQuery CRD (lab and tests only) config/fabric-router/components/fabric-api/ kustomization.yaml, daemonset-patch.yaml The opt-in sidecar Component certs-daemonset.yaml fabric-api-certs: obtains each node's certificate +config/fabric-router/components/fabric-api-permits/ Opt-in, after fabric-api: --probe-permits, Lease Role, token +config/fabric-router/components/fabric-api-require-permits/ Opt-in, after fabric-api-permits: --require-probe-permits + +tests/manifests/ Render fixtures for the Components (task test:manifests) config/monitoring/ podmonitor-fabric-router.yaml api-metrics endpoint (job=fabric-api-node) @@ -325,13 +331,23 @@ registers: certificate on every unary and streaming call, and the node-only permit service (`gateway.Permits`). The service takes each request's router inventory with an uncached pod list and runs through the shared `Runner` and - executor, but its `Enabled` field is not set, so the leader refuses valid - requests with `ServiceDisabled`; no flag turns execution on. + executor, but only while its `gateway.ServiceSwitch` (`serviceswitch.go`) + is on; otherwise the leader refuses valid requests with `ServiceDisabled`. + With `--service-config-map`, `ServiceSwitch.Watch` reads that ConfigMap's + `service` key uncached every second; only `enabled` turns it on, and + turning it off cancels running requests through the context `State` hands + each one. Without the flag it stays off. With `--aggregate-budgets` it also builds a `gateway.Admission` under a -`limit.Authority` for that holder identity, gives it to the runner, the -service and the permit service, bounds each principal's share of the executor, -and starts `Authority.Watch`, which reads the Lease every second. +`limit.Authority` for that holder identity, from the limit flags +(`gatewayLimits` refuses one without `--aggregate-budgets`, one above its +`limit.Defaults` ceiling (`Limits.Qualified`) and any breaking a cross-field +rule (`Limits.Validate`)). It gives the admission to the runner, the service +and the permit service, bounds each principal's share of the executor, and +starts `Authority.Watch`, which reads the Lease every second. The authority +also checks `limit.KernelClock` (adjtimex) and refuses, like a failed Lease +read, while the kernel clock is not synchronised within 500 ms; `State` +reports it for `fabric_api_gateway_limiter_state`. Metrics are registered on controller-runtime's registry and served on `:9347` along with its own; `/healthz` and `/readyz` are plain pings on `:8081`. @@ -443,7 +459,7 @@ manifest sets yet (see | `internal/fabric/gateway/limit` | `Limits` and `Validate`; `Buckets` (request and packet token buckets, never negative, key families bounded without evicting debt); `Attempts` (duplicate attempt keys, fail closed); `Authority` (uncached Lease check, epoch, 125 s recovery hold, `Watch`) | Buckets, attempt keys, epoch (memory) | | `internal/fabric/gateway` (`discovery.go`) | Pod snapshot with omission reasons, one pod per node, node budget, node-to-certs-pod mapping (`NoCertificatePod`); `Inventory`, the service's one-router-per-node snapshot (newest usable pod, `NotRequested`, `NoSidecar`, unscheduled count, 256-router cap) | No | | `internal/fabric/gateway` (`debug.go`) | Operator debug service, leader forwarding through the election lease | Connection to the leader | -| `internal/fabric/gateway` (`service.go`) | `NewServer`, service `Allowlist`, Looking Glass service authorization and attribution validation, one-hop typed forwarding to the leader, capabilities, and (when `Enabled`) streamed execution with terminal coverage and its output budget | No | +| `internal/fabric/gateway` (`service.go`) | `NewServer`, service `Allowlist`, Looking Glass service authorization and attribution validation, one-hop typed forwarding to the leader, capabilities, and (while `Switch` is on) streamed execution with terminal coverage and its output budget | No | | `internal/fabric/gateway` (`stream.go`) | Delivery and transport bounds: the single stream writer with its 2 s write bound, per-replica call and service connection caps, fixed windows and keepalive on the listener and the follower's leader connection | No | | `internal/fabric/gateway` (`janitor.go`) | `Janitor.Sweep`, `StaleCounter` | No | | `internal/fabric/gateway` (`metrics.go`) | `fabric_api_gateway_*` and shared `fabric_api_*` collectors | Prometheus collectors | @@ -814,6 +830,7 @@ with the Component but its restart does not touch FRR. | Fan-out, deadlines, retries | `internal/fabric/gateway/runner.go:Runner.Run`, `one` | | Cell concurrency and fairness | `internal/fabric/gateway/executor.go:Executor.Acquire`, `Reserve` | | Aggregate admission and probe budgets | `internal/fabric/gateway/service.go:Service.execute`, `admission.go:Admission.permit`, `limit/` | +| Looking Glass switch and limit flags | `internal/fabric/gateway/serviceswitch.go`, `cmd/fabric-api/gateway.go:gatewayLimits` | | Probe permits on the node | `internal/fabric/node/permit.go:Permits.consume`, `server.go:probeGrant` | | Node snapshot and omission reasons | `internal/fabric/gateway/discovery.go:Discoverer.Snapshot`, `omitReason` | | Operator debug service and leader forwarding | `internal/fabric/gateway/debug.go:Debug.Query`, `forward`, `leaderAddress` | @@ -822,6 +839,7 @@ with the Component but its restart does not touch FRR. | Wire contract | `api/fabric/v1/fabric.proto` (regenerate with `task generate:proto`) | | Sidecar pod spec, UID, capabilities, volumes | `config/fabric-router/components/fabric-api/daemonset-patch.yaml` | | Gateway Deployment, janitor CronJob, RBAC | `config/fabric-api/base/`, `config/fabric-api/rbac.yaml` | +| Opt-in budget, permit and service Components | `config/fabric-api/components/`, `config/fabric-router/components/fabric-api-*permits/`, `tests/manifests/` | | Metrics and alerts | `internal/fabric/node/metrics.go`, `gateway/metrics.go`, `config/monitoring/prometheusrule.yaml` (`fabric-api` group) | **Stable vs. frequently changed:** diff --git a/docs/fabric-api/configuration.md b/docs/fabric-api/configuration.md index d1e938dfc..9bb08e4a1 100644 --- a/docs/fabric-api/configuration.md +++ b/docs/fabric-api/configuration.md @@ -387,10 +387,13 @@ service presents the certificate on its gRPC connection to the gateway's `debug` port and, to rotate without a restart, reloads the files as cert-manager renews them; the gateway accepts the overlapping-bundle rotation below. The service contract is [service-contract.md](service-contract.md). The gateway -does not execute service diagnostics: it answers a valid `RunDiagnostic` -with `ServiceDisabled`, and `GetCapabilities` reports `enabled: false`. With -`--aggregate-budgets`, `GetCapabilities` also lists `aggregate-probe-budgets` -and the cell's admission limits. +executes service diagnostics only while its service switch is on, under +`--aggregate-budgets` (see +[Operating the Looking Glass service](#operating-the-looking-glass-service)); +otherwise it answers a valid `RunDiagnostic` with `ServiceDisabled`, and +`GetCapabilities` reports `enabled: false`. While execution is on, +`GetCapabilities` also lists `aggregate-probe-budgets` and the cell's +admission limits. ### Rotation @@ -448,38 +451,38 @@ variables then apply. Trace-context propagation is always on. ### `fabric-api node` -| Flag | Env | Default | Meaning | -| ------------------------------ | ------------------------ | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--node-name` | `NODE_NAME` | | This node's name. Required; requests naming another node are refused (`WrongNode`) | -| `--site` | `SITE` | | Site this node serves; reported by `Info` | -| `--cell` | `CELL` | | Cell name in the mTLS identities. If empty the process idles and serves only metrics | -| `--namespace` | `POD_NAMESPACE` | | This pod's namespace. Required | -| `--pod-name` | `POD_NAME` | | This pod's name. Required | -| `--host-ip` | `HOST_IP` | | Address the gRPC service binds to: the pod's `hostIP`. Required | -| `--port` | | `9344` | gRPC port | -| `--metrics-bind-address` | `METRICS_BIND_ADDRESS` | `:9345` | Address serving `/metrics` | -| `--frr-socket-dir` | | `/run/frr` | Directory holding `bgpd.vty` and `zebra.vty` | -| `--tls-cert` | `FABRIC_API_TLS_CERT` | `/var/run/fabric-api/tls/tls.crt` | Certificate file | -| `--tls-key` | `FABRIC_API_TLS_KEY` | `/var/run/fabric-api/tls/tls.key` | Private key file | -| `--tls-ca` | `FABRIC_API_TLS_CA` | `/var/run/fabric-api/tls/ca.crt` | Trust bundle file | -| `--probe-source-ipv4` | `PROBE_SOURCE_IPV4` | | Explicit IPv4 probe source | -| `--probe-source-ipv6` | `PROBE_SOURCE_IPV6` | | Explicit IPv6 probe source | -| `--probe-source-interface` | `PROBE_SOURCE_INTERFACE` | `lo` | Interface whose single global address per family is the source for a family with no explicit one; empty disables | -| `--deny-prefixes` | | | Comma-separated platform or management CIDRs no probe may target | -| `--operator-allow-prefixes` | | | Comma-separated CIDRs only operator identities may probe. Lab only; never set in production | -| `--enable-expensive-queries` | | `false` | Enable `ASPath`, `Community` and `LargeCommunity` searches. See [Query types](#query-types) | -| `--max-concurrent` | | `4` | `Execute` calls running at once; further calls wait within their deadline | -| `--max-expensive` | | `1` | Expensive searches running at once; no queue (`NodeBusy`) | -| `--max-probes` | | `2` | Probes running at once; no queue (`NodeBusy`) | -| `--probe-packet-rate` | | `20` | Probe packets per second across all probes on the node (burst 5, not configurable) | -| `--expensive-breaker-cooldown` | | `10m` | How long expensive searches stay suspended after one times out (`--search-source=frr` only) | -| `--search-source` | | `index` | What answers AS-path and community searches: `index` (a local copy of bgpd's Loc-RIB fed over BMP) or `frr` (FRR's own scans, which starve bgpd on full tables) | -| `--bmp-station-address` | | `127.0.0.1:9348` | Loopback address the BMP station listens on, with `--search-source=index` | -| `--search-index-max-routes` | | `4000000` | Prefixes the index holds at most; announcements for new prefixes beyond it are dropped and counted | -| `--probe-permits` | | `false` | Verify and enforce the gateway's probe permits, and report `probePermits` in `Info`. Needs API access; see [Aggregate probe budgets](#aggregate-probe-budgets) | -| `--require-probe-permits` | | `false` | With `--probe-permits`, refuse any probe without a permit; a direct operator's probe first obtains one from `--gateway-address` | -| `--gateway-address` | | | `host:port` of the cell gateway's gRPC service, from which direct operator probes obtain permits. Required by `--require-probe-permits` | -| `--gateway-lease-name` | | `fabric-api-gateway` | The gateway's election lease, read uncached in `--namespace` to verify each permit's epoch | +| Flag | Env | Default | Meaning | +| ------------------------------ | ------------------------ | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--node-name` | `NODE_NAME` | | This node's name. Required; requests naming another node are refused (`WrongNode`) | +| `--site` | `SITE` | | Site this node serves; reported by `Info` | +| `--cell` | `CELL` | | Cell name in the mTLS identities. If empty the process idles and serves only metrics | +| `--namespace` | `POD_NAMESPACE` | | This pod's namespace. Required | +| `--pod-name` | `POD_NAME` | | This pod's name. Required | +| `--host-ip` | `HOST_IP` | | Address the gRPC service binds to: the pod's `hostIP`. Required | +| `--port` | | `9344` | gRPC port | +| `--metrics-bind-address` | `METRICS_BIND_ADDRESS` | `:9345` | Address serving `/metrics` | +| `--frr-socket-dir` | | `/run/frr` | Directory holding `bgpd.vty` and `zebra.vty` | +| `--tls-cert` | `FABRIC_API_TLS_CERT` | `/var/run/fabric-api/tls/tls.crt` | Certificate file | +| `--tls-key` | `FABRIC_API_TLS_KEY` | `/var/run/fabric-api/tls/tls.key` | Private key file | +| `--tls-ca` | `FABRIC_API_TLS_CA` | `/var/run/fabric-api/tls/ca.crt` | Trust bundle file | +| `--probe-source-ipv4` | `PROBE_SOURCE_IPV4` | | Explicit IPv4 probe source | +| `--probe-source-ipv6` | `PROBE_SOURCE_IPV6` | | Explicit IPv6 probe source | +| `--probe-source-interface` | `PROBE_SOURCE_INTERFACE` | `lo` | Interface whose single global address per family is the source for a family with no explicit one; empty disables | +| `--deny-prefixes` | | | Comma-separated platform or management CIDRs no probe may target | +| `--operator-allow-prefixes` | | | Comma-separated CIDRs only operator identities may probe. Lab only; never set in production | +| `--enable-expensive-queries` | | `false` | Enable `ASPath`, `Community` and `LargeCommunity` searches. See [Query types](#query-types) | +| `--max-concurrent` | | `4` | `Execute` calls running at once; further calls wait within their deadline | +| `--max-expensive` | | `1` | Expensive searches running at once; no queue (`NodeBusy`) | +| `--max-probes` | | `2` | Probes running at once; no queue (`NodeBusy`) | +| `--probe-packet-rate` | | `20` | Probe packets per second across all probes on the node (burst 5, not configurable) | +| `--expensive-breaker-cooldown` | | `10m` | How long expensive searches stay suspended after one times out (`--search-source=frr` only) | +| `--search-source` | | `index` | What answers AS-path and community searches: `index` (a local copy of bgpd's Loc-RIB fed over BMP) or `frr` (FRR's own scans, which starve bgpd on full tables) | +| `--bmp-station-address` | | `127.0.0.1:9348` | Loopback address the BMP station listens on, with `--search-source=index` | +| `--search-index-max-routes` | | `4000000` | Prefixes the index holds at most; announcements for new prefixes beyond it are dropped and counted | +| `--probe-permits` | | `false` | Verify and enforce the gateway's probe permits, and report `probePermits` in `Info`. Permits are refused while the kernel clock is unsynchronised. Needs API access; see [Aggregate probe budgets](#aggregate-probe-budgets) | +| `--require-probe-permits` | | `false` | With `--probe-permits`, refuse any probe without a permit; a direct operator's probe first obtains one from `--gateway-address` | +| `--gateway-address` | | | `host:port` of the cell gateway's gRPC service, from which direct operator probes obtain permits. Required by `--require-probe-permits` | +| `--gateway-lease-name` | | `fabric-api-gateway` | The gateway's election lease, read uncached in `--namespace` to verify each permit's epoch | Not configurable by flag: the 4 MiB FRR read cap, the 2 second socket dial timeout, the duplicate-suppression cache (1024 entries or 32 MiB), the 60 second @@ -496,32 +499,34 @@ FRR, so it follows [Rollout](#rollout). ### `fabric-api gateway` -| Flag | Env | Default | Meaning | -| ------------------------------------- | ------------------------------------ | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--site` | `SITE` | | Site this cell serves. Required | -| `--cluster-name` | `CLUSTER_NAME` | | This cell's Karmada member cluster name. Required | -| `--cell` | `CELL` | | Cell name in the mTLS identities. Required | -| `--namespace` | `POD_NAMESPACE` | `galactic-system` | Namespace of the `fabric-router` pods, the election lease and this pod | -| `--pod-name` | `POD_NAME` | | This pod's name. Required | -| `--debug-bind-address` | | | Address the debug service binds to. Empty binds every address in the pod's network namespace, which a port-forward (through the pod's loopback) and the Service both need | -| `--pod-selector` | | `app.kubernetes.io/name=fabric-router` | Label selector of `fabric-router` pods | -| `--certs-selector` | | `app.kubernetes.io/name=fabric-api-certs` | Label selector of the per-node `fabric-api-certs` pods whose identity each sidecar presents | -| `--lease-name` | | `fabric-api-gateway` | Leader election lease name | -| `--debug-port` | | `9346` | Operator debug gRPC port | -| `--metrics-bind-address` | | `:9347` | Address serving `/metrics` | -| `--health-probe-bind-address` | | `:8081` | Address serving `/healthz` and `/readyz` | -| `--tls-cert`, `--tls-key`, `--tls-ca` | `FABRIC_API_TLS_CERT`, `_KEY`, `_CA` | `/var/run/fabric-api/tls/tls.crt`, `tls.key`, `ca.crt` | As for the node | -| `--cell-slots` | | `8` | Node RPCs running at once across all queries | -| `--cell-expensive-slots` | | `2` | Of those, expensive searches | -| `--cell-queue` | | `256` | Node RPCs that may wait for a slot | -| `--max-nodes` | | `32` | Nodes one query executes on in this cell (ceiling 32) | -| `--max-object-bytes` | | `393216` (384 KiB) | Serialized `FabricQuery` size ceiling (ceiling 384 KiB) | -| `--max-node-response-bytes` | | `131072` (128 KiB) | Node response ceiling (ceiling 128 KiB) | -| `--max-in-flight` | | `256` | Queries executing at once; more wait for a requeue | -| `--retention` | | `1h` | Retention the stale-object count assumes; keep equal to the janitor's `--retention` | -| `--cleanup-grace` | | `15m` | Cleanup grace the stale-object count assumes; keep equal to the janitor's `--grace` | -| `--service-identities` | | | Comma-separated names of the Looking Glass service identities allowed to call this gateway. Empty allows none | -| `--aggregate-budgets` | | `false` | Enforce the cell's aggregate admission and probe packet budgets on every caller and issue probe permits. Requires `--cell-slots` at most 8; a principal's share is 2 slots and 32 queued jobs, lowered to `--cell-slots` and `--cell-queue` when those are smaller. See [Aggregate probe budgets](#aggregate-probe-budgets) | +| Flag | Env | Default | Meaning | +| ------------------------------------- | ------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `--site` | `SITE` | | Site this cell serves. Required | +| `--cluster-name` | `CLUSTER_NAME` | | This cell's Karmada member cluster name. Required | +| `--cell` | `CELL` | | Cell name in the mTLS identities. Required | +| `--namespace` | `POD_NAMESPACE` | `galactic-system` | Namespace of the `fabric-router` pods, the election lease and this pod | +| `--pod-name` | `POD_NAME` | | This pod's name. Required | +| `--debug-bind-address` | | | Address the debug service binds to. Empty binds every address in the pod's network namespace, which a port-forward (through the pod's loopback) and the Service both need | +| `--pod-selector` | | `app.kubernetes.io/name=fabric-router` | Label selector of `fabric-router` pods | +| `--certs-selector` | | `app.kubernetes.io/name=fabric-api-certs` | Label selector of the per-node `fabric-api-certs` pods whose identity each sidecar presents | +| `--lease-name` | | `fabric-api-gateway` | Leader election lease name | +| `--debug-port` | | `9346` | Operator debug gRPC port | +| `--metrics-bind-address` | | `:9347` | Address serving `/metrics` | +| `--health-probe-bind-address` | | `:8081` | Address serving `/healthz` and `/readyz` | +| `--tls-cert`, `--tls-key`, `--tls-ca` | `FABRIC_API_TLS_CERT`, `_KEY`, `_CA` | `/var/run/fabric-api/tls/tls.crt`, `tls.key`, `ca.crt` | As for the node | +| `--cell-slots` | | `8` | Node RPCs running at once across all queries | +| `--cell-expensive-slots` | | `2` | Of those, expensive searches | +| `--cell-queue` | | `256` | Node RPCs that may wait for a slot | +| `--max-nodes` | | `32` | Nodes one query executes on in this cell (ceiling 32) | +| `--max-object-bytes` | | `393216` (384 KiB) | Serialized `FabricQuery` size ceiling (ceiling 384 KiB) | +| `--max-node-response-bytes` | | `131072` (128 KiB) | Node response ceiling (ceiling 128 KiB) | +| `--max-in-flight` | | `256` | Queries executing at once; more wait for a requeue | +| `--retention` | | `1h` | Retention the stale-object count assumes; keep equal to the janitor's `--retention` | +| `--cleanup-grace` | | `15m` | Cleanup grace the stale-object count assumes; keep equal to the janitor's `--grace` | +| `--service-identities` | | | Comma-separated names of the Looking Glass service identities allowed to call this gateway. Empty allows none | +| `--service-config-map` | | | ConfigMap in `--namespace` whose key `service` turns Looking Glass execution on (`enabled`) or off while the gateway runs, read every second. Empty keeps it off. Needs `--aggregate-budgets`. See [Operating the Looking Glass service](#operating-the-looking-glass-service) | +| `--aggregate-budgets` | | `false` | Enforce the cell's aggregate admission and probe packet budgets on every caller and issue probe permits. Requires `--cell-slots` at most 8. See [Aggregate probe budgets](#aggregate-probe-budgets) | +| Limit flags | | The contract's | `--request-*`, `--packet-*`, `--principal-slots`, `--principal-queue`, `--service-streams`, `--project-streams` and `--queue-wait`: the aggregate limits, each only lowerable; need `--aggregate-budgets`. See [Limits and capacity](#limits-and-capacity) | `--max-nodes`, `--max-object-bytes` and `--max-node-response-bytes` can only lower their ceilings: zero or a value above the ceiling selects the ceiling. The @@ -772,8 +777,19 @@ one from the gateway's `RequestPermit`, charged to that operator. When a probe's node call ends without the node's answer, its slot stays held until the job's deadline plus 2 seconds, since the node may still be sending -it. The rates and caps are the contract's defaults; only `--cell-slots` and -`--cell-queue` change them. +it. The rates and caps are the contract's defaults, which are also their +ceilings: [Limits and capacity](#limits-and-capacity) lists the flags that +lower them. + +The leader trusts its clock only while the kernel reports it synchronised, +with an estimated error of at most 500 ms (`adjtimex`, read without +privileges and allowed by the default seccomp profiles). Otherwise its limiter is +unavailable: it admits nothing (`LimiterUnavailable`), cancels the epoch's +work like a failed Lease read, and serves a new 125-second hold once the +clock recovers. A node with `--probe-permits` refuses every permit while its +own clock is unsynchronised. A host whose time daemon (chrony, ntpd, +systemd-timesyncd, Talos timed) disciplines the kernel clock passes; a host +with none does not. ### Stream delivery and transport bounds @@ -798,41 +814,197 @@ calls in flight. ### Enabling -The deployment manifests do not set these flags yet. Turn them on in this -order, each step cell by cell: - -1. **Nodes verify permits.** Give the `fabric-router` ServiceAccount `get` on - the gateway's Lease and mount its token into the `fabric-api` container (the - Component mounts it only into `frr-init` and `config-agent`): - - ```yaml - apiVersion: rbac.authorization.k8s.io/v1 - kind: Role - metadata: - name: fabric-api-node-lease - namespace: galactic-system - rules: - - apiGroups: ["coordination.k8s.io"] - resources: ["leases"] - resourceNames: ["fabric-api-gateway"] - verbs: ["get"] - ``` - - Bind it to the `fabric-router` ServiceAccount and add `--probe-permits` to - the sidecar's args. This changes the pod template, so it is a routing - rollout: follow [Rollout](#rollout). -2. **The gateway enforces budgets.** Add `--aggregate-budgets` to the gateway. - Expect operator and `FabricQuery` probes to be refused for 125 seconds after - each gateway restart. +Opt-in Kustomize Components set these flags. Turn them on in this order, +each step cell by cell: + +1. **Nodes verify permits.** Add + `config/fabric-router/components/fabric-api-permits` after + `components/fabric-api` in the cell's `fabric-router` overlay. It adds + `--probe-permits` to the sidecar, mounts the `fabric-router` + ServiceAccount's token into it and grants `get` on the gateway's Lease + alone (Role `fabric-api-node-lease`). This changes the pod template, so it + is a routing rollout: follow [Rollout](#rollout). +2. **The gateway enforces budgets.** Add + `config/fabric-api/components/aggregate-budgets` to the cell's gateway + overlay. Expect operator and `FabricQuery` probes to be refused for 125 + seconds after each gateway restart. 3. **Nodes require permits.** Until this step, probes operators send nodes directly are not charged, and the Looking Glass service must not be - enabled. Add `--require-probe-permits` and - `--gateway-address=fabric-api-gateway.galactic-system.svc:9346` (the gateway - Service) to the sidecar, so direct operator probes are charged too. Another + enabled. Add `config/fabric-router/components/fabric-api-require-permits` + after `components/fabric-api-permits`. It adds `--require-probe-permits` + and `--gateway-address=fabric-api-gateway.galactic-system.svc:9346` (the + gateway Service), so direct operator probes are charged too. Another routing rollout. +4. **The gateway serves the Looking Glass service, switched off.** Add + `config/fabric-api/components/service` after + `components/aggregate-budgets`. See + [Operating the Looking Glass service](#operating-the-looking-glass-service) + for turning it on. -Roll back in the reverse order. Removing `--aggregate-budgets` while nodes still -require permits refuses every gateway probe (`LimiterUnavailable`). +Each Component that needs an earlier one fails the build without it, so an +overlay cannot list them out of order. Roll back in the reverse order. +Removing `--aggregate-budgets` while nodes still require permits refuses +every gateway probe (`LimiterUnavailable`). + +## Operating the Looking Glass service + +### Turning execution on and off + +A gateway executes a Looking Glass request only when all of these hold: + +- it runs with `--aggregate-budgets`; +- `--service-config-map` names a ConfigMap in its namespace whose key + `service` is exactly `enabled`; +- the caller's service identity is in `--service-identities`. + +`config/fabric-api/components/service` sets `--service-config-map` to +`fabric-api-service`, `--service-identities` to `looking-glass`, and creates +that ConfigMap with `service: disabled` and a Role that lets the gateway +`get` it and no other ConfigMap. Each replica reads it, uncached, every +second. A missing ConfigMap or key, `disabled`, a failed read and any other +value all mean off; the last two log a warning once. The gateway refuses to +start with `--service-config-map` but without `--aggregate-budgets`. + +The ConfigMap carries `kustomize.toolkit.fluxcd.io/ssa: IfNotPresent`, so Flux +creates it once and never overwrites it: the value in the cluster is the +switch, and a reconcile never turns the service back on after an operator +stopped it. To manage it from Git instead, drop the annotation in the +overlay. + +To stop new customer execution: + +```sh +kubectl -n galactic-system patch configmap fabric-api-service --type merge \ + -p '{"data":{"service":"disabled"}}' +``` + +Each replica reads the change within a second, and from then on, without a +restart: + +- a new `RunDiagnostic` is refused with `ServiceDisabled` (`FAILED_PRECONDITION`), + and `GetCapabilities` reports `enabled: false`; +- every running request's queued and running routers are cancelled within 2 + seconds. Each such router's outcome is `Cancelled`, and the stream ends + with `complete` reason `Cancelled` while its consumer is still reading. A + request still in router discovery is refused with `ServiceDisabled`; +- nothing resumes when the service is turned back on. Request tokens and + probe packets already charged stay charged, so the customer service starts + any new attempt itself, with a new request ID. + +Routing, operator `Query`/`ListNodes`, direct node probes, `FabricQuery` +execution and the limiter's buckets and election are untouched: turning the +switch never starts a recovery hold. Turn it back on with +`{"data":{"service":"enabled"}}`. + +### Limits and capacity + +Every limit defaults to the [service contract](service-contract.md#initial-defaults-and-hard-bounds)'s +qualified value, which is also its ceiling: a cell may lower one, never raise +it, until a contract revision qualifies a higher value. A limit flag without +`--aggregate-budgets`, a value above its ceiling, and a combination that +breaks a cross-field rule (a non-positive rate, a burst over 120 seconds of +its rate, a packet burst that cannot fund one 20-packet traceroute, a +per-project or per-principal limit above its cell's) all stop the gateway +from starting, naming every offending limit in its log. A rolling update to +such a configuration leaves the previous replicas serving. + +| Flag | Default and ceiling | Bounds | +| ----------------------------------------------------- | ------------------- | ------------------------------------------------------------------------------------------ | +| `--request-cell-rate`, `--request-cell-burst` | 2/s, 8 | Looking Glass requests admitted in the cell | +| `--request-project-rate`, `--request-project-burst` | 0.2/s, 2 | Looking Glass requests admitted per project | +| `--packet-cell-rate`, `--packet-cell-burst` | 100/s, 640 | Worst-case probe packets charged in the cell, every caller included | +| `--packet-principal-rate`, `--packet-principal-burst` | 20/s, 640 | Worst-case probe packets per project, `FabricQuery` source or operator | +| `--packet-host-rate`, `--packet-host-burst` | 20/s, 640 | Worst-case probe packets per destination address | +| `--packet-prefix-rate`, `--packet-prefix-burst` | 40/s, 640 | Worst-case probe packets per destination IPv4 /24 or IPv6 /64 | +| `--cell-slots`, `--principal-slots` | 8, 2 | Node jobs running at once in the cell, and per principal | +| `--cell-queue`, `--principal-queue` | 256, 32 | Node jobs queued in the cell, and per principal | +| `--service-streams`, `--project-streams` | 16, 2 | Live Looking Glass streams in the cell, and per project, queued and draining ones included | +| `--queue-wait` | 10s | A Looking Glass router job's, or a direct operator permit's, wait for a slot | + +A smaller `--cell-slots`, `--cell-queue` or `--service-streams` lowers the +per-principal default with it. Changing any limit restarts the gateway, so +like any gateway restart it cancels running Looking Glass requests and +refuses every probe in the cell for the 125-second recovery hold; make limit +changes when that pause is acceptable. + +Lower a limit when its traffic is a problem, not because it refuses work. +`fabric_api_gateway_admission_refusals_total` shows which scope refuses: + +- `scope="project"`: one project, `FabricQuery` source or operator at its + own budget. Fairness working; lower the project limits only to protect the + routers or destinations further. +- `scope="cell"`: the cell's budget is exhausted across callers. Raising it + needs a contract revision; lower `--request-project-*` to share it more + evenly. +- `scope="destination"`: probes concentrated on one address or prefix, + whatever their callers. These budgets protect the destination. +- `scope="queue"`: slots, queue or streams are full. A request selecting + fewer routers needs fewer slots. + +The bounds these limits give, from the contract: a cancelled, disabled or +stalled request releases its slots and stops its reachable routers within 2 +seconds; a queued router job dispatches or fails `QueueTimeout` within +`--queue-wait`; a node sends no probe packet later than its permit's deadline +plus 2 seconds, at most 32 seconds after dispatch; a new leader admits +nothing for 125 seconds. In any interval of length T, the packets a bucket of +rate r and burst B allows the cell to send are at most B + r(T + 32): with the +destination host defaults, at most 1300 packets in any one second. + +### Telemetry and diagnosis + +The gateway logs one line per Looking Glass request the leader ran, +`Looking Glass request finished`, with the service name, project, request ID, +operation, reason, router counts (`routers`, `selected`, `successful`, +`failed`, `omitted`, `truncated`) and duration; a request refused before its +snapshot is logged at debug level only. No log line or metric label carries +a target, a result, node error text, or node or pod names, and no metric +label carries a project, request or service name. + +To find out why requests fail: + +1. `fabric_api_gateway_service_requests_total{operation,reason}` gives each + request's end: a terminal coverage reason (`Succeeded`, `PartialResults`, + `ExecutionFailed`, ...), the refusal's reason before the snapshot + (`Throttled`, `QueueFull`, `ServiceDisabled`, `LimiterUnavailable`, ...), + or `DeliveryFailed` when the stream broke. A follower counts only what it + refused itself. +2. For throttling, `fabric_api_gateway_admission_refusals_total{class,scope,reason}` + splits refusals by traffic class (`service`, `operator`, `fabricquery`) + and limiter scope; see [Limits and capacity](#limits-and-capacity). +3. For `LimiterUnavailable`, `fabric_api_gateway_limiter_state` shows whether + the leader is `ready`, `recovering` or `unavailable`, and + `fabric_api_gateway_clock_synchronized` whether its clock is trusted. + `fabric_api_gateway_limiter_keys{kind}` near 4096 project or 16384 + destination keys means new keys are refused until old ones refill. +4. For failed routers, `fabric_api_gateway_service_router_outcomes_total{operation,outcome}` + gives each router's failure or omission reason, and + `fabric_api_node_permits_total{outcome}` on the node why it refused a + permit. +5. A specific request's log line, found by its request ID, gives its counts. + +### Upgrade and rollback + +Roll out in the [Enabling](#enabling) order, then switch the service on only +after the cell's qualification. Every replica must run an image that knows +`--service-config-map` before `components/service` is applied; an older +image refuses to start on the unknown flag. A node without `--probe-permits` +never runs a probe for the gateway under `--aggregate-budgets` (its router +fails `QueryTypeUnavailable`), so mixed node versions reduce coverage, not +the budgets. + +To roll back: + +1. Switch the service off (above); running requests stop within 2 seconds. +2. Remove `components/service`. Its ConfigMap is pruned, which also reads as + off. +3. Remove `components/fabric-api-require-permits`, a routing rollout. Direct + operator probes are no longer charged. +4. Remove `components/aggregate-budgets`. Probes are no longer charged to + the aggregate budgets. +5. Remove `components/fabric-api-permits`, a routing rollout. + +Keep step 4 after step 3: nodes requiring permits refuse every probe while +no gateway issues them. ## Probe sources and destinations @@ -936,17 +1108,21 @@ Scrape config and alert rules are in `config/monitoring/` (not part of - The `fabric-api` group in `prometheusrule.yaml`, unit-tested by `task test:alerts`. None fires merely because nobody ran a query. -| Alert | Fires when | For | -| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | --- | -| `FabricAPIExecutionStalled` | A gateway has executions in flight and finished none in 10 minutes | 10m | -| `FabricAPINodeDiagnosticsUnavailable` | `fabric_api_node_diagnostics_available` is 0 | 15m | -| `FabricAPINodeUnreachable` | More than half of at least 5 node calls in 30 minutes were `NodeUnreachable` or `Timeout` | 15m | -| `FabricAPIResultsOversized` | 10 or more `ResponseTooLarge` outcomes on a node in an hour | 15m | -| `FabricAPICleanupBacklog` | More than 50 stale `FabricQuery` objects | 1h | -| `FabricAPICertificateRenewalFailing` | A loaded certificate has less than 4 hours left | 15m | -| `FabricAPICredentialsMissing` | `fabric_api_credentials_loaded` is 0 | 15m | -| `FabricAPISearchIndexUnsynced` | `fabric_api_node_search_index_synced` is 0 on a node whose index has held routes (a node with no `bmp targets fabric-api` block never fires) | 15m | -| `FabricAPIMetricsDown` | A fabric-api target cannot be scraped | 10m | +| Alert | Fires when | For | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | --- | +| `FabricAPIExecutionStalled` | A gateway has executions in flight and finished none in 10 minutes | 10m | +| `FabricAPINodeDiagnosticsUnavailable` | `fabric_api_node_diagnostics_available` is 0 | 15m | +| `FabricAPINodeUnreachable` | More than half of at least 5 node calls in 30 minutes were `NodeUnreachable` or `Timeout` | 15m | +| `FabricAPIResultsOversized` | 10 or more `ResponseTooLarge` outcomes on a node in an hour | 15m | +| `FabricAPICleanupBacklog` | More than 50 stale `FabricQuery` objects | 1h | +| `FabricAPICertificateRenewalFailing` | A loaded certificate has less than 4 hours left | 15m | +| `FabricAPICredentialsMissing` | `fabric_api_credentials_loaded` is 0 | 15m | +| `FabricAPISearchIndexUnsynced` | `fabric_api_node_search_index_synced` is 0 on a node whose index has held routes (a node with no `bmp targets fabric-api` block never fires) | 15m | +| `FabricAPILimiterUnavailable` | No gateway replica in a cell has had a ready aggregate limiter (`fabric_api_gateway_limiter_state{state="ready"}`), so every probe is refused | 10m | +| `FabricAPIClockUnsynchronized` | A gateway with `--aggregate-budgets` or a node with `--probe-permits` runs on a kernel clock not synchronised within 500 ms | 10m | +| `FabricAPIServiceThrottled` | More than half of at least 20 Looking Glass requests in 30 minutes were refused `Throttled`, `QueueFull` or `LimiterUnavailable` | 15m | +| `FabricAPIServiceExecutionFailing` | More than half of at least 10 executed Looking Glass requests in 30 minutes ended `ExecutionFailed`, `NoNodesAvailable`, `OwnershipLost` or `Internal` | 15m | +| `FabricAPIMetricsDown` | A fabric-api target cannot be scraped | 10m | All are `severity: warning`, `service: galactic`, `team: connect`. On Datum's infra the PodMonitors are scraped on each edge cluster but the rules are evaluated from @@ -965,8 +1141,12 @@ Node metrics (port 9345, a private registry with Go and process collectors): `fabric_api_node_expensive_breaker_open`, `fabric_api_node_probe_packets_total`, `fabric_api_node_identity_refreshes_total{outcome}`, +`fabric_api_node_permits_total{outcome}` (`accepted`, or why a permit was +refused: `malformed`, `mismatch`, `expired`, `starting`, `clock`, `lease`, +`epoch`, `replayed`, `full`), `fabric_api_certificate_expiry_timestamp_seconds` and -`fabric_api_credentials_loaded`. +`fabric_api_credentials_loaded`. With `--probe-permits` the node also exports +`fabric_api_node_clock_synchronized`. Gateway metrics (port 9347, on controller-runtime's registry, so its own metrics appear too): `fabric_api_gateway_queries_total{type,reason}`, @@ -978,7 +1158,17 @@ appear too): `fabric_api_gateway_queries_total{type,reason}`, `completion`), `fabric_api_gateway_executions_in_flight`, `fabric_api_gateway_queue_wait_seconds` (time a node RPC waited for a cell slot), `fabric_api_gateway_stale_objects`, `fabric_api_certificate_expiry_timestamp_seconds` -and `fabric_api_credentials_loaded`. Request IDs and targets are never labels. +and `fabric_api_credentials_loaded`. For the Looking Glass service: +`fabric_api_gateway_service_enabled`, +`fabric_api_gateway_service_requests_total{operation,reason}`, +`fabric_api_gateway_service_router_outcomes_total{operation,outcome}` and +`fabric_api_gateway_service_request_duration_seconds{operation}`. With +`--aggregate-budgets`: `fabric_api_gateway_admission_refusals_total{class,scope,reason}`, +`fabric_api_gateway_probe_packets_charged_total{class}`, +`fabric_api_gateway_limiter_state{state}`, `fabric_api_gateway_limiter_keys{kind}`, +`fabric_api_gateway_service_streams` and `fabric_api_gateway_clock_synchronized`. +Request, project and service IDs, node names and targets are never labels; +[Telemetry and diagnosis](#telemetry-and-diagnosis) walks them. ## Rollout diff --git a/docs/fabric-api/service-contract.md b/docs/fabric-api/service-contract.md index 25c76cf27..edaca8101 100644 --- a/docs/fabric-api/service-contract.md +++ b/docs/fabric-api/service-contract.md @@ -28,8 +28,8 @@ schemas and result meanings. FabricQuery retains its existing persistence and resume semantics; customer requests have no such persistence or replay. Today, `api/fabric/v1/fabric.proto` exposes only unary methods. The gateway -authenticates service identities and validates their requests (#1043). With -`gateway.Service.Enabled` set, the leader streams a request as specified under +authenticates service identities and validates their requests (#1043). While +its `gateway.Service.Switch` is on, the leader streams a request as specified under "Stream grammar and coverage": `Discoverer.Inventory` takes the unique-router snapshot, `Runner.Stream` hands off each router's outcome as it finishes, and the terminal coverage follows (#1044). With the gateway's `--aggregate-budgets`, @@ -39,16 +39,24 @@ nodes run with `--probe-permits` verify each probe's permit (#1045). Execution requires the gateway's admission, and capabilities advertise `aggregate-probe-budgets` only while execution is enabled with it. Nodes charge direct operator probes only with `--require-probe-permits`, so enabling -execution requires every node to run with it. No deployment sets `Enabled` or -these flags, so a valid `RunDiagnostic` is answered with `ServiceDisabled`. +execution requires every node to run with it. Opt-in Kustomize Components set +these flags, and the gateway's `--service-config-map` names the ConfigMap +whose `service` key switches execution on and off at run time (#1047); it +ships off, so a valid `RunDiagnostic` is answered with `ServiceDisabled` until +an operator switches it on. The delivery and transport bounds under "Cancellation, delivery, and failure assumptions" are enforced (#1046): one writer per stream, the 2 s write and hand-off bound on the leader and on a forwarding follower, the per-outcome and per-stream output caps, the per-replica call and service connection caps, fixed 64 KiB windows and buffers, and keepalive on the gateway listener (`internal/fabric/gateway/stream.go`). A shutdown signal stops the listener at -once. Service disable is a startup setting until #1047 adds its controls, and -the metrics and packaged configuration are #1047's. Operator and FabricQuery +once. Switching the service off cancels its running requests within the 2 s +bound without a restart. The limits are gateway flags that may only lower +the defaults below; the gateway refuses to start on any other value, and +the leader and nodes fail closed while the kernel clock is unsynchronised +within 500 ms. [configuration.md](configuration.md#operating-the-looking-glass-service) +documents the switch, the limit flags, the metrics, the alerts and the +upgrade and rollback order. Operator and FabricQuery discovery still return pod candidates, including duplicates. ## Service and identity @@ -651,8 +659,9 @@ an operator explicitly returns to legacy policy. Removing permit enforcement must not leave a service advertising aggregate guarantees. No service endpoint is exposed publicly by this contract. Configure it alongside -the internal gateway listener with distinct method authorization. #1047 defines -validated configuration keys and operational commands from these semantics. +the internal gateway listener with distinct method authorization. Its +validated configuration keys and operational commands are in +[configuration.md](configuration.md#operating-the-looking-glass-service). Metrics use bounded labels (operation, reason, traffic class, limiter scope), never project IDs, request IDs, destinations, node UIDs, or result contents. Routine logs may contain sanitized attempt metadata but not diagnostic output, diff --git a/internal/fabric/gateway/admission.go b/internal/fabric/gateway/admission.go index 71a9f985f..f8e70fc57 100644 --- a/internal/fabric/gateway/admission.go +++ b/internal/fabric/gateway/admission.go @@ -13,9 +13,11 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" + servicev1 "go.datum.net/galactic/api/fabric/service/v1" fabricv1 "go.datum.net/galactic/api/fabric/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" ) @@ -35,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 @@ -78,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]++ @@ -93,6 +99,43 @@ 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 +// and the function that ends the stream. +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 refuse(err) + } + if err := a.Buckets.ChargeRequest(project, a.now()); err != nil { + return refuse(err) + } + if err := a.Attempts.Register(attemptKey(caller, req), requestDigest(req), req.GetExpiresAt().AsTime(), + a.now()); err != nil { + return refuse(err) + } + closeStream, err := a.openStream(project) + if err != nil { + return nil, nil, err + } + return epochCtx, closeStream, nil +} + // probeCost is a probe's worst-case packet count. func probeCost(t query.Type) int { if t == query.TypeTraceroute { @@ -109,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) @@ -117,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/limit/authority.go b/internal/fabric/gateway/limit/authority.go index 6526e7d99..110b52c96 100644 --- a/internal/fabric/gateway/limit/authority.go +++ b/internal/fabric/gateway/limit/authority.go @@ -25,6 +25,10 @@ const ( RecoveryHold = 125 * time.Second // LeaseReadTimeout bounds each uncached election Lease read. LeaseReadTimeout = time.Second + // MaxClockError bounds the kernel's estimate of its clock's error: two + // clocks within it of true time are within the contract's 1 s of each + // other. + MaxClockError = 500 * time.Millisecond ) // Epoch identifies one term of the election: the Lease object's UID and @@ -67,7 +71,8 @@ func ReadEpoch(ctx context.Context, r client.Reader, namespace, name string, now // remaining delay; the first valid read after the hold empties the buckets // and admits from that instant. A failed read, another holder or an expired // term refuses with OwnershipLost and cancels the context of the epoch's -// work. +// work. An unhealthy Clock is treated like a failed read, refused with +// LimiterUnavailable. type Authority struct { // Reader must read uncached. Reader client.Reader @@ -77,6 +82,9 @@ type Authority struct { Identity string // Buckets are emptied when a hold ends. Buckets *Buckets + // Clock, when set, reports an error while this host's clock cannot be + // trusted within MaxClockError; KernelClock is the production check. + Clock func() error // Hold overrides RecoveryHold; tests only. Hold time.Duration // Now returns the current time; nil selects time.Now. @@ -114,6 +122,10 @@ func (a *Authority) Check(ctx context.Context) (Epoch, context.Context, error) { if err == nil && epoch.Holder != a.Identity { err = errcode.Status(errcode.OwnershipLost, "this gateway does not hold the election lease") } + if err == nil && a.Clock != nil && a.Clock() != nil { + err = errcode.Retry(errcode.LimiterUnavailable, "this gateway's clock is not synchronised", string(ScopeCell), + time.Second) + } a.mu.Lock() defer a.mu.Unlock() if err != nil { @@ -136,6 +148,29 @@ func (a *Authority) Check(ctx context.Context) (Epoch, context.Context, error) { return a.epoch, a.epochCtx, nil } +// Authority states, as State reports them. +const ( + StateReady = "ready" + StateRecovering = "recovering" + StateUnavailable = "unavailable" +) + +// State reports StateReady while the authority admits work, +// StateRecovering during a recovery hold, and StateUnavailable while this +// process does not hold the election or could not confirm it at its last +// check. +func (a *Authority) State() string { + a.mu.Lock() + defer a.mu.Unlock() + switch { + case a.active: + return StateReady + case a.epochCtx != nil: + return StateRecovering + } + return StateUnavailable +} + // WatchInterval is how often Watch confirms ownership. const WatchInterval = time.Second diff --git a/internal/fabric/gateway/limit/clock_linux.go b/internal/fabric/gateway/limit/clock_linux.go new file mode 100644 index 000000000..183689b5a --- /dev/null +++ b/internal/fabric/gateway/limit/clock_linux.go @@ -0,0 +1,38 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package limit + +import ( + "errors" + "fmt" + "time" + + "golang.org/x/sys/unix" +) + +// KernelClock reports an error unless the kernel considers its clock +// synchronised, with an estimated error of at most MaxClockError. It reads +// the clock discipline with adjtimex without changing it, which needs no +// capability and which the default containerd and Docker seccomp profiles +// allow: a host whose time daemon (chrony, ntpd, systemd-timesyncd, Talos +// timed) disciplines the kernel clock passes, and one with no daemon +// reports TIME_ERROR. The kernel's maximum error is not used: it grows by +// 500 µs every second between the daemon's updates, which chrony spaces up +// to about 17 minutes apart, so it exceeds the bound on a healthy host; the +// kernel reports TIME_ERROR itself once it reaches 16 s. +func KernelClock() error { + var tx unix.Timex + state, err := unix.Adjtimex(&tx) + if err != nil { + return fmt.Errorf("read the clock discipline: %w", err) + } + if state == unix.TIME_ERROR { + return errors.New("the kernel clock is not synchronised") + } + if estErr := time.Duration(tx.Esterror) * time.Microsecond; estErr > MaxClockError { + return fmt.Errorf("the kernel clock's estimated error %s exceeds %s", estErr, MaxClockError) + } + return nil +} diff --git a/internal/fabric/gateway/limit/clock_other.go b/internal/fabric/gateway/limit/clock_other.go new file mode 100644 index 000000000..749627337 --- /dev/null +++ b/internal/fabric/gateway/limit/clock_other.go @@ -0,0 +1,13 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +//go:build !linux + +package limit + +import "errors" + +// KernelClock reports every clock unhealthy: only Linux exposes the clock +// discipline it reads. +func KernelClock() error { return errors.New("clock health is unknown on this platform") } diff --git a/internal/fabric/gateway/limit/limit_test.go b/internal/fabric/gateway/limit/limit_test.go index ff3701fce..2e5c03b90 100644 --- a/internal/fabric/gateway/limit/limit_test.go +++ b/internal/fabric/gateway/limit/limit_test.go @@ -48,6 +48,38 @@ func TestDefaultsValidate(t *testing.T) { } } +func TestQualified(t *testing.T) { + if err := Defaults().Qualified(); err != nil { + t.Fatalf("defaults above their own ceilings: %v", err) + } + lower := Defaults() + lower.PacketHost = Rate{PerSecond: 10, Burst: 320} + lower.PrincipalSlots, lower.ProjectStreams = 1, 1 + if err := lower.Qualified(); err != nil { + t.Errorf("lowered limits refused: %v", err) + } + cases := map[string]func(*Limits){ + "request cell rate": func(l *Limits) { l.RequestCell.PerSecond = 3 }, + "request project": func(l *Limits) { l.RequestProject.Burst = 3 }, + "packet cell burst": func(l *Limits) { l.PacketCell.Burst = 641 }, + "packet principal": func(l *Limits) { l.PacketPrincipal.PerSecond = 21 }, + "packet host": func(l *Limits) { l.PacketHost.PerSecond = 21 }, + "packet prefix": func(l *Limits) { l.PacketPrefix.Burst = 700 }, + "principal slots": func(l *Limits) { l.PrincipalSlots = 3 }, + "principal queue": func(l *Limits) { l.PrincipalQueue = 33 }, + "project streams": func(l *Limits) { l.ProjectStreams = 3 }, + } + for name, mod := range cases { + t.Run(name, func(t *testing.T) { + l := Defaults() + mod(&l) + if err := l.Qualified(); err == nil { + t.Fatal("limit above its qualified ceiling accepted") + } + }) + } +} + func TestValidateRejects(t *testing.T) { cases := map[string]func(*Limits){ "zero rate": func(l *Limits) { l.PacketCell.PerSecond = 0 }, @@ -437,3 +469,47 @@ func TestAuthorityIgnoresCallerCancellation(t *testing.T) { t.Fatalf("authority left its active state: %v", err) } } + +// An unsynchronised clock is uncertainty like a failed Lease read: work is +// refused and cancelled, and admission resumes only after a new hold. +func TestAuthorityClockHealth(t *testing.T) { + clk := &clock{now: t0} + lc := newLease(t, holderA, t0) + var clockErr error + a := &Authority{Reader: lc, Namespace: leaseNS, Name: leaseName, Identity: holderA, + Buckets: NewBuckets(Defaults(), t0), Now: clk.Now, Hold: time.Second, + Clock: func() error { return clockErr }} + if s := a.State(); s != StateUnavailable { + t.Fatalf("state before any check = %s", s) + } + _, _, _ = a.Check(t.Context()) + if s := a.State(); s != StateRecovering { + t.Fatalf("state in hold = %s", s) + } + clk.now = t0.Add(time.Second) + lc.set(t, "u1", clk.now) + _, ctx, err := a.Check(t.Context()) + if err != nil { + t.Fatal(err) + } + if s := a.State(); s != StateReady { + t.Fatalf("state after hold = %s", s) + } + + clockErr = errors.New("unsynchronised") + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + if ctx.Err() == nil { + t.Fatal("epoch context survived an unhealthy clock") + } + if s := a.State(); s != StateUnavailable { + t.Fatalf("state with an unhealthy clock = %s", s) + } + + clockErr = nil + _, _, err = a.Check(t.Context()) + wantCode(t, err, errcode.LimiterUnavailable) + if d, _ := errcode.RetryDelay(err); d != time.Second { + t.Fatalf("hold after the clock recovered = %s", d) + } +} diff --git a/internal/fabric/gateway/limit/limits.go b/internal/fabric/gateway/limit/limits.go index 449cff6c5..1d02d1b5b 100644 --- a/internal/fabric/gateway/limit/limits.go +++ b/internal/fabric/gateway/limit/limits.go @@ -153,3 +153,33 @@ func (l Limits) Validate() error { } return errors.Join(errs...) } + +// Qualified refuses limits above the contract's qualified ceilings, its +// Defaults: a cell may lower a rate, burst or count, never raise one, until +// a contract revision qualifies the higher value. It complements Validate, +// which checks the cross-field rules every set of limits must meet. +func (l Limits) Qualified() error { + d := Defaults() + var errs []error + rate := func(name string, r, top Rate) { + if r.PerSecond > top.PerSecond || r.Burst > top.Burst { + errs = append(errs, fmt.Errorf("%s: rate %g burst %g exceeds the qualified rate %g burst %g", + name, r.PerSecond, r.Burst, top.PerSecond, top.Burst)) + } + } + rate("request cell", l.RequestCell, d.RequestCell) + rate("request project", l.RequestProject, d.RequestProject) + rate("packet cell", l.PacketCell, d.PacketCell) + rate("packet principal", l.PacketPrincipal, d.PacketPrincipal) + rate("packet host", l.PacketHost, d.PacketHost) + rate("packet prefix", l.PacketPrefix, d.PacketPrefix) + count := func(name string, v, top int) { + if v > top { + errs = append(errs, fmt.Errorf("%s: %d exceeds the qualified %d", name, v, top)) + } + } + count("principal slots", l.PrincipalSlots, d.PrincipalSlots) + count("principal queue", l.PrincipalQueue, d.PrincipalQueue) + count("project streams", l.ProjectStreams, d.ProjectStreams) + return errors.Join(errs...) +} 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 621286e20..9d26b5411 100644 --- a/internal/fabric/gateway/runner.go +++ b/internal/fabric/gateway/runner.go @@ -243,9 +243,9 @@ var errOwnershipLost = errors.New("the gateway lost execution ownership") var errOutputLimit = errors.New("the stream's output budget is exhausted") // requestErr reports a failure that ctx's end, or the request's expiration, -// caused as the request's own DeadlineExceeded, Cancelled or, when the -// election was lost or the output budget ran out, OwnershipLost or -// OutputLimitExceeded. +// caused as the request's own DeadlineExceeded, Cancelled (also when the +// service was turned off) or, when the election was lost or the output +// budget ran out, OwnershipLost or OutputLimitExceeded. func requestErr(ctx context.Context, err error, expired bool) error { if err == nil || (ctx.Err() == nil && !expired) { return err @@ -258,6 +258,9 @@ func requestErr(ctx context.Context, err error, expired bool) error { if errors.Is(context.Cause(ctx), errOwnershipLost) { return errcode.Status(errcode.OwnershipLost, "the gateway lost execution ownership before the router finished") } + if errors.Is(context.Cause(ctx), errServiceDisabled) { + return errcode.Status(errcode.Cancelled, "the service was disabled before the router finished") + } if errors.Is(context.Cause(ctx), errOutputLimit) { return errcode.Status(errcode.OutputLimitExceeded, "the stream's output budget ran out before the router finished") } @@ -285,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") } @@ -320,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 df7bbf392..f33e5d8bf 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" @@ -78,7 +79,7 @@ const ( // probes are charged too. func (s *Service) features() []string { f := []string{FeatureRouterOutcomes, FeatureTerminalCoverage} - if s.Enabled && s.Admission != nil { + if s.enabled() { f = append(f, FeatureAggregateProbeBudgets) } return f @@ -218,15 +219,16 @@ type LeaderDialer interface { // Service implements the Looking Glass service. Any replica authenticates // and validates a request; a follower forwards it once to the leader, which -// validates it again before executing. Unless Enabled and given an +// validates it again before executing. Unless its Switch is on and it has an // Admission, the leader refuses a valid request with ServiceDisabled. type Service struct { servicev1.UnimplementedLookingGlassServiceServer // Cell is the cell this gateway serves. Cell string - // Enabled makes the leader execute valid requests. - Enabled bool + // Switch, while on, makes the leader execute valid requests; turning it + // off cancels those running. A nil Switch is off. + Switch *ServiceSwitch // Admission enforces the cell's aggregate admission and probe budgets. // It must be the Runner's; without it nothing executes. Admission *Admission @@ -243,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 @@ -257,6 +261,13 @@ func (s *Service) now() time.Time { return time.Now() } +// enabled reports whether the service executes requests: its Switch is on +// and it has an Admission. +func (s *Service) enabled() bool { + on, _ := s.Switch.State() + return on && s.Admission != nil +} + // GetCapabilities reports the cell's service policy. func (s *Service) GetCapabilities( ctx context.Context, req *servicev1.GetCapabilitiesRequest, @@ -282,7 +293,7 @@ func (s *Service) capabilities() *servicev1.GetCapabilitiesResponse { resp := &servicev1.GetCapabilitiesResponse{ Cell: s.Cell, ApiMajor: ServiceAPIMajor, - Enabled: s.Enabled && s.Admission != nil, + Enabled: s.enabled(), Operations: []*servicev1.Operation{ {Type: fabricv1.QueryType_QUERY_TYPE_ROUTE_LOOKUP, AddressFamilies: families}, {Type: fabricv1.QueryType_QUERY_TYPE_BGP_SUMMARY, AddressFamilies: families}, @@ -359,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() { @@ -542,16 +554,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) @@ -584,7 +600,8 @@ func (s *Service) forward( // write or a hand-off to the buffer blocked for SendBound, cancels every // router still running and ends the stream without complete; the deadline, // the loss of the election and the output budget cancel them too, but the -// stream still ends with complete. An outcome larger than +// stream still ends with complete, as it does when the Switch is turned off. +// An outcome larger than // maxOutcomeBytes is delivered as a ResponseTooLarge failure, and once the // stream's output budget cannot hold an outcome, that router and every // router still running fail with OutputLimitExceeded. A failure before the @@ -594,41 +611,35 @@ 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") } adm := s.Admission - if !s.Enabled || adm == nil || s.Discoverer == nil || s.Runner == nil { + on, offCtx := s.Switch.State() + if !on || adm == nil || s.Discoverer == nil || s.Runner == nil { return errcode.Status(errcode.ServiceDisabled, "this cell does not execute Looking Glass service diagnostics") } project := req.GetProjectId() - _, epochCtx, err := adm.Authority.Check(ctx) - if err != nil { - return err - } - if err := adm.Buckets.ChargeRequest(project, adm.now()); err != nil { - return err - } - if err := adm.Attempts.Register(attemptKey(caller, req), requestDigest(req), req.GetExpiresAt().AsTime(), - adm.now()); err != nil { - return err - } - closeStream, err := adm.openStream(project) + epochCtx, closeStream, err := adm.admit(ctx, caller, req) if err != nil { return err } defer closeStream() // sendCtx ends when the stream does, a write fails or the consumer - // stalls; runCtx also ends at the deadline, when the election is lost or - // when the output budget runs out. Outcomes those cut short still reach - // the writer, so the consumer can see them while the stream lasts. + // stalls; runCtx also ends at the deadline, when the election is lost, + // when the service is turned off or when the output budget runs out. + // Outcomes those cut short still reach the writer, so the consumer can + // see them while the stream lasts. sendCtx, abort := context.WithCancelCause(ctx) defer abort(nil) ownedCtx, lose := context.WithCancelCause(sendCtx) defer lose(nil) defer context.AfterFunc(epochCtx, func() { lose(errOwnershipLost) })() + defer context.AfterFunc(offCtx, func() { lose(errServiceDisabled) })() runCtx, cancel := context.WithDeadline(ownedCtx, deadline) defer cancel() @@ -640,6 +651,8 @@ func (s *Service) execute( switch { case errors.Is(context.Cause(runCtx), errOwnershipLost): return errcode.Status(errcode.OwnershipLost, "the election was lost during router discovery") + case errors.Is(context.Cause(runCtx), errServiceDisabled): + return errcode.Status(errcode.ServiceDisabled, "the service was disabled during router discovery") case errors.Is(runCtx.Err(), context.DeadlineExceeded): return errcode.Status(errcode.DeadlineExceeded, "request's deadline passed during router discovery") case runCtx.Err() != nil: @@ -653,8 +666,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) @@ -671,6 +686,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() @@ -723,13 +741,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/service_execution_test.go b/internal/fabric/gateway/service_execution_test.go index 30429b702..45cf6727b 100644 --- a/internal/fabric/gateway/service_execution_test.go +++ b/internal/fabric/gateway/service_execution_test.go @@ -174,7 +174,7 @@ func newService(t *testing.T, objs []client.Object, nodes *routerNodes, slots in certs, _ := labels.Parse(DefaultCertsSelector) adm := newTestAdmission(t, roomyLimits()) return &Service{ - Cell: testSite, Allowlist: testAllowlist, Elected: elected, Enabled: true, Revision: "abc123", + Cell: testSite, Allowlist: testAllowlist, Elected: elected, Switch: switchedOn(), Revision: "abc123", Discoverer: &Discoverer{Reader: reader, Namespace: DefaultNamespace, Selector: sel, CertsSelector: certs}, Runner: &Runner{Clients: nodes, Executor: NewExecutor(slots, 0, 0), QueueWait: 200 * time.Millisecond, Admission: adm}, @@ -182,6 +182,13 @@ func newService(t *testing.T, objs []client.Object, nodes *routerNodes, slots in } } +// switchedOn returns a service switch that is on. +func switchedOn() *ServiceSwitch { + w := &ServiceSwitch{} + w.Set(true) + return w +} + // chanStream is a RunDiagnostic server stream that hands each event to a // channel, and fails a send once failAt events were sent, or every send // when failAt is negative. @@ -726,7 +733,7 @@ func TestServiceCapabilities(t *testing.T) { t.Errorf("features = %v", f) } again, _ := svc.GetCapabilities(ctx, req) - svc.Enabled = false + svc.Switch.Set(false) off, _ := svc.GetCapabilities(ctx, req) // With execution off nothing is advertised as enforced. if slices.Contains(off.GetFeatures(), FeatureAggregateProbeBudgets) || off.GetLimits().GetAdmission() != nil { @@ -738,7 +745,7 @@ func TestServiceCapabilities(t *testing.T) { // A request requiring an unserved feature, or a budget above its // maximum, is refused before any work. - svc.Enabled = true + svc.Switch.Set(true) for name, edit := range map[string]func(*runReq){ "unknown feature": func(r *runReq) { r.RequiredFeatures = []string{"router-outcomes-v2"} }, "large budget": func(r *runReq) { r.Budgets = &fabricv1.Budgets{MaxPathsPerPrefix: 9} }, diff --git a/internal/fabric/gateway/serviceswitch.go b/internal/fabric/gateway/serviceswitch.go new file mode 100644 index 000000000..af7817bcb --- /dev/null +++ b/internal/fabric/gateway/serviceswitch.go @@ -0,0 +1,130 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gateway + +import ( + "context" + "errors" + "log/slog" + "sync" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// ServiceSwitchKey is the key of the service ConfigMap that turns Looking +// Glass execution on: only ServiceSwitchEnabled does. +const ( + ServiceSwitchKey = "service" + ServiceSwitchEnabled = "enabled" + ServiceSwitchDisabled = "disabled" +) + +// ServiceSwitchInterval is how often Watch reads the service ConfigMap, and +// so how soon a change takes effect. +const ServiceSwitchInterval = time.Second + +// serviceSwitchReadTimeout bounds one read of the service ConfigMap. +const serviceSwitchReadTimeout = time.Second + +// errServiceDisabled is the cause with which a service request's execution +// is cancelled when the service is turned off. +var errServiceDisabled = errors.New("the Looking Glass service was disabled") + +// ServiceSwitch turns Looking Glass service execution on and off while the +// gateway runs. Its zero value is off. Turning it off cancels the context +// State handed every running request, so their routers stop; turning it +// back on admits new requests and resumes nothing. It never touches +// operator or FabricQuery work, or the limiter's state. +type ServiceSwitch struct { + mu sync.Mutex + on bool + ctx context.Context + cancel context.CancelCauseFunc +} + +// State reports whether the service executes and, when it does, a context +// that ends when it is turned off. A nil switch is off. +func (w *ServiceSwitch) State() (bool, context.Context) { + if w == nil { + return false, nil + } + w.mu.Lock() + defer w.mu.Unlock() + return w.on, w.ctx +} + +// Set turns the service on or off. +func (w *ServiceSwitch) Set(on bool) { + w.mu.Lock() + defer w.mu.Unlock() + if on == w.on { + return + } + w.on = on + if on { + w.ctx, w.cancel = context.WithCancelCause(context.Background()) + } else { + w.cancel(errServiceDisabled) + w.ctx, w.cancel = nil, nil + } + slog.Info("Looking Glass service execution switched", "enabled", on) +} + +// Watch reads key ServiceSwitchKey of ConfigMap namespace/name with reader, +// which should read uncached, every interval until ctx ends, and sets the +// switch from it. The service is on only while the read succeeds and the key +// is exactly ServiceSwitchEnabled: a missing ConfigMap or key, the value +// ServiceSwitchDisabled, a failed read or any other value turns it off, +// the last two with a warning when the problem first appears. It turns the +// service off when ctx ends. +func (w *ServiceSwitch) Watch(ctx context.Context, reader client.Reader, namespace, name string, + interval time.Duration) { + t := time.NewTicker(interval) + defer t.Stop() + var last string + for { + on, problem := readServiceSwitch(ctx, reader, namespace, name) + if ctx.Err() != nil { + w.Set(false) + return + } + if problem != "" && problem != last { + slog.Warn("Looking Glass execution is off: "+problem, "configmap", name, "key", ServiceSwitchKey) + } + last = problem + w.Set(on) + select { + case <-ctx.Done(): + w.Set(false) + return + case <-t.C: + } + } +} + +// readServiceSwitch reads the switch's ConfigMap and reports whether it +// turns the service on, and what is wrong with it when it cannot be read or +// holds an invalid value. +func readServiceSwitch(ctx context.Context, reader client.Reader, namespace, name string) (bool, string) { + ctx, cancel := context.WithTimeout(ctx, serviceSwitchReadTimeout) + defer cancel() + var cm corev1.ConfigMap + if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, &cm); err != nil { + if apierrors.IsNotFound(err) { + return false, "" + } + return false, "the service ConfigMap could not be read" + } + switch cm.Data[ServiceSwitchKey] { + case ServiceSwitchEnabled: + return true, "" + case ServiceSwitchDisabled, "": + return false, "" + } + return false, "the service ConfigMap's value is neither " + ServiceSwitchEnabled + " nor " + ServiceSwitchDisabled +} diff --git a/internal/fabric/gateway/serviceswitch_test.go b/internal/fabric/gateway/serviceswitch_test.go new file mode 100644 index 000000000..88bd5535c --- /dev/null +++ b/internal/fabric/gateway/serviceswitch_test.go @@ -0,0 +1,304 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +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" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + 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/query" +) + +const testSwitchName = "fabric-api-service" + +// switchConfig serves the service ConfigMap, whose reads fail while failing +// is set. +type switchConfig struct { + client.Client + mu sync.Mutex + failing bool +} + +func newSwitchConfig(t *testing.T) *switchConfig { + t.Helper() + s := runtime.NewScheme() + _ = clientgoscheme.AddToScheme(s) + c := &switchConfig{} + c.Client = fake.NewClientBuilder().WithScheme(s).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, + opts ...client.GetOption) error { + c.mu.Lock() + failing := c.failing + c.mu.Unlock() + if failing { + return errors.New("api unavailable") + } + return cl.Get(ctx, key, obj, opts...) + }, + }).Build() + return c +} + +// set writes the ConfigMap's service value; remove deletes it. +func (c *switchConfig) set(t *testing.T, value string) { + t.Helper() + cm := &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: DefaultNamespace, Name: testSwitchName}, + Data: map[string]string{ServiceSwitchKey: value}, + } + if err := c.Update(t.Context(), cm); err != nil { + if err := c.Create(t.Context(), cm); err != nil { + t.Fatal(err) + } + } +} + +func (c *switchConfig) remove(t *testing.T) { + t.Helper() + cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: DefaultNamespace, Name: testSwitchName}} + if err := c.Delete(t.Context(), cm); err != nil { + t.Fatal(err) + } +} + +func (c *switchConfig) fail(on bool) { + c.mu.Lock() + defer c.mu.Unlock() + c.failing = on +} + +// Only the exact value "enabled" turns the service on; everything else, +// including a failed read, turns it off. +func TestServiceSwitchWatch(t *testing.T) { + cfg := newSwitchConfig(t) + w := &ServiceSwitch{} + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + go func() { + defer close(done) + w.Watch(ctx, cfg, DefaultNamespace, testSwitchName, 10*time.Millisecond) + }() + want := func(step string, on bool) { + t.Helper() + within(t, step, time.Now(), time.Second, func() bool { + got, _ := w.State() + return got == on + }) + } + want("missing ConfigMap", false) + cfg.set(t, ServiceSwitchEnabled) + want("enabled", true) + cfg.set(t, ServiceSwitchDisabled) + want("disabled", false) + cfg.set(t, ServiceSwitchEnabled) + want("enabled again", true) + cfg.set(t, "Enabled") + want("invalid value", false) + cfg.set(t, ServiceSwitchEnabled) + want("enabled after an invalid value", true) + cfg.fail(true) + want("unreadable", false) + cfg.fail(false) + want("readable again", true) + cfg.set(t, "") + want("empty value", false) + cfg.set(t, ServiceSwitchEnabled) + want("enabled before removal", true) + cfg.remove(t) + want("removed", false) + cfg.set(t, ServiceSwitchEnabled) + want("recreated", true) + cancel() + <-done + if on, _ := w.State(); on { + t.Error("the switch stayed on after its watch ended") + } +} + +// Turning the switch off cancels a running request within the contract's +// 2 s, ends its stream with Cancelled coverage, and refuses new requests +// with ServiceDisabled; the limiter keeps its state and operator probes +// keep running. +func TestServiceDisableCancelsRunningWork(t *testing.T) { + a := newCancelAnswer() + nodes := &routerNodes{answers: map[string]routerAnswer{routerA: a.answer}} + svc := newService(t, routerPods(routerA, routerB), nodes, 8) + events, done := run(t, svc, validRequest(time.Now()), 0) + if next(t, events).GetSnapshot() == nil { + t.Fatal("first event is not the snapshot") + } + <-a.started + + start := time.Now() + svc.Switch.Set(false) + within(t, "running router cancelled", start, releaseBound, a.cancelled) + var rest []*servicev1.DiagnosticEvent + for ev := range events { + rest = append(rest, ev) + } + if err := <-done; err != nil { + t.Fatalf("stream ended with %v, want OK with complete", err) + } + within(t, "execution released", start, releaseBound, func() bool { return idle(svc) }) + last := rest[len(rest)-1].GetComplete() + if last.GetReason() != string(errcode.Cancelled) { + t.Fatalf("terminal reason = %q", last.GetReason()) + } + for _, ev := range rest { + if o := ev.GetOutcome(); o.GetNode() == routerA && o.GetFailure().GetReason() != string(errcode.Cancelled) { + t.Errorf("router-a outcome = %v", o) + } + } + + if _, err := collect(t, svc, validRequest(time.Now())); errcode.Of(err) != errcode.ServiceDisabled { + t.Fatalf("request while disabled: %v", err) + } + if s := svc.Admission.Authority.State(); s != limit.StateReady { + t.Fatalf("limiter state after disabling = %s", s) + } + nodes.mu.Lock() + nodes.answers = nil + nodes.mu.Unlock() + ping, err := query.Canonicalize(query.Query{Type: query.TypePing, Target: probeTarget6}) + if err != nil { + t.Fatal(err) + } + out := svc.Runner.Run(t.Context(), operatorPrincipal("ops"), testRequestID, ping, + []Node{{Name: routerA, PodUID: podA, Selected: true}}, nil, time.Now().Add(30*time.Second)) + if len(out) != 1 || out[0].Err != nil { + 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, but not one the leader +// ran, 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) + for labels, want := range map[[2]string]float64{ + {ping, string(errcode.VersionUnsupported)}: 1, + {ping, string(errcode.OwnershipLost)}: 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..fc550dac7 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 (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 5164b7e13..71b5de22d 100644 --- a/internal/fabric/node/permit.go +++ b/internal/fabric/node/permit.go @@ -56,7 +56,8 @@ type PermitGateway interface { // at least PermitStartupRefusal after the node started, and only while the // gateway election Lease, read uncached, still carries the permit's epoch. // Consumed IDs are kept until their deadline plus PermitGrace in a set that -// fails closed when full. +// fails closed when full. A node whose Clock is unhealthy refuses every +// permit. type Permits struct { // Reader reads the gateway's election Lease uncached. Reader client.Reader @@ -73,6 +74,11 @@ type Permits struct { // MaxConsumed and MaxConsumedBytes bound the consumed set; zero selects // the defaults. MaxConsumed, MaxConsumedBytes int + // 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 @@ -90,49 +96,79 @@ type grant struct { deadline time.Time } +// Permit decisions, as fabric_api_node_permits_total's outcome label +// reports them. +const ( + PermitAccepted = "accepted" + 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(permitMismatch) 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(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 @@ -146,7 +182,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 { @@ -158,11 +194,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 e34a6ca82..5b5bc0d0e 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,41 +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, 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 { @@ -186,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") + } }) } } diff --git a/tests/manifests/README.md b/tests/manifests/README.md new file mode 100644 index 000000000..0c322a7de --- /dev/null +++ b/tests/manifests/README.md @@ -0,0 +1,6 @@ +# Manifest render fixtures + +`task test:manifests` builds every kustomization here with kustomize. Each +directory under `fabric-api/` composes opt-in Components the way a cell +overlay does and must build; each directory under `invalid/` lists a +Component without the one it requires and must fail to build. diff --git a/tests/manifests/fabric-api/gateway-service/kustomization.yaml b/tests/manifests/fabric-api/gateway-service/kustomization.yaml new file mode 100644 index 000000000..fcd705d08 --- /dev/null +++ b/tests/manifests/fabric-api/gateway-service/kustomization.yaml @@ -0,0 +1,7 @@ +# The gateway enforcing aggregate budgets and serving the Looking Glass +# service behind its switch. +resources: + - ../../../../config/fabric-api/base +components: + - ../../../../config/fabric-api/components/aggregate-budgets + - ../../../../config/fabric-api/components/service diff --git a/tests/manifests/fabric-api/node-permits/kustomization.yaml b/tests/manifests/fabric-api/node-permits/kustomization.yaml new file mode 100644 index 000000000..d93f2805e --- /dev/null +++ b/tests/manifests/fabric-api/node-permits/kustomization.yaml @@ -0,0 +1,7 @@ +# The node sidecar requiring probe permits, with every Component it needs. +resources: + - ../../../../config/fabric-router +components: + - ../../../../config/fabric-router/components/fabric-api + - ../../../../config/fabric-router/components/fabric-api-permits + - ../../../../config/fabric-router/components/fabric-api-require-permits diff --git a/tests/manifests/invalid/permits-without-sidecar/kustomization.yaml b/tests/manifests/invalid/permits-without-sidecar/kustomization.yaml new file mode 100644 index 000000000..b3f8b8285 --- /dev/null +++ b/tests/manifests/invalid/permits-without-sidecar/kustomization.yaml @@ -0,0 +1,4 @@ +resources: + - ../../../../config/fabric-router +components: + - ../../../../config/fabric-router/components/fabric-api-permits diff --git a/tests/manifests/invalid/require-without-permits/kustomization.yaml b/tests/manifests/invalid/require-without-permits/kustomization.yaml new file mode 100644 index 000000000..ceb1052cb --- /dev/null +++ b/tests/manifests/invalid/require-without-permits/kustomization.yaml @@ -0,0 +1,5 @@ +resources: + - ../../../../config/fabric-router +components: + - ../../../../config/fabric-router/components/fabric-api + - ../../../../config/fabric-router/components/fabric-api-require-permits diff --git a/tests/manifests/invalid/service-without-budgets/kustomization.yaml b/tests/manifests/invalid/service-without-budgets/kustomization.yaml new file mode 100644 index 000000000..de3e2da30 --- /dev/null +++ b/tests/manifests/invalid/service-without-budgets/kustomization.yaml @@ -0,0 +1,4 @@ +resources: + - ../../../../config/fabric-api/base +components: + - ../../../../config/fabric-api/components/service