diff --git a/docs/agents/ARCHITECTURE-FABRIC-API.md b/docs/agents/ARCHITECTURE-FABRIC-API.md index d0885f530..562a2944e 100644 --- a/docs/agents/ARCHITECTURE-FABRIC-API.md +++ b/docs/agents/ARCHITECTURE-FABRIC-API.md @@ -1,836 +1,87 @@ # Architecture — fabric-api -The proposed [Looking Glass service contract](../fabric-api/service-contract.md) defines the -separate customer-service API, coverage, aggregate limits, and failure bounds -for #1042. It is a future implementation contract; the interfaces and settings -documented on this page remain the current baseline. - -> The fabric looking glass: a single `fabric-api` binary that answers -> bounded, asynchronous diagnostics about `fabric-router`'s FRR state. Its -> `node` subcommand runs as a sidecar in each `fabric-router` pod and reads -> FRR over its vty sockets or sends ICMP probes from the node's fabric -> loopback; its `gateway` subcommand runs once per edge cell, executes -> `FabricQuery` objects by fanning them out to the node sidecars over mTLS -> gRPC, and serves an operator debug service; its `janitor` subcommand -> deletes expired `FabricQuery` copies the federation failed to delete; its -> `certsync` subcommand runs in a separate per-node pod that obtains the -> sidecar's certificate. Everything is opt-in, and a diagnostic failure never -> gates routing. - -_Last updated: 2026-10-07_ - -This document covers `cmd/fabric-api` and `internal/fabric/` only: the -galactic half of the looking glass. The public `LookingGlassQuery` API, the -federation hub plumbing (the `FabricQuery` hub CRD install, per-cell -propagation policies, Karmada status aggregation) and the cell issuer belong -to other repositories and are described here only where this code depends on -them. See [ARCHITECTURE-ROUTER.md](ARCHITECTURE-ROUTER.md) for the -`galactic-router` control plane and [ARCHITECTURE-GATEWAY.md](ARCHITECTURE-GATEWAY.md) -for the unrelated `galactic-gateway` L4 load balancer: despite the name, -fabric-api's "gateway" is a cell-level query executor and has nothing to do -with `NetworkGateway`. `fabric-router` itself (the FRR underlay DaemonSet and -`fabric-config-agent`) is described in [AGENTS.md](../../AGENTS.md#deployments); -this document covers only the fourth container fabric-api adds to its pod. -Operator-facing configuration is in -[docs/fabric-api/configuration.md](../fabric-api/configuration.md), and the -`FabricQuery` contract is in [docs/fabric-api/api.md](../fabric-api/api.md). - ---- - -## Overview - -`fabric-router` runs FRR as the underlay eBGP speaker on every node, and -FRR's vty sockets live in a pod-scoped `emptyDir` (`/run/frr`), so nothing -outside the pod can read routing state. fabric-api is the supported way to -look at it: it answers seven query types, each against one router's own view. - -| Query type | Reads | Cost | -| ---------------- | ------------------------------------------------------------------------ | ---------------------------------- | -| `RouteLookup` | bgpd (`show bgp unicast json`), zebra | One prefix; exact or longest match | -| `BGPSummary` | bgpd (`show bgp unicast summary json`) | Peer table | -| `Ping` | Raw ICMP socket | 3 echo requests | -| `Traceroute` | Raw ICMP socket | Up to 20 hops, 1 probe per hop | -| `ASPath` | The sidecar's search index (default), or bgpd with `--search-source=frr` | Whole table; gated | -| `Community` | The search index (default), or bgpd | Whole table; gated | -| `LargeCommunity` | The search index (default), or bgpd | Whole table; gated | - -The three scanning types ("expensive" in the code) are refused with -`QueryTypeUnavailable` unless the node runs with `--enable-expensive-queries`. -They search the whole BGP table, so by default they are answered not by FRR but -by a local copy of bgpd's selected routes that the sidecar keeps from a BMP -stream (the search index, `internal/fabric/index`). The full-table load test in -[docs/fabric-api/load-test.md](../fabric-api/load-test.md) showed that FRR's own -scans pin bgpd's main thread and roughly triple convergence after a session reset, -and that the index passes the gate. Searches stay off by default until staging -confirms those numbers on real fabric routers. - -Three principles shape everything below: - -- **Bounded.** Every boundary has a byte, count or time limit that a caller - cannot raise: FRR's response (4 MiB), a node's response (128 KiB), the - `FabricQuery` object (384 KiB), the request lifetime (120 s) and a node's - execution (30 s). Results are shaped down to budget with `truncated=true`, - or refused with `ResponseTooLarge`; they are never persisted unbounded and - trimmed later. -- **Per-router.** Each node's answer is its own observation, with its own - sample time, router ID and ASN. Nothing merges paths across nodes or - invents a location-wide best path. BGP selection and zebra installation - are sampled separately and neither asserts end-to-end reachability. -- **Diagnostics never gate routing.** The sidecar has no readiness, liveness - or startup probe, and a missing certificate, an unreachable vty socket or an - unsupported FRR version makes it report "diagnostics unavailable", not fail. - -The binary is separate from the `fabric-router` image, which carries FRR and -`fabric-config-agent`. The `fabric-api` image is a static Go binary on `scratch` -with no FRR, no `vtysh` and no shell, and it imports no eBPF packages, so -building it needs no clang or `go generate`. The same image serves the node -sidecar, the gateway Deployment, the janitor CronJob, the per-node `certsync` -pod and the operator `query` client. - ---- - -## Repository Layout - -``` -cmd/fabric-api/ - main.go Root command, logging flags, --version/--build-info - node.go `node`: sidecar server, probe source selection - gateway.go `gateway`: controller-runtime manager, debug server - janitor.go `janitor`: expired FabricQuery sweeper - query.go `query`: operator client for the node and the gateway - certsync.go `certsync`: copies a csi-issued certificate to the node - tracing.go W3C propagation; OTLP exporter when configured - -api/fabric/v1/ - fabric.proto FabricService (node) and FabricGatewayService (debug) - fabric.pb.go, fabric_grpc.pb.go Generated by buf, committed -api/fabric/service/v1/ - service.proto LookingGlassService, the customer service's contract -api/fabric/forward/v1/ - forward.proto ForwardService, gateway-only follower-to-leader forwarding -api/fabric/permit/v1/ - permit.proto PermitService, node-only probe permits for direct operator probes - -internal/fabric/ - api/v1alpha1/ FabricQuery types, deepcopy, CRD envtest - query/ Canonical query, destination policy, budgets - frr/ vty client, closed command builder, version gate, parsers - probe/ ICMP ping and traceroute on raw sockets - index/ BMP station and in-memory index of bgpd's selected routes - 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/limit/ Aggregate token buckets, attempt keys, election authority and limits - testpki/ Throwaway CA for tests - -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 - 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/monitoring/ - podmonitor-fabric-router.yaml api-metrics endpoint (job=fabric-api-node) - podmonitor-fabric-api-gateway.yaml - prometheusrule.yaml `fabric-api` rule group - -containers/fabric-api/Dockerfile -hack/fabric-api-loadtest/ Full-table load harness (task test:fabric-api-load) -deploy/containerlab/ deploy:cert-manager, deploy:fabric-api, verify:fabric-api* -``` - -The generated Go files under `api/fabric/v1/` are committed and never hand -edited; regenerate them with `task generate:proto`. `zz_generated.deepcopy.go` -and `config/fabric-api/crd/` come from `task generate:crd`. - ---- - -## Data Flow - -### Federated path (`FabricQuery`) - -A public `LookingGlassQuery` is turned into one `FabricQuery` per resolved cell -by NSO on the federation hub; Karmada propagates it to the one pinned member -cluster. From there the cell gateway takes over: - -``` - hub (NSO, out of scope) edge cell (this repo) - ─────────────────────── ───────────────────────────────────────────── - FabricQuery ──Karmada──► FabricQuery (spec immutable, expiresAt <= 120 s) - │ watch (cached, all namespaces) - ▼ - gateway Reconciler (leader only) - 1. predicate: spec.site and spec.clusterName match - 2. validate: re-canonicalize, clamp budgets, check expiry - 3. snapshot fabric-router pods ──► fixed node list - 4. status: start marker (attempt, nodes, Running) - 5. launch execution under the leader's context - │ - ▼ - Runner: one goroutine per selected node - Executor.Acquire (8 slots, 2 expensive, 256 queue, - round robin across projects) - │ mTLS gRPC Execute, hostIP:9344 - ▼ - node sidecar (one per fabric-router pod) - identity ─► shape ─► node name ─► expiry ─► enabled - type ─► dedup (requestID, node, type) ─► budgets - │ - ┌──────────────┴───────────────┐ - ▼ ▼ - bgpd.vty / zebra.vty (read) raw ICMP socket (probe) - └──────────────┬───────────────┘ - ▼ - Observation, or a typed error - │ - Reconciler.persist: one terminal status write - shape to object budget, set conditions + coverage - │ - FabricQuery.status ◄──Karmada status return── FabricQuery.status - (NSO groups observations by location) -``` - -Execution is at-least-once. The node suppresses duplicates by -`(requestID, node, operation)`, and a completed query (`Complete=True`) is -never touched again. A gateway that dies after an RPC but before the terminal -write is replaced by a leader that resumes on the status's fixed snapshot with -`attempt` incremented, which may repeat node calls; the dedup cache absorbs -most repeats but is in memory, so a node restart or eviction permits one. - -### Operator debug path - -An operator with a certificate carrying an `operator` identity can bypass the -federation, for diagnosing a cell directly: - -``` - fabric-api query ──mTLS──► gateway Service (ClusterIP :9346) - --gateway host:9346 │ any replica; a follower forwards Query to the - │ leader named by the election lease's holder - ▼ - Debug.Query ─► Runner (project key "operator/"; FabricQuery "fabricquery//") - │ nodes see the *gateway* identity, so the - ▼ public destination policy applies - node sidecars - - fabric-api query ──mTLS──► one node sidecar (hostIP:9344) - --node host:9344 node sees an *operator* identity, so the - operator destination policy applies -``` - -Both routes run the same canonicalization, validation and limits as federated -execution. They differ only in which destination policy the node applies, which -follows the caller's role, not the route (see -[Known Constraints](#known-constraints)). - -### Search path (BMP-fed index) - -`ASPath`, `Community` and `LargeCommunity` do not go to bgpd's search commands. -bgpd streams its selected routes to the sidecar, which searches its own copy: - -``` - bgpd ──BMP Loc-RIB (ipv4 + ipv6 unicast)──► Station 127.0.0.1:9348 - `bmp targets fabric-api` │ loopback peer, one session - ▼ - Index: prefix ─► interned attribute set - BeginSession: empty, bgpd resends the table - synced: update rate settles after the - initial dump (or End-of-RIB) - EndSession: unsynced - │ - Execute(ASPath|Community|LargeCommunity) ───────┤ synced: Search ─► matches + - │ exact total + index state - └ unsynced: QueryTypeUnavailable - (no scan of bgpd) -``` - -A search is subject to the same node checks as any other (identity, canonical -query, expiry, `--enable-expensive-queries`) and to the one-search-at-a-time -budget. Its result carries the index's state (`syncedAt`, `lastUpdate`, `version`, -`routes`) so a consumer can judge freshness. - ---- - -## Entry Points - -All subcommands share `--log-level` (env `LOG_LEVEL`, default `info`) and -`--log-format` (env `LOG_FORMAT`, `json` or `text`, default `json`). The root -command also takes `--version`/`-V` and `--build-info`. Every flag with an env -var is listed in [docs/fabric-api/configuration.md](../fabric-api/configuration.md). - -### `cmd/fabric-api/node.go` — `fabric-api node` - -The sidecar. It requires `--node-name`, `--namespace`, `--pod-name` and -`--host-ip` (all from the downward API in the Component) and exits with an -error without them. `--cell` is the exception: with an empty cell the process -does not exit. It logs an error and serves only metrics until signalled, so a -missing per-cell ConfigMap crash-loops nothing in the `fabric-router` pod. -Its certificate is issued to the `fabric-api-certs` pod on its node, not to its -own pod, so its credentials accept any node identity in its cell and namespace -(`Credentials.AcceptAnyNode`); the gateway pins the node's certs pods when it dials. -It reads the certificate from `/var/run/fabric-api/tls`, a read-only hostPath -mount of the node's `/run/fabric-api/tls`. - -With a cell set, `runNode`: - -1. Resolves per-family probe sources (`probeSources`). -2. With `--search-source=index` (the default), creates the search index and its - BMP station on `--bmp-station-address` (`127.0.0.1:9348`) and registers the - index metrics. `--search-source=frr` skips this and answers searches with FRR's - own scans. Any other value is an error. -3. Builds a `node.Server` with a `frr.VTY` (4 MiB read cap), a `probe.Prober`, - the index (if any), the public and operator destination policies and the node - budgets. -4. Starts `identity.Credentials.Run` (reload every 10 s) and `Server.Run` - (reads FRR's version, router ID and ASN every 60 s, every 5 s while FRR is - unreachable; a request that finds the last read unreachable also re-reads - FRR, at most once a second, so a node does not refuse diagnostics for a - minute after FRR comes up). -5. Serves `FabricService` and the standard gRPC health service on - `:9344` with TLS 1.3, a 64 KiB receive limit and a send limit of - the node response ceiling plus 16 KiB. Health is `SERVING` only while - `Info.diagnostics_available` is true, and is wired to no pod probe. -6. Serves `/metrics` on `:9345` unless `--metrics-bind-address` is set. - -With `--probe-permits`, step 3 also gives the server a `node.Permits`, which -reads the gateway's election Lease through an uncached client built from the -pod's service account, and with `--gateway-address` a `PermitService` client -for direct operator probes. - -Shutdown is a graceful gRPC stop with a 10 s limit. - -### `cmd/fabric-api/gateway.go` — `fabric-api gateway` - -The cell executor. It requires `--site`, `--cluster-name`, `--cell` and -`--pod-name`. It builds a controller-runtime manager with leader election -(lease `fabric-api-gateway` in the pods' namespace, released on cancel, held -through its own resource lock under the identity `_`), caches -`Pod`s only in the `fabric-router` namespace and `FabricQuery` cluster-wide, and -registers: - -- the `fabricquery` controller (`gateway.Reconciler`, 8 concurrent reconciles), - whose execution context exists only while this replica leads; -- a `StaleCounter` that publishes `fabric_api_gateway_stale_objects` on every - replica, using `--retention` and `--cleanup-grace` (keep them equal to the - janitor's); -- the gateway gRPC server (`gateway.NewServer`) on port 9346 (every address - unless `--debug-bind-address` is set): the operator debug service - (`gateway.Debug`), the Looking Glass service (`gateway.Service`) and the - gateway-only forwarding service, authorized per role from - `gateway.GatewayMethods` by a `node.Authorizer` that re-verifies the caller's - 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. - -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. - -Metrics are registered on controller-runtime's registry and served on `:9347` -along with its own; `/healthz` and `/readyz` are plain pings on `:8081`. - -### `cmd/fabric-api/certsync.go` — `fabric-api certsync` - -Runs in the `fabric-api-certs` DaemonSet pod on each fabric node. Every -`--interval` (10 s) it copies `tls.crt`, `tls.key` and `ca.crt` from `--source` -(the csi-driver volume, default `/var/run/fabric-api/csi`) to `--dest` (the -node-local directory the sidecar reads, default `/var/run/fabric-api/node`, -the hostPath `/run/fabric-api/tls` on the node). It copies only when all three -files exist, the key pair validates and the content differs, and it replaces -each file atomically (`internal/fabric/identity/sync.go`). If the Issuer cannot -issue, this pod waits and the sidecar reports no credentials; the -`fabric-router` pod is unaffected. - -### `cmd/fabric-api/janitor.go` — `fabric-api janitor` - -Lists `FabricQuery` in every namespace and deletes those whose expiration or -completion, whichever is later, is more than `--retention` plus `--grace` in the -past. `--interval 0` (the default) sweeps once and exits, which is how the -CronJob runs it. A non-zero interval loops. - -### `cmd/fabric-api/query.go` — `fabric-api query` - -The operator client: `fabric-api query [TYPE [TARGET]]` with exactly one of -`--gateway host:port` or `--node host:port` (plus `--node-name` and `--node-pod`, -the node's `fabric-api-certs` pod, whose identity its sidecar presents). `--info` asks a node for its identity and availability. -It canonicalizes the query locally, calls with the operator certificate -(`--cell`, `--operator`, `--tls-*`), and prints the response as JSON. Errors print -as `: ` using the typed code. - -### `cmd/fabric-api/tracing.go` - -W3C trace context and baggage propagation is always on. An OTLP gRPC exporter is -enabled only when `OTEL_EXPORTER_OTLP_ENDPOINT` or -`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is set, with service name `fabric-api-node` -or `fabric-api-gateway`. - ---- - -## Configuration - -Flags and environment variables, ports, certificate identities, limits and -rollout are documented in -[docs/fabric-api/configuration.md](../fabric-api/configuration.md); this section -lists only what the architecture depends on. - -| Port | Component | Binds to | Purpose | -| ---- | --------- | ------------------- | ------------------------------------------------------ | -| 9344 | node | pod's `hostIP` | mTLS gRPC `FabricService` (`fabric-api` port) | -| 9345 | node | `hostIP` by default | `/metrics` (`api-metrics` port) | -| 9346 | gateway | all addresses | mTLS gRPC operator debug service (`debug` port) | -| 9347 | gateway | all addresses | `/metrics` (`metrics` port) | -| 9348 | node | `127.0.0.1` only | BMP station: bgpd's Loc-RIB stream to the search index | -| 8081 | gateway | all addresses | `/healthz`, `/readyz` (`health` port) | - -The Component's `fabric-api` container reads `NODE_NAME`, `POD_NAME`, -`POD_NAMESPACE` and `HOST_IP` from the downward API, and `SITE` and `CELL` from -the optional per-cell `fabric-api` ConfigMap. The gateway reads `SITE`, `CELL` -and `CLUSTER_NAME` from the same ConfigMap (keys `site`, `cell`, -`cluster-name`). The fabric-router pod is `hostNetwork`, so 9344 and 9345 are on -the node's own address; they are bound to `hostIP` only and not to every -interface, because edge nodes carry public uplinks. - -The Component also adds the `fabric-api-certs` DaemonSet (see -[Key Design Decisions](#key-design-decisions)), with the same placement as -`fabric-router`, no API token, and a `csi.cert-manager.io` volume named -`fabric-api-csi` whose URI SAN names that pod. - -The Component sets `automountServiceAccountToken: false` on the pod and adds a -projected token volume mounted only into `frr-init` and `config-agent`, the two -containers that call the Kubernetes API. The `fabric-api` sidecar needs no API -access and gets no token, unless it runs with `--probe-permits`, which no -manifest sets yet (see -[Aggregate probe budgets](../fabric-api/configuration.md#aggregate-probe-budgets)). - ---- - -## Module / Package Reference - -| Package | Responsibility | Owns state | -| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | -| `cmd/fabric-api` | Cobra commands (`node`, `gateway`, `janitor`, `query`, `certsync`), flag/env wiring, probe source selection, tracing | No | -| `api/fabric/v1` | `FabricService` and `FabricGatewayService` contract: `Execute`, `Info`, `Query`, `ListNodes`; observations, budgets | No | -| `api/fabric/service/v1` | `LookingGlassService` contract: `GetCapabilities` (policy, features, limits), `RunDiagnostic` and its snapshot, outcome and complete events; `testdata/` holds the wire examples | No | -| `api/fabric/forward/v1` | `ForwardService.ForwardDiagnostic`: the gateway-only envelope a follower forwards to the leader | No | -| `api/fabric/permit/v1` | `PermitService.RequestPermit`/`ReleasePermit`: a node obtains a probe permit for a direct operator's probe | No | -| `internal/fabric/query` | `Canonicalize` (target rules, family inference, AS-path grammar, community forms), `DestinationPolicy`, `Budgets`/`Ceilings`, probe limits. Imports nothing from the rest of galactic | No | -| `internal/fabric/frr` (`command.go`) | Closed command builder: `VersionCommand`, `SummaryCommand`, `LookupCommand`, `SearchCommand`, `RouteCommand`. `Command` fields are unexported, so there is no free-text path | No | -| `internal/fabric/frr` (`vty.go`) | Unix-socket client: `cmd\0` out, read to `\0\0\0`, per-command connection, byte cap, deadline handling | No | -| `internal/fabric/frr` (`parse.go`) | Typed parsers for lookup, search, summary and zebra installation; malformed input is an error, never an empty answer | No | -| `internal/fabric/frr` (`version.go`) | `SupportedReleases = ["10.7"]`, `CheckSupported` (`FRRVersionUnsupported`) | No | -| `internal/fabric/probe` | `Prober.Ping`/`Traceroute` on raw ICMP/ICMPv6 sockets bound to a source; reply correlation by ID, sequence and quoted packet | No | -| `internal/fabric/index` (`index.go`) | `Index`: selected-path store with interned, reference-counted attribute sets; `Search` (AS-path, community, large community; exact total, first matches in prefix order); sync state; `MaxRoutes` overflow counter | Routes and attribute sets (memory) | -| `internal/fabric/index` (`station.go`) | `Station`: BMP (RFC 7854) station for Loc-RIB route monitoring (RFC 9069); loopback peers only, one session at a time; synced when the dump's update rate settles | The BMP session | -| `internal/fabric/identity` | `ID` and its URI SAN; `Credentials` (reload, rotation, fail closed, `AcceptAnyNode`), `ServerConfig`/`ClientConfig`; `Sync` (certificate copy for `certsync`) | Loaded certificate, key and bundle | -| `internal/fabric/errcode` | Typed codes, gRPC status mapping, `ErrorInfo` (domain `fabric-api.datumapis.com`; `InvalidQuery` carries the query package's code under metadata key `queryCode`) | No | -| `internal/fabric/node` (`server.go`) | `Execute` pipeline, `Info`, FRR identity refresh, expensive-query breaker, probe policy and budgets | Semaphores, limiter, breaker, last-read FRR state | -| `internal/fabric/node` (`dedup.go`) | Duplicate-suppression cache keyed by `(requestID, node, operation)`, bounded in entries and bytes | In-memory cache | -| `internal/fabric/node` (`shape.go`) | Per-node shaping: path and community caps, response fit | No | -| `internal/fabric/node` (`permit.go`) | `Permits`: verifies and consumes each probe permit once (node, request, destination, operation, deadline, Lease epoch), refuses all for 32 s after start, obtains and releases permits for direct operator probes | Consumed permit IDs (memory) | -| `internal/fabric/node` (`auth.go`) | `Authorizer` (unary and stream) and `AuthInterceptor`: identity from the handshake, optional per-call re-verification capped at certificate expiry, per-role method table, call logging | No | -| `internal/fabric/gateway` (`reconciler.go`) | `FabricQuery` lifecycle: validation, snapshot, start marker, terminal status, conditions, coverage, shrink to budget | In-flight executions (memory) | -| `internal/fabric/gateway` (`runner.go`) | `Pool` (one mTLS connection per sidecar, pinned to its certs pod's identity), `Runner` fan-out, per-node deadline, cheap-read retry; `Runner.Stream` hands each outcome off as its node finishes, with no retry and a queue bound (`QueueTimeout`) | Connections | -| `internal/fabric/gateway` (`executor.go`) | Cell-wide slots with an expensive sub-budget and per-principal round-robin queue; optional per-principal slot and queue caps; all-or-nothing `Reserve` of a request's jobs | Queue state | -| `internal/fabric/gateway` (`admission.go`) | `Admission`: request tokens, attempt keys, live stream caps and probe permits charged to the packet buckets, under the election `Authority`; slot hold after a lost node answer | Stream counts (memory) | -| `internal/fabric/gateway` (`permit.go`) | `Permits`: the node-only permit service; maps the node identity's certs pod to its node, holds the operator's slot until release or deadline plus 2 s, forwards once to the leader | Held permits (memory) | -| `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` (`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 | -| `internal/fabric/api/v1alpha1` | `FabricQuery` Go types with kubebuilder markers, condition and reason constants, request labels | No | - ---- - -## External Dependencies - -| Dependency | Used for | -| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| FRR 10.7 (`fabric-router` image) | The only data source for non-probe queries. Read through `/run/frr/bgpd.vty` and `/run/frr/zebra.vty`; no `vtysh`, no `exec` | -| bgpd's BMP module (`-M bmp`) | Streams the Loc-RIB to the sidecar's station on `127.0.0.1:9348` when the node's `frr.conf` has the `bmp targets fabric-api` block. The `fabric-router` image's `daemons` file already loads the module. The production `frr.conf` renderer (infra) must emit the block | -| cert-manager and its csi-driver | Issues each `fabric-api-certs` pod's and the gateway's short-lived certificate and renews it in place. A required prerequisite; this repo installs none of it | -| The cell's `fabric-api` `Issuer` | Backed by a dedicated per-cell CA. Owned by infra in production; the lab's own is `deploy/containerlab/resources/fabric-api/pki/` | -| `FabricQuery` CRD (`galactic.datumapis.com`) | Installed by infra in every cell. `config/fabric-api/crd/` is the lab and test copy | -| NSO and Karmada | Create `FabricQuery` objects on the hub and propagate them to the pinned cluster; return status. Out of scope here | -| `sigs.k8s.io/controller-runtime` | Manager, leader election, cached client for `FabricQuery` and `Pod` | -| `google.golang.org/grpc` | Node and debug services, health service, keepalive | -| `golang.org/x/net/icmp`, `x/time/rate` | Raw ICMP sockets; the node-wide probe packet limiter | -| `prometheus/client_golang` | Node metrics (private registry) and gateway metrics (controller-runtime's registry) | -| OpenTelemetry (`otelgrpc`, OTLP) | Optional tracing of every RPC | -| Prometheus Operator CRDs | Only for `config/monitoring/`, which is not part of the default `config/` kustomization | - ---- - -## Key Design Decisions - -- **`FabricQuery` types live in galactic until the `network` repository ships - them.** The kind is `galactic.datumapis.com/v1alpha1`, as the plan locks, but - `../network` does not contain it yet and is read-only from here. The Go types - are in `internal/fabric/api/v1alpha1`; `config/fabric-api/crd/` holds a - generated CRD for the lab and tests only (`task generate:crd`). The shared - canonicalization in `internal/fabric/query` imports nothing from the rest of - galactic so it can move to `network` unchanged, where NSO and galactic would - both import it. Swapping is an import change. -- **FRR 10.7 only.** `frr.SupportedReleases` is `["10.7"]`. The sidecar reads - `show version` at startup and on reconnect, and any other release reports - `FRRVersionUnsupported` and diagnostics unavailable instead of parsing on a - guess. The parser fixtures in `internal/fabric/frr/testdata/frr-10.7/` were - captured from a standalone four-router FRR 10.7.1 topology (two eBGP - upstreams with ECMP, communities, large communities and a default route; one - iBGP neighbor; a local AS_SET aggregate; a down peer), so they do not depend - on lab routing state. 10.2 support and its fixtures were dropped once the lab - moved to 10.7.1. An `FRR_VERSION` bump in `fabric-router` needs a fabric-api - release that supports it first: capture the new fixtures into - `testdata/frr-./`, add the release to `SupportedReleases`, then - move the image. -- **vty framing and warning-as-data.** The client writes `command\0` and reads - until it sees `\0\0\0`. Return code 0 is success, 1 is a warning, and - anything else (2 is "unknown command") is `CommandFailed`. A warning whose - output is a complete JSON object is data: zebra answers an absent route with - `{}` and code 1. A warning whose output is not JSON is FRR rejecting the - command (for example a regular expression it cannot compile) and becomes - `CommandFailed`. Each command uses its own connection, so a daemon restart - costs one failed command. The response cap is 4 MiB; exceeding it closes the - connection and returns `ResponseTooLarge` with no partial output. Parsers - require complete valid JSON, and a path missing its AS path or next hops is - malformed, not skipped. -- **Closed command builder.** `frr.Command` has unexported fields and is only - built by five constructors, each a fixed template over typed values. A - `show ` prefix and printable-ASCII check inside `build` is a second line of - defence, not the authorization rule. There is no raw-command RPC. A read-only - socket mount would not make the socket read-only, so this builder is what - keeps fabric-api read-only; a compromised sidecar could bypass it, and the - design treats the sidecar as trusted control-plane code accordingly. -- **gRPC `ErrorInfo` error model.** A successful `Execute` returns an - `Observation`. Every failure is a gRPC status whose `google.rpc.ErrorInfo` - reason is the typed code (domain `fabric-api.datumapis.com`), so the code - survives the wire and maps onto `FabricQuery` and public reasons. - `ResponseTooLarge` travels as `RESOURCE_EXHAUSTED`. `errcode.Of` falls back - to a code derived from the gRPC status when no `ErrorInfo` is present. -- **Per-pod SPIFFE-style URI SAN identities.** Each certificate carries exactly - one URI SAN in trust domain `fabric-api.datumapis.com`: - `/cell//gateway`, `/cell//ns//pod/`, - `/cell//operator/` or `/cell//service/`. A service - identity is accepted only by the gateway, only when `--service-identities` - lists its name, and only for the Looking Glass service. The node identity names a pod rather than the - node because cert-manager's csi-driver can template a pod's name but not its - node's. That pod is the node's `fabric-api-certs` pod, not the - `fabric-router` pod (see the next decisions). The gateway's `Discoverer` maps - each node to its newest Running `fabric-api-certs` pod - (`--certs-selector`, default `app.kubernetes.io/name=fabric-api-certs`), - records it in `status.nodes[].certificatePod`, and dials accepting only the - identities of that node's certs pods (`Credentials.ClientConfigAny`): the - newest and any it is replacing, since the sidecar presents a replaced pod's - certificate until the new one reaches it. A node with no running certs pod is omitted with reason - `NoCertificatePod`. The sidecar cannot know that pod's name, so its - credentials accept any node identity in its own cell and namespace - (`AcceptAnyNode`). The trust bundle is per cell, and the cell segment is - checked as well as the chain. Chain verification is done in - `VerifyPeerCertificate` against the bundle current at handshake time, with - `InsecureSkipVerify` set only to replace the stock verifier, which would pin - roots at config creation and check a DNS name. -- **Credential reload.** `identity.Credentials` polls the mounted files every - 30 s and swaps in new ones only when the certificate matches `Self` (for the sidecar, any node identity in its cell and namespace), is valid - now and chains to the bundle it ships with. A bad renewal keeps the previous - credentials until they expire; with none loaded, every handshake fails closed - and the process keeps running and retrying. Rotation therefore needs no - restart, and CA rotation works through multi-certificate bundles. -- **Sidecar runs as UID 0 with only `NET_RAW`.** Raw ICMP sockets need - `CAP_NET_RAW` in the effective set, and Kubernetes grants added capabilities - to a non-root container's bounding set only. So the Component sets - `runAsUser: 0`, `runAsGroup: 102` (`frrvty`), drops every capability and adds - `NET_RAW`. Without `CAP_DAC_OVERRIDE` it reaches FRR's `0770 frr:frrvty` - sockets through group 102, as `frr-exporter` does. The root filesystem is - read-only and the `/run/frr` mount is read-only. The image's own `USER` is - `65532`; the gateway, janitor and query client run as it, and the Component - overrides it for the sidecar. -- **The certificate is issued in its own pod, not in `fabric-router`'s.** A - `csi.cert-manager.io` volume blocks its pod until the certificate is issued, - and `continueOnNotReady` does not change that: it only covers the driver's own - readiness gates. A lab test with a broken Issuer left the `fabric-router` pod - in `PodInitializing`, FRR down, with `MountVolume.SetUp` waiting for the - Issuer. So the csi volume lives in a separate `fabric-api-certs` DaemonSet - (`certs-daemonset.yaml`, added by the Component), placed like `fabric-router`, - with no API token, running `fabric-api certsync`. It copies the certificate, - key and bundle to the node's tmpfs `/run/fabric-api/tls` every 10 s, validating - the key pair and replacing files atomically. The sidecar mounts that directory - read-only as a hostPath of type `DirectoryOrCreate`, which never blocks the - pod. A broken Issuer therefore stalls only the certs pod. Because `/run` is - tmpfs the key never reaches the node's disk. `task verify:fabric-api-bootstrap` - is the lab's check of this property. -- **The sidecar has no probes.** Readiness is FRR's. The sidecar reports - availability through gRPC health, `Info` and - `fabric_api_node_diagnostics_available`. A process crash can still affect - aggregate Pod Ready and rollout progress, so that coupling is watched, not - denied. -- **Node budgets and the expensive-search breaker.** Defaults: 4 concurrent - `Execute` calls (later calls wait within their deadline), 1 expensive search - and 2 probes (no queue; a full budget answers `NodeBusy`), a 20 packets per - second limiter with burst 5 shared by every probe, a duplicate cache of 1024 - entries or 32 MiB, and a 10 minute breaker. Cancelling a client does not stop - bgpd's scan, so a scan that times out suspends expensive searches for the - cooldown (`QueryTypeUnavailable`, `fabric_api_node_expensive_breaker_open`). The - breaker applies only with `--search-source=frr`; the index never scans bgpd. The - one-expensive-search-at-a-time budget (no queue, `NodeBusy`) applies to both. -- **Executor fairness.** The gateway's `Executor` grants at most 8 node RPCs at - once across all requests, at most 2 of them expensive so searches cannot take - every slot. Waiters queue per project and are served round robin across - projects, FIFO within one, so one project's burst cannot starve another. The - queue is bounded at 256 and a full queue refuses at once (`NodeBusy`) rather - than letting waits outlive requests. Each node's deadline (earlier of request - expiry and 30 s) is fixed before it queues, so waiting counts against it. -- **Start marker, then one terminal status.** The gateway writes a small start - marker (attempt, fixed node snapshot, coverage, `Running`) and later exactly - one bounded terminal result. There are no incremental result payloads. The - terminal write retries optimistic conflicts against the latest object (up to - six tries) without rerunning any RPC, and stops if the object is gone, - terminal, or belongs to another attempt. Once `Complete=True` the status never - changes. -- **Resume on the fixed snapshot.** A non-terminal query with a start marker - whose `observedGeneration` equals the object's generation and with a node - snapshot reuses that snapshot with `attempt` incremented, instead of - discovering nodes again. This is what a new leader does after a failover. A - leadership loss stops local work, but not FRR's own command. -- **Discovered nodes are accounted for, never dropped.** A pod that is - terminating, not running, without a `hostIP` or without a running `fabric-api` - container stays in the snapshot with `selected=false` and an omission reason. - Pod `Ready` is deliberately not consulted: FRR's probes drive it and the - sidecar never gates it. During a rolling update a node can have two pods; one - usable pod is selected and the rest are recorded as `DuplicatePod`, which does - not count as missing coverage. A node whose certs pod is not running is - omitted as `NoCertificatePod`. `status.nodes` is capped at its schema bound of - 64 entries with selected nodes listed first; coverage still counts every - discovered node. -- **Searches run against a BMP-fed index, not FRR.** The load test - ([docs/fabric-api/load-test.md](../fabric-api/load-test.md)) showed direct - `regexp`, `community` and `large-community` scans saturating bgpd's main thread - (101% of a core, cheap queries slowing from 2 ms to seconds, convergence 3.1 - times the idle time, and `ResponseTooLarge` still costing the scan). bgpd already - streams its Loc-RIB incrementally over BMP, so the sidecar runs a BMP station and - searches a local copy. With the index, expensive searches cost bgpd 2% of a core - and convergence under load is +5%. -- **The index holds each prefix's selected path only.** Loc-RIB monitoring carries - what bgpd selected, so a search matches the selected path's attributes. FRR's own - search lists any path that matches, so the index can return fewer prefixes (see - Known Constraints). Path attributes (AS path, origin, MED, local preference, - communities, large communities, next hop) are interned and reference-counted: - about 212,000 distinct sets serve about 1.4 million prefixes, and a search - evaluates each set once, not each prefix. Results are the first matches in prefix - order with an exact total. -- **Sync, and refusing instead of falling back.** Each BMP session starts empty - (`BeginSession`) and bgpd resends the table. FRR 10.7 sends no End-of-RIB for - Loc-RIB monitoring (verified on the wire: Initiation, Peer Up, then routes), and - a quiet period never comes on a churning full table, so the station decides the - initial dump is over from its rate: synced once the session has carried routes - and the last 5 seconds' rate is at most 50 per second or 1% of the session's peak. - An explicit End-of-RIB, from any peer header, also syncs. When the session ends the index is unsynced again. Unsynced, a search - answers `QueryTypeUnavailable`; there is no fallback to scanning bgpd, since that - is the thing the index exists to avoid. Every search reports the index's state - (`index.syncedAt`, `lastUpdate`, `version`, `routes`). -- **The station accepts one loopback session.** It listens on `127.0.0.1:9348`, - refuses non-loopback peers and refuses a second session while one is active. A - local root process could connect first (see Known Constraints). Updates for new - prefixes beyond `--search-index-max-routes` (4,000,000) are dropped and counted in - `fabric_api_node_search_index_overflow_total`, never silently served as complete. -- **Janitor has separate RBAC.** The gateway's ClusterRole can read `FabricQuery` - and update their status, nothing else. Deleting is a different ServiceAccount - (`fabric-api-janitor`) with `list` and `delete` on `fabricqueries` only, run as - a CronJob, so delete access never reaches the process that executes queries. - Deletion carries a UID precondition so a reused name is never touched. -- **Stale-objects gauge on the gateway.** The janitor is an unscraped CronJob - with no metrics (it logs what it deletes), so a cleanup backlog would otherwise - be invisible. Every gateway replica publishes `fabric_api_gateway_stale_objects` - from its cache each minute, using its `--retention` and `--cleanup-grace` - (defaults 1h and 15m), which must be kept equal to the janitor's `--retention` - and `--grace`. -- **Retries are narrow.** The gateway retries a node call once, and only for a - cheap read (not a search, not a probe) that failed with `NodeUnreachable`, - since the node deduplicates by request ID. A search or probe that may have run - is never retried within an attempt; its error is preserved. -- **Probe sources are explicit.** Each family has at most one source address, - loopback and unspecified addresses are refused at startup, and a family with - no source answers `ProbeSourceUnavailable` instead of falling back to - `127.0.0.1`, `::1` or an unrelated interface. - ---- - -## Testing - -| Layer | Command | Framework | Scope | -| ----------- | ------------------------------------------------------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Unit | `task test:unit` | `go test -race` | `internal/fabric/query` (canonicalization, destination policy, budgets); `frr` (10.7 fixtures, vty framing, partial reads, return codes, byte cap, early close, timeout, unavailable, command grammar); `probe` (fake socket, loss, hop limits, pacing) | -| Unit | `task test:unit` | `go test -race` | `identity` (mutual TLS, load failures, rotation with an overlapping bundle, certificate sync); `errcode` (metadata); `node` (validation, expensive gate and breaker, no-queue expensive budget, deadline clamping, duplicates, eviction, shaping, probe policy and budget, gRPC over mTLS) | -| Unit | `task test:unit` | `go test -race`, fake client | `gateway` (reconcile outcomes, no-nodes, rejection, expiry before and during execution, resume on a fixed snapshot, status conflict retry without rerunning, deletion cancels, other cells ignored, shrink to budget, leader forwarding, janitor, executor, service streaming: finished routers first, coverage and omission reasons, refusals before the snapshot, deadline and queue bound, stream failure cancels, transport through a follower) | -| Unit | `task test:unit` | `go test -race` | `internal/fabric/index`: apply and search, withdraw releasing attribute sets, `MaxRoutes`, a station fed over a real socket, rate-based sync, community values | -| CRD schema | `go test ./internal/fabric/api/v1alpha1/` with `KUBEBUILDER_ASSETS` set | envtest (kube-apiserver, etcd) | `TestCRDSchema` installs the generated CRD and checks structural bounds, CEL rules, the immutable spec and the status subresource. Skipped when `KUBEBUILDER_ASSETS` is unset | -| Raw socket | `go test ./internal/fabric/probe/` with `FABRIC_PROBE_SOURCE` and `FABRIC_PROBE_TARGET` set | `go test` | `TestRawSocket` sends real probes; needs `CAP_NET_RAW` and a reachable target. Skipped otherwise | -| Alert rules | `task test:alerts` | `promtool test rules` | `config/monitoring/tests/rules-test.yaml` covers every `FabricAPI*` alert. Not part of `task ci` | -| E2E | `task verify:fabric-api` (in `deploy/containerlab/`) | bash, live containerlab lab | Per node, directly with an operator certificate; through each cell's gateway debug service; and through a `FabricQuery` written as NSO would write it | -| Bootstrap | `task verify:fabric-api-bootstrap` (in `deploy/containerlab/`) | bash, live containerlab lab | Disruptive. Breaks the cell's `Issuer` and clears the node's synced credentials, then recreates its `fabric-api-certs` and `fabric-router` pods and checks that the certs pod waits while FRR and the underlay come up and the sidecar reports no credentials, then repairs the Issuer and checks the sidecar recovers without a restart | -| Load | `task test:fabric-api-load MRT=` | Go harness, Docker | Full Internet tables (RouteViews MRT dumps) fed to FRR 10.7.1 with the real sidecar driven over mTLS; bgpd CPU and RSS, convergence and session drops by phase. Needs Docker and about 4 GiB; not part of CI. Results in [load-test.md](../fabric-api/load-test.md) | - -`task verify:fabric-api` checks, on every `fabric-router` node: `Info` reports -diagnostics available, FRR 10.7 and a router ID and ASN; every underlay session -`Established` for both families; an exact lookup and a longest-match lookup of -another site's loopback, each with a selected BGP path and zebra installation -evidence; a longest-match lookup of the site's gateway VIP; an exact lookup of -an unannounced prefix returning a successful empty answer; an AS-path and a -community search answered from the index with its freshness and equal to FRR's own -best-path matches; and operator ping and traceroute to another -site's loopback in both families. Through each gateway it checks that a debug -`BGPSummary` is answered by every node and that the same loopback ping is -refused with `DestinationNotAllowed` on every node (public policy never carries -the lab exceptions). It then writes a `FabricQuery` and expects `Succeeded` with -one observation per node, and that a query pinned to another cluster is left -untouched. It claims nothing about tenant EVPN tables. - -Run the lab flow with `task build:fabric-api`, `task deploy:cert-manager` and -`task deploy:fabric-api` (all in `deploy/containerlab/`); `task deploy` also -runs them in order, with `deploy:cert-manager` before `deploy:fabric` so the -csi-driver exists when the `fabric-api-certs` pods start. - ---- - -## CI/CD - -**Pipeline:** `.github/workflows/ci.yaml` runs `task lint`, `task test:unit` and -`task build`, which cover the unit tests above and build `bin/fabric-api`; see [ARCHITECTURE-ROUTER.md#cicd](ARCHITECTURE-ROUTER.md#cicd) for -the shared tier structure. The envtest, raw-socket, `promtool` and containerlab -checks are not part of CI. - -**Publish pipeline:** `.github/workflows/publish.yaml`'s -`publish-fabric-api-image` job builds and pushes `ghcr.io/datum-cloud/fabric-api` -for `linux/amd64` and `linux/arm64`. `publish-kustomize-bundles` stamps its tag -into both `config/fabric-router/components/fabric-api` and -`config/fabric-api/base`, so the Component and the gateway always reference a -published image. - -**Container image:** `containers/fabric-api/Dockerfile` — golang builder with -`CGO_ENABLED=0` → `scratch`, `ENTRYPOINT ["/usr/bin/fabric-api"]`. No clang, no -`go generate`, and no FRR or shell in the image. `task build` also produces -`bin/fabric-api` for local use. - -Because the sidecar lives in the `fabric-router` pod, changing the `fabric-api` -tag changes the DaemonSet pod template and the rolling update recreates the whole -pod, FRR included. Sidecar releases are routing rollouts; see -[Rollout](../fabric-api/configuration.md#rollout). Gateway-only releases do not -touch `fabric-router`; `fabric-api-certs` runs the same image, so its tag moves -with the Component but its restart does not touch FRR. - ---- - -## Known Constraints - -- **Searches are off until staging confirms the load test.** `ASPath`, - `Community` and `LargeCommunity` need `--enable-expensive-queries` and answer - `QueryTypeUnavailable` otherwise. The full-table load test passed for the index - in a Docker lab ([load-test.md](../fabric-api/load-test.md)); the numbers have not - been confirmed on real fabric routers, and enabling is an infra rollout step. The - containerlab lab enables them. -- **The index holds only selected paths.** A search matches each prefix's best path - as bgpd selected it, so it can return fewer prefixes than FRR's own search, which - lists any path that matches. `matched` counts prefixes whose selected path - matches. The index equalled FRR's best-path matches on all 40 load-test targets. -- **The index needs the BMP block in `frr.conf`.** Without `bmp targets fabric-api` - the index never syncs and searches stay `QueryTypeUnavailable`. Infra's `frr.conf` - renderer must emit it for production nodes. With the index the breaker is not used. -- **The BMP station trusts loopback.** Any local process on the node that can reach - `127.0.0.1:9348` could connect first and feed the index, and bgpd's later session - is then refused while that one is active. The port is on the loopback interface, - so only processes on the node can reach it. -- **Index memory is sized for a full table.** The load test measured a sidecar RSS - of about 430 MB for 1.39 million prefixes; the Component requests 64Mi and limits - memory to 768Mi with `GOMEMLIMIT=640MiB`. Prefixes beyond - `--search-index-max-routes` are dropped and counted, not refused. -- **Operator debug through the gateway applies the public policy.** The nodes see - the gateway's identity on that route, so the public destination policy applies - and the lab's loopback exceptions are unavailable. Operator exceptions - (`--operator-allow-prefixes`) apply only to calls made directly to a node with - an operator identity, and are never set in production. -- **The `FabricQuery` CRD copy is lab-only.** `config/fabric-api/crd/` exists for - the containerlab lab and envtest. Infra owns the CRD in every cell and NSO on - the hub. Types live here only until `network` ships them. -- **Hostnames are never resolved here.** A probe target reaching the gateway must - already be a numeric address in the query's family; NSO resolves and pins it. - The gateway rejects a hostname with `InvalidQuery`. -- **The duplicate cache is in memory.** A sidecar restart or an eviction can let - a repeated request run again. Execution budgets and the packet limiter still - apply; exactly-once is not a goal. -- **Late status never reopens a query.** Once `Complete=True` the gateway never - touches the object again. NSO is responsible for resolving a cell that never - returns to `DeadlineExceeded` at the absolute expiration. -- **Status lists are bounded.** `status.nodes` holds at most 64 entries and - `status.observations` at most 32. The gateway selects at most 32 nodes and lists - selected nodes first; discovered nodes beyond the 64-entry bound are counted in - `coverage` but not listed. -- **The certificate hand-off is node-local and eventually consistent.** The - sidecar sees a new certificate only after `certsync` copies it (every 10 s) and - the sidecar reloads it (every 10 s). A node whose `fabric-api-certs` pod is not - running is `NoCertificatePod` to the gateway, even if its sidecar still holds an - unexpired certificate. The key sits in the node's tmpfs, readable by root on - the node, as any hostPath secret is. -- **The janitor has no metrics.** It logs each deletion and, at debug level, each - outcome. The gateway's `--retention` and `--cleanup-grace` are not read from the - janitor, so they must be kept equal by hand. -- **Other repositories are out of scope.** The public `LookingGlassQuery`, hub - CRD installation, per-cell propagation policies and Lua status aggregation - (NSO, `network`), the per-cell issuer and certificate rotation prerequisites - (infra) and the portal UI are not implemented or verified here. - ---- - -## For Claude - -**Where to start for each concern:** - -| Concern | Start here | -| -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -| What a query means, target rules, family inference | `internal/fabric/query/query.go:Canonicalize`, `Lookup` | -| Probe destination policy | `internal/fabric/query/destination.go:DestinationPolicy.Check`, `ResolvedProbe` | -| Byte, count and time ceilings | `internal/fabric/query/limits.go:Ceilings`, `Budgets.Clamp` | -| Which FRR commands may ever be sent | `internal/fabric/frr/command.go` (every constructor) | -| Searches from the BMP index, sync state | `internal/fabric/index/index.go:Index.Search`, `station.go:Station`, `node/server.go:runIndexed`, `searchUnavailable` | -| vty framing, return codes, read cap | `internal/fabric/frr/vty.go:VTY.Run`, `read`, `result` | -| Parsing FRR JSON, empty vs malformed | `internal/fabric/frr/parse.go:ParseLookup`, `ParseSearch`, `ParseSummary`, `ParseInstallation` | -| Supported FRR releases | `internal/fabric/frr/version.go:SupportedReleases` | -| The sidecar's request pipeline | `internal/fabric/node/server.go:Execute`, `validate`, `execute` | -| Duplicate suppression | `internal/fabric/node/dedup.go:dedupCache.do` | -| Shaping a node response to budget | `internal/fabric/node/shape.go:fitResponse`, `prefixObservation` | -| Who may call what | `internal/fabric/node/auth.go:nodeMethods`, `gateway/debug.go:GatewayMethods`, `gateway/service.go:Allowlist` | -| Identities and URI SAN formats | `internal/fabric/identity/identity.go` | -| Certificate reload and rotation | `internal/fabric/identity/credentials.go:Credentials.Reload` | -| Certificate hand-off to the node (certsync) | `internal/fabric/identity/sync.go:Sync.Once`, `config/fabric-router/components/fabric-api/certs-daemonset.yaml` | -| Typed error codes and their gRPC mapping | `internal/fabric/errcode/errcode.go` | -| FabricQuery lifecycle, conditions, coverage | `internal/fabric/gateway/reconciler.go:Reconcile`, `terminalStatus`, `persist` | -| 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/` | -| 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` | -| Cleanup | `internal/fabric/gateway/janitor.go:Janitor.Sweep`, `StaleCounter` | -| The `FabricQuery` schema and CEL rules | `internal/fabric/api/v1alpha1/fabricquery_types.go` (regenerate with `task generate:crd`) | -| 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` | -| Metrics and alerts | `internal/fabric/node/metrics.go`, `gateway/metrics.go`, `config/monitoring/prometheusrule.yaml` (`fabric-api` group) | - -**Stable vs. frequently changed:** -- Stable: `internal/fabric/frr/vty.go` and `command.go` (small, closed, fully unit-tested), `internal/fabric/identity` (the SAN formats are a deployment contract; changing them re-issues every certificate). -- Active: `internal/fabric/index` (the BMP-fed search path), `internal/fabric/query/limits.go` budgets (raising a ceiling needs boundary and load tests), the expensive-query gate, and the `FabricQuery` types, which move to `network` when it ships them. - -**Non-obvious patterns:** -- The gateway's reconcile does not run an execution inline: it writes the start marker, then `launch`es a goroutine under the leader's context and returns. `running` is in memory, which is why a restarted gateway re-enters `Reconcile` for a non-terminal query and takes the resume path. -- A node validates `q != Canonicalize(q)` and rejects a non-canonical query rather than fixing it, so a caller that skipped canonicalization fails loudly. The gateway does the same for the spec's query. -- `errcode.Of` returns `ResponseTooLarge` for any `RESOURCE_EXHAUSTED` without an `ErrorInfo`; a node's `NodeBusy` also travels as `RESOURCE_EXHAUSTED` but always with its own `ErrorInfo`. -- `node.AuthInterceptor` is shared by the node and the gateway debug server; each passes its own method table, and `nil` selects the node's. -- The `fabric-api` pod's token mount is the Component's job. Adding a container to the `fabric-router` pod that needs the Kubernetes API means adding it to the projected volume's mounts in `daemonset-patch.yaml`. +This document moved to [architecture](../fabric-api/architecture.md). Update bookmarks to the maintained page. + + + +See [Overview](../fabric-api/architecture.md). + + + +See [Repository Layout](../fabric-api/architecture.md). + + + +See [Data Flow](../fabric-api/architecture.md). + + + +See [Federated path (`FabricQuery`)](../fabric-api/architecture.md). + + + +See [Operator debug path](../fabric-api/architecture.md). + + + +See [Search path (BMP-fed index)](../fabric-api/architecture.md). + + + +See [Entry Points](../fabric-api/architecture.md). + + + +See [`cmd/fabric-api/node.go` — `fabric-api node`](../fabric-api/architecture.md). + + + +See [`cmd/fabric-api/gateway.go` — `fabric-api gateway`](../fabric-api/architecture.md). + + + +See [`cmd/fabric-api/certsync.go` — `fabric-api certsync`](../fabric-api/architecture.md). + + + +See [`cmd/fabric-api/janitor.go` — `fabric-api janitor`](../fabric-api/architecture.md). + + + +See [`cmd/fabric-api/query.go` — `fabric-api query`](../fabric-api/architecture.md). + + + +See [`cmd/fabric-api/tracing.go`](../fabric-api/architecture.md). + + + +See [Configuration](../fabric-api/architecture.md). + + + +See [Module / Package Reference](../fabric-api/architecture.md). + + + +See [External Dependencies](../fabric-api/architecture.md). + + + +See [Key Design Decisions](../fabric-api/architecture.md). + + + +See [Testing](../fabric-api/architecture.md). + + + +See [CI/CD](../fabric-api/architecture.md). + + + +See [Known Constraints](../fabric-api/architecture.md). + + + +See [For Claude](../fabric-api/architecture.md). diff --git a/docs/archive/README.md b/docs/archive/README.md new file mode 100644 index 000000000..b9acb8a75 --- /dev/null +++ b/docs/archive/README.md @@ -0,0 +1,17 @@ +# Historical evidence + +These records retain the state, findings and measurements of their named revisions. They are not current operating instructions or proof that a candidate release passed the same checks. + +## Reviews + +- [Egress active/active review, October 9](reviews/egress-active-active_2026-10-09.md). +- [Resolution record](reviews/egress-active-active_2026-10-09-resolution.md). +- [Re-review of the intermediate fixes](reviews/egress-active-active_2026-10-09_rereview.md). + +Use the [current egress rollout checklist](../nat/active-active-rollout.md). In particular, an open disposition in a historical review can predate a fix in the candidate release, while a recorded lab pass does not establish staging acceptance. + +## Measurements + +- [fabric-api full-table measurements, October 7](benchmarks/fabric-api-2026-10-07.md). + +Use the [maintained load-test procedure](../fabric-api/load-test.md) to qualify a new release. Record its revision, environment and result instead of replacing the older evidence. diff --git a/docs/archive/benchmarks/fabric-api-2026-10-07.md b/docs/archive/benchmarks/fabric-api-2026-10-07.md new file mode 100644 index 000000000..60c697b71 --- /dev/null +++ b/docs/archive/benchmarks/fabric-api-2026-10-07.md @@ -0,0 +1,109 @@ +# fabric-api load-test evidence, 2026-10-07 + +Historical measurements from one Docker host. These results are not current capacity claims or production qualification. Use the [maintained load-test procedure](../../fabric-api/load-test.md) to repeat the experiment against a candidate release. + +## Purpose + +A search such as an AS-path regular expression traverses the whole BGP table, and +neither a client cancellation nor a response byte cap proves that bgpd stopped +computing. Before searches can be enabled anywhere, a representative full-table load +test must show: + +- no query-induced BGP session loss; +- no bgpd memory growth caused by searches; +- routing convergence after a session reset within an agreed budget of the same + event with no diagnostics running; and +- (added by this test) search answers equal to what FRR itself would answer. + +## Gate, as measured here + +This is a proposal for infra to adopt; the numeric budget was not fixed before the +test. A configuration passes when, with full IPv4 and IPv6 Internet tables: + +1. zero unplanned BGP session drops in every phase; +2. convergence after a session reset under search load within 10% of the idle + baseline; +3. no bgpd memory growth from searches; and +4. search answers equal FRR's own best-path answers. + +## Method + +The harness is `hack/fabric-api-loadtest` (Go). It needs Docker and about 4 GiB of +memory, and removes its containers and network on exit. + +- **Router.** FRR 10.7.1 (`quay.io/frrouting/frr:10.7.1`, the release used for this measurement) in + Docker, with bgpd and zebra. +- **Feeder.** A GoBGP container injects the best paths of RouteViews MRT RIB dumps + over one IPv4 and one IPv6 eBGP session. One pass per address family, with the + next hop overridden. Inputs: RouteViews + `route-views2` `rib.20261007.0000` (IPv4) and `route-views6` + `rib.20261007.0000` (IPv6). `route-views2` carries no IPv6 table, so IPv6 comes + from the second file. +- **System under test.** The real `fabric-api node` sidecar beside that FRR, driven + over mTLS as an operator by 8 concurrent workers (`--concurrency`). +- **Phases**, each 2 minutes (`--duration`) after loading the table: + 1. *baseline*: convergence time after `clear bgp *` with no queries running; + 2. *cheap*: `RouteLookup` and `BGPSummary`; + 3. *expensive*: adds `ASPath`, `Community` and `LargeCommunity` searches, within + the node's own budgets; + 4. *expensive + reset*: a session reset while the expensive load runs. +- **Measurements.** Per query type: latency percentiles and outcome codes. For + bgpd: CPU seconds and RSS, sampled from `/proc`. Unplanned session drops, from the + peers' `connectionsDropped` counters, other than the harness's own resets. +- **Consistency check** (index runs only): the index's counts are compared with + FRR's own best-path matches for a fixed set of search targets. + +## Results + +### Run A: direct FRR scans (`--search-source=frr`), IPv4 only + +1,126,600 prefixes (`route-views2` has no IPv6). + +| Phase | bgpd CPU | Query latency and outcomes | bgpd RSS | Unplanned drops | +| ----------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | --------------- | +| baseline | | Convergence after `clear bgp *`: 41.5 s | | | +| cheap | 98.4 CPU-s (82% of a core) | `RouteLookup` n=266,593, p50 2 ms, p99 4 ms, max 15 ms. `BGPSummary` n=265,614, p50 2 ms, p99 4 ms | 1034 to 1087 MiB | 0 | +| expensive | 120.9 CPU-s (101%) | `ASPath` n=246: NodeBusy 219, OK 21, ResponseTooLarge 6; p95 3.0 s, p99 3.9 s, max 4.8 s. `Community` n=240: NodeBusy 196, OK 31, ResponseTooLarge 13; p99 3.6 s. `LargeCommunity` n=255: NodeBusy 212, OK 43; p99 4.2 s. `RouteLookup` p50 657 ms, p99 4.3 s. `BGPSummary` p50 661 ms, p99 4.2 s | flat | 0 | +| expensive + reset | 133.8 CPU-s (112%) | Convergence under load: 2 m 10.0 s, 3.1 times the idle 41.5 s. `RouteLookup` p50 1.13 s, p99 5.6 s | | 0 | + +**Conclusion: fails the gate.** bgpd's main thread saturates under searches, cheap +queries that were 2 ms become seconds, convergence after a reset takes 3.1 times +longer, and a `ResponseTooLarge` answer still costs bgpd the whole scan. No sessions +dropped and memory stayed flat, but the convergence and starvation results rule out +enabling direct scans. + +### Run B: BMP-fed index (default), IPv4 and IPv6 + +1,126,600 IPv4 and 263,799 IPv6 prefixes. + +**Index build and footprint.** After the sidecar started, the index synced in 29.2 s, +costing bgpd 23.4 CPU-s once. It held 212,524 distinct attribute sets. The sidecar's +RSS was about 430 MB (Go heap in use about 370 MB); bgpd's RSS about 1.5 GB. + +**Consistency.** 40 search targets (9 AS-path, 7 community and 4 large-community +targets, each for both families): the index's match counts equalled FRR's own +best-path matches for all 40. + +| Phase | bgpd CPU | Query latency and outcomes | Unplanned drops | +| ----------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | +| baseline | | Convergence after `clear bgp *`: 41.7 s | | +| cheap | 107 CPU-s (89% of a core) | `RouteLookup` n=212,655, p50 2 ms, p99 22 ms. `BGPSummary` n=212,686, p50 1 ms, p99 22 ms | 0 | +| expensive | 3.0 CPU-s (2%) | `ASPath` OK 201 (NodeBusy 5,344), p99 515 ms, max 715 ms. `Community` OK 219, p99 90 ms. `LargeCommunity` OK 192, p99 77 ms. `RouteLookup` p99 3 ms. `BGPSummary` p99 2 ms. bgpd RSS flat | 0 | +| expensive + reset | 34.1 CPU-s (28%, the reconvergence itself) | Convergence under load: 43.7 s, +5% over the idle 41.7 s. `ASPath` p99 920 ms. `RouteLookup` p99 186 ms | 0 | + +The `NodeBusy` count for `ASPath` is the node's own budget at work: it runs one +search at a time with no queue, and 8 workers keep asking. + +**Conclusion: passes** every criterion of the gate above: zero drops, convergence +within 10% of idle (+5%), no bgpd memory growth, and answers equal to FRR's +best-path answers. Searches cost bgpd nothing beyond the one-time +index build (23.4 CPU-s) and the BMP stream. + +### Reading the numbers + +- Cheap-query throughput in the cheap phase, about 1,700 to 2,200 queries per second + per node, far exceeds what the gateway's 8 cell slots and NSO's rate limits allow + to reach a node, so cheap queries are not a capacity concern. +- The runs measure one router in a Docker lab on one machine. They do not measure + real fabric routers, real peer counts, or concurrent exporter and config-agent + activity. diff --git a/docs/archive/reviews/egress-active-active_2026-10-09-resolution.md b/docs/archive/reviews/egress-active-active_2026-10-09-resolution.md new file mode 100644 index 000000000..880897cf3 --- /dev/null +++ b/docs/archive/reviews/egress-active-active_2026-10-09-resolution.md @@ -0,0 +1,110 @@ +# Resolution: egress-active-active review (2026-10-09) + +Historical review of the revisions named below. Findings and test results are preserved as recorded, including dispositions that later commits changed. This is not the current release checklist; use [active/active egress rollout](../../nat/active-active-rollout.md) and verify the candidate release. + +Resolution record for [egress-active-active_2026-10-09.md](egress-active-active_2026-10-09.md), +which reviewed `f61103b2`, `69ebb6cc` and `c8830ea9`. The review is kept as +written; this file records what was done about each finding and how it was +validated. + +## Findings + +| Finding | Status | Resolution | +| ---------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| F01 Disable after a failed refresh | Fixed | `egressGroup.refresh` returns `Refresh`'s error. Leaving hashed mode publishes every enabled group as `CLOSING` (forwarding, but CNI ADD writes no new sentinel), then converts, and disables only after a conversion that read and wrote every route without error and found no sentinel left, foreign-namespace sentinels included. CNI ADD re-reads the groups after writing its routes and rewrites them in ordered mode if they closed meanwhile, which closes the race with concurrent registration. | +| F04 Pool compatibility | Fixed | One shard group per translation class: NAT66 for `::/0`, one per NAT64 prefix (at most three in hashed mode; more is a startup error). A shard joins a class's group only if its status can translate it (IPv6 address; or IPv4 address and that `nat64Prefix`, or `translatesWellKnownPrefix` for `64:ff9b::/96`). Every sweep recomputes eligibility, so a shard that changes leaves. Ineligible shards are logged and exported (`pool_members{state="ineligible"}`); a class no shard serves gets no route and `GalacticEgressClassUnserved`. Single-family clusters keep working. | +| F05 Generation uniqueness | Fixed | Superseded by the F06 design: a group is published as one snapshot in one atomic swap, so a slot that failed to publish was never visible to a packet. Generations come from `next_slot_generation` in the published snapshot plus an in-process high-water mark that also counts failed publications; disable keeps the counter, restart resumes from it, 0 is never handed out. The review's A→B(failed)→C sequence is reproduced against the kernel at each of the three publication steps. | +| F06 Coherent BPF publication | Fixed | `egress_shard_group_table` and `egress_shard_table` (ARRAY maps updated in place) replaced by `egress_shard_groups`, an `ARRAY_OF_MAPS` whose slot holds one immutable snapshot: Maglev table and every member's SID, next hop, flags and generation. Publication creates a new inner map, fills it and swaps the outer slot in one update (an RCU pointer replacement; the old snapshot is freed after readers finish). The packet path reads everything from that one snapshot; one extra map lookup per grouped packet. The finding was confirmed on a kernel before the fix: updating a published value in place produced 17 torn packets out of 54,777; the snapshot swap produced 0 out of 49,011. | +| F02 Drain verification | Fixed | `verify-nat-active-active.sh` rewritten. Every probe requires every request to succeed, the capture to see every probe, and every source to be an expected masquerade address; silence fails. Fresh, never-pinned tenant addresses are added inside the tenant's network namespace, so drain and failure are checked under default pins. A self-test blackholes a fresh tenant and requires the probe to fail. Background downloads propagate failures; cleanup restores the environment, drain flags, ClusterRole, routes and addresses it found. | +| F03 Drain lifecycle documentation | Fixed | Docs and the new rollout checklist say: `spec.drain: true`, wait for sessions to end, then delete; deletion tears the shard down at once; a busy tenant can keep a shard draining indefinitely; pins off cannot preserve sessions. A terminating `EgressShard` is now excluded from the groups rather than treated as draining. No finalizer was added. | + +## Additional recommendations + +| Recommendation | Resolution | +| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| CRD/schema prerequisite, RBAC, drain read-back | Documented in `docs/nat/configuration.md` (Prerequisites) and `docs/nat/active-active-rollout.md`; the lab check verifies all three. | +| Unique identities, translation compatibility, return routing | Documented as prerequisites; enforced for compatibility (F04); the lab preflight checks distinct SIDs and addresses and a return route to each from the transit. | +| NAT64 and TCP/UDP/ICMP coverage | The lab check covers TCP, UDP and ICMP over NAT66 and NAT64. | +| Default pins, addition, withdrawal, all down, restart, informer, rollback | Covered by the lab check (addition by a shard's re-origination), except addition of a third shard, which the lab topology cannot do; it is covered by the privileged datapath tests. | +| Prohibit route vs BGP | Lab stages are labelled; the real BGP stage removes the SID origination from the shard node's FRR. | +| Load, pins, replication, fragments | Documented in configuration.md (How a shard is chosen; Known constraints). | +| Cross-node placement | Confirmed: VRF table IDs are allocated per node (`vrf.nextFreeTableID`). Kept, and documented as a per-node guarantee: sessions, pins and reply SIDs are node-specific, so a stable cross-node identity would buy nothing. | +| Monitoring of zero candidates, informer failure, incompatibility, missing metrics | New control-loop series (`egress_mode`, `shard_watch_synced`, `group_routes`, `sweep_errors_total`) and alerts (`GalacticEgressClassUnserved`, `GalacticEgressShardWatchNotSynced`, `GalacticEgressSweepFailing`, `GalacticCNIMetricsDown`); `PoolEmpty` fires on zero candidates with routes; an unpublished node reports no pool series rather than zeros. | +| Central evaluator | Documented: repository rules are the tested source; infra must install them in its central evaluator. | +| Staging acceptance and rollback checklist | `docs/nat/active-active-rollout.md`. | + +## Compatibility + +- **Map layout.** The two pre-review group maps are gone; `egress_shard_groups` + and `egress_shard_group_template` are new. No map that existed before the + feature changes, so an upgrade from a release without it keeps every pinned + row. A node that ran a pre-review build of this branch (only the + containerlab lab) has the two obsolete pins removed at load; its groups are + rebuilt by the next sweep, and until then a route naming a group drops. +- **Rollback.** Unchanged in principle and now observable: switch to ordered + mode, wait for `galactic_cni_egress_group_routes` to read 0 on every node, + then roll back the image. +- **Older clang.** `egress_shard_group_template` exists because clang before + 21 emits the inner map value as a forward declaration. Generation was + checked with clang-18 (CI's compiler) and clang-19 (the image builder's). + +## Validation + +Run on 2026-10-09 on a Fedora 44 host (kernel 7.1) against the containerlab +`gvpc` lab's dfw cluster. The lab is local and isolated; no staging or +production resource was touched. + +| Check | Result | +| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `golangci-lint` (via `task ci`) | Passed, 0 issues. | +| `yamlfmt -lint` | Passed with a temporary config. `task ci`'s own yamlfmt step stops in a git worktree on `stat .git/**: not a directory`, a known worktree artifact; the remaining `ci` stages were then run directly. | +| `task build`, `task test:unit`, `task test:e2e` | Passed. The unprivileged unit run skips every root-gated test. | +| `task test:unit-root` (privileged, host clang 22) | Passed in two of three full runs. The third failed once in `internal/cnibgp` (`TestRegisterEBPFDatapath_RegistersAllThreeTables`: its test interface was not found), which then passed 3 of 3 alone and 5 of 5 as a package on this branch and on `origin/main`; that code is unchanged here. A later run reproduced it, with `internal/cni`'s `TestCmdCheckValidConfigMissingResources`, only while root packages ran in parallel; with `-p 1` every root-gated package passed, so these tests collide on host interfaces when run concurrently. Skipped: `TestReconcileRadvActors_FailedRemovalIsRetried`, as before. | +| Privileged datapath tests against clang-18 objects | Passed: the whole `prog` suite (verifier acceptance and the verifier-cost limit included) and every `TestGroupDatapath`/`TestGroupPublication` test, with objects built by clang-18, the CI compiler. Generation also checked with clang-19, the image builder's compiler. | +| Concurrent publication (`ConcurrentSwapsStayCoherent`) | 0 mixed packets of 122,312 across 400 swaps. A throwaway control that rewrote a published value in place produced 17 mixed of 54,777 (not committed: it is nondeterministic by nature). | +| `task test:alerts` | Passed: 32 rules, every rule test. | +| `verify:nat-active-active` (lab) | Passed all ten stages, including the real BGP withdrawal (withdrawal and re-origination each reached the group in about 2 s). An earlier run failed once in the drain stage when a fresh tenant got no answer; it was not reproduced by hand or in the next full run after the script's fresh-address allocation was made unique (it had reused a random byte across a subshell). The cause is not proven. | +| Upgrade on lab nodes | `galactic-cni` loaded the new maps beside every existing pin and removed the two obsolete ones on all three dfw nodes. | + +Not run: the privileged suite on the staging kernel version, any staging +acceptance step, adding a third shard in a live cluster (the lab has two per +site), and infra's central alert evaluation. + +## Remaining staging gates + +1. Release the `network` change adding `spec.drain` (branch + `feat/egressshard-drain`, commit `36ee528`), install its CRD in staging, + and re-pin galactic's `go.mod` to the release. +2. infra: install the CNI RBAC, originate every shard's SID, IPv6 and IPv4 + addresses from its own node with a distinct IPv4 per shard, copy the + `galactic-cni-egress` rule group to the central evaluator, and write the + runbook anchors for the seven egress alerts. +3. Run `docs/nat/active-active-rollout.md` in staging, including the + privileged CI job on the staging kernel version. + +## Risks + +- One extra map lookup per grouped packet, and a new inner map per change to + a group (about 2.4 KiB, freed after RCU); a flapping shard costs a + publication per change. +- A busy tenant keeps a draining shard in use indefinitely; draining needs an + operator decision on how long to wait. +- The cause of the one unreproduced drain-stage lab failure is unknown. + +## Re-review findings + +[egress-active-active_2026-10-09_rereview.md](egress-active-active_2026-10-09_rereview.md) +reviewed an intermediate state of the fixes above. Status of its findings +against the code as committed: + +| Finding | Status | Notes | +| ---------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| R01 Closing does not exclude in-flight CNI writes | Partial | CNI ADD re-reads the groups after writing and rewrites its routes in ordered mode if they closed. Every ordered-mode sweep also moves any route still naming a group back to the static list, so a late write is repaired within one sweep (30s), dropping that VRF's egress meanwhile. There is no cross-process barrier, so `group_routes` reading 0 can precede such a write by one sweep. | +| R02 Empty hashed membership restores static shard routes | Open | With no class served, a hashed sweep refreshes without groups and moves routes back to the first resolvable static SID, bypassing readiness and translation checks. | +| R03 Unserved NAT64 prefix falls through to the NAT66 route | Open | CNI ADD skips a configured NAT64 prefix with no eligible shard, so longest-prefix match sends it to the NAT66 group's `::/0` route. | +| R04 Fresh-address counter lost in subshells | Fixed | The counter is kept in a state file, and a failed address add ends the run. | +| R05 Group IDs reused when the prefix list changes | Open | Group IDs are positions in `GALACTIC_CNI_NAT64_PREFIX`; removing or reordering a prefix republishes a group that existing routes still name for a different class. | +| R06 BGP stage withdraws only one route source | Not borne out | The stage removes only the FRR origination, and the shard was reported unreachable within about 2s on every passing run: the compute resolver did not resolve the SID through the EVPN plain route. The stage does not separately assert the compute FIB lookup. | + +R02, R03 and R05 affect hashed mode only and block enabling it; ordered mode, +the default, does not read the groups. diff --git a/docs/archive/reviews/egress-active-active_2026-10-09.md b/docs/archive/reviews/egress-active-active_2026-10-09.md new file mode 100644 index 000000000..4e17e4221 --- /dev/null +++ b/docs/archive/reviews/egress-active-active_2026-10-09.md @@ -0,0 +1,248 @@ +# Architecture Review: egress-active-active + +Historical review of the revisions named below. Findings and test results are preserved as recorded, including dispositions that later commits changed. This is not the current release checklist; use [active/active egress rollout](../../nat/active-active-rollout.md) and verify the candidate release. +**Language:** go | **Reviewed:** 2026-10-09T20:36:23.650844+00:00 + +## Summary + +Not ready for staging enablement signoff: fix rollback and shard-state publication defects, enforce pool compatibility, and complete privileged validation. + +**6 findings:** 🔴 0 critical 🟠 3 high 🟡 3 medium ⚪ 0 low + + +**Scope:** `f61103b2`, `69ebb6cc`, `c8830ea9` (`HEAD~3..HEAD`). Working tree was clean when review began. No earlier report exists in this directory. Review covers implementation, added tests, configuration, monitoring, docs and lab verification. No staging resources were changed. + +**Decision:** Hold staging enablement signoff. The feature can proceed to an isolated validation environment after the high-priority fixes; this review does not certify the live staging environment or current CI run. Changes are opt-in and the deployment manifest still defaults to ordered mode. Estimated remediation is **medium**, principally because coherent BPF publication needs design and kernel validation. + +### Validation evidence + +| Check | Result and limit | +| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `task build:ebpf` | Passed; all four datapaths regenerated, including both BPF endiannesses. Compilation does not prove kernel verifier acceptance. | +| `go build ./cmd/...` | Passed (exit 0); emitted a nonfatal warning about a read-only module stat cache. | +| `bin/golangci-lint run --timeout 5m` | Passed: `0 issues.` | +| Focused `go test -race -count=1 -v` | `egressroutemap`, `attachreg`, `metrics` passed. Root-gated cases skipped, including **all seven new TestGroupDatapath tests**. | +| Config and added installer tests | Passed. The full installer suite encountered sandbox restrictions on TCP/netlink sockets; this is not evidence of an application regression or a passing full suite. | +| Focused `go vet` | Passed for config, installer, egressroutemap, attachreg and metrics. | +| Failure-injection reproduction | Confirmed F05 in a temporary fake-map test: A starts at generation 1; replacing with B writes slot generation 2 but group publication fails; replacing with C also gets generation 2. Test removed after execution; source implementation unchanged. | +| Shell syntax; diff whitespace | `bash -n` and `git diff --check HEAD~3 HEAD` passed. | +| YAML formatter | Could not complete: `stat .git/**: not a directory` in this worktree. | +| Privileged BPF, containerlab, alert tests, full CI | Not completed. Docker socket access denied and review runs unprivileged. No promtool executable available. | +| Remote CI status | Unverified: GitHub API connection failed. | +| Live staging CRD, routing, scrape health and image availability | Unverified; no live staging evidence obtained. | + +Logs from this review are in `/tmp/galactic-review-{datapath-tests,reproductions,lint,build}.log` for this workspace session. + +### Staging acceptance gates + +1. Fix F01 and F05 with iterator/write failure-injection tests. Resolve F06 with an explicit publication/snapshot contract and concurrency coverage. For F04, enforce compatible pool membership; a tightly controlled initial staging trial can also explicitly verify homogeneous shards, but this does not fix general admission behavior. +2. Install and verify the external `EgressShard` CRD version supporting `spec.drain` (the Go dependency now points to network commit `36ee528904ff`). A Go module bump does not update a cluster's schema. Verify a drain patch persists by reading it back. Confirm the updated CNI get/list/watch RBAC is deployed. Document these prerequisites in the rollout procedure. +3. Verify every candidate has unique advertised SID and masquerade addresses, supports the required NAT66/NAT64 families, and agrees on NAT64 prefix/well-known-prefix behavior. Test return routing through **each** shard before distributing tenants. +4. Require a green `task ci`, the separate privileged `task test:unit-root` job on the target kernel, and `task test:alerts`. Fix F02 before treating `verify:nat-active-active` as an acceptance gate. +5. Run a two-shard staging canary using `hashed`, `source`, the default `2h4m` pin idle, and pool minimum `2`. Exercise NAT66 **and NAT64**, TCP/UDP/ICMP, large packets and sustained sessions. The added lab script uses only IPv6 HTTP/NAT66; its flow phase uses pins off and its source phase uses 20 seconds, so it does not establish all default-mode behavior. +6. Check shard addition, actual BGP route withdrawal and restoration, explicit drain, CNI restart with existing pins, initial informer delay/API outage, all shards unavailable, and concurrent membership changes. A prohibit route validates local selection failure, not full BGP failure detection timing. Confirm sessions on a surviving shard continue; sessions on a failed shard are expected to break because NAT state is not replicated. +7. Verify the existing CNI PodMonitor produces `job="galactic-cni"` and correct node labels, the new rules are installed in the actual evaluator (infra centrally evaluates its own copy), and targets scrape successfully. Confirm active/minimum, per-shard traffic and drop counters. Do not interpret absent series as health. +8. Rehearse rollback: preserve the static SID list in the init-container configuration, switch to ordered on the new binary, verify no sentinel routes remain and the group is disabled, then roll back the binary. Mode changes can break sessions placed on a different shard. Delete only **after explicit drain and session quiescence**, not as the drain operation. + +## Architecture + +**Layers observed:** environment configuration → installer informer and netlink watch → egress shard group reconciliation → BPF map adapters → Prometheus collectors + +**Dependency direction:** clean + +``` +EgressShard informer + netlink events -> debounced installer sweep -> shard maps + per-VRF route maps -> datapath +``` + +Reviewed the combined HEAD~3..HEAD change (33 files, 4,237 insertions and 161 deletions), surrounding CNI/NAT controller, resolver, loader, CI and deployment contracts. Dependency direction is coherent. See validation and staging gates below for limits of the evidence. + +## Findings + +### 🔴 P0 — Critical + +No P0 findings. + +### 🟠 P1 — High + +#### [F01] Do not disable the group after a failed ordered-mode refresh +**Location:** `internal/installer/egressgroup.go:175-179` | **Category:** error-handling + +**Problem:** g.refresh logs and discards Refresh's error, returning partial counters. Refresh decides all sentinel rewrites first and increments Ungrouped, leaving InGroup zero when every destination resolves. If iteration or any subsequent Put fails, some/all sentinel routes remain but ordered sweep still disables their group. This violates the promised rollback ordering. + +**Risk:** Switching hashed to ordered during a transient map write/read failure drops all packets on the unconverted VRFs until a later successful sweep; sustained error makes the outage persistent. + +**Before:** +``` +result := g.refresh(table, foreignTableIDs, g.staticSIDs) +if result.InGroup == 0 { groups.Disable(egressroutemap.ClusterShardGroup) } +``` +**After:** +``` +result, err := g.refresh(table, foreignTableIDs, g.staticSIDs) +if err == nil && result.InGroup == 0 { groups.Disable(egressroutemap.ClusterShardGroup) } +``` + +#### [F04] Validate shard translation compatibility before adding it to the pool +**Location:** `internal/installer/egressgroup.go:310-326` | **Category:** config + +**Problem:** Candidate selection accepts every Ready+Programmed SID without checking status.shardAddressIPv6, status.shardAddressIPv4, or status.nat64Prefix. The API/controller legitimately allows shards serving only one family; identityFromSpec only requires at least one masquerade address (egressshard_controller.go:394-397). Both default NAT66 and NAT64 routes now use this same pool. Adding a Ready NAT66-only shard therefore directs a fraction of NAT64 requests to a shard unable to translate them; a different NAT64 prefix has the same defect. Ordered mode could explicitly select compatible shards, but hashed mode silently broadens to every shard. + +**Risk:** Partial deterministic tenant egress outage when a cluster contains valid but heterogeneous shards, including incremental rollout of an incompletely configured second shard. + +**Before:** +``` +if shard.Status.ShardSID == "" || !Programmed || !Ready { continue } +candidates = append(candidates, ShardCandidate{SID: sid, Draining: ...}) +``` +**After:** +``` +Validate each candidate against the compute node's required NAT66/NAT64 families and NAT64 prefix; reject incompatible pool configuration with a surfaced error, or maintain eligible groups per translation route. +``` + +#### [F05] Reserve slot generations across failed group publication +**Location:** `internal/plumbing/ebpf/egressroutemap/shardgroup.go:291,356-361` | **Category:** concurrency + +**Problem:** A new slot receives current group generation + 1, but slots are written before the group generation is committed. If the group Put fails, the changed slot is already visible to packets through the old Maglev table. Another candidate replacement before the next successful group publication receives the same generation. Pins created for the first replacement are then accepted for the second. The documented never-reused identity guarantee is false on partial failure. + +**Risk:** A pin can silently follow an unrelated shard after partial reconciliation; draining replacements can inherit live pins and existing sessions can move unexpectedly. + +**Before:** +``` +nextGeneration := current.Generation + 1 +value.Generation = nextGeneration +// write slots, then group; return on failure +``` +**After:** +``` +Allocate identities from durable monotonic state that includes partially published slots, and preserve uniqueness through retries and slot clearing. Add failure-injection tests across every write boundary. +``` + +### 🟡 P2 — Medium + +#### [F02] Require successful new-tenant egress in the drain check +**Location:** `deploy/containerlab/scripts/verify-nat-active-active.sh:224-231` | **Category:** testing + +**Problem:** The drain test only rejects observed packets on the drained shard. sources suppresses curl/tcpdump errors, and an empty capture produces seen=[]; the loop executes zero times and announces success. A regression blackholing all unpinned tenants during drain therefore passes this stage, while the existing A connection alone is checked for success. + +**Risk:** The advertised end-to-end staging gate can certify broken drain behavior. + +**Before:** +``` +mapfile -t seen < <(sources "${t}" 3) +for addr in "${seen[@]}"; do ...; done +echo "ok ..." +``` +**After:** +``` +Require successful requests and exactly one captured source, matching the surviving shard's expected masquerade address, before reporting success. +``` + +#### [F03] Remove the claim that deleting a shard gracefully drains it +**Location:** `docs/nat/configuration.md:517-518` | **Category:** config + +**Problem:** The new operator guide says deleting EgressShard drains it like spec.drain. EgressShardReconciler has no finalizer, withdraws advertisement on deletion (internal/controller/egressshard_controller.go:167-185), and excludes terminating shards from syncNode at line 220. Translation is cleared immediately rather than retained until sessions drain. Merely marking a terminating object as a draining candidate cannot change this lifecycle. + +**Risk:** An operator using deletion as documented interrupts every session on that shard. + +**Before:** +``` +Deleting an EgressShard drains it the same way for as long as it takes to go. +``` +**After:** +``` +Set spec.drain=true, wait for sessions to reach zero, then delete. Deleting without this sequence immediately tears down the shard and its sessions. +``` + +#### [F06] Read a coherent shard snapshot during concurrent map updates +**Location:** `internal/plumbing/ebpf/prog/usid.c:1212-1228,3673-3680,3712-3736` | **Category:** concurrency + +**Problem:** The group and shard maps are ordinary BPF ARRAY maps. Userspace updates modify the existing value in place, while the packet program retains pointers and reads flags/generation separately from SID, ifindex and MACs. A slot or next-hop update can interleave after validation but before route copying, so a packet can validate one identity and encapsulate with a different or mixed record. Ordered writes between maps do not make an individual array record atomic. + +**Risk:** Transient packet loss or incorrect encapsulation during membership and next-hop changes. Existing sequential BPF_PROG_RUN tests cannot establish concurrency safety. This is source-supported, not reproduced on a kernel in this review. + +**Before:** +``` +shard = bpf_map_lookup_elem(...); // validate flags/generation +... +memcpy(route.sid, shard->sid, ...); route.link_ifindex = shard->link_ifindex; +``` +**After:** +``` +Publish immutable/versioned records or use a supported synchronization scheme that copies and validates one consistent snapshot; stress updates concurrently with real packet processing. +``` + +### ⚪ P3 — Low + +No P3 findings. + +## What's Working Well + +- Configuration validates mode, hash, pin timeout, and minimum at startup rather than silently falling back. +- Unsynced informer state is distinguished from an empty candidate set. +- Informer and netlink events feed a bounded debounced sweep; periodic ticker backs up event delivery. +- Egress route sweeps preserve sidecar-owned namespace state. +- Docs explicitly require switching to ordered before rolling back to a binary predating group sentinels. +- New read-only EgressShard RBAC is scoped by resource and informer namespace. +- Metrics expose active/draining/unreachable state and selection outcomes; existing CNI PodMonitor is present. +- Added installer helper tests and config tests pass; verification script passes bash syntax check. +- go vet ./internal/config ./internal/installer passes. + +## Refactor Plan + +Each step is independently mergeable and must not break existing behavior. + +### Step 1: Preserve refresh errors through rollback +*Addresses: F01* + +**What:** Return the error from g.refresh and only disable groups after a complete successful conversion; add failure-injection coverage for iterator and route Put errors. + +**Why now:** Rollback reliability is a staging safety prerequisite. + +**Safe when:** Failed conversion leaves group enabled and old sentinel routes usable; successful retry converts routes then disables it. + +### Step 2: Make shard publication and identity retry-safe +*Addresses: F05, F06* + +**What:** Preserve unique slot identities through partial writes and implement coherent datapath snapshots. + +**Why now:** Pin continuity depends on stable identity and consistent route reads. + +**Safe when:** Fault injection cannot reuse identity, and concurrent packet/update stress shows no mixed route or invalid pin acceptance. + +### Step 3: Enforce compatible translation identities +*Addresses: F04* + +**What:** Validate status families and NAT64 prefix against local egress requirements before pool admission, with explicit error reporting and mixed-pool tests. + +**Why now:** Ready alone does not mean the shard can serve every route moved to the common pool. + +**Safe when:** A NAT66-only or differently prefixed shard cannot receive NAT64 traffic it does not support. + +### Step 4: Make drain verification fail on absence of traffic +*Addresses: F02* + +**What:** Check request success and require the expected surviving source address. + +**Why now:** Readiness evidence must detect drops as well as wrong placement. + +**Safe when:** A blackholed fresh tenant makes the script fail; a healthy surviving shard passes. + +### Step 5: Correct deletion procedure +*Addresses: F03* + +**What:** Document explicit drain, session wait, then delete; remove unsupported graceful-delete claim. + +**Why now:** Operators need accurate lifecycle guidance before first staging rollout. + +**Safe when:** Runbook matches reconciler lifecycle and no longer treats delete as graceful. + +## Additional constraints and coverage observations + +- Source placement is address-based, not load-aware. Roughly equal address counts do not imply equal byte rates when tenants vary in traffic volume. +- Pins are local to a compute node and bounded by a 65,536-entry LRU. Eviction after a membership change can move an active address; drain can persist indefinitely if an address keeps sending. This is not replicated NAT session state. +- Hash input includes the node-local Linux VRF table ID. `internal/plumbing/vrf/vrf.go` allocates these locally, so identical Maglev member sets alone do not guarantee the same placement for a VPC address on different compute nodes. Workload migration continuity needs separate validation; no cross-node pin transfer is implemented. +- Flow-mode fragment placement is tested for IPv4 in the selector, but existing NAT translation explicitly lacks full fragment handling. Do not advertise end-to-end fragment support based on the selector test. +- Current new installer tests cover candidate filtering, event matching and kick coalescing, not informer startup, actual sweep sequencing, partial failures or mode-transition races. Datapath tests are sequential; they do not test userspace/kernel update interleavings. +- The group-empty alert intentionally requires at least one member. A zero-candidate pool with existing sentinels instead relies on below-minimum or traffic-driven drop alerts. An informer that never initializes can leave enabled=0, suppressing the pool alerts; verify desired mode and startup logs separately. + +For F06, the kernel documents that array lookup returns a pointer into shared array storage and requires synchronization for concurrent access: [Linux BPF array-map documentation](https://docs.kernel.org/bpf/map_array.html). `array_map_update_elem` copies into the existing element unless locking is explicitly requested: [Linux array-map implementation](https://github.com/torvalds/linux/blob/master/kernel/bpf/arraymap.c). These establish the map semantics; the packet-level interleaving is an inference from this change's reads and writes, not an observed live incident. diff --git a/docs/archive/reviews/egress-active-active_2026-10-09_rereview.md b/docs/archive/reviews/egress-active-active_2026-10-09_rereview.md new file mode 100644 index 000000000..ea34e3335 --- /dev/null +++ b/docs/archive/reviews/egress-active-active_2026-10-09_rereview.md @@ -0,0 +1,232 @@ +# Architecture Review: egress-active-active + +Historical review of the revisions named below. Findings and test results are preserved as recorded, including dispositions that later commits changed. This is not the current release checklist; use [active/active egress rollout](../../nat/active-active-rollout.md) and verify the candidate release. +**Language:** go | **Reviewed:** 2026-10-09T21:36:38.278824+00:00 + +## Summary + +Not ready for staging enablement: snapshot publication is substantially improved, but rollback and translation-class routing still have correctness defects. + +**6 findings:** 🔴 0 critical 🟠 4 high 🟡 2 medium ⚪ 0 low + + +**Scope:** Current uncommitted changes relative to `c8830ea9`, including new untracked implementation files. HEAD has not advanced since the original review. Reviewed against the original report and the implementation prompt. The original report is preserved unchanged. + +**Decision:** Hold staging enablement. The snapshot redesign addresses the original mutable-array and partial-publication problems, but four high-priority routing/transition findings remain. Estimated remediation is medium. No implementation files were changed by this review and no infrastructure was modified. + +### Original findings disposition + +| Original finding | Assessment | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| F01 — unsafe rollback after refresh errors | Error propagation fixed. Concurrent CNI registration is still unsafe (R01). | +| F02 — drain test accepts no traffic | Original vacuous pass fixed. Fresh-address allocation and the real-BGP failure scenario need correction (R04, R06). | +| F03 — deletion described as graceful drain | Fixed in the updated guide and deletion candidate filtering. | +| F04 — incompatible pool members | Per-class capability filtering added, but route selection can bypass it (R02, R03), and class reconfiguration can redirect to a different class (R05). | +| F05 — generation reuse after partial writes | Structurally addressed by atomic snapshot publication and persisted slot generation state. | +| F06 — torn shard records during updates | Structurally addressed by immutable map-in-map publication. Concurrent kernel test added; execution remains unverified here. | + +### Validation and reproductions + +- `task build:ebpf`: passed, all four datapaths regenerated. +- `go build ./cmd/...`: passed (exit 0), with a nonfatal read-only module stat-cache warning. +- Repository-wide `golangci-lint run --timeout 5m`: passed, **0 issues**. +- `go test -race -count=1 -v` for egressroutemap, attachreg and metrics: passed for runnable cases. Privileged packet/publication tests skipped, including the new concurrent-swap and publication-failure tests. +- Focused installer group/shard/egress/class tests: passed. +- Focused `go vet` for installer, egressroutemap, attachreg, metrics and attach: passed. +- `bash -n` for the acceptance script and `git diff --check`: passed. +- Three temporary Go overlay reproductions confirmed R01, R02 and R05 without modifying source files. These tests assert the defective behavior to establish the finding; their passing is not acceptance evidence. +- R01: inject a sentinel after the ordered sweep's scan. The group becomes disabled with one referencing route left. +- R02: a synced empty shard list converts three existing group routes back to a resolvable static shard. +- R05: remove the first NAT64 prefix from a two-prefix configuration. Its route remains on group 1, which now serves the second prefix and its different shard. +- R03 follows directly from the installed route set and longest-prefix-match lookup; existing single-family tests expect the missing specific prefix and do not exercise actual packet selection through the catch-all. +- No privileged kernel acceptance, containerlab scenario, promtool alert tests, full `task ci`, remote CI verification or live staging checks were completed in this review. A green lint/unit run does not close these gates. + +Reproduction artifacts for this session: `/tmp/review-overlay.json`, `/tmp/review_regression_test.go`, `/tmp/review-class-overlay.json`, `/tmp/review_class_lifecycle_test.go`, and `/tmp/egress-rereview-class-repro.log`. Other checks are logged under `/tmp/egress-rereview-*.log`. + +## Architecture + +**Layers observed:** installer informer → translation-class groups → CNI registration → metrics → acceptance script + +**Dependency direction:** clean + +Translation-scoped groups are a sound direction; empty-class and transition semantics require correction. + +## Findings + +### 🔴 P0 — Critical + +No P0 findings. + +### 🟠 P1 — High + +#### [R01] Closing groups does not exclude in-flight CNI sentinel writes +**Location:** `internal/plumbing/ebpf/attachreg/egressgroups.go:91-106` | **Category:** concurrency + +**Problem:** A CNI ADD can read an open group and pause; ordered sweep closes it, scans/converts all visible routes and disables it; ADD then writes a sentinel referencing the disabled group. The post-write check only repairs afterward and may fail, encounter an empty static list, or never run if the process terminates. An error after a partial class install also returns before rechecking. Existing VRF routes can be affected by ADD/FillVRF, not just a not-yet-connected pod. + +**Risk:** Rollback can still blackhole tenant routes while reporting no group routes and a disabled group. Original refresh error propagation is fixed but the requested concurrent-registration safety is not. + +**Before:** +``` +installGroupRoutesIn(...); stillOpen, err := groups.AnyOpen(); installOrderedEgress(...) +``` +**After:** +``` +Serialize sentinel publication and group closing/last scan with a cross-process registration barrier or equivalent protocol; retiring must wait for admitted writers. Test late publication and failed repair. +``` + +#### [R02] Empty hashed membership silently restores static shard routes +**Location:** `internal/installer/egressgroup.go:335-339` | **Category:** config + +**Problem:** With no class having candidates, byClass is empty and WithShardGroups is omitted. Refresh interprets this as ordered mode and rewrites existing sentinels to the first resolvable static SID, even though the informer rejected it or removed its capabilities. Static SID resolution does not validate readiness or translation. + +**Risk:** Hashed mode bypasses its admission and empty-group safeguards, sending traffic to unready, deleted-but-still-routable or incompatible shards. Group-empty metrics/alerts can also lose their route evidence. + +**Before:** +``` +if len(byClass) > 0 { opts = append(opts, WithShardGroups(groupFor)) } +``` +**After:** +``` +Always express hashed refresh semantics, including an empty class map; preserve or install explicit empty-class sentinels rather than invoking ordered fallback. +``` + +#### [R03] Skipping an unserved NAT64 prefix lets NAT66 default route catch it +**Location:** `internal/plumbing/ebpf/attachreg/egressgroups.go:155-158` | **Category:** config + +**Problem:** When NAT66 has candidates but a configured NAT64 /96 has none, installGroupRoutesIn installs ::/0 and skips the /96. LPM lookup then selects the NAT66 group for packets to that configured NAT64 prefix. TestInstallVRFEgress_SingleFamilyDeployments/NAT66Only and MismatchedPrefix explicitly encode this unsafe route set. + +**Risk:** NAT64 traffic is sent to shards not admitted to its translation class, defeating F04. New VRFs behave differently from existing VRFs whose empty NAT64 sentinel remains. + +**Before:** +``` +if !found || !status.Open() || status.Candidates == 0 { continue } +``` +**After:** +``` +Install an explicit rejecting/empty-group route for each configured but unserved NAT64 prefix, or fail attachment when the class is required. Exercise actual LPM selection against ::/0. +``` + +#### [R05] Do not reuse a translation-class group while old routes reference it +**Location:** `internal/installer/egressgroup.go:355-358; internal/plumbing/ebpf/egressroutemap/egressroute.go:767-771` | **Category:** config + +**Problem:** Group IDs are the positions in the current configured prefix list. With [NAT66, P1, P2] published, removing P1 changes the list to [NAT66, P2] and overwrites group 1 with P2 before repairing existing routes. A route for P1 still names group 1. Refresh finds no configured class for P1 and deliberately leaves its sentinel untouched, so it now sends P1 traffic to P2-only shards. Old group 2 is never retired and remains a duplicate P2 group; FindClass and the sweep can pick different duplicates. + +**Risk:** Configuration changes cause persistent cross-class routing and NAT64 outages. Removed classes also remain published and can retain stale members indefinitely. + +**Before:** +``` +for i, class := range g.classes { groups.Apply(uint32(i), ..., eligible) } +``` +**After:** +``` +Allocate stable class identities and reconcile retired classes explicitly. Do not reuse a group ID until every reference has been safely migrated or replaced with a fail-closed route. Test removal, reorder, replacement, and restart with old snapshots. +``` + +### 🟡 P2 — Medium + +#### [R04] Fresh-address counter is lost in command substitutions +**Location:** `deploy/containerlab/scripts/verify-nat-active-active.sh:157-165` | **Category:** testing + +**Problem:** Every fresh call is through $(fresh), which runs in a subshell. FRESH_N increments never persist in the parent, so every address has counter=1 and only one random byte distinguishes calls. About 17 calls in the full script give roughly 42% collision probability. Reused addresses still carry default-duration pins, and ip addr add failures can be hidden because the function continues to echo an address. + +**Risk:** The acceptance gate intermittently fails for address collisions or tests already-pinned addresses as fresh tenants during drain/failure; it cannot reliably certify fresh selection. + +**Before:** +``` +a=$(fresh) # fresh increments FRESH_N locally and uses random.randrange(256) +``` +**After:** +``` +Allocate monotonically unique addresses in the parent shell or persistent state file; propagate addr-add errors and verify no address reuse. Avoid command substitution for the state mutation. +``` + +#### [R06] Withdraw every route source before measuring shard-unreachable convergence +**Location:** `deploy/containerlab/scripts/verify-nat-active-active.sh:337-340,515-516` | **Category:** testing + +**Problem:** The real-BGP scenario removes only the fabric-router network statement for the shard /64. EgressShardReconciler independently advertises that same /64 as plain reachability through galactic-router EVPN (egressshard_controller.go:466-507,529 onward), and processEVPNPath installs it through the plain-route reconciler (runtime/gobgp/monitor.go:184-188). The node loopback remains reachable. The compute resolver can therefore keep finding the EVPN route and a healthy uplink neighbor; withdrawing the FRR origin alone does not establish shard unreachability. + +**Risk:** The acceptance scenario can time out waiting for unreachable=1 on a correctly configured lab; it cannot be treated as proof of end-to-end failure detection. + +**Before:** +``` +originate "${SHARD_B}" no; wait_metric ... unreachable 1 300 +``` +**After:** +``` +Use an isolated, reversible failure that removes all usable paths to that shard, or suppress both advertisement sources with reliable restoration. Assert the actual compute FIB lookup no longer resolves over a fabric uplink before measuring selection convergence. +``` + +### ⚪ P3 — Low + +No P3 findings. + +## What's Working Well + +- Refresh errors now propagate and prevent disable after failed iterator/map write. +- Candidates check realized status families, NAT64 prefix and well-known-prefix support; terminating shards excluded. +- Drain documentation correctly requires explicit drain then quiescence before delete. +- Probe checks requests and capture counts, includes blackhole negative check and NAT64/UDP/ICMP coverage. +- Adds watch synchronization, desired mode, sweep failure metrics and staging rollback checklist. +- Immutable group snapshots combine membership, Maglev, generation and forwarding fields and publish via one ARRAY_OF_MAPS replacement. +- F05 partial slot publication is eliminated because failed create/write/swap attempts do not publish the new inner map. +- New kernel tests cover failure boundaries, restart pin retention, class isolation and concurrent snapshot swaps; these still require privileged execution. + +## Refactor Plan + +Each step is independently mergeable and must not break existing behavior. + +### Step 1: Make group retirement exclude concurrent writers +*Addresses: R01* + +**What:** Implement registration barrier and fault tests. + +**Why now:** Rollback must be safe. + +**Safe when:** No late writer can outlive disabled group. + +### Step 2: Preserve fail-closed translation classes +*Addresses: R02, R03* + +**What:** Keep hashed refresh semantics for empty classes and install explicit per-prefix failures. + +**Why now:** Admission must apply to actual traffic. + +**Safe when:** Zero candidates never sends traffic to static or another class. + +### Step 3: Reconcile translation-class lifetime +*Addresses: R05* + +**What:** Keep class-to-group identity stable and safely retire removed classes and routes. + +**Why now:** Changing configuration must not reinterpret existing sentinel routes. + +**Safe when:** Removal/reorder/replacement never forwards a route to a group for a different prefix. + +### Step 4: Make fresh probes deterministic +*Addresses: R04* + +**What:** Persist unique address allocation and check errors. + +**Why now:** Acceptance must be repeatable. + +**Safe when:** Repeated calls never reuse source addresses. + +### Step 5: Make the BGP acceptance failure remove all usable paths +*Addresses: R06* + +**What:** Account for both FRR and galactic-router advertisements; verify the compute FIB and reliably restore the failure. + +**Why now:** A routing failover test must induce the failure it claims to measure. + +**Safe when:** The test proves actual loss and recovery of reachability without a local prohibit-route shortcut. + +## Remaining staging gates and review observations + +Fix R01–R05 and correct the routing failure scenario before treating the lab script as an acceptance gate. Re-run privileged tests on the staging kernel, alert tests, full CI and the complete lab scenario. Confirm the external CRD, read-back of `spec.drain`, RBAC, unique per-shard addresses, per-class eligibility and actual central alert deployment. The new rollout checklist is useful documentation, not evidence those checks were performed. + +The new script checks UDP outbound arrival but does not demonstrate translated UDP return traffic. Shard addition, initial first-sync delay and concurrent membership changes still need explicit execution evidence. Its rollback stage assumes the saved starting mode was ordered even though cleanup claims general restoration; make that precondition explicit or set ordered for the test and restore the original state separately. + +Monitoring now exposes desired mode and watch sync, which is an improvement. Missing map-derived pool series and stale successful-sweep timestamps still need an operational check: early pinned-map open failures bypass SweepError, and there is no dedicated alert consuming the successful-sweep timestamp. Confirm those cases cannot appear healthy merely because the process answers scrapes. + +Upgrade from the reviewed experimental mutable-array build is not explicitly migrated: the new outer map starts empty while existing sentinel routes/pins can remain, and obsolete map pins are removed. If that experimental build was ever enabled anywhere, require an ordered-mode transition before this upgrade or implement/test state migration. This is an additional deployment prerequisite, not a claim that the old experimental build was deployed. diff --git a/docs/designs/README.md b/docs/designs/README.md new file mode 100644 index 000000000..bcc5a9f51 --- /dev/null +++ b/docs/designs/README.md @@ -0,0 +1,15 @@ +# Designs and proposals + +These documents explain decisions and planned work. Their status describes implementation scope, not whether a deployment has passed its rollout gates. Use component operating guides for current commands and defaults. + +| Design | Status | Current reference | +| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| [Interface traffic policy](interface-traffic-policy.md) | Implemented design; rollout remains explicit | [Rollout](../traffic-policy/rollout.md) and [node behavior](../traffic-policy/node.md) | +| [Galactic Edge](galactic-edge.md) | Partially implemented and subject to qualification | [Provider contract](../edge/provider-contract.md) and its open items | +| [Private Service Connect](private-service-connect.md) | Partially implemented; qualification gaps remain | [Private-service routes](../router/private-service-routes.md) | +| [Looking Glass backend service](looking-glass-service.md) | Proposed implementation contract; authentication scaffolding does not enable service execution | [Current fabric-api](../fabric-api/README.md) | +| [Shared DNS64](dns64/README.md) | Proposed; end-to-end validation outstanding | [NAT configuration](../nat/configuration.md) for implemented translation | +| [Latency-aware routing](latency-aware-routing.md) | Exploratory proposal | [Router configuration](../router/configuration.md) for available settings | +| [MASQUE gateway](masque-gateway.md) | Exploratory proposal; external references may describe historical designs | [Gateway configuration](../gateway/configuration.md) for the implemented XDP/DSR gateway | + +When implementing a proposal, move the available interface or operating procedure into its component guide and update this status. Retain decisions and alternatives here. Keep measurements tied to their revision and environment in the [evidence archive](../archive/README.md), rather than presenting old results as current readiness. diff --git a/docs/designs/dns64/README.md b/docs/designs/dns64/README.md new file mode 100644 index 000000000..ddb2f03e7 --- /dev/null +++ b/docs/designs/dns64/README.md @@ -0,0 +1,215 @@ +# Shared DNS64 service + +Status: Proposed. This design has not passed end-to-end Galactic validation. + +## Summary + +Provide a managed DNS64 service for IPv6-only Compute instances. PowerDNS +Recursor resolves public names and synthesizes AAAA records from A records +when a name has no usable native AAAA record. Galactic's NAT64 gateway +translates connections to IPv4. + +The initial service uses one shared `/96` NAT64 prefix per serving fabric and a +shared regional resolver fleet. The planning range is 10,000–100,000 tenants; +it is not a verified capacity limit. The service scales resolver capacity by +traffic and configuration size instead of deploying a resolver for every +tenant. + +Private DNS, tenant-specific views, private zones, conditional forwarding, +and tenant-specific NAT64 prefixes are outside this proposal. + +## Motivation + +IPv6-only instances need to reach IPv4-only public services without requiring +each customer to operate a DNS64 resolver or NAT64 gateway. A managed service +provides a consistent resolver address and connects DNS synthesis to the +Galactic routing and NAT64 path. + +## Goals + +- Resolve public names for IPv6-only instances. +- Synthesize eligible AAAA records using the shared NAT64 prefix. +- Deliver a stable IPv6 resolver endpoint through the Compute network path. +- Scale through shared resolver replicas and bounded capacity shards. +- Validate DNSSEC behavior, synthesis exclusions, abuse controls, failover, and + end-to-end NAT64 connectivity. +- Report resolver health, query failures, synthesis, and NAT64 reachability. + +## Non-goals + +- Provide private zones, split-horizon DNS, or customer DNS forwarding. +- Provide tenant-specific resolver views, caches, upstreams, or NAT64 prefixes. +- Build a DNS protocol engine or replace public authoritative DNS. +- Operate an open recursive resolver or expose public encrypted DNS endpoints. +- Make IPv4 literals work or create connectivity to unreachable destinations. +- Preserve established connections when a NAT64 gateway loses session state. + +## High-level architectural proposal + +Use PowerDNS Recursor as the short-term recursive DNS64 engine. Its native +`recursor.dns64_prefix` setting supplies the shared `/96` prefix and performs +RFC 6147 synthesis. A DNS service controller publishes resolver configuration +and readiness. Galactic supplies network isolation, resolver endpoint routing, +and NAT64 forwarding. dnsdist and authoritative DNS components are deferred +until a later capability requires them. + +A resolver shard is a bounded group of PowerDNS Recursor replicas. Shards are +selected by aggregate query rate, cache size, and operational limits rather +than by one-process-per-tenant allocation. The initial endpoint is shared by +the serving region; workload attachment and routing determine which network +may reach it. + +![Compute uses Galactic to reach a shared PowerDNS Recursor fleet and a separate NAT64 gateway. A DNS service controller reads the gateway prefix from the network API.](containers.svg) + +[Container diagram source](containers.puml). + +The container diagram is the component and relationship reference. The +resolver service and PowerDNS Recursor are shared regionally; the NAT64 path is +separate from the DNS query path. + +### Endpoint access and resource controls + +The resolver VIP is a managed network service. Galactic authorizes the workload +attachment and routes only eligible network traffic to the endpoint. The +attachment and resolver service must reject spoofed sources and unauthorized +queries. + +The first milestone does not require a resolver process or cache per tenant. +Bound shard memory, connections, outstanding queries, and query rates. Apply +ACLs and rate limits at the resolver service and enforce limits consistently +across replicas. Reject EDNS Client Subnet from clients and do not send it to +public upstreams unless a later privacy review approves an exception. + +## Design details + +### Resolution and connection flow + +The Compute platform configures the instance. The instance then uses ordinary +DNS and TCP or UDP; the DNS service controller is not on the query path. + +![The Compute platform attaches an IPv6-only instance to Galactic and supplies a resolver endpoint. PowerDNS Recursor returns a synthesized address. Galactic routes the connection through NAT64 to an IPv4 service.](resolution-sequence.svg) + +[Sequence diagram source](resolution-sequence.puml). + +The sequence diagram is the flow reference. The important invariants are that +DNS does not select a NAT64 gateway, the synthesized address uses the shared +prefix, and application traffic returns through the same translation path. + +The [CNI route implementation][cni-routes] and [NAT64 gateway design][nat64-design] +define the existing networking side of this flow. Resolver endpoint delivery +remains a proposed integration. + +### Shared prefix and routing contract + +Use one Datum-managed `/96` prefix shared across the fabric. Read it from +[`EgressShard.status.nat64Prefix`][egress-status]; do not allocate prefixes in +the DNS service. Require agreement between assigned NAT64 shards and the CNI +configuration before enabling synthesis. + +Require current gateway status, route convergence, and active IPv4 connection +checks. The current [`Ready` condition][shard-readiness] reports an attached +translation program, not working IPv4 connectivity. Operators must provide +[IPv4 return routing][return-routing]. + +If the prefix is missing or inconsistent, disable synthesis and report the +reason. Native IPv6 resolution can continue. Coordinate prefix changes with +route retention for cached synthesized answers; clients can retain earlier +answers until their TTL expires. + +### Synthesis and DNS security + +Follow [RFC 6147][dns64-rfc]. Synthesize only for an AAAA query when eligible +A records exist and no usable native AAAA record exists. Preserve NXDOMAIN, +negative answers, and upstream errors. Exclude IPv4 literals, special-use +names, destinations covered by local policy, and any destination that must +remain unreachable. + +Enable PowerDNS Recursor DNSSEC validation. Do not synthesize when validation +returns `Bogus`. Synthesized records are generated by the resolver and do not +carry a signature from the original zone. Validate behavior for signed +IPv4-only names, unsigned names, SERVFAIL, and negative answers. + +Use public-root trust anchors and query-name minimization for public +resolution. Apply ACLs, response-rate limiting, maximum response sizes, and +resource limits to reduce cache-poisoning, amplification, and denial-of- +service risk. + +### Configuration and rollout + +The DNS service controller distributes versioned fleet configuration to the +assigned resolver shards. The initial configuration contains the shared +prefix, public upstream policy, ACLs, synthesis exclusions, resource limits, +and observability settings. It does not manage tenant zones or tenant DNS +records. + +Validate each revision before activation and retain the previous revision for +rollback. Drain a replica before upgrade, verify health and synthesis, then +return it to service. Admit a shard only after its configuration, resolver +health, and NAT64 prefix agree with the active revision. + +### Availability, capacity, and operations + +Place resolver replicas across failure domains within each region. Keep enough +spare capacity to lose a replica. Use a stable IPv6 VIP with health-aware +backend selection. Rebuild caches after failure; do not treat them as durable +state. + +Assign shards by query rate, cache size, response size, and connection limits. +Configuration and memory still grow with aggregate traffic, but shared replicas +avoid a fixed deployment per tenant. Measure query latency, error rate, +synthesis rate, cache hit rate, resolver resource use, and NAT64 connection +success. Bound metric cardinality and query-log retention. Add tenant-level +accounting only when quotas or billing require it. + +## Implementation boundary + +The existing prototype exercised dnsdist, BIND, and Jool in a controlled lab. +That implementation is not the short-term production design. The new prototype +must exercise PowerDNS Recursor with the shared prefix and the intended +Galactic/NAT64 path. Jool remains a test fixture only. + +The Galactic compatibility profile validates saved configuration offline; it +does not prove the Galactic packet path. Controlled upstreams and same-host +replicas do not establish internet-resolution performance or failure-domain +availability. + +Galactic source reviewed on September 16, 2026, supports TCP and UDP. It lacks +ICMP translation, fragmentation handling, and path MTU discovery, and it does +not provide full [RFC 6146][nat64-rfc] behavior. Gateway restart loses session +state. See the [datapath limits][nat-limits] and [gateway design constraints][nat64-constraints]. + +Before a production pilot, complete these checks: + +1. Verify resolver endpoint delivery and unauthorized-source rejection through + Galactic. +2. Test native AAAA, synthesized AAAA, DNSSEC failures, exclusions, negative + answers, and upstream failures. +3. Verify the intended NAT64 route and IPv4 return path with TCP and UDP; + measure gateway restart, stale status, and large-packet behavior. +4. Qualify PowerDNS Recursor shard limits, cache behavior, rate limiting, + rolling upgrades, configuration rollback, and resolver failover. +5. Run load and abuse tests at the planned 1,000, 5,000, and 10,000 aggregate + QPS shard profiles. + +Production requires agreed service objectives, a durable control-plane design, +and a documented resolution or accepted product restriction for NAT64 protocol +limits. + +## Diagram maintenance + +Edit the PlantUML sources, then regenerate both SVG files from the repository +root. PlantUML 1.2026.5 and its bundled C4 library produced these diagrams. + +```sh +plantuml -tsvg docs/designs/dns64/containers.puml docs/designs/dns64/resolution-sequence.puml +``` + +[nat64-design]: https://github.com/datum-cloud/enhancements/blob/a778a6c3104b60b0e7634af4f3e5d2e3ae303549/enhancements/networking/nat64-gateway-for-vpc-networks.md#L184-L198 +[egress-status]: https://github.com/datum-cloud/network/blob/ec15d7bda7eb47960a5e2b38daa4d30d42b12748/api/v1alpha1/egressshard_types.go#L90-L114 +[cni-routes]: https://github.com/datum-cloud/galactic/blob/846f5d2a189f2849e044de3b383b5ca7be759777/internal/cnibgp/bgp.go#L759-L834 +[shard-readiness]: https://github.com/datum-cloud/galactic/blob/846f5d2a189f2849e044de3b383b5ca7be759777/internal/controller/egressshard_controller.go#L286-L303 +[return-routing]: https://github.com/datum-cloud/galactic/blob/846f5d2a189f2849e044de3b383b5ca7be759777/internal/controller/egressshard_controller.go#L180-L184 +[nat-limits]: https://github.com/datum-cloud/galactic/blob/846f5d2a189f2849e044de3b383b5ca7be759777/internal/plumbing/ebpf/natprog/nat.c#L74-L92 +[nat64-constraints]: https://github.com/datum-cloud/enhancements/blob/a778a6c3104b60b0e7634af4f3e5d2e3ae303549/enhancements/networking/nat64-gateway-for-vpc-networks.md#L184-L198 +[dns64-rfc]: https://www.rfc-editor.org/rfc/rfc6147.html +[nat64-rfc]: https://www.rfc-editor.org/rfc/rfc6146.html diff --git a/docs/enhancements/dns64/containers.puml b/docs/designs/dns64/containers.puml similarity index 100% rename from docs/enhancements/dns64/containers.puml rename to docs/designs/dns64/containers.puml diff --git a/docs/enhancements/dns64/containers.svg b/docs/designs/dns64/containers.svg similarity index 100% rename from docs/enhancements/dns64/containers.svg rename to docs/designs/dns64/containers.svg diff --git a/docs/enhancements/dns64/resolution-sequence.puml b/docs/designs/dns64/resolution-sequence.puml similarity index 100% rename from docs/enhancements/dns64/resolution-sequence.puml rename to docs/designs/dns64/resolution-sequence.puml diff --git a/docs/enhancements/dns64/resolution-sequence.svg b/docs/designs/dns64/resolution-sequence.svg similarity index 100% rename from docs/enhancements/dns64/resolution-sequence.svg rename to docs/designs/dns64/resolution-sequence.svg diff --git a/docs/designs/galactic-edge.md b/docs/designs/galactic-edge.md new file mode 100644 index 000000000..aea001e16 --- /dev/null +++ b/docs/designs/galactic-edge.md @@ -0,0 +1,257 @@ +# Galactic Edge Foundation + +Status: partially implemented design. Core resources, controllers, the node agent and a reference-provider conformance harness exist. The [provider contract](../edge/provider-contract.md) is the maintained integration reference. Open qualification items and deployment-dependent timing targets remain; this design is not evidence of production readiness. + +Tracking issue: [Galactic Edge Foundation (#992)](https://github.com/datum-cloud/galactic/issues/992). + +This design follows the [Datum enhancement template](https://github.com/datum-cloud/enhancements/blob/main/enhancements/template/README.md). Read the status above before treating a requirement or milestone as available behavior. + +- [Summary](#summary) +- [Motivation](#motivation) +- [Proposal](#proposal) +- [Design Details](#design-details) +- [Production Readiness Review Questionnaire](#production-readiness-review-questionnaire) +- [Implementation History](#implementation-history) +- [Drawbacks](#drawbacks) +- [Alternatives](#alternatives) + +## Summary + +Galactic Edge is a common foundation for services that connect external networks and clients to gVPC workloads. A service integrates as a **provider**: it requests an authorized tenant attachment and declares which authorized prefixes it can serve. The foundation supplies isolation, gVPC traffic policy, route lifecycle, recovery, and exclusive forwarding ownership. + +Providers own their protocols and client sessions. Galactic Edge owns the boundary between those services and shared VPC networking. A new provider should integrate through the same contract without changing the foundation or receiving direct access to shared host networking. + +## Motivation + +External connectivity services need many of the same networking guarantees, even when their protocols differ. Each needs a tenant-specific path into the VPC, a return path, authorization, policy enforcement, and safe cleanup when an instance fails or moves. Reimplementing these responsibilities in each service creates competing writers and inconsistent failure behavior. + +Galactic Edge makes these guarantees reusable while retaining the existing Galactic routing and SRv6 data plane. It gives service authors a small integration boundary and operators one model for attachment health and ownership. + +### Goals + +- Connect independently developed providers to authorized gVPCs through one internal contract. +- Isolate tenants, including tenants using identical addresses. +- Publish prefix reachability only while authorization, attachment readiness, and exclusive forwarding ownership remain valid. +- Bound forwarding expiry and route withdrawal during failure, including API outages and stalled providers. +- Recover owned resources without disrupting workloads or other services. + +### Non-Goals + +- Define public customer APIs, enrollment experiences, or client software. +- Specify a transport protocol, credential format, prefix size, or session migration mechanism. +- Replace Galactic's routing control plane or build a general networking plugin marketplace. +- Migrate every existing gateway or NAT service into the framework. +- Define concrete schemas, RPC methods, kernel objects, or deployment manifests. + +## Proposal + +Introduce Galactic Edge as the trusted intermediary between service providers and gVPC networking. Its first contract supports isolated packet attachments and authorized prefix reachability. Additional capabilities should be added only when a concrete consumer requires them. + +### System context — C4 level 1 + +The framework is the system of interest. Providers and existing Galactic networking are separate systems with explicit responsibilities. + +```mermaid +C4Context + title Galactic Edge - system context + Person(operator, "Platform operator", "Configures provider access and observes attachment health") + System_Ext(client, "External network or client", "Exchanges tenant traffic through a provider") + System_Ext(provider, "Connectivity provider", "Owns its external protocol and client sessions") + System(edge, "Galactic Edge", "Authorizes and manages isolated VPC attachments and prefix reachability") + System_Ext(authority, "Platform authority", "Supplies trusted provider identity, VPC grants, and policy") + System_Ext(vpc, "Galactic VPC networking", "Routes traffic to and from tenant workloads") + Rel(operator, authority, "Configures grants and policy") + Rel(operator, edge, "Observes lifecycle and failures") + BiRel(client, provider, "Service-specific traffic") + Rel(provider, edge, "Requests attachment and prefix reachability") + Rel(edge, authority, "Validates authority and reads policy") + BiRel(edge, vpc, "Exchanges tenant traffic and manages reachability") +``` + +### Core concepts + +| Concept | Meaning | +| ------------------- | --------------------------------------------------------------------------------------------------------------------- | +| Provider | An authenticated service integration; its running instances own protocol-specific sessions. | +| Grant | Trusted authorization for a provider to use a particular gVPC and specified prefixes, within a validity period. | +| Attachment | An isolated connection between a provider instance and one gVPC, with policy and lifecycle managed by the foundation. | +| Forwarding claim | Time-bounded, exclusive authority for an instance to forward for a particular grant. | +| Prefix reachability | The routes that direct traffic for an authorized prefix to its current forwarding owner. | + +A grant can outlive an individual connection. An attachment can exist while forwarding is disabled. A retained prefix does not imply that a route remains advertised. Keeping these lifetimes separate allows reconnects and recovery without leaving stale forwarding authority behind. + +### Representative provider + +Consider a service that connects an external site to a tenant's VPC. It establishes a session with that site and carries packets for an authorized site prefix. The protocol and prefix length are immaterial to this example. + +The provider requests an attachment for the tenant and reachability for the prefix. Galactic Edge verifies the grant, prepares the isolated connection, and enables forwarding and routing only when their prerequisites hold. Return traffic follows the published prefix to the attachment; the provider delivers it to the external site. + +A second service using a different protocol follows the same lifecycle. This is the reuse requirement in [#992](https://github.com/datum-cloud/galactic/issues/992), illustrated through an abstract provider. The [MASQUE proposal (#970)](https://github.com/datum-cloud/galactic/issues/970) is one potential consumer; its transport requirements are outside this design. + +### Risks and Mitigations + +| Risk | Architectural response | +| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | +| A provider requests another tenant's resources | Validate trusted grants; provider-supplied identities and prefixes are requests, not authorization. | +| An old instance continues forwarding after replacement | Independently enforce local expiry and require fencing before replacement activation. | +| Cleanup removes a replacement's resources | Bind every mutation to immutable ownership identity and the current ownership generation. | +| A provider exhausts shared capacity | Bound attachments, prefixes, requests, and buffering; reject excess work before allocation. | +| The framework accumulates service-specific behavior | Prove integration with an independent provider against unchanged core artifacts. | + +## Design Details + +### Runtime boundaries — C4 level 2 + +The diagram separates the provider runtime, trusted foundation runtime, authoritative state, and existing routing and forwarding systems. The foundation's control and local enforcement responsibilities may require separate processes; their packaging is a contract-design decision. + +```mermaid +C4Container + title Galactic Edge - runtime boundaries + System_Ext(authority, "Platform authority", "Provider identity, grants, and VPC policy") + Container_Ext(provider, "Provider runtime", "Service process", "External protocol and client sessions") + System_Boundary(edge, "Galactic Edge") { + Container(control, "Foundation control", "Trusted control runtime", "Admission, attachment lifecycle, ownership, and route intent") + Container(local, "Local enforcement", "Trusted node runtime and datapath", "Isolated attachment, policy, and independent forwarding expiry") + } + ContainerDb_Ext(state, "Authoritative state", "Platform control plane", "Grants, ownership, and desired lifecycle state") + Container_Ext(router, "Galactic routing", "Existing routing control plane", "Publishes and withdraws VPC reachability") + Container_Ext(datapath, "VPC forwarding", "Existing Galactic datapath", "Carries isolated tenant traffic to and from workloads") + Rel(control, authority, "Validates grants and obtains policy") + Rel(provider, control, "Requests attachment, renewal, and release") + Rel(control, state, "Coordinates exclusive ownership and desired state") + Rel(control, local, "Reconciles authorized attachment and deadlines") + Rel(control, router, "Requests owner-scoped route publication") + Rel(local, router, "Invalidates local reachability on expiry") + BiRel(provider, local, "Exchanges packets through its attachment") + BiRel(local, datapath, "Exchanges policy-checked tenant traffic") +``` + +The state boundary is logical: this proposal does not require a new database. Likewise, Galactic Edge reuses the existing routing system rather than introducing another BGP implementation. Local withdrawal must have an API-independent enforcement path; writing desired state to an unavailable API is insufficient. + +### Responsibility split + +The provider authenticates its clients, implements its external protocol, checks session-specific packet ownership, and handles connection recovery. It cannot expand its VPC or prefix authority by asserting a client identity. + +The foundation authenticates the provider and validates grants against trusted authority. It owns shared attachment resources, enforces gVPC policy in both directions, constrains traffic to the admitted tenant and prefix scope, and coordinates forwarding claims and routes. Provider checks can narrow access; they cannot replace foundation enforcement. + +Existing Galactic components continue to own their routing and forwarding subsystems. Their reconciliation, repair, refresh, and garbage collection must respect foundation resource ownership. A provider receives access only to its attachment, never unrestricted control of shared routes or host networking. + +### The provider contract + +The contract needs a small set of capabilities: request an attachment, request reachability for granted prefixes, observe readiness and failures, renew forwarding authority, and drain or release resources. It must define compatible versions and reject unsupported capabilities before provisioning. + +Requests are scoped to immutable provider-instance and tenant identities. Retries are idempotent. Readiness reflects installed attachment and policy state, valid ownership, and local route programming; it does not promise that every remote router has converged. + +A provider may serve multiple tenants, but every packet enters through an explicit tenant attachment. Identical addresses in separate VPCs remain independent. Conflicting prefix ownership within one VPC is rejected. + +### Attachment activation + +Preparation starts with forwarding closed. A claim alone is insufficient: local enforcement must be installed, the provider must be ready to receive traffic, and any previous owner must already be fenced. + +```mermaid +sequenceDiagram + participant P as Provider + participant F as Foundation control + participant A as Authority and ownership state + participant L as Local enforcement + participant R as Galactic routing + P->>F: Request VPC attachment and granted prefix + F->>A: Verify identity, grant, and prefix authority + A-->>F: Authorized scope and validity ceiling + F->>A: Acquire exclusive forwarding claim + A-->>F: Ownership generation and deadline + F->>L: Prepare isolated attachment and policy, forwarding closed + L-->>F: Attachment prepared + F-->>P: Attachment available for preparation + P->>F: Ready to receive traffic + F->>L: Activate within current authority and deadline + L-->>F: Forwarding enforcement active + F->>R: Publish prefix for this owner + R-->>F: Local route contribution programmed + F-->>P: Ready, remote convergence proceeds separately +``` + +Every step rechecks the authority relevant to its mutation. Failed or partial activation remains unready and is reconciled or cleaned up. Work completed under expired authority cannot later become active through a delayed retry. + +### Failure and ownership replacement + +Forwarding authority expires independently of provider cooperation and API availability. The local forwarding gate must stop traffic even if the provider or its control loop stalls. Renewal cannot extend authority beyond the grant's validity ceiling. + +Replacement waits until the old owner cannot forward, using confirmed fencing or a safely elapsed enforcement deadline under the defined clock assumptions. An unreachable owner is not proof of a fenced owner. A temporary outage is preferable to two active owners for the same grant. + +```mermaid +sequenceDiagram + participant Old as Old provider + participant L as Old node enforcement + participant A as Authority and ownership state + participant New as Replacement foundation + participant R as Galactic routing + Note over Old,A: API connectivity is lost while packet connectivity remains + Old--xA: Renewal fails + New->>A: Request replacement ownership + A-->>New: Previous authority may still be live, activation blocked + L->>L: Enforced deadline expires, stop forwarding + L->>R: Withdraw old owner's local route contribution + Note over A,New: Confirm fencing or establish safe expiry under clock assumptions + New->>A: Acquire next ownership generation + A-->>New: Replacement authority granted + New->>New: Prepare attachment and enforce new authority + New->>R: Publish replacement reachability + Note over L,R: Late old-owner cleanup cannot remove the replacement route +``` + +The sequence shows required ordering, not a chosen lease algorithm. Numeric forwarding-expiry, revocation, and local-withdrawal bounds, including their clock and failure assumptions, are set in the [provider contract](../edge/provider-contract.md#timing-and-failure-bounds). Remote route convergence is measured separately. Stale remote routes may cause packet loss, but must not restore expired local forwarding authority. + +On restart, cached state is evidence for reconciliation, not permission to resume forwarding. Revalidate authority before reopening the attachment. + +### Drain, cleanup, and policy updates + +Drain stops new admissions and lets the provider finish existing work within a bounded window. Final release closes forwarding, withdraws the owner's reachability, and removes its attachment resources. Prefix retention follows the grant's lifecycle rather than the session's lifecycle. + +Recovery and cleanup use the same ownership rules as normal operations. They must preserve replacement routes, other providers' attachments, and shared VPC resources still in use. + +Policy changes apply to active attachments. Missing or invalid required policy keeps affected forwarding closed, with explicitly permitted control traffic preserved. Revocation shortens authority; it does not wait indefinitely for a provider to acknowledge it. During disconnection, previously granted authority can last only until its independently enforced deadline. + +## Production Readiness Review Questionnaire + +This provisional draft records the readiness expectations. Measurements and mechanism-specific answers are required before the design becomes implementable. + +### Feature Enablement and Rollback + +Enable the foundation and each provider explicitly. Existing services retain their current behavior. Disable by stopping admission, draining or fencing active owners, withdrawing routes, and cleaning up owned resources. Removing a deployment alone is not a complete rollback procedure. + +### Rollout, Upgrade and Rollback Planning + +Qualify an independent provider against fixed core artifacts on the target Talos/Cilium environment. Test overlapping tenants, unauthorized requests, policy changes, partial setup, provider crash and pause, API isolation, restart, cross-node replacement, and delayed cleanup. Capture packet evidence and failure timings. Upgrade and rollback must preserve the same ownership rules and reject incompatible contracts before activation. + +### Monitoring Requirements + +Expose admission failures, attachment readiness, active ownership and expiry, policy drops, route publication and withdrawal, resource use, and cleanup failures. Operators should be able to distinguish an unauthorized request, an unready attachment, expired ownership, and routing convergence without inspecting the provider's protocol internals. + +### Dependencies + +The foundation depends on trusted identity and grant state, gVPC policy, existing Galactic routing and forwarding, and supported node networking. Authority outages prevent new ownership and renewals; existing forwarding ends at its enforced deadline. Routing outages can delay remote reachability but cannot extend forwarding authority. + +### Scalability + +Set and test limits for providers, attachments, claims, prefixes, reconciliation work, and packet resources. Measure steady-state operation and renewal or reconnect bursts. No capacity or throughput target is claimed by this draft. + +### Troubleshooting + +Report lifecycle state and the reason progress stopped, correlated by provider, attachment, grant, and ownership generation. Measure local forwarding cutoff, local route withdrawal, and remote convergence separately. Avoid one health indicator that hides these distinct failure domains. + +## Implementation History + +- 2026-10-22: Initial architecture enhancement drafted, based on [#992 and its milestones](https://github.com/datum-cloud/galactic/issues/992). No implementation or qualification results are claimed here. + +## Drawbacks + +The shared foundation becomes a dependency for every adopting provider. Its contract needs careful evolution, and its privileged scope requires strong isolation tests. Exclusive ownership also introduces an intentional gap in availability when safe replacement requires waiting for expiry. + +## Alternatives + +**Each service owns its networking.** This permits independent development but duplicates authorization, resource recovery, and fencing. It also creates multiple writers to shared networking state. + +**Share a helper library only.** A library can reduce duplicate code, but does not by itself establish a trusted owner for shared resources or enforce expiry when its caller stalls. Libraries may support the foundation internally. + +**Build one service containing every protocol.** This centralizes ownership but couples protocol releases and failures. Independent providers preserve a smaller common framework and separate service lifecycles. diff --git a/docs/designs/interface-traffic-policy.md b/docs/designs/interface-traffic-policy.md new file mode 100644 index 000000000..507df9eef --- /dev/null +++ b/docs/designs/interface-traffic-policy.md @@ -0,0 +1,842 @@ +# Interface traffic policy + +Status: implemented design with deployment-dependent rollout. The API, controller, node reconciler and datapath exist. Use the [rollout guide](../traffic-policy/rollout.md) for enabling enforcement. The delivery sequence below records the original implementation plan, not outstanding work or a claim about current production settings. + +- [Summary](#summary) +- [Motivation](#motivation) + - [Goals](#goals) + - [Non-goals](#non-goals) +- [Proposal](#proposal) + - [Fixed requirements](#fixed-requirements) + - [Risks and mitigations](#risks-and-mitigations) +- [Design details](#design-details) + - [API ownership](#api-ownership) + - [Resource model](#resource-model) + - [Rule language](#rule-language) + - [Admission and explicit null](#admission-and-explicit-null) + - [Default policy identity](#default-policy-identity) + - [Binding transitions](#binding-transitions) + - [Forwarding path classification](#forwarding-path-classification) + - [Packet path audit](#packet-path-audit) + - [Parser contract](#parser-contract) + - [Link operation exceptions](#link-operation-exceptions) + - [BPF maps](#bpf-maps) + - [Publication and lifetime](#publication-and-lifetime) + - [Lifecycle activation and continuity](#lifecycle-activation-and-continuity) + - [Reconciliation and status](#reconciliation-and-status) + - [Metrics](#metrics) + - [Kernel requirements](#kernel-requirements) +- [Rollout](#rollout) +- [Delivery plan](#delivery-plan) + - [Pull request sequence](#pull-request-sequence) + - [Requirement checklist](#requirement-checklist) +- [Alternatives](#alternatives) + +## Summary + +A TrafficPolicy is an ordered list of Allow and Deny rules. Each VPC interface +binds one policy for traffic the workload receives (ingress) and, separately, +one for traffic the workload sends (egress). The CNI BPF datapath evaluates the +bound policy on every packet in that direction. An interface with no binding in +a direction uses a built-in policy whose only rule denies everything. + +Policies are stateless. Allowing a request never allows its reply; the reply +needs its own rule in its own direction. + +## Motivation + +Every tenant interface today forwards whatever its VPC routes allow. A workload +that should only serve one private port can also reach the internet through a +NAT shard, and a workload that should only make outbound calls can receive +anything routed to it. Operators have no per-interface control and no record +of what was denied. + +### Goals + +- Give each interface independent ingress and egress policies. +- Deny by default, including while an interface is being created and while the + control plane is unavailable. +- Let rules match the forwarding path (private VPC routing, a NAT shard, or a + public service), the IP family, exact addresses or prefixes, the protocol, + ports and ICMP type and code. +- Apply updates to running interfaces without restarting workloads. +- Count every packet against the rule that decided it. + +### Non-goals + +- Connection tracking or any implicit reply allowance. +- Policy attached to a whole VPC, VRF or namespace. +- Tiered precedence, merging of several policies, or deny-overrides-allow. +- SMTP or any other port-specific platform rule. +- Application-layer, DNS-name or rate-based matching. +- Provisioning NAT, VIPs or services. An Allow only permits use of forwarding + that already exists. +- Interoperability with Kubernetes NetworkPolicy or with BGPPolicy, which is + route-advertisement policy. + +## Proposal + +### Fixed requirements + +These come from the product brief and are not open to redesign here. + +| ID | Requirement | +| --- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| R1 | Policy applies to one VPC interface. Two interfaces in one VPC and VRF can differ. | +| R2 | Each interface has an independent ingress policy and egress policy, named by the workload's direction. | +| R3 | Neither direction creates permissions in the other. No connection tracking or synthesized replies. | +| R4 | The default policy has exactly one rule, deny all, and applies to any direction without a binding. | +| R5 | Rules are ordered Allow and Deny. First match wins. No match denies. | +| R6 | Rules match path, protocol, optional source and destination addresses or prefixes, and ports. NAT access is an ordinary path match. | +| R7 | Updates apply to existing interfaces without recreation, and one direction's update never changes the other. | +| R8 | Missing enforcement state never allows. Failed same-identity updates keep the last good policy. Rebinding and deletion never keep old grants. | + +### Risks and mitigations + +| Risk | Mitigation | +| ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Default deny breaks every running workload on rollout | Enforcement is off per node until an explicit enable, and operators bind policies first (see [Rollout](#rollout)). | +| A path is misclassified and a narrow Allow matches the wrong traffic | Classification uses only trusted forwarding state. Any lookup that cannot finish is `classification_error`, which denies at the first rule naming a path that the packet otherwise matches. | +| A packet reaches a workload by a path that skips the check | The [packet path audit](#packet-path-audit) names the check for every delivery mechanism, and the integration tests send traffic down each one. | +| Counter rows are reused while a packet still counts into them | Rows are freed only after the outer-map update returns, which the kernel guarantees waits for every program that could hold the old snapshot (see [Publication and lifetime](#publication-and-lifetime)). | +| Verifier cost and stack depth of the evaluation | Evaluation is a separately verified global function that walks the snapshot with `bpf_for_each_map_elem`, so its cost does not grow with the rule count; the existing verifier budget test covers it. | +| Dropping every fragment breaks workloads that rely on them, such as large UDP DNS answers | `audit` mode counts would-be fragment drops per interface before a site enforces, and the user guide calls the change out. | + +## Design details + +### API ownership + +The cloud and network API types now live in `api/cloud/v1alpha1` and +`api/network/v1alpha1` of the Galactic module. All of these types use +`galactic.datumapis.com/v1alpha1`. TrafficPolicy and TrafficPolicyBinding +remain in `api/v1alpha1` under the same group. + +VPC and VPCAttachment are owned by the Galactic cell controller, which writes both the +spec and the status of every VPCAttachment. The node controller does not write either. +Bindings are therefore a separate Galactic kind rather than new fields on +VPCAttachment. + +One VPCAttachment describes exactly one interface: its `spec.interface` is a +single object, and the cloud operator creates one VPCAttachment, and one +NetworkAttachmentDefinition of the same name, per NetworkInterface. The +attachment's namespace, name and UID identify an interface lifetime. An +ifindex is a node-local detail and never appears in the API. + +### Resource model + +Both kinds are namespaced. References are local names, so a policy is always +in the binding's namespace and there is no field that could name another +tenant's policy. + +```yaml +apiVersion: galactic.datumapis.com/v1alpha1 +kind: TrafficPolicy +metadata: + name: public-web-egress + namespace: tenant-a +spec: + rules: + - name: https-through-nat + action: Allow + match: + path: PublicNAT + protocol: TCP + destinationPorts: + - start: 443 + end: 443 + - name: deny-all + action: Deny +``` + +```yaml +apiVersion: galactic.datumapis.com/v1alpha1 +kind: TrafficPolicyBinding +metadata: + name: web-0-eth0 # the VPCAttachment's name + namespace: tenant-a +spec: + ingressPolicyRef: + name: private-web-ingress + egressPolicyRef: + name: public-web-egress +status: + observedGeneration: 3 + ingress: + policy: {name: private-web-ingress, uid: 6d1c...} + conditions: [...] # Resolved, Applied + egress: + policy: {name: public-web-egress, uid: 91fa...} + conditions: [...] + nodes: + - node: dfw-compute-3 + ingress: + policy: {name: private-web-ingress, uid: 6d1c..., generation: 4} + state: Applied # Applied, Pending or Failed + observedGeneration: 3 # the binding generation applied + lastTransitionTime: ... + egress: + policy: {name: public-web-egress, uid: 91fa..., generation: 2} + state: Applied +``` + +- The binding has no attachment field: it applies to the VPCAttachment with + its namespace and name. That makes "one binding per interface" a property + of naming rather than a conflict to detect, so there is exactly one + effective policy per interface and direction. +- Omitting a reference selects the built-in default for that direction only. + Removing a reference restores the default for that direction only. +- A binding for an attachment that does not exist yet is accepted and waits. + An attachment without a binding is denied in both directions. +- `status.ingress` and `status.egress` report the resolved policy identity and + a `Resolved` condition. `status.nodes` reports what each node applied, + separately from what the API asked for. Admission success is never reported + as convergence. + +### Rule language + +| Field | Type | Meaning | +| --------------------------------------------- | ----------------------------------------- | ----------------------------------------------------------------------- | +| `name` | DNS label, unique in the policy | Diagnostic and metric identity | +| `action` | `Allow` or `Deny` | Deny drops; no ICMP is synthesized | +| `match` | object, optional | All present fields are ANDed; absent means a catch-all | +| `match.path` | `Private`, `PublicNAT` or `PublicService` | Absent means any path | +| `match.ipFamily` | `IPv4` or `IPv6` | Absent means both | +| `match.protocol` | `TCP`, `UDP`, `ICMP` or `ICMPv6` | Absent means any IP protocol, allowed only without ports or ICMP fields | +| `match.sourceIPs`, `match.destinationIPs` | 1 to 64 literal addresses, a set | Exact /32 or /128 | +| `match.sourceCIDRs`, `match.destinationCIDRs` | 1 to 64 prefixes, a set | Network address must have no host bits | +| `match.sourcePorts`, `match.destinationPorts` | 1 to 16 `{start, end}` ranges | Inclusive, 0 to 65535, TCP or UDP only, no overlap | +| `match.icmp` | `{type, code?}` | ICMP or ICMPv6 only | + +- Entries within one list are alternatives (OR). Different fields are ANDed. +- `sourceIPs` and `sourceCIDRs` are mutually exclusive, as are + `destinationIPs` and `destinationCIDRs`. An IP list on one side with a CIDR + list on the other is allowed. Several exact addresses and prefixes on one + side need separate ordered rules. +- Source always means the packet's source and destination the packet's + destination, in both directions. +- Every address and prefix must match `ipFamily` when it is set, and ICMP + requires IPv4 while ICMPv6 requires IPv6. With no family set, a list may mix + families, and a packet can only match entries of its own family. A rule never + matches one side as IPv4 and the other as IPv6. +- An IPv4-mapped IPv6 literal (`::ffff:192.0.2.1`) is rejected, as the + Kubernetes IP validation library does. It is never unmapped into an IPv4 + match. +- IPv6 literals are canonicalized (RFC 5952) before the webhook's duplicate + check. Zone + identifiers, hostnames, `host:port` and prefix notation in an IP list are + rejected. +- Absent means wildcard. An empty list and an explicit `null` are rejected. +- A policy holds at most 64 rules and compiles to at most 256 datapath entries. + A rule compiles to the product of its source, destination and port + alternatives, so the compiler counts entries and rejects a policy over the + limit rather than truncating it. Rules are never reordered. +- A rule fully shadowed by an earlier rule is reported as a warning, not an + error. +- Addresses and ports are stored in network byte order in the datapath. Ranges + are compared after converting the packet's port to host order. + +NAT64 is matched as the workload sees it. On egress, a packet to a synthesized +`64:ff9b::/96` address is IPv6, so an IPv4 literal does not match it. On +ingress, the reply reaches the workload as IPv6 from the synthesized address +and is matched as that. Outer SRv6 addresses and a shard's public masquerade +address are never substituted into these fields. + +### Admission and explicit null + +An experiment against kube-apiserver 1.33 established how the CRD pipeline +treats `null`: + +- On a field without `nullable: true`, an explicit `null` is pruned before + validation and stored as if omitted, so nothing can reject it. +- On a field with `nullable: true`, the `null` is stored. CRD CEL cannot see + it: `has()` reports false for a null field, and a typed comparison with + `null` does not compile. +- A JSON merge patch that sets a field to `null` removes the field, which is + an intentional change to omission. + +So every optional match field, and `match` itself, is declared +`nullable: true`, and a fail-closed validating webhook (`failurePolicy: Fail`) +rejects a `null` at any of them by inspecting the admitted object. The enum +fields (`path`, `ipFamily`, `protocol`) need no webhook check: the schema's +enum already rejects a null there. Everything CRD validation can express +(enums, bounds, list types, mutual exclusion, family consistency) stays in the +schema as well, so it holds even for clients that bypass the webhook's checks. +While the webhook is down, writes fail rather than admit a null. + +The CEL IP and CIDR functions the schema uses need Kubernetes 1.31 or later; +the schema is tested on 1.33 and 1.35, and edge clusters run 1.35. + +The webhook also parses every address and prefix again, since the schema only +checks strings, and enforces the reserved default name (next section). + +### Default policy identity + +The built-in default is named `default-deny-all` with one rule, `deny-all`, +action `Deny`. It is authoritative for every omitted reference and never needs +an API object. Its metric `policy_uid` is the reserved string +`builtin:default-deny-all:v1`, which is never a Kubernetes UID. + +`galactic-controller --role=cell` also provisions a TrafficPolicy named +`default-deny-all` in each namespace that holds a VPCAttachment, so it can be +referenced explicitly. The webhook reserves that name: only the controller's +service account can create or delete it, and its spec must be exactly the one +catch-all Deny rule. If a conflicting object already exists the controller +reports a provisioning conflict on its own status, never adopts or overwrites +it, and omitted references keep using the built-in default. An explicit +reference to a conflicting object is unresolved and denied. + +An explicit reference to the controller-owned object follows the ordinary +reference rules and reports the object's real UID. An omitted reference always +reports the synthetic identity, even while the object exists. Deleting the +object therefore changes nothing for omitted references and makes explicit +references unresolved. + +### Binding transitions + +Policy identity is the namespace plus the policy's API UID. Each interface and +direction moves independently. + +| Event | Enforcement | Status | +| ------------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------- | +| New interface, binding not yet resolved | Deny, `policy_unavailable` | Pending | +| Reference omitted or removed | Publish the built-in default | Default applied | +| Valid update to the bound UID | Old snapshot until the new one is fully published | Desired and applied generations reported separately | +| Admission rejects an update | Unchanged | Error returned to the writer | +| Accepted update to the same UID fails to compile or install | Keep last good, or deny if there is none | Installation failure with both generations; retried | +| Rebind to another UID | Publish the new policy if it is ready, otherwise invalidate and deny | Pending or failed; never restores old grants | +| Referenced policy confirmed deleted, including same-name recreation | Invalidate and deny until the new UID is installed | Unresolved, or pending for the new UID | +| API outage or cache not synced | Keep what is installed; new bindings stay denied | Stale discovery reported | +| Installed state lost | Deny | Repaired, or the interface is quarantined | + +Absence is established only by a synchronized informer or an authoritative +read. A timeout never counts as deletion. + +Invalidation never depends on allocating anything. It deletes the binding's +outer-map entry, which makes the next evaluation deny with +`policy_unavailable`. If even that delete fails, the node agent sets the +interface's host link down (quarantine) and reports the failure. + +### Forwarding path classification + +| Path | Egress (workload sends) | Ingress (workload receives) | +| ------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| Private | Private VPC routing, same-node delivery, private services, kernel VRF fallback | Ordinary decapsulation, private service tunnel (next header 253), same-node delivery | +| PublicNAT | A shard group sentinel, or a route whose SID is a NAT shard's | Decapsulated packet whose outer source is a NAT shard's SID | +| PublicService | Source VIP translation toward the public uplink (DSR reply) | Gateway delivery (nonzero uSID slot) or inbound VIP translation | + +Classification uses forwarding state only, never whether an address looks +public. + +- **Egress.** The class comes from the same `egress_route_table` value the + forwarding decision uses, in the same lookup, so a route rewritten in place + can never be seen with a stale class: + - a group sentinel (`link_ifindex == 0xFFFFFFFF`) is PublicNAT; + - a route whose SID's top 64 bits are in `tp_nat_locator_table` is + PublicNAT; + - a local pass-through entry and every other route are Private. + + `tp_nat_locator_table` has one writer, the installer. It holds the locator of + every configured shard SID (`GALACTIC_CNI_EGRESS_SHARD_SIDS`) and every + EgressShard it has ever seen. Entries are only ever added while the agent + runs, because the EgressShard controller already keeps shard locators + disjoint from every BGPRouter locator, so a retained entry can never + reclassify private traffic. A restart rebuilds the set before setting the + synced flag in `tp_state`. Until the flag is set, an encapsulating egress + route is `classification_error`. +- **Ingress, NAT.** The outer source of a NAT shard's reply is the shard's + SID, so the same table classifies it. Until the flag is set, an + encapsulated ingress packet is `classification_error`. +- **Trust.** Sender authenticity rests on the existing fabric trust model: + `usid_ingress` already accepts any packet addressed to a local locator from + the fabric uplink. A tenant cannot choose the outer header, because every + tenant packet is encapsulated by the sending node's `usid_egress`, and a + tenant packet that carries its own SRv6 header is encapsulated inside one. + Nothing a tenant controls (inner addresses, ports, marks or its own SRH) + selects a class. +- **Errors.** A rule with no `path` is evaluated normally when classification + failed, and so is a rule with a `path` whose other fields do not match, + since it could not decide the packet on any path. The first rule with a + `path` whose other fields all match ends evaluation with a + `classification_error` deny, so a failed lookup can never skip an earlier + rule and reach a broader Allow. + +### Packet path audit + +**Interfaces.** `tp_iface_table` holds a row for every interface a Galactic +program can deliver to or is attached to, with a kind: + +- `tenant`: a VPCAttachment interface. Policy applies. +- `infra`: the ingress sidecar's synthetic veth peers. They belong to the + platform, carry no tenant identity, and are never evaluated; traffic they + pass on to a tenant interface is checked at that interface. + +A program that finds no row for an interface it is attached to, or that +`usid_ingress` is about to deliver to, denies as `policy_unavailable` +(unattributed). Missing state is never read as "unmanaged". + +**Hooks on a tenant interface**, with `P` the configured filter priority: + +| Hook | Program | Role | +| ------------------------------------- | --------------------- | ------------------------------------------------------------------------ | +| Host-side tc ingress, priority P | `usid_service_egress` | Private service requests and replies | +| Host-side tc ingress, priority P+1 | `usid_egress` | Everything else the workload sends | +| Host-side tc egress, priority P (new) | `tp_deliver` | Workload ingress for packets the kernel or a non-peer redirect transmits | +| Fabric uplink tc ingress | `usid_ingress` | Decapsulation and delivery | + +**Egress tuple.** The packet's addresses, protocol and ports are captured +once, at the top of the first program that sees the packet and before any +NPTv6 or VIP rewrite, so `sourceIPs` and `sourceCIDRs` always see the +workload's own address. The check itself runs at the exit, where the class is +known, using that captured tuple. It runs before `send_too_big`, so a denied +packet never produces a Packet Too Big quoting it, and exactly once per packet +even where the VIP path falls through to the route logic. + +**Every exit of the egress programs:** + +| Exit | Today | With policy | +| -------------------------------------------------------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bpf_skb_pull_data` fails | `UNSPEC` to the kernel | Evaluate as Private: the capture reads with `bpf_skb_load_bytes`, which needs no pull, so a packet it cannot parse is a `parse_error` drop and one it can is decided by the rules | +| Not IPv4, IPv6 or ARP | `UNSPEC` | Link drop | +| ARP | `UNSPEC` | Link-operation allowlist, otherwise link drop | +| `ifindex_vrf_table`, `vrf_table` or scratch miss | `UNSPEC` | `policy_unavailable` drop when the tenant row is also missing; otherwise evaluate as Private and return `UNSPEC` | +| Short IPv4 or IPv6 header | `UNSPEC` | `parse_error` drop | +| VIP source rewrite and redirect to the uplink | Forwarded | Evaluate as PublicService first | +| VIP rewrite with no uplink configured | Falls through to the route logic | Evaluated once, at the route exit, with the route's class | +| Multicast or link-local destination | `UNSPEC` | Evaluate as Private | +| Neighbor discovery (133 to 137) | `UNSPEC` | Link-operation allowlist; otherwise evaluate as Private | +| Route miss | `UNSPEC` | Evaluate as Private | +| Local pass-through route | `UNSPEC` | Evaluate as Private | +| No node source address configured | `UNSPEC` | Evaluate with the route's class, then `UNSPEC` | +| Group sentinel | Resolved, then encapsulated | Evaluate as PublicNAT before the group is resolved, so a denied packet moves no pin | +| Group sentinel, resolution failed after an Allow | Drop | Drop, counted under its existing reason after the Allow's rule hit, like any later forwarding failure | +| Remote route | Encapsulated | Evaluate with the route's class | +| `usid_service_egress` parse failure or non-IP | `UNSPEC` to `usid_egress` | Handled by `usid_egress` | +| `usid_service_egress` non-TCP/UDP, or a service-route miss without a deny marker | `UNSPEC` to `usid_egress` | Handled by `usid_egress` | +| Service request or reply, local or remote | Rewritten and redirected | Evaluate as Private before the rewrite | +| Service deny marker or service policy denial | Drop | Unchanged; the service policy's own drop, counted by it | + +A packet that service policy drops has no traffic-policy outcome: the +private service checks run first, and traffic policy decides only a request or +reply they authorized, on the tuple captured before any rewrite. That is a +different policy's decision, already counted under its own reason. + +**Workload ingress:** + +| Mechanism | Where it is enforced | Path | +| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | --------------------- | +| Remote delivery to a veth by `bpf_redirect_peer` | `usid_ingress`, after the FIB names the interface and before the redirect | From the outer header | +| Remote delivery to a tap by `bpf_redirect`, or to a cold neighbor by `bpf_redirect_neigh` | `usid_ingress`, as above, which then marks the packet evaluated | From the outer header | +| Same-node delivery through the kernel VRF | `tp_deliver` on the receiver's host interface | Private | +| Local private service delivery by `bpf_redirect_neigh` | `tp_deliver` | Private | +| Packet Too Big that `usid_egress` sends back to the workload | `tp_deliver` | Private | +| Host-generated traffic, such as kernel ICMP errors | `tp_deliver` | Private | +| Delivery from the ingress sidecar | `tp_deliver` | Private | + +- `bpf_redirect_peer` moves the packet into the peer namespace without running + the host device's tc egress, so `usid_ingress` must check before the + redirect. Plain `bpf_redirect` and `bpf_redirect_neigh` transmit through the + host device, so `tp_deliver` would see the same packet again. +- To check it once, `usid_ingress` sets a reserved mark value on the packets it + has evaluated and sends by those two helpers. `tp_deliver` skips a packet + that carries exactly that value and clears it. A workload cannot set it: a + normal veth transmit between namespaces clears the mark, and a tap delivers + with mark 0. A host component that uses the same mark value would collide, + so the value is configurable (`GALACTIC_CNI_POLICY_MARK`) and the rollout + guide has operators check it against the node's netfilter and routing + rules. +- Kubelet probes reach a pod through its primary network, not a Galactic + interface, so they never meet `tp_deliver`. +- Deny is a real `TC_ACT_SHOT` before any fallback. A missing route is never + used to mean deny. + +### Parser contract + +| Packet | Behavior | +| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| Well-formed IPv4 or IPv6 | Evaluate the rules | +| IPv4 with MF set or a nonzero offset; IPv6 with any Fragment header, including an atomic fragment | `parse_error` drop before any rule | +| Truncated or malformed header, or a parser bound exceeded | `parse_error` drop before any rule | +| Validated ARP or neighbor discovery on the allowlist | Link operation, outside the rules and their metrics | +| Any other non-IP frame, or invalid ARP | Link drop, counted separately | +| GSO skb | The same parse on the observable skb, counted once at its buffer length; never requires a checksum hardware has not computed | + +Bounds and allowlists: + +- IPv4: version 4, IHL from 5 to 15, total length at least the header and no + more than the buffer. Options are skipped without interpretation; they never + move or hide the transport header. +- IPv6: payload length no more than the buffer. Extension headers on the + allowlist are Hop-by-Hop (0), Destination Options (60), and Routing (43) + only with segments left 0, at most 4 of them and 256 bytes in total. A + Routing header with segments left could be re-forwarded to a destination + other than the one evaluated, so it is `parse_error`. Fragment (44), AH + (51), Mobility (135), HIP (139), Shim6 (140) and the experimental values are + `parse_error`. ESP (50) and No Next Header (59) end the chain as a protocol + with no ports. +- TCP and UDP need the whole fixed header inside the IP packet. ICMP and + ICMPv6 need their first 4 bytes. +- Ethernet padding after the IP total length is excluded from the byte count. + +Dropping every fragment is a behavior change: today fragments are forwarded +(the service path only drops them by marker). It is listed under +[Risks and mitigations](#risks-and-mitigations). In `audit` mode a fragment +is counted as a `parse_error` that would have been dropped, and forwarded. + +### Link operation exceptions + +Only these frames bypass the rules, and only after validation. + +| Frame | Direction | Checks | +| ------------------------------------------------------------------------------------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ARP request or reply | Both | Ethernet/IPv4, hardware length 6, protocol length 4; on egress, the sender address is one of the interface's IPv4 addresses or 0.0.0.0, and the target is the gateway, the sender itself (gratuitous ARP) or one of the interface's addresses (an RFC 5227 probe) | +| Router Solicitation (133), Neighbor Solicitation (135), Neighbor Advertisement (136) | Egress | Hop limit 255, code 0, valid length, no extension headers; source is link-local, one of the interface's addresses, or unspecified for DAD; destination is link-local unicast, in `ff02::/16`, or the interface's gateway address | +| Router Advertisement (134), Neighbor Solicitation, Neighbor Advertisement | Ingress | Hop limit 255, code 0, valid length, no extension headers. The source is not checked: a hop limit of 255 already proves the message came from the link, and the host answers for the gateway from the gateway's own address | + +The destination check stops a workload from using a neighbor discovery type to +reach another tenant's routable address past its own egress policy. A message +the kernel forwarded has a hop limit below 255, so it fails the ingress check +and is evaluated as ordinary traffic. + +Everything else is ordinary tenant traffic: DNS, other ICMP, multicast and +link-local data. Galactic does not serve DHCP, so there is nothing to except. +Under default deny that includes Packet Too Big and other ICMP errors, so a +policy that allows TCP should usually allow ICMPv6 type 2 (and ICMP type 3 +code 4 for IPv4) toward the workload. The user guide says so. + +### BPF maps + +Every map is new, so no existing pinned map changes layout. + +| Map | Type | Key, value | Writer | +| -------------------------- | -------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------ | +| `tp_iface_table` | HASH | ifindex, `{policy_token, kind, state}` | CNI ADD and DEL, the sidecar installer, repair | +| `tp_iface_addr_table` | HASH | `{ifindex, family, address}`, nothing | CNI ADD and DEL, for the link-operation source checks | +| `tp_binding_table` | HASH_OF_MAPS | `{ifindex, direction}`, inner snapshot | galactic-router | +| inner snapshot | ARRAY, 257 entries | 0: header `{policy_token, counter_base, count}`; 1-256: compiled entries | galactic-router, before insertion | +| `tp_nat_locator_table` | HASH | shard Block and Node, nothing | Installer | +| `tp_rule_counters` | PERCPU_ARRAY, 16,384 | counter ID, `{packets, bytes}` | Datapath | +| `tp_fallback_counters` | PERCPU_HASH | `{ifindex, policy_token, direction, reason}`, `{packets, bytes}` | Rows created by CNI ADD; datapath updates existing rows only | +| `tp_unattributed_counters` | PERCPU_ARRAY | `{direction, reason}`, `{packets, bytes}` | Datapath | +| `tp_accounting_errors` | PERCPU_ARRAY | `{direction, action}`, count; the one reason is a missing rule counter | Datapath | +| `tp_link_drops` | PERCPU_ARRAY | direction, `{packets, bytes}` | Datapath | +| `tp_state` | ARRAY(1) | enforcement mode, NAT locator synced flag | Installer | + +A compiled entry is 88 bytes: action, logical rule index, match flags, family, +protocol, path, ICMP type and code, one source and one destination port range, +and the source and destination prefixes each with its mask. The masks are +computed in user space so matching is a branch-free masked compare: compared +bit length by bit length, the verifier explored every length and the +evaluation alone cost about 13,000 instructions; with masks the whole of +`usid_egress` verifies in about 12,500, against 9,700 before the policy hooks +and a budget of 20,000. Evaluation walks the snapshot with +`bpf_for_each_map_elem` (5.13), which iterates the inner array in index order +and stops at the first match. The logical rule index +plus the snapshot's `counter_base` gives the counter row, so every entry a +rule expands to adds to that rule's one row. + +**Policy token.** CNI ADD writes a random 64-bit `policy_token` into +`tp_iface_table` when it creates the interface, and nothing else changes it. +That is deliberately not the existing `attachment_identity_table` token, +which also rotates whenever programs are replaced. A snapshot header's token +must equal the interface row's token, so a recycled ifindex, whose row CNI ADD +rewrites, never inherits a previous interface's snapshot, while a program +upgrade leaves every binding valid. + +**Stack.** `usid_egress` is already close to the 512-byte stack limit, which +is why `send_too_big` and `clamp_tcp_mss` are global functions. `tp_capture` +and `tp_decide` are global functions too, and keep the packet tuple and the +walk's state in a per-CPU scratch map rather than on the stack. The kernel +refuses to load any program whose deepest call chain passes 512 bytes, and +every kernel test loads the full datapath, so a change that crosses it fails +in CI. + +### Publication and lifetime + +**Switching a direction.** + +1. Allocate counter rows and zero them, so every installed rule is visible + with zero hits. +2. Create a new inner map and write its header and entries. +3. Insert it with one update of `tp_binding_table[{ifindex, direction}]`. + +The two directions are separate keys, so neither update can overwrite the +other. + +**Holding a snapshot.** An evaluation does one lookup in the outer map and +uses the returned inner map for the rest of the run. tc programs are +non-sleepable and run inside an RCU read-side critical section, so a packet +evaluates against exactly one complete snapshot, old or new. + +**When the old snapshot is no longer in use.** An update or delete of a +map-in-map entry from user space calls `synchronize_rcu()` before the +syscall returns (`maybe_wait_bpf_programs()` in `kernel/bpf/syscall.c`, there +since Linux 4.20). The kernel added that wait precisely so user space would +know that every non-sleepable program that could have looked up the old inner +map has finished. So when the outer-map update returns, no program holds the +old snapshot or can write the counter rows only it referenced. + +**Retiring counters.** After the update returns, the agent frees the counter +IDs that only the old snapshot referenced. A user-space reference count or a +timer is never the evidence; the synchronous wait is. Releasing the old inner +map's memory is the kernel's business: since Linux 6.8 ("bpf: Defer the free +of inner map when necessary") it is freed only after the grace periods that +also cover sleepable programs, which closed a use-after-free in older +kernels. The publication tests race updates against packets and check that +no packet is ever counted in a row after its ID is freed. + +**Failure.** If the outer-map update fails, the old snapshot stays bound and +its counters stay live; the new inner map is closed and its rows freed. Live +storage is never reused. + +**Restart.** The outer map and the counter arrays are pinned. A restarted +agent rebuilds its allocator from the inner maps still referenced by the +outer map, and treats every counter row they do not reference as free. + +**Counter continuity.** Within one interface lifetime, a rule's counter row is +keyed by its name and action. A new snapshot that keeps both reuses the row, +whatever its match or position. Renaming the rule or changing its action +starts a new row. Unbinding, removing a rule or changing its action ends the +interval at publication. Returning later starts a new row at zero; a freed +row is zeroed before reuse and never revived with old counts. + +### Lifecycle activation and continuity + +The CNI chain is `galactic-veth` or `galactic-tap` (the master plugin, which +creates the interface and today brings both ends up), then `galactic-bgp` +(which registers the datapath and attaches `usid_service_egress` and +`usid_egress` through `attachreg.RegisterDatapath`). Activation follows that +order when the enforcement mode is `audit` or `enforce`: + +1. **Master plugin.** Create the interface, bring the workload side up, and + leave the host side down. Down keeps the workload's sent traffic, and any + delivery that transmits through the host device, from moving. +2. **`galactic-bgp`.** Write the `tp_iface_table` row (kind `tenant`, state + `pending`, a new `policy_token`) and the fallback counter rows; register + the datapath; attach `tp_deliver`; read every filter back to verify it. +3. **`galactic-bgp`.** Set the host side up and report success. With state + `pending` and no binding row, every packet in both directions is denied as + `policy_unavailable` until galactic-router publishes the built-in default + or the bound policy. + +A failure in step 2 or 3 leaves the host side down, rolls back only state +belonging to this interface lifetime, and fails the ADD. If the node has no +SRv6 locator, `RegisterDatapath` registers nothing today and succeeds; with +enforcement on, `galactic-bgp` fails the ADD instead, since nothing would +enforce policy. The tap plugin's repair path, which brings a down tap back +up, first checks that the interface's `tp_iface_table` row is active and its +filters are present. + +A down host link does not stop `bpf_redirect_peer` delivery, which only +checks the peer. Ingress to a veth is denied by the check inside +`usid_ingress`, which needs the binding row; a missing row denies there. So +there are two independent controls, used together: + +- **Missing map rows** are handled by the programs that are present, which + deny in both directions. +- **A missing tenant-interface program** is handled by the link being down: + repair in `galactic-cni run` sets the host side down before reattaching, + and up only after verification. `usid_ingress` lives on the uplink, not the + tenant interface, so it is unaffected. + +Other operations: + +- **CNI CHECK** reads the filters back as well as the map rows. A missing + filter fails the check. +- **Program upgrades** replace each filter in place with the same priority + and handle. `cls_bpf` swaps the program pointer atomically, so there is no + moment without a program. An upgrade never detaches first, and it never + changes a `policy_token`, so bindings stay valid. +- **Agent crash.** tc filters, pinned maps and a down link all survive a + crash. A restarted agent verifies identity, filters and map compatibility + before setting any link up. +- **Map loss.** If a policy map has to be recreated because its shape + changed, the loader removes the old pin only after every managed link has + been set down and every binding is gone. Repair restores state, then sets + the links up. +- **Last resort.** If the agent cannot publish an invalidation, it deletes the + outer-map row, which denies both directions; if that also fails it sets the + host link down, which stops egress and every non-peer delivery, and reports + the interface as quarantined. A node whose map operations fail entirely + cannot deny peer-redirect ingress; that is reported, not hidden. + +Continuity covers agent crashes, loader and upgrade failures, and controlled +map or program replacement. A privileged user removing filters or maps by hand +is outside this guarantee. + +In mode `off` none of these lifecycle changes apply: links come up as they do +today, CHECK ignores the new filter, and repair never sets a link down. The +`tp_iface_table` rows and filters are still written, so switching a node to +`audit` or `enforce` needs no interface recreation. + +Revocation applies to every packet evaluated after publication in that +direction, including packets of existing flows. NAT sessions, shard pins, +cached routes and service entries are not exemptions. A packet already +evaluating against the old snapshot finishes under it. + +### Reconciliation and status + +**galactic-controller (`--role=cell`)** owns the API side: + +- serves the validating webhook; +- provisions `default-deny-all`; +- resolves each binding's references and writes `status.ingress` and + `status.egress`; +- surfaces validation and compile errors on the TrafficPolicy status. + +**galactic-router** owns the node side, because it already watches +VPCAttachment and writes per-interface fail-closed maps. Its new +TrafficPolicyReconciler: + +- watches TrafficPolicy, TrafficPolicyBinding and VPCAttachment; +- maps each attachment whose `status.node` is this node to its host ifindex + and `policy_token`; +- compiles each direction, publishes and retires snapshots as above; +- reports the applied identity and generation in `status.nodes`. + +It reconciles on start, on every watch event, and every five minutes. After a +restart it adopts each snapshot whose token, policy UID and generation still +match, so counters continue; one no attachment claims within a resync is +unbound and its rows freed. galactic-cni removes the outer-map rows of +interfaces that no longer exist. It writes no status on VPCAttachment. It runs +only when `GALACTIC_ROUTER_TRAFFIC_POLICY` is set, because it watches CRDs a +cluster may not have installed. + +A diagnostic command, `galactic-router policy show /`, +prints both bindings, this node's status entry, the bound snapshots and each +rule's counters. `galactic-router policy explain` evaluates a packet tuple and +path against a policy file or a live policy with both the Go evaluator and the +compiled entries, fails if they disagree, and never touches live counters. + +### Metrics + +Exported from galactic-router's existing `:9179/metrics` endpoint, which +already has a PodMonitor. galactic-router allocates every counter row and +knows which rule, policy and interface it belongs to, so it is the one +process that can label a row without a second lookup table. The +`galactic_cni_` prefix names the datapath the counters belong to, not the +process that serves them. A row the collector cannot read is left out, not +reported as zero, and counted in the `galactic_cni_traffic_policy_counter_read_errors` +gauge. + +| Metric | Labels | +| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `galactic_cni_traffic_policy_rule_hits_total` | namespace, vpc, attachment, interface, interface_uid, direction, policy, policy_uid, rule, action | +| `galactic_cni_traffic_policy_rule_bytes_total` | the same | +| `galactic_cni_traffic_policy_fallback_packets_total` | namespace, vpc, attachment, interface, interface_uid, direction, reason | +| `galactic_cni_traffic_policy_fallback_bytes_total` | the same | +| `galactic_cni_traffic_policy_unattributed_drops_total` | direction, reason | +| `galactic_cni_traffic_policy_accounting_errors_total` | direction, action, reason | + +- `reason` on the fallback metrics is one of `no_match`, + `policy_unavailable`, `parse_error` or `classification_error`. +- `interface_uid` is the VPCAttachment UID. +- The collector labels each row from what galactic-router installed, never + from packet fields. After a restart, a row counts on in the kernel and is + exported again once its interface is reconciled and its snapshot adopted. +- Each evaluation produces exactly one outcome: a winning rule's hit and bytes, + or one fallback pair. The one exception is a packet captured while the mode + was off and decided just after it turned on, at most one per CPU at the + switch, which is forwarded and not counted. +- Bytes are the tenant IP packet at the evaluation point, without Ethernet or + outer SRv6. A GSO skb counts once at its buffer length. +- A malformed packet whose IP boundary cannot be found adds zero bytes. +- A missing counter row keeps the verdict and increments + `accounting_errors_total{reason="missing_rule_counter"}`. + +**Cardinality.** A node exports, per tenant interface, one series pair per +installed rule per direction plus four fallback pairs per direction. A node +with 100 interfaces whose policies average 8 rules exports about +100 × 2 × (8 + 4) × 2 = 4,800 series. The limits (64 rules, 256 entries) cap +the worst case at 100 × 2 × 68 × 2 = 27,200, which PR 7 states as the +supported budget. `policy_uid` changes only on rebind or recreation, which +ends the old series by design. + +### Kernel requirements + +The design needs `HASH_OF_MAPS`, `bpf_for_each_map_elem` (5.13), the tc egress hook, the +synchronous map-in-map wait (4.20), and the 6.8 fix to inner-map freeing. +Production and staging run Talos v1.13.10, whose kernel line is 6.18. + +The CNI preflight gains probes for `HASH_OF_MAPS` and `bpf_for_each_map_elem`. The inner-map +fix cannot be probed, so the preflight also requires kernel 6.8 or later. That +check is deliberately conservative: it rejects a distribution kernel that +backported the fix, and an operator can override it with +`GALACTIC_CNI_TRAFFIC_POLICY_KERNEL_CHECK=false` after confirming the +backport. A node that fails them reports a capability error and, when the mode +is `audit` or `enforce`, refuses new managed interfaces. It never falls back to +forwarding without enforcement. This raises the minimum kernel for +enforcement to 6.8, which the pull requests call out. + +## Rollout + +Default deny is a deliberate behavior change. The enforcement mode in +`tp_state` is `off`, `audit` or `enforce`, set per node by +`GALACTIC_CNI_TRAFFIC_POLICY`. It defaults to `off`; only the containerlab lab +enforces by default. [docs/traffic-policy/rollout.md](../traffic-policy/rollout.md) +is the operator's step-by-step guide. + +- `off` changes nothing. Maps and programs are loaded, but `tp_capture` and + `tp_decide` return immediately. +- `audit` evaluates and counts every packet but forwards as before. Operators + use the counters to find interfaces whose traffic would be denied. +- `enforce` drops. + +Operators move a site to `enforce` only after every running interface has +explicit bindings for the traffic it needs. An interface created before the +release that adds the ingress side gets its policy row from `galactic-cni` +at startup, with a fresh token, so its bindings apply; its assigned addresses +are not known there, so until the workload is recreated its ARP and its +neighbor discovery from a global address are ordinary traffic rather than +link operations. Recreate such workloads before enforcing. Steady-state interfaces default to +deny in every mode except `off`. There is no legacy allow and no generated +reverse rule. `audit` is a measurement mode for migration, not a +compatibility allowance, and `enforce` is the only mode the steady state uses. + +## Delivery plan + +### Pull request sequence + +Each PR builds and passes `task ci` against its declared base. Until the last +PR, enforcement stays `off` and nothing changes for any packet. + +| # | PR | Depends on | Delivers | Still inactive | +| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------------------------------------- | ------------------------------------------ | +| 1 | This design | none | Decisions, audit, lifetime argument, plan | Everything | +| 2 | `api/v1alpha1` TrafficPolicy and TrafficPolicyBinding, generated CRDs and API docs, CEL validation, envtest | 1 | The schema | Nothing reads it | +| 3 | `galactic-controller --role=cell`: webhook, default provisioning, binding resolution status, manifests and RBAC | 2 | Admission and status | Datapath | +| 4 | `internal/trafficpolicy`: Go evaluator and compiler with bounds | 2 | Semantics oracle and entry layout | Datapath | +| 5 | BPF: maps, parser, `tp_capture` and `tp_decide`, egress classification, the checks at every egress exit, the publication package and counter allocator | 4 | Egress enforcement, tested against the Go evaluator | Mode `off` by default; ingress unchecked | +| 6 | Ingress: the check in `usid_ingress`, `tp_deliver`, the ingress mark, link-down activation, CHECK and repair, preflight | 5 | Every path in the audit is checked | Mode `off` by default | +| 7 | galactic-router TrafficPolicyReconciler, node status, collector and metrics, `policy show` and `explain` | 3, 6 | Live updates and observability | Mode `off` by default | +| 8 | Lab: containerlab policies for every fixture, positive and negative checks for each path, docs and rollout guide; the mode defaults to `enforce` in the lab only | 7 | End-to-end validation | Production stays `off` until infra opts in | + +### Requirement checklist + +| Requirement | PRs | Validation | +| ------------------------- | ---------- | -------------------------------------------------------------------------------- | +| R1 per interface | 2, 5, 6, 7 | Two interfaces in one VRF with different policies, same node and remote | +| R2 independent directions | 2, 5, 7 | Binding one direction leaves the other at default | +| R3 no implicit replies | 4, 5, 8 | Egress Allow leaves replies denied; ingress Allow leaves workload replies denied | +| R4 one-rule default | 2, 3, 4 | Default has one rule and no SMTP rule | +| R5 first match | 4, 5 | BPF verdicts equal the Go evaluator on generated packets | +| R6 match fields | 2, 4, 5 | Path, family, IP and CIDR, ports, ICMP tables | +| R7 live updates | 5, 7 | Concurrent publication shows only whole old or whole new verdicts | +| R8 fail closed | 5, 6, 7 | Every binding-transition row and fault-injection case | +| Path audit | 6, 8 | Traffic down each mechanism in the audit, both allowed and denied | +| Parser | 5 | Every parser-table row | +| Metrics | 5, 7 | Collector names, labels and types; exactly-once counting | + +## Alternatives + +- **References on VPCAttachment.** The cloud operator owns and rewrites that + spec, and the cloud repository is being retired into Galactic. +- **A per-attachment on/off NAT switch (NetworkEgressPolicy).** It would + conflict with policy, and the requirement makes NAT an ordinary path match. +- **A standalone tc program in front of `usid_egress`.** It would have to + repeat every route and group lookup to classify the path, and could disagree + with the program that forwards. Calling one evaluator from each forwarding + exit uses the classification the forwarding decision already made. +- **Evaluating ingress only at host tc egress.** `bpf_redirect_peer` skips that + hook, and giving up the peer redirect would cost every veth delivery a + backlog round trip. +- **CEL-only null rejection.** Shown above not to work. diff --git a/docs/designs/latency-aware-routing.md b/docs/designs/latency-aware-routing.md new file mode 100644 index 000000000..b717b5140 --- /dev/null +++ b/docs/designs/latency-aware-routing.md @@ -0,0 +1,526 @@ + + +Status: proposed. This document describes an exploratory design and does not establish an implemented tenant routing policy. Its roadmap is not a release commitment. +# Latency-Aware Routing + +- [Summary](#summary) +- [Motivation](#motivation) + - [Goals](#goals) + - [Non-Goals](#non-goals) +- [Proposal](#proposal) + - [Policy Model](#policy-model) + - [Delay Measurement](#delay-measurement) + - [Delay Distribution via BGP](#delay-distribution-via-bgp) + - [Path Selection](#path-selection) + - [Tag-Based Policy Routing](#tag-based-policy-routing) + - [Policy Enforcement Points](#policy-enforcement-points) + - [Tenant Observability](#tenant-observability) + - [How It Comes Together](#how-it-comes-together) +- [Design Decisions](#design-decisions) +- [Roadmap](#roadmap) +- [Dependencies](#dependencies) + +## Summary + +Latency-aware routing enables VPC customers to express routing intent — low +latency, geographic constraints, bandwidth requirements — as declarative +policies attached to their workloads. The platform continuously measures +network delay between nodes, distributes delay metrics through +[BGP][bgp-overview], and makes autonomous, per-node path selection decisions +using [SRv6][srv6] traffic engineering. Customers see the results through +metrics exposed in the platform's telemetry system. + +This enhancement builds on the existing [BGP control plane][datum-bgp] and +[SRv6 data plane](../cni/README.md) to add three capabilities: active delay +measurement, delay-aware route advertisement, and policy-driven path +selection — all operating autonomously within each cluster without +management cluster involvement in the forwarding path. + +## Motivation + +Today, traffic between VPC workloads follows the shortest available path +through the network fabric — but the shortest path isn't always the fastest. +As the platform scales across regions and availability zones, the gap between +"shortest path" and "lowest latency path" grows. Customers running +latency-sensitive workloads have no way to express that their traffic should +prefer low-latency paths, and no visibility into the actual latency their +traffic experiences. + +Different services within the same VPC have fundamentally different +connectivity requirements. A real-time trading API needs sub-millisecond +optimization while a batch log shipper just needs reachability. Geo-aware +routing, latency-based routing, and bandwidth optimization are per-service +concerns, not per-network concerns. The platform needs to support this +granularity down to the individual connection. + +The core insight from research into protocols like [DDM][ddm] (Delay Driven +Multipath) and Google's [Swift][swift] is that **delay is a simple, +effective, and universal signal** for path quality — it inherently encodes +congestion, distance, and link health into a single measurable value. + +### Goals + +- Continuously measure network delay between all nodes using active probes + based on [STAMP][stamp] +- Distribute measured delay metrics through the existing BGP control plane + using standard path attributes ([AIGP][aigp]) +- Enable each node to make autonomous, delay-aware path selection decisions + without management cluster involvement +- Allow VPC customers to express routing intent (low latency, geographic + constraints) as declarative policies with workload selectors +- Apply policies at attachment time — when a pod starts or a + [MASQUE][masque] tunnel is established — not per-packet +- Expose measured path latency, jitter, and loss to customers through the + platform's telemetry system +- Provide basic connectivity optimization for all VPCs by default + +### Non-Goals + +- Replacing the primary CNI for intra-cluster pod-to-pod networking +- Per-packet deep inspection or application-layer routing decisions +- Centralized path computation (PCE) for routine routing decisions — nodes + must operate autonomously +- Hardware-specific optimizations (ASIC timestamping, hardware queuing) +- Guaranteed bandwidth reservation (this is a path selection enhancement, + not a QoS reservation system) + +## Proposal + +### Policy Model + +Routing intent is expressed through two resource types: a tenant-facing +**VPCRoutingPolicy** that selects workloads and assigns tags, and a +platform-level **RoutingProfile** that defines what each tag means in terms +of forwarding behavior. + +**VPCRoutingPolicy** — created by tenants, scoped to a VPC: + +```yaml +apiVersion: networking.galactic.datumapis.com/v1alpha1 +kind: VPCRoutingPolicy +metadata: + name: gold-realtime +spec: + vpcRef: my-vpc + selector: + matchLabels: + app: trading-engine + tag: gold + requirements: + maxLatency: 5ms + geoConstraint: US +``` + +```yaml +apiVersion: networking.galactic.datumapis.com/v1alpha1 +kind: VPCRoutingPolicy +metadata: + name: standard-batch +spec: + vpcRef: my-vpc + selector: + matchLabels: + app: log-shipper + tag: standard +``` + +Multiple policies can coexist for the same VPC — different services get +different routing behavior. Policy selectors match against workload labels +on VPCAttachments and ConnectorAttachments. + +**RoutingProfile** — defined by the platform, delivered to clusters by the +fleet agent: + +```yaml +apiVersion: networking.galactic.datumapis.com/v1alpha1 +kind: RoutingProfile +metadata: + name: gold +spec: + color: 100 + dscp: 46 # EF - Expedited Forwarding + pathSelection: min-delay + constraints: + maxLatency: 5ms + affinities: + include: [US] +--- +apiVersion: networking.galactic.datumapis.com/v1alpha1 +kind: RoutingProfile +metadata: + name: standard +spec: + color: 300 + dscp: 0 # Best Effort + pathSelection: default +``` + +The RoutingProfile translates a tag into three forwarding behaviors: + +- **Color** ([SR Policy Color Extended Community][sr-policy]): determines + which set of delay-aware routes the headend resolves against +- **DSCP**: marks the outer IPv6 header so every transit node applies the + correct queuing behavior without any tenant awareness +- **Path selection constraints**: delay ceiling, geographic affinity + inclusion/exclusion, bandwidth floor + +### Delay Measurement + +Each galactic-agent node runs a [STAMP][stamp] sender and reflector to +actively measure one-way and round-trip delay to its BGP peers. STAMP is the +IETF standard for active measurement, with [SRv6-specific +extensions][stamp-sr] that ensure probes follow the exact same paths as real +traffic. + +Measurement operates entirely in-memory on each node: + +1. The agent sends STAMP test packets to each peer at a configured interval + (e.g., every 2 seconds) +2. Timestamps are applied at send (T1), receive (T2), reflect (T3), and + return (T4) +3. Two-way delay = (T4 - T1) - (T3 - T2) — no clock synchronization + required +4. The agent maintains a rolling average delay value per peer link +5. Delay values are stored in the agent's local memory — **never written to + etcd** + +On Linux, the STAMP reflector can be implemented as an [eBPF][ebpf] program +attached to SRv6 SID processing via the kernel's `End.BPF` behavior, +providing kernel-space timestamping with negligible forwarding impact. + +### Delay Distribution via BGP + +Measured delay is distributed through BGP itself — the same TCP sessions +already exchanging routes. No additional protocols, no etcd writes, no +management cluster involvement. + +The mechanism is the [AIGP attribute (RFC 7311)][aigp], an optional BGP path +attribute that accumulates a metric across AS boundaries. The +[draft-ietf-idr-performance-routing][perf-routing] proposes a +NETWORK_LATENCY TLV within AIGP specifically for delay values. + +**How it flows:** + +1. Node A measures 2ms delay to Node B via STAMP +2. When Node A advertises its SRv6 /48 prefix, the advertisement reconciler + attaches an AIGP attribute with the measured delay value (2000 + microseconds) +3. Node B receives the route. When re-advertising to Node C, Node B adds + its own measured link delay to the AIGP value (accumulation) +4. By the time a route reaches a decision point, the AIGP value represents + the total end-to-end delay along that path + +``` +Node A originates route for 2001:db8:x::/48 + → AIGP: 0 μs (originated locally) + +Node B receives from Node A, re-advertises to Node C + → AIGP: 2000 μs (0 + 2000 measured on A→B link) + +Node C receives from Node B, re-advertises to Node D + → AIGP: 5000 μs (2000 + 3000 measured on B→C link) + +Node D has two paths to 2001:db8:x::/48: + Path 1 via Node C: AIGP = 5000 μs + Path 2 via Node E: AIGP = 3000 μs + → GoBGP selects Path 2 (lower AIGP wins) +``` + +[GoBGP][gobgp] already implements AIGP-aware best-path selection — AIGP +comparison runs before AS-path length in the tie-breaking sequence. No +custom path selection logic is needed. + +**What touches etcd vs. what doesn't:** + +| Data | Where it lives | Update frequency | +| -------------------------- | ------------------ | --------------------------- | +| Delay measurements | Agent memory | Every few seconds | +| AIGP attribute on routes | BGP sessions (TCP) | On measurement change | +| RoutingProfile definitions | etcd (CRD) | Infrequent (policy changes) | +| VPCRoutingPolicy | etcd (CRD) | Infrequent (tenant changes) | +| Per-link delay metrics | Prometheus | Scraped periodically | + +High-frequency delay data never touches the API server. + +### Path Selection + +When a node has multiple BGP paths to the same prefix, GoBGP's existing +best-path algorithm uses the AIGP value as a tiebreaker — lower accumulated +delay wins. The route watcher receives the best-path update and programs the +kernel via `netlink.AddRoute`. No explicit segment lists are needed for +basic delay optimization. + +For Color-aware routing, the node resolves routes differently per Color: + +1. A BGP route arrives with a [Color Extended Community][sr-policy] + (e.g., Color 100 = min-delay) +2. The node resolves the route against paths tagged with that Color +3. Among matching paths, AIGP selects the lowest-delay option +4. The route watcher programs the appropriate kernel forwarding entry + +This is the distributed model — every node makes its own path selection +decision based on locally-received BGP routes with delay annotations. No +central controller is involved in the forwarding path. The management +cluster's only role is delivering the RoutingProfile definitions that map +Colors to constraints, which happens infrequently via the fleet agent. + +### Tag-Based Policy Routing + +Tags connect tenant intent to forwarding behavior through three layers: + +**Classification (at the source node):** + +When a pod starts and the CNI plugin creates its VPC network interface, the +galactic-agent evaluates VPCRoutingPolicy selectors against the pod's +labels. The matching policy's tag resolves to a RoutingProfile, and the +agent programs an eBPF classifier on the pod's veth interface that: + +- Sets the DSCP value in the outer IPv6 header +- Steers traffic toward routes matching the profile's Color + +This classification is programmed once at attachment time. Per-packet +processing is a simple eBPF lookup — no policy evaluation per packet. + +**Path steering (at the headend):** + +The DSCP-marked, Color-steered packet is SRv6-encapsulated using the +delay-optimized path selected for that Color. The segment list is determined +by the BGP route resolution for the destination prefix at the specified +Color. + +**Per-hop treatment (at transit nodes):** + +Transit nodes see only the DSCP value in the outer IPv6 header and the SRv6 +destination. They apply queuing behavior based on DSCP (standard Linux +traffic control) and forward based on the segment list. Transit nodes have +no knowledge of tenants, policies, or tags. + +``` +Source node (headend): + - Knows the tenant policy (VPCRoutingPolicy CRD) + - Classifies traffic by pod labels + - Chooses path based on Color + - Sets DSCP based on tag + - Encapsulates in SRv6 + +Transit nodes: + - See DSCP in outer IPv6 header → queue priority + - See SRv6 destination → forward per segment list + - No knowledge of tenants, policies, or tags + +Destination node: + - End.DT46 decapsulates into VRF + - Delivers to destination pod +``` + +### Policy Enforcement Points + +Policies are applied at **attachment time** — the moment a workload connects +to the VPC network. This is the identity boundary where the platform knows +which tenant, service, and routing requirements apply. + +**Pod attachment (CNI time):** + +The galactic-agent programs the eBPF classifier on the pod's veth pair when +the CNI plugin creates the network interface. The pod's labels are matched +against VPCRoutingPolicy selectors, and the resulting classification rules +are installed. + +**Connector attachment ([MASQUE][masque] tunnel establishment):** + +When a Connector establishes a MASQUE tunnel, the proxy: + +1. Authenticates the client (mTLS client certificate) +2. Looks up the ConnectorAttachment — confirms VPC binding +3. Evaluates VPCRoutingPolicy selectors against the ConnectorAttachment's + labels +4. Programs classification rules for this tunnel +5. All traffic entering through the tunnel gets the correct DSCP marking + and Color-based path selection + +Different Connectors to the same VPC can get different routing treatment +based on their labels: + +```yaml +ConnectorAttachment "trading-link": + labels: { app: trading, tier: premium } + → matches VPCRoutingPolicy "gold-realtime" + → Color 100, DSCP 46, min-delay path + +ConnectorAttachment "log-link": + labels: { app: logging, tier: standard } + → matches VPCRoutingPolicy "standard-batch" + → Color 300, DSCP 0, default path +``` + +**Gateway attachment:** + +Gateway pods connecting to VPC networks follow the same pattern as pod +attachment — the galactic-agent programs classification rules when the +Gateway's VPCAttachment is created. + +**Policy updates:** + +If a tenant updates their VPCRoutingPolicy, the galactic-agent watches for +the change and reprograms the eBPF classifiers on affected attachments. The +data plane connections remain up — only the forwarding behavior changes. + +### Tenant Observability + +Measured delay data is exposed to tenants through the platform's telemetry +system — the same metrics and dashboards they use for everything else. + +**Platform-level metrics (for operators):** + +- `bgp_link_delay_microseconds{peer="..."}` — per-link measured delay +- `bgp_link_delay_variation_microseconds{peer="..."}` — jitter +- `bgp_path_aigp_microseconds{prefix="...", peer="..."}` — accumulated + end-to-end delay per path + +**Tenant-visible metrics:** + +- Per-VPC latency between attachment points +- Per-policy SLO compliance (is traffic actually meeting the maxLatency + constraint?) +- Path performance for traffic matching each VPCRoutingPolicy + +These are derived from the same STAMP measurements that drive routing +decisions, but aggregated and scoped per-tenant through the telemetry +pipeline. Tenants observe outcomes; they don't interact with the measurement +infrastructure directly. + +### How It Comes Together + +When a new workload connects to a VPC with latency-aware routing: + +1. Tenant creates a **VPCRoutingPolicy** with a selector and tag +2. The fleet agent has already delivered the **RoutingProfile** definitions + to the cluster (Color, DSCP, path selection constraints) +3. A pod starts — the **CNI plugin** creates the VPC interface +4. The **galactic-agent** evaluates the policy selector against the pod's + labels, resolves the tag to a RoutingProfile, and programs the **eBPF + classifier** on the pod's veth +5. Meanwhile, STAMP probes have been continuously measuring link delays + between all nodes +6. Delay values are attached as **AIGP attributes** on BGP route + advertisements and accumulate across the path +7. GoBGP selects the **lowest-delay path** for routes matching the pod's + Color +8. The first packet from the pod is classified (DSCP marked, Color + steered), **SRv6-encapsulated** with the delay-optimized segment, and + forwarded +9. Transit nodes **queue by DSCP** and forward by SRv6 — no tenant + awareness needed +10. The destination node **decapsulates** (End.DT46) into the VRF and + delivers to the target pod +11. **Telemetry** exposes the measured latency to the tenant, confirming + the SLO is being met + +The management cluster's involvement was limited to delivering the +RoutingProfile definitions. Everything else — measurement, route +advertisement, path selection, classification, forwarding — operates +autonomously within the cluster. + +## Design Decisions + +### Distributed path selection over centralized PCE + +The platform uses BGP-distributed delay metrics and per-node path selection +rather than a centralized Path Computation Element. This follows the +existing design principle that clusters are self-sufficient once the fleet +agent delivers initial configuration. + +A centralized PCE would create a latency and availability bottleneck — +every path decision would depend on reachability to the controller. The +distributed model means each node makes decisions using locally-received BGP +routes, reacting to delay changes in real-time without calling home. + +The tradeoff is that complex multi-constraint optimization (e.g., "low delay +AND avoid region X AND disjoint from path Y") may require a controller in +the future. The Color-based architecture accommodates this — a central +controller could populate SR Policies for specific Colors without changing +the tenant-facing model. + +### AIGP for delay transport over custom attributes + +AIGP (RFC 7311) is a standard BGP attribute with native accumulation +semantics — each node adds its contribution as the route propagates. GoBGP +already supports it. Using a standard attribute means the delay information +works across eBGP boundaries between clusters without custom interop. + +### Policy at attachment time over per-packet classification + +Evaluating tenant policies once when the workload connects (CNI time or +MASQUE tunnel establishment) avoids per-packet policy lookups. The eBPF +classifier programmed at attachment time executes in the kernel fast path +with no user-space involvement. Policy changes trigger reprogramming of the +classifier, not per-packet evaluation. + +### Delay data in BGP over etcd + +STAMP measurements update every few seconds per link. Writing these to CRDs +would generate massive etcd write load and trigger reconciliation storms. +Instead, delay values flow through BGP sessions (existing TCP connections +between nodes) and are consumed by GoBGP's in-memory path selection. +Prometheus metrics provide observability. etcd stores only infrequently +changing policy definitions. + +### Default optimization for all VPCs + +All VPCs get basic connectivity optimization without explicit policy. The +platform always prefers better-performing paths when they exist, because +AIGP-aware best-path selection runs for all routes regardless of Color. +Explicit policies let tenants tighten constraints beyond the baseline. + +## Roadmap + +| Phase | Scope | +| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Phase 1** | STAMP measurement between nodes; AIGP delay attribute on route advertisements; basic delay-aware best-path selection for all traffic | +| **Phase 2** | VPCRoutingPolicy and RoutingProfile CRDs; Color Extended Community support; tag-based classification with eBPF; DSCP marking; per-tag path selection | +| **Phase 3** | MASQUE Connector policy enforcement; geographic affinity constraints; tenant-facing latency metrics; SLO compliance alerting | +| **Phase 4** | Cross-cluster delay optimization via eBGP AIGP propagation; predictive routing using delay derivatives (DDM-inspired); bandwidth-aware path selection | + +## Dependencies + +- **[VPC Networking](../cni/README.md)**: Provides the SRv6 data plane, VPC/ + VPCAttachment resources, VRF isolation, and the CNI plugin where + classification rules are installed. + +- **Fleet Networking (external dependency)**: Provides + the BGP control plane, IPAM, and topology policy that this enhancement + extends with delay awareness. RoutingProfile definitions are delivered to + clusters through the same fleet agent mechanism. + +- **[BGP Control Plane][datum-bgp]**: The topology-agnostic BGP system + running on every cluster. This enhancement extends its CRDs and + reconcilers with AIGP support, Color Extended Communities, and STAMP + measurement integration. + +- **Telemetry System**: Platform observability infrastructure where + per-tenant latency metrics are exposed. The galactic-agent exports + Prometheus metrics; the telemetry pipeline aggregates and scopes them + per-tenant. + + +[bgp-overview]: https://datatracker.ietf.org/doc/html/rfc4271 +[srv6]: https://datatracker.ietf.org/doc/html/rfc8986 +[sr-policy]: https://datatracker.ietf.org/doc/html/rfc9256 +[stamp]: https://datatracker.ietf.org/doc/html/rfc8762 +[stamp-sr]: https://datatracker.ietf.org/doc/html/rfc9503 +[aigp]: https://datatracker.ietf.org/doc/html/rfc7311 +[perf-routing]: https://datatracker.ietf.org/doc/draft-ietf-idr-performance-routing/ +[bgp-car]: https://datatracker.ietf.org/doc/draft-ietf-idr-bgp-car/ +[flex-algo]: https://datatracker.ietf.org/doc/html/rfc9350 +[flex-algo-bw]: https://datatracker.ietf.org/doc/html/rfc9843 +[bgp-ls-te]: https://datatracker.ietf.org/doc/html/rfc8571 +[isis-te]: https://datatracker.ietf.org/doc/html/rfc8570 +[network-slicing]: https://datatracker.ietf.org/doc/html/rfc9543 +[ibn]: https://datatracker.ietf.org/doc/html/rfc9315 +[ddm]: https://rfd.shared.oxide.computer/rfd/0347 +[swift]: https://research.google/pubs/swift-delay-is-simple-and-effective-for-congestion-control-in-the-datacenter/ +[espresso]: https://research.google/pubs/taking-the-edge-off-with-espresso-scale-reliability-and-programmability-for-global-internet-peering/ +[masque]: https://datatracker.ietf.org/doc/html/rfc9484 +[gobgp]: https://osrg.github.io/gobgp/ +[datum-bgp]: https://github.com/datum-cloud/bgp +[ebpf]: https://ebpf.io/ diff --git a/docs/designs/looking-glass-service.md b/docs/designs/looking-glass-service.md new file mode 100644 index 000000000..053f5cd8b --- /dev/null +++ b/docs/designs/looking-glass-service.md @@ -0,0 +1,694 @@ +# Looking Glass backend service contract + +Status: proposed implementation contract for [#1042](https://github.com/datum-cloud/galactic/issues/1042), +under [#1041](https://github.com/datum-cloud/galactic/issues/1041). +This document specifies required future behavior. It does not announce an +available API, validated capacity, or measured failure bound. Implementation is +tracked in #1043–#1047 and qualification in #1048; enabling customer execution +requires those gates. Baseline inspected: Galactic `6da52240`. + +The consumer and backend reviewers must approve this contract before dependent +milestones freeze their wire schema. Changes to the decisions below require a +contract update and corresponding acceptance cases, not undocumented defaults. + +## Scope and existing behavior + +Galactic executes bounded diagnostics in one cell's fabric-router network +context. The customer service owns authentication, project IAM, location +placement, session revocation detection, durable single-use claims, and delivery +to the customer. A project identifier received by Galactic is trusted +attribution from that service, not proof of the customer's permission. +Backend duplicate suppression cannot implement a durable single-use session. + +Reuse the four existing diagnostic implementations, discovery, and shared +executor. Keep node RPCs unary; stream completed router outcomes, not individual +traceroute hops. Existing operator `FabricGatewayService.Query/ListNodes`, node +`FabricService.Execute/Info`, and the [FabricQuery API](../fabric-api/api.md) retain their wire +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 +"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`, +the leader enforces "Admission, execution, and aggregate accounting" below +(`internal/fabric/gateway/limit`, `gateway.Admission`, `gateway.Permits`), and +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`. +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 +discovery still return pod candidates, including duplicates. + +## Service and identity + +Publish a separate `fabric.service.v1` protobuf package at +`api/fabric/service/v1/service.proto`, with Go import +`go.datum.net/galactic/api/fabric/service/v1`. The intended service surface is: + +```proto +service LookingGlassService { + rpc GetCapabilities(GetCapabilitiesRequest) returns (GetCapabilitiesResponse); + rpc RunDiagnostic(RunDiagnosticRequest) returns (stream DiagnosticEvent); +} +``` + +This is a service declaration excerpt, not a compilable schema. The field +contract below is normative input to schema generation in #1044. Reuse the public +`fabric.v1.Observation`, `Query`, and `Budgets` messages; do not expose Go +`internal/` types or add streaming semantics to an existing unary method. + +Use the URI SAN +`spiffe://fabric-api.datumapis.com/cell//service/`. +Require the cell's trust bundle, valid certificate lifetime, exactly one +fabric-api identity, matching cell, and a configured service-name allowlist. +An authenticated service can call only these two methods. It cannot call +operator Query/ListNodes or node Execute/Info. Existing roles gain no direct +service-method permission. Apply authorization to unary and streaming RPCs, +including on reused TLS connections; cap a stream at certificate expiration. +Certificate rotation follows the existing reload/overlapping-CA mechanism. + +A follower authenticates the original caller before forwarding once to the +leader over same-cell gateway mTLS. A separate gateway-only forwarding method +carries a typed envelope: original service URI, cell, project ID, request ID, +canonical request, original admission time, and absolute deadline. It is not a +customer-callable method. The leader validates the envelope, role, cell, +allowlist, and deadline again. Strip incoming forwarding metadata; never trust +caller-provided operator or service headers. Reject a second forwarding hop. +The gateway identity is a trusted deputy; compromise of that identity is outside +this isolation guarantee. Do not automatically retry a failed forward. + +## Requests, capabilities, and results + +`GetCapabilitiesRequest` contains `cell` and `api_major=1`. Its response contains +`cell`, `api_major`, `contract_revision`, `enabled`, `policy_revision`, the four +operation/family combinations enabled by cell policy, required features, +effective limits from this document, and `generated_at`. It reveals no node +addresses or credentials. Cap it at 64 KiB, a 2 s deadline, 1 call/s with burst 2 +per authenticated service per replica, and 8 concurrent calls per replica. +The initial feature names are `router-outcomes`, `terminal-coverage`, and +`aggregate-probe-budgets`; all three are required to advertise an enabled v1 +service. `contract_revision` is the implementing release commit SHA and +`policy_revision` is the digest of effective service policy and limits. +`limits.admission` reports the cell's admission and packet budgets, present +only with `aggregate-probe-budgets`. A router failure refused by a limit +carries the same `scope` and `retry_delay` as a refused request. It does not probe routers or reserve +diagnostic capacity. Cache for at most 30 s. Capabilities advertise policy, not current router availability. Validate +again on execution; policy changes may reject a previously advertised request. + +`RunDiagnosticRequest` fields: + +| Field | Meaning and validation | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `api_major` | Must be 1; incompatible majors fail before execution. | +| `cell` | Required; exact match with authenticated identity and serving cell. | +| `project_id` | Required opaque canonical project UID supplied by the service, ASCII `[A-Za-z0-9._:-]`, 1–128 bytes; not a project display name. | +| `request_id` | Required UUID identifying this backend attempt; unique within service, project, and cell. | +| `expires_at` | Required UTC timestamp; future and at most 120 s after first gateway receipt. Forwarding never extends it. | +| `query` | One supported operation, target, and address family as below. | +| `nodes` | Optional unique node names, at most 32; empty selects all eligible routers within the fan-out bound. Unknown names fail validation. | +| `budgets` | Optional lower response/path/community limits; values exceeding advertised limits fail validation. Zero selects advertised defaults. | +| `required_features` | Set of capability names needed by the caller; unknown or unsupported requirements fail before work. | + +Use the minimum of request expiration, transport deadline, and certificate +expiration. A client should supply a 30 s deadline unless it needs a longer +bounded allowance for discovery and delivery. There is no implicit deadline +extension. Reject +oversized/unknown enum inputs, controls, ambiguous identifiers, and unsupported +operations before reserving work. Normalize numeric targets exactly once and +pass the canonical value to nodes. Do not resolve DNS in the backend. + +| Operation | Inputs | Successful observation | +| ----------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | +| RouteLookup | Bare IPv4/IPv6 address for longest match, or prefix with no host bits for exact match; family inferred or explicitly matching. | Router-local paths and separately sampled zebra installation; no matching route is a successful empty result. | +| BGPSummary | Empty target; explicit IPv4 or IPv6 family required. | Peer states and counters; a down peer is data. | +| Ping | Numeric unicast address, matching/inferred family; no hostname, zone, or IPv4-mapped IPv6 form. | Three ICMP echo attempts, source/destination, replies, loss and RTT. | +| Traceroute | Same target rules as Ping. | At most 20 hops, one ICMP probe per hop, source/destination, reached flag and hop observations. | + +Reject ASPath, Community, LargeCommunity, arbitrary commands, and caller-selected +probe sources. Ping/traceroute use at most 64 payload bytes per packet and a 1 s +reply wait. Apply the existing public destination policy at gateway and node: +special-use and deployment-denied platform/management ranges are forbidden; +IPv6 must be in the allowed global-unicast space. Operator allow exceptions +never apply to service traffic. Route visibility is independently gated by the +service's cell policy; project IAM and customer visibility decisions remain +upstream launch prerequisites, not inferred from certificate possession. + +### Stream grammar and coverage + +Each event has `request_id`, consecutive `sequence` starting at 1, and exactly +one of `snapshot`, `outcome`, or `complete`. A stream has one snapshot first, +zero or more outcomes in completion order, and at most one complete last. +The server finishes a fully delivered stream with gRPC OK, including when its +terminal diagnostic result is partial or failed. Transport failure or missing +complete means incomplete delivery, never success inferred from EOF alone. + +Before admission, take one logical discovery snapshot of the configured +fabric-router pod inventory in the cell. Record `snapshot_id`, `captured_at`, +and the list resourceVersion; certify identities from the corresponding cert +pod read. These reads are not an atomic Kubernetes multi-resource snapshot. +Do not refresh membership or substitute a replacement pod during the run. + +Group scheduled fabric-router pods by node name, including those without a +sidecar, usable address, running container, or certificate. Select one usable +pod per router deterministically: newest creation time, then pod name. Retain +other candidates only as diagnostic metadata; duplicate pods do not increase +expected coverage. Unscheduled pods have no router identity and are reported +in the snapshot field `unscheduled_pod_count` (zero when none). Nodes with no +fabric-router pod are outside +this inventory; coverage must not claim all physical routers in the cell. + +Apply explicit `nodes` selection before the fan-out cap; otherwise use sorted +node names. The snapshot records every unique router as selected or omitted, +with a reason (`NotRequested`, `NoSidecar`, `PodTerminating`, `PodNotRunning`, +`SidecarNotRunning`, `NoHostIP`, `NoCertificatePod`, or `NodeBudget`). A selected +router includes its frozen pod UID. An explicit selection takes precedence: +routers outside it have reason `NotRequested`, regardless of their availability. +Do not expose dial addresses or certificate +pod names to the service. Cap the inventory at 256 unique routers and 64 KiB +serialized snapshot; fail with `InventoryTooLarge` rather than silently +truncating membership. This does not change legacy FabricQuery discovery. + +Let E be snapshot routers, S selected routers, and O omitted routers. +At terminal completion, every selected router has exactly one outcome: + +```text +E = S + O +S = successful + failed +E = successful + failed + omitted +``` + +Send the snapshot before dispatching node jobs. Reserve queue capacity first, +so failure to admit cannot produce an apparently admitted snapshot. If snapshot +delivery fails, release that capacity and dispatch nothing. Outcome sequence +reflects completion handoff order; simultaneous completions may appear in either +order, but a slow router must not delay a completed router. + +An outcome contains node name, frozen pod UID, completion time, and exactly one +observation or typed failure. An observation retains router ID, ASN, sample time, +duration, and its operation's result. Sample time is the start of that router's +read/probe, not the snapshot time; errors before sampling have no fabricated +sample time. Unreachable nodes and selected work canceled before dispatch are +failed, not omitted. A capability missing on a selected node is also a failure. + +`complete` repeats snapshot ID and counts, has `finished_at`, `truncated_routers`, +and a terminal reason: `Succeeded`, `PartialResults`, `ExecutionFailed`, +`NoNodesAvailable`, `DeadlineExceeded`, `Cancelled`, `OwnershipLost`, or +`OutputLimitExceeded`. Cancellation/deadline/ownership/output-limit reasons take +precedence. Otherwise no selected routers gives `NoNodesAvailable`; zero +successful gives `ExecutionFailed`; any failed or truncated result, or any +omission other than `NotRequested`, gives `PartialResults`; the remainder is +`Succeeded`. Keep `NotRequested` routers in expected and omitted counts: a +successful explicit subset can have nonzero omissions without claiming that +every router in the cell was queried. Empty inventory has all counts zero and +`NoNodesAvailable`. + +Packet loss, unreachable ICMP replies, and silent hops are successful diagnostic +observations. `truncated=true` also remains a successful observation, but warns +that its payload is incomplete. Zebra read errors retain their existing nested +installation error while the BGP observation stands. Neither truncation nor an +installation error may silently become an empty complete result. + +A connected client may receive synthesized cancellation failures and complete +while the deadline allows; a disconnected client cannot be promised either. +On an interrupted stream, preserve delivered observations, mark remaining +selected routers unknown to the consumer, and report only locally known counts. +Never fabricate the server's final coverage. There is no resume cursor or result +retrieval RPC. + +## Errors and retries + +Use `google.rpc.ErrorInfo` with domain `fabric-api.datumapis.com`. Its reason is +a stable machine-readable string; messages are sanitized and at most 256 bytes. +Router failures carry equivalent typed fields in their outcome. Errors must +not echo target addresses, credentials, or raw FRR text into routine logs. + +| Condition/reason | gRPC status before snapshot | Retry guidance | +| -------------------------------------------------------------------------- | ---------------------------------------- | ---------------------------------------------------------------- | +| Missing/invalid TLS identity | UNAUTHENTICATED or TLS handshake failure | Repair credentials; no automatic execution retry. | +| `Unauthorized` | PERMISSION_DENIED | Repair role, cell or policy. | +| `InvalidQuery`, `DestinationNotAllowed` | INVALID_ARGUMENT | Correct the request. | +| `VersionUnsupported`, `QueryTypeUnavailable`, `ServiceDisabled` | FAILED_PRECONDITION | Refresh capabilities/configuration. | +| `Throttled`, `QueueFull`, `NodeBusy` | RESOURCE_EXHAUSTED | Include RetryInfo; new authorized attempt only. | +| `InventoryTooLarge`, `ResponseTooLarge`, `OutputLimitExceeded` | RESOURCE_EXHAUSTED | Lower scope/output or change configuration; not a rate throttle. | +| `DuplicateRequest`, `DuplicateConflict` | ALREADY_EXISTS | Do not replay or treat this as a saved result. | +| `LimiterUnavailable`, `OwnershipLost`, `NodeUnreachable`, `FRRUnavailable` | UNAVAILABLE | Resolve availability; outcome may be unknown. | +| `DeadlineExceeded`, `QueueTimeout` | DEADLINE_EXCEEDED | No automatic retry. | +| `Cancelled` | CANCELLED | No automatic retry. | +| `ProbeSourceUnavailable`, `FRRVersionUnsupported` | FAILED_PRECONDITION | Repair node capability. | +| `MalformedResponse`, `Internal`, `ProbeFailed` | INTERNAL | Investigate backend; no automatic retry. | + +Existing node reasons, including `Timeout`, remain intact in router failures; +translate only the service-level deadline into `DeadlineExceeded`. After the +snapshot, operational failures should be outcomes/complete where delivery is +possible; the table's transport status applies when no stream can be delivered. +Unknown reasons must be rendered as backend failures, not packet loss. +`ResponseTooLarge` describes a single response that cannot fit its budget; +`OutputLimitExceeded` describes exhaustion of the service stream budget. +`OwnershipLost` and `OutputLimitExceeded` deliberately have both transport +status mappings and terminal stream reasons, depending on whether a complete +event can still be delivered. + +For throttling include `google.rpc.RetryInfo.retry_delay` and bounded ErrorInfo +metadata `scope` (cell/project/destination/queue) and `execution_started=false`. +Never include another project's identity or destination. Token shortage delay +is the maximum deficit/rate across depleted buckets, rounded up to milliseconds; +queue or concurrency refusal uses 1 s advisory delay. Recovery reports the +remaining recovery delay. Guidance is not a reservation or permission to retry. +A service may start a new attempt only under its own session/IAM policy, with a +new request ID and fresh charges. It must never replay an interrupted attempt. + +Disable application and configured gRPC retries/hedging for customer execution, +including the runner's existing cheap-read retry. No response bytes is not proof +that execution did not occur. The admission owner records the attempt key and +canonical argument digest until `expires_at + 2 s`; identical duplicates are +`DuplicateRequest`, changed arguments `DuplicateConflict`. Bound this cache at +4096 entries/2 MiB and fail closed when full; never evict live keys to admit more. +This volatile cache may be lost on restart. Node duplicate suppression is also +volatile and is an optimization only. + +## Admission, execution, and aggregate accounting + +### One cell authority and recovery + +Use the existing elected gateway as the single cell scheduler and limiter. +Followers forward; they never maintain independent execution buckets. Keep +bucket state in bounded leader memory, not Kubernetes session objects or a new +external datastore. Use an uncached election Lease read before each admission +and node dispatch to confirm holder UID/epoch and unexpired ownership. Define +epoch as Lease object UID plus the complete holderIdentity (including its unique +process-election suffix); recreating a Lease or acquiring it again must produce +a new epoch. Never reuse a previous holderIdentity after ownership uncertainty. Bound +that read to 1 s; any failure refuses new work and cancels active service work. +A stale cached leader boolean alone cannot authorize dispatch. + +Every process start, leadership acquisition, limiter-state loss, or return from +an uncertain ownership interval enters a **125 s recovery hold**, even on a new +cell. Do not restore work or carry queued customer requests across epochs. +At the end, require a fresh valid Lease read, initialize all buckets empty, and +refill from that instant. A key first seen later starts with at most +min(burst, rate × time since that instant); a safely evicted, fully refilled key +can be recreated full. Release of the old Lease does not waive the hold. +Changing limits also cancels service work and enters recovery; rolling updates +therefore have an explicit diagnostic availability cost. + +The hold exceeds the 120 s maximum request lifetime plus the combined 2 s +clock-skew and scheduling allowance. No prior-epoch request may be dispatched +with a new deadline. All bucket burst/rate ratios must be at most 120 s; then +the hold also clears the largest possible prior token debt. No traffic is +admitted by the authority during recovery, including aggregate-budget probes +from alternate interfaces. This conservative recovery is chosen over a durable +reservation datastore or independent replica buckets: it needs no new storage +service and avoids resetting available tokens at failover. Faster recovery +requires a separately reviewed durable accounting design. + +An old gateway isolated from the API cannot obtain new dispatch checks. Nodes +also validate the current epoch via an uncached Lease read before accepting a +probe permit; stale or unverifiable permits fail closed. Previously started +calls expire within the bounds below. A delayed old process must recheck its +absolute deadline and ownership before every dispatch. These rules, together +with the recovery hold, prevent simultaneous old/new-epoch execution. + +### Charging and scheduling + +Apply request admission token buckets after authentication and shape validation +but before discovery. First debit one cell and one project request token +atomically, then check/register the attempt key. A token-admitted duplicate +consumes both request tokens and returns `DuplicateRequest` or +`DuplicateConflict` without reserving node jobs or packets. Later validation, +discovery, or dispatch failures do not refund request tokens. If +either bucket is short, reject without debiting either; never go into negative +credit. Register the attempt key before discovery and before accepting jobs; +all later failures retain its tombstone through expiration. +Project buckets are keyed by canonical project UID across all authorized service +identities. Never use the common service account as the fairness key. + +After snapshot construction, admit all selected node jobs to the bounded shared +executor atomically or refuse the request. Charge one node-job unit per selected +router; omitted routers cost no node execution or packets. Maintain FIFO within +a principal and round robin between principal queues. A service request's +principal is its project UID, an operator's its identity name, and a +FabricQuery's `fabricquery//`: FabricQuery carries no +project UID, so a FabricQuery and a service request for the same project are +separate principals, sharing the executor and the cell and destination packet +budgets but not a fairness key or a project packet budget. A principal may +hold at most two node slots. +The shared executor has eight slots total. Keep the existing two-slot ceiling +for legacy expensive queries, which this service cannot submit. Queue admission +counts reserved snapshot-delivery slots toward the same limits. Live-stream +caps do not reserve node-job capacity: a second 32-router stream from a project +whose first stream still occupies its queue is refused with `QueueFull`. +FabricQuery work counts against its own principal's queue limit. + +Immediately before dispatch of each probe node job, atomically reserve its +worst-case packet count from cell, project (when present), and destination +buckets together. Charge Ping 3 and Traceroute 20. Insufficient credit fails +that selected router with `Throttled` without dispatching it. Never refund +unused, timed-out, rejected, canceled, or deduplicated attempts: conservatively +charged work must not become a retry bypass. A route read costs one node slot +and no packet credit. Three selected traceroute routers cost at most 60 packets; +32 cost at most 640. Actual early termination can only reduce that traffic. + +Destination keys are the canonical IPv4 /32 or IPv6 /128 **and** containing +IPv4 /24 or IPv6 /64. Charge both, independent of project and operation. Limits +are cell-wide, not global across cells. Rotating projects cannot evade them; +rotating hosts within one prefix still consumes its prefix budget. Avoid a +claim of global internet destination protection from a cell-local mechanism. + +Use bounded maps (4096 project keys, 16384 destination/prefix keys, 4 MiB total +bucket-state storage). A key may be discarded only when fully refilled: it then +holds no debt, and a key recreated later starts at no more than a full bucket. On capacity exhaustion reject new keys with +`LimiterUnavailable`; never evict debt. Persist no diagnostic payload in these +maps. Expose aggregate counts rather than key-valued metrics. + +### Alternate callers and node enforcement + +Cell and destination packet buckets include service, operator gateway, +FabricQuery, and direct operator-node probes. Each principal above has its own +packet bucket at the project rate: a service project, a FabricQuery source, or +an operator, whether through the gateway or directly; a direct probe is +charged only on a node running both `--probe-permits` and +`--require-probe-permits`. Every probe, including direct-node Execute, must obtain a +single-node, single-attempt permit from the active cell authority. For direct +operators, the node requests it on an authenticated node-only internal RPC; +the service has no access to that RPC. That admission uses the same executor +and global packet buckets. Keep a remote execution reservation until a node +acknowledges completion or its absolute expiry plus 2 s. Cancellation or a lost +RPC response alone must not free remote concurrency credit; otherwise repeated +disconnects could exceed the eight-job limit. This applies to gateway-originated +node calls too. Local RPC workers may exit immediately while a bounded timer +retains the reservation. Never wait indefinitely for a release callback. + +A permit binds epoch, request/attempt ID, node identity, canonical destination, +operation, packet allowance, and a deadline at most 30 s away. Carry permits +only on internal RPCs, authenticated by gateway mTLS; direct-node permit +responses are accepted only from that gateway. No caller-supplied permit +metadata is trusted. A node consumes a permit once and enforces its allowance +and deadline locally. Keep consumed permit IDs through expiry + 2 s in a +separate bounded set (4096 entries, 2 MiB); fail closed at capacity, never evict +a live permit to make room. The existing response-dedup cache is insufficient +because it can evict completed entries. After node restart or lost +permit-consumption state, +refuse permits for 32 s, then validate epoch and expiration before accepting +new ones; never reuse a surviving permit. Unsupported/old nodes fail closed +for aggregate-budget probes when the feature is enabled: a node reports +`probe_permits` in `Info` only when it enforces permits, and the gateway sends +a probe to no other node, failing that router with `QueryTypeUnavailable`. + +Keep the existing node-wide packet pacing and destination checks as additional +limits. Per-node pacing alone cannot substitute for aggregate charging. +Previously valid operator and FabricQuery probes can now be throttled, or refused +while the authority is unavailable; this is an intentional operational +compatibility change requiring rollout notice. Legacy wire schemas, observation +meanings, and direct operator destination exceptions remain unchanged. Legacy +reads need no packet permit. Do not silently exempt direct operator probes and +still advertise an aggregate ceiling. + +### Initial defaults and hard bounds + +Values below are proposed initial settings, subject to measured qualification. +Rates are tokens per second; packet rates count worst-case **reservations**, not +instantaneous emissions. Capacity reductions may be configured; increases +require boundary/load qualification. A changed configuration is rejected unless +all cross-field constraints hold. + +| Limit | Initial value / hard bound | +| ---------------------------------------------------- | ----------------------------------------------- | +| Service enabled | false until qualification and explicit opt-in | +| Request tokens, cell | 2/s, burst 8 | +| Request tokens, project | 0.2/s, burst 2 | +| Live service streams, cell / project | 16 / 2, including queued and draining streams | +| Shared active node jobs / per project | 8 / 2 | +| Shared queued node jobs / per project | 256 / 32 | +| Node job queue wait | 10 s, inside all existing deadlines | +| Selected routers / inventory routers | 32 / 256 | +| Packet tokens, cell | 100/s, burst 640 | +| Packet tokens, project or direct operator | 20/s, burst 640 | +| Packet tokens, destination host | 20/s, burst 640 | +| Packet tokens, destination prefix | 40/s, burst 640 | +| Maximum request lifetime / node queue plus execution | 120 s / 30 s | +| Request message / snapshot / complete | 64 KiB / 64 KiB / 64 KiB | +| Observation payload / full outcome event | 128 KiB / 144 KiB | +| Total serialized events per stream | 5 MiB, excluding transport framing | +| Buffered completed outcomes per stream | 2, at most 288 KiB | +| Blocked enqueue or network send | 2 s | +| Live attempt keys / storage | 4096 / 2 MiB | +| Bucket keys / storage | 4096 project + 16384 destination/prefix / 4 MiB | +| Error message | 256 bytes | +| Route paths / communities per path | 8 / 64 for each community kind | + +Check that each packet burst can fund at least one maximum-cost node job (20), +all rates are positive, burst/rate is at most 120 s, project caps do not exceed +cell caps, node time fits request lifetime, and output reserves cover the +maximum selected-router count. These defaults can fund 32 traceroute node +jobs, but the per-project slot +cap and 10 s queue deadline can produce failed outcomes even in a lightly +loaded cell. A fan-out ceiling is not a completion guarantee. Consumers should +select a smaller router subset when complete long-running probe coverage is +needed. Qualification must report this default behavior, not hide queue timeouts +as omitted routers or silently extend deadlines. + +For any reservation interval of length T, a bucket permits at most B + rT +packets. Dispatch-to-final-packet delay is bounded by 32 s under the failure +assumptions below. Therefore packets actually emitted in an arbitrary interval +of length T are bounded by **B + r(T + 32)**, also bounded by each node's local +pacer. For the destination-host default, a 1 s interval has an upper bound of +640 + 20 × 33 = 1300 packets across the cell. This is deliberately not a promise +of 20 packets in every wall-clock second. Qualification measures reservations +and emissions separately. A tighter instantaneous destination limit requires +central per-packet pacing and a revised contract. Because one node job +reserves and completes its packets within 32 s, the same envelope covers +failover: the 125 s quiet hold exceeds both emission delay and token debt. +Do not reset a node permit deadline on retries or transport reconnection. + +## Cancellation, delivery, and failure assumptions + +Deadlines cover discovery, admission, queueing, execution, and delivery. Freeze +each node deadline at enqueue: minimum of request expiration and now + 30 s; +its queue wait also ends at 10 s. When the queue timer expires first, emit +a router failure with reason `QueueTimeout`, not `QueueFull` or `Throttled`; +`QueueFull` is admission refusal before enqueue. If the enclosing request +deadline expires first or simultaneously, use `DeadlineExceeded` instead. +A permit may only shorten that deadline. +Stop scheduling and cancel node contexts on cancellation, stream failure, +shutdown, service disable, deadline, or loss of ownership. Disabling service +cancels existing service work and rejects new runs; legacy diagnostics remain +subject to their shared budgets and routing is unaffected. + +Release confirmed-complete execution credit before attempting result delivery; +retain uncertain remote reservations as described above. Bound completion queues; +if enqueue or send blocks for 2 s, cancel the request and close its stream. Do +not silently drop outcomes, spawn unbounded send goroutines, or keep executing +because a consumer stopped reading. Use a transport implementation that can +abort a blocked write; timing only the producer's select is insufficient. +Each selected node job may temporarily hold one 144 KiB encoded outcome during +handoff, even after releasing execution credit. Cap service job goroutines at +16 × 32 = 512, a conservative ceiling even when queue limits admit fewer: +at most 72 MiB of encoded producer payload plus 4.5 MiB in +completion queues. Require implementations to account for decoded protobuf +allocations separately and measure peak RSS; these are not total process RSS +bounds. Cap incoming diagnostic RPCs at 32 per replica, follower forwarding +streams at 16 per replica, and accepted service TLS connections at 64 per +replica. Admission occurs before spawning job goroutines. Bound transport +receive windows and read/write buffers to 64 KiB each per connection/stream, +with at most one writer per stream. Followers apply the same two-event buffer +and 2 s write bounds. Reject excess connections/RPCs rather than buffering them. +Snapshots and terminal records each have their own 64 KiB bound. +The 5 MiB stream cap is cumulative output, not an allocation target. +Reserve space for failure outcomes and complete; with these limits, +32 × 144 KiB + 2 × 64 KiB = 4736 KiB, below 5 MiB. If encoding still cannot fit, +cancel with `OutputLimitExceeded`; a transport failure still means incomplete +delivery. Diagnostic results never enter Kubernetes status or routine logs for +this service. Existing FabricQuery persistence is unaffected. + +The following are acceptance targets, not measured claims: + +| Trigger | Required bound and clock origin | +| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Explicit cancellation or healthy transport disconnect notification | Queued work removed and local workers/buffers released within 2 s of receipt; reachable node probes stop within 2 s. Uncertain remote credit lasts until expiry + 2 s. | +| Blocked client write or full result queue | Abort within 2 s of blocking; local cleanup within another 2 s. | +| Silent connection blackhole | Detect within 10 s using transport liveness; local cleanup within another 2 s. | +| Explicit ownership loss, API read failure, shutdown, service disable | Stop new service admissions/dispatches immediately on detection; reachable work canceled within 2 s. | +| Isolated node or unreachable cancellation channel | Last packet no later than node absolute deadline + 2 s skew/scheduling allowance; at most 32 s after its dispatch. | +| Queued job | Dispatch or fail within 10 s of enqueue, or earlier enclosing deadline. | +| Gateway paused/crashed without delivering cancellation | No new packet after the already-issued node deadline + 2 s; replacement admits nothing during its 125 s recovery hold. | + +Assume authenticated components are non-Byzantine, the Kubernetes API provides +consistent uncached Lease reads/CAS election, pairwise wall-clock skew is at +most 1 s, and runnable deadline checks execute within 1 s. Use monotonic timers +for local durations. Nodes recheck deadlines immediately before each send, +including after a process pause. Clock jumps beyond the assumption or an +unresponsive kernel invalidate a wall-clock guarantee; fail closed when clock +health is unknown, alarm, and record the qualification failure rather than +claiming the bound. The 2 s allowance includes skew plus scheduling delay. + +A lost node process sends nothing; a paused process must not resume sending +expired work. Cancelling an FRR socket read does not promise to cancel work +already running inside bgpd. The service permits only bounded route/summary +reads, never full-table searches; routing-impact qualification remains required. +Session revocation reaches Galactic only when its caller cancels; no bound here +includes upstream revocation detection or federation latency. + +## Wire examples + +The JSON below uses protobuf JSON field spelling for the `fabric.service.v1` +messages; timestamps and UUIDs are illustrative. The request and the mixed +result stream are fixtures in `api/fabric/service/v1/testdata`, beside a +capabilities response; the release bundle's build decodes them against its own +descriptor set, and a test decodes them with only the published packages. +A request received at 12:00:00 with the following expiration has 30 s remaining: + +```json +{ + "apiMajor": 1, + "cell": "example-cell", + "projectId": "project-a", + "requestId": "b74e19ee-926f-43dc-b03d-c29550a827ab", + "expiresAt": "2026-10-24T12:00:30Z", + "query": {"type": "QUERY_TYPE_PING", "target": "1.1.1.1", "addressFamily": "ADDRESS_FAMILY_IPV4"}, + "requiredFeatures": ["router-outcomes", "terminal-coverage"] +} +``` + +A request that also lists `aggregate-probe-budgets` is refused with +`VersionUnsupported` by a gateway that does not enforce aggregate probe budgets; +a v1 service is advertised as enabled only once all three features are served. + +A mixed result stream (one JSON object per protobuf event): + +```json +[ + {"requestId":"b74e19ee-926f-43dc-b03d-c29550a827ab","sequence":1,"snapshot":{"snapshotId":"snap-1","capturedAt":"2026-10-24T12:00:00Z","resourceVersion":"100","unscheduledPodCount":0,"routers":[{"node":"router-a","podUid":"pod-a","selected":true},{"node":"router-b","podUid":"pod-b","selected":true},{"node":"router-c","selected":false,"omittedReason":"NoCertificatePod"}]}}, + {"requestId":"b74e19ee-926f-43dc-b03d-c29550a827ab","sequence":2,"outcome":{"node":"router-a","podUid":"pod-a","completedAt":"2026-10-24T12:00:03Z","observation":{"node":"router-a","routerId":"192.0.2.1","asn":64512,"sampleTime":"2026-10-24T12:00:00Z","duration":"3s","ping":{"source":"192.0.2.1","destination":"1.1.1.1","sent":3,"received":0,"replies":[{"sequence":1,"timeout":true},{"sequence":2,"timeout":true},{"sequence":3,"timeout":true}]}}}}, + {"requestId":"b74e19ee-926f-43dc-b03d-c29550a827ab","sequence":3,"outcome":{"node":"router-b","podUid":"pod-b","completedAt":"2026-10-24T12:00:04Z","failure":{"reason":"NodeUnreachable","message":"Router did not answer"}}}, + {"requestId":"b74e19ee-926f-43dc-b03d-c29550a827ab","sequence":4,"complete":{"snapshotId":"snap-1","finishedAt":"2026-10-24T12:00:04Z","expected":3,"successful":1,"failed":1,"omitted":1,"truncatedRouters":0,"reason":"PartialResults"}} +] +``` + +Here 100% loss is one successful observation. If delivery stops after sequence +2, the consumer knows one success, one omission and one unresolved selected +router; it must not invent sequence 4 or retry router-b automatically. + +For a separate request selecting only router-a from the same three-router +inventory, mark router-b and router-c `NotRequested`, even if router-c has no +certificate. If router-a succeeds without truncation, the terminal coverage +fields are: + +```json +{ + "expected": 3, + "successful": 1, + "failed": 0, + "omitted": 2, + "truncatedRouters": 0, + "reason": "Succeeded" +} +``` + +This success describes the requested subset. If router-c was requested but +omitted for `NoCertificatePod`, the reason would instead be `PartialResults`. + +A pre-execution throttle uses a gRPC status with standard details: + +```json +{ + "code": 8, + "message": "Project admission budget exhausted", + "details": [ + {"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"Throttled","domain":"fabric-api.datumapis.com","metadata":{"scope":"project","execution_started":"false"}}, + {"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"5s"} + ] +} +``` + +## Publication, compatibility, and rollout + +#1044 publishes protobuf sources, their transitive imports, generated Go client +and server types, and a descriptor set with imports in a versioned Galactic +release asset named `fabric-service-api-.tar.gz`, containing `proto/` +sources and imports, `fabric-service-v1.pb` (descriptor set with imports), and +`README.md` with the matching Go module version and generation instructions. +Publish `SHA256SUMS` alongside it. The `publish-service-api` job of +`.github/workflows/publish.yaml` attaches both to each published release, and CI +builds and verifies the same bundle on every pull request; +`task build:service-api VERSION=` builds it locally. The `proto/` +directory omits the `google/protobuf` well-known types, which every protobuf +toolchain ships; the descriptor set includes them. Commit generated Go artifacts +using `task generate:proto`; never hand-edit them. Consumers pin a release tag +or commit of `go.datum.net/galactic`, import only `api/fabric/service/v1`, +`api/fabric/v1`, and standard protobuf/gRPC packages, or generate another +language client from the published descriptor/source bundle. No internal +canonicalizer, error parser, identity helper, or Kubernetes client is required +to call the service. The release must link these artifacts and their checksums. +The source path alone is not proof that this publication gate has passed. + +Within major v1, add optional fields/features only; reserve deleted field +numbers/names and never repurpose enums. Unknown optional fields are ignored; +unknown outcome reasons remain failures. A client requiring a new feature names +it in `required_features`; the server refuses if unavailable. An unknown event +variant prevents the client from claiming complete coverage. Breaking request, +identity, counting, or execution semantics require a new API major. Alpha +implementation must not advertise v1 capabilities until these rules pass. + +Roll out node permit support first, then gateway authority/streaming support, +then enable the aggregate budget policy for all probe paths, and finally opt in +service identities. Old nodes cannot be selected for service work; missing +permit support is an explicit capability failure. Keep customer execution off +through mixed-version qualification. A rollback disables service and cancels +active runs first; retain aggregate enforcement until probes are quiescent and +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. +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, +targets, or raw remote error text. Service disable affects diagnostics only. + +## Acceptance matrix and evidence + +Every row is required. #1042 supplies specifications and examples; later owners +supply executable tests and measured evidence. No row is satisfied by this +proposal, readiness checks, or skipped tests alone. + +| ID / owner | Scenario | Required evidence | +| ----------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| A1 / #1043 | Valid service; missing, expired, wrong-role, wrong-cell credentials; rotated CA/cert | Only allowed same-cell service methods succeed, including reused connections and streams. | +| A2 / #1043 | Forged project/forward headers, direct forward RPC, second-hop forward | Rejected before execution; trusted typed attribution survives one authenticated forward. | +| A3 / #1044 | All four diagnostics and both supported families | Typed results decode with an independently built public-API client; no internal imports. | +| A4 / #1044 | One fast and one blocked router | Fast outcome delivered while the other is pending; one outcome per selected router. | +| A5 / #1044 | Duplicate pods, missing sidecar/cert, explicit subset, fan-out cap, empty inventory, >256 routers | Fixed membership and exact counts; successful explicit subsets retain NotRequested omissions; unscheduled pod count and overflow verified. | +| A6 / #1044 | Loss, silent hops, no route, truncated paths, zebra failure | Observations remain distinguishable from backend failure; truncation affects terminal reason. | +| A7 / #1044 | Old/new client, unsupported feature/enum/major | No accidental authorization or silent semantic downgrade; published descriptor fixtures decode. | +| A8 / #1045 | Bursts and sustained competing projects, including FabricQuery sharing a project | Measured admission/node-slot ceilings, FIFO/round robin progress, per-project caps, bounded queues. | +| A9 / #1045 | Ping/trace fan-out, mixed projects and addresses in one destination prefix | Reservations obey every B+rT envelope; actual emitted packets obey B+r(T+32); no refunds/retry bypass. | +| A10 / #1045 | Operator gateway, direct-node operator, FabricQuery and service probes combined | All contribute to aggregate cell/destination ceilings; direct exceptions do not bypass charging. | +| A11 / #1045 | Replica changes, lost buckets, saturated key maps, failed API reads | Single authority, 125 s hold, empty-bucket restart, no debt eviction, no unbounded fallback. | +| A12 / #1046 | Cancel during discovery/queue/execute; shutdown/disable; blackholed connection | Timings measured from specified triggers; no work continues past node deadline + 2 s. | +| A13 / #1046 | Consumer stops reading; maximum-sized outcomes on all streams | Send/enqueue aborts and resource release meet bounds; output/buffers/goroutines stay bounded. | +| A14 / #1046 | Old owner API-isolated or paused then resumed; node restart; forwarded stream lost | Expired/stale permits rejected, old work drains, no replacement replay or duplicate permit execution. | +| A15 / #1047 | Invalid limits, config changes, clock-health failure, logging/metrics capture | Invalid configuration refused; recovery applied; no payload leakage or unbounded metric labels. | +| A16 / #1048 | Legacy operator/FabricQuery regression and upgrade/rollback | Existing schemas/results remain usable; documented new probe throttling/availability behavior verified. | +| A17 / #1048 | Real routers, independent client, combined failure and load suite | Pinned artifacts, workload, clocks, limits, resource/packet captures and cleanup instructions permit reproduction. | + +Qualification records p50/p95/max delivery and cancellation times, peak RSS, +goroutines, queue depth, bytes buffered, emitted packet counts, and limiter +charges. Initial routing-impact gate: no diagnostic-induced BGP session reset +or route loss, and p95 convergence no more than 10% slower than an otherwise +identical no-diagnostics control over at least 20 controlled convergence trials. +Record baseline variability; inability to distinguish a 10% regression is +inconclusive, not a pass. A supported target platform must pass the failure +bounds above; changing a bound or gate requires an explicit contract revision. diff --git a/docs/designs/masque-gateway.md b/docs/designs/masque-gateway.md new file mode 100644 index 000000000..ac8f92849 --- /dev/null +++ b/docs/designs/masque-gateway.md @@ -0,0 +1,431 @@ +# MASQUE Gateway Architecture + +Status: proposed. This exploratory design is separate from the implemented XDP/DSR galactic-gateway and is not deployment guidance. References to external client and connector architectures are historical context, not verified current integrations. + +## Executive Summary + +This document describes the MASQUE Gateway, an ingress component that bridges external clients to the SRv6-based Galactic VPC fabric. The gateway enables secure, NAT-traversing connectivity from diverse clients into VPC workloads using modern protocols. + +### Design Philosophy + +**Bet on the future, bridge to the present.** + +- **MASQUE as the protocol standard** - IETF-standard tunneling (RFC 9484 CONNECT-IP) +- **Iroh for connectivity** - NAT traversal, hole punching, relay infrastructure +- **SRv6 as the underlay** - Internal VPC fabric routing +- **Extensible connectors** - Support multiple protocols through a common interface + +### Key Insight: Iroh + MASQUE Convergence + +Rather than choosing between Iroh and MASQUE, the architecture leverages both: + +- **Iroh provides connectivity** - NAT traversal, hole punching, public key identity, relay infrastructure +- **MASQUE provides the protocol** - IETF standard, browser support, firewall traversal + +This means Iroh relays can evolve to speak MASQUE, giving us the best of both worlds. + +--- + +## Strategic Direction + +### Protocol Convergence + +``` +┌─────────────────────────────────────────────────────────────────────────┐ +│ Current State │ +│ │ +│ Iroh (custom protocol) MASQUE (IETF standard) │ +│ ├─ Great NAT traversal ├─ HTTP/3 based │ +│ ├─ Hole punching ├─ Browser support (WebTransport) │ +│ ├─ Public key identity ├─ Firewall friendly (port 443) │ +│ ├─ Relay infrastructure ├─ Apple/Cloudflare proven │ +│ └─ Custom QUIC protocol └─ IP tunneling (CONNECT-IP) │ +│ │ +├─────────────────────────────────────────────────────────────────────────┤ +│ Future State │ +│ │ +│ ┌─────────────────────────────────────────────────────────────────┐ │ +│ │ Iroh + MASQUE │ │ +│ │ │ │ +│ │ ┌────────────────────────────────────────────────────────────┐ │ │ +│ │ │ MASQUE Protocol Layer (IETF standard) │ │ │ +│ │ │ - CONNECT-IP for VPC ingress │ │ │ +│ │ │ - CONNECT-UDP for relay │ │ │ +│ │ │ - CONNECT-TCP for HTTP proxying │ │ │ +│ │ └────────────────────────────────────────────────────────────┘ │ │ +│ │ │ │ │ +│ │ ┌────────────────────────────────────────────────────────────┐ │ │ +│ │ │ Iroh Connectivity Layer │ │ │ +│ │ │ - NAT traversal / hole punching │ │ │ +│ │ │ - Relay fallback (now speaking MASQUE) │ │ │ +│ │ │ - Public key identity │ │ │ +│ │ │ - Connection migration │ │ │ +│ │ └────────────────────────────────────────────────────────────┘ │ │ +│ └─────────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────────┘ +``` + +### Why This Approach? + +| Question | Answer | +| -------------------- | ----------------------------------------------------------------------------- | +| Why keep Iroh? | Best-in-class NAT traversal, P2P hole punching, you're already running relays | +| Why add MASQUE? | IETF standard, browser support, firewall traversal, IP-level tunneling | +| Why not just MASQUE? | Lose Iroh's P2P capabilities and relay infrastructure | +| Why not just Iroh? | Custom protocol, no browser support, HTTP-level only | + +### Migration Path + +1. **Today**: Iroh native protocol for HTTP proxying (dev tunnels) +2. **Next**: Add MASQUE CONNECT-IP capability for VPC ingress +3. **Future**: Iroh relays speak MASQUE, unifying the protocol stack + +--- + +## System Architecture + +### High-Level View + +``` +┌─────────────────────────────────────────────────────────────────────────┐ +│ External Clients │ +│ │ +│ [Browser] [Mobile App] [CLI/Desktop] [IoT Device] │ +│ WebTransport MASQUE Iroh/MASQUE Iroh │ +│ │ +└───────────────────────────────┬─────────────────────────────────────────┘ + │ + ┌───────────▼───────────┐ + │ Iroh Relays │ + │ (MASQUE-speaking) │ + │ │ + │ - NAT traversal │ + │ - CONNECT-UDP relay │ + │ - Global distribution│ + └───────────┬───────────┘ + │ + ┌───────────▼───────────┐ + │ MASQUE Gateway │ + │ │ + │ - CONNECT-IP termination + │ - Session management │ + │ - SRv6 bridge │ + └───────────┬───────────┘ + │ + ┌───────────▼───────────┐ + │ VPC Fabric │ + │ (SRv6) │ + │ │ + │ [Workloads] │ + └───────────────────────┘ +``` + +### Components + +| Component | Purpose | +| ------------------- | -------------------------------------------------------- | +| **Iroh Relays** | NAT traversal, MASQUE CONNECT-UDP relay, global presence | +| **MASQUE Gateway** | CONNECT-IP termination, authentication, SRv6 bridging | +| **SRv6 Bridge** | Translate between client IP packets and VPC fabric | +| **Session Manager** | Track connections, enforce policies, allocate addresses | + +--- + +## Protocol Stack + +### MASQUE Protocol Family + +| Protocol | RFC | Purpose | +| ----------- | ------------ | --------------------------------------------------- | +| CONNECT-IP | RFC 9484 | Full IP tunnel (VPN mode) - primary for VPC ingress | +| CONNECT-UDP | RFC 9298 | UDP proxying - used for relay | +| CONNECT-TCP | HTTP CONNECT | TCP proxying - HTTP-level access | + +### Connection Flow + +``` +Client Relay Gateway VPC + │ │ │ │ + │──Iroh hole punch────────►│ │ │ + │ (direct if possible) │ │ │ + │ │ │ │ + │──MASQUE CONNECT-UDP─────►│ (if relay needed) │ │ + │ │ │ │ + │──────────────────────────┼──MASQUE CONNECT-IP──────►│ │ + │ │ │ │ + │◄─────────────────────────┼──ADDRESS_ASSIGN──────────│ │ + │◄─────────────────────────┼──ROUTE_ADVERTISEMENT─────│ │ + │ │ │ │ + │══════════════════════════╪══IP Packets══════════════╪═════SRv6═══════════►│ + │ │ │ │ +``` + +--- + +## Resource Model + +Aligned with the Datum Connectors proposal (external design, not included in this repository). + +### Resource Relationships + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ Control Plane │ +│ │ +│ ┌─────────────┐ ┌─────────────────────┐ ┌─────────────┐ │ +│ │ Connector │─────►│ ConnectorAttachment │◄─────│ VPC │ │ +│ │ (client) │ │ (binding) │ │ (network) │ │ +│ └─────────────┘ └─────────────────────┘ └─────────────┘ │ +│ │ │ │ │ +│ ▼ ▼ ▼ │ +│ ┌─────────────┐ ┌─────────────────┐ ┌─────────────┐ │ +│ │ Connector │ │ VPCIngressPoint │ │VPCAccessPol │ │ +│ │Advertisement│ │ (gateway config)│ │ icy │ │ +│ └─────────────┘ └─────────────────┘ └─────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Key Resources + +| Resource | From | Purpose | +| ------------------------ | ------------------- | ----------------------------------------------- | +| `Connector` | Connectors proposal | Represents client device, defines capabilities | +| `ConnectorAdvertisement` | Connectors proposal | Networks reachable through connector (outbound) | +| `ConnectorAttachment` | This design | Binds connector to VPC (inbound) | +| `VPCIngressPoint` | This design | Gateway configuration per VPC | +| `VPCAccessPolicy` | This design | Fine-grained authorization rules | + +### Example: Connector with MASQUE Capability + +```yaml +apiVersion: networking.datumapis.com/v1alpha1 +kind: Connector +metadata: + name: developer-laptop +spec: + connectorClassName: datum-connect + capabilities: + - type: MASQUE + enabled: true + - type: CONNECT-IP + enabled: true + - type: CONNECT-UDP + enabled: true +status: + connectionDetails: + type: PublicKey + publicKey: + id: 2ovpybgj3snjmchns44pfn6dbwmdiu4ogfd66xyu72ghexllv6hq + homeRelay: https://relay.datum.net +``` + +### Example: Attaching Connector to VPC + +```yaml +apiVersion: networking.datumapis.com/v1alpha1 +kind: ConnectorAttachment +metadata: + name: developer-to-vpc +spec: + connectorRef: + name: developer-laptop + vpcRef: + name: production-vpc + ipAllocation: + mode: Dynamic + allowedRoutes: + - 10.0.0.0/16 +status: + assignedIP: 10.0.100.50 + phase: Connected +``` + +--- + +## SRv6 Integration + +### Bridge Operation + +The gateway translates between client IP packets and SRv6-encapsulated packets: + +``` +Client IP Packet SRv6 Packet (to VPC) +┌─────────────────┐ ┌─────────────────────────┐ +│ src: 10.0.100.50│ SRv6 │ IPv6: fc00::gateway │ +│ dst: 10.0.2.100 │ ──────────► │ → fc00::vpc:node │ +│ [payload] │ Bridge │ SRH: [fc00::vpc:node] │ +└─────────────────┘ │ [original IP packet] │ + └─────────────────────────┘ +``` + +### Bridge Modes + +| Mode | Performance | Use Case | +| ------------------- | ------------- | -------------------------------- | +| Kernel (VRF + seg6) | Good | Default, universal compatibility | +| eBPF/XDP | High | Production gateways | +| AF_XDP | Highest | Maximum throughput requirements | + +--- + +## Current Iroh Architecture Integration + +### Today's Architecture (datum-connect) + +``` + ┌─────────────────────────┐ + │ Iroh Relay │ + │ (iroh native protocol) │ + └───────────┬─────────────┘ + │ +┌──────────────┐ │ ┌──────────────┐ +│ datum-connect│◄═══════════════╪═══════════════►│ Envoy │ +│ (desktop) │ Iroh QUIC │ │ Gateway │ +│ │ │ │ │ +│ ListenNode │ │ │ Iroh Gateway │ +│ │ │ │ (sidecar) │ +└──────────────┘ │ └──────────────┘ + │ + HTTP Proxying + (absolute-form requests) +``` + +### Evolution to MASQUE + +``` + ┌─────────────────────────┐ + │ Iroh Relay │ + │ (MASQUE CONNECT-UDP) │ ◄── Protocol change + └───────────┬─────────────┘ + │ +┌──────────────┐ │ ┌──────────────┐ +│ datum-connect│◄═══════════════╪═══════════════►│ MASQUE │ +│ │ MASQUE │ │ Gateway │ +│ │ CONNECT-IP │ │ │ +│ + VPC attach │ │ │ + SRv6 bridge│ +└──────────────┘ │ └──────────────┘ + │ + IP Tunneling + HTTP Proxying +``` + +### What Changes + +| Component | Current | Future | +| -------------------- | ------------------------- | --------------------------------- | +| Relay protocol | Iroh native | MASQUE CONNECT-UDP | +| Application protocol | Iroh HTTP-connect | MASQUE CONNECT-IP/TCP | +| Gateway | Iroh Gateway (HTTP proxy) | MASQUE Gateway (IP tunnel + HTTP) | +| Client | datum-connect (Iroh only) | datum-connect (MASQUE capability) | +| VPC integration | None | ConnectorAttachment + SRv6 | + +### What Stays + +| Capability | Preserved | +| ------------------------- | ---------------------------------- | +| NAT traversal | Yes - Iroh's hole punching | +| Relay infrastructure | Yes - your relays, new protocol | +| Public key identity | Yes - connection details unchanged | +| P2P direct connections | Yes - hole punch when possible | +| Control plane integration | Yes - same Connector CRD | + +--- + +## Client SDK (datum-connect) + +### Capabilities + +The datum-connect client gains MASQUE capability: + +```yaml +# Connector status shows available capabilities +status: + capabilities: + - type: MASQUE + conditions: + - type: Ready + status: "True" + - type: CONNECT-IP # VPC ingress + conditions: + - type: Ready + status: "True" + - type: CONNECT-TCP # HTTP proxying (current) + conditions: + - type: Ready + status: "True" +``` + +### CLI Usage + +```bash +# Current: HTTP proxying (unchanged) +datum-connect tunnel --local 8080 --name my-tunnel + +# New: VPC attachment +datum-connect attach --vpc production-vpc + +# Show status +datum-connect status +# Connector: developer-laptop (Ready) +# Protocol: MASQUE +# VPC Attachments: +# - production-vpc: 10.0.100.50 (Connected) +# HTTP Tunnels: +# - my-tunnel: localhost:8080 → https://my-tunnel.example.com +``` + +--- + +## Implementation Phases + +### Phase 1: Foundation + +- MASQUE CONNECT-IP listener in gateway +- `ConnectorAttachment` and `VPCIngressPoint` CRDs +- Kernel-mode SRv6 bridge +- MASQUE capability in datum-connect + +### Phase 2: Relay Evolution + +- Iroh relays speak MASQUE CONNECT-UDP +- Unified protocol stack +- Browser connectivity via WebTransport + +### Phase 3: Production + +- eBPF/XDP bridge acceleration +- Multi-gateway HA +- Mobile SDKs + +--- + +## Open Questions + +1. **Iroh upstream changes**: Does Iroh need modifications to support MASQUE, or can we layer it? + +2. **Relay protocol migration**: How do we migrate existing relays from Iroh-native to MASQUE? + +3. **Browser path**: WebTransport speaks HTTP/3 - is that sufficient, or do we need full MASQUE in browsers? + +4. **Gateway base**: Build on quic-go (lightweight) or Envoy (battle-tested)? + +--- + +## References + +### Internal +- Datum Connectors proposal: the original relative reference is unavailable in this repository. +- Galactic VPC v2 architecture: the original design reference is unavailable. Use the [current system diagrams](../architecture/README.md) for implemented architecture. + +### MASQUE +- [RFC 9484: CONNECT-IP](https://datatracker.ietf.org/doc/rfc9484/) +- [RFC 9298: CONNECT-UDP](https://datatracker.ietf.org/doc/rfc9298/) +- [Cloudflare: Zero Trust WARP with MASQUE](https://blog.cloudflare.com/zero-trust-warp-with-a-masque/) + +### Connectivity +- [Iroh Documentation](https://www.iroh.computer/docs) +- [Datum Connect](https://github.com/datum-cloud/datum-connect) + +### SRv6 +- [RFC 8986: SRv6 Network Programming](https://datatracker.ietf.org/doc/html/rfc8986) diff --git a/docs/designs/private-service-connect.md b/docs/designs/private-service-connect.md new file mode 100644 index 000000000..419670de6 --- /dev/null +++ b/docs/designs/private-service-connect.md @@ -0,0 +1,529 @@ +# Private Service Connect + +Status: partially implemented design. Direct endpoint routes, producer selection and opt-in same-family frontend translation exist. Use the [private-service guide](../router/private-service-routes.md) for current behavior. The qualification gaps recorded below remain distinct from implementation availability. + +- [Summary](#summary) +- [Motivation](#motivation) + - [Goals](#goals) + - [Non-goals](#non-goals) +- [Proposal](#proposal) + - [User stories](#user-stories) + - [Notes, constraints, and caveats](#notes-constraints-and-caveats) + - [Risks and mitigations](#risks-and-mitigations) +- [Design Details](#design-details) + - [System architecture](#system-architecture) + - [Resource model and ownership](#resource-model-and-ownership) + - [Endpoint declaration](#endpoint-declaration) + - [Consumer access and frontend translation](#consumer-access-and-frontend-translation) + - [Validation and compatibility](#validation-and-compatibility) + - [Reconciliation and selection](#reconciliation-and-selection) + - [Status and lifecycle](#status-and-lifecycle) + - [Data plane](#data-plane) + - [Internal DNS integration](#internal-dns-integration) +- [Production readiness review questionnaire](#production-readiness-review-questionnaire) +- [Implementation history](#implementation-history) +- [Drawbacks](#drawbacks) +- [Alternatives](#alternatives) +- [Infrastructure needed](#infrastructure-needed) + +## Summary + +Private Service Connect gives a consumer VPC private access to a published +service in a producer VPC. Consumers use a stable private endpoint while the +platform selects an authorized, eligible producer. A shared service can serve +many VPCs without a separate deployment for each consumer. + +## Motivation + +Platform services need private connectivity from isolated consumer networks. +Connecting entire VPCs exposes more of the producer network than a service +requires. Private Service Connect grants access to a specific service tuple and +keeps network identity trustworthy when consumers use overlapping addresses. + +The [Internal DNS overview](https://github.com/datum-cloud/enhancements/blob/docs/internal-dns-product-proposal/architecture/deliver/dns/internal-dns/README.md) +describes the first integration: the same resolver address in each VPC reaches +that network's isolated DNS context through a shared DNS fleet. + +### Goals + +- Give workloads private access to authorized services through their existing + network configuration. +- Share producer capacity across consumer VPCs with overlapping addresses. +- Preserve consumer identity through local delivery, remote delivery, and replies. +- Withdraw access on resource deletion and stop selecting unhealthy producers. + +### Non-goals + +- Connecting entire producer and consumer networks. +- Discovering service backends or performing application health checks in Galactic. +- Defining customer-published services or their management experience. +- Defining DNS contexts, record publication, or resolver cache isolation. + +## Proposal + +A service owner publishes an endpoint and maintains its availability. Trusted +networking integration authorizes consumer attachments and assigns a private +frontend. Galactic delivers only the permitted address, protocol, and port to an +eligible producer. Service health and network programming are separate readiness +requirements. + +### User stories + +- A workload uses the network's inherited DNS resolver without selecting a + resolver deployment or configuring a service-specific route. +- Two VPCs use the same frontend address and receive their own service context. +- A service owner adds ready producers to shared capacity and withdraws unhealthy + producers without changing the consumer-facing address. + +### Notes, constraints, and caveats + +Endpoint addresses must be reachable and accepted by the producer listener. +Publishing an endpoint does not configure the producer address. The initial +frontend design translates within one address family; cross-family translation +requires a separate design. Addresses in the manifests are illustrative. + +A new consumer creates endpoint and authorization data, not a producer +workload. Producer reselection does not promise continuity for established +connections. Regional placement and fallback are explicit policies. + +### Risks and mitigations + +- Incorrect access: protect integration credentials and selection labels, and + pin authorization to the live consumer VPC identity. +- Stale programming: reconcile current resource lifetimes after restart and + define a bounded revocation policy before rollout. +- Endpoint advertised too early: require service health and verified consumer + and producer path programming before publishing workload configuration. + +## Design Details + +### System architecture + +Networking integration translates project intent into location-specific network +state. Galactic programs each node from its edge API. Traffic uses the applied +data plane without querying project APIs or Karmada per packet. + +```mermaid +flowchart TB + P["Producer project
Service and network intent"] + C["Consumer project
Network and access intent"] + I[Trusted networking integration] + K[Karmada network projections] + E["Edge API
VPCs, attachments, endpoints, policies"] + G[Galactic node controllers] + P --> I + C --> I + I -->|Location-specific desired state| K + K --> E + E -->|Local identities and service policy| G +``` + +Project APIs own intent. Karmada owns placement and projected desired state. +The edge owns local VPC and attachment identities. Networking controllers return +selected edge observations through federation and project consumer status. +The integration resolves live edge identities when creating service policies; +project and propagated object UIDs are separate lifetimes. + +The networking APIs live in the +[network repository](https://github.com/datum-cloud/network/blob/main/api/v1alpha1/serviceroute_types.go). +Galactic owns route compilation and packet handling. The +[private-service routing reference](../router/private-service-routes.md) +documents packet handling for this contract. This enhancement defines the +resource design; the network repository holds its schemas, and Galactic holds +its controller and data-plane implementation. + +### Resource model and ownership + +The design separates service publication from consumer authorization: + +- `ServiceEndpoint` describes what a producer offers: one destination address, + protocol, and port, the attachments that can serve it, and the delivery policy. + Declaring an endpoint grants no consumer access. +- `ServiceRoutePolicy` describes who can use that endpoint: selected consumer + attachments, their VPC lifetime, permitted traffic, and an optional frontend. + The policy references the service contract rather than duplicating producer + selection or listener configuration. + +This separation lets service owners change eligible producers while networking +integration changes consumer access independently. Several policies in one +namespace can reference the same endpoint. Different consumer namespaces receive +local descriptors that select shared producer attachments; the descriptors are +control-plane data, not service deployments. + +```mermaid +flowchart LR + subgraph C[Consumer edge namespace] + R[ServiceRoutePolicy] + E[ServiceEndpoint] + A[Consumer attachments] + R -->|serviceRef| E + R -->|Authorizes selected consumers| A + end + subgraph S[Service edge namespace] + P[Eligible producer attachments] + end + E -->|Selects producers| P +``` + +Both resources live in the edge API. `serviceRef` resolves in the policy's +namespace. Producer references carry their attachment namespace; producer +selectors can match attachments in the service namespace. Cross-namespace +producer selection is a privileged platform operation, not a tenant permission. + +Project APIs and federation hold intent and placement. Trusted integration +projects endpoint descriptors, resolves edge VPC names and API-assigned UIDs, +and creates consumer policies. A project UID is not an edge VPC UID. The service +owner supplies the exact service tuple and eligible producers. Only platform +controllers can write these resources or the labels that select their attachments. + +The complete API design includes `consumerVPCRef` and `frontend` on +`ServiceRoutePolicy`. Those fields extend the direct-delivery implementation; +they are present in the local prototype and remain proposed for the released +schema. This document defines both resources, including their current fields +and proposed extensions. + +### Endpoint declaration + +An endpoint names one directly delivered service tuple. Keeping one transport +per endpoint makes publication, authorization, and failure reporting explicit. +DNS uses separate UDP and TCP endpoints. `serviceClass` identifies the capability +for integration and operations; it is not an authorization role or backend lookup. + +The owner must make the endpoint address reachable through every selected +producer attachment and accepted by its listener. The address can carry a +service-defined context, as Internal DNS does. Galactic delivers that address +without choosing an application backend. Replica selection chooses the network +attachment that receives the tuple. + +The following descriptor lives in `consumer-a`. It selects shared DNS producers +through platform-managed labels, including producers in the DNS service's edge +namespace. Each eligible producer must serve this destination and DNS context. + +```yaml +apiVersion: galactic.datumapis.com/v1alpha1 +kind: ServiceEndpoint +metadata: + name: context-a-dns-udp + # Local descriptor beside consumer policies; producers can be elsewhere. + namespace: consumer-a +spec: + # Identifies the capability for integration; does not grant access. + serviceClass: internal-dns + # Exact service-side destination after frontend translation. + # The service owner makes it routable and accepted by each producer listener. + address: "fd70:100::10" + # One service port, from 1 through 65535. + port: 53 + # One transport per endpoint; use a separate descriptor for TCP. + # Supported protocol values are lowercase udp and tcp. + protocol: udp + # PreferNodeLocal selects a local producer, or a ready remote producer. + # NodeLocal requires a producer on the consumer's node. + deliveryMode: PreferNodeLocal + # Optional placement boundary; empty imposes no region restriction. + # Trusted placement and selectors establish actual location membership. + region: us-central-1 + # Select shared replicas using protected, platform-managed labels. + # Every selected producer must serve this tuple and service context. + # Alternatively, use attachmentRef with namespace and name for one producer. + # Exactly one of attachmentSelector or attachmentRef must be set. + attachmentSelector: + matchLabels: + networking.datumapis.com/service: internal-dns + topology.kubernetes.io/region: us-central-1 +``` + +The address is not a Kubernetes Service frontend or an address from which +Galactic discovers backends. An endpoint has one transport tuple; DNS requires +separate UDP and TCP descriptors. Create `context-a-dns-tcp` with the same +address, selector, placement, and port, and `protocol: tcp`. + +### Consumer access and frontend translation + +A policy applies the endpoint contract to a consumer set. It can authorize many +attachments in one VPC. The proposed lifetime reference prevents a recreated +VPC with the same name from inheriting access. The frontend belongs to this +consumer policy so different VPCs can use the same address for different service +destinations without changing the producer contract. + +The policy references the endpoint in its own namespace. `consumerVPCRef` pins +the VPC named `application-vpc` in `consumer-a` to its live edge UID. The selector +narrows eligible attachments; it does not replace the VPC identity check. + +```yaml +apiVersion: galactic.datumapis.com/v1alpha1 +kind: ServiceRoutePolicy +metadata: + name: application-vpc-dns-udp + # Policy, referenced endpoint, and consumer VPC share this edge namespace. + namespace: consumer-a +spec: + # References the service contract in this policy's namespace. + serviceRef: + name: context-a-dns-udp + # Proposed: pins authorization to one live edge VPC lifetime. + consumerVPCRef: + # Resolved against the VPC in the policy namespace. + name: application-vpc + # API-assigned edge VPC UID; recreation requires new authorization. + # A project or propagated source UID cannot replace this identity. + uid: "22222222-2222-4222-8222-222222222222" + # Select consumers through protected labels. + # Galactic also verifies membership in the live, pinned VPC. + attachmentSelector: + matchLabels: + networking.datumapis.com/vpc-uid: "22222222-2222-4222-8222-222222222222" + # Allowed tuples must match the endpoint's declared protocol and port. + # Omit this list to use the endpoint's tuple. + protocolPorts: + - protocol: udp + port: 53 + # Optional consumer placement boundary; must agree with a scoped endpoint. + # This field does not authorize cross-region fallback. + region: us-central-1 + # Proposed: consumer-facing address translated to the endpoint destination. + frontend: + # Same address family as the endpoint; restored as the reply source. + # Different VPCs can use this address with different service destinations. + address: "fd53::53" +``` + +Create a matching TCP policy referencing `context-a-dns-tcp` and permitting +`tcp/53`, with the same VPC reference, selector, region, and frontend. UDP and TCP +must satisfy the same authorization and readiness requirements. + +A second VPC uses the same `fd53::53` frontend. Its descriptors and policies live +in its own namespace, pin its own VPC UID, and use another service destination, +such as `fd70:100::20`. The producer deployment remains shared. DNS maps those +destinations to different contexts; Galactic does not interpret that mapping. + +### Validation and compatibility + +The proposed frontend contract requires a complete `consumerVPCRef` with name +and UID. Galactic must resolve that live VPC and reject missing or mismatched +identities. Each selected consumer must belong to that VPC and have the expected +programmed network identity. Platform-managed labels alone cannot grant access. + +Admission and reconciliation must enforce: + +- Exactly one endpoint attachment selection method. +- Valid frontend and endpoint IP addresses in the same family. +- Ports from 1 through 65535 and supported transport values. +- A policy's allowed tuples within its endpoint's declared tuple. +- Consistent placement and current producer and consumer identities. +- No contradictory destination mappings for the same consumer attachment, + frontend address, protocol, and port. Policy order must not decide access. + +Conflict detection across policies still requires implementation review. Endpoint +and policy regions must agree when both are set. Trusted placement and selectors +establish location membership; a region string alone is not identity proof. + +Omitting `frontend` preserves direct delivery to the endpoint address. Existing +policies without the new fields retain their existing contract; new translated +access requires the lifetime pin. Frontend translation remains disabled by +default until API and data-plane compatibility are qualified. + +### Reconciliation and selection + +Each Galactic node watches policies, endpoint descriptors, VPCs, and attachments +in the edge API. It derives current desired programming through these steps: + +1. Resolve `serviceRef`, validate the service tuple and placement, and resolve + the pinned consumer VPC name and UID. +2. Select producer attachments with current-generation `Ready` and `Programmed` + status, a node, allocated network identities, and a host interface. For a + `Single` endpoint, service owners must ensure selected producers are also + healthy for the declared tuple; a `Spread` endpoint's producers are probed + by their nodes. +3. Select consumer attachments through protected labels and verify their live + VPC membership and programmed attachment identity. +4. Choose producers for each consumer. A `Single` endpoint gets one, chosen by + a deterministic attachment ordering, preferring a local producer. A `Spread` + endpoint gets every producer on the consumer's node as one set: new flows go + to the ones its health check has not found `Unhealthy`, each TCP connection + stays with its first producer, and each UDP datagram picks its own. In both, + `NodeLocal` leaves the consumer without a path if no local producer is + available, and `PreferNodeLocal` permits one ready remote producer. +5. Program this node's consumer and producer paths. Remote paths require both + sides' trusted attachment identities, matching service grants, and return + routing. Grants bind the policy, endpoint, and attachment lifetimes to the + permitted tuple and frontend. +6. Remove obsolete programming when selection, references, or lifetimes change. + Restart reconciliation rebuilds current desired state and sweeps stale state. + +No eligible producer means no usable path; it does not make otherwise valid +policy intent invalid. A missing endpoint or mismatched VPC identity invalidates +the contract and requires stale access to be removed. An unresolved remote path +prevents that node from serving even if the shared policy remains accepted. + +Service owners of a `Single` endpoint withdraw unhealthy producers through the +endpoint's selection contract. Galactic's attachment readiness checks establish +network eligibility; they do not substitute for service health. A `Spread` +endpoint's producers are probed over TCP by their own node, which publishes +each decision in the endpoint's `status.producers`; see +[Private service routes](../router/private-service-routes.md#several-producers-on-one-node). + +### Status and lifecycle + +`ServiceRoutePolicy.status.observedGeneration` identifies the spec generation +that its conditions describe. `Accepted` reports valid configuration; it does +not prove that every required node has programmed the path. `ServiceEndpoint` +does not provide a listener-health status contract. + +```mermaid +flowchart TB + A[Authorization is current] --> R[Private endpoint ready] + N[Consumer and producer paths programmed] --> R + S[Service address and listener healthy] --> R + R --> W[Publish endpoint configuration to workloads] +``` + +The release needs node-level programming acknowledgments and a service-owned +health signal before integration advertises the frontend. Their API shape +remains a design decision; this proposal does not add a `Programmed` or `Ready` +condition that the existing controllers cannot verify. + +Changing an endpoint tuple or producer selection re-evaluates its referencing +policies. Explicit `protocolPorts` must still match; policies that omit them +follow the endpoint's declared tuple. Deleting an endpoint leaves references +unusable and removes their programming. Deleting a policy removes its access +without deleting the shared producer service or consumer attachments. + +Service owners withdraw unhealthy producers. Networking integration deletes +access when the consumer or service is deleted. Galactic removes obsolete +programming and reconciles current lifetimes after restart. Recreated VPCs and +endpoints must not inherit previous grants. The current route policy has no +authorization policy. Persistent access requires explicit revocation; bounded +access requires a renewed deadline. + +### Data plane + +Galactic classifies traffic by the trusted consumer attachment and endpoint +tuple. The proposed frontend translation changes the destination to the +authorized service address and restores the frontend on replies. Consumers use +their ordinary gateway; Galactic does not install a service-specific guest route. + +```mermaid +sequenceDiagram + participant W as Workload + participant C as Consumer node + participant P as Producer node + participant S as Service + W->>C: Packet to private frontend + Note over C: Authorize tuple
Translate target + alt Producer is on the same node + C->>S: Deliver through producer attachment + S-->>C: Reply + else Producer is on another node + C->>P: Authorized SRv6 service path + P->>S: Deliver through producer attachment + S-->>P: Reply + P-->>C: SRv6 return path + end + C-->>W: Restore frontend address and reply +``` + +`NodeLocal` requires a producer on the consumer's node. `PreferNodeLocal` uses +a local producer when available and otherwise selects a ready remote producer. +A `Single` endpoint's selection is deterministic, and it rejects multiple ready +producers in the same node and VPC because its one-target route cannot +distinguish them. A `Spread` endpoint routes to a set of up to 16 producers on +the consumer's node instead. + +Overlapping consumer addresses remain scoped to their attachments. Remote +delivery requires matching platform-programmed service grants. Tenant-supplied +addresses or packet metadata cannot grant access. The design relies on trusted +attachment state and protected fabric delivery. + +The current return path rejects concurrent flows from different consumers that +produce the same reply tuple on one producer attachment. Internal DNS separates +service-side destinations by context. General shared endpoints need equivalent +disambiguation for overlapping consumers that use identical tuples. + +This path is separate from Galactic's gateway `ServiceVIPBinding` mechanism. +Publishing a private endpoint does not create gateway load-balancer state. + +### Internal DNS integration + +Internal DNS uses a well-known frontend address in each consumer VPC. Its +networking integration maps that frontend to an authorized service-side +destination for the network's DNS context. Galactic enforces the private path; +DNS interprets the destination and isolates zones and answers. + +DNS contexts, record publication, health-aware discovery, and resolver access +belong to the [DNS component design](https://github.com/datum-cloud/dns-operator/blob/docs/internal-dns-architecture/docs/architecture/internal-dns/README.md). +The generic private-service path does not interpret DNS resources. + +## Production readiness review questionnaire + +The enhancement remains provisional. Complete and approve the release targets +and outstanding contracts before changing it to implementable. + +### Feature enablement and rollback + +Keep frontend translation disabled by default. Enable it only with compatible +API schemas and integration controllers. Disabling it can interrupt consumers +that depend on the frontend; validate cleanup and recovery before rollout. + +### Rollout, upgrade, and rollback planning + +Qualify mixed controller versions, node restart, policy replay, deletion, and +upgrade followed by rollback and reenablement. Avoid advertising endpoints while +required nodes lack the configuration. No existing API removal is proposed. + +### Monitoring requirements + +Observe acceptance, node programming, producer health, selected traffic, +translation failures, and revocation lag separately. Define availability, +latency, and revocation targets. Consumer status must distinguish valid intent +from a usable endpoint; its readiness projection remains to be designed. + +### Dependencies + +Networking integration supplies edge intent and authorization. VPC and +attachment controllers and Galactic supply network identity and packet paths. +Remote delivery requires the protected fabric and service grants. Service owners +supply address reachability, listener configuration, and health eligibility. + +### Scalability + +Endpoint and policy counts grow with consumer destinations and transports; +producer workload counts grow with shared capacity. Bound route and reverse-flow +maps, API reconciliation cost, configuration churn, and connection state before +release. Exhaustion must fail closed and produce an observable failure. + +### Troubleshooting + +An API outage can delay updates and revocation while nodes retain applied state. +Define retention and revocation budgets. Diagnose invalid policies, missing VPCs, +unready producers, path-programming failures, and reply collisions separately. +Verify the declared service destination and return path before investigating the +application protocol. + +## Implementation history + +Initial proposal: [Galactic PR #798](https://github.com/datum-cloud/galactic/pull/798). +Local kernel tests cover local and remote translation and authorization. Live +Internal DNS queries validate the local path. Normal router/CNI lifecycle, +independent edge APIs, remote live DNS traffic, scale, and regional failures +remain unqualified. + +## Drawbacks + +Distinct service destinations and per-consumer policies add address allocation +and lifecycle work. Stateful reply handling consumes node capacity and limits +connection continuity during producer changes. + +## Alternatives + +VPC peering grants broader connectivity and requires additional routing policy. +Per-consumer service deployments increase operating cost. A single shared +service destination needs another trustworthy identity mechanism and an +unambiguous return path for overlapping consumers. + +## Infrastructure needed + +Release the network API extensions and compatible Galactic controllers. Provide +shared producer attachments, service address allocation and reclamation, +protected integration permissions, endpoint readiness reporting, and staging +coverage for local and remote traffic. diff --git a/docs/edge/README.md b/docs/edge/README.md new file mode 100644 index 000000000..e83b91f70 --- /dev/null +++ b/docs/edge/README.md @@ -0,0 +1,11 @@ +# Galactic Edge + +Galactic Edge gives providers authorized attachments to tenant VPCs and controls which provider may forward each prefix. The provider owns its protocol and client sessions; Galactic owns attachment isolation, policy, route lifetime and forwarding ownership. + +- [Provider contract](provider-contract.md): resources, writers, lifecycle, timing assumptions and required failure evidence. +- [Troubleshooting](troubleshooting.md): conditions, Events, metrics and locating the current prefix holder. +- [Foundation metrics](../observability/edge.md): lifecycle and forwarding-gate measurements. +- [Design record](../designs/galactic-edge.md): motivation and design alternatives. +- [Generated API](../api/galactic.md): exact resource fields and validation. + +Implemented code and a conformance harness are not proof of production qualification. Review the contract's open items and the evidence for the candidate release before relying on capacity or timing targets. diff --git a/docs/edge/provider-contract.md b/docs/edge/provider-contract.md new file mode 100644 index 000000000..652037ce6 --- /dev/null +++ b/docs/edge/provider-contract.md @@ -0,0 +1,452 @@ +# Galactic Edge provider contract + +Status: implementation contract. The core and node implementations consume these resources and lifecycle rules. The failure-test matrix specifies required evidence, not a claim that every environment has passed. See [open qualification items](#open-items) before relying on timing or capacity targets. + +Tracking issue: [Define the internal provider contract (#993)](https://github.com/datum-cloud/galactic/issues/993), part of [#992](https://github.com/datum-cloud/galactic/issues/992). + +This document is the contract the [Galactic Edge foundation](../designs/galactic-edge.md) is built to. It fixes the resources, writers, state transitions, timing bounds and acceptance tests that the implementation milestones (#994 to #1002) follow. Where it names existing code, it describes that code; where it names a resource or process that does not exist yet, it is a decision, not a description. + +- [Decisions](#decisions) +- [Resources](#resources) +- [Provider interface](#provider-interface) +- [Lifecycle](#lifecycle) +- [Timing and failure bounds](#timing-and-failure-bounds) +- [Foundation resources and their writers](#foundation-resources-and-their-writers) +- [Failure-test matrix](#failure-test-matrix) +- [Open items](#open-items) + +## Decisions + +| Area | Decision | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Contract representation | Kubernetes resources in `galactic.datumapis.com/v1alpha1`. A provider talks only to the cell's API server; there is no provider RPC. | +| Contract version | `v1alpha1`. Capabilities are versioned separately: `SocketAccess/v1`, `PacketAccess/v1`, `PrefixReachability/v1`. | +| Provider authority | The API server's authentication of the provider pod's bound ServiceAccount token, checked by a ValidatingAdmissionPolicy (see [Admission policy](#admission-policy)). A pod-UID field a provider writes is only checked against the token, never trusted on its own. | +| Control packaging | Admission, allocation and publication run in `galactic-controller --role=cell`, leader-elected, one writer per cell. | +| Node packaging | A new `galactic-edge` DaemonSet on nodes labeled `galactic.datumapis.com/node=edge` and `galactic.datumapis.com/edge=enabled`. The `edge=enabled` label is new, and [node labels](../operations/node-labels.md) gains it when the DaemonSet ships. `galactic-edge` is the only process that changes host state for an edge attachment. It writes only the CNI datapath's maps under `/sys/fs/bpf/galactic`, and never opens `/sys/fs/bpf/galactic-edge`, which is `galactic-gateway`'s pin directory despite the name (`internal/plumbing/ebpf/edgeattach/attach.go:38`). | +| Provider privilege | None on the host. A provider pod gets no host namespace, hostPath, `NET_ADMIN` or BPF access. It opens the packet device the node agent created in its own network namespace. | +| Claim store | The cell's API server, compare-and-swap on `resourceVersion` with a UID precondition, as `internal/edge/claim` requires. Claims never span cells. | +| Node-local write fence | `internal/edge/ownership`, with its state and lock files in the hostPath `/var/lib/galactic-edge/ownership`, shared by every process that writes a fenced scope on the node. | +| Forwarding gate | A new map of the CNI datapath, with one row per edge host link and per accepted prefix holding a `CLOCK_BOOTTIME` deadline. The datapath compares it with `bpf_ktime_get_boot_ns` on every packet, the pattern `serviceroutemap` already uses for authorization deadlines. | +| Allocation | Attachment addresses come from the service's client pool, allocated by the leader of `galactic-controller`. Delegated client prefixes are routes the provider requests inside that pool; the prefix conflict check makes them exclusive. No new host table or uSID Argument is allocated: an edge attachment joins the VPC's canonical host VRF. | + +## Resources + +All resources are in `galactic.datumapis.com/v1alpha1`. Object names that carry identity are derived, so a retried create lands on the same object. + +| Kind | Scope | Name | Purpose | +| ---------------- | --------- | ----------------------------------- | --------------------------------------------------------------------------- | +| `EdgeProvider` | Cluster | Operator's choice | Registration: contract and capability versions, ServiceAccounts, privilege. | +| `EdgeService` | Namespace | Platform authority's choice | Grant: one provider, one gVPC, prefixes, client pool, validity. | +| `EdgeInstance` | Namespace | `ei-` + pod UID | One running provider process. | +| `Lease` | Namespace | The instance's name | The instance's liveness lease, a `coordination.k8s.io/v1` Lease it owns. | +| `EdgeAttachment` | Namespace | `ea-` + pod UID + `-` + service UID | One instance's isolated connection to the service's gVPC. | +| `EdgeRoute` | Namespace | `hash(gVPC UID, prefix)` | One prefix's forwarding claim and publication. | +| `EdgeRouteIndex` | Namespace | gVPC UID | Core's record of every accepted route in one gVPC; serializes acceptance. | + +`EdgeInstance`, its `Lease`, `EdgeAttachment` and `EdgeRoute` live in the provider's namespace. `EdgeService` and `EdgeRouteIndex` live in the namespace of the gVPC they reference. + +Core finds a route by its spec, never by its name. A route's name only has to be the same in every instance of one provider, so that they contend for a prefix through one object; the hash is the provider's choice. + +### Fields and writers + +A field not listed is read-only to everyone but the control plane that owns the resource. "Core" is `galactic-controller --role=cell`; "node" is `galactic-edge` on the attachment's node. + +| Resource and field | Writer | Rule | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `EdgeProvider.spec` | Operator | Contract versions, capabilities, ServiceAccounts, configuration kind. | +| `EdgeProvider.status.approved` | Operator approval role | No provider ServiceAccount holds `edgeproviders/status`. | +| `EdgeService.spec` | Platform authority | `providerRef`, `vpcRef.uid` and capabilities are immutable. `trafficPolicy` selects the policy of every attachment the service admits (see [Traffic policy](#traffic-policy)). | +| `EdgeService.status` | Core | `Admitted` and `TrafficPolicyResolved` conditions, and `allocations`: each held client-pool address and its attachment, written with a `resourceVersion` precondition. | +| `EdgeInstance.spec` (`providerRef`, `podName`, `podUID`, `nodeName`, `bootID`) | The instance, at create | Immutable. Must match the token's pod UID and the pod's node. | +| The instance's `Lease` (`spec.holderIdentity`, `spec.leaseTransitions`, the `edge-renew-start`, `edge-sequence` and `edge-released` annotations) | The instance; core to fence it | Compare-and-swap on `resourceVersion` with a UID precondition (`internal/edge/provider`). Its provider label, pod annotation and owner never change, `leaseTransitions` never decreases, and a release holds until a new epoch: the `galactic-edge-lease` policy enforces these for every writer, and the provider policy limits a pod to its own lease. No provider deletes it. | +| `EdgeAttachment.spec` (`providerRef`, `serviceRef`, `instanceRef`, `podUID`, `contractVersion`, capabilities, `packetDevice`) | The instance, at create | Immutable. `podUID` must match the token; the instance must belong to the service's provider. | +| `EdgeAttachment.status` `Admitted`, `Allocated`, `Draining`, `Published`, `nodeName`, `vpc`, `address`, `drainDeadline` | Core | As `admission.MaySetCondition` allows. | +| `EdgeAttachment.status` `Programmed`, `Released`, device names | Node | `Programmed` only after `hostattach.Readback` succeeds; `Released` only after the host state is gone. | +| `EdgeAttachment.status` `Ready` | The instance | The only condition a provider sets. | +| `EdgeAttachment` finalizer | Core | Removed after the node confirms release. | +| `EdgeRoute.spec` (`providerRef`, `vpcUID`, `prefix`, `incarnation`) | An instance of the service's provider | Immutable. | +| `EdgeRoute.spec.claim` (`attachment`, `holderPodUID`, `holderInstance`, `instanceEpoch`, `epoch`, `released`) | A pod of the service's provider, naming itself and its own attachment | Compare-and-swap only. `holderPodUID` must match the token. Another pod may only replace the claim at a higher `epoch`; only the holder releases it. A write grants nothing until core accepts it. | +| `EdgeRoute.status` `Accepted`, `Claimed`, `Published` and the accepted holder (`accepted`: `epoch`, `attachment`, `attachmentUID`, `instance`, `instanceIncarnation`, `instanceEpoch`, `node`, `vpcNamespace`) | Core | Written only after the route is committed to the `EdgeRouteIndex`. See [Acceptance](#acceptance). | +| `EdgeRoute.status.closedEpoch` | `galactic-edge` on `accepted.node` | Never decreases and never passes `accepted.epoch`. A ValidatingAdmissionPolicy requires the writer's token node name (`authentication.kubernetes.io/node-name`) to equal `accepted.node`, and the change to touch only `closedEpoch`. | +| `EdgeRouteIndex` | Core | Compare-and-swap only. No provider ServiceAccount can read or write it. | +| `BGPAdvertisement` for an `EdgeRoute` | Core | One per route in `galactic-system`, named `edge-`, labeled with the route's UID and accepted epoch. No owner reference: the route is in another namespace. See [Publication](#publication). | +| Deletion of dead `EdgeInstance`s and `EdgeRoute`s | Core | See [Reaping](#reaping). | + +`admission.Writer` knows two writers, core and provider (`internal/edge/admission/admission.go:169`). `galactic-controller` and `galactic-edge` both count as core there, so `MaySetCondition` separates core from providers, not one core process from the other. The split between them in this table is enforced by RBAC and admission policies that limit `galactic-edge`'s ServiceAccount to `Programmed`, `Released`, device names and `closedEpoch`. + +## Provider interface + +A provider integrates in five steps, all through its own ServiceAccount. Its cell must also give it two things outside these resources: + +- **The packet device.** Kubernetes gives no unprivileged pod `/dev/net/tun`, and a provider has no hostPath or capability to reach it, so a cell that offers `PacketAccess` runs a device plugin that hands the device out as a resource, and a packet-access provider pod requests it. +- **The host VRF.** An attachment joins its gVPC's canonical host VRF on its node, which only CNI ADD creates, so a workload of the gVPC must run on the provider's node. + +[examples/edge-provider](../../examples/edge-provider) is a provider built only on this contract, with the deployment it needs. + +1. **Register.** The operator creates the `EdgeProvider` and approves it. Registration grants no tenant authority (`internal/edge/admission/admission.go:10`). +2. **Start an instance.** Each provider process creates its pod's `EdgeInstance`, takes over its lease and renews it every 5 s. The holder ID is new for every process start, so a restarted container cannot continue its predecessor's lease (`internal/edge/claim/claim.go:226`). +3. **Request an attachment.** The instance creates `EdgeAttachment` for an `EdgeService` that names its provider. It names the attachment for its pod and the service (`provider.AttachmentName`), which admission requires, and treats an existing attachment of that name that names another pod or service as a conflict to report, not one to retry (`provider.CreateAttachment` returns `provider.ErrNameTaken`). Core runs `admission.Admit` (`internal/edge/admission/admission.go:91`) before allocating anything, and refuses with the reasons defined there. #994 adds what `Admit` does not check today: capacity (`CapacityExhausted`) and identity conflicts on create (`IdentityConflict`). A service whose granted prefixes overlap an earlier service's in the same gVPC admits nothing (`PrefixConflict`). The instance waits for `Programmed`, opens the packet device or binds its sockets to the pod VRF named in status, then sets `Ready`. +4. **Request reachability.** For each prefix it serves, the instance creates or takes over the `EdgeRoute`, naming its own attachment. Core accepts it only if the prefix is inside the service's grant (`PrefixNotGranted`), overlaps no other route or subnet in the gVPC (`PrefixConflict`, see [Prefix conflicts](#prefix-conflicts)), does not contain the attachment's own address (`InvalidPrefix`), and the attachment is `Ready` and belongs to the writing pod. +5. **Drain and release.** The instance deletes its `EdgeRoute`s and `EdgeAttachment`s, or sets `released` on a claim after it has stopped forwarding. Core drains the same way when a service, grant or node goes away. + +### Compatibility + +- A request names one contract version and one version per capability. An unsupported version is refused before allocation with `UnsupportedContractVersion` or `UnsupportedCapability`. +- A core release supports the current contract version and the one before it. Admission refuses any other version with `UnsupportedContractVersion`, even one the `EdgeProvider` lists. Dropping a version requires that no `EdgeProvider` still lists it as its only version. +- A core release implements the capability versions listed under [Decisions](#decisions). Admission refuses any other capability version with `UnsupportedCapability`, even one the `EdgeProvider` lists. Core refuses or revokes an `EdgeRoute` with `UnsupportedCapability` unless its `EdgeProvider` lists `PrefixReachability` at a version core implements. +- Adding a capability adds a new name; it never changes what an existing version means. + +### Authorization context + +The foundation decides every request from three inputs, and nothing else: + +1. **Who is asking.** The authenticated ServiceAccount and pod UID from the request's bound token. The ValidatingAdmissionPolicy rejects a write whose `podUID` or `holderPodUID` differs from the token's pod UID, or whose ServiceAccount is not one the `EdgeProvider` lists. A policy cannot read other objects, so core checks the rest before accepting: the attachment a route names belongs to the same pod, and the instance an attachment names has the same pod UID. One provider pod therefore cannot write another pod's instance, attachment or claim, or point its own claim at another pod's attachment. +2. **What the provider may do.** The approved `EdgeProvider`. +3. **What the tenant granted.** The `EdgeService`, written by the platform authority: one gVPC, capabilities, prefixes, client pool and an optional `validUntil`. + +Client identities, prefixes and session state that a provider learns from its own clients can narrow what it requests. They never widen it, and the foundation never reads them. The provider checks packet ownership per client session; the foundation independently limits every packet on the attachment to the attachment address and the prefixes the instance currently holds. + +### Admission policy + +A ValidatingAdmissionPolicy reads only its own parameter object, so the provider checks are built this way: + +1. Every `EdgeInstance`, `EdgeAttachment` and `EdgeRoute` carries an immutable `providerRef`. Core refuses an attachment whose `providerRef` differs from its service's, and a route whose `providerRef` differs from its attachment's. +2. One policy, `galactic-edge-provider`, has `paramKind` `EdgeProvider`. For each approved `EdgeProvider`, core creates one ValidatingAdmissionPolicyBinding whose `paramRef` names that provider, with `parameterNotFoundAction: Deny`, and a RoleBinding that grants its listed ServiceAccounts write access to the three kinds. +3. Each binding evaluates every create, update and delete by a ServiceAccount other than core's and the node agent's. A ServiceAccount the parameter lists may write only objects whose `providerRef` names the parameter, and only those ServiceAccounts may create or change such objects, so a provider cannot plant an object under an unregistered provider's name. Another ServiceAccount's delete, such as the namespace controller's, is left to RBAC. For a provider's own writes the requester must be in the object's namespace, and `podUID` or `holderPodUID` must equal the token's `authentication.kubernetes.io/pod-uid`. A provider creates an `EdgeInstance` or instance `Lease` only under the name derived from the pod it names (`provider.InstanceName`), so one pod cannot take another's name before it. The policy holds only the provider's ServiceAccounts to these names, so a provider's namespace should grant no other workload `create` on Leases. That extra is present on Kubernetes 1.30 and later; the node-name extra the instance and node agent checks read needs 1.32. +4. A provider that is not approved has no RoleBinding, so RBAC refuses its writes before the policy runs. Withdrawing approval deletes both bindings. +5. A person's writes are not checked by the policy: RBAC alone decides them, so an operator can still clear an object a provider left behind. +6. A second policy holds core's own RoleBinding writes to the provider ClusterRole. Kubernetes runs no admission policy on policy bindings themselves, so core's write access to those is bounded by RBAC alone. + +### Idempotency + +- Every create uses a derived name. `AlreadyExists` is answered by reading the object and comparing its immutable fields; a mismatch is refused with `IdentityConflict`, never overwritten. +- Claim writes are compare-and-swap. A lost reply is recovered as `claim.Instance.Renew` does: the writer rereads, and validity always runs from the start of the latest call. +- Node mutations go through `ownership.Authority.Commit` (`internal/edge/ownership/ownership.go:162`), which refuses a ticket issued before another commit. A retry built from an old view cannot undo newer state. + +### Readiness + +`Ready` on an attachment means only that the provider can take traffic. `Published` means: + +- core admitted and allocated it, +- the node programmed and read it back, including traffic policy, +- the instance's lease and the route's claim are valid, +- the node opened the forwarding gate, and +- the node's `galactic-router` installed the advertisement locally. + +Core sets `Published` on each `EdgeRoute` from its router's report on the route's advertisement, and on each attachment while at least one route accepted on it is published. + +`Published` does not mean remote routers have converged. That is measured separately (see [Timing and failure bounds](#timing-and-failure-bounds)). + +### Traffic policy + +An attachment's host link is a traffic policy subject like a workload's interface (see [Traffic policy on the node](../traffic-policy/node.md#edge-attachments)). The `EdgeService` selects its policy: `spec.trafficPolicy.ingressPolicyRef` for traffic delivered to the provider from the gVPC, and `egressPolicyRef` for traffic the provider sends into it. Each names a `TrafficPolicy` in the service's namespace. A provider controls neither: it cannot write the service, and a policy in its own namespace is never read. + +- `galactic-edge` writes the link's policy row, with the attachment's address, and attaches `usid_egress` and `tp_deliver` while the link is still down. On a node that enforces policy but failed the kernel preflight, it reports `DatapathFailed` and leaves the link down. +- `galactic-router` publishes one snapshot per direction. Until it has, the link denies everything. It publishes nothing, and unbinds what it published, while the attachment is not `Admitted` or its service is gone, being deleted, replaced or granting another provider. +- An omitted reference selects the built-in `default-deny-all`. A reference to a missing policy denies everything as `policy_unavailable`. Neighbor discovery on the link is a link operation outside the rules, so it works under any policy. +- `galactic-router` republishes when the service's references or a referenced policy change, so the change applies to active attachments. A change to the service re-admits its attachments under the new generation without draining them. +- Core reports whether both references resolve in the service's `TrafficPolicyResolved` condition. + +## Lifecycle + +### Attachment + +```mermaid +stateDiagram-v2 + [*] --> Pending: instance creates EdgeAttachment + Pending --> Refused: admission fails + Pending --> Admitted: core, admission.Admit passes + Admitted --> Allocated: core assigns address + Allocated --> Programmed: node provisions, gate closed + Programmed --> Active: Ready, lease valid, previous owner fenced + Active --> Programmed: lease or claim expires, gate closes + Active --> Draining: delete, revocation or node drain + Programmed --> Draining: delete, revocation or node drain + Draining --> Released: window ends or provider finishes + Released --> [*]: node confirms cleanup, finalizer removed + Refused --> [*] +``` + +| Transition | Writer | Guard | +| ----------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| Pending to Admitted | Core | Provider approved, versions supported, gVPC and capabilities granted, capacity available. | +| Admitted to Allocated | Core | An address in the client pool that no other attachment holds. | +| Allocated to Programmed | Node | Pod is on this node with the recorded UID; `hostattach.Provision` and `Readback` succeed; traffic policy rows exist. | +| Programmed to Active | Node | `Ready`, a lease valid on fresh reads, and a route whose accepted holder is this attachment and instance; core accepts a holder only after fencing. | +| Active to Programmed | Node | The kernel deadline passed or the claim moved; the node closes the gate and records it. | +| Any to Draining | Core | Deletion, `EdgeService` deleted or revoked, `validUntil` reached, or node maintenance. | +| Draining to Released | Node | Gate closed, routes withdrawn locally, `hostattach.Release` done, policy rows removed. | + +A failed step leaves the attachment in its last state with a condition naming the reason. Partial host state carries the attachment ID in the host link's alias, so the node finds and finishes it on restart (`internal/edge/hostattach/inventory.go:33`). + +### Forwarding claim + +Each `EdgeRoute` is the claim for one prefix in one gVPC. An instance renews one lease, not one per route, so the claim has two levels: + +- The instance's lease is a record of `internal/edge/claim`, keyed by the instance. Its holder renews it, and its epoch advances only when it is taken over. +- The `EdgeRoute` names the holder instance and that instance's epoch (`holderInstance`, `instanceEpoch`). It is written only on acquire, release and takeover. The claim is valid only while the named instance's lease is valid at that epoch. The node opens a prefix's gate only for the holder core accepted, while its own applied lease matches that holder (see [Acceptance](#acceptance)). + +```mermaid +stateDiagram-v2 + [*] --> Pending: holder swaps in epoch 1 + Pending --> Accepted: core checks grant, overlap and fencing + Pending --> Refused: grant or overlap check fails + Accepted --> Released: holder stopped forwarding + Accepted --> Pending: another attachment swaps in the next epoch + Accepted --> Pending: same attachment, newer instance epoch + Released --> Pending: a holder swaps in the next epoch + Accepted --> Revoked: grant revoked or subnet overlap +``` + +The route record changes only on these transitions. Lease renewals happen on the holder instance's lease, and the node applies them to the route's gate while the accepted holder names that instance and epoch. + +`internal/edge/claim` implements the single-level lease, and providers use it for their instance's lease through `internal/edge/provider`'s store. + +The lease is a `coordination.k8s.io/v1` Lease with the instance's namespace and name, owned by the `EdgeInstance`, so deleting the instance deletes it: + +| Lease field | Claim record | +| ---------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `spec.holderIdentity` | Holder, the provider process; null while nobody holds it | +| `spec.leaseTransitions` | Epoch | +| `metadata.uid` | Incarnation | +| Annotation `galactic.datumapis.com/edge-renew-start` | The holder's `CLOCK_BOOTTIME` in decimal nanoseconds, read before it sent the write | +| Annotation `galactic.datumapis.com/edge-sequence` | Sequence, advanced on every renewal | +| Annotation `galactic.datumapis.com/edge-released` | `true` once the holder of the epoch stopped forwarding, otherwise `false` | +| Label `galactic.datumapis.com/edge-provider` | The instance's provider | +| Annotation `galactic.datumapis.com/edge-pod-uid` | The instance's `podUID` | + +Core and the node read a Lease as the instance's lease only when it is owned by that instance and its label and pod annotation match the instance; any other Lease of that name is no lease. A provider that finds its instance's or lease's name held by an object naming another pod gets `provider.ErrNameTaken`, which wraps `claim.ErrLost`, so it stops rather than retrying until that object is deleted. `spec.leaseDurationSeconds` and `spec.renewTime` are written for tools that display Leases and are never read: validity runs from the renew start on the node's clock, and observers time a lease on their own clocks. A provider takes a route by compare-and-swap on the route's current version (`provider.Claim`), at the next claim `epoch` whenever the holder changes or its claim ended. A provider's own wait is a courtesy, not the safety mechanism: the provider runs the code, so the foundation cannot rely on it. Safety comes from acceptance. + +### Acceptance + +The gate follows the accepted holder, never the route's spec. The node opens a prefix's gate only on `accepted.node`, for `accepted.attachment`, and only while it holds an applied lease for `accepted.instance` at `accepted.instanceIncarnation` and `accepted.instanceEpoch`. A provider pod that swaps the spec to a new epoch changes nothing on any node until core accepts it, so it cannot cut off a live holder. Only core writes the accepted holder, and core accepts a new epoch in three cases: + +1. **First claim.** The route has no earlier accepted epoch in the `EdgeRouteIndex`, and no other entry overlaps its prefix. +2. **Same attachment.** The earlier accepted epoch named the same attachment. The gate, host link and pod are unchanged, so no second forwarder can exist. This covers a provider process restarting in its pod, see below. +3. **Another attachment.** Either the earlier attachment's node has written `closedEpoch` at or above the earlier epoch (confirmed fencing), or the core leader itself has seen the earlier holder's instance lease unchanged for `TakeoverWait` on its own clock. The leader reads the record with uncached quorum reads, never from its informer cache, stamps each read when it returns, and continues only if a final quorum read at the end of the wait still returns the same version. It then fences the lease before committing the index: a compare-and-swap at that version (`provider.Fence`) moves it to the next epoch with no holder. A renewal the holder sent before the final read that lands after it then fails, and its holder learns the lease is lost; a renewal that landed first makes the fence fail, and the wait starts again. Once the fence lands, no renewal can extend the earlier gate, however long the leader takes to write the index and the route's status. A renewal restarts the wait. A leader change restarts it too, because observations are in the leader's memory. A missing instance or lease counts as unchanged from the first quorum read that found it missing, since the node can apply no renewal of a deleted record, and needs no fence; a leader that finds more than `Margin` passed between that final read and the index write, as after a pause, starts the wait again. This differs on purpose from `claim.Instance.Acquire`, which creates a quarantine record when one is missing (`internal/edge/claim/claim.go:237`): core never creates a provider's lease, and writes one only to fence it. A record recreated during the wait has a new version, which restarts the wait, and a new incarnation, which the node's gate never matches. The fence ends the whole instance lease, not only this route's claim, but core reaches it only for an instance that has not renewed for longer than a lease, whose gates have all expired. + +Case 3 is the guarantee in `internal/edge/claim` with core as the replacement: it waits as `claim.Instance.Acquire` does and takes the lease away by the same compare-and-swap, but leaves it unheld. The replacement's provider code takes no part in it. A provider that swaps a route early gets nothing until core accepts it. + +**Restart in place.** A restarted provider process acquires its instance's lease with the single-level rules. The previous process's renewals have stopped, so the record stays unchanged and the wait ends after `TakeoverWait`. It then swaps each of its routes to the new instance epoch. Under case 2, core accepts at once, with no second wait on the instance it now renews itself. Measured from the restarted process's first read of its lease, forwarding resumes after `TakeoverWait` (15.53 s) plus the time to swap the routes, accept them and apply the new lease. That second part has a 1 s target, measured rather than guaranteed, because it includes API round trips. + +A holder whose instance lease expired cannot revive its routes. Its renewal returns `ErrLost`, and reacquiring the instance advances the instance epoch, which no longer matches the routes until they are swapped and accepted again. + +**Node obligations.** `galactic-edge` on `accepted.node` closes the prefix's gate and then writes `closedEpoch` when any of these happens to the accepted epoch: the holder sets `released`, core revokes the route, the attachment drains, or the lease deadline passes. A released route is therefore free only after its own node confirms the gate is closed, which case 3 then sees. When core accepts a successor on another attachment through the time branch of case 3, the old gate has already closed at its deadline, and the old node closes its state without writing `closedEpoch`, since `accepted.node` has moved. A same-attachment acceptance (case 2) closes nothing. A closed gate stays in the map, closed, until `closedEpoch` records it; an epoch at or below `closedEpoch` never opens again. A holder whose gate expired therefore claims a new epoch, which core accepts at once under case 2, and the gate opens from a renewal read after that. `galactic-edge` writes gates through the ownership fence of the gVPC's scope, so an agent process a newer one fenced cannot reopen a gate the newer one closed. It writes `closedEpoch` only after a commit in that scope finds no gate on any edge link still carrying the prefix open at that epoch, so a fenced process, or one that missed a link while listing, never reports a gate closed that another holds open. + +### Prefix conflicts + +Two routes in one gVPC conflict when either prefix contains the other, not only when they are equal. Exact-prefix contention goes through the claim, since both instances address the same `EdgeRoute`. Every other overlap is refused: + +- Acceptance is a compare-and-swap on the gVPC's `EdgeRouteIndex`, which lists every accepted route and its epoch. Core checks the new route against that list and what else the gVPC uses (below), then writes the index, then the route's status. If two controller replicas both believe they lead during a lease handoff, the second swap fails and that replica rereads. +- A route that overlaps an accepted route or a subnet is refused with `PrefixConflict`. An index holds at most 1024 routes, so a full one stays within etcd's object size limit; a route beyond that is refused with `IndexFull`. +- An entry leaves the index only when the case 3 fencing rule holds for its last accepted epoch, whatever the reason: deletion, release, revocation, the `EdgeService` going away, or a later subnet. For a removal core recorded itself (deletion, revocation, the service going away, a subnet), the entry also leaves once `TakeoverWait` has passed on the leader's clock since the recording and a final quorum read confirms it. `galactic-edge` extends a gate only after a fresh read showing the route still accepted, so the gate closes within `Duration` + `Margin` of the recording even if `galactic-edge` is stuck and the provider keeps renewing. Deleting and recreating a route never shortcuts fencing, and the recreated route is a first claim only after the old entry is gone. +- Whenever core finds no index for a gVPC, it creates one rebuilt from every route's accepted holder, then accepts no first claim in that gVPC for `TakeoverWait`, since entries for deleted routes may be gone. Core cannot tell a gVPC's first route from a lost index, so the first route of every gVPC waits too. +- A subnet created later that overlaps an accepted route revokes the route with `PrefixConflict`. The node closes the gate within the revocation bound, so the route and the new subnet can overlap for up to 15.5 s. Core does not delay subnet creation; workload subnets take precedence over provider routes. + +A route never contains its holder attachment's own address, the `/128` included. The node routes the prefix through that address, so core refuses such a claim with `InvalidPrefix` once it has confirmed the attachment is the claimant's and live, before it checks the grant, other routes or subnets (`internal/edge/route/check.go`), and an accepted route cannot come to contain it, since an attachment keeps its address. + +Besides other routes, a route conflicts with (`internal/edge/route/conflict.go`): + +- a workload subnet of the gVPC: any `VPCAttachment.status.podSubnet` of it; +- another service's client pool in the gVPC; +- the address of another attachment allocated from its own service's pool. A route may otherwise lie inside its own service's pool: that is a delegated client prefix. The allocator never hands out an address under a prefix in the gVPC's `EdgeRouteIndex`. An allocation can still race an acceptance; the route then contains the new address and is revoked; +- anything, when an earlier service's granted prefixes overlap its own service's. Grants are exclusive in a gVPC: of two services whose prefixes overlap, the later, by creation time and then UID, admits no attachment and routes nothing until they no longer overlap. A grant's prefixes stay assigned to its service until the service is deleted or its prefixes change. + +Each of these created or changed after acceptance revokes the route, like a later subnet. + +### Publication + +Core publishes one `BGPAdvertisement` for each accepted route (`internal/edge/route/publish.go`), only while: + +- the route's accepted holder is not revoked or released, +- its attachment is the accepted object, programmed, with its host link and address reported, and +- the gVPC's `BGPVRFInstance` exists on the holder's node. + +The advertisement names that node's router, the VRF's ID and export route target, the route's one prefix with `End.DT46`, and the holder's host link and address. It follows a takeover in place: the same object, updated to the new node, at the new epoch. Core withdraws it as soon as none of the conditions holds, and withdraws every advertisement annotated with the route's name that is not the current one, each on a precondition of the version read, so a pass for an earlier object of the same name never touches a replacement's or another route's. + +`galactic-router` advertises an edge route's advertisement only while the forwarding gate it names is open on its node: the named host link is the edge link of the named address and holds an unexpired gate for exactly the prefix. It reads the gate from the pinned map whenever it builds its desired state, and polls it every 250 ms so a deadline passing withdraws the prefix with no API event. Without the pinned map it advertises none, and opens the map again at most every second until it can read it. An advertisement it leaves out is reported `Advertised` False with reason `GateClosed`. Publication never widens what the gate allows: a prefix whose gate closes is withdrawn locally even if core is cut off and still publishes it. + +An attachment's own address is not published. Workloads of the gVPC on the attachment's node reach the address, and every prefix whose gate is open on the attachment's link, through local entries `galactic-edge` keeps in the uSID datapath (see [Shared, written by existing components](#shared-written-by-existing-components)). The entry for a prefix stays while its route is accepted on the node and not released, whether or not the gate is open, so a closed gate drops that traffic on the node instead of sending it to the gVPC's egress shards. Workloads on other nodes reach only published prefixes. A provider that must be reachable at its address from other nodes claims an `EdgeRoute` for the address's `/128`, which the conflict check allows for the holder's own address. That route is gated and published like any other, and adds no host route, since the link's own route already carries the address. + +Core's write access to `BGPAdvertisement` is a Role in `galactic-system`. Kubernetes RBAC cannot scope it by label, so the Role covers every advertisement there, though core reads and writes only those labeled `galactic.datumapis.com/edge-route`. + +### Reaping + +Core deletes what no live pod can still use: + +- An `EdgeInstance` whose pod no longer exists, or exists with another UID, once its record has been unchanged for `TakeoverWait`. +- An `EdgeRoute` whose attachment is gone and whose claim is released or held by a reaped instance. +- The `BGPAdvertisement` of a deleted `EdgeRoute`: core withdraws it when it sees the route gone, and an advertisement whose annotated route no longer exists when it sees the advertisement. + +The node never deletes API objects. It closes gates and releases host state for attachments that are draining or deleted. + +### Drain + +A drain stops new routes and attachments for its scope at once. Forwarding continues until the earlier of the drain window (`EdgeService.spec.drainSeconds`, default 30, maximum 300) and the lease deadline. Core records the end of the window in the attachment's `status.drainDeadline` and deletes the attachment when it passes. The node then closes the gate, `galactic-router` withdraws, and the attachment is released. A grant's prefixes stay assigned to the service across drains; only its routes go. + +### Restart and replacement + +| Event | Rule | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Provider process restarts in its pod | New holder ID. It takes over its own instance lease after a release or `TakeoverWait`, then core re-accepts its routes at once (see [Acceptance](#acceptance)). | +| Provider pod replaced, same node | New pod UID and `EdgeInstance`. Routes move by takeover. The old attachment drains. | +| Replacement on another node | As above. The old node's gate closes at its own deadline even if that node cannot reach the API. | +| `galactic-edge` restarts | New ownership owner ID, `Fence`, `Adopt`, then a snapshot commit (`internal/edge/ownership/ownership.go:212`, `:226`, `:169`). It extends no deadline until it has read a renewal newer than the one applied. | +| `galactic-router` restarts | Advertises an edge prefix only while its gate deadline, read from the pinned map, is in the future. | +| Node reboots | Pinned maps and leases from the previous boot are void: the boot ID changed. Every claim on that node is reacquired through the takeover rules. | + +Cached state is evidence to reconcile from, never permission to forward. + +## Timing and failure bounds + +### Parameters + +Every holder and replacement in a cell uses the same values. `claim.Params.Validate` rejects values that cannot provide the guarantee. + +| Parameter | Value | Basis | +| ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Lease `Duration` | 15 s | Validity one renewal grants on the holder's `CLOCK_BOOTTIME`. | +| Renewal interval | 5 s | Two consecutive renewals can fail without expiry. | +| `MaxDrift` | 0.001 | 1000 ppm relative rate error between any two nodes' monotonic clocks. | +| `Margin` | 500 ms | Delay between a deadline passing and forwarding actually stopping. | +| `TakeoverWait` | 15.53 s | `Duration × (1 + MaxDrift) / (1 − MaxDrift) + Margin` (`internal/edge/claim/claim.go:149`). | +| `MaxSkew` | 2 s | Wall-clock error of any node; used only to convert `validUntil` into a deadline. | +| Router gate poll | 250 ms | How often `galactic-router` reads the gate deadlines of the prefixes it advertises. | +| BGP hold time | ≤ 9 s | Negotiated hold time of an edge node's EVPN session to its route reflector. The bound needs at most 9 s; the deployment sets the timers on both ends. Unset, GoBGP's default is 90 s. | +| Drain window | 30 s | Default `drainSeconds`; at most 300 s. | + +### Bounds + +| Bound | Value | Enforced by | Holds while | +| ----------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------- | +| Local forwarding expiry | 15.5 s after the last applied renewal starts | The datapath compares the gate deadline with `bpf_ktime_get_boot_ns` | Provider, `galactic-edge` and API all stalled | +| Replacement activation | Not before the old gate is confirmed closed, or `TakeoverWait` | Core's acceptance, observed on the leader's clock, and the node's gate check | Any two nodes within `MaxDrift` | +| Revocation | 15.5 s after it is recorded (`Duration` + `Margin`) | `galactic-edge` applies a renewal only after reading the attachment and grant fresh | `galactic-edge` cut off from the API | +| Revocation, connected | Target 2 s after it is recorded | `galactic-edge`'s watch closes the gate when it sees the revocation | Measured, not guaranteed | +| Grant ceiling | `validUntil − MaxSkew` | The lease deadline is capped by `claim.Instance.Ceiling` | Wall clocks within `MaxSkew` | +| Local route withdrawal | 1 s after the gate deadline | `galactic-router` polls the pinned gate and withdraws with no API call | `galactic-router` running | +| Local route withdrawal, router down | 9 s after the router stops | The route reflector drops the node's paths when the 9 s hold time expires | Route reflector running | +| Remote convergence | Target 5 s after local withdrawal | BGP propagation | Measured, not guaranteed | + +Every bound measured from a deadline is on the holder's clock. With `MaxDrift` of 0.001, the 15.5 s figures are at most 15.52 s of real time, which is the pass threshold for a real-time measurement in the [failure-test matrix](#failure-test-matrix). + +The revocation bound works like this. `galactic-edge` extends a gate only after a renewal and a quorum read of the attachment, service and grant that shows them still valid. Any renewal applied after a revocation sees it. A renewal applied before the revocation started no later than the revocation, so its gate closes within `Duration` of it, and forwarding stops within `Margin` after that: 15.5 s in all. + +### Clock and failure assumptions + +- **Monotonic clock.** Each node's `CLOCK_BOOTTIME` advances at real time within `MaxDrift`, across suspend. Wall clocks are not assumed synchronized; only the grant ceiling uses them. +- **Shared node clock.** A provider and the `galactic-edge` serving it run on the same node, so the renewal start a provider records in its lease (the `edge-renew-start` annotation, with the instance's `bootID`) is on the clock the gate uses. `galactic-edge` rejects a start later than its own reading or earlier than the one it already applied, and any record from another boot. +- **No VM pause.** A node whose clock stops while the node is paused can forward past its deadline in real time. Edge nodes that run edge attachments must be physical, or virtual with pause and live migration disabled. +- **Forged renewal starts.** A provider can record a start later than its true send time. Because `galactic-edge` accepts no start later than its own reading, a forged start makes a renewal look at most as fresh as the moment `galactic-edge` read it. That extends only the provider's own gate, for prefixes it already holds, and cannot affect another provider or tenant. +- **Stale remote routes.** Until remote convergence, traffic can still arrive at the old node. The closed gate drops it. Stale routes cost packets; they never reopen forwarding. +- **Availability cost.** An API outage longer than 15 s stops every edge attachment in the affected scope. This is deliberate: two owners for one prefix is worse than an outage. + +## Foundation resources and their writers + +Foundation-owned host state is what `galactic-edge` creates for an attachment, plus the shared state it writes into. Each gVPC on the node is one scope of `internal/edge/ownership`, which `galactic-edge` owns and writes only in snapshot commits. A writer that can remove shared state an edge attachment uses does so only through `maintenance.Guard.Reclaim` (`internal/edge/maintenance`): under the scope's lock (`ownership.Authority.Exclusive`), and never between `Fence` and `Adopt`, it checks again that no edge attachment uses the gVPC; a refused check writes nothing, and a write makes every ticket `galactic-edge` holds for the scope stale, so a change prepared before it is prepared again. A gVPC is in use while the API has an `EdgeAttachment` on the node for it that is not `Released`, which covers one still being prepared, or the host has a link stamped for it. Every other writer in the table below either writes only rows an edge attachment never uses, or only adds rows; the table gives the reason for each. No lab or end-to-end environment runs `galactic-edge` yet. + +### Owned by `galactic-edge` + +| Resource | Key | Other writers allowed | +| ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Host veth `E`, alias `galactic-edge:hostattach:` | Attachment ID | None. `hostattach.Release` refuses another ID's link. | +| Pod VRF, pod link, TUN and routes inside the provider pod | Attachment ID | None. | +| Host-table routes and permanent neighbors for the attachment | Host link ifindex | None. | +| uSID registration of the host link (`ifindex_vrf_table`, `ifindex_egress_kind_table`) | Host link ifindex | None. | +| Traffic policy interface rows (`tp_iface_table`, `tp_iface_addr_table`) for the host link | Host link ifindex | None. `galactic-router`'s traffic-policy reconciler binds snapshots to the link in `tp_binding_table`, as for a workload. | +| Forwarding gate rows (`edge_link_table`, `edge_gate_table`) | Host link ifindex, and prefix | None. The link row is written before `usid_egress` and `tp_deliver` are attached to the link, and removed after its gates. | +| Local pass-through entries in `egress_route_table`: each edge link's address, and each prefix of a route its attachment holds | gVPC table and prefix | None. Each entry names its owner, `egressroutemap.PassThroughEdge`, in its value, and `galactic-edge` removes only entries with that owner. `galactic-router`'s withdrawals leave them. | +| Ownership records | Scope (gVPC on the node) | Every fenced writer, through `ownership.Authority`. | + +The host link name stays outside the CNI pattern `^G…H$` (`internal/gc/datapath_repair.go:33`), so datapath repair never mistakes an edge link for a workload. + +### Shared, written by existing components + +The table lists every site outside tests and the map packages themselves that opens a pinned map of the CNI datapath (`/sys/fs/bpf/galactic`), removes a traffic-policy interface, or creates or deletes a VRF, and every writer of `BGPAdvertisement`. This command regenerates the datapath and VRF part: + +```sh +grep -rnE '\b[a-z]+map\.OpenPinned[A-Za-z]*\(|\btpmap\.RemovePinnedInterface\(|\bvrf\.(Add|AddInRange|Delete)\(' internal cmd | grep -v '_test.go' +``` + +| Resource | Writers today | Integration | +| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Canonical host VRF of a gVPC | Created by CNI ADD (`internal/cni/ops_add.go:100`, `internal/cnitap/ops_add.go:101`). Deleted by `galactic-router` GC (`gc.RemoveOrphanedVRFs`, chosen by `gc.CollectOrphanedVRFs`, run from `internal/controller/gc_controller.go:43`) | GC skips a gVPC edge attachments use and deletes each VRF through `Reclaim`. CNI ADD only creates, and leaves an existing VRF as it is. | +| `BGPVRFInstance` of a gVPC on the node | Created by CNI ADD; deleted by `galactic-router` GC (`gc.RemoveOrphanedCRDs`, chosen by `gc.CollectOrphanedCRDs`) | GC skips a gVPC edge attachments use and deletes each instance through `Reclaim`, found from the VRF it serves, so `galactic-router` keeps importing the gVPC's routes into the VRF. An instance whose VRF is gone is deleted outright: no edge attachment can use a gVPC with no VRF on the node. | +| Ingress sidecar VRF | Created and deleted by the ingress sidecar inside its own pod namespace (`internal/ingresssidecar/backend.go:86`, `:120`) | None while it runs in its own network namespace. `vrf.Delete` works by name, so on the host network it would delete the canonical VRF; the sidecar must never run there. | +| uSID registry (`vrf_table`, locator and function rows) | `attachreg.RegisterDatapath` (`internal/plumbing/ebpf/attachreg/register.go:138`) and fill (`fill.go:93`); `galactic-cni` sweep (`internal/gc/gc.go:594`, run from `internal/installer/installer.go:1276`), egress group refresh (`internal/installer/egressgroup.go:202`) and sidecar return (`internal/installer/sidecarreturn.go:241`); the ingress sidecar (`internal/ingresssidecar/ebpfdatapath.go:314`, `:460`); sidecar prune (`internal/plumbing/ebpf/sidecarmap/prune.go:51`) | The sweep keeps every entry a stamped edge host link resolves to through its `ifindex_vrf_table` row, and removes nothing when it cannot list those links. `attachreg` writes only its own gVPC's entry, with that gVPC's VRF table. Egress group refresh only reads the registry. The sidecar, its return path and prune write only under `uformat.BlockIngressSidecar` or add node-wide locator and function rows. | +| Attachment rows, during repair | `galactic-cni`'s datapath repair (`internal/gc/datapath_repair.go:121`), through `attachreg` | None. Repair acts only on links in the CNI name pattern and writes only rows that are missing. | +| `ifindex_vrf_table` | `attachreg` (`register.go:172`, `fill.go:99`); the ingress sidecar (`ebpfdatapath.go:328`, `:444`); sidecar prune (`prune.go:55`); CNI DEL (`internal/cni/ops_del.go:144`, `internal/cnitap/ops_del.go:110`) | None. Each writer removes only its own link's row: CNI DEL looks its link up by its CNI name, so a reused ifindex never names an edge link, and the sidecar and prune stay at or above `ifindexvrfmap.SidecarIfindexBase`, which `Register` refuses for any host link. | +| `ifindex_egress_kind_table` | `attachreg` (`register.go:537`, `fill.go:105`); CNI DEL (`internal/cni/ops_del.go:160`, `internal/cnitap/ops_del.go:124`) | As for `ifindex_vrf_table`. | +| `tenant_gw_table` | `attachreg` (`register.go:586`, `fill.go:114`); CNI DEL (`internal/cni/ops_del.go:181`, `internal/cnitap/ops_del.go:145`) | As for `ifindex_vrf_table`. Edge attachments write no row. | +| `egress_route_table` | `srv6` helpers (`internal/plumbing/srv6/egress.go:49`, `:60`, `:112`, `:153`), called by `galactic-router` VRF routes (`internal/runtime/gobgp/vrfroutes.go:34`, `:108`), the ingress sidecar (`backend.go:127`) and `attachreg` (`register.go:436`); `attachreg` directly (`register.go:333`, `:407`, `fill.go:123`); egress group refresh (`egressgroup.go:196`); sidecar prune (`prune.go:60`); `galactic-router`'s startup write probe (`internal/runtime/gobgp/monitor.go:376`); `galactic-edge` through `attachreg` (`hostlink.go:200`) | `galactic-edge` writes a pass-through entry in the gVPC's table for each edge link's address, each prefix whose gate is open on the link, and each prefix of a route accepted on the node for the link's attachment and not released, and removes only the entries it owns (`attachreg.SyncHostLinkRoutes`). Without them, a workload of the gVPC on the same node matches the gVPC's `::/0` shard route and its packets leave as public egress, since `galactic-router` installs no route for its own node's advertisements. A held prefix whose gate is closed has no host route, so the kernel drops it at the VRF's unreachable default. The agent syncs the entries on every attachment pass, which a route's acceptance, release, deletion or move to another node triggers. A wanted prefix that already has another writer's pass-through entry is left to that writer. An encapsulating entry left for a prefix whose holder moved here is replaced, and `galactic-router`'s withdrawal of that remote route (`srv6.RouteEgressDel`) keeps the entry. An encapsulating entry `galactic-router` installs over it is a later holder's route; core accepts that holder only once this node's gate is confirmed closed or `TakeoverWait` has passed. A published edge route reaches other nodes through `galactic-router` like any other VRF route (see [Publication](#publication)). | +| `egress_shard_groups` | Egress group refresh (`egressgroup.go:214`); `attachreg` (`egressgroups.go:32`, `fill.go:141`) | None. Node-wide shard groups; edge attachments write no row. | +| Sidecar return maps | The ingress sidecar (`ebpfdatapath.go:491`, `:514`); `galactic-cni`'s sidecar reaper (`internal/installer/sidecarreap.go:265`) | None. Keyed by the sidecar's own ranges; edge attachments write no row. | +| Traffic policy maps (`tp_*`) | `galactic-router`'s policy reconciler (`cmd/galactic-router/policy.go:234`); CNI ADD (`internal/cnibgp/trafficpolicy.go:53`); interface removal by CNI DEL (`internal/cni/ops_del.go:173`, `internal/cnitap/ops_del.go:137`) and the ingress sidecar (`ebpfdatapath.go:452`); the node-wide mode, set by `galactic-cni` (`internal/installer/trafficpolicy.go`) | None. Interface removal acts only on its own links, like CNI DEL above. An edge host link is a policy subject like a workload interface; an unbound attachment denies everything. | +| Node-wide rows (`node_src_addr_table`, `public_uplink_table`) | The ingress sidecar (`ebpfdatapath.go:244`); `attachreg` (`register.go:263`, `:280`, `fill.go:129`, `:135`); `galactic-cni` public uplink refresh (`internal/installer/public_uplink.go:148`) | None. Each holds one node-wide value, not keyed by gVPC or attachment, and edge attachments never write them. | +| Private service maps (`service_*`) | `internal/serviceroute/dataplane.go:409` | None. Edge attachments never write them. | +| `vip_xlat_table` | `galactic-router` (`cmd/galactic-router/root.go:158`, `cmd/galactic-router/vipxlat.go:34`) | None. Edge attachments never write it. | +| `BGPAdvertisement` | CNI, `galactic-gateway`, the ingress sidecar, `galactic-controller`, GC (`gc.RemoveOrphanedCRDs`) | Core writes one edge advertisement per accepted route, labeled `galactic.datumapis.com/edge-route`, and withdraws it itself. GC deletes only an advertisement whose recorded network namespaces are all gone, and one with none recorded, as core's are, always survives. | +| Plain routes for EVPN paths without a route target | `galactic-router` (`internal/runtime/gobgp/plainroutes.go`), sole owner of its own table | None. Its table is not a canonical VRF table, and edge attachments never write it. | + +Sites the command finds that only read are left out: CNI CHECK (`internal/cnibgp/ops_check.go:168`, `:227`, `:262`), the sidecar's route inventory (`internal/ingresssidecar/routeinventory.go:60`) and the sweep's lookup of edge host links (`internal/gc/gc.go:819`). + +### Ownership transfer, recovery and cleanup + +- **Transfer between writers on a node** uses `Fence`, then `Adopt`, then a snapshot commit. `Fence` waits for a commit in progress, so the old writer's last change either lands before the barrier or not at all. +- **Transfer between instances** is a claim takeover. The new instance's gate opens only after the old generation can no longer forward, and the gate key carries the generation, so the old owner's late cleanup deletes nothing the new owner installed. +- **Recovery** after a failed or interrupted commit requires a snapshot commit (`ErrResyncRequired`), because a half-applied change is neither done nor undone. +- **Cleanup** removes only state stamped with the attachment ID, or keyed by an ifindex whose link carries that ID, and only under a current ownership ticket. Losing the ownership state directory requires stopping every writer on the node and reconciling host state before a fresh authority is created; restoring it from a backup is never allowed. + +## Failure-test matrix + +Each row is an acceptance test. The pass condition is fixed here, before anything is run. "Talos" means the target Talos/Cilium environment from #1002; "lab" is `deploy/containerlab`; "root unit" is a `requireRoot` Go test on a real kernel. + +| # | Scenario | Injected fault | Pass condition | Where | Milestone | +| --- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ------------ | +| 1 | Unknown or unapproved provider | Attachment from an unregistered or unapproved provider | Refused with its reason; no allocation or host change | Unit, lab | #994 | +| 2 | Unsupported version | Unsupported contract or capability version | Refused before allocation | Unit | #994 | +| 3 | Out-of-grant request | gVPC not granted; prefix outside the grant | `VPCNotGranted` or `PrefixNotGranted`; no route | Unit, lab | #994, #998 | +| 4 | Forged identity | Pod writes another pod's instance, attachment or claim | API server rejects the write | Lab, Talos | #994 | +| 5 | Capacity exhaustion | Requests beyond attachment or prefix limits | Refused before allocation; existing attachments unaffected | Unit, lab | #994 | +| 6 | Overlapping tenants | Two gVPCs, identical addresses and prefixes, two providers | No packet crosses gVPCs, in both directions | Root unit, Talos | #995, #1000 | +| 7 | Prefix conflict in one gVPC | Two providers request the same prefix | Second refused with `PrefixConflict`; the first keeps forwarding | Unit, lab | #998 | +| 7a | Overlapping prefixes in one gVPC | A /48 and a /56 inside it, from two providers or two instances; a route overlapping a gVPC subnet | The later route refused with `PrefixConflict`; the earlier keeps forwarding; also across a leader change | Unit, lab | #998 | +| 7b | Route on another pod's attachment | A provider pod writes a route naming another pod's attachment, at create and on takeover | API server rejects a mismatched `holderPodUID`; core refuses a mismatched attachment; no gate opens | Unit, lab | #994, #998 | +| 7c | Subnet created over a route | Create a gVPC subnet overlapping an accepted route | Route revoked with `PrefixConflict`; gate closed within the revocation bound | Unit, lab | #998 | +| 7d | Route over its own address | Route whose prefix contains its holder attachment's address: a covering prefix and the address's `/128` | Refused with `InvalidPrefix`; never accepted or indexed, so no node programs it | Unit | #1074 | +| 8 | Partial provisioning | `galactic-edge` killed during `Provision` | On restart the partial state is found by alias and finished or released; no gate opened | Root unit | #995 | +| 9 | Delayed cleanup | Old owner's release runs after a replacement is active | Replacement's link, routes and gate untouched | Root unit, lab | #995, #998 | +| 10 | Provider crash | `SIGKILL` the provider | Gate closed ≤ 15.5 s after the last renewal start; local withdrawal ≤ 1 s later | Lab, Talos | #997 | +| 11 | Provider stall | `SIGSTOP` the provider | Same bounds as row 10 | Lab, Talos | #997 | +| 12 | API isolation, packets still flowing | Block the node's API traffic only | Gate closed ≤ 15.5 s; replacement elsewhere activates no earlier than `TakeoverWait` after its first read | Talos | #997 | +| 13 | Cross-node replacement | Delete the provider pod; replacement lands on another node | No capture interval in which both nodes forward the prefix; outage measured and reported | Lab, Talos | #997, #1000 | +| 13a | Early takeover | Another instance swaps a held route to itself at once, with the holder still renewing, then with the holder stopped | Not accepted while the holder renews; accepted no earlier than the old gate's `closedEpoch` or `TakeoverWait` after the holder stops; never two forwarders | Unit, lab | #997 | +| 13b | Stale leader view | Delay the holder's renewals reaching the core leader's informer while the holder keeps renewing | No takeover accepted; the leader's quorum reads see the renewals | Unit, lab | #997 | +| 13c | Release while renewing | Holder releases one route and keeps renewing its instance; another attachment claims it | Accepted only after the holder's node writes `closedEpoch`; never two forwarders | Unit, lab | #997 | +| 13d | Spec swap without acceptance | A sibling pod swaps a held route's epoch to itself while the holder renews | The holder keeps forwarding; core refuses; no gate change on either node | Unit, lab | #997 | +| 13e | Removal with the node agent stuck | `SIGSTOP` `galactic-edge`, keep the provider renewing, delete the route | Gate closed ≤ 15.5 s after the deletion; the prefix is free for a new claim `TakeoverWait` after core recorded the deletion | Lab | #997 | +| 14 | `galactic-edge` stall | `SIGSTOP` the node agent | Gate closed ≤ 15.5 s; nothing reopens on resume until a fresh renewal | Lab, Talos | #997 | +| 15 | `galactic-edge` restart | Restart with active attachments | Forwarding continues to its deadline; no deadline extended from cached state | Root unit, lab | #995, #997 | +| 15a | Provider restart in place | Kill the provider process; the container restarts in the same pod | Routes accepted again with no wait beyond the instance's own `TakeoverWait`; forwarding resumes ≤ 15.53 s after the restarted process first reads its instance, plus accept-and-apply measured against the 1 s target | Lab | #997 | +| 16 | `galactic-router` down | Stop the node's router | Gate still closes on time; the route reflector withdraws the prefix ≤ 9 s after the router stops | Lab | #998 | +| 17 | Revocation | Delete the `EdgeService` or remove the prefix from the grant | Gate closed ≤ 15.5 s, measured against the 2 s target | Lab, Talos | #997, #999 | +| 18 | Grant ceiling | `validUntil` passes | Gate closed at or before `validUntil − MaxSkew` | Unit, lab | #997 | +| 19 | Missing or invalid policy | Reference a missing policy, or delete the `EdgeService` | Forwarding closed except neighbor discovery | Root unit, lab | #999 | +| 20 | Policy change | Change the service's policy reference, or the policy, under active traffic | New policy applies to the active attachment | Root unit, lab | #999 | +| 21 | GC with only edge users | Edge attachment is the gVPC's only user on the node; run GC and repair | VRF, `vrf_table` rows and attachment rows remain | Root unit, lab | #996 | +| 22 | Maintenance fence | Stale ticket committed after `Fence` | Refused; host state unchanged | Root unit | #996 | +| 23 | Node reboot | Reboot an edge node | No gate opens from the previous boot; claims are reacquired after `TakeoverWait` | Talos | #997 | +| 24 | Drain | Drain a service with active traffic | No new routes accepted; forwarding ends ≤ `drainSeconds`; resources released | Lab | #995 | +| 25 | Independent provider | Run rows 1 to 24 and their lettered rows with a provider built outside the core | All pass with no change to core source, schema, image or deployment | Talos | #1000, #1002 | + +Results record the commit, the environment, measured timings per row and packet captures for rows 6, 12 and 13. `tests/edgeconformance` runs the rows the containerlab lab can host with the reference provider (`task verify:edge-conformance`). + +## Open items + +These need an answer before the milestone named: + +- **Namespace acquisition (#1002).** `galactic-edge` finds the provider pod's network namespace through the node's CRI socket, from containerd's verbose sandbox status, and checks the sandbox's pod UID before `hostattach.Provision`. This needs proof on the target platform, whose CRI socket path and permissions are deployment values that differ from Kind's. +- **Capacity limits (#994).** The per-cell limits for providers, instances, attachments and routes come from the scale measurements in #1002. Until then admission keeps 10% of each shared eBPF map free, so a draining attachment and its replacement can hold rows at the same time, and refuses requests beyond that. +- **Hold time on edge sessions (#998).** The timers that keep the hold time at or under 9 s are deployment values: this repository's lab sets 9 s on both ends of every edge node's session, and datum-cloud/infra sets production's. +- **Remote convergence target (#998).** The 5 s target is checked against the lab's route reflector topology, then against production's. diff --git a/docs/edge/troubleshooting.md b/docs/edge/troubleshooting.md index f812169a1..c006237e8 100644 --- a/docs/edge/troubleshooting.md +++ b/docs/edge/troubleshooting.md @@ -3,9 +3,9 @@ How to find where an edge attachment or route stopped, which objects are involved, and who forwards a prefix now, from the conditions, Events and metrics the foundation emits. The lifecycle itself is defined in -[the provider contract](../enhancements/networking/galactic-edge/contract.md); +[the provider contract](provider-contract.md); the metrics are listed in -[the metrics reference](../metrics.md#galactic-edge-foundation--galactic_edge_foundation_). +[the metrics reference](../observability/edge.md#galactic-edge-foundation--galactic_edge_foundation_). ## Lifecycle stages @@ -171,7 +171,7 @@ section bounds. `config/monitoring/` ships the PodMonitors for both components and the `galactic-edge` alert group, listed in -[the metrics reference](../metrics.md#shipped-alerts). They fire on what the +[the metrics reference](../observability/alerts.md#shipped-alerts). They fire on what the foundation itself stopped doing: attachments not programmed, services without a resolvable policy, lost ownership scopes, failing cleanup and unreachable metrics. A refused admission is a tenant or provider decision diff --git a/docs/enhancements/dns64/README.md b/docs/enhancements/dns64/README.md index c80d8a83e..52d91247e 100644 --- a/docs/enhancements/dns64/README.md +++ b/docs/enhancements/dns64/README.md @@ -1,215 +1,59 @@ # Shared DNS64 service -Status: Proposed. This design has not passed end-to-end Galactic validation. +This document moved to [README](../../designs/dns64/README.md). Update bookmarks to the maintained page. -## Summary + -Provide a managed DNS64 service for IPv6-only Compute instances. PowerDNS -Recursor resolves public names and synthesizes AAAA records from A records -when a name has no usable native AAAA record. Galactic's NAT64 gateway -translates connections to IPv4. +See [Summary](../../designs/dns64/README.md#summary). -The initial service uses one shared `/96` NAT64 prefix per serving fabric and a -shared regional resolver fleet. The planning range is 10,000–100,000 tenants; -it is not a verified capacity limit. The service scales resolver capacity by -traffic and configuration size instead of deploying a resolver for every -tenant. + -Private DNS, tenant-specific views, private zones, conditional forwarding, -and tenant-specific NAT64 prefixes are outside this proposal. +See [Motivation](../../designs/dns64/README.md#motivation). -## Motivation + -IPv6-only instances need to reach IPv4-only public services without requiring -each customer to operate a DNS64 resolver or NAT64 gateway. A managed service -provides a consistent resolver address and connects DNS synthesis to the -Galactic routing and NAT64 path. +See [Goals](../../designs/dns64/README.md#goals). -## Goals + -- Resolve public names for IPv6-only instances. -- Synthesize eligible AAAA records using the shared NAT64 prefix. -- Deliver a stable IPv6 resolver endpoint through the Compute network path. -- Scale through shared resolver replicas and bounded capacity shards. -- Validate DNSSEC behavior, synthesis exclusions, abuse controls, failover, and - end-to-end NAT64 connectivity. -- Report resolver health, query failures, synthesis, and NAT64 reachability. +See [Non-goals](../../designs/dns64/README.md#non-goals). -## Non-goals + -- Provide private zones, split-horizon DNS, or customer DNS forwarding. -- Provide tenant-specific resolver views, caches, upstreams, or NAT64 prefixes. -- Build a DNS protocol engine or replace public authoritative DNS. -- Operate an open recursive resolver or expose public encrypted DNS endpoints. -- Make IPv4 literals work or create connectivity to unreachable destinations. -- Preserve established connections when a NAT64 gateway loses session state. +See [High-level architectural proposal](../../designs/dns64/README.md#high-level-architectural-proposal). -## High-level architectural proposal + -Use PowerDNS Recursor as the short-term recursive DNS64 engine. Its native -`recursor.dns64_prefix` setting supplies the shared `/96` prefix and performs -RFC 6147 synthesis. A DNS service controller publishes resolver configuration -and readiness. Galactic supplies network isolation, resolver endpoint routing, -and NAT64 forwarding. dnsdist and authoritative DNS components are deferred -until a later capability requires them. +See [Endpoint access and resource controls](../../designs/dns64/README.md#endpoint-access-and-resource-controls). -A resolver shard is a bounded group of PowerDNS Recursor replicas. Shards are -selected by aggregate query rate, cache size, and operational limits rather -than by one-process-per-tenant allocation. The initial endpoint is shared by -the serving region; workload attachment and routing determine which network -may reach it. + -![Compute uses Galactic to reach a shared PowerDNS Recursor fleet and a separate NAT64 gateway. A DNS service controller reads the gateway prefix from the network API.](containers.svg) +See [Design details](../../designs/dns64/README.md#design-details). -[Container diagram source](containers.puml). + -The container diagram is the component and relationship reference. The -resolver service and PowerDNS Recursor are shared regionally; the NAT64 path is -separate from the DNS query path. +See [Resolution and connection flow](../../designs/dns64/README.md#resolution-and-connection-flow). -### Endpoint access and resource controls + -The resolver VIP is a managed network service. Galactic authorizes the workload -attachment and routes only eligible network traffic to the endpoint. The -attachment and resolver service must reject spoofed sources and unauthorized -queries. +See [Shared prefix and routing contract](../../designs/dns64/README.md#shared-prefix-and-routing-contract). -The first milestone does not require a resolver process or cache per tenant. -Bound shard memory, connections, outstanding queries, and query rates. Apply -ACLs and rate limits at the resolver service and enforce limits consistently -across replicas. Reject EDNS Client Subnet from clients and do not send it to -public upstreams unless a later privacy review approves an exception. + -## Design details +See [Synthesis and DNS security](../../designs/dns64/README.md#synthesis-and-dns-security). -### Resolution and connection flow + -The Compute platform configures the instance. The instance then uses ordinary -DNS and TCP or UDP; the DNS service controller is not on the query path. +See [Configuration and rollout](../../designs/dns64/README.md#configuration-and-rollout). -![The Compute platform attaches an IPv6-only instance to Galactic and supplies a resolver endpoint. PowerDNS Recursor returns a synthesized address. Galactic routes the connection through NAT64 to an IPv4 service.](resolution-sequence.svg) - -[Sequence diagram source](resolution-sequence.puml). + -The sequence diagram is the flow reference. The important invariants are that -DNS does not select a NAT64 gateway, the synthesized address uses the shared -prefix, and application traffic returns through the same translation path. +See [Availability, capacity, and operations](../../designs/dns64/README.md#availability-capacity-and-operations). -The [CNI route implementation][cni-routes] and [NAT64 gateway design][nat64-design] -define the existing networking side of this flow. Resolver endpoint delivery -remains a proposed integration. + -### Shared prefix and routing contract +See [Implementation boundary](../../designs/dns64/README.md#implementation-boundary). -Use one Datum-managed `/96` prefix shared across the fabric. Read it from -[`EgressShard.status.nat64Prefix`][egress-status]; do not allocate prefixes in -the DNS service. Require agreement between assigned NAT64 shards and the CNI -configuration before enabling synthesis. - -Require current gateway status, route convergence, and active IPv4 connection -checks. The current [`Ready` condition][shard-readiness] reports an attached -translation program, not working IPv4 connectivity. Operators must provide -[IPv4 return routing][return-routing]. - -If the prefix is missing or inconsistent, disable synthesis and report the -reason. Native IPv6 resolution can continue. Coordinate prefix changes with -route retention for cached synthesized answers; clients can retain earlier -answers until their TTL expires. - -### Synthesis and DNS security - -Follow [RFC 6147][dns64-rfc]. Synthesize only for an AAAA query when eligible -A records exist and no usable native AAAA record exists. Preserve NXDOMAIN, -negative answers, and upstream errors. Exclude IPv4 literals, special-use -names, destinations covered by local policy, and any destination that must -remain unreachable. - -Enable PowerDNS Recursor DNSSEC validation. Do not synthesize when validation -returns `Bogus`. Synthesized records are generated by the resolver and do not -carry a signature from the original zone. Validate behavior for signed -IPv4-only names, unsigned names, SERVFAIL, and negative answers. - -Use public-root trust anchors and query-name minimization for public -resolution. Apply ACLs, response-rate limiting, maximum response sizes, and -resource limits to reduce cache-poisoning, amplification, and denial-of- -service risk. - -### Configuration and rollout - -The DNS service controller distributes versioned fleet configuration to the -assigned resolver shards. The initial configuration contains the shared -prefix, public upstream policy, ACLs, synthesis exclusions, resource limits, -and observability settings. It does not manage tenant zones or tenant DNS -records. - -Validate each revision before activation and retain the previous revision for -rollback. Drain a replica before upgrade, verify health and synthesis, then -return it to service. Admit a shard only after its configuration, resolver -health, and NAT64 prefix agree with the active revision. - -### Availability, capacity, and operations - -Place resolver replicas across failure domains within each region. Keep enough -spare capacity to lose a replica. Use a stable IPv6 VIP with health-aware -backend selection. Rebuild caches after failure; do not treat them as durable -state. - -Assign shards by query rate, cache size, response size, and connection limits. -Configuration and memory still grow with aggregate traffic, but shared replicas -avoid a fixed deployment per tenant. Measure query latency, error rate, -synthesis rate, cache hit rate, resolver resource use, and NAT64 connection -success. Bound metric cardinality and query-log retention. Add tenant-level -accounting only when quotas or billing require it. - -## Implementation boundary - -The existing prototype exercised dnsdist, BIND, and Jool in a controlled lab. -That implementation is not the short-term production design. The new prototype -must exercise PowerDNS Recursor with the shared prefix and the intended -Galactic/NAT64 path. Jool remains a test fixture only. - -The Galactic compatibility profile validates saved configuration offline; it -does not prove the Galactic packet path. Controlled upstreams and same-host -replicas do not establish internet-resolution performance or failure-domain -availability. - -Galactic source reviewed on September 16, 2026, supports TCP and UDP. It lacks -ICMP translation, fragmentation handling, and path MTU discovery, and it does -not provide full [RFC 6146][nat64-rfc] behavior. Gateway restart loses session -state. See the [datapath limits][nat-limits] and [gateway design constraints][nat64-constraints]. - -Before a production pilot, complete these checks: - -1. Verify resolver endpoint delivery and unauthorized-source rejection through - Galactic. -2. Test native AAAA, synthesized AAAA, DNSSEC failures, exclusions, negative - answers, and upstream failures. -3. Verify the intended NAT64 route and IPv4 return path with TCP and UDP; - measure gateway restart, stale status, and large-packet behavior. -4. Qualify PowerDNS Recursor shard limits, cache behavior, rate limiting, - rolling upgrades, configuration rollback, and resolver failover. -5. Run load and abuse tests at the planned 1,000, 5,000, and 10,000 aggregate - QPS shard profiles. - -Production requires agreed service objectives, a durable control-plane design, -and a documented resolution or accepted product restriction for NAT64 protocol -limits. - -## Diagram maintenance - -Edit the PlantUML sources, then regenerate both SVG files from the repository -root. PlantUML 1.2026.5 and its bundled C4 library produced these diagrams. - -```sh -plantuml -tsvg docs/enhancements/dns64/containers.puml docs/enhancements/dns64/resolution-sequence.puml -``` - -[nat64-design]: https://github.com/datum-cloud/enhancements/blob/a778a6c3104b60b0e7634af4f3e5d2e3ae303549/enhancements/networking/nat64-gateway-for-vpc-networks.md#L184-L198 -[egress-status]: https://github.com/datum-cloud/network/blob/ec15d7bda7eb47960a5e2b38daa4d30d42b12748/api/v1alpha1/egressshard_types.go#L90-L114 -[cni-routes]: https://github.com/datum-cloud/galactic/blob/846f5d2a189f2849e044de3b383b5ca7be759777/internal/cnibgp/bgp.go#L759-L834 -[shard-readiness]: https://github.com/datum-cloud/galactic/blob/846f5d2a189f2849e044de3b383b5ca7be759777/internal/controller/egressshard_controller.go#L286-L303 -[return-routing]: https://github.com/datum-cloud/galactic/blob/846f5d2a189f2849e044de3b383b5ca7be759777/internal/controller/egressshard_controller.go#L180-L184 -[nat-limits]: https://github.com/datum-cloud/galactic/blob/846f5d2a189f2849e044de3b383b5ca7be759777/internal/plumbing/ebpf/natprog/nat.c#L74-L92 -[nat64-constraints]: https://github.com/datum-cloud/enhancements/blob/a778a6c3104b60b0e7634af4f3e5d2e3ae303549/enhancements/networking/nat64-gateway-for-vpc-networks.md#L184-L198 -[dns64-rfc]: https://www.rfc-editor.org/rfc/rfc6147.html -[nat64-rfc]: https://www.rfc-editor.org/rfc/rfc6146.html + + +See [Diagram maintenance](../../designs/dns64/README.md#diagram-maintenance). diff --git a/docs/enhancements/networking/galactic-edge/README.md b/docs/enhancements/networking/galactic-edge/README.md index 9d59930b7..d78a7d36d 100644 --- a/docs/enhancements/networking/galactic-edge/README.md +++ b/docs/enhancements/networking/galactic-edge/README.md @@ -1,261 +1,107 @@ ---- -status: provisional -stage: alpha -latest-milestone: "TBD" ---- - # Galactic Edge Foundation -Tracking issue: [Galactic Edge Foundation (#992)](https://github.com/datum-cloud/galactic/issues/992). - -This draft follows the [Datum enhancement template](https://github.com/datum-cloud/enhancements/blob/main/enhancements/template/README.md). The architecture is proposed; this document does not assert that it is implemented. - -- [Summary](#summary) -- [Motivation](#motivation) -- [Proposal](#proposal) -- [Design Details](#design-details) -- [Production Readiness Review Questionnaire](#production-readiness-review-questionnaire) -- [Implementation History](#implementation-history) -- [Drawbacks](#drawbacks) -- [Alternatives](#alternatives) - -## Summary - -Galactic Edge is a common foundation for services that connect external networks and clients to gVPC workloads. A service integrates as a **provider**: it requests an authorized tenant attachment and declares which authorized prefixes it can serve. The foundation supplies isolation, gVPC traffic policy, route lifecycle, recovery, and exclusive forwarding ownership. - -Providers own their protocols and client sessions. Galactic Edge owns the boundary between those services and shared VPC networking. A new provider should integrate through the same contract without changing the foundation or receiving direct access to shared host networking. - -## Motivation - -External connectivity services need many of the same networking guarantees, even when their protocols differ. Each needs a tenant-specific path into the VPC, a return path, authorization, policy enforcement, and safe cleanup when an instance fails or moves. Reimplementing these responsibilities in each service creates competing writers and inconsistent failure behavior. - -Galactic Edge makes these guarantees reusable while retaining the existing Galactic routing and SRv6 data plane. It gives service authors a small integration boundary and operators one model for attachment health and ownership. - -### Goals - -- Connect independently developed providers to authorized gVPCs through one internal contract. -- Isolate tenants, including tenants using identical addresses. -- Publish prefix reachability only while authorization, attachment readiness, and exclusive forwarding ownership remain valid. -- Bound forwarding expiry and route withdrawal during failure, including API outages and stalled providers. -- Recover owned resources without disrupting workloads or other services. - -### Non-Goals - -- Define public customer APIs, enrollment experiences, or client software. -- Specify a transport protocol, credential format, prefix size, or session migration mechanism. -- Replace Galactic's routing control plane or build a general networking plugin marketplace. -- Migrate every existing gateway or NAT service into the framework. -- Define concrete schemas, RPC methods, kernel objects, or deployment manifests. - -## Proposal - -Introduce Galactic Edge as the trusted intermediary between service providers and gVPC networking. Its first contract supports isolated packet attachments and authorized prefix reachability. Additional capabilities should be added only when a concrete consumer requires them. - -### System context — C4 level 1 - -The framework is the system of interest. Providers and existing Galactic networking are separate systems with explicit responsibilities. - -```mermaid -C4Context - title Galactic Edge - system context - Person(operator, "Platform operator", "Configures provider access and observes attachment health") - System_Ext(client, "External network or client", "Exchanges tenant traffic through a provider") - System_Ext(provider, "Connectivity provider", "Owns its external protocol and client sessions") - System(edge, "Galactic Edge", "Authorizes and manages isolated VPC attachments and prefix reachability") - System_Ext(authority, "Platform authority", "Supplies trusted provider identity, VPC grants, and policy") - System_Ext(vpc, "Galactic VPC networking", "Routes traffic to and from tenant workloads") - Rel(operator, authority, "Configures grants and policy") - Rel(operator, edge, "Observes lifecycle and failures") - BiRel(client, provider, "Service-specific traffic") - Rel(provider, edge, "Requests attachment and prefix reachability") - Rel(edge, authority, "Validates authority and reads policy") - BiRel(edge, vpc, "Exchanges tenant traffic and manages reachability") -``` - -### Core concepts - -| Concept | Meaning | -| ------------------- | --------------------------------------------------------------------------------------------------------------------- | -| Provider | An authenticated service integration; its running instances own protocol-specific sessions. | -| Grant | Trusted authorization for a provider to use a particular gVPC and specified prefixes, within a validity period. | -| Attachment | An isolated connection between a provider instance and one gVPC, with policy and lifecycle managed by the foundation. | -| Forwarding claim | Time-bounded, exclusive authority for an instance to forward for a particular grant. | -| Prefix reachability | The routes that direct traffic for an authorized prefix to its current forwarding owner. | - -A grant can outlive an individual connection. An attachment can exist while forwarding is disabled. A retained prefix does not imply that a route remains advertised. Keeping these lifetimes separate allows reconnects and recovery without leaving stale forwarding authority behind. - -### Representative provider - -Consider a service that connects an external site to a tenant's VPC. It establishes a session with that site and carries packets for an authorized site prefix. The protocol and prefix length are immaterial to this example. +This document moved to [galactic-edge](../../../designs/galactic-edge.md). Update bookmarks to the maintained page. -The provider requests an attachment for the tenant and reachability for the prefix. Galactic Edge verifies the grant, prepares the isolated connection, and enables forwarding and routing only when their prerequisites hold. Return traffic follows the published prefix to the attachment; the provider delivers it to the external site. + -A second service using a different protocol follows the same lifecycle. This is the reuse requirement in [#992](https://github.com/datum-cloud/galactic/issues/992), illustrated through an abstract provider. The [MASQUE proposal (#970)](https://github.com/datum-cloud/galactic/issues/970) is one potential consumer; its transport requirements are outside this design. +See [Summary](../../../designs/galactic-edge.md#summary). -### Risks and Mitigations + -| Risk | Architectural response | -| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | -| A provider requests another tenant's resources | Validate trusted grants; provider-supplied identities and prefixes are requests, not authorization. | -| An old instance continues forwarding after replacement | Independently enforce local expiry and require fencing before replacement activation. | -| Cleanup removes a replacement's resources | Bind every mutation to immutable ownership identity and the current ownership generation. | -| A provider exhausts shared capacity | Bound attachments, prefixes, requests, and buffering; reject excess work before allocation. | -| The framework accumulates service-specific behavior | Prove integration with an independent provider against unchanged core artifacts. | - -## Design Details +See [Motivation](../../../designs/galactic-edge.md#motivation). -### Runtime boundaries — C4 level 2 + -The diagram separates the provider runtime, trusted foundation runtime, authoritative state, and existing routing and forwarding systems. The foundation's control and local enforcement responsibilities may require separate processes; their packaging is a contract-design decision. +See [Goals](../../../designs/galactic-edge.md#goals). -```mermaid -C4Container - title Galactic Edge - runtime boundaries - System_Ext(authority, "Platform authority", "Provider identity, grants, and VPC policy") - Container_Ext(provider, "Provider runtime", "Service process", "External protocol and client sessions") - System_Boundary(edge, "Galactic Edge") { - Container(control, "Foundation control", "Trusted control runtime", "Admission, attachment lifecycle, ownership, and route intent") - Container(local, "Local enforcement", "Trusted node runtime and datapath", "Isolated attachment, policy, and independent forwarding expiry") - } - ContainerDb_Ext(state, "Authoritative state", "Platform control plane", "Grants, ownership, and desired lifecycle state") - Container_Ext(router, "Galactic routing", "Existing routing control plane", "Publishes and withdraws VPC reachability") - Container_Ext(datapath, "VPC forwarding", "Existing Galactic datapath", "Carries isolated tenant traffic to and from workloads") - Rel(control, authority, "Validates grants and obtains policy") - Rel(provider, control, "Requests attachment, renewal, and release") - Rel(control, state, "Coordinates exclusive ownership and desired state") - Rel(control, local, "Reconciles authorized attachment and deadlines") - Rel(control, router, "Requests owner-scoped route publication") - Rel(local, router, "Invalidates local reachability on expiry") - BiRel(provider, local, "Exchanges packets through its attachment") - BiRel(local, datapath, "Exchanges policy-checked tenant traffic") -``` + -The state boundary is logical: this proposal does not require a new database. Likewise, Galactic Edge reuses the existing routing system rather than introducing another BGP implementation. Local withdrawal must have an API-independent enforcement path; writing desired state to an unavailable API is insufficient. +See [Non-Goals](../../../designs/galactic-edge.md#non-goals). -### Responsibility split + -The provider authenticates its clients, implements its external protocol, checks session-specific packet ownership, and handles connection recovery. It cannot expand its VPC or prefix authority by asserting a client identity. +See [Proposal](../../../designs/galactic-edge.md#proposal). -The foundation authenticates the provider and validates grants against trusted authority. It owns shared attachment resources, enforces gVPC policy in both directions, constrains traffic to the admitted tenant and prefix scope, and coordinates forwarding claims and routes. Provider checks can narrow access; they cannot replace foundation enforcement. + -Existing Galactic components continue to own their routing and forwarding subsystems. Their reconciliation, repair, refresh, and garbage collection must respect foundation resource ownership. A provider receives access only to its attachment, never unrestricted control of shared routes or host networking. +See [System context — C4 level 1](../../../designs/galactic-edge.md#system-context--c4-level-1). -### The provider contract + -The contract needs a small set of capabilities: request an attachment, request reachability for granted prefixes, observe readiness and failures, renew forwarding authority, and drain or release resources. It must define compatible versions and reject unsupported capabilities before provisioning. +See [Core concepts](../../../designs/galactic-edge.md#core-concepts). -Requests are scoped to immutable provider-instance and tenant identities. Retries are idempotent. Readiness reflects installed attachment and policy state, valid ownership, and local route programming; it does not promise that every remote router has converged. + -A provider may serve multiple tenants, but every packet enters through an explicit tenant attachment. Identical addresses in separate VPCs remain independent. Conflicting prefix ownership within one VPC is rejected. +See [Representative provider](../../../designs/galactic-edge.md#representative-provider). -### Attachment activation + -Preparation starts with forwarding closed. A claim alone is insufficient: local enforcement must be installed, the provider must be ready to receive traffic, and any previous owner must already be fenced. +See [Risks and Mitigations](../../../designs/galactic-edge.md#risks-and-mitigations). -```mermaid -sequenceDiagram - participant P as Provider - participant F as Foundation control - participant A as Authority and ownership state - participant L as Local enforcement - participant R as Galactic routing - P->>F: Request VPC attachment and granted prefix - F->>A: Verify identity, grant, and prefix authority - A-->>F: Authorized scope and validity ceiling - F->>A: Acquire exclusive forwarding claim - A-->>F: Ownership generation and deadline - F->>L: Prepare isolated attachment and policy, forwarding closed - L-->>F: Attachment prepared - F-->>P: Attachment available for preparation - P->>F: Ready to receive traffic - F->>L: Activate within current authority and deadline - L-->>F: Forwarding enforcement active - F->>R: Publish prefix for this owner - R-->>F: Local route contribution programmed - F-->>P: Ready, remote convergence proceeds separately -``` + -Every step rechecks the authority relevant to its mutation. Failed or partial activation remains unready and is reconciled or cleaned up. Work completed under expired authority cannot later become active through a delayed retry. +See [Design Details](../../../designs/galactic-edge.md#design-details). -### Failure and ownership replacement + -Forwarding authority expires independently of provider cooperation and API availability. The local forwarding gate must stop traffic even if the provider or its control loop stalls. Renewal cannot extend authority beyond the grant's validity ceiling. +See [Runtime boundaries — C4 level 2](../../../designs/galactic-edge.md#runtime-boundaries--c4-level-2). -Replacement waits until the old owner cannot forward, using confirmed fencing or a safely elapsed enforcement deadline under the defined clock assumptions. An unreachable owner is not proof of a fenced owner. A temporary outage is preferable to two active owners for the same grant. + -```mermaid -sequenceDiagram - participant Old as Old provider - participant L as Old node enforcement - participant A as Authority and ownership state - participant New as Replacement foundation - participant R as Galactic routing - Note over Old,A: API connectivity is lost while packet connectivity remains - Old--xA: Renewal fails - New->>A: Request replacement ownership - A-->>New: Previous authority may still be live, activation blocked - L->>L: Enforced deadline expires, stop forwarding - L->>R: Withdraw old owner's local route contribution - Note over A,New: Confirm fencing or establish safe expiry under clock assumptions - New->>A: Acquire next ownership generation - A-->>New: Replacement authority granted - New->>New: Prepare attachment and enforce new authority - New->>R: Publish replacement reachability - Note over L,R: Late old-owner cleanup cannot remove the replacement route -``` +See [Responsibility split](../../../designs/galactic-edge.md#responsibility-split). -The sequence shows required ordering, not a chosen lease algorithm. Numeric forwarding-expiry, revocation, and local-withdrawal bounds, including their clock and failure assumptions, are set in the [provider contract](contract.md#timing-and-failure-bounds). Remote route convergence is measured separately. Stale remote routes may cause packet loss, but must not restore expired local forwarding authority. + -On restart, cached state is evidence for reconciliation, not permission to resume forwarding. Revalidate authority before reopening the attachment. +See [The provider contract](../../../designs/galactic-edge.md#the-provider-contract). -### Drain, cleanup, and policy updates + -Drain stops new admissions and lets the provider finish existing work within a bounded window. Final release closes forwarding, withdraws the owner's reachability, and removes its attachment resources. Prefix retention follows the grant's lifecycle rather than the session's lifecycle. +See [Attachment activation](../../../designs/galactic-edge.md#attachment-activation). -Recovery and cleanup use the same ownership rules as normal operations. They must preserve replacement routes, other providers' attachments, and shared VPC resources still in use. + -Policy changes apply to active attachments. Missing or invalid required policy keeps affected forwarding closed, with explicitly permitted control traffic preserved. Revocation shortens authority; it does not wait indefinitely for a provider to acknowledge it. During disconnection, previously granted authority can last only until its independently enforced deadline. +See [Failure and ownership replacement](../../../designs/galactic-edge.md#failure-and-ownership-replacement). -## Production Readiness Review Questionnaire + -This provisional draft records the readiness expectations. Measurements and mechanism-specific answers are required before the design becomes implementable. +See [Drain, cleanup, and policy updates](../../../designs/galactic-edge.md#drain-cleanup-and-policy-updates). -### Feature Enablement and Rollback + -Enable the foundation and each provider explicitly. Existing services retain their current behavior. Disable by stopping admission, draining or fencing active owners, withdrawing routes, and cleaning up owned resources. Removing a deployment alone is not a complete rollback procedure. +See [Production Readiness Review Questionnaire](../../../designs/galactic-edge.md#production-readiness-review-questionnaire). -### Rollout, Upgrade and Rollback Planning + -Qualify an independent provider against fixed core artifacts on the target Talos/Cilium environment. Test overlapping tenants, unauthorized requests, policy changes, partial setup, provider crash and pause, API isolation, restart, cross-node replacement, and delayed cleanup. Capture packet evidence and failure timings. Upgrade and rollback must preserve the same ownership rules and reject incompatible contracts before activation. +See [Feature Enablement and Rollback](../../../designs/galactic-edge.md#feature-enablement-and-rollback). -### Monitoring Requirements + -Expose admission failures, attachment readiness, active ownership and expiry, policy drops, route publication and withdrawal, resource use, and cleanup failures. Operators should be able to distinguish an unauthorized request, an unready attachment, expired ownership, and routing convergence without inspecting the provider's protocol internals. +See [Rollout, Upgrade and Rollback Planning](../../../designs/galactic-edge.md#rollout-upgrade-and-rollback-planning). -### Dependencies + -The foundation depends on trusted identity and grant state, gVPC policy, existing Galactic routing and forwarding, and supported node networking. Authority outages prevent new ownership and renewals; existing forwarding ends at its enforced deadline. Routing outages can delay remote reachability but cannot extend forwarding authority. +See [Monitoring Requirements](../../../designs/galactic-edge.md#monitoring-requirements). -### Scalability + -Set and test limits for providers, attachments, claims, prefixes, reconciliation work, and packet resources. Measure steady-state operation and renewal or reconnect bursts. No capacity or throughput target is claimed by this draft. +See [Dependencies](../../../designs/galactic-edge.md#dependencies). -### Troubleshooting + -Report lifecycle state and the reason progress stopped, correlated by provider, attachment, grant, and ownership generation. Measure local forwarding cutoff, local route withdrawal, and remote convergence separately. Avoid one health indicator that hides these distinct failure domains. +See [Scalability](../../../designs/galactic-edge.md#scalability). -## Implementation History + -- 2026-10-22: Initial architecture enhancement drafted, based on [#992 and its milestones](https://github.com/datum-cloud/galactic/issues/992). No implementation or qualification results are claimed here. +See [Troubleshooting](../../../designs/galactic-edge.md#troubleshooting). -## Drawbacks + -The shared foundation becomes a dependency for every adopting provider. Its contract needs careful evolution, and its privileged scope requires strong isolation tests. Exclusive ownership also introduces an intentional gap in availability when safe replacement requires waiting for expiry. +See [Implementation History](../../../designs/galactic-edge.md#implementation-history). -## Alternatives + -**Each service owns its networking.** This permits independent development but duplicates authorization, resource recovery, and fencing. It also creates multiple writers to shared networking state. +See [Drawbacks](../../../designs/galactic-edge.md#drawbacks). -**Share a helper library only.** A library can reduce duplicate code, but does not by itself establish a trusted owner for shared resources or enforce expiry when its caller stalls. Libraries may support the foundation internally. + -**Build one service containing every protocol.** This centralizes ownership but couples protocol releases and failures. Independent providers preserve a smaller common framework and separate service lifecycles. +See [Alternatives](../../../designs/galactic-edge.md#alternatives). diff --git a/docs/enhancements/networking/galactic-edge/contract.md b/docs/enhancements/networking/galactic-edge/contract.md index 61a27a4e7..da77cb229 100644 --- a/docs/enhancements/networking/galactic-edge/contract.md +++ b/docs/enhancements/networking/galactic-edge/contract.md @@ -1,456 +1,119 @@ ---- -status: provisional -stage: alpha -latest-milestone: "TBD" ---- - # Galactic Edge provider contract -Tracking issue: [Define the internal provider contract (#993)](https://github.com/datum-cloud/galactic/issues/993), part of [#992](https://github.com/datum-cloud/galactic/issues/992). - -This document is the contract the [Galactic Edge foundation](README.md) is built to. It fixes the resources, writers, state transitions, timing bounds and acceptance tests that the implementation milestones (#994 to #1002) follow. Where it names existing code, it describes that code; where it names a resource or process that does not exist yet, it is a decision, not a description. - -- [Decisions](#decisions) -- [Resources](#resources) -- [Provider interface](#provider-interface) -- [Lifecycle](#lifecycle) -- [Timing and failure bounds](#timing-and-failure-bounds) -- [Foundation resources and their writers](#foundation-resources-and-their-writers) -- [Failure-test matrix](#failure-test-matrix) -- [Open items](#open-items) - -## Decisions - -| Area | Decision | -| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Contract representation | Kubernetes resources in `galactic.datumapis.com/v1alpha1`. A provider talks only to the cell's API server; there is no provider RPC. | -| Contract version | `v1alpha1`. Capabilities are versioned separately: `SocketAccess/v1`, `PacketAccess/v1`, `PrefixReachability/v1`. | -| Provider authority | The API server's authentication of the provider pod's bound ServiceAccount token, checked by a ValidatingAdmissionPolicy (see [Admission policy](#admission-policy)). A pod-UID field a provider writes is only checked against the token, never trusted on its own. | -| Control packaging | Admission, allocation and publication run in `galactic-controller --role=cell`, leader-elected, one writer per cell. | -| Node packaging | A new `galactic-edge` DaemonSet on nodes labeled `galactic.datumapis.com/node=edge` and `galactic.datumapis.com/edge=enabled`. The `edge=enabled` label is new, and [node labels](../../../node-labels.md) gains it when the DaemonSet ships. `galactic-edge` is the only process that changes host state for an edge attachment. It writes only the CNI datapath's maps under `/sys/fs/bpf/galactic`, and never opens `/sys/fs/bpf/galactic-edge`, which is `galactic-gateway`'s pin directory despite the name (`internal/plumbing/ebpf/edgeattach/attach.go:38`). | -| Provider privilege | None on the host. A provider pod gets no host namespace, hostPath, `NET_ADMIN` or BPF access. It opens the packet device the node agent created in its own network namespace. | -| Claim store | The cell's API server, compare-and-swap on `resourceVersion` with a UID precondition, as `internal/edge/claim` requires. Claims never span cells. | -| Node-local write fence | `internal/edge/ownership`, with its state and lock files in the hostPath `/var/lib/galactic-edge/ownership`, shared by every process that writes a fenced scope on the node. | -| Forwarding gate | A new map of the CNI datapath, with one row per edge host link and per accepted prefix holding a `CLOCK_BOOTTIME` deadline. The datapath compares it with `bpf_ktime_get_boot_ns` on every packet, the pattern `serviceroutemap` already uses for authorization deadlines. | -| Allocation | Attachment addresses come from the service's client pool, allocated by the leader of `galactic-controller`. Delegated client prefixes are routes the provider requests inside that pool; the prefix conflict check makes them exclusive. No new host table or uSID Argument is allocated: an edge attachment joins the VPC's canonical host VRF. | - -## Resources - -All resources are in `galactic.datumapis.com/v1alpha1`. Object names that carry identity are derived, so a retried create lands on the same object. - -| Kind | Scope | Name | Purpose | -| ---------------- | --------- | ----------------------------------- | --------------------------------------------------------------------------- | -| `EdgeProvider` | Cluster | Operator's choice | Registration: contract and capability versions, ServiceAccounts, privilege. | -| `EdgeService` | Namespace | Platform authority's choice | Grant: one provider, one gVPC, prefixes, client pool, validity. | -| `EdgeInstance` | Namespace | `ei-` + pod UID | One running provider process. | -| `Lease` | Namespace | The instance's name | The instance's liveness lease, a `coordination.k8s.io/v1` Lease it owns. | -| `EdgeAttachment` | Namespace | `ea-` + pod UID + `-` + service UID | One instance's isolated connection to the service's gVPC. | -| `EdgeRoute` | Namespace | `hash(gVPC UID, prefix)` | One prefix's forwarding claim and publication. | -| `EdgeRouteIndex` | Namespace | gVPC UID | Core's record of every accepted route in one gVPC; serializes acceptance. | - -`EdgeInstance`, its `Lease`, `EdgeAttachment` and `EdgeRoute` live in the provider's namespace. `EdgeService` and `EdgeRouteIndex` live in the namespace of the gVPC they reference. - -Core finds a route by its spec, never by its name. A route's name only has to be the same in every instance of one provider, so that they contend for a prefix through one object; the hash is the provider's choice. - -### Fields and writers - -A field not listed is read-only to everyone but the control plane that owns the resource. "Core" is `galactic-controller --role=cell`; "node" is `galactic-edge` on the attachment's node. - -| Resource and field | Writer | Rule | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `EdgeProvider.spec` | Operator | Contract versions, capabilities, ServiceAccounts, configuration kind. | -| `EdgeProvider.status.approved` | Operator approval role | No provider ServiceAccount holds `edgeproviders/status`. | -| `EdgeService.spec` | Platform authority | `providerRef`, `vpcRef.uid` and capabilities are immutable. `trafficPolicy` selects the policy of every attachment the service admits (see [Traffic policy](#traffic-policy)). | -| `EdgeService.status` | Core | `Admitted` and `TrafficPolicyResolved` conditions, and `allocations`: each held client-pool address and its attachment, written with a `resourceVersion` precondition. | -| `EdgeInstance.spec` (`providerRef`, `podName`, `podUID`, `nodeName`, `bootID`) | The instance, at create | Immutable. Must match the token's pod UID and the pod's node. | -| The instance's `Lease` (`spec.holderIdentity`, `spec.leaseTransitions`, the `edge-renew-start`, `edge-sequence` and `edge-released` annotations) | The instance; core to fence it | Compare-and-swap on `resourceVersion` with a UID precondition (`internal/edge/provider`). Its provider label, pod annotation and owner never change, `leaseTransitions` never decreases, and a release holds until a new epoch: the `galactic-edge-lease` policy enforces these for every writer, and the provider policy limits a pod to its own lease. No provider deletes it. | -| `EdgeAttachment.spec` (`providerRef`, `serviceRef`, `instanceRef`, `podUID`, `contractVersion`, capabilities, `packetDevice`) | The instance, at create | Immutable. `podUID` must match the token; the instance must belong to the service's provider. | -| `EdgeAttachment.status` `Admitted`, `Allocated`, `Draining`, `Published`, `nodeName`, `vpc`, `address`, `drainDeadline` | Core | As `admission.MaySetCondition` allows. | -| `EdgeAttachment.status` `Programmed`, `Released`, device names | Node | `Programmed` only after `hostattach.Readback` succeeds; `Released` only after the host state is gone. | -| `EdgeAttachment.status` `Ready` | The instance | The only condition a provider sets. | -| `EdgeAttachment` finalizer | Core | Removed after the node confirms release. | -| `EdgeRoute.spec` (`providerRef`, `vpcUID`, `prefix`, `incarnation`) | An instance of the service's provider | Immutable. | -| `EdgeRoute.spec.claim` (`attachment`, `holderPodUID`, `holderInstance`, `instanceEpoch`, `epoch`, `released`) | A pod of the service's provider, naming itself and its own attachment | Compare-and-swap only. `holderPodUID` must match the token. Another pod may only replace the claim at a higher `epoch`; only the holder releases it. A write grants nothing until core accepts it. | -| `EdgeRoute.status` `Accepted`, `Claimed`, `Published` and the accepted holder (`accepted`: `epoch`, `attachment`, `attachmentUID`, `instance`, `instanceIncarnation`, `instanceEpoch`, `node`, `vpcNamespace`) | Core | Written only after the route is committed to the `EdgeRouteIndex`. See [Acceptance](#acceptance). | -| `EdgeRoute.status.closedEpoch` | `galactic-edge` on `accepted.node` | Never decreases and never passes `accepted.epoch`. A ValidatingAdmissionPolicy requires the writer's token node name (`authentication.kubernetes.io/node-name`) to equal `accepted.node`, and the change to touch only `closedEpoch`. | -| `EdgeRouteIndex` | Core | Compare-and-swap only. No provider ServiceAccount can read or write it. | -| `BGPAdvertisement` for an `EdgeRoute` | Core | One per route in `galactic-system`, named `edge-`, labeled with the route's UID and accepted epoch. No owner reference: the route is in another namespace. See [Publication](#publication). | -| Deletion of dead `EdgeInstance`s and `EdgeRoute`s | Core | See [Reaping](#reaping). | - -`admission.Writer` knows two writers, core and provider (`internal/edge/admission/admission.go:169`). `galactic-controller` and `galactic-edge` both count as core there, so `MaySetCondition` separates core from providers, not one core process from the other. The split between them in this table is enforced by RBAC and admission policies that limit `galactic-edge`'s ServiceAccount to `Programmed`, `Released`, device names and `closedEpoch`. - -## Provider interface - -A provider integrates in five steps, all through its own ServiceAccount. Its cell must also give it two things outside these resources: - -- **The packet device.** Kubernetes gives no unprivileged pod `/dev/net/tun`, and a provider has no hostPath or capability to reach it, so a cell that offers `PacketAccess` runs a device plugin that hands the device out as a resource, and a packet-access provider pod requests it. -- **The host VRF.** An attachment joins its gVPC's canonical host VRF on its node, which only CNI ADD creates, so a workload of the gVPC must run on the provider's node. - -[examples/edge-provider](../../../../examples/edge-provider) is a provider built only on this contract, with the deployment it needs. - -1. **Register.** The operator creates the `EdgeProvider` and approves it. Registration grants no tenant authority (`internal/edge/admission/admission.go:10`). -2. **Start an instance.** Each provider process creates its pod's `EdgeInstance`, takes over its lease and renews it every 5 s. The holder ID is new for every process start, so a restarted container cannot continue its predecessor's lease (`internal/edge/claim/claim.go:226`). -3. **Request an attachment.** The instance creates `EdgeAttachment` for an `EdgeService` that names its provider. It names the attachment for its pod and the service (`provider.AttachmentName`), which admission requires, and treats an existing attachment of that name that names another pod or service as a conflict to report, not one to retry (`provider.CreateAttachment` returns `provider.ErrNameTaken`). Core runs `admission.Admit` (`internal/edge/admission/admission.go:91`) before allocating anything, and refuses with the reasons defined there. #994 adds what `Admit` does not check today: capacity (`CapacityExhausted`) and identity conflicts on create (`IdentityConflict`). A service whose granted prefixes overlap an earlier service's in the same gVPC admits nothing (`PrefixConflict`). The instance waits for `Programmed`, opens the packet device or binds its sockets to the pod VRF named in status, then sets `Ready`. -4. **Request reachability.** For each prefix it serves, the instance creates or takes over the `EdgeRoute`, naming its own attachment. Core accepts it only if the prefix is inside the service's grant (`PrefixNotGranted`), overlaps no other route or subnet in the gVPC (`PrefixConflict`, see [Prefix conflicts](#prefix-conflicts)), does not contain the attachment's own address (`InvalidPrefix`), and the attachment is `Ready` and belongs to the writing pod. -5. **Drain and release.** The instance deletes its `EdgeRoute`s and `EdgeAttachment`s, or sets `released` on a claim after it has stopped forwarding. Core drains the same way when a service, grant or node goes away. - -### Compatibility - -- A request names one contract version and one version per capability. An unsupported version is refused before allocation with `UnsupportedContractVersion` or `UnsupportedCapability`. -- A core release supports the current contract version and the one before it. Admission refuses any other version with `UnsupportedContractVersion`, even one the `EdgeProvider` lists. Dropping a version requires that no `EdgeProvider` still lists it as its only version. -- A core release implements the capability versions listed under [Decisions](#decisions). Admission refuses any other capability version with `UnsupportedCapability`, even one the `EdgeProvider` lists. Core refuses or revokes an `EdgeRoute` with `UnsupportedCapability` unless its `EdgeProvider` lists `PrefixReachability` at a version core implements. -- Adding a capability adds a new name; it never changes what an existing version means. - -### Authorization context - -The foundation decides every request from three inputs, and nothing else: - -1. **Who is asking.** The authenticated ServiceAccount and pod UID from the request's bound token. The ValidatingAdmissionPolicy rejects a write whose `podUID` or `holderPodUID` differs from the token's pod UID, or whose ServiceAccount is not one the `EdgeProvider` lists. A policy cannot read other objects, so core checks the rest before accepting: the attachment a route names belongs to the same pod, and the instance an attachment names has the same pod UID. One provider pod therefore cannot write another pod's instance, attachment or claim, or point its own claim at another pod's attachment. -2. **What the provider may do.** The approved `EdgeProvider`. -3. **What the tenant granted.** The `EdgeService`, written by the platform authority: one gVPC, capabilities, prefixes, client pool and an optional `validUntil`. - -Client identities, prefixes and session state that a provider learns from its own clients can narrow what it requests. They never widen it, and the foundation never reads them. The provider checks packet ownership per client session; the foundation independently limits every packet on the attachment to the attachment address and the prefixes the instance currently holds. - -### Admission policy - -A ValidatingAdmissionPolicy reads only its own parameter object, so the provider checks are built this way: - -1. Every `EdgeInstance`, `EdgeAttachment` and `EdgeRoute` carries an immutable `providerRef`. Core refuses an attachment whose `providerRef` differs from its service's, and a route whose `providerRef` differs from its attachment's. -2. One policy, `galactic-edge-provider`, has `paramKind` `EdgeProvider`. For each approved `EdgeProvider`, core creates one ValidatingAdmissionPolicyBinding whose `paramRef` names that provider, with `parameterNotFoundAction: Deny`, and a RoleBinding that grants its listed ServiceAccounts write access to the three kinds. -3. Each binding evaluates every create, update and delete by a ServiceAccount other than core's and the node agent's. A ServiceAccount the parameter lists may write only objects whose `providerRef` names the parameter, and only those ServiceAccounts may create or change such objects, so a provider cannot plant an object under an unregistered provider's name. Another ServiceAccount's delete, such as the namespace controller's, is left to RBAC. For a provider's own writes the requester must be in the object's namespace, and `podUID` or `holderPodUID` must equal the token's `authentication.kubernetes.io/pod-uid`. A provider creates an `EdgeInstance` or instance `Lease` only under the name derived from the pod it names (`provider.InstanceName`), so one pod cannot take another's name before it. The policy holds only the provider's ServiceAccounts to these names, so a provider's namespace should grant no other workload `create` on Leases. That extra is present on Kubernetes 1.30 and later; the node-name extra the instance and node agent checks read needs 1.32. -4. A provider that is not approved has no RoleBinding, so RBAC refuses its writes before the policy runs. Withdrawing approval deletes both bindings. -5. A person's writes are not checked by the policy: RBAC alone decides them, so an operator can still clear an object a provider left behind. -6. A second policy holds core's own RoleBinding writes to the provider ClusterRole. Kubernetes runs no admission policy on policy bindings themselves, so core's write access to those is bounded by RBAC alone. - -### Idempotency - -- Every create uses a derived name. `AlreadyExists` is answered by reading the object and comparing its immutable fields; a mismatch is refused with `IdentityConflict`, never overwritten. -- Claim writes are compare-and-swap. A lost reply is recovered as `claim.Instance.Renew` does: the writer rereads, and validity always runs from the start of the latest call. -- Node mutations go through `ownership.Authority.Commit` (`internal/edge/ownership/ownership.go:162`), which refuses a ticket issued before another commit. A retry built from an old view cannot undo newer state. - -### Readiness +This document moved to [provider-contract](../../../edge/provider-contract.md). Update bookmarks to the maintained page. -`Ready` on an attachment means only that the provider can take traffic. `Published` means: + -- core admitted and allocated it, -- the node programmed and read it back, including traffic policy, -- the instance's lease and the route's claim are valid, -- the node opened the forwarding gate, and -- the node's `galactic-router` installed the advertisement locally. +See [Decisions](../../../edge/provider-contract.md#decisions). -Core sets `Published` on each `EdgeRoute` from its router's report on the route's advertisement, and on each attachment while at least one route accepted on it is published. + -`Published` does not mean remote routers have converged. That is measured separately (see [Timing and failure bounds](#timing-and-failure-bounds)). +See [Resources](../../../edge/provider-contract.md#resources). -### Traffic policy + -An attachment's host link is a traffic policy subject like a workload's interface (see [Traffic policy on the node](../../../traffic-policy/node.md#edge-attachments)). The `EdgeService` selects its policy: `spec.trafficPolicy.ingressPolicyRef` for traffic delivered to the provider from the gVPC, and `egressPolicyRef` for traffic the provider sends into it. Each names a `TrafficPolicy` in the service's namespace. A provider controls neither: it cannot write the service, and a policy in its own namespace is never read. +See [Fields and writers](../../../edge/provider-contract.md#fields-and-writers). -- `galactic-edge` writes the link's policy row, with the attachment's address, and attaches `usid_egress` and `tp_deliver` while the link is still down. On a node that enforces policy but failed the kernel preflight, it reports `DatapathFailed` and leaves the link down. -- `galactic-router` publishes one snapshot per direction. Until it has, the link denies everything. It publishes nothing, and unbinds what it published, while the attachment is not `Admitted` or its service is gone, being deleted, replaced or granting another provider. -- An omitted reference selects the built-in `default-deny-all`. A reference to a missing policy denies everything as `policy_unavailable`. Neighbor discovery on the link is a link operation outside the rules, so it works under any policy. -- `galactic-router` republishes when the service's references or a referenced policy change, so the change applies to active attachments. A change to the service re-admits its attachments under the new generation without draining them. -- Core reports whether both references resolve in the service's `TrafficPolicyResolved` condition. + -## Lifecycle +See [Provider interface](../../../edge/provider-contract.md#provider-interface). -### Attachment + -```mermaid -stateDiagram-v2 - [*] --> Pending: instance creates EdgeAttachment - Pending --> Refused: admission fails - Pending --> Admitted: core, admission.Admit passes - Admitted --> Allocated: core assigns address - Allocated --> Programmed: node provisions, gate closed - Programmed --> Active: Ready, lease valid, previous owner fenced - Active --> Programmed: lease or claim expires, gate closes - Active --> Draining: delete, revocation or node drain - Programmed --> Draining: delete, revocation or node drain - Draining --> Released: window ends or provider finishes - Released --> [*]: node confirms cleanup, finalizer removed - Refused --> [*] -``` +See [Compatibility](../../../edge/provider-contract.md#compatibility). -| Transition | Writer | Guard | -| ----------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | -| Pending to Admitted | Core | Provider approved, versions supported, gVPC and capabilities granted, capacity available. | -| Admitted to Allocated | Core | An address in the client pool that no other attachment holds. | -| Allocated to Programmed | Node | Pod is on this node with the recorded UID; `hostattach.Provision` and `Readback` succeed; traffic policy rows exist. | -| Programmed to Active | Node | `Ready`, a lease valid on fresh reads, and a route whose accepted holder is this attachment and instance; core accepts a holder only after fencing. | -| Active to Programmed | Node | The kernel deadline passed or the claim moved; the node closes the gate and records it. | -| Any to Draining | Core | Deletion, `EdgeService` deleted or revoked, `validUntil` reached, or node maintenance. | -| Draining to Released | Node | Gate closed, routes withdrawn locally, `hostattach.Release` done, policy rows removed. | + -A failed step leaves the attachment in its last state with a condition naming the reason. Partial host state carries the attachment ID in the host link's alias, so the node finds and finishes it on restart (`internal/edge/hostattach/inventory.go:33`). +See [Authorization context](../../../edge/provider-contract.md#authorization-context). -### Forwarding claim + -Each `EdgeRoute` is the claim for one prefix in one gVPC. An instance renews one lease, not one per route, so the claim has two levels: +See [Admission policy](../../../edge/provider-contract.md#admission-policy). -- The instance's lease is a record of `internal/edge/claim`, keyed by the instance. Its holder renews it, and its epoch advances only when it is taken over. -- The `EdgeRoute` names the holder instance and that instance's epoch (`holderInstance`, `instanceEpoch`). It is written only on acquire, release and takeover. The claim is valid only while the named instance's lease is valid at that epoch. The node opens a prefix's gate only for the holder core accepted, while its own applied lease matches that holder (see [Acceptance](#acceptance)). + -```mermaid -stateDiagram-v2 - [*] --> Pending: holder swaps in epoch 1 - Pending --> Accepted: core checks grant, overlap and fencing - Pending --> Refused: grant or overlap check fails - Accepted --> Released: holder stopped forwarding - Accepted --> Pending: another attachment swaps in the next epoch - Accepted --> Pending: same attachment, newer instance epoch - Released --> Pending: a holder swaps in the next epoch - Accepted --> Revoked: grant revoked or subnet overlap -``` +See [Idempotency](../../../edge/provider-contract.md#idempotency). -The route record changes only on these transitions. Lease renewals happen on the holder instance's lease, and the node applies them to the route's gate while the accepted holder names that instance and epoch. + -`internal/edge/claim` implements the single-level lease, and providers use it for their instance's lease through `internal/edge/provider`'s store. +See [Readiness](../../../edge/provider-contract.md#readiness). -The lease is a `coordination.k8s.io/v1` Lease with the instance's namespace and name, owned by the `EdgeInstance`, so deleting the instance deletes it: + -| Lease field | Claim record | -| ---------------------------------------------------- | ----------------------------------------------------------------------------------- | -| `spec.holderIdentity` | Holder, the provider process; null while nobody holds it | -| `spec.leaseTransitions` | Epoch | -| `metadata.uid` | Incarnation | -| Annotation `galactic.datumapis.com/edge-renew-start` | The holder's `CLOCK_BOOTTIME` in decimal nanoseconds, read before it sent the write | -| Annotation `galactic.datumapis.com/edge-sequence` | Sequence, advanced on every renewal | -| Annotation `galactic.datumapis.com/edge-released` | `true` once the holder of the epoch stopped forwarding, otherwise `false` | -| Label `galactic.datumapis.com/edge-provider` | The instance's provider | -| Annotation `galactic.datumapis.com/edge-pod-uid` | The instance's `podUID` | +See [Traffic policy](../../../edge/provider-contract.md#traffic-policy). -Core and the node read a Lease as the instance's lease only when it is owned by that instance and its label and pod annotation match the instance; any other Lease of that name is no lease. A provider that finds its instance's or lease's name held by an object naming another pod gets `provider.ErrNameTaken`, which wraps `claim.ErrLost`, so it stops rather than retrying until that object is deleted. `spec.leaseDurationSeconds` and `spec.renewTime` are written for tools that display Leases and are never read: validity runs from the renew start on the node's clock, and observers time a lease on their own clocks. A provider takes a route by compare-and-swap on the route's current version (`provider.Claim`), at the next claim `epoch` whenever the holder changes or its claim ended. A provider's own wait is a courtesy, not the safety mechanism: the provider runs the code, so the foundation cannot rely on it. Safety comes from acceptance. + -### Acceptance +See [Lifecycle](../../../edge/provider-contract.md#lifecycle). -The gate follows the accepted holder, never the route's spec. The node opens a prefix's gate only on `accepted.node`, for `accepted.attachment`, and only while it holds an applied lease for `accepted.instance` at `accepted.instanceIncarnation` and `accepted.instanceEpoch`. A provider pod that swaps the spec to a new epoch changes nothing on any node until core accepts it, so it cannot cut off a live holder. Only core writes the accepted holder, and core accepts a new epoch in three cases: + -1. **First claim.** The route has no earlier accepted epoch in the `EdgeRouteIndex`, and no other entry overlaps its prefix. -2. **Same attachment.** The earlier accepted epoch named the same attachment. The gate, host link and pod are unchanged, so no second forwarder can exist. This covers a provider process restarting in its pod, see below. -3. **Another attachment.** Either the earlier attachment's node has written `closedEpoch` at or above the earlier epoch (confirmed fencing), or the core leader itself has seen the earlier holder's instance lease unchanged for `TakeoverWait` on its own clock. The leader reads the record with uncached quorum reads, never from its informer cache, stamps each read when it returns, and continues only if a final quorum read at the end of the wait still returns the same version. It then fences the lease before committing the index: a compare-and-swap at that version (`provider.Fence`) moves it to the next epoch with no holder. A renewal the holder sent before the final read that lands after it then fails, and its holder learns the lease is lost; a renewal that landed first makes the fence fail, and the wait starts again. Once the fence lands, no renewal can extend the earlier gate, however long the leader takes to write the index and the route's status. A renewal restarts the wait. A leader change restarts it too, because observations are in the leader's memory. A missing instance or lease counts as unchanged from the first quorum read that found it missing, since the node can apply no renewal of a deleted record, and needs no fence; a leader that finds more than `Margin` passed between that final read and the index write, as after a pause, starts the wait again. This differs on purpose from `claim.Instance.Acquire`, which creates a quarantine record when one is missing (`internal/edge/claim/claim.go:237`): core never creates a provider's lease, and writes one only to fence it. A record recreated during the wait has a new version, which restarts the wait, and a new incarnation, which the node's gate never matches. The fence ends the whole instance lease, not only this route's claim, but core reaches it only for an instance that has not renewed for longer than a lease, whose gates have all expired. +See [Attachment](../../../edge/provider-contract.md#attachment). -Case 3 is the guarantee in `internal/edge/claim` with core as the replacement: it waits as `claim.Instance.Acquire` does and takes the lease away by the same compare-and-swap, but leaves it unheld. The replacement's provider code takes no part in it. A provider that swaps a route early gets nothing until core accepts it. + -**Restart in place.** A restarted provider process acquires its instance's lease with the single-level rules. The previous process's renewals have stopped, so the record stays unchanged and the wait ends after `TakeoverWait`. It then swaps each of its routes to the new instance epoch. Under case 2, core accepts at once, with no second wait on the instance it now renews itself. Measured from the restarted process's first read of its lease, forwarding resumes after `TakeoverWait` (15.53 s) plus the time to swap the routes, accept them and apply the new lease. That second part has a 1 s target, measured rather than guaranteed, because it includes API round trips. +See [Forwarding claim](../../../edge/provider-contract.md#forwarding-claim). -A holder whose instance lease expired cannot revive its routes. Its renewal returns `ErrLost`, and reacquiring the instance advances the instance epoch, which no longer matches the routes until they are swapped and accepted again. + -**Node obligations.** `galactic-edge` on `accepted.node` closes the prefix's gate and then writes `closedEpoch` when any of these happens to the accepted epoch: the holder sets `released`, core revokes the route, the attachment drains, or the lease deadline passes. A released route is therefore free only after its own node confirms the gate is closed, which case 3 then sees. When core accepts a successor on another attachment through the time branch of case 3, the old gate has already closed at its deadline, and the old node closes its state without writing `closedEpoch`, since `accepted.node` has moved. A same-attachment acceptance (case 2) closes nothing. A closed gate stays in the map, closed, until `closedEpoch` records it; an epoch at or below `closedEpoch` never opens again. A holder whose gate expired therefore claims a new epoch, which core accepts at once under case 2, and the gate opens from a renewal read after that. `galactic-edge` writes gates through the ownership fence of the gVPC's scope, so an agent process a newer one fenced cannot reopen a gate the newer one closed. It writes `closedEpoch` only after a commit in that scope finds no gate on any edge link still carrying the prefix open at that epoch, so a fenced process, or one that missed a link while listing, never reports a gate closed that another holds open. +See [Acceptance](../../../edge/provider-contract.md#acceptance). -### Prefix conflicts + -Two routes in one gVPC conflict when either prefix contains the other, not only when they are equal. Exact-prefix contention goes through the claim, since both instances address the same `EdgeRoute`. Every other overlap is refused: +See [Prefix conflicts](../../../edge/provider-contract.md#prefix-conflicts). -- Acceptance is a compare-and-swap on the gVPC's `EdgeRouteIndex`, which lists every accepted route and its epoch. Core checks the new route against that list and what else the gVPC uses (below), then writes the index, then the route's status. If two controller replicas both believe they lead during a lease handoff, the second swap fails and that replica rereads. -- A route that overlaps an accepted route or a subnet is refused with `PrefixConflict`. An index holds at most 1024 routes, so a full one stays within etcd's object size limit; a route beyond that is refused with `IndexFull`. -- An entry leaves the index only when the case 3 fencing rule holds for its last accepted epoch, whatever the reason: deletion, release, revocation, the `EdgeService` going away, or a later subnet. For a removal core recorded itself (deletion, revocation, the service going away, a subnet), the entry also leaves once `TakeoverWait` has passed on the leader's clock since the recording and a final quorum read confirms it. `galactic-edge` extends a gate only after a fresh read showing the route still accepted, so the gate closes within `Duration` + `Margin` of the recording even if `galactic-edge` is stuck and the provider keeps renewing. Deleting and recreating a route never shortcuts fencing, and the recreated route is a first claim only after the old entry is gone. -- Whenever core finds no index for a gVPC, it creates one rebuilt from every route's accepted holder, then accepts no first claim in that gVPC for `TakeoverWait`, since entries for deleted routes may be gone. Core cannot tell a gVPC's first route from a lost index, so the first route of every gVPC waits too. -- A subnet created later that overlaps an accepted route revokes the route with `PrefixConflict`. The node closes the gate within the revocation bound, so the route and the new subnet can overlap for up to 15.5 s. Core does not delay subnet creation; workload subnets take precedence over provider routes. + -A route never contains its holder attachment's own address, the `/128` included. The node routes the prefix through that address, so core refuses such a claim with `InvalidPrefix` once it has confirmed the attachment is the claimant's and live, before it checks the grant, other routes or subnets (`internal/edge/route/check.go`), and an accepted route cannot come to contain it, since an attachment keeps its address. +See [Publication](../../../edge/provider-contract.md#publication). -Besides other routes, a route conflicts with (`internal/edge/route/conflict.go`): + -- a workload subnet of the gVPC: any `VPCAttachment.status.podSubnet` of it; -- another service's client pool in the gVPC; -- the address of another attachment allocated from its own service's pool. A route may otherwise lie inside its own service's pool: that is a delegated client prefix. The allocator never hands out an address under a prefix in the gVPC's `EdgeRouteIndex`. An allocation can still race an acceptance; the route then contains the new address and is revoked; -- anything, when an earlier service's granted prefixes overlap its own service's. Grants are exclusive in a gVPC: of two services whose prefixes overlap, the later, by creation time and then UID, admits no attachment and routes nothing until they no longer overlap. A grant's prefixes stay assigned to its service until the service is deleted or its prefixes change. +See [Reaping](../../../edge/provider-contract.md#reaping). -Each of these created or changed after acceptance revokes the route, like a later subnet. + -### Publication +See [Drain](../../../edge/provider-contract.md#drain). -Core publishes one `BGPAdvertisement` for each accepted route (`internal/edge/route/publish.go`), only while: + -- the route's accepted holder is not revoked or released, -- its attachment is the accepted object, programmed, with its host link and address reported, and -- the gVPC's `BGPVRFInstance` exists on the holder's node. +See [Restart and replacement](../../../edge/provider-contract.md#restart-and-replacement). -The advertisement names that node's router, the VRF's ID and export route target, the route's one prefix with `End.DT46`, and the holder's host link and address. It follows a takeover in place: the same object, updated to the new node, at the new epoch. Core withdraws it as soon as none of the conditions holds, and withdraws every advertisement annotated with the route's name that is not the current one, each on a precondition of the version read, so a pass for an earlier object of the same name never touches a replacement's or another route's. + -`galactic-router` advertises an edge route's advertisement only while the forwarding gate it names is open on its node: the named host link is the edge link of the named address and holds an unexpired gate for exactly the prefix. It reads the gate from the pinned map whenever it builds its desired state, and polls it every 250 ms so a deadline passing withdraws the prefix with no API event. Without the pinned map it advertises none, and opens the map again at most every second until it can read it. An advertisement it leaves out is reported `Advertised` False with reason `GateClosed`. Publication never widens what the gate allows: a prefix whose gate closes is withdrawn locally even if core is cut off and still publishes it. +See [Timing and failure bounds](../../../edge/provider-contract.md#timing-and-failure-bounds). -An attachment's own address is not published. Workloads of the gVPC on the attachment's node reach the address, and every prefix whose gate is open on the attachment's link, through local entries `galactic-edge` keeps in the uSID datapath (see [Shared, written by existing components](#shared-written-by-existing-components)). The entry for a prefix stays while its route is accepted on the node and not released, whether or not the gate is open, so a closed gate drops that traffic on the node instead of sending it to the gVPC's egress shards. Workloads on other nodes reach only published prefixes. A provider that must be reachable at its address from other nodes claims an `EdgeRoute` for the address's `/128`, which the conflict check allows for the holder's own address. That route is gated and published like any other, and adds no host route, since the link's own route already carries the address. + -Core's write access to `BGPAdvertisement` is a Role in `galactic-system`. Kubernetes RBAC cannot scope it by label, so the Role covers every advertisement there, though core reads and writes only those labeled `galactic.datumapis.com/edge-route`. +See [Parameters](../../../edge/provider-contract.md#parameters). -### Reaping + -Core deletes what no live pod can still use: +See [Bounds](../../../edge/provider-contract.md#bounds). -- An `EdgeInstance` whose pod no longer exists, or exists with another UID, once its record has been unchanged for `TakeoverWait`. -- An `EdgeRoute` whose attachment is gone and whose claim is released or held by a reaped instance. -- The `BGPAdvertisement` of a deleted `EdgeRoute`: core withdraws it when it sees the route gone, and an advertisement whose annotated route no longer exists when it sees the advertisement. + -The node never deletes API objects. It closes gates and releases host state for attachments that are draining or deleted. +See [Clock and failure assumptions](../../../edge/provider-contract.md#clock-and-failure-assumptions). -### Drain + -A drain stops new routes and attachments for its scope at once. Forwarding continues until the earlier of the drain window (`EdgeService.spec.drainSeconds`, default 30, maximum 300) and the lease deadline. Core records the end of the window in the attachment's `status.drainDeadline` and deletes the attachment when it passes. The node then closes the gate, `galactic-router` withdraws, and the attachment is released. A grant's prefixes stay assigned to the service across drains; only its routes go. +See [Foundation resources and their writers](../../../edge/provider-contract.md#foundation-resources-and-their-writers). -### Restart and replacement + -| Event | Rule | -| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Provider process restarts in its pod | New holder ID. It takes over its own instance lease after a release or `TakeoverWait`, then core re-accepts its routes at once (see [Acceptance](#acceptance)). | -| Provider pod replaced, same node | New pod UID and `EdgeInstance`. Routes move by takeover. The old attachment drains. | -| Replacement on another node | As above. The old node's gate closes at its own deadline even if that node cannot reach the API. | -| `galactic-edge` restarts | New ownership owner ID, `Fence`, `Adopt`, then a snapshot commit (`internal/edge/ownership/ownership.go:212`, `:226`, `:169`). It extends no deadline until it has read a renewal newer than the one applied. | -| `galactic-router` restarts | Advertises an edge prefix only while its gate deadline, read from the pinned map, is in the future. | -| Node reboots | Pinned maps and leases from the previous boot are void: the boot ID changed. Every claim on that node is reacquired through the takeover rules. | +See [Owned by `galactic-edge`](../../../edge/provider-contract.md#owned-by-galactic-edge). -Cached state is evidence to reconcile from, never permission to forward. + -## Timing and failure bounds +See [Shared, written by existing components](../../../edge/provider-contract.md#shared-written-by-existing-components). -### Parameters + -Every holder and replacement in a cell uses the same values. `claim.Params.Validate` rejects values that cannot provide the guarantee. +See [Ownership transfer, recovery and cleanup](../../../edge/provider-contract.md#ownership-transfer-recovery-and-cleanup). -| Parameter | Value | Basis | -| ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Lease `Duration` | 15 s | Validity one renewal grants on the holder's `CLOCK_BOOTTIME`. | -| Renewal interval | 5 s | Two consecutive renewals can fail without expiry. | -| `MaxDrift` | 0.001 | 1000 ppm relative rate error between any two nodes' monotonic clocks. | -| `Margin` | 500 ms | Delay between a deadline passing and forwarding actually stopping. | -| `TakeoverWait` | 15.53 s | `Duration × (1 + MaxDrift) / (1 − MaxDrift) + Margin` (`internal/edge/claim/claim.go:149`). | -| `MaxSkew` | 2 s | Wall-clock error of any node; used only to convert `validUntil` into a deadline. | -| Router gate poll | 250 ms | How often `galactic-router` reads the gate deadlines of the prefixes it advertises. | -| BGP hold time | ≤ 9 s | Negotiated hold time of an edge node's EVPN session to its route reflector. The bound needs at most 9 s; the deployment sets the timers on both ends. Unset, GoBGP's default is 90 s. | -| Drain window | 30 s | Default `drainSeconds`; at most 300 s. | + -### Bounds +See [Failure-test matrix](../../../edge/provider-contract.md#failure-test-matrix). -| Bound | Value | Enforced by | Holds while | -| ----------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------- | -| Local forwarding expiry | 15.5 s after the last applied renewal starts | The datapath compares the gate deadline with `bpf_ktime_get_boot_ns` | Provider, `galactic-edge` and API all stalled | -| Replacement activation | Not before the old gate is confirmed closed, or `TakeoverWait` | Core's acceptance, observed on the leader's clock, and the node's gate check | Any two nodes within `MaxDrift` | -| Revocation | 15.5 s after it is recorded (`Duration` + `Margin`) | `galactic-edge` applies a renewal only after reading the attachment and grant fresh | `galactic-edge` cut off from the API | -| Revocation, connected | Target 2 s after it is recorded | `galactic-edge`'s watch closes the gate when it sees the revocation | Measured, not guaranteed | -| Grant ceiling | `validUntil − MaxSkew` | The lease deadline is capped by `claim.Instance.Ceiling` | Wall clocks within `MaxSkew` | -| Local route withdrawal | 1 s after the gate deadline | `galactic-router` polls the pinned gate and withdraws with no API call | `galactic-router` running | -| Local route withdrawal, router down | 9 s after the router stops | The route reflector drops the node's paths when the 9 s hold time expires | Route reflector running | -| Remote convergence | Target 5 s after local withdrawal | BGP propagation | Measured, not guaranteed | + -Every bound measured from a deadline is on the holder's clock. With `MaxDrift` of 0.001, the 15.5 s figures are at most 15.52 s of real time, which is the pass threshold for a real-time measurement in the [failure-test matrix](#failure-test-matrix). - -The revocation bound works like this. `galactic-edge` extends a gate only after a renewal and a quorum read of the attachment, service and grant that shows them still valid. Any renewal applied after a revocation sees it. A renewal applied before the revocation started no later than the revocation, so its gate closes within `Duration` of it, and forwarding stops within `Margin` after that: 15.5 s in all. - -### Clock and failure assumptions - -- **Monotonic clock.** Each node's `CLOCK_BOOTTIME` advances at real time within `MaxDrift`, across suspend. Wall clocks are not assumed synchronized; only the grant ceiling uses them. -- **Shared node clock.** A provider and the `galactic-edge` serving it run on the same node, so the renewal start a provider records in its lease (the `edge-renew-start` annotation, with the instance's `bootID`) is on the clock the gate uses. `galactic-edge` rejects a start later than its own reading or earlier than the one it already applied, and any record from another boot. -- **No VM pause.** A node whose clock stops while the node is paused can forward past its deadline in real time. Edge nodes that run edge attachments must be physical, or virtual with pause and live migration disabled. -- **Forged renewal starts.** A provider can record a start later than its true send time. Because `galactic-edge` accepts no start later than its own reading, a forged start makes a renewal look at most as fresh as the moment `galactic-edge` read it. That extends only the provider's own gate, for prefixes it already holds, and cannot affect another provider or tenant. -- **Stale remote routes.** Until remote convergence, traffic can still arrive at the old node. The closed gate drops it. Stale routes cost packets; they never reopen forwarding. -- **Availability cost.** An API outage longer than 15 s stops every edge attachment in the affected scope. This is deliberate: two owners for one prefix is worse than an outage. - -## Foundation resources and their writers - -Foundation-owned host state is what `galactic-edge` creates for an attachment, plus the shared state it writes into. Each gVPC on the node is one scope of `internal/edge/ownership`, which `galactic-edge` owns and writes only in snapshot commits. A writer that can remove shared state an edge attachment uses does so only through `maintenance.Guard.Reclaim` (`internal/edge/maintenance`): under the scope's lock (`ownership.Authority.Exclusive`), and never between `Fence` and `Adopt`, it checks again that no edge attachment uses the gVPC; a refused check writes nothing, and a write makes every ticket `galactic-edge` holds for the scope stale, so a change prepared before it is prepared again. A gVPC is in use while the API has an `EdgeAttachment` on the node for it that is not `Released`, which covers one still being prepared, or the host has a link stamped for it. Every other writer in the table below either writes only rows an edge attachment never uses, or only adds rows; the table gives the reason for each. No lab or end-to-end environment runs `galactic-edge` yet. - -### Owned by `galactic-edge` - -| Resource | Key | Other writers allowed | -| ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Host veth `E`, alias `galactic-edge:hostattach:` | Attachment ID | None. `hostattach.Release` refuses another ID's link. | -| Pod VRF, pod link, TUN and routes inside the provider pod | Attachment ID | None. | -| Host-table routes and permanent neighbors for the attachment | Host link ifindex | None. | -| uSID registration of the host link (`ifindex_vrf_table`, `ifindex_egress_kind_table`) | Host link ifindex | None. | -| Traffic policy interface rows (`tp_iface_table`, `tp_iface_addr_table`) for the host link | Host link ifindex | None. `galactic-router`'s traffic-policy reconciler binds snapshots to the link in `tp_binding_table`, as for a workload. | -| Forwarding gate rows (`edge_link_table`, `edge_gate_table`) | Host link ifindex, and prefix | None. The link row is written before `usid_egress` and `tp_deliver` are attached to the link, and removed after its gates. | -| Local pass-through entries in `egress_route_table`: each edge link's address, and each prefix of a route its attachment holds | gVPC table and prefix | None. Each entry names its owner, `egressroutemap.PassThroughEdge`, in its value, and `galactic-edge` removes only entries with that owner. `galactic-router`'s withdrawals leave them. | -| Ownership records | Scope (gVPC on the node) | Every fenced writer, through `ownership.Authority`. | - -The host link name stays outside the CNI pattern `^G…H$` (`internal/gc/datapath_repair.go:33`), so datapath repair never mistakes an edge link for a workload. - -### Shared, written by existing components - -The table lists every site outside tests and the map packages themselves that opens a pinned map of the CNI datapath (`/sys/fs/bpf/galactic`), removes a traffic-policy interface, or creates or deletes a VRF, and every writer of `BGPAdvertisement`. This command regenerates the datapath and VRF part: - -```sh -grep -rnE '\b[a-z]+map\.OpenPinned[A-Za-z]*\(|\btpmap\.RemovePinnedInterface\(|\bvrf\.(Add|AddInRange|Delete)\(' internal cmd | grep -v '_test.go' -``` - -| Resource | Writers today | Integration | -| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Canonical host VRF of a gVPC | Created by CNI ADD (`internal/cni/ops_add.go:100`, `internal/cnitap/ops_add.go:101`). Deleted by `galactic-router` GC (`gc.RemoveOrphanedVRFs`, chosen by `gc.CollectOrphanedVRFs`, run from `internal/controller/gc_controller.go:43`) | GC skips a gVPC edge attachments use and deletes each VRF through `Reclaim`. CNI ADD only creates, and leaves an existing VRF as it is. | -| `BGPVRFInstance` of a gVPC on the node | Created by CNI ADD; deleted by `galactic-router` GC (`gc.RemoveOrphanedCRDs`, chosen by `gc.CollectOrphanedCRDs`) | GC skips a gVPC edge attachments use and deletes each instance through `Reclaim`, found from the VRF it serves, so `galactic-router` keeps importing the gVPC's routes into the VRF. An instance whose VRF is gone is deleted outright: no edge attachment can use a gVPC with no VRF on the node. | -| Ingress sidecar VRF | Created and deleted by the ingress sidecar inside its own pod namespace (`internal/ingresssidecar/backend.go:86`, `:120`) | None while it runs in its own network namespace. `vrf.Delete` works by name, so on the host network it would delete the canonical VRF; the sidecar must never run there. | -| uSID registry (`vrf_table`, locator and function rows) | `attachreg.RegisterDatapath` (`internal/plumbing/ebpf/attachreg/register.go:138`) and fill (`fill.go:93`); `galactic-cni` sweep (`internal/gc/gc.go:594`, run from `internal/installer/installer.go:1276`), egress group refresh (`internal/installer/egressgroup.go:202`) and sidecar return (`internal/installer/sidecarreturn.go:241`); the ingress sidecar (`internal/ingresssidecar/ebpfdatapath.go:314`, `:460`); sidecar prune (`internal/plumbing/ebpf/sidecarmap/prune.go:51`) | The sweep keeps every entry a stamped edge host link resolves to through its `ifindex_vrf_table` row, and removes nothing when it cannot list those links. `attachreg` writes only its own gVPC's entry, with that gVPC's VRF table. Egress group refresh only reads the registry. The sidecar, its return path and prune write only under `uformat.BlockIngressSidecar` or add node-wide locator and function rows. | -| Attachment rows, during repair | `galactic-cni`'s datapath repair (`internal/gc/datapath_repair.go:121`), through `attachreg` | None. Repair acts only on links in the CNI name pattern and writes only rows that are missing. | -| `ifindex_vrf_table` | `attachreg` (`register.go:172`, `fill.go:99`); the ingress sidecar (`ebpfdatapath.go:328`, `:444`); sidecar prune (`prune.go:55`); CNI DEL (`internal/cni/ops_del.go:144`, `internal/cnitap/ops_del.go:110`) | None. Each writer removes only its own link's row: CNI DEL looks its link up by its CNI name, so a reused ifindex never names an edge link, and the sidecar and prune stay at or above `ifindexvrfmap.SidecarIfindexBase`, which `Register` refuses for any host link. | -| `ifindex_egress_kind_table` | `attachreg` (`register.go:537`, `fill.go:105`); CNI DEL (`internal/cni/ops_del.go:160`, `internal/cnitap/ops_del.go:124`) | As for `ifindex_vrf_table`. | -| `tenant_gw_table` | `attachreg` (`register.go:586`, `fill.go:114`); CNI DEL (`internal/cni/ops_del.go:181`, `internal/cnitap/ops_del.go:145`) | As for `ifindex_vrf_table`. Edge attachments write no row. | -| `egress_route_table` | `srv6` helpers (`internal/plumbing/srv6/egress.go:49`, `:60`, `:112`, `:153`), called by `galactic-router` VRF routes (`internal/runtime/gobgp/vrfroutes.go:34`, `:108`), the ingress sidecar (`backend.go:127`) and `attachreg` (`register.go:436`); `attachreg` directly (`register.go:333`, `:407`, `fill.go:123`); egress group refresh (`egressgroup.go:196`); sidecar prune (`prune.go:60`); `galactic-router`'s startup write probe (`internal/runtime/gobgp/monitor.go:376`); `galactic-edge` through `attachreg` (`hostlink.go:200`) | `galactic-edge` writes a pass-through entry in the gVPC's table for each edge link's address, each prefix whose gate is open on the link, and each prefix of a route accepted on the node for the link's attachment and not released, and removes only the entries it owns (`attachreg.SyncHostLinkRoutes`). Without them, a workload of the gVPC on the same node matches the gVPC's `::/0` shard route and its packets leave as public egress, since `galactic-router` installs no route for its own node's advertisements. A held prefix whose gate is closed has no host route, so the kernel drops it at the VRF's unreachable default. The agent syncs the entries on every attachment pass, which a route's acceptance, release, deletion or move to another node triggers. A wanted prefix that already has another writer's pass-through entry is left to that writer. An encapsulating entry left for a prefix whose holder moved here is replaced, and `galactic-router`'s withdrawal of that remote route (`srv6.RouteEgressDel`) keeps the entry. An encapsulating entry `galactic-router` installs over it is a later holder's route; core accepts that holder only once this node's gate is confirmed closed or `TakeoverWait` has passed. A published edge route reaches other nodes through `galactic-router` like any other VRF route (see [Publication](#publication)). | -| `egress_shard_groups` | Egress group refresh (`egressgroup.go:214`); `attachreg` (`egressgroups.go:32`, `fill.go:141`) | None. Node-wide shard groups; edge attachments write no row. | -| Sidecar return maps | The ingress sidecar (`ebpfdatapath.go:491`, `:514`); `galactic-cni`'s sidecar reaper (`internal/installer/sidecarreap.go:265`) | None. Keyed by the sidecar's own ranges; edge attachments write no row. | -| Traffic policy maps (`tp_*`) | `galactic-router`'s policy reconciler (`cmd/galactic-router/policy.go:234`); CNI ADD (`internal/cnibgp/trafficpolicy.go:53`); interface removal by CNI DEL (`internal/cni/ops_del.go:173`, `internal/cnitap/ops_del.go:137`) and the ingress sidecar (`ebpfdatapath.go:452`); the node-wide mode, set by `galactic-cni` (`internal/installer/trafficpolicy.go`) | None. Interface removal acts only on its own links, like CNI DEL above. An edge host link is a policy subject like a workload interface; an unbound attachment denies everything. | -| Node-wide rows (`node_src_addr_table`, `public_uplink_table`) | The ingress sidecar (`ebpfdatapath.go:244`); `attachreg` (`register.go:263`, `:280`, `fill.go:129`, `:135`); `galactic-cni` public uplink refresh (`internal/installer/public_uplink.go:148`) | None. Each holds one node-wide value, not keyed by gVPC or attachment, and edge attachments never write them. | -| Private service maps (`service_*`) | `internal/serviceroute/dataplane.go:409` | None. Edge attachments never write them. | -| `vip_xlat_table` | `galactic-router` (`cmd/galactic-router/root.go:158`, `cmd/galactic-router/vipxlat.go:34`) | None. Edge attachments never write it. | -| `BGPAdvertisement` | CNI, `galactic-gateway`, the ingress sidecar, `galactic-controller`, GC (`gc.RemoveOrphanedCRDs`) | Core writes one edge advertisement per accepted route, labeled `galactic.datumapis.com/edge-route`, and withdraws it itself. GC deletes only an advertisement whose recorded network namespaces are all gone, and one with none recorded, as core's are, always survives. | -| Plain routes for EVPN paths without a route target | `galactic-router` (`internal/runtime/gobgp/plainroutes.go`), sole owner of its own table | None. Its table is not a canonical VRF table, and edge attachments never write it. | - -Sites the command finds that only read are left out: CNI CHECK (`internal/cnibgp/ops_check.go:168`, `:227`, `:262`), the sidecar's route inventory (`internal/ingresssidecar/routeinventory.go:60`) and the sweep's lookup of edge host links (`internal/gc/gc.go:819`). - -### Ownership transfer, recovery and cleanup - -- **Transfer between writers on a node** uses `Fence`, then `Adopt`, then a snapshot commit. `Fence` waits for a commit in progress, so the old writer's last change either lands before the barrier or not at all. -- **Transfer between instances** is a claim takeover. The new instance's gate opens only after the old generation can no longer forward, and the gate key carries the generation, so the old owner's late cleanup deletes nothing the new owner installed. -- **Recovery** after a failed or interrupted commit requires a snapshot commit (`ErrResyncRequired`), because a half-applied change is neither done nor undone. -- **Cleanup** removes only state stamped with the attachment ID, or keyed by an ifindex whose link carries that ID, and only under a current ownership ticket. Losing the ownership state directory requires stopping every writer on the node and reconciling host state before a fresh authority is created; restoring it from a backup is never allowed. - -## Failure-test matrix - -Each row is an acceptance test. The pass condition is fixed here, before anything is run. "Talos" means the target Talos/Cilium environment from #1002; "lab" is `deploy/containerlab`; "root unit" is a `requireRoot` Go test on a real kernel. - -| # | Scenario | Injected fault | Pass condition | Where | Milestone | -| --- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ------------ | -| 1 | Unknown or unapproved provider | Attachment from an unregistered or unapproved provider | Refused with its reason; no allocation or host change | Unit, lab | #994 | -| 2 | Unsupported version | Unsupported contract or capability version | Refused before allocation | Unit | #994 | -| 3 | Out-of-grant request | gVPC not granted; prefix outside the grant | `VPCNotGranted` or `PrefixNotGranted`; no route | Unit, lab | #994, #998 | -| 4 | Forged identity | Pod writes another pod's instance, attachment or claim | API server rejects the write | Lab, Talos | #994 | -| 5 | Capacity exhaustion | Requests beyond attachment or prefix limits | Refused before allocation; existing attachments unaffected | Unit, lab | #994 | -| 6 | Overlapping tenants | Two gVPCs, identical addresses and prefixes, two providers | No packet crosses gVPCs, in both directions | Root unit, Talos | #995, #1000 | -| 7 | Prefix conflict in one gVPC | Two providers request the same prefix | Second refused with `PrefixConflict`; the first keeps forwarding | Unit, lab | #998 | -| 7a | Overlapping prefixes in one gVPC | A /48 and a /56 inside it, from two providers or two instances; a route overlapping a gVPC subnet | The later route refused with `PrefixConflict`; the earlier keeps forwarding; also across a leader change | Unit, lab | #998 | -| 7b | Route on another pod's attachment | A provider pod writes a route naming another pod's attachment, at create and on takeover | API server rejects a mismatched `holderPodUID`; core refuses a mismatched attachment; no gate opens | Unit, lab | #994, #998 | -| 7c | Subnet created over a route | Create a gVPC subnet overlapping an accepted route | Route revoked with `PrefixConflict`; gate closed within the revocation bound | Unit, lab | #998 | -| 7d | Route over its own address | Route whose prefix contains its holder attachment's address: a covering prefix and the address's `/128` | Refused with `InvalidPrefix`; never accepted or indexed, so no node programs it | Unit | #1074 | -| 8 | Partial provisioning | `galactic-edge` killed during `Provision` | On restart the partial state is found by alias and finished or released; no gate opened | Root unit | #995 | -| 9 | Delayed cleanup | Old owner's release runs after a replacement is active | Replacement's link, routes and gate untouched | Root unit, lab | #995, #998 | -| 10 | Provider crash | `SIGKILL` the provider | Gate closed ≤ 15.5 s after the last renewal start; local withdrawal ≤ 1 s later | Lab, Talos | #997 | -| 11 | Provider stall | `SIGSTOP` the provider | Same bounds as row 10 | Lab, Talos | #997 | -| 12 | API isolation, packets still flowing | Block the node's API traffic only | Gate closed ≤ 15.5 s; replacement elsewhere activates no earlier than `TakeoverWait` after its first read | Talos | #997 | -| 13 | Cross-node replacement | Delete the provider pod; replacement lands on another node | No capture interval in which both nodes forward the prefix; outage measured and reported | Lab, Talos | #997, #1000 | -| 13a | Early takeover | Another instance swaps a held route to itself at once, with the holder still renewing, then with the holder stopped | Not accepted while the holder renews; accepted no earlier than the old gate's `closedEpoch` or `TakeoverWait` after the holder stops; never two forwarders | Unit, lab | #997 | -| 13b | Stale leader view | Delay the holder's renewals reaching the core leader's informer while the holder keeps renewing | No takeover accepted; the leader's quorum reads see the renewals | Unit, lab | #997 | -| 13c | Release while renewing | Holder releases one route and keeps renewing its instance; another attachment claims it | Accepted only after the holder's node writes `closedEpoch`; never two forwarders | Unit, lab | #997 | -| 13d | Spec swap without acceptance | A sibling pod swaps a held route's epoch to itself while the holder renews | The holder keeps forwarding; core refuses; no gate change on either node | Unit, lab | #997 | -| 13e | Removal with the node agent stuck | `SIGSTOP` `galactic-edge`, keep the provider renewing, delete the route | Gate closed ≤ 15.5 s after the deletion; the prefix is free for a new claim `TakeoverWait` after core recorded the deletion | Lab | #997 | -| 14 | `galactic-edge` stall | `SIGSTOP` the node agent | Gate closed ≤ 15.5 s; nothing reopens on resume until a fresh renewal | Lab, Talos | #997 | -| 15 | `galactic-edge` restart | Restart with active attachments | Forwarding continues to its deadline; no deadline extended from cached state | Root unit, lab | #995, #997 | -| 15a | Provider restart in place | Kill the provider process; the container restarts in the same pod | Routes accepted again with no wait beyond the instance's own `TakeoverWait`; forwarding resumes ≤ 15.53 s after the restarted process first reads its instance, plus accept-and-apply measured against the 1 s target | Lab | #997 | -| 16 | `galactic-router` down | Stop the node's router | Gate still closes on time; the route reflector withdraws the prefix ≤ 9 s after the router stops | Lab | #998 | -| 17 | Revocation | Delete the `EdgeService` or remove the prefix from the grant | Gate closed ≤ 15.5 s, measured against the 2 s target | Lab, Talos | #997, #999 | -| 18 | Grant ceiling | `validUntil` passes | Gate closed at or before `validUntil − MaxSkew` | Unit, lab | #997 | -| 19 | Missing or invalid policy | Reference a missing policy, or delete the `EdgeService` | Forwarding closed except neighbor discovery | Root unit, lab | #999 | -| 20 | Policy change | Change the service's policy reference, or the policy, under active traffic | New policy applies to the active attachment | Root unit, lab | #999 | -| 21 | GC with only edge users | Edge attachment is the gVPC's only user on the node; run GC and repair | VRF, `vrf_table` rows and attachment rows remain | Root unit, lab | #996 | -| 22 | Maintenance fence | Stale ticket committed after `Fence` | Refused; host state unchanged | Root unit | #996 | -| 23 | Node reboot | Reboot an edge node | No gate opens from the previous boot; claims are reacquired after `TakeoverWait` | Talos | #997 | -| 24 | Drain | Drain a service with active traffic | No new routes accepted; forwarding ends ≤ `drainSeconds`; resources released | Lab | #995 | -| 25 | Independent provider | Run rows 1 to 24 and their lettered rows with a provider built outside the core | All pass with no change to core source, schema, image or deployment | Talos | #1000, #1002 | - -Results record the commit, the environment, measured timings per row and packet captures for rows 6, 12 and 13. `tests/edgeconformance` runs the rows the containerlab lab can host with the reference provider (`task verify:edge-conformance`). - -## Open items - -These need an answer before the milestone named: - -- **Namespace acquisition (#1002).** `galactic-edge` finds the provider pod's network namespace through the node's CRI socket, from containerd's verbose sandbox status, and checks the sandbox's pod UID before `hostattach.Provision`. This needs proof on the target platform, whose CRI socket path and permissions are deployment values that differ from Kind's. -- **Capacity limits (#994).** The per-cell limits for providers, instances, attachments and routes come from the scale measurements in #1002. Until then admission keeps 10% of each shared eBPF map free, so a draining attachment and its replacement can hold rows at the same time, and refuses requests beyond that. -- **Hold time on edge sessions (#998).** The timers that keep the hold time at or under 9 s are deployment values: this repository's lab sets 9 s on both ends of every edge node's session, and datum-cloud/infra sets production's. -- **Remote convergence target (#998).** The 5 s target is checked against the lab's route reflector topology, then against production's. +See [Open items](../../../edge/provider-contract.md#open-items). diff --git a/docs/enhancements/networking/interface-traffic-policy/README.md b/docs/enhancements/networking/interface-traffic-policy/README.md index 4ee157df0..a6d737387 100644 --- a/docs/enhancements/networking/interface-traffic-policy/README.md +++ b/docs/enhancements/networking/interface-traffic-policy/README.md @@ -1,846 +1,119 @@ ---- -status: provisional -stage: alpha -latest-milestone: "TBD" ---- - # Interface traffic policy -- [Summary](#summary) -- [Motivation](#motivation) - - [Goals](#goals) - - [Non-goals](#non-goals) -- [Proposal](#proposal) - - [Fixed requirements](#fixed-requirements) - - [Risks and mitigations](#risks-and-mitigations) -- [Design details](#design-details) - - [API ownership](#api-ownership) - - [Resource model](#resource-model) - - [Rule language](#rule-language) - - [Admission and explicit null](#admission-and-explicit-null) - - [Default policy identity](#default-policy-identity) - - [Binding transitions](#binding-transitions) - - [Forwarding path classification](#forwarding-path-classification) - - [Packet path audit](#packet-path-audit) - - [Parser contract](#parser-contract) - - [Link operation exceptions](#link-operation-exceptions) - - [BPF maps](#bpf-maps) - - [Publication and lifetime](#publication-and-lifetime) - - [Lifecycle activation and continuity](#lifecycle-activation-and-continuity) - - [Reconciliation and status](#reconciliation-and-status) - - [Metrics](#metrics) - - [Kernel requirements](#kernel-requirements) -- [Rollout](#rollout) -- [Delivery plan](#delivery-plan) - - [Pull request sequence](#pull-request-sequence) - - [Requirement checklist](#requirement-checklist) -- [Alternatives](#alternatives) - -## Summary - -A TrafficPolicy is an ordered list of Allow and Deny rules. Each VPC interface -binds one policy for traffic the workload receives (ingress) and, separately, -one for traffic the workload sends (egress). The CNI BPF datapath evaluates the -bound policy on every packet in that direction. An interface with no binding in -a direction uses a built-in policy whose only rule denies everything. - -Policies are stateless. Allowing a request never allows its reply; the reply -needs its own rule in its own direction. - -## Motivation - -Every tenant interface today forwards whatever its VPC routes allow. A workload -that should only serve one private port can also reach the internet through a -NAT shard, and a workload that should only make outbound calls can receive -anything routed to it. Operators have no per-interface control and no record -of what was denied. - -### Goals - -- Give each interface independent ingress and egress policies. -- Deny by default, including while an interface is being created and while the - control plane is unavailable. -- Let rules match the forwarding path (private VPC routing, a NAT shard, or a - public service), the IP family, exact addresses or prefixes, the protocol, - ports and ICMP type and code. -- Apply updates to running interfaces without restarting workloads. -- Count every packet against the rule that decided it. - -### Non-goals - -- Connection tracking or any implicit reply allowance. -- Policy attached to a whole VPC, VRF or namespace. -- Tiered precedence, merging of several policies, or deny-overrides-allow. -- SMTP or any other port-specific platform rule. -- Application-layer, DNS-name or rate-based matching. -- Provisioning NAT, VIPs or services. An Allow only permits use of forwarding - that already exists. -- Interoperability with Kubernetes NetworkPolicy or with BGPPolicy, which is - route-advertisement policy. - -## Proposal - -### Fixed requirements - -These come from the product brief and are not open to redesign here. - -| ID | Requirement | -| -- | --------------------------------------------------------------------------------------------------------------------------------------------- | -| R1 | Policy applies to one VPC interface. Two interfaces in one VPC and VRF can differ. | -| R2 | Each interface has an independent ingress policy and egress policy, named by the workload's direction. | -| R3 | Neither direction creates permissions in the other. No connection tracking or synthesized replies. | -| R4 | The default policy has exactly one rule, deny all, and applies to any direction without a binding. | -| R5 | Rules are ordered Allow and Deny. First match wins. No match denies. | -| R6 | Rules match path, protocol, optional source and destination addresses or prefixes, and ports. NAT access is an ordinary path match. | -| R7 | Updates apply to existing interfaces without recreation, and one direction's update never changes the other. | -| R8 | Missing enforcement state never allows. Failed same-identity updates keep the last good policy. Rebinding and deletion never keep old grants. | - -### Risks and mitigations - -| Risk | Mitigation | -| ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Default deny breaks every running workload on rollout | Enforcement is off per node until an explicit enable, and operators bind policies first (see [Rollout](#rollout)). | -| A path is misclassified and a narrow Allow matches the wrong traffic | Classification uses only trusted forwarding state. Any lookup that cannot finish is `classification_error`, which denies at the first rule naming a path that the packet otherwise matches. | -| A packet reaches a workload by a path that skips the check | The [packet path audit](#packet-path-audit) names the check for every delivery mechanism, and the integration tests send traffic down each one. | -| Counter rows are reused while a packet still counts into them | Rows are freed only after the outer-map update returns, which the kernel guarantees waits for every program that could hold the old snapshot (see [Publication and lifetime](#publication-and-lifetime)). | -| Verifier cost and stack depth of the evaluation | Evaluation is a separately verified global function that walks the snapshot with `bpf_for_each_map_elem`, so its cost does not grow with the rule count; the existing verifier budget test covers it. | -| Dropping every fragment breaks workloads that rely on them, such as large UDP DNS answers | `audit` mode counts would-be fragment drops per interface before a site enforces, and the user guide calls the change out. | - -## Design details - -### API ownership - -The cloud and network API types now live in `api/cloud/v1alpha1` and -`api/network/v1alpha1` of the Galactic module. All of these types use -`galactic.datumapis.com/v1alpha1`. TrafficPolicy and TrafficPolicyBinding -remain in `api/v1alpha1` under the same group. - -VPC and VPCAttachment are owned by the Galactic cell controller, which writes both the -spec and the status of every VPCAttachment. The node controller does not write either. -Bindings are therefore a separate Galactic kind rather than new fields on -VPCAttachment. - -One VPCAttachment describes exactly one interface: its `spec.interface` is a -single object, and the cloud operator creates one VPCAttachment, and one -NetworkAttachmentDefinition of the same name, per NetworkInterface. The -attachment's namespace, name and UID identify an interface lifetime. An -ifindex is a node-local detail and never appears in the API. - -### Resource model - -Both kinds are namespaced. References are local names, so a policy is always -in the binding's namespace and there is no field that could name another -tenant's policy. - -```yaml -apiVersion: galactic.datumapis.com/v1alpha1 -kind: TrafficPolicy -metadata: - name: public-web-egress - namespace: tenant-a -spec: - rules: - - name: https-through-nat - action: Allow - match: - path: PublicNAT - protocol: TCP - destinationPorts: - - start: 443 - end: 443 - - name: deny-all - action: Deny -``` - -```yaml -apiVersion: galactic.datumapis.com/v1alpha1 -kind: TrafficPolicyBinding -metadata: - name: web-0-eth0 # the VPCAttachment's name - namespace: tenant-a -spec: - ingressPolicyRef: - name: private-web-ingress - egressPolicyRef: - name: public-web-egress -status: - observedGeneration: 3 - ingress: - policy: {name: private-web-ingress, uid: 6d1c...} - conditions: [...] # Resolved, Applied - egress: - policy: {name: public-web-egress, uid: 91fa...} - conditions: [...] - nodes: - - node: dfw-compute-3 - ingress: - policy: {name: private-web-ingress, uid: 6d1c..., generation: 4} - state: Applied # Applied, Pending or Failed - observedGeneration: 3 # the binding generation applied - lastTransitionTime: ... - egress: - policy: {name: public-web-egress, uid: 91fa..., generation: 2} - state: Applied -``` - -- The binding has no attachment field: it applies to the VPCAttachment with - its namespace and name. That makes "one binding per interface" a property - of naming rather than a conflict to detect, so there is exactly one - effective policy per interface and direction. -- Omitting a reference selects the built-in default for that direction only. - Removing a reference restores the default for that direction only. -- A binding for an attachment that does not exist yet is accepted and waits. - An attachment without a binding is denied in both directions. -- `status.ingress` and `status.egress` report the resolved policy identity and - a `Resolved` condition. `status.nodes` reports what each node applied, - separately from what the API asked for. Admission success is never reported - as convergence. - -### Rule language - -| Field | Type | Meaning | -| --------------------------------------------- | ----------------------------------------- | ----------------------------------------------------------------------- | -| `name` | DNS label, unique in the policy | Diagnostic and metric identity | -| `action` | `Allow` or `Deny` | Deny drops; no ICMP is synthesized | -| `match` | object, optional | All present fields are ANDed; absent means a catch-all | -| `match.path` | `Private`, `PublicNAT` or `PublicService` | Absent means any path | -| `match.ipFamily` | `IPv4` or `IPv6` | Absent means both | -| `match.protocol` | `TCP`, `UDP`, `ICMP` or `ICMPv6` | Absent means any IP protocol, allowed only without ports or ICMP fields | -| `match.sourceIPs`, `match.destinationIPs` | 1 to 64 literal addresses, a set | Exact /32 or /128 | -| `match.sourceCIDRs`, `match.destinationCIDRs` | 1 to 64 prefixes, a set | Network address must have no host bits | -| `match.sourcePorts`, `match.destinationPorts` | 1 to 16 `{start, end}` ranges | Inclusive, 0 to 65535, TCP or UDP only, no overlap | -| `match.icmp` | `{type, code?}` | ICMP or ICMPv6 only | - -- Entries within one list are alternatives (OR). Different fields are ANDed. -- `sourceIPs` and `sourceCIDRs` are mutually exclusive, as are - `destinationIPs` and `destinationCIDRs`. An IP list on one side with a CIDR - list on the other is allowed. Several exact addresses and prefixes on one - side need separate ordered rules. -- Source always means the packet's source and destination the packet's - destination, in both directions. -- Every address and prefix must match `ipFamily` when it is set, and ICMP - requires IPv4 while ICMPv6 requires IPv6. With no family set, a list may mix - families, and a packet can only match entries of its own family. A rule never - matches one side as IPv4 and the other as IPv6. -- An IPv4-mapped IPv6 literal (`::ffff:192.0.2.1`) is rejected, as the - Kubernetes IP validation library does. It is never unmapped into an IPv4 - match. -- IPv6 literals are canonicalized (RFC 5952) before the webhook's duplicate - check. Zone - identifiers, hostnames, `host:port` and prefix notation in an IP list are - rejected. -- Absent means wildcard. An empty list and an explicit `null` are rejected. -- A policy holds at most 64 rules and compiles to at most 256 datapath entries. - A rule compiles to the product of its source, destination and port - alternatives, so the compiler counts entries and rejects a policy over the - limit rather than truncating it. Rules are never reordered. -- A rule fully shadowed by an earlier rule is reported as a warning, not an - error. -- Addresses and ports are stored in network byte order in the datapath. Ranges - are compared after converting the packet's port to host order. - -NAT64 is matched as the workload sees it. On egress, a packet to a synthesized -`64:ff9b::/96` address is IPv6, so an IPv4 literal does not match it. On -ingress, the reply reaches the workload as IPv6 from the synthesized address -and is matched as that. Outer SRv6 addresses and a shard's public masquerade -address are never substituted into these fields. - -### Admission and explicit null - -An experiment against kube-apiserver 1.33 established how the CRD pipeline -treats `null`: - -- On a field without `nullable: true`, an explicit `null` is pruned before - validation and stored as if omitted, so nothing can reject it. -- On a field with `nullable: true`, the `null` is stored. CRD CEL cannot see - it: `has()` reports false for a null field, and a typed comparison with - `null` does not compile. -- A JSON merge patch that sets a field to `null` removes the field, which is - an intentional change to omission. - -So every optional match field, and `match` itself, is declared -`nullable: true`, and a fail-closed validating webhook (`failurePolicy: Fail`) -rejects a `null` at any of them by inspecting the admitted object. The enum -fields (`path`, `ipFamily`, `protocol`) need no webhook check: the schema's -enum already rejects a null there. Everything CRD validation can express -(enums, bounds, list types, mutual exclusion, family consistency) stays in the -schema as well, so it holds even for clients that bypass the webhook's checks. -While the webhook is down, writes fail rather than admit a null. - -The CEL IP and CIDR functions the schema uses need Kubernetes 1.31 or later; -the schema is tested on 1.33 and 1.35, and edge clusters run 1.35. - -The webhook also parses every address and prefix again, since the schema only -checks strings, and enforces the reserved default name (next section). - -### Default policy identity - -The built-in default is named `default-deny-all` with one rule, `deny-all`, -action `Deny`. It is authoritative for every omitted reference and never needs -an API object. Its metric `policy_uid` is the reserved string -`builtin:default-deny-all:v1`, which is never a Kubernetes UID. - -`galactic-controller --role=cell` also provisions a TrafficPolicy named -`default-deny-all` in each namespace that holds a VPCAttachment, so it can be -referenced explicitly. The webhook reserves that name: only the controller's -service account can create or delete it, and its spec must be exactly the one -catch-all Deny rule. If a conflicting object already exists the controller -reports a provisioning conflict on its own status, never adopts or overwrites -it, and omitted references keep using the built-in default. An explicit -reference to a conflicting object is unresolved and denied. - -An explicit reference to the controller-owned object follows the ordinary -reference rules and reports the object's real UID. An omitted reference always -reports the synthetic identity, even while the object exists. Deleting the -object therefore changes nothing for omitted references and makes explicit -references unresolved. - -### Binding transitions - -Policy identity is the namespace plus the policy's API UID. Each interface and -direction moves independently. - -| Event | Enforcement | Status | -| ------------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------- | -| New interface, binding not yet resolved | Deny, `policy_unavailable` | Pending | -| Reference omitted or removed | Publish the built-in default | Default applied | -| Valid update to the bound UID | Old snapshot until the new one is fully published | Desired and applied generations reported separately | -| Admission rejects an update | Unchanged | Error returned to the writer | -| Accepted update to the same UID fails to compile or install | Keep last good, or deny if there is none | Installation failure with both generations; retried | -| Rebind to another UID | Publish the new policy if it is ready, otherwise invalidate and deny | Pending or failed; never restores old grants | -| Referenced policy confirmed deleted, including same-name recreation | Invalidate and deny until the new UID is installed | Unresolved, or pending for the new UID | -| API outage or cache not synced | Keep what is installed; new bindings stay denied | Stale discovery reported | -| Installed state lost | Deny | Repaired, or the interface is quarantined | - -Absence is established only by a synchronized informer or an authoritative -read. A timeout never counts as deletion. - -Invalidation never depends on allocating anything. It deletes the binding's -outer-map entry, which makes the next evaluation deny with -`policy_unavailable`. If even that delete fails, the node agent sets the -interface's host link down (quarantine) and reports the failure. - -### Forwarding path classification - -| Path | Egress (workload sends) | Ingress (workload receives) | -| ------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| Private | Private VPC routing, same-node delivery, private services, kernel VRF fallback | Ordinary decapsulation, private service tunnel (next header 253), same-node delivery | -| PublicNAT | A shard group sentinel, or a route whose SID is a NAT shard's | Decapsulated packet whose outer source is a NAT shard's SID | -| PublicService | Source VIP translation toward the public uplink (DSR reply) | Gateway delivery (nonzero uSID slot) or inbound VIP translation | - -Classification uses forwarding state only, never whether an address looks -public. - -- **Egress.** The class comes from the same `egress_route_table` value the - forwarding decision uses, in the same lookup, so a route rewritten in place - can never be seen with a stale class: - - a group sentinel (`link_ifindex == 0xFFFFFFFF`) is PublicNAT; - - a route whose SID's top 64 bits are in `tp_nat_locator_table` is - PublicNAT; - - a local pass-through entry and every other route are Private. - - `tp_nat_locator_table` has one writer, the installer. It holds the locator of - every configured shard SID (`GALACTIC_CNI_EGRESS_SHARD_SIDS`) and every - EgressShard it has ever seen. Entries are only ever added while the agent - runs, because the EgressShard controller already keeps shard locators - disjoint from every BGPRouter locator, so a retained entry can never - reclassify private traffic. A restart rebuilds the set before setting the - synced flag in `tp_state`. Until the flag is set, an encapsulating egress - route is `classification_error`. -- **Ingress, NAT.** The outer source of a NAT shard's reply is the shard's - SID, so the same table classifies it. Until the flag is set, an - encapsulated ingress packet is `classification_error`. -- **Trust.** Sender authenticity rests on the existing fabric trust model: - `usid_ingress` already accepts any packet addressed to a local locator from - the fabric uplink. A tenant cannot choose the outer header, because every - tenant packet is encapsulated by the sending node's `usid_egress`, and a - tenant packet that carries its own SRv6 header is encapsulated inside one. - Nothing a tenant controls (inner addresses, ports, marks or its own SRH) - selects a class. -- **Errors.** A rule with no `path` is evaluated normally when classification - failed, and so is a rule with a `path` whose other fields do not match, - since it could not decide the packet on any path. The first rule with a - `path` whose other fields all match ends evaluation with a - `classification_error` deny, so a failed lookup can never skip an earlier - rule and reach a broader Allow. - -### Packet path audit - -**Interfaces.** `tp_iface_table` holds a row for every interface a Galactic -program can deliver to or is attached to, with a kind: - -- `tenant`: a VPCAttachment interface. Policy applies. -- `infra`: the ingress sidecar's synthetic veth peers. They belong to the - platform, carry no tenant identity, and are never evaluated; traffic they - pass on to a tenant interface is checked at that interface. - -A program that finds no row for an interface it is attached to, or that -`usid_ingress` is about to deliver to, denies as `policy_unavailable` -(unattributed). Missing state is never read as "unmanaged". - -**Hooks on a tenant interface**, with `P` the configured filter priority: - -| Hook | Program | Role | -| ------------------------------------- | --------------------- | ------------------------------------------------------------------------ | -| Host-side tc ingress, priority P | `usid_service_egress` | Private service requests and replies | -| Host-side tc ingress, priority P+1 | `usid_egress` | Everything else the workload sends | -| Host-side tc egress, priority P (new) | `tp_deliver` | Workload ingress for packets the kernel or a non-peer redirect transmits | -| Fabric uplink tc ingress | `usid_ingress` | Decapsulation and delivery | - -**Egress tuple.** The packet's addresses, protocol and ports are captured -once, at the top of the first program that sees the packet and before any -NPTv6 or VIP rewrite, so `sourceIPs` and `sourceCIDRs` always see the -workload's own address. The check itself runs at the exit, where the class is -known, using that captured tuple. It runs before `send_too_big`, so a denied -packet never produces a Packet Too Big quoting it, and exactly once per packet -even where the VIP path falls through to the route logic. - -**Every exit of the egress programs:** - -| Exit | Today | With policy | -| -------------------------------------------------------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `bpf_skb_pull_data` fails | `UNSPEC` to the kernel | Evaluate as Private: the capture reads with `bpf_skb_load_bytes`, which needs no pull, so a packet it cannot parse is a `parse_error` drop and one it can is decided by the rules | -| Not IPv4, IPv6 or ARP | `UNSPEC` | Link drop | -| ARP | `UNSPEC` | Link-operation allowlist, otherwise link drop | -| `ifindex_vrf_table`, `vrf_table` or scratch miss | `UNSPEC` | `policy_unavailable` drop when the tenant row is also missing; otherwise evaluate as Private and return `UNSPEC` | -| Short IPv4 or IPv6 header | `UNSPEC` | `parse_error` drop | -| VIP source rewrite and redirect to the uplink | Forwarded | Evaluate as PublicService first | -| VIP rewrite with no uplink configured | Falls through to the route logic | Evaluated once, at the route exit, with the route's class | -| Multicast or link-local destination | `UNSPEC` | Evaluate as Private | -| Neighbor discovery (133 to 137) | `UNSPEC` | Link-operation allowlist; otherwise evaluate as Private | -| Route miss | `UNSPEC` | Evaluate as Private | -| Local pass-through route | `UNSPEC` | Evaluate as Private | -| No node source address configured | `UNSPEC` | Evaluate with the route's class, then `UNSPEC` | -| Group sentinel | Resolved, then encapsulated | Evaluate as PublicNAT before the group is resolved, so a denied packet moves no pin | -| Group sentinel, resolution failed after an Allow | Drop | Drop, counted under its existing reason after the Allow's rule hit, like any later forwarding failure | -| Remote route | Encapsulated | Evaluate with the route's class | -| `usid_service_egress` parse failure or non-IP | `UNSPEC` to `usid_egress` | Handled by `usid_egress` | -| `usid_service_egress` non-TCP/UDP, or a service-route miss without a deny marker | `UNSPEC` to `usid_egress` | Handled by `usid_egress` | -| Service request or reply, local or remote | Rewritten and redirected | Evaluate as Private before the rewrite | -| Service deny marker or service policy denial | Drop | Unchanged; the service policy's own drop, counted by it | - -A packet that service policy drops has no traffic-policy outcome: the -private service checks run first, and traffic policy decides only a request or -reply they authorized, on the tuple captured before any rewrite. That is a -different policy's decision, already counted under its own reason. - -**Workload ingress:** - -| Mechanism | Where it is enforced | Path | -| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | --------------------- | -| Remote delivery to a veth by `bpf_redirect_peer` | `usid_ingress`, after the FIB names the interface and before the redirect | From the outer header | -| Remote delivery to a tap by `bpf_redirect`, or to a cold neighbor by `bpf_redirect_neigh` | `usid_ingress`, as above, which then marks the packet evaluated | From the outer header | -| Same-node delivery through the kernel VRF | `tp_deliver` on the receiver's host interface | Private | -| Local private service delivery by `bpf_redirect_neigh` | `tp_deliver` | Private | -| Packet Too Big that `usid_egress` sends back to the workload | `tp_deliver` | Private | -| Host-generated traffic, such as kernel ICMP errors | `tp_deliver` | Private | -| Delivery from the ingress sidecar | `tp_deliver` | Private | - -- `bpf_redirect_peer` moves the packet into the peer namespace without running - the host device's tc egress, so `usid_ingress` must check before the - redirect. Plain `bpf_redirect` and `bpf_redirect_neigh` transmit through the - host device, so `tp_deliver` would see the same packet again. -- To check it once, `usid_ingress` sets a reserved mark value on the packets it - has evaluated and sends by those two helpers. `tp_deliver` skips a packet - that carries exactly that value and clears it. A workload cannot set it: a - normal veth transmit between namespaces clears the mark, and a tap delivers - with mark 0. A host component that uses the same mark value would collide, - so the value is configurable (`GALACTIC_CNI_POLICY_MARK`) and the rollout - guide has operators check it against the node's netfilter and routing - rules. -- Kubelet probes reach a pod through its primary network, not a Galactic - interface, so they never meet `tp_deliver`. -- Deny is a real `TC_ACT_SHOT` before any fallback. A missing route is never - used to mean deny. - -### Parser contract - -| Packet | Behavior | -| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -| Well-formed IPv4 or IPv6 | Evaluate the rules | -| IPv4 with MF set or a nonzero offset; IPv6 with any Fragment header, including an atomic fragment | `parse_error` drop before any rule | -| Truncated or malformed header, or a parser bound exceeded | `parse_error` drop before any rule | -| Validated ARP or neighbor discovery on the allowlist | Link operation, outside the rules and their metrics | -| Any other non-IP frame, or invalid ARP | Link drop, counted separately | -| GSO skb | The same parse on the observable skb, counted once at its buffer length; never requires a checksum hardware has not computed | - -Bounds and allowlists: - -- IPv4: version 4, IHL from 5 to 15, total length at least the header and no - more than the buffer. Options are skipped without interpretation; they never - move or hide the transport header. -- IPv6: payload length no more than the buffer. Extension headers on the - allowlist are Hop-by-Hop (0), Destination Options (60), and Routing (43) - only with segments left 0, at most 4 of them and 256 bytes in total. A - Routing header with segments left could be re-forwarded to a destination - other than the one evaluated, so it is `parse_error`. Fragment (44), AH - (51), Mobility (135), HIP (139), Shim6 (140) and the experimental values are - `parse_error`. ESP (50) and No Next Header (59) end the chain as a protocol - with no ports. -- TCP and UDP need the whole fixed header inside the IP packet. ICMP and - ICMPv6 need their first 4 bytes. -- Ethernet padding after the IP total length is excluded from the byte count. - -Dropping every fragment is a behavior change: today fragments are forwarded -(the service path only drops them by marker). It is listed under -[Risks and mitigations](#risks-and-mitigations). In `audit` mode a fragment -is counted as a `parse_error` that would have been dropped, and forwarded. - -### Link operation exceptions - -Only these frames bypass the rules, and only after validation. - -| Frame | Direction | Checks | -| ------------------------------------------------------------------------------------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| ARP request or reply | Both | Ethernet/IPv4, hardware length 6, protocol length 4; on egress, the sender address is one of the interface's IPv4 addresses or 0.0.0.0, and the target is the gateway, the sender itself (gratuitous ARP) or one of the interface's addresses (an RFC 5227 probe) | -| Router Solicitation (133), Neighbor Solicitation (135), Neighbor Advertisement (136) | Egress | Hop limit 255, code 0, valid length, no extension headers; source is link-local, one of the interface's addresses, or unspecified for DAD; destination is link-local unicast, in `ff02::/16`, or the interface's gateway address | -| Router Advertisement (134), Neighbor Solicitation, Neighbor Advertisement | Ingress | Hop limit 255, code 0, valid length, no extension headers. The source is not checked: a hop limit of 255 already proves the message came from the link, and the host answers for the gateway from the gateway's own address | - -The destination check stops a workload from using a neighbor discovery type to -reach another tenant's routable address past its own egress policy. A message -the kernel forwarded has a hop limit below 255, so it fails the ingress check -and is evaluated as ordinary traffic. - -Everything else is ordinary tenant traffic: DNS, other ICMP, multicast and -link-local data. Galactic does not serve DHCP, so there is nothing to except. -Under default deny that includes Packet Too Big and other ICMP errors, so a -policy that allows TCP should usually allow ICMPv6 type 2 (and ICMP type 3 -code 4 for IPv4) toward the workload. The user guide says so. - -### BPF maps - -Every map is new, so no existing pinned map changes layout. - -| Map | Type | Key, value | Writer | -| -------------------------- | -------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------ | -| `tp_iface_table` | HASH | ifindex, `{policy_token, kind, state}` | CNI ADD and DEL, the sidecar installer, repair | -| `tp_iface_addr_table` | HASH | `{ifindex, family, address}`, nothing | CNI ADD and DEL, for the link-operation source checks | -| `tp_binding_table` | HASH_OF_MAPS | `{ifindex, direction}`, inner snapshot | galactic-router | -| inner snapshot | ARRAY, 257 entries | 0: header `{policy_token, counter_base, count}`; 1-256: compiled entries | galactic-router, before insertion | -| `tp_nat_locator_table` | HASH | shard Block and Node, nothing | Installer | -| `tp_rule_counters` | PERCPU_ARRAY, 16,384 | counter ID, `{packets, bytes}` | Datapath | -| `tp_fallback_counters` | PERCPU_HASH | `{ifindex, policy_token, direction, reason}`, `{packets, bytes}` | Rows created by CNI ADD; datapath updates existing rows only | -| `tp_unattributed_counters` | PERCPU_ARRAY | `{direction, reason}`, `{packets, bytes}` | Datapath | -| `tp_accounting_errors` | PERCPU_ARRAY | `{direction, action}`, count; the one reason is a missing rule counter | Datapath | -| `tp_link_drops` | PERCPU_ARRAY | direction, `{packets, bytes}` | Datapath | -| `tp_state` | ARRAY(1) | enforcement mode, NAT locator synced flag | Installer | - -A compiled entry is 88 bytes: action, logical rule index, match flags, family, -protocol, path, ICMP type and code, one source and one destination port range, -and the source and destination prefixes each with its mask. The masks are -computed in user space so matching is a branch-free masked compare: compared -bit length by bit length, the verifier explored every length and the -evaluation alone cost about 13,000 instructions; with masks the whole of -`usid_egress` verifies in about 12,500, against 9,700 before the policy hooks -and a budget of 20,000. Evaluation walks the snapshot with -`bpf_for_each_map_elem` (5.13), which iterates the inner array in index order -and stops at the first match. The logical rule index -plus the snapshot's `counter_base` gives the counter row, so every entry a -rule expands to adds to that rule's one row. - -**Policy token.** CNI ADD writes a random 64-bit `policy_token` into -`tp_iface_table` when it creates the interface, and nothing else changes it. -That is deliberately not the existing `attachment_identity_table` token, -which also rotates whenever programs are replaced. A snapshot header's token -must equal the interface row's token, so a recycled ifindex, whose row CNI ADD -rewrites, never inherits a previous interface's snapshot, while a program -upgrade leaves every binding valid. - -**Stack.** `usid_egress` is already close to the 512-byte stack limit, which -is why `send_too_big` and `clamp_tcp_mss` are global functions. `tp_capture` -and `tp_decide` are global functions too, and keep the packet tuple and the -walk's state in a per-CPU scratch map rather than on the stack. The kernel -refuses to load any program whose deepest call chain passes 512 bytes, and -every kernel test loads the full datapath, so a change that crosses it fails -in CI. - -### Publication and lifetime - -**Switching a direction.** - -1. Allocate counter rows and zero them, so every installed rule is visible - with zero hits. -2. Create a new inner map and write its header and entries. -3. Insert it with one update of `tp_binding_table[{ifindex, direction}]`. - -The two directions are separate keys, so neither update can overwrite the -other. - -**Holding a snapshot.** An evaluation does one lookup in the outer map and -uses the returned inner map for the rest of the run. tc programs are -non-sleepable and run inside an RCU read-side critical section, so a packet -evaluates against exactly one complete snapshot, old or new. - -**When the old snapshot is no longer in use.** An update or delete of a -map-in-map entry from user space calls `synchronize_rcu()` before the -syscall returns (`maybe_wait_bpf_programs()` in `kernel/bpf/syscall.c`, there -since Linux 4.20). The kernel added that wait precisely so user space would -know that every non-sleepable program that could have looked up the old inner -map has finished. So when the outer-map update returns, no program holds the -old snapshot or can write the counter rows only it referenced. - -**Retiring counters.** After the update returns, the agent frees the counter -IDs that only the old snapshot referenced. A user-space reference count or a -timer is never the evidence; the synchronous wait is. Releasing the old inner -map's memory is the kernel's business: since Linux 6.8 ("bpf: Defer the free -of inner map when necessary") it is freed only after the grace periods that -also cover sleepable programs, which closed a use-after-free in older -kernels. The publication tests race updates against packets and check that -no packet is ever counted in a row after its ID is freed. - -**Failure.** If the outer-map update fails, the old snapshot stays bound and -its counters stay live; the new inner map is closed and its rows freed. Live -storage is never reused. - -**Restart.** The outer map and the counter arrays are pinned. A restarted -agent rebuilds its allocator from the inner maps still referenced by the -outer map, and treats every counter row they do not reference as free. - -**Counter continuity.** Within one interface lifetime, a rule's counter row is -keyed by its name and action. A new snapshot that keeps both reuses the row, -whatever its match or position. Renaming the rule or changing its action -starts a new row. Unbinding, removing a rule or changing its action ends the -interval at publication. Returning later starts a new row at zero; a freed -row is zeroed before reuse and never revived with old counts. - -### Lifecycle activation and continuity - -The CNI chain is `galactic-veth` or `galactic-tap` (the master plugin, which -creates the interface and today brings both ends up), then `galactic-bgp` -(which registers the datapath and attaches `usid_service_egress` and -`usid_egress` through `attachreg.RegisterDatapath`). Activation follows that -order when the enforcement mode is `audit` or `enforce`: - -1. **Master plugin.** Create the interface, bring the workload side up, and - leave the host side down. Down keeps the workload's sent traffic, and any - delivery that transmits through the host device, from moving. -2. **`galactic-bgp`.** Write the `tp_iface_table` row (kind `tenant`, state - `pending`, a new `policy_token`) and the fallback counter rows; register - the datapath; attach `tp_deliver`; read every filter back to verify it. -3. **`galactic-bgp`.** Set the host side up and report success. With state - `pending` and no binding row, every packet in both directions is denied as - `policy_unavailable` until galactic-router publishes the built-in default - or the bound policy. - -A failure in step 2 or 3 leaves the host side down, rolls back only state -belonging to this interface lifetime, and fails the ADD. If the node has no -SRv6 locator, `RegisterDatapath` registers nothing today and succeeds; with -enforcement on, `galactic-bgp` fails the ADD instead, since nothing would -enforce policy. The tap plugin's repair path, which brings a down tap back -up, first checks that the interface's `tp_iface_table` row is active and its -filters are present. - -A down host link does not stop `bpf_redirect_peer` delivery, which only -checks the peer. Ingress to a veth is denied by the check inside -`usid_ingress`, which needs the binding row; a missing row denies there. So -there are two independent controls, used together: - -- **Missing map rows** are handled by the programs that are present, which - deny in both directions. -- **A missing tenant-interface program** is handled by the link being down: - repair in `galactic-cni run` sets the host side down before reattaching, - and up only after verification. `usid_ingress` lives on the uplink, not the - tenant interface, so it is unaffected. - -Other operations: - -- **CNI CHECK** reads the filters back as well as the map rows. A missing - filter fails the check. -- **Program upgrades** replace each filter in place with the same priority - and handle. `cls_bpf` swaps the program pointer atomically, so there is no - moment without a program. An upgrade never detaches first, and it never - changes a `policy_token`, so bindings stay valid. -- **Agent crash.** tc filters, pinned maps and a down link all survive a - crash. A restarted agent verifies identity, filters and map compatibility - before setting any link up. -- **Map loss.** If a policy map has to be recreated because its shape - changed, the loader removes the old pin only after every managed link has - been set down and every binding is gone. Repair restores state, then sets - the links up. -- **Last resort.** If the agent cannot publish an invalidation, it deletes the - outer-map row, which denies both directions; if that also fails it sets the - host link down, which stops egress and every non-peer delivery, and reports - the interface as quarantined. A node whose map operations fail entirely - cannot deny peer-redirect ingress; that is reported, not hidden. - -Continuity covers agent crashes, loader and upgrade failures, and controlled -map or program replacement. A privileged user removing filters or maps by hand -is outside this guarantee. - -In mode `off` none of these lifecycle changes apply: links come up as they do -today, CHECK ignores the new filter, and repair never sets a link down. The -`tp_iface_table` rows and filters are still written, so switching a node to -`audit` or `enforce` needs no interface recreation. - -Revocation applies to every packet evaluated after publication in that -direction, including packets of existing flows. NAT sessions, shard pins, -cached routes and service entries are not exemptions. A packet already -evaluating against the old snapshot finishes under it. - -### Reconciliation and status - -**galactic-controller (`--role=cell`)** owns the API side: - -- serves the validating webhook; -- provisions `default-deny-all`; -- resolves each binding's references and writes `status.ingress` and - `status.egress`; -- surfaces validation and compile errors on the TrafficPolicy status. - -**galactic-router** owns the node side, because it already watches -VPCAttachment and writes per-interface fail-closed maps. Its new -TrafficPolicyReconciler: - -- watches TrafficPolicy, TrafficPolicyBinding and VPCAttachment; -- maps each attachment whose `status.node` is this node to its host ifindex - and `policy_token`; -- compiles each direction, publishes and retires snapshots as above; -- reports the applied identity and generation in `status.nodes`. - -It reconciles on start, on every watch event, and every five minutes. After a -restart it adopts each snapshot whose token, policy UID and generation still -match, so counters continue; one no attachment claims within a resync is -unbound and its rows freed. galactic-cni removes the outer-map rows of -interfaces that no longer exist. It writes no status on VPCAttachment. It runs -only when `GALACTIC_ROUTER_TRAFFIC_POLICY` is set, because it watches CRDs a -cluster may not have installed. - -A diagnostic command, `galactic-router policy show /`, -prints both bindings, this node's status entry, the bound snapshots and each -rule's counters. `galactic-router policy explain` evaluates a packet tuple and -path against a policy file or a live policy with both the Go evaluator and the -compiled entries, fails if they disagree, and never touches live counters. - -### Metrics - -Exported from galactic-router's existing `:9179/metrics` endpoint, which -already has a PodMonitor. galactic-router allocates every counter row and -knows which rule, policy and interface it belongs to, so it is the one -process that can label a row without a second lookup table. The -`galactic_cni_` prefix names the datapath the counters belong to, not the -process that serves them. A row the collector cannot read is left out, not -reported as zero, and counted in the `galactic_cni_traffic_policy_counter_read_errors` -gauge. - -| Metric | Labels | -| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `galactic_cni_traffic_policy_rule_hits_total` | namespace, vpc, attachment, interface, interface_uid, direction, policy, policy_uid, rule, action | -| `galactic_cni_traffic_policy_rule_bytes_total` | the same | -| `galactic_cni_traffic_policy_fallback_packets_total` | namespace, vpc, attachment, interface, interface_uid, direction, reason | -| `galactic_cni_traffic_policy_fallback_bytes_total` | the same | -| `galactic_cni_traffic_policy_unattributed_drops_total` | direction, reason | -| `galactic_cni_traffic_policy_accounting_errors_total` | direction, action, reason | - -- `reason` on the fallback metrics is one of `no_match`, - `policy_unavailable`, `parse_error` or `classification_error`. -- `interface_uid` is the VPCAttachment UID. -- The collector labels each row from what galactic-router installed, never - from packet fields. After a restart, a row counts on in the kernel and is - exported again once its interface is reconciled and its snapshot adopted. -- Each evaluation produces exactly one outcome: a winning rule's hit and bytes, - or one fallback pair. The one exception is a packet captured while the mode - was off and decided just after it turned on, at most one per CPU at the - switch, which is forwarded and not counted. -- Bytes are the tenant IP packet at the evaluation point, without Ethernet or - outer SRv6. A GSO skb counts once at its buffer length. -- A malformed packet whose IP boundary cannot be found adds zero bytes. -- A missing counter row keeps the verdict and increments - `accounting_errors_total{reason="missing_rule_counter"}`. - -**Cardinality.** A node exports, per tenant interface, one series pair per -installed rule per direction plus four fallback pairs per direction. A node -with 100 interfaces whose policies average 8 rules exports about -100 × 2 × (8 + 4) × 2 = 4,800 series. The limits (64 rules, 256 entries) cap -the worst case at 100 × 2 × 68 × 2 = 27,200, which PR 7 states as the -supported budget. `policy_uid` changes only on rebind or recreation, which -ends the old series by design. - -### Kernel requirements - -The design needs `HASH_OF_MAPS`, `bpf_for_each_map_elem` (5.13), the tc egress hook, the -synchronous map-in-map wait (4.20), and the 6.8 fix to inner-map freeing. -Production and staging run Talos v1.13.10, whose kernel line is 6.18. - -The CNI preflight gains probes for `HASH_OF_MAPS` and `bpf_for_each_map_elem`. The inner-map -fix cannot be probed, so the preflight also requires kernel 6.8 or later. That -check is deliberately conservative: it rejects a distribution kernel that -backported the fix, and an operator can override it with -`GALACTIC_CNI_TRAFFIC_POLICY_KERNEL_CHECK=false` after confirming the -backport. A node that fails them reports a capability error and, when the mode -is `audit` or `enforce`, refuses new managed interfaces. It never falls back to -forwarding without enforcement. This raises the minimum kernel for -enforcement to 6.8, which the pull requests call out. - -## Rollout - -Default deny is a deliberate behavior change. The enforcement mode in -`tp_state` is `off`, `audit` or `enforce`, set per node by -`GALACTIC_CNI_TRAFFIC_POLICY`. It defaults to `off`; only the containerlab lab -enforces by default. [docs/traffic-policy/rollout.md](../../../traffic-policy/rollout.md) -is the operator's step-by-step guide. - -- `off` changes nothing. Maps and programs are loaded, but `tp_capture` and - `tp_decide` return immediately. -- `audit` evaluates and counts every packet but forwards as before. Operators - use the counters to find interfaces whose traffic would be denied. -- `enforce` drops. - -Operators move a site to `enforce` only after every running interface has -explicit bindings for the traffic it needs. An interface created before the -release that adds the ingress side gets its policy row from `galactic-cni` -at startup, with a fresh token, so its bindings apply; its assigned addresses -are not known there, so until the workload is recreated its ARP and its -neighbor discovery from a global address are ordinary traffic rather than -link operations. Recreate such workloads before enforcing. Steady-state interfaces default to -deny in every mode except `off`. There is no legacy allow and no generated -reverse rule. `audit` is a measurement mode for migration, not a -compatibility allowance, and `enforce` is the only mode the steady state uses. - -## Delivery plan - -### Pull request sequence - -Each PR builds and passes `task ci` against its declared base. Until the last -PR, enforcement stays `off` and nothing changes for any packet. - -| # | PR | Depends on | Delivers | Still inactive | -| - | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------------------------------------- | ------------------------------------------ | -| 1 | This design | none | Decisions, audit, lifetime argument, plan | Everything | -| 2 | `api/v1alpha1` TrafficPolicy and TrafficPolicyBinding, generated CRDs and API docs, CEL validation, envtest | 1 | The schema | Nothing reads it | -| 3 | `galactic-controller --role=cell`: webhook, default provisioning, binding resolution status, manifests and RBAC | 2 | Admission and status | Datapath | -| 4 | `internal/trafficpolicy`: Go evaluator and compiler with bounds | 2 | Semantics oracle and entry layout | Datapath | -| 5 | BPF: maps, parser, `tp_capture` and `tp_decide`, egress classification, the checks at every egress exit, the publication package and counter allocator | 4 | Egress enforcement, tested against the Go evaluator | Mode `off` by default; ingress unchecked | -| 6 | Ingress: the check in `usid_ingress`, `tp_deliver`, the ingress mark, link-down activation, CHECK and repair, preflight | 5 | Every path in the audit is checked | Mode `off` by default | -| 7 | galactic-router TrafficPolicyReconciler, node status, collector and metrics, `policy show` and `explain` | 3, 6 | Live updates and observability | Mode `off` by default | -| 8 | Lab: containerlab policies for every fixture, positive and negative checks for each path, docs and rollout guide; the mode defaults to `enforce` in the lab only | 7 | End-to-end validation | Production stays `off` until infra opts in | - -### Requirement checklist - -| Requirement | PRs | Validation | -| ------------------------- | ---------- | -------------------------------------------------------------------------------- | -| R1 per interface | 2, 5, 6, 7 | Two interfaces in one VRF with different policies, same node and remote | -| R2 independent directions | 2, 5, 7 | Binding one direction leaves the other at default | -| R3 no implicit replies | 4, 5, 8 | Egress Allow leaves replies denied; ingress Allow leaves workload replies denied | -| R4 one-rule default | 2, 3, 4 | Default has one rule and no SMTP rule | -| R5 first match | 4, 5 | BPF verdicts equal the Go evaluator on generated packets | -| R6 match fields | 2, 4, 5 | Path, family, IP and CIDR, ports, ICMP tables | -| R7 live updates | 5, 7 | Concurrent publication shows only whole old or whole new verdicts | -| R8 fail closed | 5, 6, 7 | Every binding-transition row and fault-injection case | -| Path audit | 6, 8 | Traffic down each mechanism in the audit, both allowed and denied | -| Parser | 5 | Every parser-table row | -| Metrics | 5, 7 | Collector names, labels and types; exactly-once counting | - -## Alternatives - -- **References on VPCAttachment.** The cloud operator owns and rewrites that - spec, and the cloud repository is being retired into Galactic. -- **A per-attachment on/off NAT switch (NetworkEgressPolicy).** It would - conflict with policy, and the requirement makes NAT an ordinary path match. -- **A standalone tc program in front of `usid_egress`.** It would have to - repeat every route and group lookup to classify the path, and could disagree - with the program that forwards. Calling one evaluator from each forwarding - exit uses the classification the forwarding decision already made. -- **Evaluating ingress only at host tc egress.** `bpf_redirect_peer` skips that - hook, and giving up the peer redirect would cost every veth delivery a - backlog round trip. -- **CEL-only null rejection.** Shown above not to work. +This document moved to [interface-traffic-policy](../../../designs/interface-traffic-policy.md). Update bookmarks to the maintained page. + + + +See [Summary](../../../designs/interface-traffic-policy.md#summary). + + + +See [Motivation](../../../designs/interface-traffic-policy.md#motivation). + + + +See [Goals](../../../designs/interface-traffic-policy.md#goals). + + + +See [Non-goals](../../../designs/interface-traffic-policy.md#non-goals). + + + +See [Proposal](../../../designs/interface-traffic-policy.md#proposal). + + + +See [Fixed requirements](../../../designs/interface-traffic-policy.md#fixed-requirements). + + + +See [Risks and mitigations](../../../designs/interface-traffic-policy.md#risks-and-mitigations). + + + +See [Design details](../../../designs/interface-traffic-policy.md#design-details). + + + +See [API ownership](../../../designs/interface-traffic-policy.md#api-ownership). + + + +See [Resource model](../../../designs/interface-traffic-policy.md#resource-model). + + + +See [Rule language](../../../designs/interface-traffic-policy.md#rule-language). + + + +See [Admission and explicit null](../../../designs/interface-traffic-policy.md#admission-and-explicit-null). + + + +See [Default policy identity](../../../designs/interface-traffic-policy.md#default-policy-identity). + + + +See [Binding transitions](../../../designs/interface-traffic-policy.md#binding-transitions). + + + +See [Forwarding path classification](../../../designs/interface-traffic-policy.md#forwarding-path-classification). + + + +See [Packet path audit](../../../designs/interface-traffic-policy.md#packet-path-audit). + + + +See [Parser contract](../../../designs/interface-traffic-policy.md#parser-contract). + + + +See [Link operation exceptions](../../../designs/interface-traffic-policy.md#link-operation-exceptions). + + + +See [BPF maps](../../../designs/interface-traffic-policy.md#bpf-maps). + + + +See [Publication and lifetime](../../../designs/interface-traffic-policy.md#publication-and-lifetime). + + + +See [Lifecycle activation and continuity](../../../designs/interface-traffic-policy.md#lifecycle-activation-and-continuity). + + + +See [Reconciliation and status](../../../designs/interface-traffic-policy.md#reconciliation-and-status). + + + +See [Metrics](../../../designs/interface-traffic-policy.md#metrics). + + + +See [Kernel requirements](../../../designs/interface-traffic-policy.md#kernel-requirements). + + + +See [Rollout](../../../designs/interface-traffic-policy.md#rollout). + + + +See [Delivery plan](../../../designs/interface-traffic-policy.md#delivery-plan). + + + +See [Pull request sequence](../../../designs/interface-traffic-policy.md#pull-request-sequence). + + + +See [Requirement checklist](../../../designs/interface-traffic-policy.md#requirement-checklist). + + + +See [Alternatives](../../../designs/interface-traffic-policy.md#alternatives). diff --git a/docs/enhancements/networking/latency-aware-routing/README.md b/docs/enhancements/networking/latency-aware-routing/README.md index 515134972..f5b824f57 100644 --- a/docs/enhancements/networking/latency-aware-routing/README.md +++ b/docs/enhancements/networking/latency-aware-routing/README.md @@ -1,530 +1,87 @@ ---- -status: provisional -stage: alpha -latest-milestone: "v0.1" ---- - - # Latency-Aware Routing -- [Summary](#summary) -- [Motivation](#motivation) - - [Goals](#goals) - - [Non-Goals](#non-goals) -- [Proposal](#proposal) - - [Policy Model](#policy-model) - - [Delay Measurement](#delay-measurement) - - [Delay Distribution via BGP](#delay-distribution-via-bgp) - - [Path Selection](#path-selection) - - [Tag-Based Policy Routing](#tag-based-policy-routing) - - [Policy Enforcement Points](#policy-enforcement-points) - - [Tenant Observability](#tenant-observability) - - [How It Comes Together](#how-it-comes-together) -- [Design Decisions](#design-decisions) -- [Roadmap](#roadmap) -- [Dependencies](#dependencies) - -## Summary - -Latency-aware routing enables VPC customers to express routing intent — low -latency, geographic constraints, bandwidth requirements — as declarative -policies attached to their workloads. The platform continuously measures -network delay between nodes, distributes delay metrics through -[BGP][bgp-overview], and makes autonomous, per-node path selection decisions -using [SRv6][srv6] traffic engineering. Customers see the results through -metrics exposed in the platform's telemetry system. - -This enhancement builds on the existing [BGP control plane][datum-bgp] and -[SRv6 data plane](../vpc/) to add three capabilities: active delay -measurement, delay-aware route advertisement, and policy-driven path -selection — all operating autonomously within each cluster without -management cluster involvement in the forwarding path. - -## Motivation - -Today, traffic between VPC workloads follows the shortest available path -through the network fabric — but the shortest path isn't always the fastest. -As the platform scales across regions and availability zones, the gap between -"shortest path" and "lowest latency path" grows. Customers running -latency-sensitive workloads have no way to express that their traffic should -prefer low-latency paths, and no visibility into the actual latency their -traffic experiences. - -Different services within the same VPC have fundamentally different -connectivity requirements. A real-time trading API needs sub-millisecond -optimization while a batch log shipper just needs reachability. Geo-aware -routing, latency-based routing, and bandwidth optimization are per-service -concerns, not per-network concerns. The platform needs to support this -granularity down to the individual connection. - -The core insight from research into protocols like [DDM][ddm] (Delay Driven -Multipath) and Google's [Swift][swift] is that **delay is a simple, -effective, and universal signal** for path quality — it inherently encodes -congestion, distance, and link health into a single measurable value. - -### Goals - -- Continuously measure network delay between all nodes using active probes - based on [STAMP][stamp] -- Distribute measured delay metrics through the existing BGP control plane - using standard path attributes ([AIGP][aigp]) -- Enable each node to make autonomous, delay-aware path selection decisions - without management cluster involvement -- Allow VPC customers to express routing intent (low latency, geographic - constraints) as declarative policies with workload selectors -- Apply policies at attachment time — when a pod starts or a - [MASQUE][masque] tunnel is established — not per-packet -- Expose measured path latency, jitter, and loss to customers through the - platform's telemetry system -- Provide basic connectivity optimization for all VPCs by default - -### Non-Goals - -- Replacing the primary CNI for intra-cluster pod-to-pod networking -- Per-packet deep inspection or application-layer routing decisions -- Centralized path computation (PCE) for routine routing decisions — nodes - must operate autonomously -- Hardware-specific optimizations (ASIC timestamping, hardware queuing) -- Guaranteed bandwidth reservation (this is a path selection enhancement, - not a QoS reservation system) - -## Proposal - -### Policy Model - -Routing intent is expressed through two resource types: a tenant-facing -**VPCRoutingPolicy** that selects workloads and assigns tags, and a -platform-level **RoutingProfile** that defines what each tag means in terms -of forwarding behavior. - -**VPCRoutingPolicy** — created by tenants, scoped to a VPC: - -```yaml -apiVersion: networking.galactic.datumapis.com/v1alpha1 -kind: VPCRoutingPolicy -metadata: - name: gold-realtime -spec: - vpcRef: my-vpc - selector: - matchLabels: - app: trading-engine - tag: gold - requirements: - maxLatency: 5ms - geoConstraint: US -``` - -```yaml -apiVersion: networking.galactic.datumapis.com/v1alpha1 -kind: VPCRoutingPolicy -metadata: - name: standard-batch -spec: - vpcRef: my-vpc - selector: - matchLabels: - app: log-shipper - tag: standard -``` - -Multiple policies can coexist for the same VPC — different services get -different routing behavior. Policy selectors match against workload labels -on VPCAttachments and ConnectorAttachments. - -**RoutingProfile** — defined by the platform, delivered to clusters by the -fleet agent: - -```yaml -apiVersion: networking.galactic.datumapis.com/v1alpha1 -kind: RoutingProfile -metadata: - name: gold -spec: - color: 100 - dscp: 46 # EF - Expedited Forwarding - pathSelection: min-delay - constraints: - maxLatency: 5ms - affinities: - include: [US] ---- -apiVersion: networking.galactic.datumapis.com/v1alpha1 -kind: RoutingProfile -metadata: - name: standard -spec: - color: 300 - dscp: 0 # Best Effort - pathSelection: default -``` - -The RoutingProfile translates a tag into three forwarding behaviors: - -- **Color** ([SR Policy Color Extended Community][sr-policy]): determines - which set of delay-aware routes the headend resolves against -- **DSCP**: marks the outer IPv6 header so every transit node applies the - correct queuing behavior without any tenant awareness -- **Path selection constraints**: delay ceiling, geographic affinity - inclusion/exclusion, bandwidth floor - -### Delay Measurement - -Each galactic-agent node runs a [STAMP][stamp] sender and reflector to -actively measure one-way and round-trip delay to its BGP peers. STAMP is the -IETF standard for active measurement, with [SRv6-specific -extensions][stamp-sr] that ensure probes follow the exact same paths as real -traffic. - -Measurement operates entirely in-memory on each node: - -1. The agent sends STAMP test packets to each peer at a configured interval - (e.g., every 2 seconds) -2. Timestamps are applied at send (T1), receive (T2), reflect (T3), and - return (T4) -3. Two-way delay = (T4 - T1) - (T3 - T2) — no clock synchronization - required -4. The agent maintains a rolling average delay value per peer link -5. Delay values are stored in the agent's local memory — **never written to - etcd** - -On Linux, the STAMP reflector can be implemented as an [eBPF][ebpf] program -attached to SRv6 SID processing via the kernel's `End.BPF` behavior, -providing kernel-space timestamping with negligible forwarding impact. - -### Delay Distribution via BGP - -Measured delay is distributed through BGP itself — the same TCP sessions -already exchanging routes. No additional protocols, no etcd writes, no -management cluster involvement. - -The mechanism is the [AIGP attribute (RFC 7311)][aigp], an optional BGP path -attribute that accumulates a metric across AS boundaries. The -[draft-ietf-idr-performance-routing][perf-routing] proposes a -NETWORK_LATENCY TLV within AIGP specifically for delay values. - -**How it flows:** - -1. Node A measures 2ms delay to Node B via STAMP -2. When Node A advertises its SRv6 /48 prefix, the advertisement reconciler - attaches an AIGP attribute with the measured delay value (2000 - microseconds) -3. Node B receives the route. When re-advertising to Node C, Node B adds - its own measured link delay to the AIGP value (accumulation) -4. By the time a route reaches a decision point, the AIGP value represents - the total end-to-end delay along that path - -``` -Node A originates route for 2001:db8:x::/48 - → AIGP: 0 μs (originated locally) - -Node B receives from Node A, re-advertises to Node C - → AIGP: 2000 μs (0 + 2000 measured on A→B link) - -Node C receives from Node B, re-advertises to Node D - → AIGP: 5000 μs (2000 + 3000 measured on B→C link) - -Node D has two paths to 2001:db8:x::/48: - Path 1 via Node C: AIGP = 5000 μs - Path 2 via Node E: AIGP = 3000 μs - → GoBGP selects Path 2 (lower AIGP wins) -``` - -[GoBGP][gobgp] already implements AIGP-aware best-path selection — AIGP -comparison runs before AS-path length in the tie-breaking sequence. No -custom path selection logic is needed. - -**What touches etcd vs. what doesn't:** - -| Data | Where it lives | Update frequency | -|------|---------------|-----------------| -| Delay measurements | Agent memory | Every few seconds | -| AIGP attribute on routes | BGP sessions (TCP) | On measurement change | -| RoutingProfile definitions | etcd (CRD) | Infrequent (policy changes) | -| VPCRoutingPolicy | etcd (CRD) | Infrequent (tenant changes) | -| Per-link delay metrics | Prometheus | Scraped periodically | - -High-frequency delay data never touches the API server. - -### Path Selection - -When a node has multiple BGP paths to the same prefix, GoBGP's existing -best-path algorithm uses the AIGP value as a tiebreaker — lower accumulated -delay wins. The route watcher receives the best-path update and programs the -kernel via `netlink.AddRoute`. No explicit segment lists are needed for -basic delay optimization. - -For Color-aware routing, the node resolves routes differently per Color: - -1. A BGP route arrives with a [Color Extended Community][sr-policy] - (e.g., Color 100 = min-delay) -2. The node resolves the route against paths tagged with that Color -3. Among matching paths, AIGP selects the lowest-delay option -4. The route watcher programs the appropriate kernel forwarding entry - -This is the distributed model — every node makes its own path selection -decision based on locally-received BGP routes with delay annotations. No -central controller is involved in the forwarding path. The management -cluster's only role is delivering the RoutingProfile definitions that map -Colors to constraints, which happens infrequently via the fleet agent. +This document moved to [latency-aware-routing](../../../designs/latency-aware-routing.md). Update bookmarks to the maintained page. + + + +See [Summary](../../../designs/latency-aware-routing.md#summary). + + + +See [Motivation](../../../designs/latency-aware-routing.md#motivation). + + + +See [Goals](../../../designs/latency-aware-routing.md#goals). + + + +See [Non-Goals](../../../designs/latency-aware-routing.md#non-goals). + + + +See [Proposal](../../../designs/latency-aware-routing.md#proposal). + + + +See [Policy Model](../../../designs/latency-aware-routing.md#policy-model). + + + +See [Delay Measurement](../../../designs/latency-aware-routing.md#delay-measurement). + + + +See [Delay Distribution via BGP](../../../designs/latency-aware-routing.md#delay-distribution-via-bgp). + + + +See [Path Selection](../../../designs/latency-aware-routing.md#path-selection). + + + +See [Tag-Based Policy Routing](../../../designs/latency-aware-routing.md#tag-based-policy-routing). + + + +See [Policy Enforcement Points](../../../designs/latency-aware-routing.md#policy-enforcement-points). + + + +See [Tenant Observability](../../../designs/latency-aware-routing.md#tenant-observability). + + + +See [How It Comes Together](../../../designs/latency-aware-routing.md#how-it-comes-together). + + -### Tag-Based Policy Routing +See [Design Decisions](../../../designs/latency-aware-routing.md#design-decisions). -Tags connect tenant intent to forwarding behavior through three layers: + -**Classification (at the source node):** +See [Distributed path selection over centralized PCE](../../../designs/latency-aware-routing.md#distributed-path-selection-over-centralized-pce). -When a pod starts and the CNI plugin creates its VPC network interface, the -galactic-agent evaluates VPCRoutingPolicy selectors against the pod's -labels. The matching policy's tag resolves to a RoutingProfile, and the -agent programs an eBPF classifier on the pod's veth interface that: + -- Sets the DSCP value in the outer IPv6 header -- Steers traffic toward routes matching the profile's Color +See [AIGP for delay transport over custom attributes](../../../designs/latency-aware-routing.md#aigp-for-delay-transport-over-custom-attributes). -This classification is programmed once at attachment time. Per-packet -processing is a simple eBPF lookup — no policy evaluation per packet. + -**Path steering (at the headend):** +See [Policy at attachment time over per-packet classification](../../../designs/latency-aware-routing.md#policy-at-attachment-time-over-per-packet-classification). -The DSCP-marked, Color-steered packet is SRv6-encapsulated using the -delay-optimized path selected for that Color. The segment list is determined -by the BGP route resolution for the destination prefix at the specified -Color. + -**Per-hop treatment (at transit nodes):** +See [Delay data in BGP over etcd](../../../designs/latency-aware-routing.md#delay-data-in-bgp-over-etcd). -Transit nodes see only the DSCP value in the outer IPv6 header and the SRv6 -destination. They apply queuing behavior based on DSCP (standard Linux -traffic control) and forward based on the segment list. Transit nodes have -no knowledge of tenants, policies, or tags. + -``` -Source node (headend): - - Knows the tenant policy (VPCRoutingPolicy CRD) - - Classifies traffic by pod labels - - Chooses path based on Color - - Sets DSCP based on tag - - Encapsulates in SRv6 +See [Default optimization for all VPCs](../../../designs/latency-aware-routing.md#default-optimization-for-all-vpcs). -Transit nodes: - - See DSCP in outer IPv6 header → queue priority - - See SRv6 destination → forward per segment list - - No knowledge of tenants, policies, or tags + -Destination node: - - End.DT46 decapsulates into VRF - - Delivers to destination pod -``` - -### Policy Enforcement Points - -Policies are applied at **attachment time** — the moment a workload connects -to the VPC network. This is the identity boundary where the platform knows -which tenant, service, and routing requirements apply. - -**Pod attachment (CNI time):** - -The galactic-agent programs the eBPF classifier on the pod's veth pair when -the CNI plugin creates the network interface. The pod's labels are matched -against VPCRoutingPolicy selectors, and the resulting classification rules -are installed. +See [Roadmap](../../../designs/latency-aware-routing.md#roadmap). -**Connector attachment ([MASQUE][masque] tunnel establishment):** - -When a Connector establishes a MASQUE tunnel, the proxy: + -1. Authenticates the client (mTLS client certificate) -2. Looks up the ConnectorAttachment — confirms VPC binding -3. Evaluates VPCRoutingPolicy selectors against the ConnectorAttachment's - labels -4. Programs classification rules for this tunnel -5. All traffic entering through the tunnel gets the correct DSCP marking - and Color-based path selection - -Different Connectors to the same VPC can get different routing treatment -based on their labels: - -```yaml -ConnectorAttachment "trading-link": - labels: { app: trading, tier: premium } - → matches VPCRoutingPolicy "gold-realtime" - → Color 100, DSCP 46, min-delay path - -ConnectorAttachment "log-link": - labels: { app: logging, tier: standard } - → matches VPCRoutingPolicy "standard-batch" - → Color 300, DSCP 0, default path -``` - -**Gateway attachment:** - -Gateway pods connecting to VPC networks follow the same pattern as pod -attachment — the galactic-agent programs classification rules when the -Gateway's VPCAttachment is created. - -**Policy updates:** - -If a tenant updates their VPCRoutingPolicy, the galactic-agent watches for -the change and reprograms the eBPF classifiers on affected attachments. The -data plane connections remain up — only the forwarding behavior changes. - -### Tenant Observability - -Measured delay data is exposed to tenants through the platform's telemetry -system — the same metrics and dashboards they use for everything else. - -**Platform-level metrics (for operators):** - -- `bgp_link_delay_microseconds{peer="..."}` — per-link measured delay -- `bgp_link_delay_variation_microseconds{peer="..."}` — jitter -- `bgp_path_aigp_microseconds{prefix="...", peer="..."}` — accumulated - end-to-end delay per path - -**Tenant-visible metrics:** - -- Per-VPC latency between attachment points -- Per-policy SLO compliance (is traffic actually meeting the maxLatency - constraint?) -- Path performance for traffic matching each VPCRoutingPolicy - -These are derived from the same STAMP measurements that drive routing -decisions, but aggregated and scoped per-tenant through the telemetry -pipeline. Tenants observe outcomes; they don't interact with the measurement -infrastructure directly. - -### How It Comes Together - -When a new workload connects to a VPC with latency-aware routing: - -1. Tenant creates a **VPCRoutingPolicy** with a selector and tag -2. The fleet agent has already delivered the **RoutingProfile** definitions - to the cluster (Color, DSCP, path selection constraints) -3. A pod starts — the **CNI plugin** creates the VPC interface -4. The **galactic-agent** evaluates the policy selector against the pod's - labels, resolves the tag to a RoutingProfile, and programs the **eBPF - classifier** on the pod's veth -5. Meanwhile, STAMP probes have been continuously measuring link delays - between all nodes -6. Delay values are attached as **AIGP attributes** on BGP route - advertisements and accumulate across the path -7. GoBGP selects the **lowest-delay path** for routes matching the pod's - Color -8. The first packet from the pod is classified (DSCP marked, Color - steered), **SRv6-encapsulated** with the delay-optimized segment, and - forwarded -9. Transit nodes **queue by DSCP** and forward by SRv6 — no tenant - awareness needed -10. The destination node **decapsulates** (End.DT46) into the VRF and - delivers to the target pod -11. **Telemetry** exposes the measured latency to the tenant, confirming - the SLO is being met - -The management cluster's involvement was limited to delivering the -RoutingProfile definitions. Everything else — measurement, route -advertisement, path selection, classification, forwarding — operates -autonomously within the cluster. - -## Design Decisions - -### Distributed path selection over centralized PCE - -The platform uses BGP-distributed delay metrics and per-node path selection -rather than a centralized Path Computation Element. This follows the -existing design principle that clusters are self-sufficient once the fleet -agent delivers initial configuration. - -A centralized PCE would create a latency and availability bottleneck — -every path decision would depend on reachability to the controller. The -distributed model means each node makes decisions using locally-received BGP -routes, reacting to delay changes in real-time without calling home. - -The tradeoff is that complex multi-constraint optimization (e.g., "low delay -AND avoid region X AND disjoint from path Y") may require a controller in -the future. The Color-based architecture accommodates this — a central -controller could populate SR Policies for specific Colors without changing -the tenant-facing model. - -### AIGP for delay transport over custom attributes - -AIGP (RFC 7311) is a standard BGP attribute with native accumulation -semantics — each node adds its contribution as the route propagates. GoBGP -already supports it. Using a standard attribute means the delay information -works across eBGP boundaries between clusters without custom interop. - -### Policy at attachment time over per-packet classification - -Evaluating tenant policies once when the workload connects (CNI time or -MASQUE tunnel establishment) avoids per-packet policy lookups. The eBPF -classifier programmed at attachment time executes in the kernel fast path -with no user-space involvement. Policy changes trigger reprogramming of the -classifier, not per-packet evaluation. - -### Delay data in BGP over etcd - -STAMP measurements update every few seconds per link. Writing these to CRDs -would generate massive etcd write load and trigger reconciliation storms. -Instead, delay values flow through BGP sessions (existing TCP connections -between nodes) and are consumed by GoBGP's in-memory path selection. -Prometheus metrics provide observability. etcd stores only infrequently -changing policy definitions. - -### Default optimization for all VPCs - -All VPCs get basic connectivity optimization without explicit policy. The -platform always prefers better-performing paths when they exist, because -AIGP-aware best-path selection runs for all routes regardless of Color. -Explicit policies let tenants tighten constraints beyond the baseline. - -## Roadmap - -| Phase | Scope | -|-------|-------| -| **Phase 1** | STAMP measurement between nodes; AIGP delay attribute on route advertisements; basic delay-aware best-path selection for all traffic | -| **Phase 2** | VPCRoutingPolicy and RoutingProfile CRDs; Color Extended Community support; tag-based classification with eBPF; DSCP marking; per-tag path selection | -| **Phase 3** | MASQUE Connector policy enforcement; geographic affinity constraints; tenant-facing latency metrics; SLO compliance alerting | -| **Phase 4** | Cross-cluster delay optimization via eBGP AIGP propagation; predictive routing using delay derivatives (DDM-inspired); bandwidth-aware path selection | - -## Dependencies - -- **[VPC Networking](../vpc/)**: Provides the SRv6 data plane, VPC/ - VPCAttachment resources, VRF isolation, and the CNI plugin where - classification rules are installed. - -- **[Fleet Networking](../../infrastructure/fleet-networking/)**: Provides - the BGP control plane, IPAM, and topology policy that this enhancement - extends with delay awareness. RoutingProfile definitions are delivered to - clusters through the same fleet agent mechanism. - -- **[BGP Control Plane][datum-bgp]**: The topology-agnostic BGP system - running on every cluster. This enhancement extends its CRDs and - reconcilers with AIGP support, Color Extended Communities, and STAMP - measurement integration. - -- **Telemetry System**: Platform observability infrastructure where - per-tenant latency metrics are exposed. The galactic-agent exports - Prometheus metrics; the telemetry pipeline aggregates and scopes them - per-tenant. - - -[bgp-overview]: https://datatracker.ietf.org/doc/html/rfc4271 -[srv6]: https://datatracker.ietf.org/doc/html/rfc8986 -[sr-policy]: https://datatracker.ietf.org/doc/html/rfc9256 -[stamp]: https://datatracker.ietf.org/doc/html/rfc8762 -[stamp-sr]: https://datatracker.ietf.org/doc/html/rfc9503 -[aigp]: https://datatracker.ietf.org/doc/html/rfc7311 -[perf-routing]: https://datatracker.ietf.org/doc/draft-ietf-idr-performance-routing/ -[bgp-car]: https://datatracker.ietf.org/doc/draft-ietf-idr-bgp-car/ -[flex-algo]: https://datatracker.ietf.org/doc/html/rfc9350 -[flex-algo-bw]: https://datatracker.ietf.org/doc/html/rfc9843 -[bgp-ls-te]: https://datatracker.ietf.org/doc/html/rfc8571 -[isis-te]: https://datatracker.ietf.org/doc/html/rfc8570 -[network-slicing]: https://datatracker.ietf.org/doc/html/rfc9543 -[ibn]: https://datatracker.ietf.org/doc/html/rfc9315 -[ddm]: https://rfd.shared.oxide.computer/rfd/0347 -[swift]: https://research.google/pubs/swift-delay-is-simple-and-effective-for-congestion-control-in-the-datacenter/ -[espresso]: https://research.google/pubs/taking-the-edge-off-with-espresso-scale-reliability-and-programmability-for-global-internet-peering/ -[masque]: https://datatracker.ietf.org/doc/html/rfc9484 -[gobgp]: https://osrg.github.io/gobgp/ -[datum-bgp]: https://github.com/datum-cloud/bgp -[ebpf]: https://ebpf.io/ +See [Dependencies](../../../designs/latency-aware-routing.md#dependencies). diff --git a/docs/enhancements/networking/private-service-connect/README.md b/docs/enhancements/networking/private-service-connect/README.md index a567e9e1e..ef8ef29c0 100644 --- a/docs/enhancements/networking/private-service-connect/README.md +++ b/docs/enhancements/networking/private-service-connect/README.md @@ -1,533 +1,119 @@ ---- -status: provisional -stage: alpha -latest-milestone: "TBD" ---- - # Private Service Connect -- [Summary](#summary) -- [Motivation](#motivation) - - [Goals](#goals) - - [Non-goals](#non-goals) -- [Proposal](#proposal) - - [User stories](#user-stories) - - [Notes, constraints, and caveats](#notes-constraints-and-caveats) - - [Risks and mitigations](#risks-and-mitigations) -- [Design Details](#design-details) - - [System architecture](#system-architecture) - - [Resource model and ownership](#resource-model-and-ownership) - - [Endpoint declaration](#endpoint-declaration) - - [Consumer access and frontend translation](#consumer-access-and-frontend-translation) - - [Validation and compatibility](#validation-and-compatibility) - - [Reconciliation and selection](#reconciliation-and-selection) - - [Status and lifecycle](#status-and-lifecycle) - - [Data plane](#data-plane) - - [Internal DNS integration](#internal-dns-integration) -- [Production readiness review questionnaire](#production-readiness-review-questionnaire) -- [Implementation history](#implementation-history) -- [Drawbacks](#drawbacks) -- [Alternatives](#alternatives) -- [Infrastructure needed](#infrastructure-needed) - -## Summary - -Private Service Connect gives a consumer VPC private access to a published -service in a producer VPC. Consumers use a stable private endpoint while the -platform selects an authorized, eligible producer. A shared service can serve -many VPCs without a separate deployment for each consumer. - -## Motivation - -Platform services need private connectivity from isolated consumer networks. -Connecting entire VPCs exposes more of the producer network than a service -requires. Private Service Connect grants access to a specific service tuple and -keeps network identity trustworthy when consumers use overlapping addresses. - -The [Internal DNS overview](https://github.com/datum-cloud/enhancements/blob/docs/internal-dns-product-proposal/architecture/deliver/dns/internal-dns/README.md) -describes the first integration: the same resolver address in each VPC reaches -that network's isolated DNS context through a shared DNS fleet. - -### Goals - -- Give workloads private access to authorized services through their existing - network configuration. -- Share producer capacity across consumer VPCs with overlapping addresses. -- Preserve consumer identity through local delivery, remote delivery, and replies. -- Withdraw access on resource deletion and stop selecting unhealthy producers. - -### Non-goals - -- Connecting entire producer and consumer networks. -- Discovering service backends or performing application health checks in Galactic. -- Defining customer-published services or their management experience. -- Defining DNS contexts, record publication, or resolver cache isolation. - -## Proposal - -A service owner publishes an endpoint and maintains its availability. Trusted -networking integration authorizes consumer attachments and assigns a private -frontend. Galactic delivers only the permitted address, protocol, and port to an -eligible producer. Service health and network programming are separate readiness -requirements. - -### User stories - -- A workload uses the network's inherited DNS resolver without selecting a - resolver deployment or configuring a service-specific route. -- Two VPCs use the same frontend address and receive their own service context. -- A service owner adds ready producers to shared capacity and withdraws unhealthy - producers without changing the consumer-facing address. - -### Notes, constraints, and caveats - -Endpoint addresses must be reachable and accepted by the producer listener. -Publishing an endpoint does not configure the producer address. The initial -frontend design translates within one address family; cross-family translation -requires a separate design. Addresses in the manifests are illustrative. - -A new consumer creates endpoint and authorization data, not a producer -workload. Producer reselection does not promise continuity for established -connections. Regional placement and fallback are explicit policies. - -### Risks and mitigations - -- Incorrect access: protect integration credentials and selection labels, and - pin authorization to the live consumer VPC identity. -- Stale programming: reconcile current resource lifetimes after restart and - define a bounded revocation policy before rollout. -- Endpoint advertised too early: require service health and verified consumer - and producer path programming before publishing workload configuration. - -## Design Details - -### System architecture - -Networking integration translates project intent into location-specific network -state. Galactic programs each node from its edge API. Traffic uses the applied -data plane without querying project APIs or Karmada per packet. - -```mermaid -flowchart TB - P["Producer project
Service and network intent"] - C["Consumer project
Network and access intent"] - I[Trusted networking integration] - K[Karmada network projections] - E["Edge API
VPCs, attachments, endpoints, policies"] - G[Galactic node controllers] - P --> I - C --> I - I -->|Location-specific desired state| K - K --> E - E -->|Local identities and service policy| G -``` - -Project APIs own intent. Karmada owns placement and projected desired state. -The edge owns local VPC and attachment identities. Networking controllers return -selected edge observations through federation and project consumer status. -The integration resolves live edge identities when creating service policies; -project and propagated object UIDs are separate lifetimes. - -The networking APIs live in the -[network repository](https://github.com/datum-cloud/network/blob/main/api/v1alpha1/serviceroute_types.go). -Galactic owns route compilation and packet handling. The -[private-service routing reference](../../../router/private-service-routes.md) -documents packet handling for this contract. This enhancement defines the -resource design; the network repository holds its schemas, and Galactic holds -its controller and data-plane implementation. - -### Resource model and ownership - -The design separates service publication from consumer authorization: - -- `ServiceEndpoint` describes what a producer offers: one destination address, - protocol, and port, the attachments that can serve it, and the delivery policy. - Declaring an endpoint grants no consumer access. -- `ServiceRoutePolicy` describes who can use that endpoint: selected consumer - attachments, their VPC lifetime, permitted traffic, and an optional frontend. - The policy references the service contract rather than duplicating producer - selection or listener configuration. - -This separation lets service owners change eligible producers while networking -integration changes consumer access independently. Several policies in one -namespace can reference the same endpoint. Different consumer namespaces receive -local descriptors that select shared producer attachments; the descriptors are -control-plane data, not service deployments. - -```mermaid -flowchart LR - subgraph C[Consumer edge namespace] - R[ServiceRoutePolicy] - E[ServiceEndpoint] - A[Consumer attachments] - R -->|serviceRef| E - R -->|Authorizes selected consumers| A - end - subgraph S[Service edge namespace] - P[Eligible producer attachments] - end - E -->|Selects producers| P -``` - -Both resources live in the edge API. `serviceRef` resolves in the policy's -namespace. Producer references carry their attachment namespace; producer -selectors can match attachments in the service namespace. Cross-namespace -producer selection is a privileged platform operation, not a tenant permission. - -Project APIs and federation hold intent and placement. Trusted integration -projects endpoint descriptors, resolves edge VPC names and API-assigned UIDs, -and creates consumer policies. A project UID is not an edge VPC UID. The service -owner supplies the exact service tuple and eligible producers. Only platform -controllers can write these resources or the labels that select their attachments. - -The complete API design includes `consumerVPCRef` and `frontend` on -`ServiceRoutePolicy`. Those fields extend the direct-delivery implementation; -they are present in the local prototype and remain proposed for the released -schema. This document defines both resources, including their current fields -and proposed extensions. - -### Endpoint declaration - -An endpoint names one directly delivered service tuple. Keeping one transport -per endpoint makes publication, authorization, and failure reporting explicit. -DNS uses separate UDP and TCP endpoints. `serviceClass` identifies the capability -for integration and operations; it is not an authorization role or backend lookup. - -The owner must make the endpoint address reachable through every selected -producer attachment and accepted by its listener. The address can carry a -service-defined context, as Internal DNS does. Galactic delivers that address -without choosing an application backend. Replica selection chooses the network -attachment that receives the tuple. - -The following descriptor lives in `consumer-a`. It selects shared DNS producers -through platform-managed labels, including producers in the DNS service's edge -namespace. Each eligible producer must serve this destination and DNS context. - -```yaml -apiVersion: galactic.datumapis.com/v1alpha1 -kind: ServiceEndpoint -metadata: - name: context-a-dns-udp - # Local descriptor beside consumer policies; producers can be elsewhere. - namespace: consumer-a -spec: - # Identifies the capability for integration; does not grant access. - serviceClass: internal-dns - # Exact service-side destination after frontend translation. - # The service owner makes it routable and accepted by each producer listener. - address: "fd70:100::10" - # One service port, from 1 through 65535. - port: 53 - # One transport per endpoint; use a separate descriptor for TCP. - # Supported protocol values are lowercase udp and tcp. - protocol: udp - # PreferNodeLocal selects a local producer, or a ready remote producer. - # NodeLocal requires a producer on the consumer's node. - deliveryMode: PreferNodeLocal - # Optional placement boundary; empty imposes no region restriction. - # Trusted placement and selectors establish actual location membership. - region: us-central-1 - # Select shared replicas using protected, platform-managed labels. - # Every selected producer must serve this tuple and service context. - # Alternatively, use attachmentRef with namespace and name for one producer. - # Exactly one of attachmentSelector or attachmentRef must be set. - attachmentSelector: - matchLabels: - networking.datumapis.com/service: internal-dns - topology.kubernetes.io/region: us-central-1 -``` - -The address is not a Kubernetes Service frontend or an address from which -Galactic discovers backends. An endpoint has one transport tuple; DNS requires -separate UDP and TCP descriptors. Create `context-a-dns-tcp` with the same -address, selector, placement, and port, and `protocol: tcp`. - -### Consumer access and frontend translation - -A policy applies the endpoint contract to a consumer set. It can authorize many -attachments in one VPC. The proposed lifetime reference prevents a recreated -VPC with the same name from inheriting access. The frontend belongs to this -consumer policy so different VPCs can use the same address for different service -destinations without changing the producer contract. - -The policy references the endpoint in its own namespace. `consumerVPCRef` pins -the VPC named `application-vpc` in `consumer-a` to its live edge UID. The selector -narrows eligible attachments; it does not replace the VPC identity check. - -```yaml -apiVersion: galactic.datumapis.com/v1alpha1 -kind: ServiceRoutePolicy -metadata: - name: application-vpc-dns-udp - # Policy, referenced endpoint, and consumer VPC share this edge namespace. - namespace: consumer-a -spec: - # References the service contract in this policy's namespace. - serviceRef: - name: context-a-dns-udp - # Proposed: pins authorization to one live edge VPC lifetime. - consumerVPCRef: - # Resolved against the VPC in the policy namespace. - name: application-vpc - # API-assigned edge VPC UID; recreation requires new authorization. - # A project or propagated source UID cannot replace this identity. - uid: "22222222-2222-4222-8222-222222222222" - # Select consumers through protected labels. - # Galactic also verifies membership in the live, pinned VPC. - attachmentSelector: - matchLabels: - networking.datumapis.com/vpc-uid: "22222222-2222-4222-8222-222222222222" - # Allowed tuples must match the endpoint's declared protocol and port. - # Omit this list to use the endpoint's tuple. - protocolPorts: - - protocol: udp - port: 53 - # Optional consumer placement boundary; must agree with a scoped endpoint. - # This field does not authorize cross-region fallback. - region: us-central-1 - # Proposed: consumer-facing address translated to the endpoint destination. - frontend: - # Same address family as the endpoint; restored as the reply source. - # Different VPCs can use this address with different service destinations. - address: "fd53::53" -``` - -Create a matching TCP policy referencing `context-a-dns-tcp` and permitting -`tcp/53`, with the same VPC reference, selector, region, and frontend. UDP and TCP -must satisfy the same authorization and readiness requirements. - -A second VPC uses the same `fd53::53` frontend. Its descriptors and policies live -in its own namespace, pin its own VPC UID, and use another service destination, -such as `fd70:100::20`. The producer deployment remains shared. DNS maps those -destinations to different contexts; Galactic does not interpret that mapping. - -### Validation and compatibility - -The proposed frontend contract requires a complete `consumerVPCRef` with name -and UID. Galactic must resolve that live VPC and reject missing or mismatched -identities. Each selected consumer must belong to that VPC and have the expected -programmed network identity. Platform-managed labels alone cannot grant access. - -Admission and reconciliation must enforce: - -- Exactly one endpoint attachment selection method. -- Valid frontend and endpoint IP addresses in the same family. -- Ports from 1 through 65535 and supported transport values. -- A policy's allowed tuples within its endpoint's declared tuple. -- Consistent placement and current producer and consumer identities. -- No contradictory destination mappings for the same consumer attachment, - frontend address, protocol, and port. Policy order must not decide access. - -Conflict detection across policies still requires implementation review. Endpoint -and policy regions must agree when both are set. Trusted placement and selectors -establish location membership; a region string alone is not identity proof. - -Omitting `frontend` preserves direct delivery to the endpoint address. Existing -policies without the new fields retain their existing contract; new translated -access requires the lifetime pin. Frontend translation remains disabled by -default until API and data-plane compatibility are qualified. - -### Reconciliation and selection - -Each Galactic node watches policies, endpoint descriptors, VPCs, and attachments -in the edge API. It derives current desired programming through these steps: - -1. Resolve `serviceRef`, validate the service tuple and placement, and resolve - the pinned consumer VPC name and UID. -2. Select producer attachments with current-generation `Ready` and `Programmed` - status, a node, allocated network identities, and a host interface. For a - `Single` endpoint, service owners must ensure selected producers are also - healthy for the declared tuple; a `Spread` endpoint's producers are probed - by their nodes. -3. Select consumer attachments through protected labels and verify their live - VPC membership and programmed attachment identity. -4. Choose producers for each consumer. A `Single` endpoint gets one, chosen by - a deterministic attachment ordering, preferring a local producer. A `Spread` - endpoint gets every producer on the consumer's node as one set: new flows go - to the ones its health check has not found `Unhealthy`, each TCP connection - stays with its first producer, and each UDP datagram picks its own. In both, - `NodeLocal` leaves the consumer without a path if no local producer is - available, and `PreferNodeLocal` permits one ready remote producer. -5. Program this node's consumer and producer paths. Remote paths require both - sides' trusted attachment identities, matching service grants, and return - routing. Grants bind the policy, endpoint, and attachment lifetimes to the - permitted tuple and frontend. -6. Remove obsolete programming when selection, references, or lifetimes change. - Restart reconciliation rebuilds current desired state and sweeps stale state. - -No eligible producer means no usable path; it does not make otherwise valid -policy intent invalid. A missing endpoint or mismatched VPC identity invalidates -the contract and requires stale access to be removed. An unresolved remote path -prevents that node from serving even if the shared policy remains accepted. - -Service owners of a `Single` endpoint withdraw unhealthy producers through the -endpoint's selection contract. Galactic's attachment readiness checks establish -network eligibility; they do not substitute for service health. A `Spread` -endpoint's producers are probed over TCP by their own node, which publishes -each decision in the endpoint's `status.producers`; see -[Private service routes](../../../router/private-service-routes.md#several-producers-on-one-node). - -### Status and lifecycle - -`ServiceRoutePolicy.status.observedGeneration` identifies the spec generation -that its conditions describe. `Accepted` reports valid configuration; it does -not prove that every required node has programmed the path. `ServiceEndpoint` -does not provide a listener-health status contract. - -```mermaid -flowchart TB - A[Authorization is current] --> R[Private endpoint ready] - N[Consumer and producer paths programmed] --> R - S[Service address and listener healthy] --> R - R --> W[Publish endpoint configuration to workloads] -``` - -The release needs node-level programming acknowledgments and a service-owned -health signal before integration advertises the frontend. Their API shape -remains a design decision; this proposal does not add a `Programmed` or `Ready` -condition that the existing controllers cannot verify. - -Changing an endpoint tuple or producer selection re-evaluates its referencing -policies. Explicit `protocolPorts` must still match; policies that omit them -follow the endpoint's declared tuple. Deleting an endpoint leaves references -unusable and removes their programming. Deleting a policy removes its access -without deleting the shared producer service or consumer attachments. - -Service owners withdraw unhealthy producers. Networking integration deletes -access when the consumer or service is deleted. Galactic removes obsolete -programming and reconciles current lifetimes after restart. Recreated VPCs and -endpoints must not inherit previous grants. The current route policy has no -authorization policy. Persistent access requires explicit revocation; bounded -access requires a renewed deadline. - -### Data plane - -Galactic classifies traffic by the trusted consumer attachment and endpoint -tuple. The proposed frontend translation changes the destination to the -authorized service address and restores the frontend on replies. Consumers use -their ordinary gateway; Galactic does not install a service-specific guest route. - -```mermaid -sequenceDiagram - participant W as Workload - participant C as Consumer node - participant P as Producer node - participant S as Service - W->>C: Packet to private frontend - Note over C: Authorize tuple
Translate target - alt Producer is on the same node - C->>S: Deliver through producer attachment - S-->>C: Reply - else Producer is on another node - C->>P: Authorized SRv6 service path - P->>S: Deliver through producer attachment - S-->>P: Reply - P-->>C: SRv6 return path - end - C-->>W: Restore frontend address and reply -``` - -`NodeLocal` requires a producer on the consumer's node. `PreferNodeLocal` uses -a local producer when available and otherwise selects a ready remote producer. -A `Single` endpoint's selection is deterministic, and it rejects multiple ready -producers in the same node and VPC because its one-target route cannot -distinguish them. A `Spread` endpoint routes to a set of up to 16 producers on -the consumer's node instead. - -Overlapping consumer addresses remain scoped to their attachments. Remote -delivery requires matching platform-programmed service grants. Tenant-supplied -addresses or packet metadata cannot grant access. The design relies on trusted -attachment state and protected fabric delivery. - -The current return path rejects concurrent flows from different consumers that -produce the same reply tuple on one producer attachment. Internal DNS separates -service-side destinations by context. General shared endpoints need equivalent -disambiguation for overlapping consumers that use identical tuples. - -This path is separate from Galactic's gateway `ServiceVIPBinding` mechanism. -Publishing a private endpoint does not create gateway load-balancer state. - -### Internal DNS integration - -Internal DNS uses a well-known frontend address in each consumer VPC. Its -networking integration maps that frontend to an authorized service-side -destination for the network's DNS context. Galactic enforces the private path; -DNS interprets the destination and isolates zones and answers. - -DNS contexts, record publication, health-aware discovery, and resolver access -belong to the [DNS component design](https://github.com/datum-cloud/dns-operator/blob/docs/internal-dns-architecture/docs/architecture/internal-dns/README.md). -The generic private-service path does not interpret DNS resources. - -## Production readiness review questionnaire - -The enhancement remains provisional. Complete and approve the release targets -and outstanding contracts before changing it to implementable. - -### Feature enablement and rollback - -Keep frontend translation disabled by default. Enable it only with compatible -API schemas and integration controllers. Disabling it can interrupt consumers -that depend on the frontend; validate cleanup and recovery before rollout. - -### Rollout, upgrade, and rollback planning - -Qualify mixed controller versions, node restart, policy replay, deletion, and -upgrade followed by rollback and reenablement. Avoid advertising endpoints while -required nodes lack the configuration. No existing API removal is proposed. - -### Monitoring requirements - -Observe acceptance, node programming, producer health, selected traffic, -translation failures, and revocation lag separately. Define availability, -latency, and revocation targets. Consumer status must distinguish valid intent -from a usable endpoint; its readiness projection remains to be designed. - -### Dependencies - -Networking integration supplies edge intent and authorization. VPC and -attachment controllers and Galactic supply network identity and packet paths. -Remote delivery requires the protected fabric and service grants. Service owners -supply address reachability, listener configuration, and health eligibility. - -### Scalability - -Endpoint and policy counts grow with consumer destinations and transports; -producer workload counts grow with shared capacity. Bound route and reverse-flow -maps, API reconciliation cost, configuration churn, and connection state before -release. Exhaustion must fail closed and produce an observable failure. - -### Troubleshooting - -An API outage can delay updates and revocation while nodes retain applied state. -Define retention and revocation budgets. Diagnose invalid policies, missing VPCs, -unready producers, path-programming failures, and reply collisions separately. -Verify the declared service destination and return path before investigating the -application protocol. - -## Implementation history - -Initial proposal: [Galactic PR #798](https://github.com/datum-cloud/galactic/pull/798). -Local kernel tests cover local and remote translation and authorization. Live -Internal DNS queries validate the local path. Normal router/CNI lifecycle, -independent edge APIs, remote live DNS traffic, scale, and regional failures -remain unqualified. - -## Drawbacks +This document moved to [private-service-connect](../../../designs/private-service-connect.md). Update bookmarks to the maintained page. + + + +See [Summary](../../../designs/private-service-connect.md#summary). + + + +See [Motivation](../../../designs/private-service-connect.md#motivation). + + + +See [Goals](../../../designs/private-service-connect.md#goals). + + + +See [Non-goals](../../../designs/private-service-connect.md#non-goals). + + + +See [Proposal](../../../designs/private-service-connect.md#proposal). + + + +See [User stories](../../../designs/private-service-connect.md#user-stories). + + + +See [Notes, constraints, and caveats](../../../designs/private-service-connect.md#notes-constraints-and-caveats). + + + +See [Risks and mitigations](../../../designs/private-service-connect.md#risks-and-mitigations). + + + +See [Design Details](../../../designs/private-service-connect.md#design-details). + + + +See [System architecture](../../../designs/private-service-connect.md#system-architecture). + + + +See [Resource model and ownership](../../../designs/private-service-connect.md#resource-model-and-ownership). + + + +See [Endpoint declaration](../../../designs/private-service-connect.md#endpoint-declaration). + + + +See [Consumer access and frontend translation](../../../designs/private-service-connect.md#consumer-access-and-frontend-translation). + + + +See [Validation and compatibility](../../../designs/private-service-connect.md#validation-and-compatibility). + + + +See [Reconciliation and selection](../../../designs/private-service-connect.md#reconciliation-and-selection). + + + +See [Status and lifecycle](../../../designs/private-service-connect.md#status-and-lifecycle). + + + +See [Data plane](../../../designs/private-service-connect.md#data-plane). + + + +See [Internal DNS integration](../../../designs/private-service-connect.md#internal-dns-integration). + + + +See [Production readiness review questionnaire](../../../designs/private-service-connect.md#production-readiness-review-questionnaire). + + + +See [Feature enablement and rollback](../../../designs/private-service-connect.md#feature-enablement-and-rollback). + + + +See [Rollout, upgrade, and rollback planning](../../../designs/private-service-connect.md#rollout-upgrade-and-rollback-planning). + + + +See [Monitoring requirements](../../../designs/private-service-connect.md#monitoring-requirements). + + + +See [Dependencies](../../../designs/private-service-connect.md#dependencies). + + + +See [Scalability](../../../designs/private-service-connect.md#scalability). + + + +See [Troubleshooting](../../../designs/private-service-connect.md#troubleshooting). + + + +See [Implementation history](../../../designs/private-service-connect.md#implementation-history). + + -Distinct service destinations and per-consumer policies add address allocation -and lifecycle work. Stateful reply handling consumes node capacity and limits -connection continuity during producer changes. +See [Drawbacks](../../../designs/private-service-connect.md#drawbacks). -## Alternatives + -VPC peering grants broader connectivity and requires additional routing policy. -Per-consumer service deployments increase operating cost. A single shared -service destination needs another trustworthy identity mechanism and an -unambiguous return path for overlapping consumers. +See [Alternatives](../../../designs/private-service-connect.md#alternatives). -## Infrastructure needed + -Release the network API extensions and compatible Galactic controllers. Provide -shared producer attachments, service address allocation and reclamation, -protected integration permissions, endpoint readiness reporting, and staging -coverage for local and remote traffic. +See [Infrastructure needed](../../../designs/private-service-connect.md#infrastructure-needed). diff --git a/docs/enhancements/proposals/masque-gateway-design.md b/docs/enhancements/proposals/masque-gateway-design.md index 0a67053bf..38c0e2af2 100644 --- a/docs/enhancements/proposals/masque-gateway-design.md +++ b/docs/enhancements/proposals/masque-gateway-design.md @@ -1,429 +1,159 @@ # MASQUE Gateway Architecture -## Executive Summary - -This document describes the MASQUE Gateway, an ingress component that bridges external clients to the SRv6-based Galactic VPC fabric. The gateway enables secure, NAT-traversing connectivity from diverse clients into VPC workloads using modern protocols. - -### Design Philosophy - -**Bet on the future, bridge to the present.** - -- **MASQUE as the protocol standard** - IETF-standard tunneling (RFC 9484 CONNECT-IP) -- **Iroh for connectivity** - NAT traversal, hole punching, relay infrastructure -- **SRv6 as the underlay** - Internal VPC fabric routing -- **Extensible connectors** - Support multiple protocols through a common interface - -### Key Insight: Iroh + MASQUE Convergence - -Rather than choosing between Iroh and MASQUE, the architecture leverages both: - -- **Iroh provides connectivity** - NAT traversal, hole punching, public key identity, relay infrastructure -- **MASQUE provides the protocol** - IETF standard, browser support, firewall traversal - -This means Iroh relays can evolve to speak MASQUE, giving us the best of both worlds. - ---- - -## Strategic Direction - -### Protocol Convergence - -``` -┌─────────────────────────────────────────────────────────────────────────┐ -│ Current State │ -│ │ -│ Iroh (custom protocol) MASQUE (IETF standard) │ -│ ├─ Great NAT traversal ├─ HTTP/3 based │ -│ ├─ Hole punching ├─ Browser support (WebTransport) │ -│ ├─ Public key identity ├─ Firewall friendly (port 443) │ -│ ├─ Relay infrastructure ├─ Apple/Cloudflare proven │ -│ └─ Custom QUIC protocol └─ IP tunneling (CONNECT-IP) │ -│ │ -├─────────────────────────────────────────────────────────────────────────┤ -│ Future State │ -│ │ -│ ┌─────────────────────────────────────────────────────────────────┐ │ -│ │ Iroh + MASQUE │ │ -│ │ │ │ -│ │ ┌────────────────────────────────────────────────────────────┐ │ │ -│ │ │ MASQUE Protocol Layer (IETF standard) │ │ │ -│ │ │ - CONNECT-IP for VPC ingress │ │ │ -│ │ │ - CONNECT-UDP for relay │ │ │ -│ │ │ - CONNECT-TCP for HTTP proxying │ │ │ -│ │ └────────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ │ -│ │ ┌────────────────────────────────────────────────────────────┐ │ │ -│ │ │ Iroh Connectivity Layer │ │ │ -│ │ │ - NAT traversal / hole punching │ │ │ -│ │ │ - Relay fallback (now speaking MASQUE) │ │ │ -│ │ │ - Public key identity │ │ │ -│ │ │ - Connection migration │ │ │ -│ │ └────────────────────────────────────────────────────────────┘ │ │ -│ └─────────────────────────────────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────────┘ -``` - -### Why This Approach? - -| Question | Answer | -|----------|--------| -| Why keep Iroh? | Best-in-class NAT traversal, P2P hole punching, you're already running relays | -| Why add MASQUE? | IETF standard, browser support, firewall traversal, IP-level tunneling | -| Why not just MASQUE? | Lose Iroh's P2P capabilities and relay infrastructure | -| Why not just Iroh? | Custom protocol, no browser support, HTTP-level only | - -### Migration Path - -1. **Today**: Iroh native protocol for HTTP proxying (dev tunnels) -2. **Next**: Add MASQUE CONNECT-IP capability for VPC ingress -3. **Future**: Iroh relays speak MASQUE, unifying the protocol stack - ---- - -## System Architecture - -### High-Level View - -``` -┌─────────────────────────────────────────────────────────────────────────┐ -│ External Clients │ -│ │ -│ [Browser] [Mobile App] [CLI/Desktop] [IoT Device] │ -│ WebTransport MASQUE Iroh/MASQUE Iroh │ -│ │ -└───────────────────────────────┬─────────────────────────────────────────┘ - │ - ┌───────────▼───────────┐ - │ Iroh Relays │ - │ (MASQUE-speaking) │ - │ │ - │ - NAT traversal │ - │ - CONNECT-UDP relay │ - │ - Global distribution│ - └───────────┬───────────┘ - │ - ┌───────────▼───────────┐ - │ MASQUE Gateway │ - │ │ - │ - CONNECT-IP termination - │ - Session management │ - │ - SRv6 bridge │ - └───────────┬───────────┘ - │ - ┌───────────▼───────────┐ - │ VPC Fabric │ - │ (SRv6) │ - │ │ - │ [Workloads] │ - └───────────────────────┘ -``` - -### Components - -| Component | Purpose | -|-----------|---------| -| **Iroh Relays** | NAT traversal, MASQUE CONNECT-UDP relay, global presence | -| **MASQUE Gateway** | CONNECT-IP termination, authentication, SRv6 bridging | -| **SRv6 Bridge** | Translate between client IP packets and VPC fabric | -| **Session Manager** | Track connections, enforce policies, allocate addresses | - ---- - -## Protocol Stack - -### MASQUE Protocol Family - -| Protocol | RFC | Purpose | -|----------|-----|---------| -| CONNECT-IP | RFC 9484 | Full IP tunnel (VPN mode) - primary for VPC ingress | -| CONNECT-UDP | RFC 9298 | UDP proxying - used for relay | -| CONNECT-TCP | HTTP CONNECT | TCP proxying - HTTP-level access | - -### Connection Flow - -``` -Client Relay Gateway VPC - │ │ │ │ - │──Iroh hole punch────────►│ │ │ - │ (direct if possible) │ │ │ - │ │ │ │ - │──MASQUE CONNECT-UDP─────►│ (if relay needed) │ │ - │ │ │ │ - │──────────────────────────┼──MASQUE CONNECT-IP──────►│ │ - │ │ │ │ - │◄─────────────────────────┼──ADDRESS_ASSIGN──────────│ │ - │◄─────────────────────────┼──ROUTE_ADVERTISEMENT─────│ │ - │ │ │ │ - │══════════════════════════╪══IP Packets══════════════╪═════SRv6═══════════►│ - │ │ │ │ -``` - ---- - -## Resource Model - -Aligned with the [Datum Connectors proposal](../../../enhancements/enhancements/networking/connectors/initial-proposal/README.md). - -### Resource Relationships - -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ Control Plane │ -│ │ -│ ┌─────────────┐ ┌─────────────────────┐ ┌─────────────┐ │ -│ │ Connector │─────►│ ConnectorAttachment │◄─────│ VPC │ │ -│ │ (client) │ │ (binding) │ │ (network) │ │ -│ └─────────────┘ └─────────────────────┘ └─────────────┘ │ -│ │ │ │ │ -│ ▼ ▼ ▼ │ -│ ┌─────────────┐ ┌─────────────────┐ ┌─────────────┐ │ -│ │ Connector │ │ VPCIngressPoint │ │VPCAccessPol │ │ -│ │Advertisement│ │ (gateway config)│ │ icy │ │ -│ └─────────────┘ └─────────────────┘ └─────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ -``` - -### Key Resources - -| Resource | From | Purpose | -|----------|------|---------| -| `Connector` | Connectors proposal | Represents client device, defines capabilities | -| `ConnectorAdvertisement` | Connectors proposal | Networks reachable through connector (outbound) | -| `ConnectorAttachment` | This design | Binds connector to VPC (inbound) | -| `VPCIngressPoint` | This design | Gateway configuration per VPC | -| `VPCAccessPolicy` | This design | Fine-grained authorization rules | - -### Example: Connector with MASQUE Capability - -```yaml -apiVersion: networking.datumapis.com/v1alpha1 -kind: Connector -metadata: - name: developer-laptop -spec: - connectorClassName: datum-connect - capabilities: - - type: MASQUE - enabled: true - - type: CONNECT-IP - enabled: true - - type: CONNECT-UDP - enabled: true -status: - connectionDetails: - type: PublicKey - publicKey: - id: 2ovpybgj3snjmchns44pfn6dbwmdiu4ogfd66xyu72ghexllv6hq - homeRelay: https://relay.datum.net -``` - -### Example: Attaching Connector to VPC - -```yaml -apiVersion: networking.datumapis.com/v1alpha1 -kind: ConnectorAttachment -metadata: - name: developer-to-vpc -spec: - connectorRef: - name: developer-laptop - vpcRef: - name: production-vpc - ipAllocation: - mode: Dynamic - allowedRoutes: - - 10.0.0.0/16 -status: - assignedIP: 10.0.100.50 - phase: Connected -``` - ---- - -## SRv6 Integration - -### Bridge Operation - -The gateway translates between client IP packets and SRv6-encapsulated packets: - -``` -Client IP Packet SRv6 Packet (to VPC) -┌─────────────────┐ ┌─────────────────────────┐ -│ src: 10.0.100.50│ SRv6 │ IPv6: fc00::gateway │ -│ dst: 10.0.2.100 │ ──────────► │ → fc00::vpc:node │ -│ [payload] │ Bridge │ SRH: [fc00::vpc:node] │ -└─────────────────┘ │ [original IP packet] │ - └─────────────────────────┘ -``` - -### Bridge Modes - -| Mode | Performance | Use Case | -|------|-------------|----------| -| Kernel (VRF + seg6) | Good | Default, universal compatibility | -| eBPF/XDP | High | Production gateways | -| AF_XDP | Highest | Maximum throughput requirements | - ---- - -## Current Iroh Architecture Integration - -### Today's Architecture (datum-connect) - -``` - ┌─────────────────────────┐ - │ Iroh Relay │ - │ (iroh native protocol) │ - └───────────┬─────────────┘ - │ -┌──────────────┐ │ ┌──────────────┐ -│ datum-connect│◄═══════════════╪═══════════════►│ Envoy │ -│ (desktop) │ Iroh QUIC │ │ Gateway │ -│ │ │ │ │ -│ ListenNode │ │ │ Iroh Gateway │ -│ │ │ │ (sidecar) │ -└──────────────┘ │ └──────────────┘ - │ - HTTP Proxying - (absolute-form requests) -``` - -### Evolution to MASQUE - -``` - ┌─────────────────────────┐ - │ Iroh Relay │ - │ (MASQUE CONNECT-UDP) │ ◄── Protocol change - └───────────┬─────────────┘ - │ -┌──────────────┐ │ ┌──────────────┐ -│ datum-connect│◄═══════════════╪═══════════════►│ MASQUE │ -│ │ MASQUE │ │ Gateway │ -│ │ CONNECT-IP │ │ │ -│ + VPC attach │ │ │ + SRv6 bridge│ -└──────────────┘ │ └──────────────┘ - │ - IP Tunneling + HTTP Proxying -``` - -### What Changes - -| Component | Current | Future | -|-----------|---------|--------| -| Relay protocol | Iroh native | MASQUE CONNECT-UDP | -| Application protocol | Iroh HTTP-connect | MASQUE CONNECT-IP/TCP | -| Gateway | Iroh Gateway (HTTP proxy) | MASQUE Gateway (IP tunnel + HTTP) | -| Client | datum-connect (Iroh only) | datum-connect (MASQUE capability) | -| VPC integration | None | ConnectorAttachment + SRv6 | - -### What Stays - -| Capability | Preserved | -|------------|-----------| -| NAT traversal | Yes - Iroh's hole punching | -| Relay infrastructure | Yes - your relays, new protocol | -| Public key identity | Yes - connection details unchanged | -| P2P direct connections | Yes - hole punch when possible | -| Control plane integration | Yes - same Connector CRD | - ---- - -## Client SDK (datum-connect) - -### Capabilities - -The datum-connect client gains MASQUE capability: - -```yaml -# Connector status shows available capabilities -status: - capabilities: - - type: MASQUE - conditions: - - type: Ready - status: "True" - - type: CONNECT-IP # VPC ingress - conditions: - - type: Ready - status: "True" - - type: CONNECT-TCP # HTTP proxying (current) - conditions: - - type: Ready - status: "True" -``` - -### CLI Usage - -```bash -# Current: HTTP proxying (unchanged) -datum-connect tunnel --local 8080 --name my-tunnel - -# New: VPC attachment -datum-connect attach --vpc production-vpc - -# Show status -datum-connect status -# Connector: developer-laptop (Ready) -# Protocol: MASQUE -# VPC Attachments: -# - production-vpc: 10.0.100.50 (Connected) -# HTTP Tunnels: -# - my-tunnel: localhost:8080 → https://my-tunnel.example.com -``` - ---- - -## Implementation Phases - -### Phase 1: Foundation - -- MASQUE CONNECT-IP listener in gateway -- `ConnectorAttachment` and `VPCIngressPoint` CRDs -- Kernel-mode SRv6 bridge -- MASQUE capability in datum-connect - -### Phase 2: Relay Evolution +This document moved to [masque-gateway](../../designs/masque-gateway.md). Update bookmarks to the maintained page. -- Iroh relays speak MASQUE CONNECT-UDP -- Unified protocol stack -- Browser connectivity via WebTransport + -### Phase 3: Production +See [Executive Summary](../../designs/masque-gateway.md#executive-summary). -- eBPF/XDP bridge acceleration -- Multi-gateway HA -- Mobile SDKs + ---- +See [Design Philosophy](../../designs/masque-gateway.md#design-philosophy). -## Open Questions + -1. **Iroh upstream changes**: Does Iroh need modifications to support MASQUE, or can we layer it? +See [Key Insight: Iroh + MASQUE Convergence](../../designs/masque-gateway.md#key-insight-iroh--masque-convergence). -2. **Relay protocol migration**: How do we migrate existing relays from Iroh-native to MASQUE? + -3. **Browser path**: WebTransport speaks HTTP/3 - is that sufficient, or do we need full MASQUE in browsers? +See [Strategic Direction](../../designs/masque-gateway.md#strategic-direction). -4. **Gateway base**: Build on quic-go (lightweight) or Envoy (battle-tested)? + ---- +See [Protocol Convergence](../../designs/masque-gateway.md#protocol-convergence). -## References + -### Internal -- [Datum Connectors Proposal](../../../enhancements/enhancements/networking/connectors/initial-proposal/README.md) -- [Galactic VPC v2 Architecture](./v2-design.md) +See [Why This Approach?](../../designs/masque-gateway.md#why-this-approach). -### MASQUE -- [RFC 9484: CONNECT-IP](https://datatracker.ietf.org/doc/rfc9484/) -- [RFC 9298: CONNECT-UDP](https://datatracker.ietf.org/doc/rfc9298/) -- [Cloudflare: Zero Trust WARP with MASQUE](https://blog.cloudflare.com/zero-trust-warp-with-a-masque/) + -### Connectivity -- [Iroh Documentation](https://www.iroh.computer/docs) -- [Datum Connect](https://github.com/datum-cloud/datum-connect) +See [Migration Path](../../designs/masque-gateway.md#migration-path). -### SRv6 -- [RFC 8986: SRv6 Network Programming](https://datatracker.ietf.org/doc/html/rfc8986) + + +See [System Architecture](../../designs/masque-gateway.md#system-architecture). + + + +See [High-Level View](../../designs/masque-gateway.md#high-level-view). + + + +See [Components](../../designs/masque-gateway.md#components). + + + +See [Protocol Stack](../../designs/masque-gateway.md#protocol-stack). + + + +See [MASQUE Protocol Family](../../designs/masque-gateway.md#masque-protocol-family). + + + +See [Connection Flow](../../designs/masque-gateway.md#connection-flow). + + + +See [Resource Model](../../designs/masque-gateway.md#resource-model). + + + +See [Resource Relationships](../../designs/masque-gateway.md#resource-relationships). + + + +See [Key Resources](../../designs/masque-gateway.md#key-resources). + + + +See [Example: Connector with MASQUE Capability](../../designs/masque-gateway.md#example-connector-with-masque-capability). + + + +See [Example: Attaching Connector to VPC](../../designs/masque-gateway.md#example-attaching-connector-to-vpc). + + + +See [SRv6 Integration](../../designs/masque-gateway.md#srv6-integration). + + + +See [Bridge Operation](../../designs/masque-gateway.md#bridge-operation). + + + +See [Bridge Modes](../../designs/masque-gateway.md#bridge-modes). + + + +See [Current Iroh Architecture Integration](../../designs/masque-gateway.md#current-iroh-architecture-integration). + + + +See [Today's Architecture (datum-connect)](../../designs/masque-gateway.md#todays-architecture-datum-connect). + + + +See [Evolution to MASQUE](../../designs/masque-gateway.md#evolution-to-masque). + + + +See [What Changes](../../designs/masque-gateway.md#what-changes). + + + +See [What Stays](../../designs/masque-gateway.md#what-stays). + + + +See [Client SDK (datum-connect)](../../designs/masque-gateway.md#client-sdk-datum-connect). + + + +See [Capabilities](../../designs/masque-gateway.md#capabilities). + + + +See [CLI Usage](../../designs/masque-gateway.md#cli-usage). + + + +See [Implementation Phases](../../designs/masque-gateway.md#implementation-phases). + + + +See [Phase 1: Foundation](../../designs/masque-gateway.md#phase-1-foundation). + + + +See [Phase 2: Relay Evolution](../../designs/masque-gateway.md#phase-2-relay-evolution). + + + +See [Phase 3: Production](../../designs/masque-gateway.md#phase-3-production). + + + +See [Open Questions](../../designs/masque-gateway.md#open-questions). + + + +See [References](../../designs/masque-gateway.md#references). + + + +See [Internal](../../designs/masque-gateway.md#internal). + + + +See [MASQUE](../../designs/masque-gateway.md#masque). + + + +See [Connectivity](../../designs/masque-gateway.md#connectivity). + + + +See [SRv6](../../designs/masque-gateway.md#srv6). diff --git a/docs/fabric-api/README.md b/docs/fabric-api/README.md new file mode 100644 index 000000000..b062961a3 --- /dev/null +++ b/docs/fabric-api/README.md @@ -0,0 +1,14 @@ +# Fabric looking glass + +Use fabric-api to query FRR state and run bounded ICMP diagnostics from fabric routers. It is opt-in and separate from the L4 ingress gateway. + +- [Architecture](architecture.md): ownership, execution, recovery and isolation. +- [Deployment](deployment.md): prerequisites, cell gateway, node sidecar and certificate pods. +- [Configuration](configuration.md): ports, flags, budgets, index settings and cleanup. +- [Security](security.md): identities, certificate rotation and probe destination policy. +- [Operations](operations.md): observability, rollout, verification and troubleshooting. +- [FabricQuery API](api.md): query and result semantics, conditions and errors. +- [Load-test procedure](load-test.md): repeat the full-table diagnostic qualification. +- [Metric reference](../observability/fabric-api.md): exported series and alerts. + +The [Looking Glass service contract](../designs/looking-glass-service.md) specifies proposed service behavior. It does not announce a customer API or qualified aggregate limits. diff --git a/docs/fabric-api/api.md b/docs/fabric-api/api.md index 2f46acfe7..48c4e673a 100644 --- a/docs/fabric-api/api.md +++ b/docs/fabric-api/api.md @@ -1,6 +1,6 @@ # FabricQuery API Reference -The proposed [Looking Glass service contract](service-contract.md) defines the +The proposed [Looking Glass service contract](../designs/looking-glass-service.md) defines the separate customer-service API, coverage, aggregate limits, and failure bounds for #1042. It is a future implementation contract; the interfaces and settings documented on this page remain the current baseline. @@ -9,7 +9,7 @@ documented on this page remain the current baseline. fabric-api gateway: one object per public looking-glass query per resolved cell. This page documents its spec, status, validation, semantics and error codes. For how the gateway executes it see -[docs/agents/ARCHITECTURE-FABRIC-API.md](../agents/ARCHITECTURE-FABRIC-API.md); for +[docs/agents/ARCHITECTURE-FABRIC-API.md](architecture.md); for deploying it see [configuration.md](configuration.md). The **public** `LookingGlassQuery` that tenants create is served by NSO and is out @@ -25,7 +25,7 @@ cluster, and its status is written by that cell's gateway and returned by Karmad | Property | Value | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -| Group, version | `galactic.datumapis.com/v1alpha1` | +| Group, version | `galactic.datumapis.com/v1alpha1` | | Kind | `FabricQuery`, list kind `FabricQueryList` | | Scope | Namespaced (the project's mapped namespace on the hub) | | Short name | `fq` | @@ -141,7 +141,7 @@ in the `ErrorInfo` metadata under the key `queryCode` and at the start of the me Whether a numeric destination may be probed is a separate decision from syntax. The node checks it against the destination policy for the caller's role; see -[configuration.md](configuration.md#destination). In short, a public probe may +[configuration.md](security.md#destination). In short, a public probe may target only IPv6 global unicast (`2000::/3`) and non-special-use IPv4, minus any `--deny-prefixes`. Routing visibility does not authorize an active probe to every visible prefix. diff --git a/docs/fabric-api/architecture.md b/docs/fabric-api/architecture.md new file mode 100644 index 000000000..167de6bf0 --- /dev/null +++ b/docs/fabric-api/architecture.md @@ -0,0 +1,88 @@ +# fabric-api architecture + +`fabric-api` executes bounded diagnostics against each fabric router's own view. It reads FRR through vty sockets, searches a BMP-fed index, and sends ICMP probes from the node's fabric address. It does not configure routing. + +Use [deployment](deployment.md) to install it, [configuration](configuration.md) to look up flags and limits, [security](security.md) for identities and probe policy, and [the FabricQuery contract](api.md) for requests and results. The [Looking Glass service design](../designs/looking-glass-service.md) specifies future behavior beyond these operator and FabricQuery interfaces. + +## Components and ownership + +| Component | Responsibility | Location | +| --------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------ | +| `fabric-api node` | Reads FRR, maintains the search index, executes bounded probes | Sidecar in each opted-in fabric-router pod | +| `fabric-api gateway` | Discovers nodes, schedules requests, writes FabricQuery status, serves operator queries | Leader-elected Deployment per cell | +| `fabric-api certsync` | Copies validated credentials from the CSI volume to node-local tmpfs | Separate fabric-api-certs DaemonSet | +| `fabric-api janitor` | Deletes expired or retained FabricQuery copies with deletion preconditions | CronJob per cell | +| `fabric-api query` | Operator client for node and gateway RPCs | Operator environment | + +All use one image. The node sidecar shares FRR's pod-scoped `/run/frr` socket directory. The gateway has no FRR dependency. The image contains neither FRR, `vtysh`, a shell nor an eBPF program. + +Galactic owns the internal FabricQuery types in `internal/fabric/api/v1alpha1`, the protobuf services and execution code. The public LookingGlassQuery API, placement, federation and customer authorization belong to the consuming services. Infra installs the production CRDs and per-cell issuer. The generated CRD under `config/fabric-api/crd` is used by the lab and schema tests. This ownership boundary does not promise a future repository move. + +## Query execution + +1. The gateway validates a FabricQuery's cell, immutable request, expiration, query type and budgets. +2. It discovers fabric-router pods and their node certificate pods, then writes a start marker containing the attempt and a fixed node snapshot. +3. Its executor schedules node RPCs fairly across principals (a service project, a FabricQuery source or an operator), within bounded queues and concurrency. Queue time counts against the node deadline. With `--aggregate-budgets`, the leader also charges every request and probe to cell, principal and destination budgets and hands each probe a permit bound to its election epoch; see [aggregate probe budgets](configuration.md#aggregate-probe-budgets). +4. Each node authenticates the caller, revalidates the request, applies destination policy and budgets, executes the operation, and shapes its result. +5. The gateway writes one bounded terminal status. Conflicting status writes retry without repeating the node RPCs. A completed query is never reopened. + +The operator debug service reuses the executor without creating a FabricQuery. A follower forwards once to the leader. An operator querying through the gateway receives the public destination policy because the node sees the gateway identity; direct operator-to-node requests may use the configured operator exceptions. + +### Discovery and recovery + +Discovery records unusable pods and omission reasons instead of silently dropping them. During a rollout it selects one usable fabric-router pod per node and records duplicates. Pod readiness is not a selection requirement because FRR drives that condition. A node without a running certificate pod is omitted even if the sidecar still holds an unexpired certificate. + +A nonterminal query with a matching observed generation and an existing snapshot resumes that snapshot with a new attempt after leader failover. It does not discover a different population midway through the request. Status arrays and observations remain bounded; coverage counts nodes that do not fit in the stored list. + +The gateway writes a small start marker and one terminal result, not incremental result payloads. Cancellation stops local work but cannot prove that an FRR command already submitted stopped computing. Node duplicate suppression is an in-memory cache; restart or eviction can permit repeated execution. Exactly-once execution is not guaranteed. + +## FRR reads and probes + +Route lookups sample bgpd and zebra separately. A BGP best path and a kernel installation are distinct observations, neither of which proves end-to-end reachability. BGP summaries read one router's peer table. Ping and traceroute use raw ICMP sockets from the node's chosen fabric address. + +FRR commands are built from closed, typed templates. There is no arbitrary-command RPC. A read-only socket mount does not make FRR's command protocol read-only; the command builder enforces that application boundary, and the sidecar remains trusted control-plane code. + +The vty client frames a command with NUL and reads the terminating status. A warning containing complete JSON can be data, such as zebra's empty result for an absent route. A warning with non-JSON output is a command failure. Each command uses its own connection, requires complete valid JSON, and closes the connection when its byte cap is exceeded instead of persisting partial output. + +Only FRR releases listed in `internal/fabric/frr` are accepted. Unsupported versions report diagnostics unavailable rather than guessing a parser. Add captured parser fixtures and support before upgrading the FRR image. Probe destinations must already be numeric and satisfy the caller's policy; hostname resolution belongs upstream. + +Errors carry a typed reason in gRPC `ErrorInfo`, with a stable mapping into FabricQuery conditions and public errors. See [error codes](api.md#error-codes). + +## Search index + +AS-path, community and large-community searches are disabled unless explicitly enabled. Direct FRR table scans can occupy bgpd after a caller times out, so the default search source is a local index fed by bgpd's BMP Loc-RIB stream. [Dated load-test evidence](../archive/benchmarks/fabric-api-2026-10-07.md) supports that choice; [the test procedure](load-test.md) describes qualification for a candidate release. + +The index holds each prefix's selected path. A search therefore need not match FRR's search over every path. Attributes are interned and reference-counted so matching work can be shared across prefixes. Results are ordered by prefix and include the total match count and snapshot metadata. + +Each BMP session begins empty. An explicit End-of-RIB can complete synchronization; the supported FRR Loc-RIB stream also uses the documented rate-based initial-dump heuristic because it does not send that marker. Disconnect makes the index unsynced. Unsynced searches fail with `QueryTypeUnavailable`; they never fall back to an FRR scan. Overflow is counted and affects completeness rather than silently representing dropped updates as complete. + +The station accepts one loopback connection. Loopback is the trust boundary: a local process could connect before bgpd and feed data, preventing bgpd's own session while it remains connected. This interface does not authenticate an untrusted local peer. + +## Identity and routing isolation + +Each connection uses a per-cell trust bundle and exactly one allowed URI SAN. The gateway discovers the certificate-pod identities allowed for a node, including a certificate pod being replaced during rotation. It checks the cell as well as the certificate chain. A service identity is restricted to the separately authorized Looking Glass service surface and cannot use operator or node methods. + +Credentials reload atomically after validating identity, lifetime, key pair and trust. A bad renewal preserves the previous credentials until expiration; with no valid credentials, handshakes fail closed while the process keeps retrying. See [identities and certificates](security.md#identities-and-certificates) for the exact identity forms and rotation procedure. + +The certificate CSI volume belongs to a separate pod because certificate issuance blocks pod startup. Placing it in fabric-router would let an issuer outage prevent FRR from starting. Certsync copies credentials to the node's tmpfs and the sidecar mounts them read-only. A broken issuer therefore stalls certificate acquisition, not FRR startup. + +The sidecar has no readiness, startup or liveness probe that gates FRR. It exposes diagnostic availability through RPCs and metrics. A sidecar process crash can still affect aggregate pod readiness and rollout progress. An image change recreates the entire fabric-router pod, so sidecar releases must follow the [routing rollout procedure](operations.md#rollout). + +The node runs with the socket group and only the raw-socket capability it needs. The gateway and janitor have separate identities: the gateway can update query status but cannot delete queries; the janitor can delete them but cannot execute diagnostics or write their status. The janitor uses UID/resource-version preconditions to avoid deleting a replacement object. + +## Source and validation map + +| Area | Source | Validation | +| ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| Requests, canonicalization, destination policy | `internal/fabric/query` | Unit tests for limits, families and policy | +| FRR protocol and parsing | `internal/fabric/frr` | Captured version-specific fixtures and framing/error tests | +| ICMP execution | `internal/fabric/probe` | Fake sockets; opt-in real raw-socket tests | +| Trust, rotation, certificate copying | `internal/fabric/identity` | mTLS, bad renewal and overlapping CA tests | +| Node budgets and execution | `internal/fabric/node` | RPC, shaping, deadline and duplicate-cache tests | +| Probe permits on the node | `internal/fabric/node` (`permit.go`) | Single-use and refusal tests | +| Discovery, scheduling, status and cleanup | `internal/fabric/gateway` | Reconcile, failover, fairness, bounded-result and service streaming tests | +| Aggregate admission, permits, delivery bounds | `internal/fabric/gateway/limit`, `internal/fabric/gateway` (`admission.go`, `permit.go`, `stream.go`) | Bucket, attempt-key, Lease authority, admission and stream-bound tests | +| BMP station and indexed searches | `internal/fabric/index` | Stream, synchronization and search tests; full-table load harness | +| Schema | `internal/fabric/api/v1alpha1` | Envtest admission tests, requiring KUBEBUILDER_ASSETS | + +The lab's `verify:fabric-api` task exercises node and gateway queries and FabricQuery completion. `verify:fabric-api-bootstrap` deliberately breaks certificate issuance to test the routing-isolation boundary. These require the lab; a unit-test run alone does not establish those outcomes. [Operational verification](operations.md#verifying) lists the commands and expected observations. diff --git a/docs/fabric-api/configuration.md b/docs/fabric-api/configuration.md index d1e938dfc..895dab744 100644 --- a/docs/fabric-api/configuration.md +++ b/docs/fabric-api/configuration.md @@ -1,245 +1,8 @@ -# fabric-api Deployment & Configuration - -The proposed [Looking Glass service contract](service-contract.md) defines the -separate customer-service API, coverage, aggregate limits, and failure bounds -for #1042. It is a future implementation contract; the interfaces and settings -documented on this page remain the current baseline. - -This is a how-to and reference guide for deploying and configuring -`fabric-api`, the looking glass over `fabric-router`'s FRR state. For the -design rationale (why a sidecar, why pod identities, why the budgets are what -they are) see -[docs/agents/ARCHITECTURE-FABRIC-API.md](../agents/ARCHITECTURE-FABRIC-API.md); -this document covers the "how". The `FabricQuery` contract is in -[api.md](api.md). - -> Last verified: 2026-10-07 against the `feat/fabric-api` working tree: -> `cmd/fabric-api/`, `internal/fabric/`, `config/fabric-api/`, -> `config/fabric-router/components/fabric-api/`, `config/monitoring/`, and the -> lab in `deploy/containerlab/` (`deploy:cert-manager`, `deploy:fabric-api`, -> `verify:fabric-api`, `verify:fabric-api-bootstrap`). - -## What you deploy - -fabric-api has four runtime parts, all from one image, -`ghcr.io/datum-cloud/fabric-api`: - -| Part | Kind | Where | What it does | -| ------- | -------------------------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------- | -| node | Sidecar in the `fabric-router` DaemonSet pod | Every `fabric-router` node | Reads FRR over its vty sockets and sends ICMP probes; answers mTLS gRPC on the node's own address | -| gateway | Deployment, 2 replicas, leader-elected | One per cell | Executes `FabricQuery` objects by fanning out to the node sidecars; serves the operator debug service | -| certs | DaemonSet `fabric-api-certs` | Every `fabric-router` node | Obtains the node's certificate from a csi-driver volume and copies it to the node for the sidecar; needs no API token | -| janitor | CronJob | One per cell | Deletes expired `FabricQuery` copies the federation failed to delete | - -Everything is opt-in. `kubectl apply -k config/` does not deploy any of it, and -the base `fabric-router` DaemonSet is unchanged unless you include the -Component. - -## Prerequisites - -None of these are created by this repository's manifests. - -1. **cert-manager and its csi-driver**, running on every node that runs - `fabric-router` (tolerating the nodes' taints), because the `fabric-api-certs` - pods mount a csi volume. The csi-driver needs no special setting. -2. **An `Issuer` named `fabric-api`** in `galactic-system`, backed by a dedicated - per-cell fabric-api CA. Not a general cluster CA: trust is per cell. Infra owns - it in production; the lab's stand-in is - `deploy/containerlab/resources/fabric-api/pki/pki.yaml`. -3. **The `FabricQuery` CRD** (`fabricqueries.galactic.datumapis.com`). Infra owns - its lifecycle in every cell. `config/fabric-api/crd/` is a copy for the lab and - tests only; do not apply it where infra manages the CRD. -4. **A per-cell `fabric-api` ConfigMap** in `galactic-system` (see - [Per-cell ConfigMap](#step-2-per-cell-configmap)). -5. **A federation path that delivers `FabricQuery` objects** to the cell, pinned - to its member cluster. That is NSO and Karmada's work and is out of scope here. - -### Why certificates are issued in a separate pod - -A `csi.cert-manager.io` volume blocks its pod until the certificate is issued. -The driver's `continueOnNotReady` setting does not change that: it covers only the -driver's own readiness gates. With a broken Issuer a lab test showed -`MountVolume.SetUp` waiting ("Referenced issuer does not have Ready condition") -and a `fabric-router` pod stuck in `PodInitializing` with FRR down. So the -sidecar's certificate does not come from a volume in the `fabric-router` pod: - -- The Component adds a DaemonSet, `fabric-api-certs`, with the same placement as - `fabric-router` and no API token. It runs `fabric-api certsync`, which copies - `tls.crt`, `tls.key` and `ca.crt` from its csi volume (`fabric-api-csi`) to the - node's tmpfs directory `/run/fabric-api/tls` every 10 seconds. It validates the - key pair first and replaces each file atomically. -- The `fabric-router` pod mounts `/run/fabric-api/tls` read-only as a hostPath of - type `DirectoryOrCreate`, which never blocks the pod. -- A broken Issuer therefore stalls only the `fabric-api-certs` pod (it waits in - `ContainerCreating`). The sidecar reports no credentials and fails closed; - routing is unaffected. When the Issuer is repaired the sidecar picks the - certificate up without a restart. - -`task verify:fabric-api-bootstrap` in `deploy/containerlab/` is the lab's check of -this property. - -## Deployment - -### Step 1: cell-wide RBAC and ServiceAccounts +# fabric-api configuration reference -```sh -kubectl apply -k config/fabric-api/ -``` - -This applies only `serviceaccount.yaml` and `rbac.yaml`: the `fabric-api-gateway` -and `fabric-api-janitor` ServiceAccounts, and their roles. It is safe and -idempotent in any cell. - -| Identity | Scope | Permissions | -| -------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------ | -| `fabric-api-gateway` | Cluster | `fabricqueries`: get, list, watch. `fabricqueries/status`: get, update, patch. `nodes`: get (node selectors) | -| `fabric-api-gateway` | `galactic-system` | `pods`: get, list, watch. `leases`: get, list, watch, create, update, patch. `events`: create, patch | -| `fabric-api-janitor` | Cluster | `fabricqueries`: list, delete | - -The gateway cannot edit a spec, create or delete a query, or touch FRR's -ConfigMaps. Delete access is deliberately a separate identity. - -### Step 2: per-cell ConfigMap - -```yaml -apiVersion: v1 -kind: ConfigMap -metadata: - name: fabric-api - namespace: galactic-system -data: - site: dfw - cell: dfw - cluster-name: dfw -``` - -| Key | Used by | Meaning | -| -------------- | ------------- | ------------------------------------------------------------------------------------------------------------- | -| `site` | node, gateway | The location this cell serves. The gateway executes only `FabricQuery` objects whose `spec.site` equals it | -| `cell` | node, gateway | The cell name in every mTLS identity. Must equal the `CELL_NAME` in the certificates' URI SANs | -| `cluster-name` | gateway | This cell's Karmada member cluster name. The gateway executes only objects whose `spec.clusterName` equals it | - -The gateway's Deployment references all three keys as required, so it will not -start without the ConfigMap. The node sidecar references `site` and `cell` as -optional: without `cell` it stays up, logs an error, serves only metrics and -reports diagnostics unavailable, so a missing ConfigMap never crash-loops a -container in the `fabric-router` pod. Container environment is fixed at start, so -creating the ConfigMap after the Component is rolled out means recreating the -pods, which restarts FRR. Create it first. - -### Step 3: the gateway and janitor - -`config/fabric-api/base/` holds the gateway Deployment, its ClusterIP Service, a -PodDisruptionBudget (`minAvailable: 1`) and the janitor CronJob. It is not applied -by anything by default because it needs per-cell values: the ConfigMap above and -the cell name in the gateway certificate's URI SAN. Instantiate it from a per-cell -overlay (compare `deploy/containerlab/resources/fabric-api/gateway/dfw/`): - -```yaml -# overlays//gateway/kustomization.yaml -namespace: galactic-system -resources: - - ../../../config/fabric-api/base -configMapGenerator: - - name: fabric-api - literals: - - site=dfw - - cell=dfw - - cluster-name=dfw -generatorOptions: - disableNameSuffixHash: true -patches: - - target: - kind: Deployment - name: fabric-api-gateway - patch: |- - - op: replace - path: /spec/template/spec/volumes/0/csi/volumeAttributes/csi.cert-manager.io~1uri-sans - value: spiffe://fabric-api.datumapis.com/cell/dfw/gateway -``` - -Adjust the relative path to `config/fabric-api/base`. `disableNameSuffixHash` -matters: the pods reference the ConfigMap by the fixed name `fabric-api`. - -The base pins `ghcr.io/datum-cloud/fabric-api` at a tag the release pipeline -stamps. Override it from an overlay's `images:` stanza. The gateway runs as UID -65532 with a read-only root filesystem and no capabilities, requests 20m CPU and -64Mi memory, and limits memory to 512Mi. - -### Step 4: the node sidecar Component, as a canary +For installation use [deployment](deployment.md); for certificate identities use [security](security.md); for rollout, verification and troubleshooting use [operations](operations.md). The [FabricQuery reference](api.md) defines request and result semantics. -Add the Component to an overlay of `config/fabric-router` and replace -`CELL_NAME` in the URI SAN of the `fabric-api-certs` DaemonSet's csi volume: - -```yaml -# overlays//fabric-router/kustomization.yaml -resources: - - ../../../config/fabric-router -components: - - ../../../config/fabric-router/components/fabric-api -patches: - - path: fabric-api-cell-patch.yaml -``` - -```yaml -# overlays//fabric-router/fabric-api-cell-patch.yaml -apiVersion: apps/v1 -kind: DaemonSet -metadata: - name: fabric-api-certs -spec: - template: - spec: - volumes: - - name: fabric-api-csi - csi: - driver: csi.cert-manager.io - volumeAttributes: - csi.cert-manager.io/uri-sans: spiffe://fabric-api.datumapis.com/cell/dfw/ns/${POD_NAMESPACE}/pod/${POD_NAME} -``` - -`fabric-router` still needs its own per-node `fabric-router.` -ConfigMaps as usual (see `AGENTS.md`). The Component does not create the cell -ConfigMap, the Issuer or the CRD. Applying it adds the `fabric-api-certs` DaemonSet and recreates every `fabric-router` pod -and restarts FRR; follow [Rollout](#rollout). - -What the Component changes in the pod: - -- Adds the `fabric-api` container (`args: [node]`) with ports `fabric-api`/9344 - and `api-metrics`/9345, 10m CPU and 64Mi memory requested, a 768Mi memory limit - and `GOMEMLIMIT=640MiB` (the search index holds a copy of bgpd's selected routes; - see [Search index](#search-index)). - It has no readiness, liveness or startup probe, on purpose. -- Mounts FRR's `/run/frr` read-only and the node's `/run/fabric-api/tls` (a - hostPath, filled by `fabric-api-certs`) at `/var/run/fabric-api/tls` read-only. -- Runs the container as UID 0, GID 102 (`frrvty`), dropping every capability and - adding only `NET_RAW`, with a read-only root filesystem and no privilege - escalation. Raw ICMP sockets need `NET_RAW` in the effective set, which a - non-root container cannot get; without `CAP_DAC_OVERRIDE` it reaches FRR's - `0770 frr:frrvty` sockets through group 102. -- Sets `automountServiceAccountToken: false` on the pod and adds a projected - token volume mounted only into `frr-init` and `config-agent`, the containers - that call the Kubernetes API. The sidecar has no API access. - -The `fabric-api-certs` DaemonSet runs the same image with `args: [certsync, ...]`, -tolerates every taint, avoids control-plane nodes and requires the same -`galactic.datumapis.com/fabric` label values as `fabric-router`. It runs as root -(to write the root-owned node directory) with every capability dropped, a -read-only root filesystem, 5m CPU and 16Mi memory requested and a 64Mi limit. - -### Lab - -In `deploy/containerlab/`: `task build:fabric-api` builds the image, -`task deploy:cert-manager` installs cert-manager and the csi-driver in every -cluster (the csi-driver must run on every fabric node before `deploy:fabric`), and `task deploy:fabric-api` installs the CRD copy, RBAC, a stand-in PKI, -the gateway and the janitor. `task deploy` does all of them in the right order -(`deploy:cert-manager` before `deploy:fabric`, `deploy:fabric-api` last). In the -lab each site is one cell whose cell, site and member cluster name are all the site -name. Each site's fabric-router overlay creates that site's `fabric-api` -ConfigMap, so it lands with the node sidecars in `deploy:fabric`, ahead of their -start. `task verify:fabric-api` (which first runs -`task verify:fabric-api-config`, a check that the overlays render it) and -`task verify:fabric-api-bootstrap` are the checks. +The [Looking Glass service contract](../designs/looking-glass-service.md) describes future behavior beyond the currently available operator and FabricQuery interfaces. ## Ports @@ -261,172 +24,6 @@ reaches 9344 and 9345 (gateway pods to 9344, your scraper to 9345), do so. The debug Service is `ClusterIP` only; a port-forward to it is a transport choice and does not bypass the gateway's identity checks. -## Identities and certificates - -Every certificate carries exactly one URI SAN in the trust domain -`fabric-api.datumapis.com`: - -| Identity | URI SAN | Issued to | Key usages | -| -------- | ------------------------------------------------------------------------ | ----------------------------------------- | ------------------------- | -| gateway | `spiffe://fabric-api.datumapis.com/cell//gateway` | The gateway Deployment (both replicas) | `client auth,server auth` | -| node | `spiffe://fabric-api.datumapis.com/cell//ns//pod/` | Each node's `fabric-api-certs` pod | `server auth` | -| operator | `spiffe://fabric-api.datumapis.com/cell//operator/` | A person or tool calling directly | `client auth` | -| service | `spiffe://fabric-api.datumapis.com/cell//service/` | The customer-facing Looking Glass service | `client auth` | - -The node identity names a **pod**, not the node: the csi-driver can template a -pod's name and namespace (`${POD_NAME}`, `${POD_NAMESPACE}`) but not its node's -name. That pod is the node's `fabric-api-certs` pod, not the `fabric-router` pod -the sidecar runs in. The gateway maps each node to its newest Running -`fabric-api-certs` pod (selected by `--certs-selector`, default -`app.kubernetes.io/name=fabric-api-certs`), records it in -`status.nodes[].certificatePod`, and dials accepting only the identities of -that node's certs pods: the newest one, and any it is replacing, since a sidecar -keeps presenting a replaced pod's certificate until the new one reaches it. A -node with no running certs pod is omitted with reason `NoCertificatePod`. The -sidecar does not know that pod's name, so it accepts any node identity in its own -cell and namespace as its own; the gateway's pinning is what ties a certificate to -a node. Each path segment must be a lower-case DNS-label-like string (`[a-z0-9]`, -with `.` and `-` inside). - -How an identity is checked: - -- TLS 1.3 minimum, mutual. The server requires a client certificate and the - client accepts only a server proving the identity it expected. -- The chain is verified against the trust bundle current at handshake time, with - the right key usage, and the identity's **cell must equal this process's own - cell**. -- A process refuses to load a certificate whose identity is not its own (for - the sidecar: any node identity in its cell and namespace), is not valid now, or does not chain to the bundle it shipped with. -- At the handshake a node accepts only gateway and operator identities. Per RPC, a - gateway or operator may call the node's `Execute` and `Info`; on the gateway's - debug service an operator may call `Query` and `ListNodes`, and the gateway - identity may call only `Query` (the form in which a follower forwards to the - leader). Anything else is `Unauthorized`. -- The gateway also accepts node identities, which may call only its - `RequestPermit` and `ReleasePermit` (and the gateway identity, forwarding - them to the leader). The handler further requires the node identity's - namespace to be the gateway's `--namespace` and its pod to be a - `fabric-api-certs` pod on the node the call names. -- The gateway also accepts a service identity whose name is in - `--service-identities`. A service may call only the Looking Glass service's - `GetCapabilities` and `RunDiagnostic`, never `Query`, `ListNodes` or a node. - The gateway identity may call the gateway-only `ForwardDiagnostic`, with which - a follower hands a request to the leader; no other identity may. -- On every gateway RPC, unary or streaming, the gateway verifies the caller's - certificate again against its current bundle and clock, so a connection opened - by a certificate that has since expired, or whose CA has left the bundle, is - refused with `UNAUTHENTICATED`. A call's context ends when the caller's - certificate expires, after which a stream sends and receives nothing more. - Metadata keys starting `x-fabric-api-` are dropped from every call the - gateway identity did not make. - -The csi volume attributes in the `fabric-api-certs` DaemonSet (volume -`fabric-api-csi`) and the gateway Deployment: - -| Attribute | `fabric-api-certs` | Gateway | -| ---------------------------------- | -------------------------------------------------------- | ---------------------------- | -| `csi.cert-manager.io/issuer-name` | `fabric-api` | `fabric-api` | -| `csi.cert-manager.io/issuer-kind` | `Issuer` | `Issuer` | -| `csi.cert-manager.io/uri-sans` | `.../cell/CELL_NAME/ns/${POD_NAMESPACE}/pod/${POD_NAME}` | `.../cell/CELL_NAME/gateway` | -| `csi.cert-manager.io/key-usages` | `server auth` | `client auth,server auth` | -| `csi.cert-manager.io/duration` | `24h` | `24h` | -| `csi.cert-manager.io/renew-before` | `8h` | `8h` | -| `csi.cert-manager.io/fs-group` | not set | `65532` | - -`CELL_NAME` is a literal placeholder in both manifests that your overlay must -replace with the cell name (the same value as the ConfigMap's `cell` key). The -csi-driver cannot take it from a ConfigMap. A mismatch is not subtle: the process -rejects its own certificate (`certificate identity ... is not ...`), reports -credentials not loaded and fails closed. The files are `tls.crt`, `tls.key` and -`ca.crt`, read from `/var/run/fabric-api/tls` (`--tls-cert`, `--tls-key`, -`--tls-ca`). For the gateway that is its own csi volume; for the sidecar it is the -hostPath that `certsync` fills. - -### Operator certificates - -An operator certificate is a normal cert-manager `Certificate` from the same -`fabric-api` Issuer, for example the lab's: - -```yaml -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - name: fabric-api-operator - namespace: galactic-system -spec: - secretName: fabric-api-operator - duration: 24h - renewBefore: 8h - uris: - - spiffe://fabric-api.datumapis.com/cell/dfw/operator/alice - usages: - - digital signature - - client auth - privateKey: - algorithm: ECDSA - size: 256 - issuerRef: - name: fabric-api - kind: Issuer -``` - -An operator certificate can reach any node and the gateway in its cell, so treat -who may request one as an access decision. - -### Service certificates - -The customer-facing Looking Glass service gets one certificate per cell it calls, -from that cell's `fabric-api` Issuer, with URI SAN -`spiffe://fabric-api.datumapis.com/cell//service/` and usage -`client auth`, issued like an operator certificate. The gateway accepts it only -when `` is in its `--service-identities` list. The project and request -IDs in a `RunDiagnostic` request are trusted because that identity is -authenticated: issuing a service certificate grants the right to attribute -diagnostics to any project, so treat it as an access decision too. The -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. - -### Rotation - -Certificates last 24h and renew 8h before expiry. The csi-driver renews in place; for -the sidecar, `certsync` copies the new files to the node within 10 seconds. The -sidecar polls its files every 10 seconds, the gateway every 30, and each swaps in a new certificate, key and bundle without a -restart, and without touching FRR. A new set is accepted only if the certificate -matches the process's identity, is valid now and chains to the bundle delivered -with it. If it does not, the previous credentials stay in use until they expire. -With none loaded, every handshake fails closed, the process keeps running and -retrying, and routing is unaffected. - -| Situation | Behaviour | Signal | -| ---------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------- | -| Files missing or unreadable | Handshakes fail; warning logged every 30s | `fabric_api_credentials_loaded` 0; `FabricAPICredentialsMissing` after 15m | -| Renewal produces a bad certificate | The previous one keeps serving until its `notAfter`, then none | `fabric_api_certificate_expiry_timestamp_seconds` stops advancing | -| Certificate expires | Credentials cleared; handshakes fail closed | `FabricAPICertificateRenewalFailing` fires earlier, at under 4h left | -| Wrong cell, pod or role in the SAN | Certificate rejected at load | Warning in the log; credentials not loaded | - -**Rotating the CA.** A peer verifies the other side against its own current -bundle, so a leaf from a new CA is unusable by any peer that has not yet loaded a -bundle trusting that CA. Rotate with overlap, using a bundle that holds both -certificates (the loader accepts a multi-certificate `ca.crt`): - -1. Make every pod's `ca.crt` trust both the old and the new CA. -2. Wait until every node sidecar and the gateway have reloaded it (within 30 - seconds of the volume updating), confirmed by `fabric_api_credentials_loaded` 1 and - a fresh `fabric_api_certificate_expiry_timestamp_seconds` per pod. -3. Switch issuance to the new CA. Leaves renew within 24 hours and chain to it. -4. After every leaf from the old CA has been replaced (allow more than the 24h - duration), remove the old CA from the bundle. - -How step 1 is achieved depends on the issuer integration (infra owns it) and is -not exercised by this repository's lab; the code path that tolerates the overlap -is covered by `TestRotationWithOverlappingBundle`. - ## Command-line reference Every flag below is on the `fabric-api` binary; where an environment variable is @@ -492,7 +89,7 @@ the stale result. To change a flag in production, patch the `fabric-api` container's `args` in your overlay (keep `node` first). Any such change is a pod template change and restarts -FRR, so it follows [Rollout](#rollout). +FRR, so it follows [Rollout](operations.md#rollout). ### `fabric-api gateway` @@ -735,7 +332,7 @@ Without `--aggregate-budgets` the cell executor above and each node's packet pacer are the only limits, and they are local: nothing bounds how many probe packets the cell as a whole sends to one destination. With it, the leader gateway holds every budget of the -[service contract](service-contract.md#admission-execution-and-aggregate-accounting) +[service contract](../designs/looking-glass-service.md#admission-execution-and-aggregate-accounting) in memory and charges every probe, whoever asked for it: | Budget | Default | Charged to | When exhausted | @@ -796,92 +393,7 @@ client may ping no more often than every 5 seconds. On `SIGTERM` the gateway closes its listener's connections at once, cancelling operator and service 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. -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 - routing rollout. - -Roll back in the reverse order. Removing `--aggregate-budgets` while nodes still -require permits refuses every gateway probe (`LimiterUnavailable`). - -## Probe sources and destinations - -### Source - -Probes use the default VRF and an explicit per-family fabric loopback address, and -never fall back to `127.0.0.1`, `::1`, an unspecified address or an unrelated -interface. For each family the sidecar uses, in order: - -1. `--probe-source-ipv4` or `--probe-source-ipv6`, if set. The value must parse and - be of the right family; a loopback or unspecified address makes startup fail. -2. Otherwise the single global unicast address of that family on - `--probe-source-interface` (default `lo`), ignoring loopback and link-local - addresses. -3. Otherwise none. A family with no source, or with more than one candidate on the - interface (the log says "several candidate probe sources; set one explicitly"), - answers `ProbeSourceUnavailable` for that family. A missing interface logs a - warning and disables auto-detection. - -`Info.probe_sources` lists the sources that resolved. If `lo` carries other global -addresses (VIPs, for instance), set the sources explicitly. - -### Destination - -A probe's destination is a numeric address pinned by NSO; the node validates it -again and never resolves names. Under the **public policy**, the one applied to -every call from the gateway identity, a destination is refused -(`DestinationNotAllowed`) if it is: - -- an IPv6 address outside `2000::/3` (global unicast), or -- in a special-use range: IPv4 `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, - `127.0.0.0/8`, `169.254.0.0/16`, `172.16.0.0/12`, `192.0.0.0/24`, `192.0.2.0/24`, - `192.31.196.0/24`, `192.52.193.0/24`, `192.88.99.0/24`, `192.168.0.0/16`, - `192.175.48.0/24`, `198.18.0.0/15`, `198.51.100.0/24`, `203.0.113.0/24`, - `224.0.0.0/4`, `240.0.0.0/4`; IPv6 `::/128`, `::1/128`, `::ffff:0:0/96`, - `64:ff9b::/96`, `64:ff9b:1::/48`, `100::/64`, `2001::/23`, `2001:db8::/32`, - `2002::/16`, `3fff::/20`, `5f00::/16` (SRv6 SIDs), `fc00::/7`, `fe80::/10`, - `ff00::/8`, or -- inside a range listed in `--deny-prefixes`: add your management and platform - ranges here. - -The **operator policy** applies to calls made directly to a node with an operator -identity. It is the public policy plus `--operator-allow-prefixes`, and an allowed -prefix bypasses every other rule, including `--deny-prefixes`. The lab uses it to -check cross-site reachability between fabric loopbacks (`10.255.255.0/24` and -`fc00::/32`). A node refuses to start with allow exceptions on the public policy, -and nothing enforces "never in production" except not setting the flag. Calls made -through the gateway's debug service carry the gateway's identity at the node, so -they get the public policy whoever the operator is. +To turn the budgets on, follow [Enabling aggregate probe budgets](operations.md#enabling-aggregate-probe-budgets). ## Per-node and per-cell state @@ -923,143 +435,99 @@ janitor's `--retention` and `--grace`, or the gauge and alert disagree with what janitor deletes. The janitor has no metrics: it logs each deletion (and, at debug level, each outcome), so read its activity from the CronJob's logs. -## Observability - -Scrape config and alert rules are in `config/monitoring/` (not part of -`config/kustomization.yaml`; they need the Prometheus Operator CRDs): - -- The `fabric-router` PodMonitor's `api-metrics` endpoint scrapes the sidecar's - port 9345 as `job="fabric-api-node"`, with a `node` label. A pod without the port - yields no target. -- `podmonitor-fabric-api-gateway.yaml` scrapes the gateway's port 9347 as - `job="fabric-api-gateway"`. -- 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 | - -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 -infra's copy; change the rules here, with their tests, then update infra's copy. - -Node metrics (port 9345, a private registry with Go and process collectors): -`fabric_api_node_requests_total{type,outcome}`, -`fabric_api_node_request_duration_seconds{type}`, -`fabric_api_node_response_bytes{type}`, -`fabric_api_node_truncated_responses_total{type}`, -`fabric_api_node_in_flight_requests`, -`fabric_api_node_duplicate_requests_total`, -`fabric_api_node_duplicate_cache_entries`, -`fabric_api_node_diagnostics_available`, -`fabric_api_node_frr_info{version,supported}`, -`fabric_api_node_expensive_breaker_open`, -`fabric_api_node_probe_packets_total`, -`fabric_api_node_identity_refreshes_total{outcome}`, -`fabric_api_certificate_expiry_timestamp_seconds` and -`fabric_api_credentials_loaded`. - -Gateway metrics (port 9347, on controller-runtime's registry, so its own metrics -appear too): `fabric_api_gateway_queries_total{type,reason}`, -`fabric_api_gateway_node_outcomes_total{outcome}`, -`fabric_api_gateway_node_rpc_duration_seconds{type,code}`, -`fabric_api_gateway_queue_depth`, `fabric_api_gateway_status_writes_total{kind,outcome}`, -`fabric_api_gateway_status_bytes`, `fabric_api_gateway_truncated_results_total`, -`fabric_api_gateway_stage_latency_seconds{stage}` (`receipt`, `execution`, -`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. - -## Rollout - -The `fabric-api` sidecar lives in the `fabric-router` pod, and `/run/frr` stays a -pod-scoped `emptyDir` so FRR's sockets are never exposed beyond the pod. The cost -is that changing the sidecar's tag, flags or the Component itself changes the -DaemonSet's pod template, and the rolling update recreates the whole pod, FRR -included. **A sidecar release is a routing rollout.** - -1. **Do the prerequisites first**, outside the pods: cert-manager with its - csi-driver on every fabric node, the Issuer, the cell ConfigMap and the CRD. Roll out the - gateway and janitor first; they do not touch `fabric-router`. -2. **Canary one node.** Stage the change so only one node's pod is recreated - first, however your delivery system stages a DaemonSet change (the per-node - overlays used for `galactic-gateway` pin an instance to one node; the same idea - applies). Do not let the first change reach every node at once. -3. **Check underlay sessions and convergence** on the canary: every `frr_bgp_peer_state` - for the node back to Established for both families (frr-exporter on port 9342), - no `FabricBGPSessionDown` or `FabricBGPPrefixesDropped`, and `fabric-router` Ready. - Shallow daemon liveness is not a convergence gate. Then check the looking glass: - `fabric_api_node_diagnostics_available` 1, `fabric_api_credentials_loaded` 1, and - a direct `fabric-api query --info`. -4. **Pace the expansion**, one site or a small batch at a time, repeating step 3. - Stop on any session loss. -5. **Roll back** by restoring the previous tag or removing the Component from the - overlay; that is another rolling restart, so pace it the same way. Probe success - is not evidence of routing health. - -Keep the gateway's and the sidecar's tags in step. They are the same image, and -this repository does not test a gateway and sidecars at different versions. The -publish pipeline stamps one tag into both `config/fabric-api/base` and the -Component. - -A failing sidecar must not gate any of this, and a certificate that cannot be issued -stalls only the `fabric-api-certs` pod. If a `fabric-api-certs` pod hangs in -`ContainerCreating`, the csi-driver is missing on that node or the Issuer cannot -issue; the node then shows `NoCertificatePod` to the gateway. A `fabric-router` pod -that hangs on `fabric-api-tls` should not occur, since that is a hostPath; check the -Component's patch. If the sidecar runs but reports diagnostics -unavailable, FRR and the underlay are unaffected; read `unavailableReason`. - -## Verifying -```sh -# Per node (lab): ASN, router ID, both address families' sessions, exact and -# longest-match lookups with zebra evidence, operator probes, then each gateway -# and a FabricQuery end to end. -cd deploy/containerlab && task verify:fabric-api - -# Disruptive: break the Issuer, recreate one fabric-router pod, check FRR and the -# underlay come up with diagnostics unavailable, then repair the Issuer. -cd deploy/containerlab && task verify:fabric-api-bootstrap -``` +## Moved sections -In a real cell, read the same facts from the cluster: +These anchors keep older bookmarks working. Use the focused guides linked above for new references. -```sh -kubectl -n galactic-system get pods -l app.kubernetes.io/name=fabric-router \ - -o custom-columns=NODE:.spec.nodeName,POD:.metadata.name,READY:.status.containerStatuses[*].ready -kubectl -n galactic-system logs deploy/fabric-api-gateway | grep -i "fabric query" -kubectl get fabricqueries -A # short name: fq -``` + + +[deploy fabric api](deployment.md#deploy-fabric-api). + + + +[what you deploy](deployment.md#what-you-deploy). + + + +[prerequisites](deployment.md#prerequisites). + + + +[why certificates are issued in a separate pod](deployment.md#why-certificates-are-issued-in-a-separate-pod). + + + +[deployment](deployment.md#deployment). + + + +[step 1 cell wide rbac and serviceaccounts](deployment.md#step-1-cell-wide-rbac-and-serviceaccounts). + + + +[step 2 per cell configmap](deployment.md#step-2-per-cell-configmap). + + + +[step 3 the gateway and janitor](deployment.md#step-3-the-gateway-and-janitor). + + + +[step 4 the node sidecar component as a canary](deployment.md#step-4-the-node-sidecar-component-as-a-canary). + + + +[lab](deployment.md#lab). + + + +[fabric api identities and probe policy](security.md#fabric-api-identities-and-probe-policy). + + + +[identities and certificates](security.md#identities-and-certificates). + + + +[operator certificates](security.md#operator-certificates). + + + +[service certificates](security.md#service-certificates). + + + +[rotation](security.md#rotation). + + + +[probe sources and destinations](security.md#probe-sources-and-destinations). + + + +[source](security.md#source). + + + +[destination](security.md#destination). + + + +[operate fabric api](operations.md#operate-fabric-api). + + + +[observability](operations.md#observability). + + + +[rollout](operations.md#rollout). + + + +[verifying](operations.md#verifying). + + -## Troubleshooting - -| Symptom | Likely cause and where to look | -| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `fabric-api-certs` pod stuck in `ContainerCreating` | csi-driver not installed or not on this node, or the Issuer cannot issue. FRR is unaffected; the node reports no credentials and the gateway omits it as `NoCertificatePod` | -| `unavailableReason` starts with `credentials:` | Issuer missing or not ready, `certsync` has not copied files yet, or `CELL_NAME` in the `fabric-api-certs` volume is not the ConfigMap's `cell`; check the certs pod and the sidecar's log | -| `unavailableReason` is `FRRVersionUnsupported` | FRR is not 10.7; ship a fabric-api that supports the new release before the `fabric-router` image | -| `unavailableReason` is `FRRUnavailable` | `bgpd.vty`/`zebra.vty` not reachable: FRR restarting, or the container lacks group 102 | -| Sidecar logs "fabric-api node is not configured" | `CELL` is empty: the ConfigMap or its `cell` key is missing. Fix it and recreate the pod | -| Gateway pod `CreateContainerConfigError` | The `fabric-api` ConfigMap or one of `site`, `cell`, `cluster-name` is missing | -| `FabricQuery` stays untouched | `spec.site` or `spec.clusterName` does not equal this gateway's; or this replica is not the leader | -| `NodeUnreachable` for every node | Gateway cannot reach `hostIP:9344` (host firewall) or the TLS handshake fails; check identities and cell values | -| `Unauthorized` | The caller's role may not make this call: a node identity cannot call anything, and a gateway identity may call only the debug `Query` | -| `DestinationNotAllowed` on a ping | Public policy applied; a direct node call with an operator identity may carry `--operator-allow-prefixes` in the lab | -| `ProbeSourceUnavailable` | No probe source for that family; see [Source](#source) | -| `QueryTypeUnavailable` | Expensive types are gated, or the breaker is open after a timed-out scan | -| `NodeBusy` | Node or cell budget full; expensive and probe budgets have no queue | -| `ResponseTooLarge` | FRR's answer exceeded 4 MiB, or did not fit the node's budget even when shaped; see `FabricAPIResultsOversized` | -| `DuplicateConflict` | A request ID was reused with different arguments | - -For the typed codes carried in results, see [api.md](api.md#error-codes). +[troubleshooting](operations.md#troubleshooting). diff --git a/docs/fabric-api/deployment.md b/docs/fabric-api/deployment.md new file mode 100644 index 000000000..b885e571f --- /dev/null +++ b/docs/fabric-api/deployment.md @@ -0,0 +1,227 @@ +# Deploy fabric-api + +Install the opt-in looking glass in a cell. After installation, follow [verification and rollout](operations.md). Flags are in [configuration](configuration.md), and certificates in [security](security.md). + +## What you deploy + +fabric-api has four runtime parts, all from one image, +`ghcr.io/datum-cloud/fabric-api`: + +| Part | Kind | Where | What it does | +| ------- | -------------------------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------- | +| node | Sidecar in the `fabric-router` DaemonSet pod | Every `fabric-router` node | Reads FRR over its vty sockets and sends ICMP probes; answers mTLS gRPC on the node's own address | +| gateway | Deployment, 2 replicas, leader-elected | One per cell | Executes `FabricQuery` objects by fanning out to the node sidecars; serves the operator debug service | +| certs | DaemonSet `fabric-api-certs` | Every `fabric-router` node | Obtains the node's certificate from a csi-driver volume and copies it to the node for the sidecar; needs no API token | +| janitor | CronJob | One per cell | Deletes expired `FabricQuery` copies the federation failed to delete | + +Everything is opt-in. `kubectl apply -k config/` does not deploy any of it, and +the base `fabric-router` DaemonSet is unchanged unless you include the +Component. + +## Prerequisites + +None of these are created by this repository's manifests. + +1. **cert-manager and its csi-driver**, running on every node that runs + `fabric-router` (tolerating the nodes' taints), because the `fabric-api-certs` + pods mount a csi volume. The csi-driver needs no special setting. +2. **An `Issuer` named `fabric-api`** in `galactic-system`, backed by a dedicated + per-cell fabric-api CA. Not a general cluster CA: trust is per cell. Infra owns + it in production; the lab's stand-in is + `deploy/containerlab/resources/fabric-api/pki/pki.yaml`. +3. **The `FabricQuery` CRD** (`fabricqueries.galactic.datumapis.com`). Infra owns + its lifecycle in every cell. `config/fabric-api/crd/` is a copy for the lab and + tests only; do not apply it where infra manages the CRD. +4. **A per-cell `fabric-api` ConfigMap** in `galactic-system` (see + [Per-cell ConfigMap](#step-2-per-cell-configmap)). +5. **A federation path that delivers `FabricQuery` objects** to the cell, pinned + to its member cluster. That is NSO and Karmada's work and is out of scope here. + +### Why certificates are issued in a separate pod + +A `csi.cert-manager.io` volume blocks its pod until the certificate is issued. +The driver's `continueOnNotReady` setting does not change that: it covers only the +driver's own readiness gates. With a broken Issuer a lab test showed +`MountVolume.SetUp` waiting ("Referenced issuer does not have Ready condition") +and a `fabric-router` pod stuck in `PodInitializing` with FRR down. So the +sidecar's certificate does not come from a volume in the `fabric-router` pod: + +- The Component adds a DaemonSet, `fabric-api-certs`, with the same placement as + `fabric-router` and no API token. It runs `fabric-api certsync`, which copies + `tls.crt`, `tls.key` and `ca.crt` from its csi volume (`fabric-api-csi`) to the + node's tmpfs directory `/run/fabric-api/tls` every 10 seconds. It validates the + key pair first and replaces each file atomically. +- The `fabric-router` pod mounts `/run/fabric-api/tls` read-only as a hostPath of + type `DirectoryOrCreate`, which never blocks the pod. +- A broken Issuer therefore stalls only the `fabric-api-certs` pod (it waits in + `ContainerCreating`). The sidecar reports no credentials and fails closed; + routing is unaffected. When the Issuer is repaired the sidecar picks the + certificate up without a restart. + +`task verify:fabric-api-bootstrap` in `deploy/containerlab/` is the lab's check of +this property. + +## Deployment + +### Step 1: cell-wide RBAC and ServiceAccounts + +```sh +kubectl apply -k config/fabric-api/ +``` + +This applies only `serviceaccount.yaml` and `rbac.yaml`: the `fabric-api-gateway` +and `fabric-api-janitor` ServiceAccounts, and their roles. It is safe and +idempotent in any cell. + +| Identity | Scope | Permissions | +| -------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------ | +| `fabric-api-gateway` | Cluster | `fabricqueries`: get, list, watch. `fabricqueries/status`: get, update, patch. `nodes`: get (node selectors) | +| `fabric-api-gateway` | `galactic-system` | `pods`: get, list, watch. `leases`: get, list, watch, create, update, patch. `events`: create, patch | +| `fabric-api-janitor` | Cluster | `fabricqueries`: list, delete | + +The gateway cannot edit a spec, create or delete a query, or touch FRR's +ConfigMaps. Delete access is deliberately a separate identity. + +### Step 2: per-cell ConfigMap + +```yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: fabric-api + namespace: galactic-system +data: + site: dfw + cell: dfw + cluster-name: dfw +``` + +| Key | Used by | Meaning | +| -------------- | ------------- | ------------------------------------------------------------------------------------------------------------- | +| `site` | node, gateway | The location this cell serves. The gateway executes only `FabricQuery` objects whose `spec.site` equals it | +| `cell` | node, gateway | The cell name in every mTLS identity. Must equal the `CELL_NAME` in the certificates' URI SANs | +| `cluster-name` | gateway | This cell's Karmada member cluster name. The gateway executes only objects whose `spec.clusterName` equals it | + +The gateway's Deployment references all three keys as required, so it will not +start without the ConfigMap. The node sidecar references `site` and `cell` as +optional: without `cell` it stays up, logs an error, serves only metrics and +reports diagnostics unavailable, so a missing ConfigMap never crash-loops a +container in the `fabric-router` pod. Container environment is fixed at start, so +creating the ConfigMap after the Component is rolled out means recreating the +pods, which restarts FRR. Create it first. + +### Step 3: the gateway and janitor + +`config/fabric-api/base/` holds the gateway Deployment, its ClusterIP Service, a +PodDisruptionBudget (`minAvailable: 1`) and the janitor CronJob. It is not applied +by anything by default because it needs per-cell values: the ConfigMap above and +the cell name in the gateway certificate's URI SAN. Instantiate it from a per-cell +overlay (compare `deploy/containerlab/resources/fabric-api/gateway/dfw/`): + +```yaml +# overlays//gateway/kustomization.yaml +namespace: galactic-system +resources: + - ../../../config/fabric-api/base +configMapGenerator: + - name: fabric-api + literals: + - site=dfw + - cell=dfw + - cluster-name=dfw +generatorOptions: + disableNameSuffixHash: true +patches: + - target: + kind: Deployment + name: fabric-api-gateway + patch: |- + - op: replace + path: /spec/template/spec/volumes/0/csi/volumeAttributes/csi.cert-manager.io~1uri-sans + value: spiffe://fabric-api.datumapis.com/cell/dfw/gateway +``` + +Adjust the relative path to `config/fabric-api/base`. `disableNameSuffixHash` +matters: the pods reference the ConfigMap by the fixed name `fabric-api`. + +The base pins `ghcr.io/datum-cloud/fabric-api` at a tag the release pipeline +stamps. Override it from an overlay's `images:` stanza. The gateway runs as UID +65532 with a read-only root filesystem and no capabilities, requests 20m CPU and +64Mi memory, and limits memory to 512Mi. + +### Step 4: the node sidecar Component, as a canary + +Add the Component to an overlay of `config/fabric-router` and replace +`CELL_NAME` in the URI SAN of the `fabric-api-certs` DaemonSet's csi volume: + +```yaml +# overlays//fabric-router/kustomization.yaml +resources: + - ../../../config/fabric-router +components: + - ../../../config/fabric-router/components/fabric-api +patches: + - path: fabric-api-cell-patch.yaml +``` + +```yaml +# overlays//fabric-router/fabric-api-cell-patch.yaml +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: fabric-api-certs +spec: + template: + spec: + volumes: + - name: fabric-api-csi + csi: + driver: csi.cert-manager.io + volumeAttributes: + csi.cert-manager.io/uri-sans: spiffe://fabric-api.datumapis.com/cell/dfw/ns/${POD_NAMESPACE}/pod/${POD_NAME} +``` + +`fabric-router` still needs its own per-node `fabric-router.` +ConfigMaps as usual (see `AGENTS.md`). The Component does not create the cell +ConfigMap, the Issuer or the CRD. Applying it adds the `fabric-api-certs` DaemonSet and recreates every `fabric-router` pod +and restarts FRR; follow [Rollout](operations.md#rollout). + +What the Component changes in the pod: + +- Adds the `fabric-api` container (`args: [node]`) with ports `fabric-api`/9344 + and `api-metrics`/9345, 10m CPU and 64Mi memory requested, a 768Mi memory limit + and `GOMEMLIMIT=640MiB` (the search index holds a copy of bgpd's selected routes; + see [Search index](configuration.md#search-index)). + It has no readiness, liveness or startup probe, on purpose. +- Mounts FRR's `/run/frr` read-only and the node's `/run/fabric-api/tls` (a + hostPath, filled by `fabric-api-certs`) at `/var/run/fabric-api/tls` read-only. +- Runs the container as UID 0, GID 102 (`frrvty`), dropping every capability and + adding only `NET_RAW`, with a read-only root filesystem and no privilege + escalation. Raw ICMP sockets need `NET_RAW` in the effective set, which a + non-root container cannot get; without `CAP_DAC_OVERRIDE` it reaches FRR's + `0770 frr:frrvty` sockets through group 102. +- Sets `automountServiceAccountToken: false` on the pod and adds a projected + token volume mounted only into `frr-init` and `config-agent`, the containers + that call the Kubernetes API. The sidecar has no API access unless it runs + with `--probe-permits`, which no manifest sets yet (see + [Enabling aggregate probe budgets](operations.md#enabling-aggregate-probe-budgets)). + +The `fabric-api-certs` DaemonSet runs the same image with `args: [certsync, ...]`, +tolerates every taint, avoids control-plane nodes and requires the same +`galactic.datumapis.com/fabric` label values as `fabric-router`. It runs as root +(to write the root-owned node directory) with every capability dropped, a +read-only root filesystem, 5m CPU and 16Mi memory requested and a 64Mi limit. + +### Lab + +In `deploy/containerlab/`: `task build:fabric-api` builds the image, +`task deploy:cert-manager` installs cert-manager and the csi-driver in every +cluster (the csi-driver must run on every fabric node before `deploy:fabric`), and `task deploy:fabric-api` installs the CRD copy, RBAC, a stand-in PKI, +the gateway and the janitor. `task deploy` does all of them in the right order +(`deploy:cert-manager` before `deploy:fabric`, `deploy:fabric-api` last). In the +lab each site is one cell whose cell, site and member cluster name are all the site +name. Each site's fabric-router overlay creates that site's `fabric-api` +ConfigMap, so it lands with the node sidecars in `deploy:fabric`, ahead of their +start. `task verify:fabric-api` (which first runs +`task verify:fabric-api-config`, a check that the overlays render it) and +`task verify:fabric-api-bootstrap` are the checks. diff --git a/docs/fabric-api/load-test.md b/docs/fabric-api/load-test.md index 4e3ab41e1..b8f974661 100644 --- a/docs/fabric-api/load-test.md +++ b/docs/fabric-api/load-test.md @@ -1,15 +1,6 @@ -# fabric-api Full-Table Load Test +# Run the fabric-api full-table load test -This page records the load test that gates AS-path, community and large-community -searches (plan step 8), how to run it, and what it found. The result decided the -search design: answering searches with FRR's own table scans fails the gate, and -the BMP-fed index in the sidecar passes it. For the design see -[docs/agents/ARCHITECTURE-FABRIC-API.md](../agents/ARCHITECTURE-FABRIC-API.md); for -operating it see [configuration.md](configuration.md#search-index). - -> Last verified: 2026-10-07 against `hack/fabric-api-loadtest/main.go` and the -> `test:fabric-api-load` task in `Taskfile.yaml`. The numbers below are from runs in -> a Docker lab on one machine, not from real fabric routers. +The harness checks whether diagnostics disturb routing and whether indexed searches agree with FRR. Run it against a candidate release before enabling expensive queries on real fabric routers. The [October 7 measurements](../archive/benchmarks/fabric-api-2026-10-07.md) explain the choice of a BMP-fed index; they are historical evidence, not a fresh capacity measurement. ## Purpose @@ -40,7 +31,7 @@ test. A configuration passes when, with full IPv4 and IPv6 Internet tables: The harness is `hack/fabric-api-loadtest` (Go). It needs Docker and about 4 GiB of memory, and removes its containers and network on exit. -- **Router.** FRR 10.7.1 (`quay.io/frrouting/frr:10.7.1`, the production release) in +- **Router.** FRR 10.7.1 (`quay.io/frrouting/frr:10.7.1`, the harness default at the time of the recorded measurement) in Docker, with bgpd and zebra. - **Feeder.** A GoBGP container injects the best paths of RouteViews MRT RIB dumps over one IPv4 and one IPv6 eBGP session. One pass per address family, with the @@ -87,67 +78,36 @@ go to the harness: | `--keep` | `false` | Leave the containers running | | `--search-source` | `index` | The sidecar's `--search-source`: `index` or `frr` | -Run A below is `--search-source=frr`; run B is the default. - -## Results +In the [archived measurements](../archive/benchmarks/fabric-api-2026-10-07.md), Run A uses `--search-source=frr`; Run B uses the default index. -### Run A: direct FRR scans (`--search-source=frr`), IPv4 only - -1,126,600 prefixes (`route-views2` has no IPv6). +## Status of searches -| Phase | bgpd CPU | Query latency and outcomes | bgpd RSS | Unplanned drops | -| ----------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | --------------- | -| baseline | | Convergence after `clear bgp *`: 41.5 s | | | -| cheap | 98.4 CPU-s (82% of a core) | `RouteLookup` n=266,593, p50 2 ms, p99 4 ms, max 15 ms. `BGPSummary` n=265,614, p50 2 ms, p99 4 ms | 1034 to 1087 MiB | 0 | -| expensive | 120.9 CPU-s (101%) | `ASPath` n=246: NodeBusy 219, OK 21, ResponseTooLarge 6; p95 3.0 s, p99 3.9 s, max 4.8 s. `Community` n=240: NodeBusy 196, OK 31, ResponseTooLarge 13; p99 3.6 s. `LargeCommunity` n=255: NodeBusy 212, OK 43; p99 4.2 s. `RouteLookup` p50 657 ms, p99 4.3 s. `BGPSummary` p50 661 ms, p99 4.2 s | flat | 0 | -| expensive + reset | 133.8 CPU-s (112%) | Convergence under load: 2 m 10.0 s, 3.1 times the idle 41.5 s. `RouteLookup` p50 1.13 s, p99 5.6 s | | 0 | +Searches remain off by default (`--enable-expensive-queries`). Enabling them is an +infra rollout step, taken after staging confirms these numbers on real fabric +routers, and it requires each node's `frr.conf` to stream its Loc-RIB to the sidecar +(see [configuration.md](configuration.md#search-index)). The containerlab lab +enables them, and `task verify:fabric-api` checks searches against FRR's own answer. -**Conclusion: fails the gate.** bgpd's main thread saturates under searches, cheap -queries that were 2 ms become seconds, convergence after a reset takes 3.1 times -longer, and a `ResponseTooLarge` answer still costs bgpd the whole scan. No sessions -dropped and memory stayed flat, but the convergence and starvation results rule out -enabling direct scans. +## Moved sections -### Run B: BMP-fed index (default), IPv4 and IPv6 +These anchors keep older bookmarks working. Use the focused guides linked above for new references. -1,126,600 IPv4 and 263,799 IPv6 prefixes. + -**Index build and footprint.** After the sidecar started, the index synced in 29.2 s, -costing bgpd 23.4 CPU-s once. It held 212,524 distinct attribute sets. The sidecar's -RSS was about 430 MB (Go heap in use about 370 MB); bgpd's RSS about 1.5 GB. +[fabric api load test evidence 2026 10 07](../archive/benchmarks/fabric-api-2026-10-07.md#fabric-api-load-test-evidence-2026-10-07). -**Consistency.** 40 search targets (9 AS-path, 7 community and 4 large-community -targets, each for both families): the index's match counts equalled FRR's own -best-path matches for all 40. + -| Phase | bgpd CPU | Query latency and outcomes | Unplanned drops | -| ----------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | -| baseline | | Convergence after `clear bgp *`: 41.7 s | | -| cheap | 107 CPU-s (89% of a core) | `RouteLookup` n=212,655, p50 2 ms, p99 22 ms. `BGPSummary` n=212,686, p50 1 ms, p99 22 ms | 0 | -| expensive | 3.0 CPU-s (2%) | `ASPath` OK 201 (NodeBusy 5,344), p99 515 ms, max 715 ms. `Community` OK 219, p99 90 ms. `LargeCommunity` OK 192, p99 77 ms. `RouteLookup` p99 3 ms. `BGPSummary` p99 2 ms. bgpd RSS flat | 0 | -| expensive + reset | 34.1 CPU-s (28%, the reconvergence itself) | Convergence under load: 43.7 s, +5% over the idle 41.7 s. `ASPath` p99 920 ms. `RouteLookup` p99 186 ms | 0 | +[results](../archive/benchmarks/fabric-api-2026-10-07.md#results). -The `NodeBusy` count for `ASPath` is the node's own budget at work: it runs one -search at a time with no queue, and 8 workers keep asking. + -**Conclusion: passes** every criterion of the gate above: zero drops, convergence -within 10% of idle (+5%), no bgpd memory growth, and answers equal to FRR's -best-path answers. Searches cost bgpd nothing beyond the one-time -index build (23.4 CPU-s) and the BMP stream. +[run a direct frr scans search sourcefrr ipv4 only](../archive/benchmarks/fabric-api-2026-10-07.md#run-a-direct-frr-scans---search-sourcefrr-ipv4-only). -### Reading the numbers + -- Cheap-query throughput in the cheap phase, about 1,700 to 2,200 queries per second - per node, far exceeds what the gateway's 8 cell slots and NSO's rate limits allow - to reach a node, so cheap queries are not a capacity concern. -- The runs measure one router in a Docker lab on one machine. They do not measure - real fabric routers, real peer counts, or concurrent exporter and config-agent - activity. +[run b bmp fed index default ipv4 and ipv6](../archive/benchmarks/fabric-api-2026-10-07.md#run-b-bmp-fed-index-default-ipv4-and-ipv6). -## Status of searches + -Searches remain off by default (`--enable-expensive-queries`). Enabling them is an -infra rollout step, taken after staging confirms these numbers on real fabric -routers, and it requires each node's `frr.conf` to stream its Loc-RIB to the sidecar -(see [configuration.md](configuration.md#search-index)). The containerlab lab -enables them, and `task verify:fabric-api` checks searches against FRR's own answer. +[reading the numbers](../archive/benchmarks/fabric-api-2026-10-07.md#reading-the-numbers). diff --git a/docs/fabric-api/operations.md b/docs/fabric-api/operations.md new file mode 100644 index 000000000..2a7939a3b --- /dev/null +++ b/docs/fabric-api/operations.md @@ -0,0 +1,182 @@ +# Operate fabric-api + +Use this guide after [deployment](deployment.md). Sidecar image changes recreate the fabric-router pod and restart FRR, so follow the routing rollout procedure below. Certificate rotation is described in [security](security.md). + +## Observability + +Scrape config and alert rules are in `config/monitoring/` (not part of +`config/kustomization.yaml`; they need the Prometheus Operator CRDs): + +- The `fabric-router` PodMonitor's `api-metrics` endpoint scrapes the sidecar's + port 9345 as `job="fabric-api-node"`, with a `node` label. A pod without the port + yields no target. +- `podmonitor-fabric-api-gateway.yaml` scrapes the gateway's port 9347 as + `job="fabric-api-gateway"`. +- 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 | + +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 +infra's copy; change the rules here, with their tests, then update infra's copy. + +Node metrics (port 9345, a private registry with Go and process collectors): +`fabric_api_node_requests_total{type,outcome}`, +`fabric_api_node_request_duration_seconds{type}`, +`fabric_api_node_response_bytes{type}`, +`fabric_api_node_truncated_responses_total{type}`, +`fabric_api_node_in_flight_requests`, +`fabric_api_node_duplicate_requests_total`, +`fabric_api_node_duplicate_cache_entries`, +`fabric_api_node_diagnostics_available`, +`fabric_api_node_frr_info{version,supported}`, +`fabric_api_node_expensive_breaker_open`, +`fabric_api_node_probe_packets_total`, +`fabric_api_node_identity_refreshes_total{outcome}`, +`fabric_api_certificate_expiry_timestamp_seconds` and +`fabric_api_credentials_loaded`. + +Gateway metrics (port 9347, on controller-runtime's registry, so its own metrics +appear too): `fabric_api_gateway_queries_total{type,reason}`, +`fabric_api_gateway_node_outcomes_total{outcome}`, +`fabric_api_gateway_node_rpc_duration_seconds{type,code}`, +`fabric_api_gateway_queue_depth`, `fabric_api_gateway_status_writes_total{kind,outcome}`, +`fabric_api_gateway_status_bytes`, `fabric_api_gateway_truncated_results_total`, +`fabric_api_gateway_stage_latency_seconds{stage}` (`receipt`, `execution`, +`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. + +## Rollout + +The `fabric-api` sidecar lives in the `fabric-router` pod, and `/run/frr` stays a +pod-scoped `emptyDir` so FRR's sockets are never exposed beyond the pod. The cost +is that changing the sidecar's tag, flags or the Component itself changes the +DaemonSet's pod template, and the rolling update recreates the whole pod, FRR +included. **A sidecar release is a routing rollout.** + +1. **Do the prerequisites first**, outside the pods: cert-manager with its + csi-driver on every fabric node, the Issuer, the cell ConfigMap and the CRD. Roll out the + gateway and janitor first; they do not touch `fabric-router`. +2. **Canary one node.** Stage the change so only one node's pod is recreated + first, however your delivery system stages a DaemonSet change (the per-node + overlays used for `galactic-gateway` pin an instance to one node; the same idea + applies). Do not let the first change reach every node at once. +3. **Check underlay sessions and convergence** on the canary: every `frr_bgp_peer_state` + for the node back to Established for both families (frr-exporter on port 9342), + no `FabricBGPSessionDown` or `FabricBGPPrefixesDropped`, and `fabric-router` Ready. + Shallow daemon liveness is not a convergence gate. Then check the looking glass: + `fabric_api_node_diagnostics_available` 1, `fabric_api_credentials_loaded` 1, and + a direct `fabric-api query --info`. +4. **Pace the expansion**, one site or a small batch at a time, repeating step 3. + Stop on any session loss. +5. **Roll back** by restoring the previous tag or removing the Component from the + overlay; that is another rolling restart, so pace it the same way. Probe success + is not evidence of routing health. + +Keep the gateway's and the sidecar's tags in step. They are the same image, and +this repository does not test a gateway and sidecars at different versions. The +publish pipeline stamps one tag into both `config/fabric-api/base` and the +Component. + +A failing sidecar must not gate any of this, and a certificate that cannot be issued +stalls only the `fabric-api-certs` pod. If a `fabric-api-certs` pod hangs in +`ContainerCreating`, the csi-driver is missing on that node or the Issuer cannot +issue; the node then shows `NoCertificatePod` to the gateway. A `fabric-router` pod +that hangs on `fabric-api-tls` should not occur, since that is a hostPath; check the +Component's patch. If the sidecar runs but reports diagnostics +unavailable, FRR and the underlay are unaffected; read `unavailableReason`. + +### Enabling aggregate probe budgets + +The deployment manifests do not set the [aggregate probe budget](configuration.md#aggregate-probe-budgets) 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. +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 + routing rollout. + +Roll back in the reverse order. Removing `--aggregate-budgets` while nodes still +require permits refuses every gateway probe (`LimiterUnavailable`). + +## Verifying + +```sh +# Per node (lab): ASN, router ID, both address families' sessions, exact and +# longest-match lookups with zebra evidence, operator probes, then each gateway +# and a FabricQuery end to end. +cd deploy/containerlab && task verify:fabric-api + +# Disruptive: break the Issuer, recreate one fabric-router pod, check FRR and the +# underlay come up with diagnostics unavailable, then repair the Issuer. +cd deploy/containerlab && task verify:fabric-api-bootstrap +``` + +In a real cell, read the same facts from the cluster: + +```sh +kubectl -n galactic-system get pods -l app.kubernetes.io/name=fabric-router \ + -o custom-columns=NODE:.spec.nodeName,POD:.metadata.name,READY:.status.containerStatuses[*].ready +kubectl -n galactic-system logs deploy/fabric-api-gateway | grep -i "fabric query" +kubectl get fabricqueries -A # short name: fq +``` + +## Troubleshooting + +| Symptom | Likely cause and where to look | +| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `fabric-api-certs` pod stuck in `ContainerCreating` | csi-driver not installed or not on this node, or the Issuer cannot issue. FRR is unaffected; the node reports no credentials and the gateway omits it as `NoCertificatePod` | +| `unavailableReason` starts with `credentials:` | Issuer missing or not ready, `certsync` has not copied files yet, or `CELL_NAME` in the `fabric-api-certs` volume is not the ConfigMap's `cell`; check the certs pod and the sidecar's log | +| `unavailableReason` is `FRRVersionUnsupported` | FRR is not 10.7; ship a fabric-api that supports the new release before the `fabric-router` image | +| `unavailableReason` is `FRRUnavailable` | `bgpd.vty`/`zebra.vty` not reachable: FRR restarting, or the container lacks group 102 | +| Sidecar logs "fabric-api node is not configured" | `CELL` is empty: the ConfigMap or its `cell` key is missing. Fix it and recreate the pod | +| Gateway pod `CreateContainerConfigError` | The `fabric-api` ConfigMap or one of `site`, `cell`, `cluster-name` is missing | +| `FabricQuery` stays untouched | `spec.site` or `spec.clusterName` does not equal this gateway's; or this replica is not the leader | +| `NodeUnreachable` for every node | Gateway cannot reach `hostIP:9344` (host firewall) or the TLS handshake fails; check identities and cell values | +| `Unauthorized` | The caller's role may not make this call: a node identity cannot call anything, and a gateway identity may call only the debug `Query` | +| `DestinationNotAllowed` on a ping | Public policy applied; a direct node call with an operator identity may carry `--operator-allow-prefixes` in the lab | +| `ProbeSourceUnavailable` | No probe source for that family; see [Source](security.md#source) | +| `QueryTypeUnavailable` | Expensive types are gated, or the breaker is open after a timed-out scan | +| `NodeBusy` | Node or cell budget full; expensive and probe budgets have no queue | +| `ResponseTooLarge` | FRR's answer exceeded 4 MiB, or did not fit the node's budget even when shaped; see `FabricAPIResultsOversized` | +| `DuplicateConflict` | A request ID was reused with different arguments | + +For the typed codes carried in results, see [api.md](api.md#error-codes). diff --git a/docs/fabric-api/security.md b/docs/fabric-api/security.md new file mode 100644 index 000000000..f49cccc48 --- /dev/null +++ b/docs/fabric-api/security.md @@ -0,0 +1,218 @@ +# fabric-api identities and probe policy + +This reference defines authentication, certificate rotation and which probe addresses are permitted. Start with [deployment](deployment.md) before provisioning credentials. + +## Identities and certificates + +Every certificate carries exactly one URI SAN in the trust domain +`fabric-api.datumapis.com`: + +| Identity | URI SAN | Issued to | Key usages | +| -------- | ------------------------------------------------------------------------ | ----------------------------------------- | ------------------------- | +| gateway | `spiffe://fabric-api.datumapis.com/cell//gateway` | The gateway Deployment (both replicas) | `client auth,server auth` | +| node | `spiffe://fabric-api.datumapis.com/cell//ns//pod/` | Each node's `fabric-api-certs` pod | `server auth` | +| operator | `spiffe://fabric-api.datumapis.com/cell//operator/` | A person or tool calling directly | `client auth` | +| service | `spiffe://fabric-api.datumapis.com/cell//service/` | The customer-facing Looking Glass service | `client auth` | + +The node identity names a **pod**, not the node: the csi-driver can template a +pod's name and namespace (`${POD_NAME}`, `${POD_NAMESPACE}`) but not its node's +name. That pod is the node's `fabric-api-certs` pod, not the `fabric-router` pod +the sidecar runs in. The gateway maps each node to its newest Running +`fabric-api-certs` pod (selected by `--certs-selector`, default +`app.kubernetes.io/name=fabric-api-certs`), records it in +`status.nodes[].certificatePod`, and dials accepting only the identities of +that node's certs pods: the newest one, and any it is replacing, since a sidecar +keeps presenting a replaced pod's certificate until the new one reaches it. A +node with no running certs pod is omitted with reason `NoCertificatePod`. The +sidecar does not know that pod's name, so it accepts any node identity in its own +cell and namespace as its own; the gateway's pinning is what ties a certificate to +a node. Each path segment must be a lower-case DNS-label-like string (`[a-z0-9]`, +with `.` and `-` inside). + +How an identity is checked: + +- TLS 1.3 minimum, mutual. The server requires a client certificate and the + client accepts only a server proving the identity it expected. +- The chain is verified against the trust bundle current at handshake time, with + the right key usage, and the identity's **cell must equal this process's own + cell**. +- A process refuses to load a certificate whose identity is not its own (for + the sidecar: any node identity in its cell and namespace), is not valid now, or does not chain to the bundle it shipped with. +- At the handshake a node accepts only gateway and operator identities. Per RPC, a + gateway or operator may call the node's `Execute` and `Info`; on the gateway's + debug service an operator may call `Query` and `ListNodes`, and the gateway + identity may call only `Query` (the form in which a follower forwards to the + leader). Anything else is `Unauthorized`. +- The gateway also accepts node identities, which may call only its + `RequestPermit` and `ReleasePermit` (and the gateway identity, forwarding + them to the leader). The handler further requires the node identity's + namespace to be the gateway's `--namespace` and its pod to be a + `fabric-api-certs` pod on the node the call names. +- The gateway also accepts a service identity whose name is in + `--service-identities`. A service may call only the Looking Glass service's + `GetCapabilities` and `RunDiagnostic`, never `Query`, `ListNodes` or a node. + The gateway identity may call the gateway-only `ForwardDiagnostic`, with which + a follower hands a request to the leader; no other identity may. +- On every gateway RPC, unary or streaming, the gateway verifies the caller's + certificate again against its current bundle and clock, so a connection opened + by a certificate that has since expired, or whose CA has left the bundle, is + refused with `UNAUTHENTICATED`. A call's context ends when the caller's + certificate expires, after which a stream sends and receives nothing more. + Metadata keys starting `x-fabric-api-` are dropped from every call the + gateway identity did not make. + +The csi volume attributes in the `fabric-api-certs` DaemonSet (volume +`fabric-api-csi`) and the gateway Deployment: + +| Attribute | `fabric-api-certs` | Gateway | +| ---------------------------------- | -------------------------------------------------------- | ---------------------------- | +| `csi.cert-manager.io/issuer-name` | `fabric-api` | `fabric-api` | +| `csi.cert-manager.io/issuer-kind` | `Issuer` | `Issuer` | +| `csi.cert-manager.io/uri-sans` | `.../cell/CELL_NAME/ns/${POD_NAMESPACE}/pod/${POD_NAME}` | `.../cell/CELL_NAME/gateway` | +| `csi.cert-manager.io/key-usages` | `server auth` | `client auth,server auth` | +| `csi.cert-manager.io/duration` | `24h` | `24h` | +| `csi.cert-manager.io/renew-before` | `8h` | `8h` | +| `csi.cert-manager.io/fs-group` | not set | `65532` | + +`CELL_NAME` is a literal placeholder in both manifests that your overlay must +replace with the cell name (the same value as the ConfigMap's `cell` key). The +csi-driver cannot take it from a ConfigMap. A mismatch is not subtle: the process +rejects its own certificate (`certificate identity ... is not ...`), reports +credentials not loaded and fails closed. The files are `tls.crt`, `tls.key` and +`ca.crt`, read from `/var/run/fabric-api/tls` (`--tls-cert`, `--tls-key`, +`--tls-ca`). For the gateway that is its own csi volume; for the sidecar it is the +hostPath that `certsync` fills. + +### Operator certificates + +An operator certificate is a normal cert-manager `Certificate` from the same +`fabric-api` Issuer, for example the lab's: + +```yaml +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: fabric-api-operator + namespace: galactic-system +spec: + secretName: fabric-api-operator + duration: 24h + renewBefore: 8h + uris: + - spiffe://fabric-api.datumapis.com/cell/dfw/operator/alice + usages: + - digital signature + - client auth + privateKey: + algorithm: ECDSA + size: 256 + issuerRef: + name: fabric-api + kind: Issuer +``` + +An operator certificate can reach any node and the gateway in its cell, so treat +who may request one as an access decision. + +### Service certificates + +The customer-facing Looking Glass service gets one certificate per cell it calls, +from that cell's `fabric-api` Issuer, with URI SAN +`spiffe://fabric-api.datumapis.com/cell//service/` and usage +`client auth`, issued like an operator certificate. The gateway accepts it only +when `` is in its `--service-identities` list. The project and request +IDs in a `RunDiagnostic` request are trusted because that identity is +authenticated: issuing a service certificate grants the right to attribute +diagnostics to any project, so treat it as an access decision too. The +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](../designs/looking-glass-service.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. + +### Rotation + +Certificates last 24h and renew 8h before expiry. The csi-driver renews in place; for +the sidecar, `certsync` copies the new files to the node within 10 seconds. The +sidecar polls its files every 10 seconds, the gateway every 30, and each swaps in a new certificate, key and bundle without a +restart, and without touching FRR. A new set is accepted only if the certificate +matches the process's identity, is valid now and chains to the bundle delivered +with it. If it does not, the previous credentials stay in use until they expire. +With none loaded, every handshake fails closed, the process keeps running and +retrying, and routing is unaffected. + +| Situation | Behaviour | Signal | +| ---------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------- | +| Files missing or unreadable | Handshakes fail; warning logged every 30s | `fabric_api_credentials_loaded` 0; `FabricAPICredentialsMissing` after 15m | +| Renewal produces a bad certificate | The previous one keeps serving until its `notAfter`, then none | `fabric_api_certificate_expiry_timestamp_seconds` stops advancing | +| Certificate expires | Credentials cleared; handshakes fail closed | `FabricAPICertificateRenewalFailing` fires earlier, at under 4h left | +| Wrong cell, pod or role in the SAN | Certificate rejected at load | Warning in the log; credentials not loaded | + +**Rotating the CA.** A peer verifies the other side against its own current +bundle, so a leaf from a new CA is unusable by any peer that has not yet loaded a +bundle trusting that CA. Rotate with overlap, using a bundle that holds both +certificates (the loader accepts a multi-certificate `ca.crt`): + +1. Make every pod's `ca.crt` trust both the old and the new CA. +2. Wait until every node sidecar and the gateway have reloaded it (within 30 + seconds of the volume updating), confirmed by `fabric_api_credentials_loaded` 1 and + a fresh `fabric_api_certificate_expiry_timestamp_seconds` per pod. +3. Switch issuance to the new CA. Leaves renew within 24 hours and chain to it. +4. After every leaf from the old CA has been replaced (allow more than the 24h + duration), remove the old CA from the bundle. + +How step 1 is achieved depends on the issuer integration (infra owns it) and is +not exercised by this repository's lab; the code path that tolerates the overlap +is covered by `TestRotationWithOverlappingBundle`. + +## Probe sources and destinations + +### Source + +Probes use the default VRF and an explicit per-family fabric loopback address, and +never fall back to `127.0.0.1`, `::1`, an unspecified address or an unrelated +interface. For each family the sidecar uses, in order: + +1. `--probe-source-ipv4` or `--probe-source-ipv6`, if set. The value must parse and + be of the right family; a loopback or unspecified address makes startup fail. +2. Otherwise the single global unicast address of that family on + `--probe-source-interface` (default `lo`), ignoring loopback and link-local + addresses. +3. Otherwise none. A family with no source, or with more than one candidate on the + interface (the log says "several candidate probe sources; set one explicitly"), + answers `ProbeSourceUnavailable` for that family. A missing interface logs a + warning and disables auto-detection. + +`Info.probe_sources` lists the sources that resolved. If `lo` carries other global +addresses (VIPs, for instance), set the sources explicitly. + +### Destination + +A probe's destination is a numeric address pinned by NSO; the node validates it +again and never resolves names. Under the **public policy**, the one applied to +every call from the gateway identity, a destination is refused +(`DestinationNotAllowed`) if it is: + +- an IPv6 address outside `2000::/3` (global unicast), or +- in a special-use range: IPv4 `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, + `127.0.0.0/8`, `169.254.0.0/16`, `172.16.0.0/12`, `192.0.0.0/24`, `192.0.2.0/24`, + `192.31.196.0/24`, `192.52.193.0/24`, `192.88.99.0/24`, `192.168.0.0/16`, + `192.175.48.0/24`, `198.18.0.0/15`, `198.51.100.0/24`, `203.0.113.0/24`, + `224.0.0.0/4`, `240.0.0.0/4`; IPv6 `::/128`, `::1/128`, `::ffff:0:0/96`, + `64:ff9b::/96`, `64:ff9b:1::/48`, `100::/64`, `2001::/23`, `2001:db8::/32`, + `2002::/16`, `3fff::/20`, `5f00::/16` (SRv6 SIDs), `fc00::/7`, `fe80::/10`, + `ff00::/8`, or +- inside a range listed in `--deny-prefixes`: add your management and platform + ranges here. + +The **operator policy** applies to calls made directly to a node with an operator +identity. It is the public policy plus `--operator-allow-prefixes`, and an allowed +prefix bypasses every other rule, including `--deny-prefixes`. The lab uses it to +check cross-site reachability between fabric loopbacks (`10.255.255.0/24` and +`fc00::/32`). A node refuses to start with allow exceptions on the public policy, +and nothing enforces "never in production" except not setting the flag. Calls made +through the gateway's debug service carry the gateway's identity at the node, so +they get the public policy whoever the operator is. diff --git a/docs/fabric-api/service-contract.md b/docs/fabric-api/service-contract.md index 25c76cf27..aed699460 100644 --- a/docs/fabric-api/service-contract.md +++ b/docs/fabric-api/service-contract.md @@ -1,694 +1,59 @@ # Looking Glass backend service contract -Status: proposed implementation contract for [#1042](https://github.com/datum-cloud/galactic/issues/1042), -under [#1041](https://github.com/datum-cloud/galactic/issues/1041). -This document specifies required future behavior. It does not announce an -available API, validated capacity, or measured failure bound. Implementation is -tracked in #1043–#1047 and qualification in #1048; enabling customer execution -requires those gates. Baseline inspected: Galactic `6da52240`. +This document moved to [looking-glass-service](../designs/looking-glass-service.md). Update bookmarks to the maintained page. -The consumer and backend reviewers must approve this contract before dependent -milestones freeze their wire schema. Changes to the decisions below require a -contract update and corresponding acceptance cases, not undocumented defaults. + -## Scope and existing behavior +See [Scope and existing behavior](../designs/looking-glass-service.md#scope-and-existing-behavior). -Galactic executes bounded diagnostics in one cell's fabric-router network -context. The customer service owns authentication, project IAM, location -placement, session revocation detection, durable single-use claims, and delivery -to the customer. A project identifier received by Galactic is trusted -attribution from that service, not proof of the customer's permission. -Backend duplicate suppression cannot implement a durable single-use session. + -Reuse the four existing diagnostic implementations, discovery, and shared -executor. Keep node RPCs unary; stream completed router outcomes, not individual -traceroute hops. Existing operator `FabricGatewayService.Query/ListNodes`, node -`FabricService.Execute/Info`, and the [FabricQuery API](api.md) retain their wire -schemas and result meanings. FabricQuery retains its existing persistence and -resume semantics; customer requests have no such persistence or replay. +See [Service and identity](../designs/looking-glass-service.md#service-and-identity). -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 -"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`, -the leader enforces "Admission, execution, and aggregate accounting" below -(`internal/fabric/gateway/limit`, `gateway.Admission`, `gateway.Permits`), and -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`. -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 -discovery still return pod candidates, including duplicates. + -## Service and identity +See [Requests, capabilities, and results](../designs/looking-glass-service.md#requests-capabilities-and-results). -Publish a separate `fabric.service.v1` protobuf package at -`api/fabric/service/v1/service.proto`, with Go import -`go.datum.net/galactic/api/fabric/service/v1`. The intended service surface is: + -```proto -service LookingGlassService { - rpc GetCapabilities(GetCapabilitiesRequest) returns (GetCapabilitiesResponse); - rpc RunDiagnostic(RunDiagnosticRequest) returns (stream DiagnosticEvent); -} -``` +See [Stream grammar and coverage](../designs/looking-glass-service.md#stream-grammar-and-coverage). -This is a service declaration excerpt, not a compilable schema. The field -contract below is normative input to schema generation in #1044. Reuse the public -`fabric.v1.Observation`, `Query`, and `Budgets` messages; do not expose Go -`internal/` types or add streaming semantics to an existing unary method. + -Use the URI SAN -`spiffe://fabric-api.datumapis.com/cell//service/`. -Require the cell's trust bundle, valid certificate lifetime, exactly one -fabric-api identity, matching cell, and a configured service-name allowlist. -An authenticated service can call only these two methods. It cannot call -operator Query/ListNodes or node Execute/Info. Existing roles gain no direct -service-method permission. Apply authorization to unary and streaming RPCs, -including on reused TLS connections; cap a stream at certificate expiration. -Certificate rotation follows the existing reload/overlapping-CA mechanism. +See [Errors and retries](../designs/looking-glass-service.md#errors-and-retries). -A follower authenticates the original caller before forwarding once to the -leader over same-cell gateway mTLS. A separate gateway-only forwarding method -carries a typed envelope: original service URI, cell, project ID, request ID, -canonical request, original admission time, and absolute deadline. It is not a -customer-callable method. The leader validates the envelope, role, cell, -allowlist, and deadline again. Strip incoming forwarding metadata; never trust -caller-provided operator or service headers. Reject a second forwarding hop. -The gateway identity is a trusted deputy; compromise of that identity is outside -this isolation guarantee. Do not automatically retry a failed forward. + -## Requests, capabilities, and results +See [Admission, execution, and aggregate accounting](../designs/looking-glass-service.md#admission-execution-and-aggregate-accounting). -`GetCapabilitiesRequest` contains `cell` and `api_major=1`. Its response contains -`cell`, `api_major`, `contract_revision`, `enabled`, `policy_revision`, the four -operation/family combinations enabled by cell policy, required features, -effective limits from this document, and `generated_at`. It reveals no node -addresses or credentials. Cap it at 64 KiB, a 2 s deadline, 1 call/s with burst 2 -per authenticated service per replica, and 8 concurrent calls per replica. -The initial feature names are `router-outcomes`, `terminal-coverage`, and -`aggregate-probe-budgets`; all three are required to advertise an enabled v1 -service. `contract_revision` is the implementing release commit SHA and -`policy_revision` is the digest of effective service policy and limits. -`limits.admission` reports the cell's admission and packet budgets, present -only with `aggregate-probe-budgets`. A router failure refused by a limit -carries the same `scope` and `retry_delay` as a refused request. It does not probe routers or reserve -diagnostic capacity. Cache for at most 30 s. Capabilities advertise policy, not current router availability. Validate -again on execution; policy changes may reject a previously advertised request. + -`RunDiagnosticRequest` fields: +See [One cell authority and recovery](../designs/looking-glass-service.md#one-cell-authority-and-recovery). -| Field | Meaning and validation | -| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| `api_major` | Must be 1; incompatible majors fail before execution. | -| `cell` | Required; exact match with authenticated identity and serving cell. | -| `project_id` | Required opaque canonical project UID supplied by the service, ASCII `[A-Za-z0-9._:-]`, 1–128 bytes; not a project display name. | -| `request_id` | Required UUID identifying this backend attempt; unique within service, project, and cell. | -| `expires_at` | Required UTC timestamp; future and at most 120 s after first gateway receipt. Forwarding never extends it. | -| `query` | One supported operation, target, and address family as below. | -| `nodes` | Optional unique node names, at most 32; empty selects all eligible routers within the fan-out bound. Unknown names fail validation. | -| `budgets` | Optional lower response/path/community limits; values exceeding advertised limits fail validation. Zero selects advertised defaults. | -| `required_features` | Set of capability names needed by the caller; unknown or unsupported requirements fail before work. | + -Use the minimum of request expiration, transport deadline, and certificate -expiration. A client should supply a 30 s deadline unless it needs a longer -bounded allowance for discovery and delivery. There is no implicit deadline -extension. Reject -oversized/unknown enum inputs, controls, ambiguous identifiers, and unsupported -operations before reserving work. Normalize numeric targets exactly once and -pass the canonical value to nodes. Do not resolve DNS in the backend. +See [Charging and scheduling](../designs/looking-glass-service.md#charging-and-scheduling). -| Operation | Inputs | Successful observation | -| ----------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | -| RouteLookup | Bare IPv4/IPv6 address for longest match, or prefix with no host bits for exact match; family inferred or explicitly matching. | Router-local paths and separately sampled zebra installation; no matching route is a successful empty result. | -| BGPSummary | Empty target; explicit IPv4 or IPv6 family required. | Peer states and counters; a down peer is data. | -| Ping | Numeric unicast address, matching/inferred family; no hostname, zone, or IPv4-mapped IPv6 form. | Three ICMP echo attempts, source/destination, replies, loss and RTT. | -| Traceroute | Same target rules as Ping. | At most 20 hops, one ICMP probe per hop, source/destination, reached flag and hop observations. | + -Reject ASPath, Community, LargeCommunity, arbitrary commands, and caller-selected -probe sources. Ping/traceroute use at most 64 payload bytes per packet and a 1 s -reply wait. Apply the existing public destination policy at gateway and node: -special-use and deployment-denied platform/management ranges are forbidden; -IPv6 must be in the allowed global-unicast space. Operator allow exceptions -never apply to service traffic. Route visibility is independently gated by the -service's cell policy; project IAM and customer visibility decisions remain -upstream launch prerequisites, not inferred from certificate possession. +See [Alternate callers and node enforcement](../designs/looking-glass-service.md#alternate-callers-and-node-enforcement). -### Stream grammar and coverage + -Each event has `request_id`, consecutive `sequence` starting at 1, and exactly -one of `snapshot`, `outcome`, or `complete`. A stream has one snapshot first, -zero or more outcomes in completion order, and at most one complete last. -The server finishes a fully delivered stream with gRPC OK, including when its -terminal diagnostic result is partial or failed. Transport failure or missing -complete means incomplete delivery, never success inferred from EOF alone. +See [Initial defaults and hard bounds](../designs/looking-glass-service.md#initial-defaults-and-hard-bounds). -Before admission, take one logical discovery snapshot of the configured -fabric-router pod inventory in the cell. Record `snapshot_id`, `captured_at`, -and the list resourceVersion; certify identities from the corresponding cert -pod read. These reads are not an atomic Kubernetes multi-resource snapshot. -Do not refresh membership or substitute a replacement pod during the run. + -Group scheduled fabric-router pods by node name, including those without a -sidecar, usable address, running container, or certificate. Select one usable -pod per router deterministically: newest creation time, then pod name. Retain -other candidates only as diagnostic metadata; duplicate pods do not increase -expected coverage. Unscheduled pods have no router identity and are reported -in the snapshot field `unscheduled_pod_count` (zero when none). Nodes with no -fabric-router pod are outside -this inventory; coverage must not claim all physical routers in the cell. +See [Cancellation, delivery, and failure assumptions](../designs/looking-glass-service.md#cancellation-delivery-and-failure-assumptions). -Apply explicit `nodes` selection before the fan-out cap; otherwise use sorted -node names. The snapshot records every unique router as selected or omitted, -with a reason (`NotRequested`, `NoSidecar`, `PodTerminating`, `PodNotRunning`, -`SidecarNotRunning`, `NoHostIP`, `NoCertificatePod`, or `NodeBudget`). A selected -router includes its frozen pod UID. An explicit selection takes precedence: -routers outside it have reason `NotRequested`, regardless of their availability. -Do not expose dial addresses or certificate -pod names to the service. Cap the inventory at 256 unique routers and 64 KiB -serialized snapshot; fail with `InventoryTooLarge` rather than silently -truncating membership. This does not change legacy FabricQuery discovery. + -Let E be snapshot routers, S selected routers, and O omitted routers. -At terminal completion, every selected router has exactly one outcome: +See [Wire examples](../designs/looking-glass-service.md#wire-examples). -```text -E = S + O -S = successful + failed -E = successful + failed + omitted -``` + -Send the snapshot before dispatching node jobs. Reserve queue capacity first, -so failure to admit cannot produce an apparently admitted snapshot. If snapshot -delivery fails, release that capacity and dispatch nothing. Outcome sequence -reflects completion handoff order; simultaneous completions may appear in either -order, but a slow router must not delay a completed router. +See [Publication, compatibility, and rollout](../designs/looking-glass-service.md#publication-compatibility-and-rollout). -An outcome contains node name, frozen pod UID, completion time, and exactly one -observation or typed failure. An observation retains router ID, ASN, sample time, -duration, and its operation's result. Sample time is the start of that router's -read/probe, not the snapshot time; errors before sampling have no fabricated -sample time. Unreachable nodes and selected work canceled before dispatch are -failed, not omitted. A capability missing on a selected node is also a failure. + -`complete` repeats snapshot ID and counts, has `finished_at`, `truncated_routers`, -and a terminal reason: `Succeeded`, `PartialResults`, `ExecutionFailed`, -`NoNodesAvailable`, `DeadlineExceeded`, `Cancelled`, `OwnershipLost`, or -`OutputLimitExceeded`. Cancellation/deadline/ownership/output-limit reasons take -precedence. Otherwise no selected routers gives `NoNodesAvailable`; zero -successful gives `ExecutionFailed`; any failed or truncated result, or any -omission other than `NotRequested`, gives `PartialResults`; the remainder is -`Succeeded`. Keep `NotRequested` routers in expected and omitted counts: a -successful explicit subset can have nonzero omissions without claiming that -every router in the cell was queried. Empty inventory has all counts zero and -`NoNodesAvailable`. - -Packet loss, unreachable ICMP replies, and silent hops are successful diagnostic -observations. `truncated=true` also remains a successful observation, but warns -that its payload is incomplete. Zebra read errors retain their existing nested -installation error while the BGP observation stands. Neither truncation nor an -installation error may silently become an empty complete result. - -A connected client may receive synthesized cancellation failures and complete -while the deadline allows; a disconnected client cannot be promised either. -On an interrupted stream, preserve delivered observations, mark remaining -selected routers unknown to the consumer, and report only locally known counts. -Never fabricate the server's final coverage. There is no resume cursor or result -retrieval RPC. - -## Errors and retries - -Use `google.rpc.ErrorInfo` with domain `fabric-api.datumapis.com`. Its reason is -a stable machine-readable string; messages are sanitized and at most 256 bytes. -Router failures carry equivalent typed fields in their outcome. Errors must -not echo target addresses, credentials, or raw FRR text into routine logs. - -| Condition/reason | gRPC status before snapshot | Retry guidance | -| -------------------------------------------------------------------------- | ---------------------------------------- | ---------------------------------------------------------------- | -| Missing/invalid TLS identity | UNAUTHENTICATED or TLS handshake failure | Repair credentials; no automatic execution retry. | -| `Unauthorized` | PERMISSION_DENIED | Repair role, cell or policy. | -| `InvalidQuery`, `DestinationNotAllowed` | INVALID_ARGUMENT | Correct the request. | -| `VersionUnsupported`, `QueryTypeUnavailable`, `ServiceDisabled` | FAILED_PRECONDITION | Refresh capabilities/configuration. | -| `Throttled`, `QueueFull`, `NodeBusy` | RESOURCE_EXHAUSTED | Include RetryInfo; new authorized attempt only. | -| `InventoryTooLarge`, `ResponseTooLarge`, `OutputLimitExceeded` | RESOURCE_EXHAUSTED | Lower scope/output or change configuration; not a rate throttle. | -| `DuplicateRequest`, `DuplicateConflict` | ALREADY_EXISTS | Do not replay or treat this as a saved result. | -| `LimiterUnavailable`, `OwnershipLost`, `NodeUnreachable`, `FRRUnavailable` | UNAVAILABLE | Resolve availability; outcome may be unknown. | -| `DeadlineExceeded`, `QueueTimeout` | DEADLINE_EXCEEDED | No automatic retry. | -| `Cancelled` | CANCELLED | No automatic retry. | -| `ProbeSourceUnavailable`, `FRRVersionUnsupported` | FAILED_PRECONDITION | Repair node capability. | -| `MalformedResponse`, `Internal`, `ProbeFailed` | INTERNAL | Investigate backend; no automatic retry. | - -Existing node reasons, including `Timeout`, remain intact in router failures; -translate only the service-level deadline into `DeadlineExceeded`. After the -snapshot, operational failures should be outcomes/complete where delivery is -possible; the table's transport status applies when no stream can be delivered. -Unknown reasons must be rendered as backend failures, not packet loss. -`ResponseTooLarge` describes a single response that cannot fit its budget; -`OutputLimitExceeded` describes exhaustion of the service stream budget. -`OwnershipLost` and `OutputLimitExceeded` deliberately have both transport -status mappings and terminal stream reasons, depending on whether a complete -event can still be delivered. - -For throttling include `google.rpc.RetryInfo.retry_delay` and bounded ErrorInfo -metadata `scope` (cell/project/destination/queue) and `execution_started=false`. -Never include another project's identity or destination. Token shortage delay -is the maximum deficit/rate across depleted buckets, rounded up to milliseconds; -queue or concurrency refusal uses 1 s advisory delay. Recovery reports the -remaining recovery delay. Guidance is not a reservation or permission to retry. -A service may start a new attempt only under its own session/IAM policy, with a -new request ID and fresh charges. It must never replay an interrupted attempt. - -Disable application and configured gRPC retries/hedging for customer execution, -including the runner's existing cheap-read retry. No response bytes is not proof -that execution did not occur. The admission owner records the attempt key and -canonical argument digest until `expires_at + 2 s`; identical duplicates are -`DuplicateRequest`, changed arguments `DuplicateConflict`. Bound this cache at -4096 entries/2 MiB and fail closed when full; never evict live keys to admit more. -This volatile cache may be lost on restart. Node duplicate suppression is also -volatile and is an optimization only. - -## Admission, execution, and aggregate accounting - -### One cell authority and recovery - -Use the existing elected gateway as the single cell scheduler and limiter. -Followers forward; they never maintain independent execution buckets. Keep -bucket state in bounded leader memory, not Kubernetes session objects or a new -external datastore. Use an uncached election Lease read before each admission -and node dispatch to confirm holder UID/epoch and unexpired ownership. Define -epoch as Lease object UID plus the complete holderIdentity (including its unique -process-election suffix); recreating a Lease or acquiring it again must produce -a new epoch. Never reuse a previous holderIdentity after ownership uncertainty. Bound -that read to 1 s; any failure refuses new work and cancels active service work. -A stale cached leader boolean alone cannot authorize dispatch. - -Every process start, leadership acquisition, limiter-state loss, or return from -an uncertain ownership interval enters a **125 s recovery hold**, even on a new -cell. Do not restore work or carry queued customer requests across epochs. -At the end, require a fresh valid Lease read, initialize all buckets empty, and -refill from that instant. A key first seen later starts with at most -min(burst, rate × time since that instant); a safely evicted, fully refilled key -can be recreated full. Release of the old Lease does not waive the hold. -Changing limits also cancels service work and enters recovery; rolling updates -therefore have an explicit diagnostic availability cost. - -The hold exceeds the 120 s maximum request lifetime plus the combined 2 s -clock-skew and scheduling allowance. No prior-epoch request may be dispatched -with a new deadline. All bucket burst/rate ratios must be at most 120 s; then -the hold also clears the largest possible prior token debt. No traffic is -admitted by the authority during recovery, including aggregate-budget probes -from alternate interfaces. This conservative recovery is chosen over a durable -reservation datastore or independent replica buckets: it needs no new storage -service and avoids resetting available tokens at failover. Faster recovery -requires a separately reviewed durable accounting design. - -An old gateway isolated from the API cannot obtain new dispatch checks. Nodes -also validate the current epoch via an uncached Lease read before accepting a -probe permit; stale or unverifiable permits fail closed. Previously started -calls expire within the bounds below. A delayed old process must recheck its -absolute deadline and ownership before every dispatch. These rules, together -with the recovery hold, prevent simultaneous old/new-epoch execution. - -### Charging and scheduling - -Apply request admission token buckets after authentication and shape validation -but before discovery. First debit one cell and one project request token -atomically, then check/register the attempt key. A token-admitted duplicate -consumes both request tokens and returns `DuplicateRequest` or -`DuplicateConflict` without reserving node jobs or packets. Later validation, -discovery, or dispatch failures do not refund request tokens. If -either bucket is short, reject without debiting either; never go into negative -credit. Register the attempt key before discovery and before accepting jobs; -all later failures retain its tombstone through expiration. -Project buckets are keyed by canonical project UID across all authorized service -identities. Never use the common service account as the fairness key. - -After snapshot construction, admit all selected node jobs to the bounded shared -executor atomically or refuse the request. Charge one node-job unit per selected -router; omitted routers cost no node execution or packets. Maintain FIFO within -a principal and round robin between principal queues. A service request's -principal is its project UID, an operator's its identity name, and a -FabricQuery's `fabricquery//`: FabricQuery carries no -project UID, so a FabricQuery and a service request for the same project are -separate principals, sharing the executor and the cell and destination packet -budgets but not a fairness key or a project packet budget. A principal may -hold at most two node slots. -The shared executor has eight slots total. Keep the existing two-slot ceiling -for legacy expensive queries, which this service cannot submit. Queue admission -counts reserved snapshot-delivery slots toward the same limits. Live-stream -caps do not reserve node-job capacity: a second 32-router stream from a project -whose first stream still occupies its queue is refused with `QueueFull`. -FabricQuery work counts against its own principal's queue limit. - -Immediately before dispatch of each probe node job, atomically reserve its -worst-case packet count from cell, project (when present), and destination -buckets together. Charge Ping 3 and Traceroute 20. Insufficient credit fails -that selected router with `Throttled` without dispatching it. Never refund -unused, timed-out, rejected, canceled, or deduplicated attempts: conservatively -charged work must not become a retry bypass. A route read costs one node slot -and no packet credit. Three selected traceroute routers cost at most 60 packets; -32 cost at most 640. Actual early termination can only reduce that traffic. - -Destination keys are the canonical IPv4 /32 or IPv6 /128 **and** containing -IPv4 /24 or IPv6 /64. Charge both, independent of project and operation. Limits -are cell-wide, not global across cells. Rotating projects cannot evade them; -rotating hosts within one prefix still consumes its prefix budget. Avoid a -claim of global internet destination protection from a cell-local mechanism. - -Use bounded maps (4096 project keys, 16384 destination/prefix keys, 4 MiB total -bucket-state storage). A key may be discarded only when fully refilled: it then -holds no debt, and a key recreated later starts at no more than a full bucket. On capacity exhaustion reject new keys with -`LimiterUnavailable`; never evict debt. Persist no diagnostic payload in these -maps. Expose aggregate counts rather than key-valued metrics. - -### Alternate callers and node enforcement - -Cell and destination packet buckets include service, operator gateway, -FabricQuery, and direct operator-node probes. Each principal above has its own -packet bucket at the project rate: a service project, a FabricQuery source, or -an operator, whether through the gateway or directly; a direct probe is -charged only on a node running both `--probe-permits` and -`--require-probe-permits`. Every probe, including direct-node Execute, must obtain a -single-node, single-attempt permit from the active cell authority. For direct -operators, the node requests it on an authenticated node-only internal RPC; -the service has no access to that RPC. That admission uses the same executor -and global packet buckets. Keep a remote execution reservation until a node -acknowledges completion or its absolute expiry plus 2 s. Cancellation or a lost -RPC response alone must not free remote concurrency credit; otherwise repeated -disconnects could exceed the eight-job limit. This applies to gateway-originated -node calls too. Local RPC workers may exit immediately while a bounded timer -retains the reservation. Never wait indefinitely for a release callback. - -A permit binds epoch, request/attempt ID, node identity, canonical destination, -operation, packet allowance, and a deadline at most 30 s away. Carry permits -only on internal RPCs, authenticated by gateway mTLS; direct-node permit -responses are accepted only from that gateway. No caller-supplied permit -metadata is trusted. A node consumes a permit once and enforces its allowance -and deadline locally. Keep consumed permit IDs through expiry + 2 s in a -separate bounded set (4096 entries, 2 MiB); fail closed at capacity, never evict -a live permit to make room. The existing response-dedup cache is insufficient -because it can evict completed entries. After node restart or lost -permit-consumption state, -refuse permits for 32 s, then validate epoch and expiration before accepting -new ones; never reuse a surviving permit. Unsupported/old nodes fail closed -for aggregate-budget probes when the feature is enabled: a node reports -`probe_permits` in `Info` only when it enforces permits, and the gateway sends -a probe to no other node, failing that router with `QueryTypeUnavailable`. - -Keep the existing node-wide packet pacing and destination checks as additional -limits. Per-node pacing alone cannot substitute for aggregate charging. -Previously valid operator and FabricQuery probes can now be throttled, or refused -while the authority is unavailable; this is an intentional operational -compatibility change requiring rollout notice. Legacy wire schemas, observation -meanings, and direct operator destination exceptions remain unchanged. Legacy -reads need no packet permit. Do not silently exempt direct operator probes and -still advertise an aggregate ceiling. - -### Initial defaults and hard bounds - -Values below are proposed initial settings, subject to measured qualification. -Rates are tokens per second; packet rates count worst-case **reservations**, not -instantaneous emissions. Capacity reductions may be configured; increases -require boundary/load qualification. A changed configuration is rejected unless -all cross-field constraints hold. - -| Limit | Initial value / hard bound | -| ---------------------------------------------------- | ----------------------------------------------- | -| Service enabled | false until qualification and explicit opt-in | -| Request tokens, cell | 2/s, burst 8 | -| Request tokens, project | 0.2/s, burst 2 | -| Live service streams, cell / project | 16 / 2, including queued and draining streams | -| Shared active node jobs / per project | 8 / 2 | -| Shared queued node jobs / per project | 256 / 32 | -| Node job queue wait | 10 s, inside all existing deadlines | -| Selected routers / inventory routers | 32 / 256 | -| Packet tokens, cell | 100/s, burst 640 | -| Packet tokens, project or direct operator | 20/s, burst 640 | -| Packet tokens, destination host | 20/s, burst 640 | -| Packet tokens, destination prefix | 40/s, burst 640 | -| Maximum request lifetime / node queue plus execution | 120 s / 30 s | -| Request message / snapshot / complete | 64 KiB / 64 KiB / 64 KiB | -| Observation payload / full outcome event | 128 KiB / 144 KiB | -| Total serialized events per stream | 5 MiB, excluding transport framing | -| Buffered completed outcomes per stream | 2, at most 288 KiB | -| Blocked enqueue or network send | 2 s | -| Live attempt keys / storage | 4096 / 2 MiB | -| Bucket keys / storage | 4096 project + 16384 destination/prefix / 4 MiB | -| Error message | 256 bytes | -| Route paths / communities per path | 8 / 64 for each community kind | - -Check that each packet burst can fund at least one maximum-cost node job (20), -all rates are positive, burst/rate is at most 120 s, project caps do not exceed -cell caps, node time fits request lifetime, and output reserves cover the -maximum selected-router count. These defaults can fund 32 traceroute node -jobs, but the per-project slot -cap and 10 s queue deadline can produce failed outcomes even in a lightly -loaded cell. A fan-out ceiling is not a completion guarantee. Consumers should -select a smaller router subset when complete long-running probe coverage is -needed. Qualification must report this default behavior, not hide queue timeouts -as omitted routers or silently extend deadlines. - -For any reservation interval of length T, a bucket permits at most B + rT -packets. Dispatch-to-final-packet delay is bounded by 32 s under the failure -assumptions below. Therefore packets actually emitted in an arbitrary interval -of length T are bounded by **B + r(T + 32)**, also bounded by each node's local -pacer. For the destination-host default, a 1 s interval has an upper bound of -640 + 20 × 33 = 1300 packets across the cell. This is deliberately not a promise -of 20 packets in every wall-clock second. Qualification measures reservations -and emissions separately. A tighter instantaneous destination limit requires -central per-packet pacing and a revised contract. Because one node job -reserves and completes its packets within 32 s, the same envelope covers -failover: the 125 s quiet hold exceeds both emission delay and token debt. -Do not reset a node permit deadline on retries or transport reconnection. - -## Cancellation, delivery, and failure assumptions - -Deadlines cover discovery, admission, queueing, execution, and delivery. Freeze -each node deadline at enqueue: minimum of request expiration and now + 30 s; -its queue wait also ends at 10 s. When the queue timer expires first, emit -a router failure with reason `QueueTimeout`, not `QueueFull` or `Throttled`; -`QueueFull` is admission refusal before enqueue. If the enclosing request -deadline expires first or simultaneously, use `DeadlineExceeded` instead. -A permit may only shorten that deadline. -Stop scheduling and cancel node contexts on cancellation, stream failure, -shutdown, service disable, deadline, or loss of ownership. Disabling service -cancels existing service work and rejects new runs; legacy diagnostics remain -subject to their shared budgets and routing is unaffected. - -Release confirmed-complete execution credit before attempting result delivery; -retain uncertain remote reservations as described above. Bound completion queues; -if enqueue or send blocks for 2 s, cancel the request and close its stream. Do -not silently drop outcomes, spawn unbounded send goroutines, or keep executing -because a consumer stopped reading. Use a transport implementation that can -abort a blocked write; timing only the producer's select is insufficient. -Each selected node job may temporarily hold one 144 KiB encoded outcome during -handoff, even after releasing execution credit. Cap service job goroutines at -16 × 32 = 512, a conservative ceiling even when queue limits admit fewer: -at most 72 MiB of encoded producer payload plus 4.5 MiB in -completion queues. Require implementations to account for decoded protobuf -allocations separately and measure peak RSS; these are not total process RSS -bounds. Cap incoming diagnostic RPCs at 32 per replica, follower forwarding -streams at 16 per replica, and accepted service TLS connections at 64 per -replica. Admission occurs before spawning job goroutines. Bound transport -receive windows and read/write buffers to 64 KiB each per connection/stream, -with at most one writer per stream. Followers apply the same two-event buffer -and 2 s write bounds. Reject excess connections/RPCs rather than buffering them. -Snapshots and terminal records each have their own 64 KiB bound. -The 5 MiB stream cap is cumulative output, not an allocation target. -Reserve space for failure outcomes and complete; with these limits, -32 × 144 KiB + 2 × 64 KiB = 4736 KiB, below 5 MiB. If encoding still cannot fit, -cancel with `OutputLimitExceeded`; a transport failure still means incomplete -delivery. Diagnostic results never enter Kubernetes status or routine logs for -this service. Existing FabricQuery persistence is unaffected. - -The following are acceptance targets, not measured claims: - -| Trigger | Required bound and clock origin | -| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Explicit cancellation or healthy transport disconnect notification | Queued work removed and local workers/buffers released within 2 s of receipt; reachable node probes stop within 2 s. Uncertain remote credit lasts until expiry + 2 s. | -| Blocked client write or full result queue | Abort within 2 s of blocking; local cleanup within another 2 s. | -| Silent connection blackhole | Detect within 10 s using transport liveness; local cleanup within another 2 s. | -| Explicit ownership loss, API read failure, shutdown, service disable | Stop new service admissions/dispatches immediately on detection; reachable work canceled within 2 s. | -| Isolated node or unreachable cancellation channel | Last packet no later than node absolute deadline + 2 s skew/scheduling allowance; at most 32 s after its dispatch. | -| Queued job | Dispatch or fail within 10 s of enqueue, or earlier enclosing deadline. | -| Gateway paused/crashed without delivering cancellation | No new packet after the already-issued node deadline + 2 s; replacement admits nothing during its 125 s recovery hold. | - -Assume authenticated components are non-Byzantine, the Kubernetes API provides -consistent uncached Lease reads/CAS election, pairwise wall-clock skew is at -most 1 s, and runnable deadline checks execute within 1 s. Use monotonic timers -for local durations. Nodes recheck deadlines immediately before each send, -including after a process pause. Clock jumps beyond the assumption or an -unresponsive kernel invalidate a wall-clock guarantee; fail closed when clock -health is unknown, alarm, and record the qualification failure rather than -claiming the bound. The 2 s allowance includes skew plus scheduling delay. - -A lost node process sends nothing; a paused process must not resume sending -expired work. Cancelling an FRR socket read does not promise to cancel work -already running inside bgpd. The service permits only bounded route/summary -reads, never full-table searches; routing-impact qualification remains required. -Session revocation reaches Galactic only when its caller cancels; no bound here -includes upstream revocation detection or federation latency. - -## Wire examples - -The JSON below uses protobuf JSON field spelling for the `fabric.service.v1` -messages; timestamps and UUIDs are illustrative. The request and the mixed -result stream are fixtures in `api/fabric/service/v1/testdata`, beside a -capabilities response; the release bundle's build decodes them against its own -descriptor set, and a test decodes them with only the published packages. -A request received at 12:00:00 with the following expiration has 30 s remaining: - -```json -{ - "apiMajor": 1, - "cell": "example-cell", - "projectId": "project-a", - "requestId": "b74e19ee-926f-43dc-b03d-c29550a827ab", - "expiresAt": "2026-10-24T12:00:30Z", - "query": {"type": "QUERY_TYPE_PING", "target": "1.1.1.1", "addressFamily": "ADDRESS_FAMILY_IPV4"}, - "requiredFeatures": ["router-outcomes", "terminal-coverage"] -} -``` - -A request that also lists `aggregate-probe-budgets` is refused with -`VersionUnsupported` by a gateway that does not enforce aggregate probe budgets; -a v1 service is advertised as enabled only once all three features are served. - -A mixed result stream (one JSON object per protobuf event): - -```json -[ - {"requestId":"b74e19ee-926f-43dc-b03d-c29550a827ab","sequence":1,"snapshot":{"snapshotId":"snap-1","capturedAt":"2026-10-24T12:00:00Z","resourceVersion":"100","unscheduledPodCount":0,"routers":[{"node":"router-a","podUid":"pod-a","selected":true},{"node":"router-b","podUid":"pod-b","selected":true},{"node":"router-c","selected":false,"omittedReason":"NoCertificatePod"}]}}, - {"requestId":"b74e19ee-926f-43dc-b03d-c29550a827ab","sequence":2,"outcome":{"node":"router-a","podUid":"pod-a","completedAt":"2026-10-24T12:00:03Z","observation":{"node":"router-a","routerId":"192.0.2.1","asn":64512,"sampleTime":"2026-10-24T12:00:00Z","duration":"3s","ping":{"source":"192.0.2.1","destination":"1.1.1.1","sent":3,"received":0,"replies":[{"sequence":1,"timeout":true},{"sequence":2,"timeout":true},{"sequence":3,"timeout":true}]}}}}, - {"requestId":"b74e19ee-926f-43dc-b03d-c29550a827ab","sequence":3,"outcome":{"node":"router-b","podUid":"pod-b","completedAt":"2026-10-24T12:00:04Z","failure":{"reason":"NodeUnreachable","message":"Router did not answer"}}}, - {"requestId":"b74e19ee-926f-43dc-b03d-c29550a827ab","sequence":4,"complete":{"snapshotId":"snap-1","finishedAt":"2026-10-24T12:00:04Z","expected":3,"successful":1,"failed":1,"omitted":1,"truncatedRouters":0,"reason":"PartialResults"}} -] -``` - -Here 100% loss is one successful observation. If delivery stops after sequence -2, the consumer knows one success, one omission and one unresolved selected -router; it must not invent sequence 4 or retry router-b automatically. - -For a separate request selecting only router-a from the same three-router -inventory, mark router-b and router-c `NotRequested`, even if router-c has no -certificate. If router-a succeeds without truncation, the terminal coverage -fields are: - -```json -{ - "expected": 3, - "successful": 1, - "failed": 0, - "omitted": 2, - "truncatedRouters": 0, - "reason": "Succeeded" -} -``` - -This success describes the requested subset. If router-c was requested but -omitted for `NoCertificatePod`, the reason would instead be `PartialResults`. - -A pre-execution throttle uses a gRPC status with standard details: - -```json -{ - "code": 8, - "message": "Project admission budget exhausted", - "details": [ - {"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"Throttled","domain":"fabric-api.datumapis.com","metadata":{"scope":"project","execution_started":"false"}}, - {"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"5s"} - ] -} -``` - -## Publication, compatibility, and rollout - -#1044 publishes protobuf sources, their transitive imports, generated Go client -and server types, and a descriptor set with imports in a versioned Galactic -release asset named `fabric-service-api-.tar.gz`, containing `proto/` -sources and imports, `fabric-service-v1.pb` (descriptor set with imports), and -`README.md` with the matching Go module version and generation instructions. -Publish `SHA256SUMS` alongside it. The `publish-service-api` job of -`.github/workflows/publish.yaml` attaches both to each published release, and CI -builds and verifies the same bundle on every pull request; -`task build:service-api VERSION=` builds it locally. The `proto/` -directory omits the `google/protobuf` well-known types, which every protobuf -toolchain ships; the descriptor set includes them. Commit generated Go artifacts -using `task generate:proto`; never hand-edit them. Consumers pin a release tag -or commit of `go.datum.net/galactic`, import only `api/fabric/service/v1`, -`api/fabric/v1`, and standard protobuf/gRPC packages, or generate another -language client from the published descriptor/source bundle. No internal -canonicalizer, error parser, identity helper, or Kubernetes client is required -to call the service. The release must link these artifacts and their checksums. -The source path alone is not proof that this publication gate has passed. - -Within major v1, add optional fields/features only; reserve deleted field -numbers/names and never repurpose enums. Unknown optional fields are ignored; -unknown outcome reasons remain failures. A client requiring a new feature names -it in `required_features`; the server refuses if unavailable. An unknown event -variant prevents the client from claiming complete coverage. Breaking request, -identity, counting, or execution semantics require a new API major. Alpha -implementation must not advertise v1 capabilities until these rules pass. - -Roll out node permit support first, then gateway authority/streaming support, -then enable the aggregate budget policy for all probe paths, and finally opt in -service identities. Old nodes cannot be selected for service work; missing -permit support is an explicit capability failure. Keep customer execution off -through mixed-version qualification. A rollback disables service and cancels -active runs first; retain aggregate enforcement until probes are quiescent and -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. -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, -targets, or raw remote error text. Service disable affects diagnostics only. - -## Acceptance matrix and evidence - -Every row is required. #1042 supplies specifications and examples; later owners -supply executable tests and measured evidence. No row is satisfied by this -proposal, readiness checks, or skipped tests alone. - -| ID / owner | Scenario | Required evidence | -| ----------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -| A1 / #1043 | Valid service; missing, expired, wrong-role, wrong-cell credentials; rotated CA/cert | Only allowed same-cell service methods succeed, including reused connections and streams. | -| A2 / #1043 | Forged project/forward headers, direct forward RPC, second-hop forward | Rejected before execution; trusted typed attribution survives one authenticated forward. | -| A3 / #1044 | All four diagnostics and both supported families | Typed results decode with an independently built public-API client; no internal imports. | -| A4 / #1044 | One fast and one blocked router | Fast outcome delivered while the other is pending; one outcome per selected router. | -| A5 / #1044 | Duplicate pods, missing sidecar/cert, explicit subset, fan-out cap, empty inventory, >256 routers | Fixed membership and exact counts; successful explicit subsets retain NotRequested omissions; unscheduled pod count and overflow verified. | -| A6 / #1044 | Loss, silent hops, no route, truncated paths, zebra failure | Observations remain distinguishable from backend failure; truncation affects terminal reason. | -| A7 / #1044 | Old/new client, unsupported feature/enum/major | No accidental authorization or silent semantic downgrade; published descriptor fixtures decode. | -| A8 / #1045 | Bursts and sustained competing projects, including FabricQuery sharing a project | Measured admission/node-slot ceilings, FIFO/round robin progress, per-project caps, bounded queues. | -| A9 / #1045 | Ping/trace fan-out, mixed projects and addresses in one destination prefix | Reservations obey every B+rT envelope; actual emitted packets obey B+r(T+32); no refunds/retry bypass. | -| A10 / #1045 | Operator gateway, direct-node operator, FabricQuery and service probes combined | All contribute to aggregate cell/destination ceilings; direct exceptions do not bypass charging. | -| A11 / #1045 | Replica changes, lost buckets, saturated key maps, failed API reads | Single authority, 125 s hold, empty-bucket restart, no debt eviction, no unbounded fallback. | -| A12 / #1046 | Cancel during discovery/queue/execute; shutdown/disable; blackholed connection | Timings measured from specified triggers; no work continues past node deadline + 2 s. | -| A13 / #1046 | Consumer stops reading; maximum-sized outcomes on all streams | Send/enqueue aborts and resource release meet bounds; output/buffers/goroutines stay bounded. | -| A14 / #1046 | Old owner API-isolated or paused then resumed; node restart; forwarded stream lost | Expired/stale permits rejected, old work drains, no replacement replay or duplicate permit execution. | -| A15 / #1047 | Invalid limits, config changes, clock-health failure, logging/metrics capture | Invalid configuration refused; recovery applied; no payload leakage or unbounded metric labels. | -| A16 / #1048 | Legacy operator/FabricQuery regression and upgrade/rollback | Existing schemas/results remain usable; documented new probe throttling/availability behavior verified. | -| A17 / #1048 | Real routers, independent client, combined failure and load suite | Pinned artifacts, workload, clocks, limits, resource/packet captures and cleanup instructions permit reproduction. | - -Qualification records p50/p95/max delivery and cancellation times, peak RSS, -goroutines, queue depth, bytes buffered, emitted packet counts, and limiter -charges. Initial routing-impact gate: no diagnostic-induced BGP session reset -or route loss, and p95 convergence no more than 10% slower than an otherwise -identical no-diagnostics control over at least 20 controlled convergence trials. -Record baseline variability; inability to distinguish a 10% regression is -inconclusive, not a pass. A supported target platform must pass the failure -bounds above; changing a bound or gate requires an explicit contract revision. +See [Acceptance matrix and evidence](../designs/looking-glass-service.md#acceptance-matrix-and-evidence). diff --git a/docs/fabric-routing/README.md b/docs/fabric-routing/README.md new file mode 100644 index 000000000..abf5e47dd --- /dev/null +++ b/docs/fabric-routing/README.md @@ -0,0 +1,10 @@ +# Fabric routing + +The fabric routing controller compiles typed BGP resources into immutable FRR revisions. The node's config agent validates and activates released revisions. These components manage the underlay; galactic-router distributes tenant EVPN routes separately. + +- [Operating through the API](operations.md): installation, source transitions, releases, recovery, topology rollout and ConfigMap retirement. +- [Topology design](topology.md): endpoint records, generated sessions, ownership, cross-cell consistency, drain and remaining gaps. +- [Routing metrics](../observability/routing.md): fleet, node activation, FRR and tenant router series. +- [Node placement](../operations/node-labels.md): independent fabric and Galactic routing modes. + +Begin with the operating guide's prerequisites and install sequence. Enabling node activation or changing a sidecar recreates fabric-router pods and must be treated as a routing rollout. Endpoint records still need an authoritative author; topology generation does not allocate their addresses. diff --git a/docs/feature_reviews/egress-active-active_2026-10-09-resolution.md b/docs/feature_reviews/egress-active-active_2026-10-09-resolution.md index c3328cec7..6e1ccd96d 100644 --- a/docs/feature_reviews/egress-active-active_2026-10-09-resolution.md +++ b/docs/feature_reviews/egress-active-active_2026-10-09-resolution.md @@ -1,108 +1,31 @@ # Resolution: egress-active-active review (2026-10-09) -Resolution record for [egress-active-active_2026-10-09.md](egress-active-active_2026-10-09.md), -which reviewed `f61103b2`, `69ebb6cc` and `c8830ea9`. The review is kept as -written; this file records what was done about each finding and how it was -validated. +This document moved to [egress-active-active_2026-10-09-resolution](../archive/reviews/egress-active-active_2026-10-09-resolution.md). Update bookmarks to the maintained page. -## Findings + -| Finding | Status | Resolution | -| ---------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| F01 Disable after a failed refresh | Fixed | `egressGroup.refresh` returns `Refresh`'s error. Leaving hashed mode publishes every enabled group as `CLOSING` (forwarding, but CNI ADD writes no new sentinel), then converts, and disables only after a conversion that read and wrote every route without error and found no sentinel left, foreign-namespace sentinels included. CNI ADD re-reads the groups after writing its routes and rewrites them in ordered mode if they closed meanwhile, which closes the race with concurrent registration. | -| F04 Pool compatibility | Fixed | One shard group per translation class: NAT66 for `::/0`, one per NAT64 prefix (at most three in hashed mode; more is a startup error). A shard joins a class's group only if its status can translate it (IPv6 address; or IPv4 address and that `nat64Prefix`, or `translatesWellKnownPrefix` for `64:ff9b::/96`). Every sweep recomputes eligibility, so a shard that changes leaves. Ineligible shards are logged and exported (`pool_members{state="ineligible"}`); a class no shard serves gets no route and `GalacticEgressClassUnserved`. Single-family clusters keep working. | -| F05 Generation uniqueness | Fixed | Superseded by the F06 design: a group is published as one snapshot in one atomic swap, so a slot that failed to publish was never visible to a packet. Generations come from `next_slot_generation` in the published snapshot plus an in-process high-water mark that also counts failed publications; disable keeps the counter, restart resumes from it, 0 is never handed out. The review's A→B(failed)→C sequence is reproduced against the kernel at each of the three publication steps. | -| F06 Coherent BPF publication | Fixed | `egress_shard_group_table` and `egress_shard_table` (ARRAY maps updated in place) replaced by `egress_shard_groups`, an `ARRAY_OF_MAPS` whose slot holds one immutable snapshot: Maglev table and every member's SID, next hop, flags and generation. Publication creates a new inner map, fills it and swaps the outer slot in one update (an RCU pointer replacement; the old snapshot is freed after readers finish). The packet path reads everything from that one snapshot; one extra map lookup per grouped packet. The finding was confirmed on a kernel before the fix: updating a published value in place produced 17 torn packets out of 54,777; the snapshot swap produced 0 out of 49,011. | -| F02 Drain verification | Fixed | `verify-nat-active-active.sh` rewritten. Every probe requires every request to succeed, the capture to see every probe, and every source to be an expected masquerade address; silence fails. Fresh, never-pinned tenant addresses are added inside the tenant's network namespace, so drain and failure are checked under default pins. A self-test blackholes a fresh tenant and requires the probe to fail. Background downloads propagate failures; cleanup restores the environment, drain flags, ClusterRole, routes and addresses it found. | -| F03 Drain lifecycle documentation | Fixed | Docs and the new rollout checklist say: `spec.drain: true`, wait for sessions to end, then delete; deletion tears the shard down at once; a busy tenant can keep a shard draining indefinitely; pins off cannot preserve sessions. A terminating `EgressShard` is now excluded from the groups rather than treated as draining. No finalizer was added. | +See [Findings](../archive/reviews/egress-active-active_2026-10-09-resolution.md#findings). -## Additional recommendations + -| Recommendation | Resolution | -| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| CRD/schema prerequisite, RBAC, drain read-back | Documented in `docs/nat/configuration.md` (Prerequisites) and `docs/nat/active-active-rollout.md`; the lab check verifies all three. | -| Unique identities, translation compatibility, return routing | Documented as prerequisites; enforced for compatibility (F04); the lab preflight checks distinct SIDs and addresses and a return route to each from the transit. | -| NAT64 and TCP/UDP/ICMP coverage | The lab check covers TCP, UDP and ICMP over NAT66 and NAT64. | -| Default pins, addition, withdrawal, all down, restart, informer, rollback | Covered by the lab check (addition by a shard's re-origination), except addition of a third shard, which the lab topology cannot do; it is covered by the privileged datapath tests. | -| Prohibit route vs BGP | Lab stages are labelled; the real BGP stage removes the SID origination from the shard node's FRR. | -| Load, pins, replication, fragments | Documented in configuration.md (How a shard is chosen; Known constraints). | -| Cross-node placement | Confirmed: VRF table IDs are allocated per node (`vrf.nextFreeTableID`). Kept, and documented as a per-node guarantee: sessions, pins and reply SIDs are node-specific, so a stable cross-node identity would buy nothing. | -| Monitoring of zero candidates, informer failure, incompatibility, missing metrics | New control-loop series (`egress_mode`, `shard_watch_synced`, `group_routes`, `sweep_errors_total`) and alerts (`GalacticEgressClassUnserved`, `GalacticEgressShardWatchNotSynced`, `GalacticEgressSweepFailing`, `GalacticCNIMetricsDown`); `PoolEmpty` fires on zero candidates with routes; an unpublished node reports no pool series rather than zeros. | -| Central evaluator | Documented: repository rules are the tested source; infra must install them in its central evaluator. | -| Staging acceptance and rollback checklist | `docs/nat/active-active-rollout.md`. | +See [Additional recommendations](../archive/reviews/egress-active-active_2026-10-09-resolution.md#additional-recommendations). -## Compatibility + -- **Map layout.** The two pre-review group maps are gone; `egress_shard_groups` - and `egress_shard_group_template` are new. No map that existed before the - feature changes, so an upgrade from a release without it keeps every pinned - row. A node that ran a pre-review build of this branch (only the - containerlab lab) has the two obsolete pins removed at load; its groups are - rebuilt by the next sweep, and until then a route naming a group drops. -- **Rollback.** Unchanged in principle and now observable: switch to ordered - mode, wait for `galactic_cni_egress_group_routes` to read 0 on every node, - then roll back the image. -- **Older clang.** `egress_shard_group_template` exists because clang before - 21 emits the inner map value as a forward declaration. Generation was - checked with clang-18 (CI's compiler) and clang-19 (the image builder's). +See [Compatibility](../archive/reviews/egress-active-active_2026-10-09-resolution.md#compatibility). -## Validation + -Run on 2026-10-09 on a Fedora 44 host (kernel 7.1) against the containerlab -`gvpc` lab's dfw cluster. The lab is local and isolated; no staging or -production resource was touched. +See [Validation](../archive/reviews/egress-active-active_2026-10-09-resolution.md#validation). -| Check | Result | -| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `golangci-lint` (via `task ci`) | Passed, 0 issues. | -| `yamlfmt -lint` | Passed with a temporary config. `task ci`'s own yamlfmt step stops in a git worktree on `stat .git/**: not a directory`, a known worktree artifact; the remaining `ci` stages were then run directly. | -| `task build`, `task test:unit`, `task test:e2e` | Passed. The unprivileged unit run skips every root-gated test. | -| `task test:unit-root` (privileged, host clang 22) | Passed in two of three full runs. The third failed once in `internal/cnibgp` (`TestRegisterEBPFDatapath_RegistersAllThreeTables`: its test interface was not found), which then passed 3 of 3 alone and 5 of 5 as a package on this branch and on `origin/main`; that code is unchanged here. A later run reproduced it, with `internal/cni`'s `TestCmdCheckValidConfigMissingResources`, only while root packages ran in parallel; with `-p 1` every root-gated package passed, so these tests collide on host interfaces when run concurrently. Skipped: `TestReconcileRadvActors_FailedRemovalIsRetried`, as before. | -| Privileged datapath tests against clang-18 objects | Passed: the whole `prog` suite (verifier acceptance and the verifier-cost limit included) and every `TestGroupDatapath`/`TestGroupPublication` test, with objects built by clang-18, the CI compiler. Generation also checked with clang-19, the image builder's compiler. | -| Concurrent publication (`ConcurrentSwapsStayCoherent`) | 0 mixed packets of 122,312 across 400 swaps. A throwaway control that rewrote a published value in place produced 17 mixed of 54,777 (not committed: it is nondeterministic by nature). | -| `task test:alerts` | Passed: 32 rules, every rule test. | -| `verify:nat-active-active` (lab) | Passed all ten stages, including the real BGP withdrawal (withdrawal and re-origination each reached the group in about 2 s). An earlier run failed once in the drain stage when a fresh tenant got no answer; it was not reproduced by hand or in the next full run after the script's fresh-address allocation was made unique (it had reused a random byte across a subshell). The cause is not proven. | -| Upgrade on lab nodes | `galactic-cni` loaded the new maps beside every existing pin and removed the two obsolete ones on all three dfw nodes. | + -Not run: the privileged suite on the staging kernel version, any staging -acceptance step, adding a third shard in a live cluster (the lab has two per -site), and infra's central alert evaluation. +See [Remaining staging gates](../archive/reviews/egress-active-active_2026-10-09-resolution.md#remaining-staging-gates). -## Remaining staging gates + -1. Release the `network` change adding `spec.drain` (branch - `feat/egressshard-drain`, commit `36ee528`), install its CRD in staging, - and re-pin galactic's `go.mod` to the release. -2. infra: install the CNI RBAC, originate every shard's SID, IPv6 and IPv4 - addresses from its own node with a distinct IPv4 per shard, copy the - `galactic-cni-egress` rule group to the central evaluator, and write the - runbook anchors for the seven egress alerts. -3. Run `docs/nat/active-active-rollout.md` in staging, including the - privileged CI job on the staging kernel version. +See [Risks](../archive/reviews/egress-active-active_2026-10-09-resolution.md#risks). -## Risks + -- One extra map lookup per grouped packet, and a new inner map per change to - a group (about 2.4 KiB, freed after RCU); a flapping shard costs a - publication per change. -- A busy tenant keeps a draining shard in use indefinitely; draining needs an - operator decision on how long to wait. -- The cause of the one unreproduced drain-stage lab failure is unknown. - -## Re-review findings - -[egress-active-active_2026-10-09_rereview.md](egress-active-active_2026-10-09_rereview.md) -reviewed an intermediate state of the fixes above. Status of its findings -against the code as committed: - -| Finding | Status | Notes | -| ---------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| R01 Closing does not exclude in-flight CNI writes | Partial | CNI ADD re-reads the groups after writing and rewrites its routes in ordered mode if they closed. Every ordered-mode sweep also moves any route still naming a group back to the static list, so a late write is repaired within one sweep (30s), dropping that VRF's egress meanwhile. There is no cross-process barrier, so `group_routes` reading 0 can precede such a write by one sweep. | -| R02 Empty hashed membership restores static shard routes | Open | With no class served, a hashed sweep refreshes without groups and moves routes back to the first resolvable static SID, bypassing readiness and translation checks. | -| R03 Unserved NAT64 prefix falls through to the NAT66 route | Open | CNI ADD skips a configured NAT64 prefix with no eligible shard, so longest-prefix match sends it to the NAT66 group's `::/0` route. | -| R04 Fresh-address counter lost in subshells | Fixed | The counter is kept in a state file, and a failed address add ends the run. | -| R05 Group IDs reused when the prefix list changes | Open | Group IDs are positions in `GALACTIC_CNI_NAT64_PREFIX`; removing or reordering a prefix republishes a group that existing routes still name for a different class. | -| R06 BGP stage withdraws only one route source | Not borne out | The stage removes only the FRR origination, and the shard was reported unreachable within about 2s on every passing run: the compute resolver did not resolve the SID through the EVPN plain route. The stage does not separately assert the compute FIB lookup. | - -R02, R03 and R05 affect hashed mode only and block enabling it; ordered mode, -the default, does not read the groups. +See [Re-review findings](../archive/reviews/egress-active-active_2026-10-09-resolution.md#re-review-findings). diff --git a/docs/feature_reviews/egress-active-active_2026-10-09.md b/docs/feature_reviews/egress-active-active_2026-10-09.md index 9b1b90c1f..2527cface 100644 --- a/docs/feature_reviews/egress-active-active_2026-10-09.md +++ b/docs/feature_reviews/egress-active-active_2026-10-09.md @@ -1,246 +1,95 @@ # Architecture Review: egress-active-active -**Language:** go | **Reviewed:** 2026-10-09T20:36:23.650844+00:00 -## Summary +This document moved to [egress-active-active_2026-10-09](../archive/reviews/egress-active-active_2026-10-09.md). Update bookmarks to the maintained page. -Not ready for staging enablement signoff: fix rollback and shard-state publication defects, enforce pool compatibility, and complete privileged validation. + -**6 findings:** 🔴 0 critical 🟠 3 high 🟡 3 medium ⚪ 0 low +See [Summary](../archive/reviews/egress-active-active_2026-10-09.md#summary). + -**Scope:** `f61103b2`, `69ebb6cc`, `c8830ea9` (`HEAD~3..HEAD`). Working tree was clean when review began. No earlier report exists in this directory. Review covers implementation, added tests, configuration, monitoring, docs and lab verification. No staging resources were changed. +See [Validation evidence](../archive/reviews/egress-active-active_2026-10-09.md#validation-evidence). -**Decision:** Hold staging enablement signoff. The feature can proceed to an isolated validation environment after the high-priority fixes; this review does not certify the live staging environment or current CI run. Changes are opt-in and the deployment manifest still defaults to ordered mode. Estimated remediation is **medium**, principally because coherent BPF publication needs design and kernel validation. + -### Validation evidence +See [Staging acceptance gates](../archive/reviews/egress-active-active_2026-10-09.md#staging-acceptance-gates). -| Check | Result and limit | -| --- | --- | -| `task build:ebpf` | Passed; all four datapaths regenerated, including both BPF endiannesses. Compilation does not prove kernel verifier acceptance. | -| `go build ./cmd/...` | Passed (exit 0); emitted a nonfatal warning about a read-only module stat cache. | -| `bin/golangci-lint run --timeout 5m` | Passed: `0 issues.` | -| Focused `go test -race -count=1 -v` | `egressroutemap`, `attachreg`, `metrics` passed. Root-gated cases skipped, including **all seven new TestGroupDatapath tests**. | -| Config and added installer tests | Passed. The full installer suite encountered sandbox restrictions on TCP/netlink sockets; this is not evidence of an application regression or a passing full suite. | -| Focused `go vet` | Passed for config, installer, egressroutemap, attachreg and metrics. | -| Failure-injection reproduction | Confirmed F05 in a temporary fake-map test: A starts at generation 1; replacing with B writes slot generation 2 but group publication fails; replacing with C also gets generation 2. Test removed after execution; source implementation unchanged. | -| Shell syntax; diff whitespace | `bash -n` and `git diff --check HEAD~3 HEAD` passed. | -| YAML formatter | Could not complete: `stat .git/**: not a directory` in this worktree. | -| Privileged BPF, containerlab, alert tests, full CI | Not completed. Docker socket access denied and review runs unprivileged. No promtool executable available. | -| Remote CI status | Unverified: GitHub API connection failed. | -| Live staging CRD, routing, scrape health and image availability | Unverified; no live staging evidence obtained. | + -Logs from this review are in `/tmp/galactic-review-{datapath-tests,reproductions,lint,build}.log` for this workspace session. +See [Architecture](../archive/reviews/egress-active-active_2026-10-09.md#architecture). -### Staging acceptance gates + -1. Fix F01 and F05 with iterator/write failure-injection tests. Resolve F06 with an explicit publication/snapshot contract and concurrency coverage. For F04, enforce compatible pool membership; a tightly controlled initial staging trial can also explicitly verify homogeneous shards, but this does not fix general admission behavior. -2. Install and verify the external `EgressShard` CRD version supporting `spec.drain` (the Go dependency now points to network commit `36ee528904ff`). A Go module bump does not update a cluster's schema. Verify a drain patch persists by reading it back. Confirm the updated CNI get/list/watch RBAC is deployed. Document these prerequisites in the rollout procedure. -3. Verify every candidate has unique advertised SID and masquerade addresses, supports the required NAT66/NAT64 families, and agrees on NAT64 prefix/well-known-prefix behavior. Test return routing through **each** shard before distributing tenants. -4. Require a green `task ci`, the separate privileged `task test:unit-root` job on the target kernel, and `task test:alerts`. Fix F02 before treating `verify:nat-active-active` as an acceptance gate. -5. Run a two-shard staging canary using `hashed`, `source`, the default `2h4m` pin idle, and pool minimum `2`. Exercise NAT66 **and NAT64**, TCP/UDP/ICMP, large packets and sustained sessions. The added lab script uses only IPv6 HTTP/NAT66; its flow phase uses pins off and its source phase uses 20 seconds, so it does not establish all default-mode behavior. -6. Check shard addition, actual BGP route withdrawal and restoration, explicit drain, CNI restart with existing pins, initial informer delay/API outage, all shards unavailable, and concurrent membership changes. A prohibit route validates local selection failure, not full BGP failure detection timing. Confirm sessions on a surviving shard continue; sessions on a failed shard are expected to break because NAT state is not replicated. -7. Verify the existing CNI PodMonitor produces `job="galactic-cni"` and correct node labels, the new rules are installed in the actual evaluator (infra centrally evaluates its own copy), and targets scrape successfully. Confirm active/minimum, per-shard traffic and drop counters. Do not interpret absent series as health. -8. Rehearse rollback: preserve the static SID list in the init-container configuration, switch to ordered on the new binary, verify no sentinel routes remain and the group is disabled, then roll back the binary. Mode changes can break sessions placed on a different shard. Delete only **after explicit drain and session quiescence**, not as the drain operation. +See [Findings](../archive/reviews/egress-active-active_2026-10-09.md#findings). -## Architecture + -**Layers observed:** environment configuration → installer informer and netlink watch → egress shard group reconciliation → BPF map adapters → Prometheus collectors +See [🔴 P0 — Critical](../archive/reviews/egress-active-active_2026-10-09.md#-p0--critical). -**Dependency direction:** clean + -``` -EgressShard informer + netlink events -> debounced installer sweep -> shard maps + per-VRF route maps -> datapath -``` +See [🟠 P1 — High](../archive/reviews/egress-active-active_2026-10-09.md#-p1--high). -Reviewed the combined HEAD~3..HEAD change (33 files, 4,237 insertions and 161 deletions), surrounding CNI/NAT controller, resolver, loader, CI and deployment contracts. Dependency direction is coherent. See validation and staging gates below for limits of the evidence. + -## Findings +See [[F01] Do not disable the group after a failed ordered-mode refresh](../archive/reviews/egress-active-active_2026-10-09.md#f01-do-not-disable-the-group-after-a-failed-ordered-mode-refresh). -### 🔴 P0 — Critical + -No P0 findings. +See [[F04] Validate shard translation compatibility before adding it to the pool](../archive/reviews/egress-active-active_2026-10-09.md#f04-validate-shard-translation-compatibility-before-adding-it-to-the-pool). -### 🟠 P1 — High + -#### [F01] Do not disable the group after a failed ordered-mode refresh -**Location:** `internal/installer/egressgroup.go:175-179` | **Category:** error-handling +See [[F05] Reserve slot generations across failed group publication](../archive/reviews/egress-active-active_2026-10-09.md#f05-reserve-slot-generations-across-failed-group-publication). -**Problem:** g.refresh logs and discards Refresh's error, returning partial counters. Refresh decides all sentinel rewrites first and increments Ungrouped, leaving InGroup zero when every destination resolves. If iteration or any subsequent Put fails, some/all sentinel routes remain but ordered sweep still disables their group. This violates the promised rollback ordering. + -**Risk:** Switching hashed to ordered during a transient map write/read failure drops all packets on the unconverted VRFs until a later successful sweep; sustained error makes the outage persistent. +See [🟡 P2 — Medium](../archive/reviews/egress-active-active_2026-10-09.md#-p2--medium). -**Before:** -``` -result := g.refresh(table, foreignTableIDs, g.staticSIDs) -if result.InGroup == 0 { groups.Disable(egressroutemap.ClusterShardGroup) } -``` -**After:** -``` -result, err := g.refresh(table, foreignTableIDs, g.staticSIDs) -if err == nil && result.InGroup == 0 { groups.Disable(egressroutemap.ClusterShardGroup) } -``` + -#### [F04] Validate shard translation compatibility before adding it to the pool -**Location:** `internal/installer/egressgroup.go:310-326` | **Category:** config +See [[F02] Require successful new-tenant egress in the drain check](../archive/reviews/egress-active-active_2026-10-09.md#f02-require-successful-new-tenant-egress-in-the-drain-check). -**Problem:** Candidate selection accepts every Ready+Programmed SID without checking status.shardAddressIPv6, status.shardAddressIPv4, or status.nat64Prefix. The API/controller legitimately allows shards serving only one family; identityFromSpec only requires at least one masquerade address (egressshard_controller.go:394-397). Both default NAT66 and NAT64 routes now use this same pool. Adding a Ready NAT66-only shard therefore directs a fraction of NAT64 requests to a shard unable to translate them; a different NAT64 prefix has the same defect. Ordered mode could explicitly select compatible shards, but hashed mode silently broadens to every shard. + -**Risk:** Partial deterministic tenant egress outage when a cluster contains valid but heterogeneous shards, including incremental rollout of an incompletely configured second shard. +See [[F03] Remove the claim that deleting a shard gracefully drains it](../archive/reviews/egress-active-active_2026-10-09.md#f03-remove-the-claim-that-deleting-a-shard-gracefully-drains-it). -**Before:** -``` -if shard.Status.ShardSID == "" || !Programmed || !Ready { continue } -candidates = append(candidates, ShardCandidate{SID: sid, Draining: ...}) -``` -**After:** -``` -Validate each candidate against the compute node's required NAT66/NAT64 families and NAT64 prefix; reject incompatible pool configuration with a surfaced error, or maintain eligible groups per translation route. -``` + -#### [F05] Reserve slot generations across failed group publication -**Location:** `internal/plumbing/ebpf/egressroutemap/shardgroup.go:291,356-361` | **Category:** concurrency +See [[F06] Read a coherent shard snapshot during concurrent map updates](../archive/reviews/egress-active-active_2026-10-09.md#f06-read-a-coherent-shard-snapshot-during-concurrent-map-updates). -**Problem:** A new slot receives current group generation + 1, but slots are written before the group generation is committed. If the group Put fails, the changed slot is already visible to packets through the old Maglev table. Another candidate replacement before the next successful group publication receives the same generation. Pins created for the first replacement are then accepted for the second. The documented never-reused identity guarantee is false on partial failure. + -**Risk:** A pin can silently follow an unrelated shard after partial reconciliation; draining replacements can inherit live pins and existing sessions can move unexpectedly. +See [⚪ P3 — Low](../archive/reviews/egress-active-active_2026-10-09.md#-p3--low). -**Before:** -``` -nextGeneration := current.Generation + 1 -value.Generation = nextGeneration -// write slots, then group; return on failure -``` -**After:** -``` -Allocate identities from durable monotonic state that includes partially published slots, and preserve uniqueness through retries and slot clearing. Add failure-injection tests across every write boundary. -``` + -### 🟡 P2 — Medium +See [What's Working Well](../archive/reviews/egress-active-active_2026-10-09.md#whats-working-well). -#### [F02] Require successful new-tenant egress in the drain check -**Location:** `deploy/containerlab/scripts/verify-nat-active-active.sh:224-231` | **Category:** testing + -**Problem:** The drain test only rejects observed packets on the drained shard. sources suppresses curl/tcpdump errors, and an empty capture produces seen=[]; the loop executes zero times and announces success. A regression blackholing all unpinned tenants during drain therefore passes this stage, while the existing A connection alone is checked for success. +See [Refactor Plan](../archive/reviews/egress-active-active_2026-10-09.md#refactor-plan). -**Risk:** The advertised end-to-end staging gate can certify broken drain behavior. + -**Before:** -``` -mapfile -t seen < <(sources "${t}" 3) -for addr in "${seen[@]}"; do ...; done -echo "ok ..." -``` -**After:** -``` -Require successful requests and exactly one captured source, matching the surviving shard's expected masquerade address, before reporting success. -``` +See [Step 1: Preserve refresh errors through rollback](../archive/reviews/egress-active-active_2026-10-09.md#step-1-preserve-refresh-errors-through-rollback). -#### [F03] Remove the claim that deleting a shard gracefully drains it -**Location:** `docs/nat/configuration.md:517-518` | **Category:** config + -**Problem:** The new operator guide says deleting EgressShard drains it like spec.drain. EgressShardReconciler has no finalizer, withdraws advertisement on deletion (internal/controller/egressshard_controller.go:167-185), and excludes terminating shards from syncNode at line 220. Translation is cleared immediately rather than retained until sessions drain. Merely marking a terminating object as a draining candidate cannot change this lifecycle. +See [Step 2: Make shard publication and identity retry-safe](../archive/reviews/egress-active-active_2026-10-09.md#step-2-make-shard-publication-and-identity-retry-safe). -**Risk:** An operator using deletion as documented interrupts every session on that shard. + -**Before:** -``` -Deleting an EgressShard drains it the same way for as long as it takes to go. -``` -**After:** -``` -Set spec.drain=true, wait for sessions to reach zero, then delete. Deleting without this sequence immediately tears down the shard and its sessions. -``` +See [Step 3: Enforce compatible translation identities](../archive/reviews/egress-active-active_2026-10-09.md#step-3-enforce-compatible-translation-identities). -#### [F06] Read a coherent shard snapshot during concurrent map updates -**Location:** `internal/plumbing/ebpf/prog/usid.c:1212-1228,3673-3680,3712-3736` | **Category:** concurrency + -**Problem:** The group and shard maps are ordinary BPF ARRAY maps. Userspace updates modify the existing value in place, while the packet program retains pointers and reads flags/generation separately from SID, ifindex and MACs. A slot or next-hop update can interleave after validation but before route copying, so a packet can validate one identity and encapsulate with a different or mixed record. Ordered writes between maps do not make an individual array record atomic. +See [Step 4: Make drain verification fail on absence of traffic](../archive/reviews/egress-active-active_2026-10-09.md#step-4-make-drain-verification-fail-on-absence-of-traffic). -**Risk:** Transient packet loss or incorrect encapsulation during membership and next-hop changes. Existing sequential BPF_PROG_RUN tests cannot establish concurrency safety. This is source-supported, not reproduced on a kernel in this review. + -**Before:** -``` -shard = bpf_map_lookup_elem(...); // validate flags/generation -... -memcpy(route.sid, shard->sid, ...); route.link_ifindex = shard->link_ifindex; -``` -**After:** -``` -Publish immutable/versioned records or use a supported synchronization scheme that copies and validates one consistent snapshot; stress updates concurrently with real packet processing. -``` +See [Step 5: Correct deletion procedure](../archive/reviews/egress-active-active_2026-10-09.md#step-5-correct-deletion-procedure). -### ⚪ P3 — Low + -No P3 findings. - -## What's Working Well - -- Configuration validates mode, hash, pin timeout, and minimum at startup rather than silently falling back. -- Unsynced informer state is distinguished from an empty candidate set. -- Informer and netlink events feed a bounded debounced sweep; periodic ticker backs up event delivery. -- Egress route sweeps preserve sidecar-owned namespace state. -- Docs explicitly require switching to ordered before rolling back to a binary predating group sentinels. -- New read-only EgressShard RBAC is scoped by resource and informer namespace. -- Metrics expose active/draining/unreachable state and selection outcomes; existing CNI PodMonitor is present. -- Added installer helper tests and config tests pass; verification script passes bash syntax check. -- go vet ./internal/config ./internal/installer passes. - -## Refactor Plan - -Each step is independently mergeable and must not break existing behavior. - -### Step 1: Preserve refresh errors through rollback -*Addresses: F01* - -**What:** Return the error from g.refresh and only disable groups after a complete successful conversion; add failure-injection coverage for iterator and route Put errors. - -**Why now:** Rollback reliability is a staging safety prerequisite. - -**Safe when:** Failed conversion leaves group enabled and old sentinel routes usable; successful retry converts routes then disables it. - -### Step 2: Make shard publication and identity retry-safe -*Addresses: F05, F06* - -**What:** Preserve unique slot identities through partial writes and implement coherent datapath snapshots. - -**Why now:** Pin continuity depends on stable identity and consistent route reads. - -**Safe when:** Fault injection cannot reuse identity, and concurrent packet/update stress shows no mixed route or invalid pin acceptance. - -### Step 3: Enforce compatible translation identities -*Addresses: F04* - -**What:** Validate status families and NAT64 prefix against local egress requirements before pool admission, with explicit error reporting and mixed-pool tests. - -**Why now:** Ready alone does not mean the shard can serve every route moved to the common pool. - -**Safe when:** A NAT66-only or differently prefixed shard cannot receive NAT64 traffic it does not support. - -### Step 4: Make drain verification fail on absence of traffic -*Addresses: F02* - -**What:** Check request success and require the expected surviving source address. - -**Why now:** Readiness evidence must detect drops as well as wrong placement. - -**Safe when:** A blackholed fresh tenant makes the script fail; a healthy surviving shard passes. - -### Step 5: Correct deletion procedure -*Addresses: F03* - -**What:** Document explicit drain, session wait, then delete; remove unsupported graceful-delete claim. - -**Why now:** Operators need accurate lifecycle guidance before first staging rollout. - -**Safe when:** Runbook matches reconciler lifecycle and no longer treats delete as graceful. - -## Additional constraints and coverage observations - -- Source placement is address-based, not load-aware. Roughly equal address counts do not imply equal byte rates when tenants vary in traffic volume. -- Pins are local to a compute node and bounded by a 65,536-entry LRU. Eviction after a membership change can move an active address; drain can persist indefinitely if an address keeps sending. This is not replicated NAT session state. -- Hash input includes the node-local Linux VRF table ID. `internal/plumbing/vrf/vrf.go` allocates these locally, so identical Maglev member sets alone do not guarantee the same placement for a VPC address on different compute nodes. Workload migration continuity needs separate validation; no cross-node pin transfer is implemented. -- Flow-mode fragment placement is tested for IPv4 in the selector, but existing NAT translation explicitly lacks full fragment handling. Do not advertise end-to-end fragment support based on the selector test. -- Current new installer tests cover candidate filtering, event matching and kick coalescing, not informer startup, actual sweep sequencing, partial failures or mode-transition races. Datapath tests are sequential; they do not test userspace/kernel update interleavings. -- The group-empty alert intentionally requires at least one member. A zero-candidate pool with existing sentinels instead relies on below-minimum or traffic-driven drop alerts. An informer that never initializes can leave enabled=0, suppressing the pool alerts; verify desired mode and startup logs separately. - -For F06, the kernel documents that array lookup returns a pointer into shared array storage and requires synchronization for concurrent access: [Linux BPF array-map documentation](https://docs.kernel.org/bpf/map_array.html). `array_map_update_elem` copies into the existing element unless locking is explicitly requested: [Linux array-map implementation](https://github.com/torvalds/linux/blob/master/kernel/bpf/arraymap.c). These establish the map semantics; the packet-level interleaving is an inference from this change's reads and writes, not an observed live incident. +See [Additional constraints and coverage observations](../archive/reviews/egress-active-active_2026-10-09.md#additional-constraints-and-coverage-observations). diff --git a/docs/feature_reviews/egress-active-active_2026-10-09_rereview.md b/docs/feature_reviews/egress-active-active_2026-10-09_rereview.md index 12d1484fa..1c6b7a57f 100644 --- a/docs/feature_reviews/egress-active-active_2026-10-09_rereview.md +++ b/docs/feature_reviews/egress-active-active_2026-10-09_rereview.md @@ -1,230 +1,95 @@ # Architecture Review: egress-active-active -**Language:** go | **Reviewed:** 2026-10-09T21:36:38.278824+00:00 -## Summary +This document moved to [egress-active-active_2026-10-09_rereview](../archive/reviews/egress-active-active_2026-10-09_rereview.md). Update bookmarks to the maintained page. -Not ready for staging enablement: snapshot publication is substantially improved, but rollback and translation-class routing still have correctness defects. + -**6 findings:** 🔴 0 critical 🟠 4 high 🟡 2 medium ⚪ 0 low +See [Summary](../archive/reviews/egress-active-active_2026-10-09_rereview.md#summary). + -**Scope:** Current uncommitted changes relative to `c8830ea9`, including new untracked implementation files. HEAD has not advanced since the original review. Reviewed against the original report and the implementation prompt. The original report is preserved unchanged. +See [Original findings disposition](../archive/reviews/egress-active-active_2026-10-09_rereview.md#original-findings-disposition). -**Decision:** Hold staging enablement. The snapshot redesign addresses the original mutable-array and partial-publication problems, but four high-priority routing/transition findings remain. Estimated remediation is medium. No implementation files were changed by this review and no infrastructure was modified. + -### Original findings disposition +See [Validation and reproductions](../archive/reviews/egress-active-active_2026-10-09_rereview.md#validation-and-reproductions). -| Original finding | Assessment | -| --- | --- | -| F01 — unsafe rollback after refresh errors | Error propagation fixed. Concurrent CNI registration is still unsafe (R01). | -| F02 — drain test accepts no traffic | Original vacuous pass fixed. Fresh-address allocation and the real-BGP failure scenario need correction (R04, R06). | -| F03 — deletion described as graceful drain | Fixed in the updated guide and deletion candidate filtering. | -| F04 — incompatible pool members | Per-class capability filtering added, but route selection can bypass it (R02, R03), and class reconfiguration can redirect to a different class (R05). | -| F05 — generation reuse after partial writes | Structurally addressed by atomic snapshot publication and persisted slot generation state. | -| F06 — torn shard records during updates | Structurally addressed by immutable map-in-map publication. Concurrent kernel test added; execution remains unverified here. | + -### Validation and reproductions +See [Architecture](../archive/reviews/egress-active-active_2026-10-09_rereview.md#architecture). -- `task build:ebpf`: passed, all four datapaths regenerated. -- `go build ./cmd/...`: passed (exit 0), with a nonfatal read-only module stat-cache warning. -- Repository-wide `golangci-lint run --timeout 5m`: passed, **0 issues**. -- `go test -race -count=1 -v` for egressroutemap, attachreg and metrics: passed for runnable cases. Privileged packet/publication tests skipped, including the new concurrent-swap and publication-failure tests. -- Focused installer group/shard/egress/class tests: passed. -- Focused `go vet` for installer, egressroutemap, attachreg, metrics and attach: passed. -- `bash -n` for the acceptance script and `git diff --check`: passed. -- Three temporary Go overlay reproductions confirmed R01, R02 and R05 without modifying source files. These tests assert the defective behavior to establish the finding; their passing is not acceptance evidence. -- R01: inject a sentinel after the ordered sweep's scan. The group becomes disabled with one referencing route left. -- R02: a synced empty shard list converts three existing group routes back to a resolvable static shard. -- R05: remove the first NAT64 prefix from a two-prefix configuration. Its route remains on group 1, which now serves the second prefix and its different shard. -- R03 follows directly from the installed route set and longest-prefix-match lookup; existing single-family tests expect the missing specific prefix and do not exercise actual packet selection through the catch-all. -- No privileged kernel acceptance, containerlab scenario, promtool alert tests, full `task ci`, remote CI verification or live staging checks were completed in this review. A green lint/unit run does not close these gates. + -Reproduction artifacts for this session: `/tmp/review-overlay.json`, `/tmp/review_regression_test.go`, `/tmp/review-class-overlay.json`, `/tmp/review_class_lifecycle_test.go`, and `/tmp/egress-rereview-class-repro.log`. Other checks are logged under `/tmp/egress-rereview-*.log`. +See [Findings](../archive/reviews/egress-active-active_2026-10-09_rereview.md#findings). -## Architecture + -**Layers observed:** installer informer → translation-class groups → CNI registration → metrics → acceptance script +See [🔴 P0 — Critical](../archive/reviews/egress-active-active_2026-10-09_rereview.md#-p0--critical). -**Dependency direction:** clean + -Translation-scoped groups are a sound direction; empty-class and transition semantics require correction. +See [🟠 P1 — High](../archive/reviews/egress-active-active_2026-10-09_rereview.md#-p1--high). -## Findings + -### 🔴 P0 — Critical +See [[R01] Closing groups does not exclude in-flight CNI sentinel writes](../archive/reviews/egress-active-active_2026-10-09_rereview.md#r01-closing-groups-does-not-exclude-in-flight-cni-sentinel-writes). -No P0 findings. + -### 🟠 P1 — High +See [[R02] Empty hashed membership silently restores static shard routes](../archive/reviews/egress-active-active_2026-10-09_rereview.md#r02-empty-hashed-membership-silently-restores-static-shard-routes). -#### [R01] Closing groups does not exclude in-flight CNI sentinel writes -**Location:** `internal/plumbing/ebpf/attachreg/egressgroups.go:91-106` | **Category:** concurrency + -**Problem:** A CNI ADD can read an open group and pause; ordered sweep closes it, scans/converts all visible routes and disables it; ADD then writes a sentinel referencing the disabled group. The post-write check only repairs afterward and may fail, encounter an empty static list, or never run if the process terminates. An error after a partial class install also returns before rechecking. Existing VRF routes can be affected by ADD/FillVRF, not just a not-yet-connected pod. +See [[R03] Skipping an unserved NAT64 prefix lets NAT66 default route catch it](../archive/reviews/egress-active-active_2026-10-09_rereview.md#r03-skipping-an-unserved-nat64-prefix-lets-nat66-default-route-catch-it). -**Risk:** Rollback can still blackhole tenant routes while reporting no group routes and a disabled group. Original refresh error propagation is fixed but the requested concurrent-registration safety is not. + -**Before:** -``` -installGroupRoutesIn(...); stillOpen, err := groups.AnyOpen(); installOrderedEgress(...) -``` -**After:** -``` -Serialize sentinel publication and group closing/last scan with a cross-process registration barrier or equivalent protocol; retiring must wait for admitted writers. Test late publication and failed repair. -``` +See [[R05] Do not reuse a translation-class group while old routes reference it](../archive/reviews/egress-active-active_2026-10-09_rereview.md#r05-do-not-reuse-a-translation-class-group-while-old-routes-reference-it). -#### [R02] Empty hashed membership silently restores static shard routes -**Location:** `internal/installer/egressgroup.go:335-339` | **Category:** config + -**Problem:** With no class having candidates, byClass is empty and WithShardGroups is omitted. Refresh interprets this as ordered mode and rewrites existing sentinels to the first resolvable static SID, even though the informer rejected it or removed its capabilities. Static SID resolution does not validate readiness or translation. +See [🟡 P2 — Medium](../archive/reviews/egress-active-active_2026-10-09_rereview.md#-p2--medium). -**Risk:** Hashed mode bypasses its admission and empty-group safeguards, sending traffic to unready, deleted-but-still-routable or incompatible shards. Group-empty metrics/alerts can also lose their route evidence. + -**Before:** -``` -if len(byClass) > 0 { opts = append(opts, WithShardGroups(groupFor)) } -``` -**After:** -``` -Always express hashed refresh semantics, including an empty class map; preserve or install explicit empty-class sentinels rather than invoking ordered fallback. -``` +See [[R04] Fresh-address counter is lost in command substitutions](../archive/reviews/egress-active-active_2026-10-09_rereview.md#r04-fresh-address-counter-is-lost-in-command-substitutions). -#### [R03] Skipping an unserved NAT64 prefix lets NAT66 default route catch it -**Location:** `internal/plumbing/ebpf/attachreg/egressgroups.go:155-158` | **Category:** config + -**Problem:** When NAT66 has candidates but a configured NAT64 /96 has none, installGroupRoutesIn installs ::/0 and skips the /96. LPM lookup then selects the NAT66 group for packets to that configured NAT64 prefix. TestInstallVRFEgress_SingleFamilyDeployments/NAT66Only and MismatchedPrefix explicitly encode this unsafe route set. +See [[R06] Withdraw every route source before measuring shard-unreachable convergence](../archive/reviews/egress-active-active_2026-10-09_rereview.md#r06-withdraw-every-route-source-before-measuring-shard-unreachable-convergence). -**Risk:** NAT64 traffic is sent to shards not admitted to its translation class, defeating F04. New VRFs behave differently from existing VRFs whose empty NAT64 sentinel remains. + -**Before:** -``` -if !found || !status.Open() || status.Candidates == 0 { continue } -``` -**After:** -``` -Install an explicit rejecting/empty-group route for each configured but unserved NAT64 prefix, or fail attachment when the class is required. Exercise actual LPM selection against ::/0. -``` +See [⚪ P3 — Low](../archive/reviews/egress-active-active_2026-10-09_rereview.md#-p3--low). -#### [R05] Do not reuse a translation-class group while old routes reference it -**Location:** `internal/installer/egressgroup.go:355-358; internal/plumbing/ebpf/egressroutemap/egressroute.go:767-771` | **Category:** config + -**Problem:** Group IDs are the positions in the current configured prefix list. With [NAT66, P1, P2] published, removing P1 changes the list to [NAT66, P2] and overwrites group 1 with P2 before repairing existing routes. A route for P1 still names group 1. Refresh finds no configured class for P1 and deliberately leaves its sentinel untouched, so it now sends P1 traffic to P2-only shards. Old group 2 is never retired and remains a duplicate P2 group; FindClass and the sweep can pick different duplicates. +See [What's Working Well](../archive/reviews/egress-active-active_2026-10-09_rereview.md#whats-working-well). -**Risk:** Configuration changes cause persistent cross-class routing and NAT64 outages. Removed classes also remain published and can retain stale members indefinitely. + -**Before:** -``` -for i, class := range g.classes { groups.Apply(uint32(i), ..., eligible) } -``` -**After:** -``` -Allocate stable class identities and reconcile retired classes explicitly. Do not reuse a group ID until every reference has been safely migrated or replaced with a fail-closed route. Test removal, reorder, replacement, and restart with old snapshots. -``` +See [Refactor Plan](../archive/reviews/egress-active-active_2026-10-09_rereview.md#refactor-plan). -### 🟡 P2 — Medium + -#### [R04] Fresh-address counter is lost in command substitutions -**Location:** `deploy/containerlab/scripts/verify-nat-active-active.sh:157-165` | **Category:** testing +See [Step 1: Make group retirement exclude concurrent writers](../archive/reviews/egress-active-active_2026-10-09_rereview.md#step-1-make-group-retirement-exclude-concurrent-writers). -**Problem:** Every fresh call is through $(fresh), which runs in a subshell. FRESH_N increments never persist in the parent, so every address has counter=1 and only one random byte distinguishes calls. About 17 calls in the full script give roughly 42% collision probability. Reused addresses still carry default-duration pins, and ip addr add failures can be hidden because the function continues to echo an address. + -**Risk:** The acceptance gate intermittently fails for address collisions or tests already-pinned addresses as fresh tenants during drain/failure; it cannot reliably certify fresh selection. +See [Step 2: Preserve fail-closed translation classes](../archive/reviews/egress-active-active_2026-10-09_rereview.md#step-2-preserve-fail-closed-translation-classes). -**Before:** -``` -a=$(fresh) # fresh increments FRESH_N locally and uses random.randrange(256) -``` -**After:** -``` -Allocate monotonically unique addresses in the parent shell or persistent state file; propagate addr-add errors and verify no address reuse. Avoid command substitution for the state mutation. -``` + -#### [R06] Withdraw every route source before measuring shard-unreachable convergence -**Location:** `deploy/containerlab/scripts/verify-nat-active-active.sh:337-340,515-516` | **Category:** testing +See [Step 3: Reconcile translation-class lifetime](../archive/reviews/egress-active-active_2026-10-09_rereview.md#step-3-reconcile-translation-class-lifetime). -**Problem:** The real-BGP scenario removes only the fabric-router network statement for the shard /64. EgressShardReconciler independently advertises that same /64 as plain reachability through galactic-router EVPN (egressshard_controller.go:466-507,529 onward), and processEVPNPath installs it through the plain-route reconciler (runtime/gobgp/monitor.go:184-188). The node loopback remains reachable. The compute resolver can therefore keep finding the EVPN route and a healthy uplink neighbor; withdrawing the FRR origin alone does not establish shard unreachability. + -**Risk:** The acceptance scenario can time out waiting for unreachable=1 on a correctly configured lab; it cannot be treated as proof of end-to-end failure detection. +See [Step 4: Make fresh probes deterministic](../archive/reviews/egress-active-active_2026-10-09_rereview.md#step-4-make-fresh-probes-deterministic). -**Before:** -``` -originate "${SHARD_B}" no; wait_metric ... unreachable 1 300 -``` -**After:** -``` -Use an isolated, reversible failure that removes all usable paths to that shard, or suppress both advertisement sources with reliable restoration. Assert the actual compute FIB lookup no longer resolves over a fabric uplink before measuring selection convergence. -``` + -### ⚪ P3 — Low +See [Step 5: Make the BGP acceptance failure remove all usable paths](../archive/reviews/egress-active-active_2026-10-09_rereview.md#step-5-make-the-bgp-acceptance-failure-remove-all-usable-paths). -No P3 findings. + -## What's Working Well - -- Refresh errors now propagate and prevent disable after failed iterator/map write. -- Candidates check realized status families, NAT64 prefix and well-known-prefix support; terminating shards excluded. -- Drain documentation correctly requires explicit drain then quiescence before delete. -- Probe checks requests and capture counts, includes blackhole negative check and NAT64/UDP/ICMP coverage. -- Adds watch synchronization, desired mode, sweep failure metrics and staging rollback checklist. -- Immutable group snapshots combine membership, Maglev, generation and forwarding fields and publish via one ARRAY_OF_MAPS replacement. -- F05 partial slot publication is eliminated because failed create/write/swap attempts do not publish the new inner map. -- New kernel tests cover failure boundaries, restart pin retention, class isolation and concurrent snapshot swaps; these still require privileged execution. - -## Refactor Plan - -Each step is independently mergeable and must not break existing behavior. - -### Step 1: Make group retirement exclude concurrent writers -*Addresses: R01* - -**What:** Implement registration barrier and fault tests. - -**Why now:** Rollback must be safe. - -**Safe when:** No late writer can outlive disabled group. - -### Step 2: Preserve fail-closed translation classes -*Addresses: R02, R03* - -**What:** Keep hashed refresh semantics for empty classes and install explicit per-prefix failures. - -**Why now:** Admission must apply to actual traffic. - -**Safe when:** Zero candidates never sends traffic to static or another class. - -### Step 3: Reconcile translation-class lifetime -*Addresses: R05* - -**What:** Keep class-to-group identity stable and safely retire removed classes and routes. - -**Why now:** Changing configuration must not reinterpret existing sentinel routes. - -**Safe when:** Removal/reorder/replacement never forwards a route to a group for a different prefix. - -### Step 4: Make fresh probes deterministic -*Addresses: R04* - -**What:** Persist unique address allocation and check errors. - -**Why now:** Acceptance must be repeatable. - -**Safe when:** Repeated calls never reuse source addresses. - -### Step 5: Make the BGP acceptance failure remove all usable paths -*Addresses: R06* - -**What:** Account for both FRR and galactic-router advertisements; verify the compute FIB and reliably restore the failure. - -**Why now:** A routing failover test must induce the failure it claims to measure. - -**Safe when:** The test proves actual loss and recovery of reachability without a local prohibit-route shortcut. - -## Remaining staging gates and review observations - -Fix R01–R05 and correct the routing failure scenario before treating the lab script as an acceptance gate. Re-run privileged tests on the staging kernel, alert tests, full CI and the complete lab scenario. Confirm the external CRD, read-back of `spec.drain`, RBAC, unique per-shard addresses, per-class eligibility and actual central alert deployment. The new rollout checklist is useful documentation, not evidence those checks were performed. - -The new script checks UDP outbound arrival but does not demonstrate translated UDP return traffic. Shard addition, initial first-sync delay and concurrent membership changes still need explicit execution evidence. Its rollback stage assumes the saved starting mode was ordered even though cleanup claims general restoration; make that precondition explicit or set ordered for the test and restore the original state separately. - -Monitoring now exposes desired mode and watch sync, which is an improvement. Missing map-derived pool series and stale successful-sweep timestamps still need an operational check: early pinned-map open failures bypass SweepError, and there is no dedicated alert consuming the successful-sweep timestamp. Confirm those cases cannot appear healthy merely because the process answers scrapes. - -Upgrade from the reviewed experimental mutable-array build is not explicitly migrated: the new outer map starts empty while existing sentinel routes/pins can remain, and obsolete map pins are removed. If that experimental build was ever enabled anywhere, require an ordered-mode transition before this upgrade or implement/test state migration. This is an additional deployment prerequisite, not a claim that the old experimental build was deployed. +See [Remaining staging gates and review observations](../archive/reviews/egress-active-active_2026-10-09_rereview.md#remaining-staging-gates-and-review-observations). diff --git a/docs/metrics.md b/docs/metrics.md index 33b662176..937f8eeb0 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -1,1155 +1,119 @@ # Metrics Reference -Every Prometheus metric galactic exports for VPC traffic, egress, ingress -load balancing, routing and NAT, with the label values each one can carry -and PromQL to start dashboards and monitors from. Names, labels and value -sets come from the collectors themselves; when this page and the code -disagree, the code wins. +This document moved to [README](observability/README.md). Update bookmarks to the maintained page. -## Where the metrics come from + -Every DaemonSet under `config/` runs `hostNetwork: true`, so its port is -bound on the node itself. `galactic-vrf` runs as a sidecar in the ingress -proxy's pod instead, which has its own network namespace, so it shares -the 9182 default with `galactic-nat` without clashing, even on the edge -nodes that run both. `galactic-controller`, `fabric-router-controller` and -the fabric-api gateway are Deployments, scraped per pod. +See [Where the metrics come from](observability/README.md#where-the-metrics-come-from). -| Area | Component | Metric prefix | Port | `job` from `config/monitoring/` | -| ----------------------- | --------------------------------------------------------- | ------------------------------------------------------------- | -------------- | ---------------------------------------- | -| VPC dataplane | `galactic-cni` (`credential-refresh`, the datapath owner) | `galactic_usid_*` | 9180 | `galactic-cni` | -| Tenant egress pool | `galactic-cni` | `galactic_cni_egress_*` | 9180 | `galactic-cni` | -| VPC ingress | `galactic-vrf` | `galactic_ingress_sidecar_*` | 9182 (default) | none shipped | -| VPC ingress return path | `galactic-cni` (`credential-refresh`) | `galactic_sidecar_return_*` | 9180 | `galactic-cni` | -| VPC ingress backends | `galactic-cni` (`credential-refresh`) | `galactic_endpointslice_repair_*` | 9180 | `galactic-cni` | -| Edge load balancer | `galactic-gateway` | `galactic_edge_*`, controller-runtime | 8081 | none shipped | -| Tenant routing (GoBGP) | `galactic-router`, `galactic-router-rr` | `galactic_router_*`, controller-runtime | 9179 | `galactic-router` / `galactic-router-rr` | -| Private service routes | `galactic-router` (plain mode only) | `galactic_service_route_*` | 9179 | `galactic-router` | -| Traffic policy | `galactic-router` with `GALACTIC_ROUTER_TRAFFIC_POLICY` | `galactic_cni_traffic_policy_*` | 9179 | `galactic-router` | -| Traffic policy webhook | `galactic-controller` | controller-runtime | 9184 | `galactic-controller` | -| Galactic Edge (core) | `galactic-controller --role=cell --edge` | `galactic_edge_foundation_*` | 9184 | `galactic-controller` | -| Galactic Edge (node) | `galactic-edge` | `galactic_edge_foundation_*`, controller-runtime | 9186 | `galactic-edge` | -| Underlay routing (FRR) | `fabric-router` `frr-exporter` sidecar | `frr_*` | 9342 | `fabric-router` | -| Underlay config | `fabric-router` `fabric-config-agent` | `fabric_router_*` | 9343 | `fabric-config-agent` | -| Fabric routing (API) | `fabric-router-controller` | `galactic_fabric_routing_*` (leader only), controller-runtime | 9185 | `fabric-router-controller` | -| Fabric looking glass | `fabric-api` node sidecar | `fabric_api_node_*`, `fabric_api_*` | 9345 | `fabric-api-node` | -| Fabric looking glass | `fabric-api` cell gateway | `fabric_api_gateway_*`, `fabric_api_*` | 9347 | `fabric-api-gateway` | -| NAT66 / NAT64 | `galactic-nat` (one per egress shard) | `galactic_nat_*` | 9182 | `galactic-nat` | + -`config/monitoring/` ships PodMonitors for `galactic-cni`, -`galactic-router`, `fabric-router` (including the opt-in fabric-api -sidecar), `fabric-router-controller`, the fabric-api gateway, -`galactic-nat`, `galactic-controller` and `galactic-edge`. Scraping -`galactic-vrf` or `galactic-gateway` needs a scrape object of your own. Copy the shipped -PodMonitors' relabeling of `__meta_kubernetes_pod_node_name` into `node`: -every galactic metric is per node, and `node` is the label you group and -alert by. `fabric-router-controller`'s fleet series name the node each -deployment or router targets themselves, and their `namespace` is the -object's, which its PodMonitor keeps with `honorLabels`. +See [VPC dataplane — `galactic_usid_*`](observability/vpc-dataplane.md#vpc-dataplane--galactic_usid_). -The eBPF-backed metrics (`galactic_usid_*`, `galactic_cni_egress_shard_*`, -`galactic_edge_*`, `galactic_edge_foundation_gate_drops_total`, `galactic_nat_*`) are read from BPF maps at scrape time, -and a pod restart that reloads the program resets them. Always use -`rate()` / `increase()`, never raw counter values. + -## VPC dataplane — `galactic_usid_*` +See [Traffic](observability/vpc-dataplane.md#traffic). -The SRv6 uSID datapath on every node, forwarding packets between the fabric -and tenant VRFs. + -### Traffic +See [Drops](observability/vpc-dataplane.md#drops). -Each node keeps one VRF per VPC, so every series below is one VPC on one -node, keyed by its uSID (Block, Argument). `vpc_attachment` names the -attachment that registered the VRF last, not each attachment's own traffic. -`vrf_interface` is the name of the VPC's VRF device on the node, as -`ip link` shows it. + -| Metric | Type | Labels | Meaning | -|---------------------------------------------|---------|--------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------| -| `galactic_usid_vrf_forwarded_packets_total` | counter | `block`, `argument`, `vrf_table_id`, `vpc`, `vpc_attachment`, `vrf_interface`, `direction` | Packets forwarded into (`ingress`) or out of (`egress`) the VRF | -| `galactic_usid_vrf_forwarded_bytes_total` | counter | same | Tenant bytes of those packets: the IP header and payload, in both directions | -| `galactic_usid_vrf_dropped_packets_total` | counter | same | Packets dropped after the datapath resolved them to the VRF, by direction | -| `galactic_usid_vrf_packets_total` | counter | `block`, `argument`, `vrf_table_id`, `vpc`, `vpc_attachment`, `vrf_interface` | Inbound packets that matched the VRF, counted before any later drop | -| `galactic_usid_vrf_bytes_total` | counter | same | Bytes of those packets, measured as the whole tunneled frame with outer headers | +See [SID capacity](observability/vpc-dataplane.md#sid-capacity). -What each `direction` counts: + -| `direction` | Counted when | -|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `ingress` | `usid_ingress` decapsulates a packet and redirects it to an attachment, or another attachment on the same node sends one to it | -| `egress` | a tenant packet is encapsulated toward another node or an egress shard, sent unencapsulated out the public uplink (a VIP reply), or delivered to another attachment on the node | +See [MTU handling](observability/vpc-dataplane.md#mtu-handling). -- A packet counts once, when the datapath has committed to forwarding it. - Traffic the datapath hands to the kernel to route (no matching egress - route) and fail-open paths are not counted. -- A packet too big for the fabric, answered with a Packet Too Big or - Fragmentation Needed, counts as neither forwarded nor dropped; see - `galactic_usid_pmtu_packets_total`. -- Traffic between two attachments of one VPC on the same node counts once - as `egress` and once as `ingress` on that VPC's series, when it is handed - to the kernel for delivery, so the kernel can still drop it. Traffic to the - sender's own gateway address counts in neither; traffic to another - attachment's gateway address in the same VPC counts as delivered. -- A private service route delivering to another attachment on the node - counts `egress` on the sender's VPC and `ingress` on the receiver's, which - may be a different VPC. -- A GSO or GRO super-packet counts as one packet carrying all its bytes. -- Drop reasons are in `galactic_usid_drops_total`, which has no VRF. - `galactic_usid_vrf_dropped_packets_total` has the VRF but no reason, and - covers drops in decapsulation, delivery, encapsulation and the PMTU check, - including inbound private service tunnels. Outbound private service route - drops (`service_route_*` from the sending attachment) and failed - public-uplink redirects appear only in `galactic_usid_drops_total`. -- The two older series keep their meaning: inbound only, claimed before any - drop, and the full frame. Prefer the `forwarded` series for throughput. -- Registering a VRF again never resets its counters. They reset when the - datapath reloads, or when the VRF's rows are removed and created again, - which `rate()` copes with. -- `vpc`, `vpc_attachment` and `vrf_interface` are empty when the VPC - attribution map has no entry for that Argument. Treat `vpc=""` traffic as - unattributed and watch for it. -- Cardinality is one series per active Argument per node for the older pair, - at most 4095 per Block, and twice that for each `direction` metric. + -```promql -# Throughput per VPC and direction, bits/s -sum by (vpc, direction) (rate(galactic_usid_vrf_forwarded_bytes_total[5m])) * 8 +See [Datapath lifecycle](observability/vpc-dataplane.md#datapath-lifecycle). -# Top 10 VPCs on a node by outbound packet rate -topk(10, sum by (node, vpc) (rate(galactic_usid_vrf_forwarded_packets_total{direction="egress"}[5m]))) + -# Share of a VPC's packets dropped after the datapath claimed them -sum by (vpc, direction) (rate(galactic_usid_vrf_dropped_packets_total[5m])) - / (sum by (vpc, direction) (rate(galactic_usid_vrf_forwarded_packets_total[5m])) - + sum by (vpc, direction) (rate(galactic_usid_vrf_dropped_packets_total[5m]))) +See [Tenant egress pool — `galactic_cni_egress_*`](observability/egress-pool.md#tenant-egress-pool--galactic_cni_egress_). -# Traffic the datapath can't attribute to a VPC -sum by (node) (rate(galactic_usid_vrf_forwarded_bytes_total{vpc=""}[5m])) -``` + -### Drops +See [VPC ingress — `galactic_ingress_sidecar_*`](observability/vpc-ingress.md#vpc-ingress--galactic_ingress_sidecar_). -`galactic_usid_drops_total{reason}` (counter) counts packets the uSID -datapath dropped, inbound and outbound. Every named reason is always -emitted, at zero when unused, plus `unknown_` for an index the binary -has no name for. + -| Reason group | Values | Usually means | -|------------------|--------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------| -| Unknown SID | `unknown_function`, `unknown_argument` | Traffic for a VRF or Argument this node no longer, or never, registered: stale routes elsewhere | -| Malformed | `malformed_inner`, `unknown_inner_version`, `unexpected_nexthdr`, `unsupported_behavior`, `strip_failed` | Bad or unsupported packets; a sustained rate is a bug | -| FIB / forwarding | `fib_lookup_failed`, `fib_no_neigh`, `fib_unreachable`, `fib_frag_needed`, `redirect_failed` | Kernel route or neighbor missing for the inner destination | -| Egress | `egress_route_encap_failed`, `egress_route_fib_lookup_failed`, `egress_route_redirect_failed`, `public_uplink_redirect_failed` | Tenant traffic leaving the node couldn't be encapsulated or sent | -| Service routes | `service_route_denied`, `service_route_redirect_failed` | A private service route refused the sender, or its redirect to the target failed | -| IPv4 VIP | `vip_xlat_failed`, `vip_ipv4_fragment`, `vip_udp_no_checksum`, `vip_ipv4_backend`, `vip_ttl_exceeded` | An IPv4 VIP packet was untranslatable; `vip_ipv4_backend` means a pre-translation router | +See [Startup and sweep](observability/vpc-ingress.md#startup-and-sweep). -```promql -sum by (node, reason) (rate(galactic_usid_drops_total[5m])) > 0 -``` + -### SID capacity +See [Convergence](observability/vpc-ingress.md#convergence). -| Metric | Type | Labels | Meaning | -|--------------------------------------------------|-------|---------|--------------------------------------------------------| -| `galactic_usid_block_arguments_used` | gauge | `block` | Arguments (VRF entries) registered in the Block | -| `galactic_usid_block_argument_utilization_ratio` | gauge | `block` | `arguments_used / 4095`, the usable capacity per Block | + -```promql -max by (node, block) (galactic_usid_block_argument_utilization_ratio) > 0.8 -``` +See [EndpointSlice inputs](observability/vpc-ingress.md#endpointslice-inputs). -### MTU handling + -| Metric | Type | Labels | Meaning | -|-------------------------------------------|---------|----------|---------------------------------------------------------------------------| -| `galactic_usid_tcp_mss_clamp_syns_total` | counter | `result` | TCP SYNs the MSS clamp examined | -| `galactic_usid_tcp_mss_clamp_limit_bytes` | gauge | `family` | MSS that SYNs are clamped to; `0` means clamping is off for that family | -| `galactic_usid_pmtu_packets_total` | counter | `result` | Tenant packets too big for the fabric once encapsulated | -| `galactic_usid_pmtu_limit_bytes` | gauge | none | Largest tenant packet the egress encapsulates; `0` means the check is off | +See [Datapath checks](observability/vpc-ingress.md#datapath-checks). -`galactic_usid_tcp_mss_clamp_syns_total` result values: + -- **Clamping worked:** `clamped_ipv4`, `clamped_ipv6`, `within_limit`. -- **SYN crossed the fabric unclamped:** `no_mss_option`, - `skipped_extension_header`, `malformed_options`, `rewrite_failed`, - `walk_limit`. +See [Return-path gateway](observability/vpc-ingress.md#return-path-gateway). -`galactic_usid_pmtu_packets_total` result values: + -- **Tenant got an ICMP error back:** `too_big_sent_ipv6`, - `frag_needed_sent_ipv4`. -- **Dropped without an ICMP error (black-hole risk):** `dropped_no_df`, - `dropped_icmp_error`, `rate_limited`, `no_gateway`, `build_failed`. +See [Node source address](observability/vpc-ingress.md#node-source-address). -```promql -# SYNs that crossed unclamped -sum by (node, result) (rate(galactic_usid_tcp_mss_clamp_syns_total{result!~"clamped_.*|within_limit"}[5m])) + -# PMTU drops with no ICMP error, the case that stalls connections silently -sum by (node, result) (rate(galactic_usid_pmtu_packets_total{result!~"too_big_sent_ipv6|frag_needed_sent_ipv4"}[5m])) +See [Host return path — `galactic_sidecar_return_*`](observability/vpc-ingress.md#host-return-path--galactic_sidecar_return_). -# Clamp off for a family -galactic_usid_tcp_mss_clamp_limit_bytes == 0 -``` + -### Datapath lifecycle +See [Backend EndpointSlice repair — `galactic_endpointslice_repair_*`](observability/vpc-ingress.md#backend-endpointslice-repair--galactic_endpointslice_repair_). -| Metric | Type | Labels | Meaning | -|----------------------------------------------|---------|------------------------------------------------------|--------------------------------------------------------------------| -| `galactic_usid_datapath_load_events_total` | counter | `result` (`success`, `failure`) | BPF program load attempts | -| `galactic_usid_datapath_attach_events_total` | counter | `interface`, `action` (`attach`, `detach`), `result` | TC ingress attach/detach, including every netlink-driven re-attach | + -```promql -increase(galactic_usid_datapath_load_events_total{result="failure"}[15m]) > 0 -increase(galactic_usid_datapath_attach_events_total{result="failure"}[15m]) > 0 +See [Edge load balancer — `galactic_edge_*`](observability/gateway.md#edge-load-balancer--galactic_edge_). -# Re-attach churn: a flapping interface -sum by (node, interface) (increase(galactic_usid_datapath_attach_events_total{action="attach"}[1h])) > 5 -``` + -## Tenant egress pool — `galactic_cni_egress_*` +See [Galactic Edge foundation — `galactic_edge_foundation_*`](observability/edge.md#galactic-edge-foundation--galactic_edge_foundation_). -How each compute node spreads tenant egress across the cluster's -`EgressShard`s. With `GALACTIC_CNI_EGRESS_MODE=hashed`, `usid_egress` keeps -one shard group per translation class: `nat66`, and `nat64:` for -each NAT64 prefix. See -[nat/configuration.md](nat/configuration.md#active-active-egress). + -The pool series come from the maps, so a node with no group publishes -none. The control-loop series (`mode`, `shard_watch_synced`, -`group_routes`, the sweep pair) are always exported, so a node told to run -hashed mode that never published a group still shows it. +See [Traffic policy — `galactic_cni_traffic_policy_*`](observability/traffic-policy.md#traffic-policy--galactic_cni_traffic_policy_). -| Metric | Type | Labels | Meaning | -| ------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `galactic_cni_egress_shard_packets_total` | counter | `shard_sid`, `class` | Tenant packets this node encapsulated toward each shard, since the shard took its slot | -| `galactic_cni_egress_shard_bytes_total` | counter | `shard_sid`, `class` | Tenant bytes of those packets | -| `galactic_cni_egress_shard_selections_total` | counter | `result` | How `usid_egress` placed each packet whose route names a shard group | -| `galactic_cni_egress_pool_members` | gauge | `class`, `state` (`active`, `draining`, `unreachable`, `local`, `ineligible`) | The class's shards as this node's group sees them | -| `galactic_cni_egress_pool_min_active` | gauge | none | `GALACTIC_CNI_EGRESS_POOL_MIN_ACTIVE`, the fewest active shards each class should have | -| `galactic_cni_egress_pool_enabled` | gauge | `class` | 1 while the class's group takes new routes; a group being retired still forwards but reads 0 | -| `galactic_cni_egress_mode` | gauge | `mode` (`ordered`, `hashed`) | 1 for the configured mode, 0 for the other | -| `galactic_cni_egress_shard_watch_synced` | gauge | none | 1 once the `EgressShard` watch has listed the cluster | -| `galactic_cni_egress_group_routes` | gauge | `class` | `egress_route_table` entries naming a shard group. Must be 0 before rolling back past hashed mode | -| `galactic_cni_egress_sweep_errors_total` | counter | `stage` (`apply`, `refresh`, `watch`, `close`, `disable`) | Egress route sweep failures, by step | -| `galactic_cni_egress_last_successful_sweep_timestamp_seconds` | gauge | none | Unix time of the last sweep that finished without an error | + -`galactic_cni_egress_shard_selections_total` result values: +See [Routing](observability/routing.md#routing). -- **Forwarded:** `pin_hit` (the tenant address's pin still names a live - shard), `maglev` (placed by the Maglev table). -- **Re-placed:** `pin_stale` (the pin named a shard that left the group). -- **Dropped:** `group_empty`, `shard_dead`, `parse_failed`. + -`state` values: `active` shards take new tenant addresses; `draining` ones -(`spec.drain`) serve only the tenants already pinned to them; `unreachable` -ones have no route from this node; `local` ones run on this node and take -no tenant from it; `ineligible` ones cannot translate the class (no -masquerade address in its family, or another NAT64 prefix). +See [Underlay — `frr_*`](observability/routing.md#underlay--frr_). -```promql -# Active shards per class, per node -sum by (node, class) (galactic_cni_egress_pool_members{state="active"}) + -# Egress bytes/s each shard receives from the cluster's compute nodes -sum by (shard_sid, class) (rate(galactic_cni_egress_shard_bytes_total[5m])) * 8 +See [Underlay config — `fabric_router_*`](observability/routing.md#underlay-config--fabric_router_). -# Packets dropped on the way to a shard group (GalacticEgressShardGroupDropping) -sum by (node, result) (increase(galactic_cni_egress_shard_selections_total{result=~"group_empty|shard_dead|parse_failed"}[5m])) > 0 + -# Seconds since the last clean sweep -time() - galactic_cni_egress_last_successful_sweep_timestamp_seconds -``` +See [Fabric routing — `galactic_fabric_routing_*`](observability/routing.md#fabric-routing--galactic_fabric_routing_). -## VPC ingress — `galactic_ingress_sidecar_*` + -`galactic-vrf` installs per-VPC VRF devices and per-pod seg6 egress routes on -ingress nodes. It runs in the ingress proxy's pod, so each sidecar exports its -own copy of these. +See [Tenant routing — `galactic_router_*`](observability/routing.md#tenant-routing--galactic_router_). -| Metric | Type | Labels | Meaning | -| ----------------------------------------------------- | --------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| `galactic_ingress_sidecar_vrf_active` | gauge | none | VRF devices the store tracks as installed, including those draining. Store state, not a kernel check | -| `galactic_ingress_sidecar_route_active` | gauge | none | Installed route claims, one per EndpointSlice, including draining ones. Claims sharing a prefix share one kernel route | -| `galactic_ingress_sidecar_vrf_teardown_pending` | gauge | none | VRFs past their last route at the last sweep: within their grace period, or whose removal failed | -| `galactic_ingress_sidecar_route_teardown_pending` | gauge | none | Route claims whose EndpointSlice is gone at the last sweep: within their grace period, or whose removal failed | -| `galactic_ingress_sidecar_reconcile_errors_total` | counter | `kind` | Backend errors: `ensure_vrf`, `ensure_route`, `remove_vrf`, `remove_route`, `reapply_vrf`, `reapply_route`, `prune_datapath`. No attempt denominator | -| `galactic_ingress_sidecar_reconcile_duration_seconds` | histogram | none | Each desired-state update, including waiting for the store's lock (default buckets). Not sweeps | -| `galactic_ingress_sidecar_reapply_total` | counter | none | Reapply passes: after a datapath reload, after this sidecar's rows went missing, and retries of a failed pass. Not unique reloads | + -`route_active` does not measure an apply backlog: a route stays counted as -installed while a later update to it is still unapplied. +See [Private service routes — `galactic_service_route_*`](observability/routing.md#private-service-routes--galactic_service_route_). -### Startup and sweep + -A sidecar serves `/metrics` from the moment it starts, before its startup has -finished and whether or not its sweep is still running, so `up` and the -gauges above cannot tell a working sidecar from a stuck one. Startup runs -three stages in order: list the selected EndpointSlices and apply them -(`seed`, retried until the list succeeds), adopt existing host state -(`inventory`), and remove an earlier pod's rows from the shared eBPF maps -(`prune`, skipped after a failed inventory). The sweep starts after the first -inventory attempt either way. A failed inventory is retried before each sweep -until it succeeds, and the prune runs once it does: on a node that has just -booted, the inventory fails until galactic-cni pins the shared eBPF maps. The -prune is not retried. +See [NAT66 / NAT64 — `galactic_nat_*`](observability/nat.md#nat66--nat64--galactic_nat_). -| Metric | Type | Labels | Meaning | -| ----------------------------------------------------------------- | --------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `galactic_ingress_sidecar_startup_stage_status` | gauge | `stage`, `status` | 1 for each stage's current status, 0 for its others. `stage`: `seed`, `inventory`, `prune`. `status`: `pending`, `running`, `complete`, `failed`, `skipped` | -| `galactic_ingress_sidecar_startup_attempts_total` | counter | `stage`, `result` | Completed stage attempts, `result` `success` or `error`. The prune is not retried | -| `galactic_ingress_sidecar_startup_complete` | gauge | none | 1 once the seed succeeded, inventory and prune were handled, and the sweep started. A failed inventory or prune still reports 1 | -| `galactic_ingress_sidecar_sweep_last_completed_timestamp_seconds` | gauge | none | Unix time the last sweep finished, whatever its operations' results; 0 before the first | -| `galactic_ingress_sidecar_sweep_duration_seconds` | histogram | none | Each sweep, including waiting for the store's lock (1ms to 120s). One overrunning its interval absorbs the ticks it missed | -| `galactic_ingress_sidecar_sweep_interval_seconds` | gauge | none | Configured time between sweeps | -| `galactic_ingress_sidecar_teardown_grace_seconds` | gauge | none | Configured grace period, applied to a route and then, in turn, to its VRF | -| `galactic_ingress_sidecar_pruned_rows_total` | counter | none | Shared eBPF map rows the startup prune removed, including any removed before it failed | + -`startup_complete` is the startup procedure, not readiness: it says nothing -about whether routes are installed or traffic flows, and a degraded start -stays visible in `startup_stage_status`. These add 43 series per sidecar, -fixed: no label carries a VPC, route or error. +See [Fabric looking glass — `fabric_api_*`](observability/fabric-api.md#fabric-looking-glass--fabric_api_). -```promql -sum by (node, kind) (rate(galactic_ingress_sidecar_reconcile_errors_total[10m])) > 0 -histogram_quantile(0.99, sum by (le, node) (rate(galactic_ingress_sidecar_reconcile_duration_seconds_bucket[5m]))) + -# Teardown backlog that never drains -min_over_time(galactic_ingress_sidecar_vrf_teardown_pending[1h]) > 0 - -# Startup still not complete two minutes after the sidecar process started. -# instance and job pick the sidecar's own process, not another container's. -galactic_ingress_sidecar_startup_complete == 0 - and on (instance, job) (time() - process_start_time_seconds > 120) - -# A stage that ended badly: the inventory is still failing, or the prune failed -# or was skipped -galactic_ingress_sidecar_startup_stage_status{status=~"failed|skipped"} == 1 - -# Sweep stalled: the last sweep finished more than three intervals ago. -(galactic_ingress_sidecar_sweep_last_completed_timestamp_seconds > 0) - and (time() - galactic_ingress_sidecar_sweep_last_completed_timestamp_seconds - > 3 * galactic_ingress_sidecar_sweep_interval_seconds) - -# Never swept: startup completed but no sweep has finished. The first sweep is -# due one interval after startup, so alert with a "for" well beyond three -# intervals. -galactic_ingress_sidecar_startup_complete == 1 - and galactic_ingress_sidecar_sweep_last_completed_timestamp_seconds == 0 - -histogram_quantile(0.99, sum by (le, namespace, pod) (rate(galactic_ingress_sidecar_sweep_duration_seconds_bucket[10m]))) -``` - -### Convergence - -How far a sidecar's host state is from what its EndpointSlices ask for. A -claim is one selected, ready EndpointSlice's route; claims sharing a prefix -share one kernel route. - -| Metric | Type | Labels | Meaning | -| ----------------------------------------------------------------------- | ------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| `galactic_ingress_sidecar_route_claims_desired` | gauge | none | Claims the sidecar wants installed, including any whose install failed | -| `galactic_ingress_sidecar_route_claims_apply_pending` | gauge | none | Desired claims whose latest update is not applied, whether or not an earlier version of the route is installed | -| `galactic_ingress_sidecar_route_apply_oldest_pending_timestamp_seconds` | gauge | none | Unix time the longest-pending claim stopped being applied; 0 when none is pending | -| `galactic_ingress_sidecar_teardown_overdue` | gauge | `resource` | Routes or VRFs (`route`, `vrf`) whose own grace period ran out but whose removal has not completed, as of the last sweep | -| `galactic_ingress_sidecar_operations_total` | counter | `operation`, `result` | Completed backend operations: `ensure_vrf`, `ensure_route`, `remove_vrf`, `remove_route`, `reapply_vrf`, `reapply_route`; `success` or `error` | - -- A claim's pending age starts when it first fails to apply after being - applied or created, and survives failed retries and newer updates of the - same claim: the route has been unapplied since then. It clears when the - claim applies or stops being desired; a claim reactivated during its grace - period starts a new age. -- The claim counts and the oldest pending time are exact after every update - and sweep, at a constant cost per update however large the backlog. -- `teardown_overdue` counts only removals that failed after their own grace - period. Draining within the grace period is normal and shows only in the - `*_teardown_pending` gauges. A route's and then its VRF's grace periods run - one after the other. It is set at each sweep, so a claim reactivated after a - failed removal still counts until the next one: alert on it with a `for` - of at least one sweep interval. -- A reapply that fails after a datapath reload leaves the claim applied as - far as these gauges know; it shows in - `operations_total{operation=~"reapply_.*",result="error"}`. -- `operations_total{result="error"}` counts the same failures as - `reconcile_errors_total` for those six kinds, each failure once. Never add - the two. `reconcile_errors_total` alone also counts `prune_datapath`. -- These add 17 fixed series per sidecar. - -```promql -# Apply backlog: how long the oldest claim has been unapplied. 0 means none. -time() - galactic_ingress_sidecar_route_apply_oldest_pending_timestamp_seconds - and galactic_ingress_sidecar_route_apply_oldest_pending_timestamp_seconds > 0 - -# Teardown stuck past its grace period -galactic_ingress_sidecar_teardown_overdue > 0 - -# Backend error ratio by operation; absent, not zero, when nothing ran -sum by (namespace, pod, operation) (rate(galactic_ingress_sidecar_operations_total{result="error"}[5m])) - / sum by (namespace, pod, operation) (rate(galactic_ingress_sidecar_operations_total[5m])) -``` - -### EndpointSlice inputs - -The selected EndpointSlices a sidecar reads, whether or not they have a -route. A selected slice carries the tenant label. It is `ready` once it parses -into a route, `waiting_sid` while its node's SID annotation has not appeared -(normal for a freshly published slice), and `invalid` when it cannot be -parsed, for a malformed tenant identifier, SID or address, or a non-IPv6 -address type. Parsing reads only the first endpoint's first address. - -| Metric | Type | Labels | Meaning | -| ----------------------------------------------------------- | ------- | ------------------ | ---------------------------------------------------------------------------------------------------------- | -| `galactic_ingress_sidecar_endpoint_slices` | gauge | `state` | Selected slices by `state`: `ready`, `waiting_sid`, `invalid` | -| `galactic_ingress_sidecar_endpoint_slice_evaluations_total` | counter | `source`, `result` | Evaluations by `source` (`seed`, `watch`) and `result` (`ready`, `waiting_sid`, `invalid`, `not_selected`) | - -- A slice that turns `invalid` keeps any route it had: the sidecar keeps the - last good desired state rather than tearing the route down. A successful - reconcile therefore does not mean the slice was usable. -- The startup seed and the watch evaluate slices concurrently. Once the watch - has seen a slice during a seed, the seed's result for it counts as an - evaluation but does not set its state, so a list taken earlier can neither - overwrite a newer update nor bring back a deleted slice. -- The state is eventually consistent: a watch observation read from a - lagging cache can briefly hold older data than the seed's list, until the - slice's next event. -- One entry per selected slice is kept, removed when the reconciler finds the - slice deleted or without the tenant label. The watch currently drops an - update that only removes the label, so a deselected slice keeps its last - state here, and its route, until it is deleted or the sidecar restarts. - These add 11 fixed series per sidecar. - -```promql -# Slices that cannot be parsed, and slices still waiting for their SID -galactic_ingress_sidecar_endpoint_slices{state=~"invalid|waiting_sid"} > 0 -``` - -### Datapath checks - -Every sweep reads the shared eBPF datapath's generation and, when it has not -changed, reads this sidecar's rows back from the two registration maps -(`vrf_table`, `ifindex_vrf_table`). A changed generation, missing rows, or a -pass that left something unapplied makes it reapply every tracked VRF and -route. These checks do not cover every route, the TC attachment, the -gateway's local route or the host return path, so `ok` here is not full -datapath health. - -| Metric | Type | Labels | Meaning | -| -------------------------------------------------------------------------- | ------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | -| `galactic_ingress_sidecar_datapath_checks_total` | counter | `check`, `result` | Completed checks: `generation` (`ok`, `error`) and `registration_rows` (`ok`, `missing`, `error`) | -| `galactic_ingress_sidecar_datapath_check_status` | gauge | `check`, `status` | 1 for each check's latest status, 0 for its others: `unknown` (not read yet, or an `ok` not re-read this sweep), `ok`, `missing`, `error` | -| `galactic_ingress_sidecar_datapath_check_last_completed_timestamp_seconds` | gauge | `check` | Unix time each check last completed, whatever its result; 0 before the first | -| `galactic_ingress_sidecar_datapath_reapply_total` | counter | `reason`, `result` | Reapply passes by `reason` (`generation_changed`, `rows_missing`, `retry`) and `result` (`success` when every reapply succeeded, `error`) | -| `galactic_ingress_sidecar_datapath_reapply_pending` | gauge | none | 1 while a pass left something unapplied, until a later one succeeds | - -- A failed read is `error`, not `ok`: the state is unknown. Repair stays - conservative and does not reapply on a failed read; the next successful - read decides. -- The rows are read only while the generation is unchanged and no retry is - due, and only when there is a VRF to read back. On any other sweep, and - after a reapply rewrote them, a last `ok` becomes `unknown`; a `missing` or - `error` stays until a read replaces it, so a problem never turns into an - unverified healthy result. Its timestamp shows when the rows were last read. -- A pass's reason is `generation_changed` whenever the generation moved, even - if a retry was also due; otherwise `rows_missing` when this sweep found rows - gone, otherwise `retry`. `reapply_total` keeps counting every pass, of any - reason. These add 22 fixed series per sidecar. - -```promql -# A check that failed or found rows missing -galactic_ingress_sidecar_datapath_check_status{status=~"missing|error"} == 1 - -# A check that completed before but not in the last three sweeps (15s at the -# default 5s sweep interval) -(galactic_ingress_sidecar_datapath_check_last_completed_timestamp_seconds > 0) - and (time() - galactic_ingress_sidecar_datapath_check_last_completed_timestamp_seconds > 15) - -# Reapply churn by reason -sum by (namespace, pod, reason) (increase(galactic_ingress_sidecar_datapath_reapply_total[10m])) -``` - -### Return-path gateway - -With a node name configured, the sidecar publishes one return-path gateway -advertisement per VPC, so a backend's replies have a route back to this -node: it resolves the VPC's gateway address, then writes a -`BGPAdvertisement`. Either step can fail without failing the route that -triggered it. - -| Metric | Type | Labels | Meaning | -| ------------------------------------------------------------------- | ------- | --------------------- | ------------------------------------------------------------------------------------------------ | -| `galactic_ingress_sidecar_gateway_publication_enabled` | gauge | none | 1 when the sidecar publishes return-path advertisements | -| `galactic_ingress_sidecar_gateway_address_assignment_enabled` | gauge | none | 1 when the sidecar assigns each VPC's gateway address from its own gateway prefix | -| `galactic_ingress_sidecar_gateway_vrfs` | gauge | `state` | Installed, non-draining VRFs by `state`: `awaiting_address`, `awaiting_publication`, `published` | -| `galactic_ingress_sidecar_gateway_oldest_pending_timestamp_seconds` | gauge | none | Unix time the longest-unpublished VRF started waiting; 0 when none waits | -| `galactic_ingress_sidecar_gateway_operations_total` | counter | `operation`, `result` | `resolve` (`success`, `error`, `not_provisioned`), `publish` and `withdraw` (`success`, `error`) | - -- `published` is local publication only: the advertisement was written. - It does not show the route reached any BGP peer, or that the - advertisement still exists; nothing re-checks it after publication. -- With publication disabled every `gateway_vrfs` series is 0, so check - `gateway_publication_enabled` before reading 0 as healthy. Disabled, - idle (enabled with no VRFs), waiting and published are all distinct. -- With publication enabled but address assignment off, the sidecar only - finds an address something else provisioned, so VRFs waiting in - `awaiting_address` and `resolve{result="not_provisioned"}` counting up on - every attempt are expected there. -- A successful withdrawal clears a VRF's published state, so a VRF - withdrawn for teardown that then survives, because its removal failed, - and whose VPC comes back is published again, like any VRF waiting. -- A VRF waits from when it is first counted unpublished, through retries, - until it is published or starts draining. A failed withdrawal is counted - and teardown carries on; garbage collection removes the advertisement it - leaves. These add 13 fixed series per sidecar. - -```promql -# Gateway publication pending for more than a minute, only where the sidecar -# both publishes and assigns the address itself -(time() - galactic_ingress_sidecar_gateway_oldest_pending_timestamp_seconds > 60) - and (galactic_ingress_sidecar_gateway_oldest_pending_timestamp_seconds > 0) - and on (namespace, pod) (galactic_ingress_sidecar_gateway_publication_enabled == 1) - and on (namespace, pod) (galactic_ingress_sidecar_gateway_address_assignment_enabled == 1) - -# Resolve and publish failures, as opposed to waiting for an address -sum by (namespace, pod, operation) ( - rate(galactic_ingress_sidecar_gateway_operations_total{result="error"}[10m])) -``` - -### Node source address - -`node_src_addr_table` holds this node's SRv6 source address, which -`usid_egress` stamps on every packet it encapsulates. Until it holds one, -encapsulation fails open and nothing is counted. While any VRF is installed, -each sweep reads the table, writes the address resolved from this node's -`BGPRouter` when the table is unset or holds another, and reads the write -back. - -| Metric | Type | Labels | Meaning | -| ----------------------------------------------------------------------------- | ------- | -------- | --------------------------------------------------------------------------------------- | -| `galactic_ingress_sidecar_node_source_address_status` | gauge | `status` | 1 for the last check's result: `unknown`, `unconfigured`, `ok`, `unresolved` or `error` | -| `galactic_ingress_sidecar_node_source_address_last_checked_timestamp_seconds` | gauge | none | Unix time of the last sweep that checked the table; 0 before the first | -| `galactic_ingress_sidecar_node_source_address_repairs_total` | counter | none | Sweeps that found the table unset or holding another address and wrote this node's | - -- `unknown` means no VRF has been installed since the sidecar started, so - nothing has checked. Sweeps check only while a VRF is installed, so after - the last one is removed the status and timestamp keep their last values; - alert on the timestamp's age only where VRFs are installed. -- `unconfigured` means the sidecar has no node name, so it cannot resolve the - address. `unresolved` means this node's `BGPRouter` has no SRv6 locator and - node ID yet, and the table was left as it was. -- `error` covers a failed read or write, and a write that did not read back. - The status and timestamp are read from one snapshot. -- The repair count includes a sweep that sets the address after a restart, - when it could not be resolved as the VRF was created. A count that keeps - rising means something keeps changing the table: a datapath reload, - another writer, or galactic-cni writing an address that disagrees with this - node's `BGPRouter` as the sidecar reads it. These add 7 fixed series per - sidecar. - -```promql -# Encapsulation failing open: the source address is not set -max_over_time(galactic_ingress_sidecar_node_source_address_status{status=~"unresolved|error"}[10m]) == 1 -``` - -### Host return path — `galactic_sidecar_return_*` - -`galactic-cni` installs the host side of each sidecar's return path: for every -gateway address a sidecar on the node advertises, a route, a permanent -neighbor and a `vrf_table` entry that point a decapsulated reply at the -sidecar's pod. It runs one pass each tick, and these series report it. A -published advertisement only shows the sidecar's half; these show whether -replies can reach the pod. - -| Metric | Type | Labels | Meaning | -| ---------------------------------------------------------- | ------- | --------------------- | ----------------------------------------------------------------------------------------- | -| `galactic_sidecar_return_endpoints` | gauge | `state` | `desired` (advertised), `applied` (installed by the last pass), `pending` (not installed) | -| `galactic_sidecar_return_reconcile_total` | counter | `result` | Passes: `success`, `partial`, `waiting_identity`, `error` | -| `galactic_sidecar_return_last_completed_timestamp_seconds` | gauge | none | Unix time of the last pass that listed the advertisements; 0 before the first | -| `galactic_sidecar_return_operations_total` | counter | `operation`, `result` | `install` (per endpoint), `register`, `prune`, `reap`, each `success` or `error` | - -- `applied` and `pending` partition `desired`; do not add all three. A - scrape reads the three counts and the timestamp from one pass. -- `partial` means an endpoint failed to install or the prune failed. - `waiting_identity` means endpoints are advertised but this node's - `BGPRouter` has no SRv6 locator yet, so all are pending. `error` means - nothing could be installed: listing the advertisements, reading the node's - identity, or registering the node in the maps failed. A failed prune on a - `waiting_identity` or `error` pass shows only in `operations_total`. -- A pass that cannot list the advertisements leaves the counts and the - timestamp as they were. An ageing timestamp, not a zero count, is how a - failing or stalled pass shows. A node with no sidecar reports a fresh - timestamp and 0 desired. A node without a Kubernetes client or node name - never runs a pass, and its timestamp stays 0. -- `install` success means the route, neighbor and map entry were written. It - does not prove a reply reached the pod. These add 16 fixed series per node. - -```promql -# Return path not installed for some endpoint for 10 minutes; a fresh node -# waiting for its SRv6 locator is pending briefly -min_over_time(galactic_sidecar_return_endpoints{state="pending"}[10m]) > 0 - -# Return path pass stalled (passes run every 30s) -time() - galactic_sidecar_return_last_completed_timestamp_seconds > 300 -``` - -### Backend EndpointSlice repair — `galactic_endpointslice_repair_*` - -`galactic-cni` recreates the per-pod EndpointSlice of any Running pod on its -node that has a galactic IPv6 attachment but no slice, every 5 minutes (see -[conflist-reference.md](cni/conflist-reference.md#endpointslice-publish-http-ingress-backend-discovery)). -The HTTP ingress sidecar finds a VPC backend only through that slice, so each -recreated slice is a pod whose HTTP ingress was down until the pass. - -| Metric | Type | Labels | Meaning | -| ---------------------------------------------- | ------- | ------ | ------------------------------------------------------------------------------ | -| `galactic_endpointslice_repair_restored_total` | counter | none | Missing EndpointSlices the repair recreated | -| `galactic_endpointslice_repair_failures_total` | counter | none | Passes that could not list the node's pods, or read or create an EndpointSlice | - -A pod the pass cannot resolve (no NetworkAttachmentDefinition, `BGPRouter` or -`BGPVRFInstance`) is logged and retried on the next pass, not counted as a -failure. - -```promql -# Slices going missing on a node: something removed them while their pods ran -increase(galactic_endpointslice_repair_restored_total[1h]) > 0 -``` - -## Edge load balancer — `galactic_edge_*` - -`galactic-gateway`'s XDP DSR load balancer on gateway-role edge nodes. -Every gateway node serves every VIP identically (anycast), so the same -series appear on each one. Direct server return keeps no per-flow state, -so there is no connection table to report. See -[ARCHITECTURE-GATEWAY.md](agents/ARCHITECTURE-GATEWAY.md). - -| Metric | Type | Labels | Meaning | -| ------------------------------------------------------- | ------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `galactic_edge_rule_packets_total` | counter | `proto`, `port`, `vip`, `vpc` | Packets that matched the VIP, port and protocol, whatever happened to them next | -| `galactic_edge_rule_bytes_total` | counter | same | Bytes of those packets | -| `galactic_edge_rule_dropped_packets_total` | counter | same | Matched packets the datapath then dropped, such as for no backends. A subset of `rule_packets_total` | -| `galactic_edge_rule_backends` | gauge | same | Backends registered for the VIP | -| `galactic_edge_rule_seconds_since_last_packet` | gauge | same | Seconds since a packet last matched the VIP. Absent until the first one | -| `galactic_edge_return_packets_total` | counter | `vip`, `vpc` | Replies sourced from the VIP that this node forwarded past the kernel (`edge_return`) | -| `galactic_edge_return_bytes_total` | counter | same | Bytes of those replies | -| `galactic_edge_return_dropped_packets_total` | counter | same | Replies sourced from the VIP that the datapath dropped. A subset of `return_packets_total` | -| `galactic_edge_drops_total` | counter | `reason` | Packets `edge_lb` and `edge_return` dropped, by reason | -| `galactic_edge_neigh_fallbacks_total` | counter | none | Packets `edge_lb` handed to the kernel to resolve the next hop. Not counted as drops | -| `galactic_edge_control_plane_drops_total` | counter | `rule`, `reason` (`quota_exceeded`) | Rule applications refused before they reached the datapath | -| `galactic_edge_dispatch_lease_renewals_total` | counter | `slot`, `result` | Renewals of the gateway's XDP dispatcher slot leases. Dispatch mode only | -| `galactic_edge_dispatch_lease_expiry_timestamp_seconds` | gauge | `slot` | Unix time each lease, as last renewed, expires. Dispatch mode only | - -- `proto` is `tcp`, `udp`, or the protocol number for anything else. -- `vpc` is empty until the process has applied a rule that owns the VIP, - as after a restart before the first reconcile. A VIP address used by - rules of more than one VPC has an empty `vpc` on its return series, since - the return counters can't be split between them. -- The per-VIP counters survive re-registration, such as a reconcile that - only changes the backend list. The return series read zero, not absent, - on a node with no compute tier behind it. -- `galactic_edge_drops_total` reasons: `empty_backend_list`, - `no_encap_config`, `fib_no_neigh`, `fib_unreachable`, `fib_frag_needed`, - `fib_lookup_failed`, `adjust_head_failed`, `no_egress_ifindex`, - `redirect_failed`, `return_hop_limit`, `icmp_rate_limited`, plus - `unknown_` for an index the binary has no name for. -- `fib_no_neigh` counts only replies `edge_return` forwards and ICMP errors - the gateway sends. A load-balanced packet whose next hop has no neighbor - entry goes to the kernel, which resolves the neighbor and forwards it, and - is counted in `galactic_edge_neigh_fallbacks_total` instead. That counter - rises briefly after a link or node rejoins the fabric. Steady growth means - neighbor entries keep expiring or a next hop does not answer, and the - kernel drops what it cannot resolve. The counter records the handoff, not - delivery: these packets cross the node's netfilter FORWARD hook, unlike the - XDP path, so a host firewall that drops forwarded traffic drops them too. - -The port also serves controller-runtime's metrics for the -`NetworkGateway`/`NetworkService` reconcilers. - -```promql -# Requests per second per VIP and port -sum by (vpc, vip, port, proto) (rate(galactic_edge_rule_packets_total[5m])) - -# VIPs with no backends -max by (vip, port, proto) (galactic_edge_rule_backends) == 0 - -# Drops by reason -sum by (node, reason) (rate(galactic_edge_drops_total[5m])) > 0 - -# Rules refused by quota -sum by (node, rule) (increase(galactic_edge_control_plane_drops_total[1h])) > 0 -``` - -## Galactic Edge foundation — `galactic_edge_foundation_*` - -The attachment lifecycle and forwarding claims of the Galactic Edge -foundation (`config/galactic-edge/`), distinct from the edge load -balancer's `galactic_edge_*` above. Core's series come from -`galactic-controller --role=cell --edge`; every replica reads its cache at -scrape time, so aggregate them with `max`. Node series come from -`galactic-edge` on each edge node. No label names an attachment, pod, -route, prefix or address: `provider` is an approved `EdgeProvider`'s name -or `unknown`, and `reason` is a condition reason or `Other`. Find the -objects behind a series with the Events and `kubectl` queries in -[the troubleshooting guide](edge/troubleshooting.md). - -| Metric | Type | Source | Labels | Meaning | -| ------------------------------------------------- | ------- | ------ | ---------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| `galactic_edge_foundation_attachments` | gauge | core | `provider`, `state`, `reason` | Attachments by the first lifecycle stage they have not passed, and the condition reason holding them | -| `galactic_edge_foundation_routes` | gauge | core | `provider`, `state`, `reason` | Routes by claim state, and the condition reason holding them | -| `galactic_edge_foundation_services` | gauge | core | `provider`, `policy`, `reason` | Services whose traffic policy is `Resolved` or `Unresolved`, with the reason when unresolved | -| `galactic_edge_foundation_state_collect_errors` | gauge | core | none | Kinds the last scrape could not list and left out | -| `galactic_edge_foundation_failures_total` | counter | both | `component`, `stage`, `reason` | Transitions into a failed stage, counted once per transition, not per retry. Each also records an Event | -| `galactic_edge_foundation_gate_closures_total` | counter | node | `component`, `cause` | Open forwarding gates the agent closed, by cause. Each also records an Event on the route | -| `galactic_edge_foundation_cleanup_failures_total` | counter | node | `component` | Host state releases and gate sweeps that failed and are retried | -| `galactic_edge_foundation_links` | gauge | node | none | Host links registered with the node's forwarding gate | -| `galactic_edge_foundation_gates` | gauge | node | `state` (`open`, `expired`, `closed`) | Gates on the node. `expired` passed its deadline before the agent closed it | -| `galactic_edge_foundation_gate_drops_total` | counter | node | `check` (`ingress`, `egress`, `deliver`) | Packets dropped on an edge link because no open gate covered the address | -| `galactic_edge_foundation_scopes_lost` | gauge | node | none | VPC ownership scopes another writer took from this process | -| `galactic_edge_foundation_node_collect_errors` | gauge | node | none | Gate table reads the last scrape could not make | - -- Attachment `state`, in lifecycle order: `Admission`, `Allocation`, - `Programming`, `Ready`, `Active`, then `Draining` and `Releasing`. - `reason` is `Pending` while the stage's condition is unset, and - `NotReady` for `Ready`, whose own reason the provider writes. -- Route `state`: `Unclaimed`, `Pending`, `Accepted` (with the `Published` - condition's reason), `Published`, `Revoked` or `Released`. -- `stage`: `Admission`, `Allocation`, `Programming`, `Policy`, `Route`. -- `cause`: `Expired` (no renewal extended the gate), `Released`, - `Revoked`, `InstanceGone`, `AuthorityEnded`, `GrantCeiling`, - `RouteGone` or `HolderMoved`. -- Packet drops by traffic policy on an edge link are - `galactic_cni_traffic_policy_*` from `galactic-router`, labeled with the - attachment. - -```promql -# Attachments the foundation has admitted but not yet programmed, per provider -max by (provider, reason) (galactic_edge_foundation_attachments{state="Programming"}) - -# Gates closing because providers stop renewing -sum by (node) (increase(galactic_edge_foundation_gate_closures_total{cause="Expired"}[1h])) -``` - -## Traffic policy — `galactic_cni_traffic_policy_*` - -Interface traffic policy decisions in the uSID datapath. The counters live in -per-CPU BPF maps the datapath writes; `galactic-router`, which allocates -every counter row and knows the rule, policy and interface it belongs to, -reads and labels them, so they are served on its port (9179) and scraped by -the `galactic-router` PodMonitor. The prefix names the datapath, not the -process. Only routers running with `GALACTIC_ROUTER_TRAFFIC_POLICY=true` -export them. See [traffic-policy/node.md](traffic-policy/node.md). - -| Metric | Type | Labels | Meaning | -| ------------------------------------------------------ | ------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | -| `galactic_cni_traffic_policy_rule_hits_total` | counter | namespace, vpc, attachment, interface, interface_uid, direction, policy, policy_uid, rule, action | Packets evaluated with this rule as the winning rule | -| `galactic_cni_traffic_policy_rule_bytes_total` | counter | the same | Tenant IP bytes evaluated with this rule as the winning rule | -| `galactic_cni_traffic_policy_fallback_packets_total` | counter | namespace, vpc, attachment, interface, interface_uid, direction, reason | Packets denied without a winning rule | -| `galactic_cni_traffic_policy_fallback_bytes_total` | counter | the same | Tenant IP bytes denied without a winning rule | -| `galactic_cni_traffic_policy_unattributed_drops_total` | counter | direction, reason | Policy denials whose interface or fallback row could not be resolved | -| `galactic_cni_traffic_policy_accounting_errors_total` | counter | direction, action, reason | Verdicts whose rule counter row was missing; the verdict stood, the count was lost | -| `galactic_cni_traffic_policy_counter_read_errors` | gauge | none | Counter rows the last scrape could not read, and so left out rather than reporting zero | - -- `direction` is `ingress` or `egress`; `action` is `allow` or `deny`. -- `reason` is one of `no_match`, `policy_unavailable`, `parse_error` or - `classification_error`; `accounting_errors_total` uses - `missing_rule_counter`. -- `interface_uid` is the VPCAttachment UID. For a Galactic Edge - attachment, `namespace`, `attachment` and `interface_uid` are the - EdgeAttachment's, `vpc` is its EdgeService's VPC and `interface` is its - host link. `policy_uid` is the policy's - UID, or `builtin:default-deny-all:v1` for a direction with no reference, - which gets the built-in default. Its deny-all rule is a rule hit, not a - fallback, so the default stays visible per interface and direction. -- One evaluation produces one outcome: a rule's hit and bytes, or one - fallback pair. A packet between two managed interfaces is two - evaluations, the sender's egress and the receiver's ingress. -- A hit is a policy decision, not forwarded traffic: an allowed packet - dropped later still counts. -- Bytes are the tenant IP packet at the evaluation point, without Ethernet - or outer SRv6. A GSO packet counts once, at its buffer length. A packet - whose IP boundary cannot be found adds zero bytes. -- A rule keeps its series while its name and action stay the same within - one policy and interface lifetime, so editing its match keeps counting. - Rename a rule to start a fresh measurement. Rebinding another policy, - removing a rule, flipping its action, or recreating the interface starts - from zero. -- A node reboot or a datapath reload resets them. Use `rate()` or - `increase()`. - -```promql -# Rule hits per second, aggregated across nodes and interfaces. -sum by (namespace, policy, rule, direction, action) ( - rate(galactic_cni_traffic_policy_rule_hits_total[5m]) -) - -# Tenant bytes per second explicitly denied by a rule on each interface. -sum by (namespace, attachment, interface, interface_uid, direction, rule) ( - rate(galactic_cni_traffic_policy_rule_bytes_total{action="deny"}[5m]) -) - -# Failures and no-match denies, which are not attributed to a winning rule. -sum by (namespace, direction, reason) ( - rate(galactic_cni_traffic_policy_fallback_packets_total[5m]) -) - -# Interfaces still on the built-in default deny. -count by (namespace, attachment, direction) ( - galactic_cni_traffic_policy_rule_hits_total{policy_uid="builtin:default-deny-all:v1"} -) - -# Counts the datapath lost or could not attribute. -sum by (node, direction, reason) ( - rate(galactic_cni_traffic_policy_unattributed_drops_total[5m]) - or rate(galactic_cni_traffic_policy_accounting_errors_total[5m]) -) > 0 -``` - -## Routing - -Two planes: FRR (`fabric-router`) carries the underlay to the upstream -routers, and GoBGP (`galactic-router`) carries tenant EVPN/VPN routes. - -### Underlay — `frr_*` - -Exported by the `frr-exporter` sidecar with the `bgp`, `bgp6` and -`bgp.advertised-prefixes` collectors on; OSPF and BFD are off. - -| Metric | Use | -|------------------------------------------------|--------------------------------------------------------------------------------------------| -| `frr_bgp_peer_state` | `0` down, `1` established, `2` administratively down; labels include `peer`, `afi`, `safi` | -| `frr_bgp_peer_uptime_seconds` | Resets on every session drop, so `resets()` counts flaps | -| `frr_bgp_peer_prefixes_received_count_total` | Prefixes received per peer; a gauge despite the `_total` suffix | -| `frr_bgp_peer_prefixes_advertised_count_total` | Prefixes advertised per peer | -| `frr_collector_up` | `0` means the exporter can't read FRR, so every other `frr_*` on that node is stale | - -```promql -# Session table for a dashboard -max by (node, peer, afi) (frr_bgp_peer_state) - -# Flaps in the last 30m -resets(frr_bgp_peer_uptime_seconds{job="fabric-router"}[30m]) - -# Received prefixes halved while the session stays up -frr_bgp_peer_prefixes_received_count_total < 0.5 * (frr_bgp_peer_prefixes_received_count_total offset 1h) - and frr_bgp_peer_state == 1 -``` - -### Underlay config — `fabric_router_*` - -| Metric | Type | Labels | Meaning | -|-------------------------------------------------|---------|------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `fabric_router_bgp_mapped_nexthop` | gauge | `peer` | `1` when a session from a global IPv6 address announces an IPv4-mapped next hop (`::ffff:`); remote sites then lose their routes to this node's locators and NAT shards | -| `fabric_router_bgp_mapped_nexthop_resets_total` | counter | `peer` | Hard resets the agent issued to clear a mapped next hop | -| `fabric_router_bgp_uninstalled_routes` | gauge | `afi` (`ipv4`, `ipv6`) | Prefixes zebra has a BGP route for but that have no kernel route from any protocol | - -Both gauges refresh every 30s. On a node routed through the API the agent -also exports `fabric_router_activations_total`, -`fabric_router_activation_duration_seconds`, -`fabric_router_staging_runs_total`, `fabric_router_writer_lock_wait_seconds` -and `fabric_router_boot_source`; see below. - -### Fabric routing — `galactic_fabric_routing_*` - -`fabric-router-controller`'s leader exports each FabricRouterDeployment's -source, epochs, heartbeat, conditions and staged candidate, each outstanding -FabricReleaseAuthorization, and each fabric router's compile result, read from -its cache at scrape time. The full list, with the node agent's activation -metrics, lives with the rest of the operator guide in -[fabric-routing/operations.md](fabric-routing/operations.md#metrics-and-alerts). - -### Tenant routing — `galactic_router_*` - -| Metric | Type | Labels | Meaning | -|-----------------------------------------|-------|-----------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `galactic_router_route_install_failing` | gauge | `router` (namespace/name), `kind` | Routes with a known best path whose last kernel/datapath install failed. `kind="vrf"` is tenant VRF routes, `kind="plain"` routes with no route target (egress shards, VIPs). Above zero means part of a VPC or shard is unreachable from this node | -| `galactic_router_bmp_station_up` | gauge | `router`, `station` | BMP session to the collector: `1` up, `0` down | - -`galactic-router` also exposes the standard controller-runtime metrics -(`controller_runtime_reconcile_total`, -`controller_runtime_reconcile_errors_total`, `workqueue_*`) and Go process -metrics. GoBGP session state is not a metric: read it from `BGPPeer` status -(`STATE=Established`) or the BMP stream. - -```promql -sum by (node, kind) (galactic_router_route_install_failing) > 0 -sum by (controller) (rate(controller_runtime_reconcile_errors_total{job=~"galactic-router.*"}[10m])) -``` - -### Private service routes — `galactic_service_route_*` - -The node-local `ServiceRoutePolicy` controller in plain-mode -`galactic-router`, which programs attachment-scoped eBPF service paths. -The route reflector doesn't run it. Resource names are kept in logs, not -labels, so the series stay bounded. - -| Metric | Type | Labels | Meaning | -| --------------------------------------------------- | --------- | -------------------------------------------------------------- | --------------------------------------------------------- | -| `galactic_service_route_reconciliations_total` | counter | `result` (`success`, `error`) | `ServiceRoutePolicy` reconciliations | -| `galactic_service_route_reconcile_duration_seconds` | histogram | none | Time per reconcile (default buckets) | -| `galactic_service_route_route_operations_total` | counter | `operation` (`apply`, `remove`), `result` (`success`, `error`) | Datapath writes and removals | -| `galactic_service_route_programmed_routes` | gauge | none | Attachment-scoped service paths the controller now tracks | -| `galactic_service_route_producers` | gauge | `state` (`Healthy`, `Unhealthy`, `Unknown`) | Producers of `Spread` endpoints this node probes | - -Datapath drops on these paths are the `service_route_*` reasons of -`galactic_usid_drops_total`. - -```promql -sum by (node, operation) (rate(galactic_service_route_route_operations_total{result="error"}[10m])) > 0 -``` - -## NAT66 / NAT64 — `galactic_nat_*` - -One `galactic-nat` pod per egress shard; every value is per shard. - -| Metric | Type | Labels | Meaning | -|--------------------------------------------------------|---------|---------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------| -| `galactic_nat_conns` | gauge | `family` (`nat66`, `nat64`) | Rows in the connection table, expired sessions included. A session holds two rows | -| `galactic_nat_sessions` | gauge | `family`, `proto` (`tcp`, `udp`, `icmp`) | Live sessions: one per session within its idle timeout | -| `galactic_nat_conn_table_oldest_row_age_seconds` | gauge | none | Seconds since the least recently seen session, expired ones included, last translated a packet. Meaningful only on a near-full table | -| `galactic_nat_conn_table_max_entries` | gauge | none | Table capacity in rows, shared by both families | -| `galactic_nat_drops_total` | counter | `reason` | Packets dropped by the NAT datapath | -| `galactic_nat_packets_total` | counter | `family`, `direction` (`outbound`, `return`), `action` (`redirect`, `tx`) | Packets the shard translated and queued for transmit. Every combination is reported, zero included | -| `galactic_nat_bytes_total` | counter | same | Bytes of those packets: the translated IP packet, without Ethernet or the SRv6 outer header | -| `galactic_nat_datapath_enabled` | gauge | none | 1 when the datapath is turned on by configuration, 0 when it is turned off | -| `galactic_nat_datapath_attached` | gauge | none | 1 once the datapath has loaded and attached, 0 before that or while turned off | -| `galactic_nat_programmed` | gauge | none | 1 while the datapath holds an EgressShard identity, 0 while it claims no packet | -| `galactic_nat_uplink_covered` | gauge | `interface` | 1 for each resolved uplink the datapath translates on, 0 for one it misses. Absent while turned off | -| `galactic_nat_family_enabled` | gauge | `family` | 1 when the programmed identity has a masquerade address for the family | -| `galactic_nat_info` | gauge | `shard_sid`, `nat64_prefix`, `xdp_attach`, `version` | Always 1. Empty `shard_sid` and `nat64_prefix` while unprogrammed; `xdp_attach="off"` while turned off | -| `galactic_nat_masquerade_ports_in_use` | gauge | `family`, `address`, `proto` | Distinct masquerade ports live sessions hold on the address, toward any destination | -| `galactic_nat_masquerade_destination_ports_max` | gauge | `family`, `address`, `proto` | The most ports live sessions hold toward any single destination address and port. New flows to it fail as this nears the range | -| `galactic_nat_masquerade_port_range` | gauge | none | Ports (or ICMP Echo Identifiers) available toward each destination: 28000 | -| `galactic_nat_dispatch_lease_renewals_total` | counter | `slot`, `result` (`success`, `error`) | Renewals of the shard's XDP dispatcher slot lease. Dispatch mode only | -| `galactic_nat_dispatch_lease_expiry_timestamp_seconds` | gauge | `slot` | Unix time the lease, as last renewed, expires. Dispatch mode only | -| `galactic_nat_session_creates_total` | counter | `family`, `proto` | New sessions the shard opened, one masquerade port claim each | -| `galactic_nat_masquerade_claim_probes_total` | counter | `family`, `proto`, `probes` (`1`..`8`) | Those claims by how many probes each took. Rising multi-probe shares mean busy destinations are filling | -| `galactic_nat_uplink_resolve_errors_total` | counter | none | Failed re-resolutions of the uplinks after a link or route change; the shard keeps its previous coverage | -| `galactic_nat_uplink_rx_queue_packets_total` | counter | `interface`, `driver`, `queue` | Packets one NIC receive queue of an uplink received, from `ethtool -S`. Exported for `bnxt_en`, `ixgbe`, `ice`, `i40e`, `mlx5_core` | -| `galactic_nat_uplink_rx_queue_discards_total` | counter | `interface`, `driver`, `queue` | Packets one receive queue discarded before the datapath saw them. Reported only by drivers that count per queue: `bnxt_en` today | -| `galactic_nat_uplink_queue_driver_stat_total` | counter | `interface`, `driver`, `queue`, `stat` | One of a queue's other driver counters, under its `ethtool -S` name. `bnxt_en` only, see below | -| `galactic_nat_uplink_info` | gauge | `interface`, `driver`, `driver_version`, `firmware_version`, `kernel` | Always 1. Names each uplink's driver and NIC firmware versions and the node's kernel release | - -Caveats for the translated traffic and state series: - -- `outbound` is tenant traffic the shard decapsulated and translated toward - the internet; `return` is a reply translated back and encapsulated toward - the tenant. `tx` means the packet left over the uplink it arrived on, - `redirect` over another one. -- Messages the shard sends on its own behalf (Packet Too Big, Fragmentation - Needed, echo replies to its own address) and packets it passes on - unclaimed are not translations and are not counted. -- The counters live in a pinned map, so they outlive a pod restart, like - `galactic_nat_drops_total`. -- A shard can be attached and programmed and still translate nothing, when - its uplinks never hand it the traffic. Compare - `galactic_nat_packets_total{direction="outbound"}` with the compute nodes' - `galactic_cni_egress_shard_packets_total` for its `shard_sid` - (`GalacticNatNotTranslating`). -- Cardinality: 8 series each for packets and bytes, one `uplink_covered` - series per uplink, and one `info` series per shard. - -Caveats for the masquerade port series: - -- A port is claimed per destination address and port, not per masquerade - address, so the same port can serve many destinations at once. - `galactic_nat_masquerade_ports_in_use` can sit near the range on a healthy - shard that talks to many destinations; - `galactic_nat_masquerade_destination_ports_max` is what predicts exhaustion. -- A claim probes 8 of the range's ports, so a destination fails new flows well - before it is full: about 0.4% of new flows at half full, 17% at 80% - (`GalacticNatPortsNearExhaustion` warns at half full). -- Every protocol of every address the programmed identity serves is reported, - zero included, except when the session clock cannot be read: then only the - range is reported, rather than zeros that would read as an idle shard. An - address a re-programmed identity replaced is reported while live sessions - still hold its ports. -- Both are read from the session table walk at scrape time, like - `galactic_nat_sessions`, so they are approximate on a churning table. - -Caveats for session creation: - -- `galactic_nat_session_creates_total` is the sum of - `galactic_nat_masquerade_claim_probes_total` over `probes`. A claim that - finds no port is a `*_pat_exhausted` drop, and a claim that adopts a live - session's lost port opens no new session; neither is counted. -- With a share u of a destination's ports held, a claim needs more than k - probes with probability of roughly u^k (the probes walk consecutive ports, - and held ports cluster, so it is an estimate). The share of claims needing more than one - probe therefore estimates how full the destinations taking new flows are, - before `galactic_nat_masquerade_destination_ports_max` names the worst one - and long before `*_pat_exhausted` drops start. -- Cardinality: 6 creates series and 48 probe series per shard. - -The `EgressShard` reconciler's controller-runtime metrics -(`controller_runtime_reconcile_total{controller="egressshard"}`, -`controller_runtime_reconcile_errors_total`, `workqueue_*`) are served on the -same port, from the same registry. - -The dispatcher lease series are registered in dispatch mode only. The -edge gateway exports the same pair as `galactic_edge_dispatch_lease_*` for -its two slots; no shipped alert reads the gateway's yet. - -Caveats for the session table: - -- Expired sessions keep their rows until the LRU evicts them or a new claim - reuses their port, so `galactic_nat_conns` sits near capacity on any busy - shard. That is normal. Use `galactic_nat_sessions` for live sessions. -- Live sessions are at risk only when the table is full and its oldest row is - younger than the longest session timeout, 7440 s for established TCP. The - table's LRU evicts in approximate order, so the age is an estimate. -- The table is a self-evicting LRU, so the counts can move without traffic - changing. - -| Reason group | Values | Meaning | -|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------| -| Port exhaustion | `nat66_pat_exhausted`, `nat64_pat_exhausted` | No free port on the shard's public address; tenants see failed connections | -| Shard availability | `nat64_shard_unavailable` | NAT64 had no shard to send to | -| Return-path misses | `nat66_no_return_conn`, `nat64_no_return_conn`, `nat66_icmp_no_conn`, `nat64_icmp_no_conn`, `icmp_unsolicited` | Inbound packets with no matching session; background noise is normal, a jump after a restart means lost state | -| Malformed | `nat66_malformed_forward`, `nat66_malformed_return`, `nat64_malformed_forward`, `nat64_malformed_return`, `nat66_icmp_malformed`, `nat64_icmp_malformed`, `icmp_untranslatable` | Packets that couldn't be translated | -| IPv4 limits (NAT64) | `nat64_v4_fragment`, `nat64_v4_options`, `nat64_non_global_dest` | Unsupported IPv4 fragments or options, or a non-global destination | -| Forwarding | `fib_lookup_failed`, `fib_no_neigh`, `fib_unreachable`, `fib_frag_needed`, `adjust_head_failed`, `no_egress_ifindex`, `redirect_failed`, `hop_limit_exceeded` | Route, neighbor or redirect failure after translation | -| Rate limit | `icmp_rate_limited` | ICMP errors suppressed by the rate limiter | - -Caveats for the uplink queue counters: - -- `galactic_nat_uplink_queue_driver_stat_total` carries `bnxt_en`'s other - per-ring counters: transmit packets, discards and errors, `rx_errors`, - `rx_buf_errors`, `rx_resets` and `missed_irqs`. A ring's receive and transmit - share one completion ring, so comparing a stalled ring's transmit rate with - its siblings' shows whether transmit stopped along with receive. -- `galactic_nat_uplink_info` is exported for every uplink, whatever its - driver, so per-queue behavior can be matched against driver, firmware and - kernel versions across nodes. - -```promql -# Live sessions per family -sum by (node, family) (galactic_nat_sessions) - -# Idle live sessions being evicted: table full, oldest row younger than the TCP timeout -# (GalacticNatSessionTableEvictingLive) -sum by (node) (galactic_nat_conns) / on (node) max by (node) (galactic_nat_conn_table_max_entries) > 0.9 - and on (node) max by (node) (galactic_nat_conn_table_oldest_row_age_seconds) < 7440 - -# Port exhaustion or no shard -sum by (node, reason) (rate(galactic_nat_drops_total{reason=~".*_pat_exhausted|nat64_shard_unavailable"}[5m])) > 0 - -# New flows dropped for want of a port, held for 15 minutes (GalacticNatPortExhausted) -sum by (node, reason) (increase(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted"}[10m])) > 0 - -# Drop rate by reason -sum by (node, reason) (rate(galactic_nat_drops_total[5m])) > 0 - -# Translated packets per shard and direction -sum by (node, direction) (rate(galactic_nat_packets_total[5m])) - -# Share of the shard's own traffic it dropped (GalacticNatForwardDropRatio) -sum by (node) (rate(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted|nat(66|64)_malformed_forward|redirect_failed|no_egress_ifindex|adjust_head_failed"}[10m])) - / (sum by (node) (rate(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted|nat(66|64)_malformed_forward|redirect_failed|no_egress_ifindex|adjust_head_failed"}[10m])) - + sum by (node) (rate(galactic_nat_packets_total[10m]))) - -# Busiest destination per masquerade address, as a share of the range (GalacticNatPortsNearExhaustion) -max by (node, family, address, proto) (galactic_nat_masquerade_destination_ports_max) - / on (node) group_left () max by (node) (galactic_nat_masquerade_port_range) - -# Share of new sessions whose port claim needed more than one probe -sum by (node, family) (rate(galactic_nat_masquerade_claim_probes_total{probes!="1"}[10m])) - / sum by (node, family) (rate(galactic_nat_session_creates_total[10m])) - -# Seconds left on the dispatcher lease, by the node's clock -galactic_nat_dispatch_lease_expiry_timestamp_seconds - time() - -# No successful lease renewal in two minutes (GalacticNatDispatchLeaseExpiring) -changes(galactic_nat_dispatch_lease_renewals_total{result="success"}[2m]) == 0 - -# Shards turned on but not programmed, and uplinks not covered -galactic_nat_datapath_enabled == 1 and on (node) galactic_nat_programmed == 0 -galactic_nat_uplink_covered == 0 - -# Discard share per uplink receive queue (#673) -rate(galactic_nat_uplink_rx_queue_discards_total[5m]) - / (rate(galactic_nat_uplink_rx_queue_discards_total[5m]) + rate(galactic_nat_uplink_rx_queue_packets_total[5m])) - -# Transmit rate on each uplink ring, to compare a stalled ring with its siblings (#673) -sum by (node, interface, queue) ( - rate(galactic_nat_uplink_queue_driver_stat_total{stat=~"tx_(ucast|mcast|bcast)_packets"}[5m]) -) -``` - -## Fabric looking glass — `fabric_api_*` - -The opt-in fabric-api exports `fabric_api_node_*` from each node sidecar -(9345) and `fabric_api_gateway_*` from each cell gateway (9347). Both -export `fabric_api_credentials_loaded` and -`fabric_api_certificate_expiry_timestamp_seconds` for their mTLS identity. -Its full metric list, with labels and meanings, lives with the rest of -its operator reference in -[fabric-api/configuration.md](fabric-api/configuration.md). - -## Shipped alerts - -`config/monitoring/prometheusrule.yaml` (the `galactic-bgp` PrometheusRule, -unit-tested with `task test:alerts`) covers routing, fabric routing through -the API, the NAT session table -and ports, the egress shards' state, drop ratio and uplinks, the compute -nodes' egress shard groups, the fabric-api looking glass and the Galactic -Edge foundation. Every alert -carries `service: galactic`, `team: connect` and a `runbook_url`. - -| Alert | Fires when | For | Severity | -|--------------------------------------|---------------------------------------------------------------------------|-----|----------| -| FabricBGPSessionDown | `frr_bgp_peer_state == 0` | 5m | critical | -| FabricBGPSessionAdminDown | `frr_bgp_peer_state == 2` | 1h | warning | -| FabricBGPSessionFlapping | `resets(frr_bgp_peer_uptime_seconds[30m]) >= 3` | 0 | warning | -| FabricBGPPrefixesDropped | received prefixes under half of an hour ago, session up | 15m | warning | -| FabricRouterExporterCollectorFailing | `frr_collector_up == 0` | 10m | warning | -| FabricRouterMetricsDown | `fabric-router` scrape down | 5m | warning | -| FabricBGPMappedNextHop | `fabric_router_bgp_mapped_nexthop == 1` | 15m | critical | -| FabricBGPRoutesNotInstalled | `fabric_router_bgp_uninstalled_routes > 0` | 10m | warning | -| FabricConfigAgentMetricsDown | `fabric-config-agent` scrape down | 5m | warning | -| FabricRoutingNoEligibleRecovery | `Degraded` with reason `NoEligibleRecovery` | 5m | critical | -| FabricRoutingDeploymentDegraded | `Degraded` for another reason than that or `Recovered` | 15m | warning | -| FabricRoutingRecoveryConflict | `RecoveryConflict` True | 10m | warning | -| FabricRoutingAgentHeartbeatStale | on Shadow or CRD, no agent report for 5m, or never | 5m | warning | -| FabricRoutingReleaseFailed | a failed release still blocks its routing domain | 30m | warning | -| FabricRoutingReleaseUnknown | a release is `Unknown` | 15m | warning | -| FabricRoutingHandoffPending | `Accepted` False with reason `HandoffPending` or `ConfigMapRetired` | 15m | warning | -| FabricRoutingCandidateRejected | `Staged` False on a node staging on Shadow or CRD | 15m | warning | -| FabricRoutingPromotionRefused | `Accepted` False: `PromotionRefused`, `NotAuthorized`, `RevisionNotFound` | 15m | warning | -| FabricRoutingRevisionRefused | the controller refuses a fabric router's inputs | 15m | warning | -| FabricRoutingCollectFailing | the leader cannot read a kind from its cache | 10m | warning | -| FabricRouterControllerMetricsDown | `fabric-router-controller` scrape down | 5m | warning | -| GalacticRouterBMPStationDown | `galactic_router_bmp_station_up == 0` | 10m | warning | -| GalacticRouterRoutesNotInstalled | `galactic_router_route_install_failing > 0` | 10m | warning | -| GalacticRouterMetricsDown | `galactic-router` or `galactic-router-rr` scrape down | 5m | warning | -| GalacticNatSessionTableEvictingLive | table over 90% full, oldest row under 7440 s | 15m | warning | -| GalacticNatPortExhausted | `*_pat_exhausted` drops in every 10-minute window | 15m | warning | -| GalacticNatUplinkRxQueueStalled | one uplink rx queue delivers nothing while discarding | 10m | critical | -| GalacticNatUplinkRxQueueLossy | one uplink rx queue discards >1%, most siblings do not | 30m | warning | -| GalacticNatNotProgrammed | turned on, no EgressShard identity | 10m | warning | -| GalacticNatUplinkUncovered | `galactic_nat_uplink_covered == 0` | 10m | critical | -| GalacticNatForwardDropRatio | owned-traffic drops over 1% of translated, over 10 packets/s | 15m | warning | -| GalacticNatNotTranslating | compute nodes send to the shard's SID, it translates none outbound | 10m | critical | -| GalacticNatPortsNearExhaustion | busiest destination holds over half its port range | 10m | warning | -| GalacticNatDispatchLeaseFailing | more than two lease renewal errors in every 5-minute window | 5m | warning | -| GalacticNatDispatchLeaseExpiring | no successful lease renewal in 2 minutes | 0 | critical | -| GalacticNatMetricsDown | `galactic-nat` scrape down | 5m | warning | -| GalacticEgressPoolEmpty | no active shard for a class while routes on the node name it | 2m | critical | -| GalacticEgressPoolBelowMinimum | fewer active shards than `galactic_cni_egress_pool_min_active` | 10m | warning | -| GalacticEgressClassUnserved | every shard ineligible for a class | 15m | warning | -| GalacticEgressShardGroupDropping | `group_empty`, `shard_dead` or `parse_failed` in every 5m window | 10m | warning | -| GalacticEgressShardWatchNotSynced | hashed mode, `EgressShard` watch never listed | 10m | warning | -| GalacticEgressSweepFailing | sweep errors in every 10-minute window | 15m | warning | -| GalacticCNIMetricsDown | `galactic-cni` scrape down | 5m | warning | -| FabricAPIExecutionStalled | gateway has executions in flight, finished none in 10m | 10m | warning | -| FabricAPINodeDiagnosticsUnavailable | `fabric_api_node_diagnostics_available == 0` | 15m | warning | -| FabricAPINodeUnreachable | over half of 5+ node calls in 30m unreachable or timed out | 15m | warning | -| FabricAPIResultsOversized | 10+ `ResponseTooLarge` requests on a node in an hour | 15m | warning | -| FabricAPICleanupBacklog | over 50 expired `FabricQuery` objects left | 1h | warning | -| FabricAPICertificateRenewalFailing | mTLS certificate expires in under 4 hours | 15m | warning | -| FabricAPICredentialsMissing | `fabric_api_credentials_loaded == 0` | 15m | warning | -| FabricAPISearchIndexUnsynced | search index holds routes but is not synced with bgpd | 15m | warning | -| FabricAPIMetricsDown | `fabric-api-node` or `fabric-api-gateway` scrape down | 10m | warning | -| GalacticEdgeAttachmentNotProgrammed | admitted and allocated attachments not programmed by their node | 15m | warning | -| GalacticEdgeServicePolicyUnresolved | an `EdgeService`'s `TrafficPolicyResolved` is False | 10m | warning | -| GalacticEdgeScopeLost | `galactic_edge_foundation_scopes_lost > 0` | 5m | warning | -| GalacticEdgeCleanupFailing | more than two cleanup failures in every 15-minute window | 15m | warning | -| GalacticEdgeMetricsDown | `galactic-edge` or `galactic-controller` scrape down | 5m | warning | +See [Shipped alerts](observability/alerts.md#shipped-alerts). diff --git a/docs/migration/galactic-api-consolidation.md b/docs/migration/galactic-api-consolidation.md index 701216b28..530590d24 100644 --- a/docs/migration/galactic-api-consolidation.md +++ b/docs/migration/galactic-api-consolidation.md @@ -1,82 +1,11 @@ # Consolidating the cloud and network APIs -This change moves the `cloud` and `network` main-branch API types and the cloud -API types into Galactic. The served API group for VPC, BGP, gateway, traffic -policy, and FabricQuery resources is `galactic.datumapis.com/v1alpha1`. -`NetworkRule` is now `NetworkService`, matching the network main branch. +This document moved to [galactic-api-consolidation](../operations/migrations/galactic-api-consolidation.md). Update bookmarks to the maintained page. -The source revisions are cloud `55c38b5`, network `5a51626`, and Galactic -`c1769cb`. The VPC, subnet status, and attachment reconcilers run in the NSO -cell manager with `galactic.enabled: true` and the cell's `attachmentMode`. -The Galactic cell role retains BGP status projection and traffic policy. The central fabric identity reconciler -runs in the same binary with `--role=fabric` and a separate deployment because -its hub and IPAM credentials do not belong in each cell. + -## Cutover sequence +See [Cutover sequence](../operations/migrations/galactic-api-consolidation.md#cutover-sequence). -1. Export the existing `cloud.datumapis.com` and `network.datumapis.com` - resources, including their status, before changing any CRD or controller. - Keep the old CRDs installed throughout cutover. Kubernetes treats each new - group as a different resource; installing the Galactic CRDs does not copy - objects or convert owner references. -2. Apply `config/crd` on the hub and every cell that serves these kinds. - Apply `config/fabric-api/crd/galactic.datumapis.com_fabricqueries.yaml` - wherever FabricQuery is served. Install the `galactic-controller` cell - RBAC, webhook certificate, and both webhook configurations before routing - requests to the new controllers. Upgrade NSO's cell manager with Galactic - reconciliation disabled until the old cell writer is stopped. -3. Deploy `config/galactic-controller/fabric` centrally, with a hub credential - bound to `config/galactic-controller/fabric/hub-rbac.yaml` on the hub and an - IPAM credential for the platform project. Confirm the new - `NetworkFabricIdentity` objects have the same identity values as the old - objects and have propagated to their cells before stopping the old fabric - identity controller. The claim names are stable, so the allocator reuses - the retained IPAM claims. -4. Move the desired BGP, gateway, egress, and service resources to the new - group before replacing their node controllers. Use the new API schemas; - `NetworkRule` becomes `NetworkService`. Copy specs and selected labels and - annotations, not Kubernetes UIDs, resource versions, or status. The old - objects do not become visible to the new controllers automatically. -5. Stop the old cloud cell controller before enabling Galactic reconciliation - in NSO's cell manager, so only one controller writes each - NetworkAttachmentDefinition and NSO `NetworkInterface` status. Configure - the correct `galactic.attachmentMode` for the cell. NSO reuses the legacy NAD's VPC and - attachment IDs, transfers its owner reference to the new attachment, and - updates `NetworkInterface.status.attachmentRef.apiGroup` to - `galactic.datumapis.com`. On group change it sets `Programmed=Unknown` until - the new-group BGP advertisement proves programming again. -6. Reattach or roll existing workloads to republish their CNI-created - `BGPAdvertisement` objects under the new group. Keep old routing state - available until their new advertisements are present and the NSO interface - and claim conditions have reconverged. Verify every live interface reports - the Galactic attachment group and `Programmed=True`, and check gateway - and BGP node status before retiring old CRDs and controllers. + -NSO writes `NetworkInterfaceAttachmentRef.APIGroup` as -`galactic.datumapis.com` when its cell reconciler creates a new attachment. -The tenant-facing NSO CRDs remain in `networking.datumapis.com`. Galactic's -BGP reconciler projects data-plane programming status to the Galactic -attachment and NSO interface and claim. - -The old group's VPC finalizers require the old controller to finish deletion, -or an operator-reviewed cleanup after the old objects are no longer serving. -Do not remove old CRDs while objects still carry finalizers or while a node -still depends on their advertisements. - -## Retiring the old API groups - -The new Galactic binaries read and write `galactic.datumapis.com`. Old -`network.datumapis.com` BGP objects can remain after rollout, including objects -for a workload whose CNI ADD ran before the new group was installed. Their old -`Ready` conditions may be stale; do not treat that status as proof that the new -router still advertises their routes. - -Run `hack/audit-legacy-bgp.py --context ` for every migrated cell. It -flags old-only objects, different specs, and new counterparts without a Ready -condition. For each result, check whether its workload still needs a route. -Reattach or restart a live workload and confirm the new-group advertisement -and VRF become ready before removing the old object. Once the -old group has no users, export its objects for the migration record, remove the -old objects, then remove the old CRDs through infra's retirement procedure. -Never delete an old CRD while it still holds objects: Kubernetes deletes those -objects with the CRD. +See [Retiring the old API groups](../operations/migrations/galactic-api-consolidation.md#retiring-the-old-api-groups). diff --git a/docs/node-labels.md b/docs/node-labels.md index 41c4b7c2b..26074d8ca 100644 --- a/docs/node-labels.md +++ b/docs/node-labels.md @@ -1,323 +1,67 @@ # Node Labeling Strategy -> How Galactic decides which DaemonSets run on which nodes. - -_Last updated: 2026-10-06_ - -This document is cross-cutting — it covers the node-selection contract shared -by `galactic-cni`, `galactic-router`, `galactic-gateway`, `galactic-nat`, -and `fabric-router`, none of which owns it individually. See -[AGENTS.md](../AGENTS.md) for which per-component architecture doc to read -for everything else about a given binary. - ---- - -## The labels - -| Label | Deploys | Kind | -|-------------------------------------------|--------------------------------------------------------------------------------|-------------------------| -| `galactic.datumapis.com/node=compute` | nothing exclusively (see below) | primary role enum | -| `galactic.datumapis.com/node=edge` | `galactic-vrf` (ingress sidecar pods); hosts `galactic-gateway`/`galactic-nat` | primary role enum | -| `galactic.datumapis.com/gateway=enabled` | `galactic-gateway`, on a `node=edge` node only | opt-in flag (edge only) | -| `galactic.datumapis.com/nat=enabled` | `galactic-nat`, on a `node=edge` node only | opt-in flag (edge only) | -| `galactic.datumapis.com/edge=enabled` | `galactic-edge`, on a `node=edge` node only | opt-in flag (edge only) | -| `galactic.datumapis.com/galactic=router` | `galactic-cni`, `galactic-router` (plain/tenant mode) | mode enum | -| `galactic.datumapis.com/galactic=control` | `galactic-router-rr` | mode enum | -| `galactic.datumapis.com/fabric=router` | `fabric-router` (plain mode) | mode enum | -| `galactic.datumapis.com/fabric=control` | `fabric-router` (reflector mode, same image) | mode enum | - -`galactic-gateway` and `galactic-nat` are **never deployed automatically**: a -node runs one only after an operator labels it, and their manifests live in -`base/` directories no default kustomization applies. Each requires -`galactic.datumapis.com/node=edge` *and* its own opt-in label, so they run -on edge nodes alongside `galactic-vrf`, and only on the edge nodes an -operator picks. They are independent of each other, so an edge node can -carry either opt-in label or both. - -Every affinity also excludes Kubernetes control-plane nodes -(`node-role.kubernetes.io/control-plane: DoesNotExist`), independently of -which of the above a node carries. - ---- - -## Two label families, each an enum, for two different reasons - -**`galactic.datumapis.com/node` is a primary-role enum.** A node has exactly -one value — `compute` or `edge` — because a Kubernetes label key is -single-valued, and these two are genuinely mutually exclusive by design: -`edge` nodes are tainted specifically to keep tenant workloads off them (see -`deploy/containerlab/node_files/iad/config.yaml`'s NAT-node taints), so a -node is never both at once. Each value deploys only what actually differs -between the two roles, not everything that role runs (see the worked example -below for the full per-node picture). Today that is all on the `edge` side: -`galactic-gateway` (ingress) and `galactic-nat` (egress). `compute` deploys -nothing exclusively since `galactic-nat` moved to `edge`, but the label stays: -it is still the tenant-serving role, it keeps `edge`'s mutual exclusivity -meaningful, and it is where the next compute-only component would key. - -**`galactic.datumapis.com/galactic` and `galactic.datumapis.com/fabric` are -each a mode enum: "plain" vs. "control."** `galactic-cni` and -`galactic-router` (plain mode) are needed by *both* primary roles — every -`compute` node and every `edge` node runs both, unconditionally. Modeling -that as two independent boolean flags (as an earlier version of this scheme -did) or as an enumerated `In: [compute, edge]` list on each of their own -affinities both have the same failure mode this scheme has already been -bitten by once (see the bugs list below): a list of roles that has to be -kept in sync by hand every time a role is added, and silently goes stale -when it isn't. A single key with `router`/`control` values sidesteps that: -`galactic-router-rr` (the EVPN route reflector) and plain `galactic-router` -are genuinely mutually exclusive on one node — a route-reflector node never -also runs plain-mode `galactic-router`, and vice versa — so encoding them as -values of one key, rather than two separately-settable booleans, makes that -exclusivity structural instead of a convention someone has to maintain. -`galactic.datumapis.com/fabric` mirrors the same shape for the underlay: -`router` is the ordinary underlay eBGP participant (every current role), -`control` is the underlay's own route reflector — distinct from the EVPN -reflector above, and on the standard BGP port rather than a dedicated one, -since `fabric-router` and `galactic-router-rr` are already two independent -processes on any node that runs both. - -`galactic.datumapis.com/galactic` and `galactic.datumapis.com/fabric` are -independent keys, so a node can mix values across them — e.g. an EVPN route -reflector (`galactic=control`) that is just an ordinary underlay participant, -not the underlay's own reflector (`fabric=router`). - -**The rule of thumb**: if two things can never legitimately coexist on one -node, encode the difference as one key's enum value — whether that's a -primary role (`node`) or a mode within a family (`galactic`, `fabric`). If -they *can* coexist, or you're not sure, give the capability its own -independent flag instead. Getting this wrong is a real, previously-shipped -bug, not a hypothetical: - -- `fabric-router`'s affinity used to enumerate roles via `In: [edge, - route-reflector, gateway]`. `nat66` was never added to that list, so a - NAT66 shard node silently never got the underlay BGP session its own SID - advertisement depends on. Fixed by making `fabric` its own label that any - role opts into, rather than a list `fabric-router` has to keep in sync - with every other component's roles. -- `galactic-nat` used to require `galactic.datumapis.com/node: nat66` as a - dedicated enum value. Since a node can only have one `node` value, that - made it impossible for a node to be both `edge` (i.e. `compute`, in - today's naming — see below) and a NAT66 shard at once, which is the only - configuration that's ever actually used. Fixed by dropping `nat66` from - the enum and folding shard duty into `node=compute` directly. It has since - moved to `node=edge`, where a shard is one hop from the transit its - masquerade addresses are originated into. An edge node runs it once it - carries `galactic.datumapis.com/nat=enabled`, sharing each uplink's XDP - hook with `galactic-gateway` through the node's XDP dispatcher. -- `galactic-router-rr` used to require a dedicated - `galactic.datumapis.com/galactic-route-reflector=true` boolean flag, - independent of everything else. Once `galactic-cni`/`galactic-router` - needed to run on *both* `compute` and `edge` nodes, that would have meant - *three* independent flags (`galactic-cni`, `galactic-router`, - `galactic-route-reflector`) with an unenforced rule that the last one - must never coexist with the second. Fixed by folding the first two into - one `galactic=router` value and the third into the mutually-exclusive - `galactic=control` value of that same key — see above. - ---- - -## What `edge` means, and how gateway and NAT opt in - -**`galactic.datumapis.com/node=edge` marks the nodes that host -`galactic-vrf`** — the ingress sidecar that runs next to Envoy and wires a -tenant VRF into the pod — **and the only nodes that may host -`galactic-gateway` and `galactic-nat`.** Like `compute`, an `edge` node also -runs `galactic-cni`, `galactic-router` and `fabric-router`, through their own -labels (`galactic=router`, `fabric=router`). - -`node=edge` alone does not deploy the gateway or a shard. Each needs its own -opt-in label on top (`gateway=enabled`, `nat=enabled`), so an operator picks -which edge nodes run which, and a cluster can have edge nodes that run -neither. Their affinities require both labels, so neither ever lands on a -`compute` node, a node with no `node` value, or a control-plane node. - -Earlier versions of this scheme went the other way twice. First `node=edge` -alone selected both, so they could never be placed independently (one label, -one value). Then they got their own labels but refused any node that carried -a `node` value at all, which kept them off `galactic-vrf`'s nodes. No -datapath reason required that: `galactic-vrf` claims nothing on the uplinks -(its replies arrive encapsulated to the node's own uSID, which the gateway -and the shard pass untouched), and egress shards are meant to run on edge -nodes. So all three now share the edge node. One configuration hazard -remains: an `EgressShard` whose SID reuses its node's router Block and -Node-ID captures that node's tenant ingress -([#711](https://github.com/datum-cloud/galactic/issues/711)). - -Note the historical wording elsewhere in this repo: "edge XDP" describes -`galactic-gateway`'s datapath and predates this scheme; it is unrelated to -`node=edge`. - -**Placement of `galactic-vrf` itself** is not defined in this repo yet (no -`config/galactic-vrf/`; see the note above `publish-galactic-vrf-image` in -`.github/workflows/publish.yaml`). Whatever defines its pods must require -`galactic.datumapis.com/node=edge`. - ---- - -## Per-role reference - -### `galactic.datumapis.com/node=compute` - -The ordinary tenant-serving node. Runs (via -`galactic.datumapis.com/galactic=router`, below) `galactic-cni` and -`galactic-router`, and nothing keyed on this label itself. - -`galactic-nat` used to run here, one egress shard per compute node. It now -runs on `nat=enabled` nodes (below): a compute node's tenant egress is -encapsulated toward its own site's shards instead -(`GALACTIC_CNI_EGRESS_SHARD_SIDS`, set per site, with no other site's shard as -a fallback). - -### `galactic.datumapis.com/node=edge` - -The nodes that host `galactic-vrf`. Runs (via -`galactic.datumapis.com/galactic=router` and -`galactic.datumapis.com/fabric=router`) `galactic-cni`, `galactic-router` and -`fabric-router`. A manifest in this repo deploys nothing on this label alone, -but it is required by `galactic-gateway` and `galactic-nat`, which run here -when the node also carries `gateway=enabled` or `nat=enabled` (below). - -### `galactic.datumapis.com/gateway=enabled` - -Runs `galactic-gateway`'s standalone, single-container pod -(`config/galactic-gateway/base/daemonset.yaml`). Opt-in, never automatic, and -independent of `nat`. The node must also carry -`galactic.datumapis.com/node=edge`. `galactic-router` and `galactic-cni` run -here too if the node also has `galactic=router`, as their own independent -DaemonSets. - -### `galactic.datumapis.com/nat=enabled` - -Runs `galactic-nat`, the egress shard -(`config/galactic-nat/base/daemonset.yaml`). Opt-in, never automatic, and -independent of `gateway`. The node must also carry -`galactic.datumapis.com/node=edge`. - -A node with no gateway can use the base, whose `GALACTIC_NAT_XDP_ATTACH` -defaults to `direct`: the shard attaches its own XDP program to its uplinks. -A node that also carries `gateway=enabled` must set -`GALACTIC_NAT_XDP_ATTACH=dispatch`. An interface takes one program, so the -shard and the gateway, which runs in dispatch mode by default, each run from -their own slot of the node's shared, pinned XDP dispatcher, and either can -restart without detaching the other (see -[docs/nat/configuration.md](nat/configuration.md)). Compute nodes reach their -site's shards over SRv6 (`GALACTIC_CNI_EGRESS_SHARD_SIDS`). - -### `galactic.datumapis.com/edge=enabled` - -Runs `galactic-edge`, the Galactic Edge node agent -(`config/galactic-edge/base/daemonset.yaml`), which programs and releases the -host side of every `EdgeAttachment` admitted to the node. Opt-in, never -automatic, and independent of `gateway` and `nat`. The node must also carry -`galactic.datumapis.com/node=edge`, and `galactic=router`: an attachment joins -its VPC's canonical host VRF and uSID entry, which `galactic-cni` creates. - -### `galactic.datumapis.com/galactic=router` - -Runs `galactic-cni` and `galactic-router` in its plain (non-reflector) -mode, together, on every `compute` and every `edge` node. - -- `config/galactic-cni/daemonset.yaml` -- `config/galactic-router/overlays/router/daemonset-patch.yaml` - -### `galactic.datumapis.com/galactic=control` - -Runs `galactic-router-rr` (`GALACTIC_ROUTER_REFLECTOR=true`), the EVPN -route reflector every `galactic=router` node's `galactic-router` peers into -over iBGP. Mutually exclusive with `galactic=router` on the same node (one -label key, one value) — a route-reflector node never also runs plain-mode -`galactic-router`, and never runs `galactic-cni` either (a dedicated -route-reflector node hosts no tenant pods). See -`config/galactic-router/overlays/control/daemonset-patch.yaml`. - -### `galactic.datumapis.com/fabric=router` - -Runs `fabric-router`, the FRR underlay eBGP DaemonSet, independently of -whatever `node` or `galactic` value a node also carries. See -`config/fabric-router/daemonset.yaml`'s own affinity comment for the full -history of why this is a dedicated label rather than an enumerated list. - -### `galactic.datumapis.com/fabric=control` - -The underlay's own iBGP route reflector, distinct from the EVPN one above. -Unlike `galactic=control`, this has no separate binary or overlay to run -- -`fabric-router` has no Go code of its own at all (it's a plain FRR -container), so `control` runs the identical image `router` does. The -reflector-vs-plain distinction lives entirely in the per-node `frr.conf` -`infra`'s own renderer produces for this node: a `route-reflector-client` -peer-group instead of the four canonical ones. This DaemonSet's affinity -matches both values identically; only the rendered config differs. -Mutually exclusive with `fabric=router` on the same node, the same way -`galactic`'s two values are. - ---- - -## Worked example: the containerlab lab - -| Node | `node` | `galactic` | `fabric` | Runs | -|------------------------------------------------------------|-----------|------------|----------|----------------------------------------------------------------------------------------------------------------------------| -| `dfw-worker`, `sjc-worker`, `iad-worker` | `compute` | `router` | `router` | `galactic-cni`, `galactic-router`, `fabric-router` | -| `dfw-worker2`, `dfw-worker3`, `sjc-worker2`, `iad-worker2` | `edge` | `router` | `router` | `galactic-gateway` (`gateway=enabled`), `galactic-nat` (`nat=enabled`), `galactic-cni`, `galactic-router`, `fabric-router` | -| `iad-worker3` | — | `control` | `router` | `galactic-router-rr`, `fabric-router` | - -The lab's edge workers carry `node=edge` plus both `gateway=enabled` and -`nat=enabled`, which place a `galactic-gateway` and a `galactic-nat` shard on -each; the lab deploys no `galactic-vrf` yet. The shard runs with -`GALACTIC_NAT_XDP_ATTACH=dispatch`, so it and the gateway share the uplinks -through the node's XDP dispatcher. - -The reflector row is the one that shows why `galactic` is a mode enum rather -than a boolean: `iad-worker3` carries no `node` value at all. Both `node` -roles imply `galactic=router`, and `router`/`control` are mutually exclusive -values of one key, so a reflector structurally cannot also be a compute or -edge node — it needs a worker of its own. - -Every worker in the lab carries `fabric=router` today (see -`deploy/containerlab/node_files/{dfw,iad,sjc}/config.yaml`), since every -role in this topology needs the underlay. That's a property of this -particular lab's topology, not a rule the label scheme enforces — a real -deployment is free to have nodes with no galactic role at all (GPU, -monitoring, etc.), which correctly get none of these labels and none of -these DaemonSets. - ---- - -## Migrating gateway and NAT nodes onto `node=edge` - -The DaemonSet controller removes a pod from any node its affinity stops -matching, whether the node's labels or the DaemonSet's affinity changed. The -old manifests refuse a node carrying `galactic.datumapis.com/node` and the new -ones require `node=edge`, so no order avoids one restart of each gateway and -shard. Keep the gap to that restart: - -1. On each gateway or NAT node, add `galactic.datumapis.com/node=edge`, - keeping `galactic.datumapis.com/gateway=enabled` and/or - `galactic.datumapis.com/nat=enabled`. The old manifests remove the gateway - and shard pods from the node at once, and anything placed on `node=edge`, - such as `galactic-vrf` and the Envoy it serves, can now land on it. -2. Apply the new manifests straight away. They place the pods back on the - node. - -Production is not affected: infra sets its own placement and already requires -`node=edge`. A gateway or NAT node that should not become an edge node has no -place in the new scheme: move its role to an edge node instead. - ---- - -## Adding a new role - -1. Decide whether it's mutually exclusive with an existing enum value in - the same family (→ a new value of that key) or can coexist with an - existing role (→ its own independent label). Default to the independent - label unless you're certain the exclusivity is real and permanent — see - the bugs list above for what happens when that assumption turns out to - be wrong later. -2. If it needs the underlay, it still needs - `galactic.datumapis.com/fabric=router` set explicitly — nothing infers - this from the new label automatically. -3. If it needs `galactic-cni`/`galactic-router` (plain mode), set - `galactic.datumapis.com/galactic=router` — don't add it to an enumerated - list on `galactic-cni`'s or `galactic-router`'s own affinity. -4. Update the reference table at the top of this document and in - [AGENTS.md](../AGENTS.md)'s "Node label strategy" section. +This document moved to [node-labels](operations/node-labels.md). Update bookmarks to the maintained page. + + + +See [The labels](operations/node-labels.md#the-labels). + + + +See [Two label families, each an enum, for two different reasons](operations/node-labels.md#two-label-families-each-an-enum-for-two-different-reasons). + + + +See [What `edge` means, and how gateway and NAT opt in](operations/node-labels.md#what-edge-means-and-how-gateway-and-nat-opt-in). + + + +See [Per-role reference](operations/node-labels.md#per-role-reference). + + + +See [`galactic.datumapis.com/node=compute`](operations/node-labels.md#galacticdatumapiscomnodecompute). + + + +See [`galactic.datumapis.com/node=edge`](operations/node-labels.md#galacticdatumapiscomnodeedge). + + + +See [`galactic.datumapis.com/gateway=enabled`](operations/node-labels.md#galacticdatumapiscomgatewayenabled). + + + +See [`galactic.datumapis.com/nat=enabled`](operations/node-labels.md#galacticdatumapiscomnatenabled). + + + +See [`galactic.datumapis.com/edge=enabled`](operations/node-labels.md#galacticdatumapiscomedgeenabled). + + + +See [`galactic.datumapis.com/galactic=router`](operations/node-labels.md#galacticdatumapiscomgalacticrouter). + + + +See [`galactic.datumapis.com/galactic=control`](operations/node-labels.md#galacticdatumapiscomgalacticcontrol). + + + +See [`galactic.datumapis.com/fabric=router`](operations/node-labels.md#galacticdatumapiscomfabricrouter). + + + +See [`galactic.datumapis.com/fabric=control`](operations/node-labels.md#galacticdatumapiscomfabriccontrol). + + + +See [Worked example: the containerlab lab](operations/node-labels.md#worked-example-the-containerlab-lab). + + + +See [Migrating gateway and NAT nodes onto `node=edge`](operations/node-labels.md#migrating-gateway-and-nat-nodes-onto-nodeedge). + + + +See [Adding a new role](operations/node-labels.md#adding-a-new-role). diff --git a/docs/observability/README.md b/docs/observability/README.md new file mode 100644 index 000000000..c8069237b --- /dev/null +++ b/docs/observability/README.md @@ -0,0 +1,60 @@ +# Observability + +Metrics, scrape configuration and shipped alert rules. Use the subsystem reference for metric names, labels and interpretation. + +- [VPC dataplane — `galactic_usid_*`](vpc-dataplane.md) +- [Tenant egress pool — `galactic_cni_egress_*`](egress-pool.md) +- [VPC ingress — `galactic_ingress_sidecar_*`](vpc-ingress.md) +- [Edge load balancer — `galactic_edge_*`](gateway.md) +- [Galactic Edge foundation — `galactic_edge_foundation_*`](edge.md) +- [Traffic policy — `galactic_cni_traffic_policy_*`](traffic-policy.md) +- [Routing](routing.md) +- [NAT66 / NAT64 — `galactic_nat_*`](nat.md) +- [Fabric looking glass — `fabric_api_*`](fabric-api.md) +- [Shipped alerts](alerts.md) + +## Where the metrics come from + +The dataplane and fabric-router DaemonSets use `hostNetwork: true`, so +their metric ports are bound on the node itself. `galactic-vrf` runs as a sidecar in the ingress +proxy's pod instead, which has its own network namespace, so it shares +the 9182 default with `galactic-nat` without clashing, even on the edge +nodes that run both. `galactic-controller`, `fabric-router-controller` and +the fabric-api gateway are Deployments, scraped per pod. + +| Area | Component | Metric prefix | Port | `job` from `config/monitoring/` | +| ----------------------- | --------------------------------------------------------- | ------------------------------------------------------------- | -------------- | ---------------------------------------- | +| VPC dataplane | `galactic-cni` (`credential-refresh`, the datapath owner) | `galactic_usid_*` | 9180 | `galactic-cni` | +| Tenant egress pool | `galactic-cni` | `galactic_cni_egress_*` | 9180 | `galactic-cni` | +| VPC ingress | `galactic-vrf` | `galactic_ingress_sidecar_*` | 9182 (default) | none shipped | +| VPC ingress return path | `galactic-cni` (`credential-refresh`) | `galactic_sidecar_return_*` | 9180 | `galactic-cni` | +| VPC ingress backends | `galactic-cni` (`credential-refresh`) | `galactic_endpointslice_repair_*` | 9180 | `galactic-cni` | +| Edge load balancer | `galactic-gateway` | `galactic_edge_*`, controller-runtime | 8081 | none shipped | +| Tenant routing (GoBGP) | `galactic-router`, `galactic-router-rr` | `galactic_router_*`, controller-runtime | 9179 | `galactic-router` / `galactic-router-rr` | +| Private service routes | `galactic-router` (plain mode only) | `galactic_service_route_*` | 9179 | `galactic-router` | +| Traffic policy | `galactic-router` with `GALACTIC_ROUTER_TRAFFIC_POLICY` | `galactic_cni_traffic_policy_*` | 9179 | `galactic-router` | +| Traffic policy webhook | `galactic-controller` | controller-runtime | 9184 | `galactic-controller` | +| Galactic Edge (core) | `galactic-controller --role=cell --edge` | `galactic_edge_foundation_*` | 9184 | `galactic-controller` | +| Galactic Edge (node) | `galactic-edge` | `galactic_edge_foundation_*`, controller-runtime | 9186 | `galactic-edge` | +| Underlay routing (FRR) | `fabric-router` `frr-exporter` sidecar | `frr_*` | 9342 | `fabric-router` | +| Underlay config | `fabric-router` `fabric-config-agent` | `fabric_router_*` | 9343 | `fabric-config-agent` | +| Fabric routing (API) | `fabric-router-controller` | `galactic_fabric_routing_*` (leader only), controller-runtime | 9185 | `fabric-router-controller` | +| Fabric looking glass | `fabric-api` node sidecar | `fabric_api_node_*`, `fabric_api_*` | 9345 | `fabric-api-node` | +| Fabric looking glass | `fabric-api` cell gateway | `fabric_api_gateway_*`, `fabric_api_*` | 9347 | `fabric-api-gateway` | +| NAT66 / NAT64 | `galactic-nat` (one per egress shard) | `galactic_nat_*` | 9182 | `galactic-nat` | + +`config/monitoring/` ships PodMonitors for `galactic-cni`, +`galactic-router`, `fabric-router` (including the opt-in fabric-api +sidecar), `fabric-router-controller`, the fabric-api gateway, +`galactic-nat`, `galactic-controller` and `galactic-edge`. Scraping +`galactic-vrf` or `galactic-gateway` needs a scrape object of your own. Copy the shipped +PodMonitors' relabeling of `__meta_kubernetes_pod_node_name` into `node`: +every galactic metric is per node, and `node` is the label you group and +alert by. `fabric-router-controller`'s fleet series name the node each +deployment or router targets themselves, and their `namespace` is the +object's, which its PodMonitor keeps with `honorLabels`. + +The eBPF-backed metrics (`galactic_usid_*`, `galactic_cni_egress_shard_*`, +`galactic_edge_*`, `galactic_edge_foundation_gate_drops_total`, `galactic_nat_*`) are read from BPF maps at scrape time, +and a pod restart that reloads the program resets them. Always use +`rate()` / `increase()`, never raw counter values. diff --git a/docs/observability/alerts.md b/docs/observability/alerts.md new file mode 100644 index 000000000..0f8368ebd --- /dev/null +++ b/docs/observability/alerts.md @@ -0,0 +1,71 @@ +# Shipped alerts + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +`config/monitoring/prometheusrule.yaml` (the `galactic-bgp` PrometheusRule, +unit-tested with `task test:alerts`) covers routing, fabric routing through +the API, the NAT session table +and ports, the egress shards' state, drop ratio and uplinks, the compute +nodes' egress shard groups, the fabric-api looking glass and the Galactic +Edge foundation. Every alert +carries `service: galactic`, `team: connect` and a `runbook_url`. + +| Alert | Fires when | For | Severity | +| -------------------------------------- | --------------------------------------------------------------------------- | ----- | ---------- | +| FabricBGPSessionDown | `frr_bgp_peer_state == 0` | 5m | critical | +| FabricBGPSessionAdminDown | `frr_bgp_peer_state == 2` | 1h | warning | +| FabricBGPSessionFlapping | `resets(frr_bgp_peer_uptime_seconds[30m]) >= 3` | 0 | warning | +| FabricBGPPrefixesDropped | received prefixes under half of an hour ago, session up | 15m | warning | +| FabricRouterExporterCollectorFailing | `frr_collector_up == 0` | 10m | warning | +| FabricRouterMetricsDown | `fabric-router` scrape down | 5m | warning | +| FabricBGPMappedNextHop | `fabric_router_bgp_mapped_nexthop == 1` | 15m | critical | +| FabricBGPRoutesNotInstalled | `fabric_router_bgp_uninstalled_routes > 0` | 10m | warning | +| FabricConfigAgentMetricsDown | `fabric-config-agent` scrape down | 5m | warning | +| FabricRoutingNoEligibleRecovery | `Degraded` with reason `NoEligibleRecovery` | 5m | critical | +| FabricRoutingDeploymentDegraded | `Degraded` for another reason than that or `Recovered` | 15m | warning | +| FabricRoutingRecoveryConflict | `RecoveryConflict` True | 10m | warning | +| FabricRoutingAgentHeartbeatStale | on Shadow or CRD, no agent report for 5m, or never | 5m | warning | +| FabricRoutingReleaseFailed | a failed release still blocks its routing domain | 30m | warning | +| FabricRoutingReleaseUnknown | a release is `Unknown` | 15m | warning | +| FabricRoutingHandoffPending | `Accepted` False with reason `HandoffPending` or `ConfigMapRetired` | 15m | warning | +| FabricRoutingCandidateRejected | `Staged` False on a node staging on Shadow or CRD | 15m | warning | +| FabricRoutingPromotionRefused | `Accepted` False: `PromotionRefused`, `NotAuthorized`, `RevisionNotFound` | 15m | warning | +| FabricRoutingRevisionRefused | the controller refuses a fabric router's inputs | 15m | warning | +| FabricRoutingCollectFailing | the leader cannot read a kind from its cache | 10m | warning | +| FabricRouterControllerMetricsDown | `fabric-router-controller` scrape down | 5m | warning | +| GalacticRouterBMPStationDown | `galactic_router_bmp_station_up == 0` | 10m | warning | +| GalacticRouterRoutesNotInstalled | `galactic_router_route_install_failing > 0` | 10m | warning | +| GalacticRouterMetricsDown | `galactic-router` or `galactic-router-rr` scrape down | 5m | warning | +| GalacticNatSessionTableEvictingLive | table over 90% full, oldest row under 7440 s | 15m | warning | +| GalacticNatPortExhausted | `*_pat_exhausted` drops in every 10-minute window | 15m | warning | +| GalacticNatUplinkRxQueueStalled | one uplink rx queue delivers nothing while discarding | 10m | critical | +| GalacticNatUplinkRxQueueLossy | one uplink rx queue discards >1%, most siblings do not | 30m | warning | +| GalacticNatNotProgrammed | turned on, no EgressShard identity | 10m | warning | +| GalacticNatUplinkUncovered | `galactic_nat_uplink_covered == 0` | 10m | critical | +| GalacticNatForwardDropRatio | owned-traffic drops over 1% of translated, over 10 packets/s | 15m | warning | +| GalacticNatNotTranslating | compute nodes send to the shard's SID, it translates none outbound | 10m | critical | +| GalacticNatPortsNearExhaustion | busiest destination holds over half its port range | 10m | warning | +| GalacticNatDispatchLeaseFailing | more than two lease renewal errors in every 5-minute window | 5m | warning | +| GalacticNatDispatchLeaseExpiring | no successful lease renewal in 2 minutes | 0 | critical | +| GalacticNatMetricsDown | `galactic-nat` scrape down | 5m | warning | +| GalacticEgressPoolEmpty | no active shard for a class while routes on the node name it | 2m | critical | +| GalacticEgressPoolBelowMinimum | fewer active shards than `galactic_cni_egress_pool_min_active` | 10m | warning | +| GalacticEgressClassUnserved | every shard ineligible for a class | 15m | warning | +| GalacticEgressShardGroupDropping | `group_empty`, `shard_dead` or `parse_failed` in every 5m window | 10m | warning | +| GalacticEgressShardWatchNotSynced | hashed mode, `EgressShard` watch never listed | 10m | warning | +| GalacticEgressSweepFailing | sweep errors in every 10-minute window | 15m | warning | +| GalacticCNIMetricsDown | `galactic-cni` scrape down | 5m | warning | +| FabricAPIExecutionStalled | gateway has executions in flight, finished none in 10m | 10m | warning | +| FabricAPINodeDiagnosticsUnavailable | `fabric_api_node_diagnostics_available == 0` | 15m | warning | +| FabricAPINodeUnreachable | over half of 5+ node calls in 30m unreachable or timed out | 15m | warning | +| FabricAPIResultsOversized | 10+ `ResponseTooLarge` requests on a node in an hour | 15m | warning | +| FabricAPICleanupBacklog | over 50 expired `FabricQuery` objects left | 1h | warning | +| FabricAPICertificateRenewalFailing | mTLS certificate expires in under 4 hours | 15m | warning | +| FabricAPICredentialsMissing | `fabric_api_credentials_loaded == 0` | 15m | warning | +| FabricAPISearchIndexUnsynced | search index holds routes but is not synced with bgpd | 15m | warning | +| FabricAPIMetricsDown | `fabric-api-node` or `fabric-api-gateway` scrape down | 10m | warning | +| GalacticEdgeAttachmentNotProgrammed | admitted and allocated attachments not programmed by their node | 15m | warning | +| GalacticEdgeServicePolicyUnresolved | an `EdgeService`'s `TrafficPolicyResolved` is False | 10m | warning | +| GalacticEdgeScopeLost | `galactic_edge_foundation_scopes_lost > 0` | 5m | warning | +| GalacticEdgeCleanupFailing | more than two cleanup failures in every 15-minute window | 15m | warning | +| GalacticEdgeMetricsDown | `galactic-edge` or `galactic-controller` scrape down | 5m | warning | diff --git a/docs/observability/edge.md b/docs/observability/edge.md new file mode 100644 index 000000000..649de9e52 --- /dev/null +++ b/docs/observability/edge.md @@ -0,0 +1,51 @@ +# Galactic Edge foundation — `galactic_edge_foundation_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +The attachment lifecycle and forwarding claims of the Galactic Edge +foundation (`config/galactic-edge/`), distinct from the edge load +balancer's `galactic_edge_*` above. Core's series come from +`galactic-controller --role=cell --edge`; every replica reads its cache at +scrape time, so aggregate them with `max`. Node series come from +`galactic-edge` on each edge node. No label names an attachment, pod, +route, prefix or address: `provider` is an approved `EdgeProvider`'s name +or `unknown`, and `reason` is a condition reason or `Other`. Find the +objects behind a series with the Events and `kubectl` queries in +[the troubleshooting guide](../edge/troubleshooting.md). + +| Metric | Type | Source | Labels | Meaning | +| ------------------------------------------------- | ------- | ------ | ---------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| `galactic_edge_foundation_attachments` | gauge | core | `provider`, `state`, `reason` | Attachments by the first lifecycle stage they have not passed, and the condition reason holding them | +| `galactic_edge_foundation_routes` | gauge | core | `provider`, `state`, `reason` | Routes by claim state, and the condition reason holding them | +| `galactic_edge_foundation_services` | gauge | core | `provider`, `policy`, `reason` | Services whose traffic policy is `Resolved` or `Unresolved`, with the reason when unresolved | +| `galactic_edge_foundation_state_collect_errors` | gauge | core | none | Kinds the last scrape could not list and left out | +| `galactic_edge_foundation_failures_total` | counter | both | `component`, `stage`, `reason` | Transitions into a failed stage, counted once per transition, not per retry. Each also records an Event | +| `galactic_edge_foundation_gate_closures_total` | counter | node | `component`, `cause` | Open forwarding gates the agent closed, by cause. Each also records an Event on the route | +| `galactic_edge_foundation_cleanup_failures_total` | counter | node | `component` | Host state releases and gate sweeps that failed and are retried | +| `galactic_edge_foundation_links` | gauge | node | none | Host links registered with the node's forwarding gate | +| `galactic_edge_foundation_gates` | gauge | node | `state` (`open`, `expired`, `closed`) | Gates on the node. `expired` passed its deadline before the agent closed it | +| `galactic_edge_foundation_gate_drops_total` | counter | node | `check` (`ingress`, `egress`, `deliver`) | Packets dropped on an edge link because no open gate covered the address | +| `galactic_edge_foundation_scopes_lost` | gauge | node | none | VPC ownership scopes another writer took from this process | +| `galactic_edge_foundation_node_collect_errors` | gauge | node | none | Gate table reads the last scrape could not make | + +- Attachment `state`, in lifecycle order: `Admission`, `Allocation`, + `Programming`, `Ready`, `Active`, then `Draining` and `Releasing`. + `reason` is `Pending` while the stage's condition is unset, and + `NotReady` for `Ready`, whose own reason the provider writes. +- Route `state`: `Unclaimed`, `Pending`, `Accepted` (with the `Published` + condition's reason), `Published`, `Revoked` or `Released`. +- `stage`: `Admission`, `Allocation`, `Programming`, `Policy`, `Route`. +- `cause`: `Expired` (no renewal extended the gate), `Released`, + `Revoked`, `InstanceGone`, `AuthorityEnded`, `GrantCeiling`, + `RouteGone` or `HolderMoved`. +- Packet drops by traffic policy on an edge link are + `galactic_cni_traffic_policy_*` from `galactic-router`, labeled with the + attachment. + +```promql +# Attachments the foundation has admitted but not yet programmed, per provider +max by (provider, reason) (galactic_edge_foundation_attachments{state="Programming"}) + +# Gates closing because providers stop renewing +sum by (node) (increase(galactic_edge_foundation_gate_closures_total{cause="Expired"}[1h])) +``` diff --git a/docs/observability/egress-pool.md b/docs/observability/egress-pool.md new file mode 100644 index 000000000..ff52c9cdf --- /dev/null +++ b/docs/observability/egress-pool.md @@ -0,0 +1,55 @@ +# Tenant egress pool — `galactic_cni_egress_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +How each compute node spreads tenant egress across the cluster's +`EgressShard`s. With `GALACTIC_CNI_EGRESS_MODE=hashed`, `usid_egress` keeps +one shard group per translation class: `nat66`, and `nat64:` for +each NAT64 prefix. See +[nat/configuration.md](../nat/configuration.md#active-active-egress). + +The pool series come from the maps, so a node with no group publishes +none. The control-loop series (`mode`, `shard_watch_synced`, +`group_routes`, the sweep pair) are always exported, so a node told to run +hashed mode that never published a group still shows it. + +| Metric | Type | Labels | Meaning | +| ------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `galactic_cni_egress_shard_packets_total` | counter | `shard_sid`, `class` | Tenant packets this node encapsulated toward each shard, since the shard took its slot | +| `galactic_cni_egress_shard_bytes_total` | counter | `shard_sid`, `class` | Tenant bytes of those packets | +| `galactic_cni_egress_shard_selections_total` | counter | `result` | How `usid_egress` placed each packet whose route names a shard group | +| `galactic_cni_egress_pool_members` | gauge | `class`, `state` (`active`, `draining`, `unreachable`, `local`, `ineligible`) | The class's shards as this node's group sees them | +| `galactic_cni_egress_pool_min_active` | gauge | none | `GALACTIC_CNI_EGRESS_POOL_MIN_ACTIVE`, the fewest active shards each class should have | +| `galactic_cni_egress_pool_enabled` | gauge | `class` | 1 while the class's group takes new routes; a group being retired still forwards but reads 0 | +| `galactic_cni_egress_mode` | gauge | `mode` (`ordered`, `hashed`) | 1 for the configured mode, 0 for the other | +| `galactic_cni_egress_shard_watch_synced` | gauge | none | 1 once the `EgressShard` watch has listed the cluster | +| `galactic_cni_egress_group_routes` | gauge | `class` | `egress_route_table` entries naming a shard group. Must be 0 before rolling back past hashed mode | +| `galactic_cni_egress_sweep_errors_total` | counter | `stage` (`apply`, `refresh`, `watch`, `close`, `disable`) | Egress route sweep failures, by step | +| `galactic_cni_egress_last_successful_sweep_timestamp_seconds` | gauge | none | Unix time of the last sweep that finished without an error | + +`galactic_cni_egress_shard_selections_total` result values: + +- **Forwarded:** `pin_hit` (the tenant address's pin still names a live + shard), `maglev` (placed by the Maglev table). +- **Re-placed:** `pin_stale` (the pin named a shard that left the group). +- **Dropped:** `group_empty`, `shard_dead`, `parse_failed`. + +`state` values: `active` shards take new tenant addresses; `draining` ones +(`spec.drain`) serve only the tenants already pinned to them; `unreachable` +ones have no route from this node; `local` ones run on this node and take +no tenant from it; `ineligible` ones cannot translate the class (no +masquerade address in its family, or another NAT64 prefix). + +```promql +# Active shards per class, per node +sum by (node, class) (galactic_cni_egress_pool_members{state="active"}) + +# Egress bytes/s each shard receives from the cluster's compute nodes +sum by (shard_sid, class) (rate(galactic_cni_egress_shard_bytes_total[5m])) * 8 + +# Packets dropped on the way to a shard group (GalacticEgressShardGroupDropping) +sum by (node, result) (increase(galactic_cni_egress_shard_selections_total{result=~"group_empty|shard_dead|parse_failed"}[5m])) > 0 + +# Seconds since the last clean sweep +time() - galactic_cni_egress_last_successful_sweep_timestamp_seconds +``` diff --git a/docs/observability/fabric-api.md b/docs/observability/fabric-api.md new file mode 100644 index 000000000..b485eefc5 --- /dev/null +++ b/docs/observability/fabric-api.md @@ -0,0 +1,11 @@ +# Fabric looking glass — `fabric_api_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +The opt-in fabric-api exports `fabric_api_node_*` from each node sidecar +(9345) and `fabric_api_gateway_*` from each cell gateway (9347). Both +export `fabric_api_credentials_loaded` and +`fabric_api_certificate_expiry_timestamp_seconds` for their mTLS identity. +Its full metric list, with labels and meanings, lives with the rest of +its operator reference in +[fabric-api/configuration.md](../fabric-api/configuration.md). diff --git a/docs/observability/gateway.md b/docs/observability/gateway.md new file mode 100644 index 000000000..01954e1bf --- /dev/null +++ b/docs/observability/gateway.md @@ -0,0 +1,65 @@ +# Edge load balancer — `galactic_edge_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +`galactic-gateway`'s XDP DSR load balancer on gateway-role edge nodes. +Every gateway node serves every VIP identically (anycast), so the same +series appear on each one. Direct server return keeps no per-flow state, +so there is no connection table to report. See +[ARCHITECTURE-GATEWAY.md](../agents/ARCHITECTURE-GATEWAY.md). + +| Metric | Type | Labels | Meaning | +| ------------------------------------------------------- | ------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `galactic_edge_rule_packets_total` | counter | `proto`, `port`, `vip`, `vpc` | Packets that matched the VIP, port and protocol, whatever happened to them next | +| `galactic_edge_rule_bytes_total` | counter | same | Bytes of those packets | +| `galactic_edge_rule_dropped_packets_total` | counter | same | Matched packets the datapath then dropped, such as for no backends. A subset of `rule_packets_total` | +| `galactic_edge_rule_backends` | gauge | same | Backends registered for the VIP | +| `galactic_edge_rule_seconds_since_last_packet` | gauge | same | Seconds since a packet last matched the VIP. Absent until the first one | +| `galactic_edge_return_packets_total` | counter | `vip`, `vpc` | Replies sourced from the VIP that this node forwarded past the kernel (`edge_return`) | +| `galactic_edge_return_bytes_total` | counter | same | Bytes of those replies | +| `galactic_edge_return_dropped_packets_total` | counter | same | Replies sourced from the VIP that the datapath dropped. A subset of `return_packets_total` | +| `galactic_edge_drops_total` | counter | `reason` | Packets `edge_lb` and `edge_return` dropped, by reason | +| `galactic_edge_neigh_fallbacks_total` | counter | none | Packets `edge_lb` handed to the kernel to resolve the next hop. Not counted as drops | +| `galactic_edge_control_plane_drops_total` | counter | `rule`, `reason` (`quota_exceeded`) | Rule applications refused before they reached the datapath | +| `galactic_edge_dispatch_lease_renewals_total` | counter | `slot`, `result` | Renewals of the gateway's XDP dispatcher slot leases. Dispatch mode only | +| `galactic_edge_dispatch_lease_expiry_timestamp_seconds` | gauge | `slot` | Unix time each lease, as last renewed, expires. Dispatch mode only | + +- `proto` is `tcp`, `udp`, or the protocol number for anything else. +- `vpc` is empty until the process has applied a rule that owns the VIP, + as after a restart before the first reconcile. A VIP address used by + rules of more than one VPC has an empty `vpc` on its return series, since + the return counters can't be split between them. +- The per-VIP counters survive re-registration, such as a reconcile that + only changes the backend list. The return series read zero, not absent, + on a node with no compute tier behind it. +- `galactic_edge_drops_total` reasons: `empty_backend_list`, + `no_encap_config`, `fib_no_neigh`, `fib_unreachable`, `fib_frag_needed`, + `fib_lookup_failed`, `adjust_head_failed`, `no_egress_ifindex`, + `redirect_failed`, `return_hop_limit`, `icmp_rate_limited`, plus + `unknown_` for an index the binary has no name for. +- `fib_no_neigh` counts only replies `edge_return` forwards and ICMP errors + the gateway sends. A load-balanced packet whose next hop has no neighbor + entry goes to the kernel, which resolves the neighbor and forwards it, and + is counted in `galactic_edge_neigh_fallbacks_total` instead. That counter + rises briefly after a link or node rejoins the fabric. Steady growth means + neighbor entries keep expiring or a next hop does not answer, and the + kernel drops what it cannot resolve. The counter records the handoff, not + delivery: these packets cross the node's netfilter FORWARD hook, unlike the + XDP path, so a host firewall that drops forwarded traffic drops them too. + +The port also serves controller-runtime's metrics for the +`NetworkGateway`/`NetworkService` reconcilers. + +```promql +# Requests per second per VIP and port +sum by (vpc, vip, port, proto) (rate(galactic_edge_rule_packets_total[5m])) + +# VIPs with no backends +max by (vip, port, proto) (galactic_edge_rule_backends) == 0 + +# Drops by reason +sum by (node, reason) (rate(galactic_edge_drops_total[5m])) > 0 + +# Rules refused by quota +sum by (node, rule) (increase(galactic_edge_control_plane_drops_total[1h])) > 0 +``` diff --git a/docs/observability/nat.md b/docs/observability/nat.md new file mode 100644 index 000000000..ac2f1c6a9 --- /dev/null +++ b/docs/observability/nat.md @@ -0,0 +1,179 @@ +# NAT66 / NAT64 — `galactic_nat_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +One `galactic-nat` pod per egress shard; every value is per shard. + +| Metric | Type | Labels | Meaning | +| -------------------------------------------------------- | --------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `galactic_nat_conns` | gauge | `family` (`nat66`, `nat64`) | Rows in the connection table, expired sessions included. A session holds two rows | +| `galactic_nat_sessions` | gauge | `family`, `proto` (`tcp`, `udp`, `icmp`) | Live sessions: one per session within its idle timeout | +| `galactic_nat_conn_table_oldest_row_age_seconds` | gauge | none | Seconds since the least recently seen session, expired ones included, last translated a packet. Meaningful only on a near-full table | +| `galactic_nat_conn_table_max_entries` | gauge | none | Table capacity in rows, shared by both families | +| `galactic_nat_drops_total` | counter | `reason` | Packets dropped by the NAT datapath | +| `galactic_nat_packets_total` | counter | `family`, `direction` (`outbound`, `return`), `action` (`redirect`, `tx`) | Packets the shard translated and queued for transmit. Every combination is reported, zero included | +| `galactic_nat_bytes_total` | counter | same | Bytes of those packets: the translated IP packet, without Ethernet or the SRv6 outer header | +| `galactic_nat_datapath_enabled` | gauge | none | 1 when the datapath is turned on by configuration, 0 when it is turned off | +| `galactic_nat_datapath_attached` | gauge | none | 1 once the datapath has loaded and attached, 0 before that or while turned off | +| `galactic_nat_programmed` | gauge | none | 1 while the datapath holds an EgressShard identity, 0 while it claims no packet | +| `galactic_nat_uplink_covered` | gauge | `interface` | 1 for each resolved uplink the datapath translates on, 0 for one it misses. Absent while turned off | +| `galactic_nat_family_enabled` | gauge | `family` | 1 when the programmed identity has a masquerade address for the family | +| `galactic_nat_info` | gauge | `shard_sid`, `nat64_prefix`, `xdp_attach`, `version` | Always 1. Empty `shard_sid` and `nat64_prefix` while unprogrammed; `xdp_attach="off"` while turned off | +| `galactic_nat_masquerade_ports_in_use` | gauge | `family`, `address`, `proto` | Distinct masquerade ports live sessions hold on the address, toward any destination | +| `galactic_nat_masquerade_destination_ports_max` | gauge | `family`, `address`, `proto` | The most ports live sessions hold toward any single destination address and port. New flows to it fail as this nears the range | +| `galactic_nat_masquerade_port_range` | gauge | none | Ports (or ICMP Echo Identifiers) available toward each destination: 28000 | +| `galactic_nat_dispatch_lease_renewals_total` | counter | `slot`, `result` (`success`, `error`) | Renewals of the shard's XDP dispatcher slot lease. Dispatch mode only | +| `galactic_nat_dispatch_lease_expiry_timestamp_seconds` | gauge | `slot` | Unix time the lease, as last renewed, expires. Dispatch mode only | +| `galactic_nat_session_creates_total` | counter | `family`, `proto` | New sessions the shard opened, one masquerade port claim each | +| `galactic_nat_masquerade_claim_probes_total` | counter | `family`, `proto`, `probes` (`1`..`8`) | Those claims by how many probes each took. Rising multi-probe shares mean busy destinations are filling | +| `galactic_nat_uplink_resolve_errors_total` | counter | none | Failed re-resolutions of the uplinks after a link or route change; the shard keeps its previous coverage | +| `galactic_nat_uplink_rx_queue_packets_total` | counter | `interface`, `driver`, `queue` | Packets one NIC receive queue of an uplink received, from `ethtool -S`. Exported for `bnxt_en`, `ixgbe`, `ice`, `i40e`, `mlx5_core` | +| `galactic_nat_uplink_rx_queue_discards_total` | counter | `interface`, `driver`, `queue` | Packets one receive queue discarded before the datapath saw them. Reported only by drivers that count per queue: `bnxt_en` today | +| `galactic_nat_uplink_queue_driver_stat_total` | counter | `interface`, `driver`, `queue`, `stat` | One of a queue's other driver counters, under its `ethtool -S` name. `bnxt_en` only, see below | +| `galactic_nat_uplink_info` | gauge | `interface`, `driver`, `driver_version`, `firmware_version`, `kernel` | Always 1. Names each uplink's driver and NIC firmware versions and the node's kernel release | + +Caveats for the translated traffic and state series: + +- `outbound` is tenant traffic the shard decapsulated and translated toward + the internet; `return` is a reply translated back and encapsulated toward + the tenant. `tx` means the packet left over the uplink it arrived on, + `redirect` over another one. +- Messages the shard sends on its own behalf (Packet Too Big, Fragmentation + Needed, echo replies to its own address) and packets it passes on + unclaimed are not translations and are not counted. +- The counters live in a pinned map, so they outlive a pod restart, like + `galactic_nat_drops_total`. +- A shard can be attached and programmed and still translate nothing, when + its uplinks never hand it the traffic. Compare + `galactic_nat_packets_total{direction="outbound"}` with the compute nodes' + `galactic_cni_egress_shard_packets_total` for its `shard_sid` + (`GalacticNatNotTranslating`). +- Cardinality: 8 series each for packets and bytes, one `uplink_covered` + series per uplink, and one `info` series per shard. + +Caveats for the masquerade port series: + +- A port is claimed per destination address and port, not per masquerade + address, so the same port can serve many destinations at once. + `galactic_nat_masquerade_ports_in_use` can sit near the range on a healthy + shard that talks to many destinations; + `galactic_nat_masquerade_destination_ports_max` is what predicts exhaustion. +- A claim probes 8 of the range's ports, so a destination fails new flows well + before it is full: about 0.4% of new flows at half full, 17% at 80% + (`GalacticNatPortsNearExhaustion` warns at half full). +- Every protocol of every address the programmed identity serves is reported, + zero included, except when the session clock cannot be read: then only the + range is reported, rather than zeros that would read as an idle shard. An + address a re-programmed identity replaced is reported while live sessions + still hold its ports. +- Both are read from the session table walk at scrape time, like + `galactic_nat_sessions`, so they are approximate on a churning table. + +Caveats for session creation: + +- `galactic_nat_session_creates_total` is the sum of + `galactic_nat_masquerade_claim_probes_total` over `probes`. A claim that + finds no port is a `*_pat_exhausted` drop, and a claim that adopts a live + session's lost port opens no new session; neither is counted. +- With a share u of a destination's ports held, a claim needs more than k + probes with probability of roughly u^k (the probes walk consecutive ports, + and held ports cluster, so it is an estimate). The share of claims needing more than one + probe therefore estimates how full the destinations taking new flows are, + before `galactic_nat_masquerade_destination_ports_max` names the worst one + and long before `*_pat_exhausted` drops start. +- Cardinality: 6 creates series and 48 probe series per shard. + +The `EgressShard` reconciler's controller-runtime metrics +(`controller_runtime_reconcile_total{controller="egressshard"}`, +`controller_runtime_reconcile_errors_total`, `workqueue_*`) are served on the +same port, from the same registry. + +The dispatcher lease series are registered in dispatch mode only. The +edge gateway exports the same pair as `galactic_edge_dispatch_lease_*` for +its two slots; no shipped alert reads the gateway's yet. + +Caveats for the session table: + +- Expired sessions keep their rows until the LRU evicts them or a new claim + reuses their port, so `galactic_nat_conns` sits near capacity on any busy + shard. That is normal. Use `galactic_nat_sessions` for live sessions. +- Live sessions are at risk only when the table is full and its oldest row is + younger than the longest session timeout, 7440 s for established TCP. The + table's LRU evicts in approximate order, so the age is an estimate. +- The table is a self-evicting LRU, so the counts can move without traffic + changing. + +| Reason group | Values | Meaning | +| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| Port exhaustion | `nat66_pat_exhausted`, `nat64_pat_exhausted` | No free port on the shard's public address; tenants see failed connections | +| Shard availability | `nat64_shard_unavailable` | NAT64 had no shard to send to | +| Return-path misses | `nat66_no_return_conn`, `nat64_no_return_conn`, `nat66_icmp_no_conn`, `nat64_icmp_no_conn`, `icmp_unsolicited` | Inbound packets with no matching session; background noise is normal, a jump after a restart means lost state | +| Malformed | `nat66_malformed_forward`, `nat66_malformed_return`, `nat64_malformed_forward`, `nat64_malformed_return`, `nat66_icmp_malformed`, `nat64_icmp_malformed`, `icmp_untranslatable` | Packets that couldn't be translated | +| IPv4 limits (NAT64) | `nat64_v4_fragment`, `nat64_v4_options`, `nat64_non_global_dest` | Unsupported IPv4 fragments or options, or a non-global destination | +| Forwarding | `fib_lookup_failed`, `fib_no_neigh`, `fib_unreachable`, `fib_frag_needed`, `adjust_head_failed`, `no_egress_ifindex`, `redirect_failed`, `hop_limit_exceeded` | Route, neighbor or redirect failure after translation | +| Rate limit | `icmp_rate_limited` | ICMP errors suppressed by the rate limiter | + +Caveats for the uplink queue counters: + +- `galactic_nat_uplink_queue_driver_stat_total` carries `bnxt_en`'s other + per-ring counters: transmit packets, discards and errors, `rx_errors`, + `rx_buf_errors`, `rx_resets` and `missed_irqs`. A ring's receive and transmit + share one completion ring, so comparing a stalled ring's transmit rate with + its siblings' shows whether transmit stopped along with receive. +- `galactic_nat_uplink_info` is exported for every uplink, whatever its + driver, so per-queue behavior can be matched against driver, firmware and + kernel versions across nodes. + +```promql +# Live sessions per family +sum by (node, family) (galactic_nat_sessions) + +# Idle live sessions being evicted: table full, oldest row younger than the TCP timeout +# (GalacticNatSessionTableEvictingLive) +sum by (node) (galactic_nat_conns) / on (node) max by (node) (galactic_nat_conn_table_max_entries) > 0.9 + and on (node) max by (node) (galactic_nat_conn_table_oldest_row_age_seconds) < 7440 + +# Port exhaustion or no shard +sum by (node, reason) (rate(galactic_nat_drops_total{reason=~".*_pat_exhausted|nat64_shard_unavailable"}[5m])) > 0 + +# New flows dropped for want of a port, held for 15 minutes (GalacticNatPortExhausted) +sum by (node, reason) (increase(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted"}[10m])) > 0 + +# Drop rate by reason +sum by (node, reason) (rate(galactic_nat_drops_total[5m])) > 0 + +# Translated packets per shard and direction +sum by (node, direction) (rate(galactic_nat_packets_total[5m])) + +# Share of the shard's own traffic it dropped (GalacticNatForwardDropRatio) +sum by (node) (rate(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted|nat(66|64)_malformed_forward|redirect_failed|no_egress_ifindex|adjust_head_failed"}[10m])) + / (sum by (node) (rate(galactic_nat_drops_total{reason=~"nat(66|64)_pat_exhausted|nat(66|64)_malformed_forward|redirect_failed|no_egress_ifindex|adjust_head_failed"}[10m])) + + sum by (node) (rate(galactic_nat_packets_total[10m]))) + +# Busiest destination per masquerade address, as a share of the range (GalacticNatPortsNearExhaustion) +max by (node, family, address, proto) (galactic_nat_masquerade_destination_ports_max) + / on (node) group_left () max by (node) (galactic_nat_masquerade_port_range) + +# Share of new sessions whose port claim needed more than one probe +sum by (node, family) (rate(galactic_nat_masquerade_claim_probes_total{probes!="1"}[10m])) + / sum by (node, family) (rate(galactic_nat_session_creates_total[10m])) + +# Seconds left on the dispatcher lease, by the node's clock +galactic_nat_dispatch_lease_expiry_timestamp_seconds - time() + +# No successful lease renewal in two minutes (GalacticNatDispatchLeaseExpiring) +changes(galactic_nat_dispatch_lease_renewals_total{result="success"}[2m]) == 0 + +# Shards turned on but not programmed, and uplinks not covered +galactic_nat_datapath_enabled == 1 and on (node) galactic_nat_programmed == 0 +galactic_nat_uplink_covered == 0 + +# Discard share per uplink receive queue (#673) +rate(galactic_nat_uplink_rx_queue_discards_total[5m]) + / (rate(galactic_nat_uplink_rx_queue_discards_total[5m]) + rate(galactic_nat_uplink_rx_queue_packets_total[5m])) + +# Transmit rate on each uplink ring, to compare a stalled ring with its siblings (#673) +sum by (node, interface, queue) ( + rate(galactic_nat_uplink_queue_driver_stat_total{stat=~"tx_(ucast|mcast|bcast)_packets"}[5m]) +) +``` diff --git a/docs/observability/routing.md b/docs/observability/routing.md new file mode 100644 index 000000000..dae47ca62 --- /dev/null +++ b/docs/observability/routing.md @@ -0,0 +1,94 @@ +# Routing + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +Two planes: FRR (`fabric-router`) carries the underlay to the upstream +routers, and GoBGP (`galactic-router`) carries tenant EVPN/VPN routes. + +### Underlay — `frr_*` + +Exported by the `frr-exporter` sidecar with the `bgp`, `bgp6` and +`bgp.advertised-prefixes` collectors on; OSPF and BFD are off. + +| Metric | Use | +| ------------------------------------------------ | -------------------------------------------------------------------------------------------- | +| `frr_bgp_peer_state` | `0` down, `1` established, `2` administratively down; labels include `peer`, `afi`, `safi` | +| `frr_bgp_peer_uptime_seconds` | Resets on every session drop, so `resets()` counts flaps | +| `frr_bgp_peer_prefixes_received_count_total` | Prefixes received per peer; a gauge despite the `_total` suffix | +| `frr_bgp_peer_prefixes_advertised_count_total` | Prefixes advertised per peer | +| `frr_collector_up` | `0` means the exporter can't read FRR, so every other `frr_*` on that node is stale | + +```promql +# Session table for a dashboard +max by (node, peer, afi) (frr_bgp_peer_state) + +# Flaps in the last 30m +resets(frr_bgp_peer_uptime_seconds{job="fabric-router"}[30m]) + +# Received prefixes halved while the session stays up +frr_bgp_peer_prefixes_received_count_total < 0.5 * (frr_bgp_peer_prefixes_received_count_total offset 1h) + and frr_bgp_peer_state == 1 +``` + +### Underlay config — `fabric_router_*` + +| Metric | Type | Labels | Meaning | +| ------------------------------------------------- | --------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `fabric_router_bgp_mapped_nexthop` | gauge | `peer` | `1` when a session from a global IPv6 address announces an IPv4-mapped next hop (`::ffff:`); remote sites then lose their routes to this node's locators and NAT shards | +| `fabric_router_bgp_mapped_nexthop_resets_total` | counter | `peer` | Hard resets the agent issued to clear a mapped next hop | +| `fabric_router_bgp_uninstalled_routes` | gauge | `afi` (`ipv4`, `ipv6`) | Prefixes zebra has a BGP route for but that have no kernel route from any protocol | + +Both gauges refresh every 30s. On a node routed through the API the agent +also exports `fabric_router_activations_total`, +`fabric_router_activation_duration_seconds`, +`fabric_router_staging_runs_total`, `fabric_router_writer_lock_wait_seconds` +and `fabric_router_boot_source`; see below. + +### Fabric routing — `galactic_fabric_routing_*` + +`fabric-router-controller`'s leader exports each FabricRouterDeployment's +source, epochs, heartbeat, conditions and staged candidate, each outstanding +FabricReleaseAuthorization, and each fabric router's compile result, read from +its cache at scrape time. The full list, with the node agent's activation +metrics, lives with the rest of the operator guide in +[fabric-routing/operations.md](../fabric-routing/operations.md#metrics-and-alerts). + +### Tenant routing — `galactic_router_*` + +| Metric | Type | Labels | Meaning | +| ----------------------------------------- | ------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `galactic_router_route_install_failing` | gauge | `router` (namespace/name), `kind` | Routes with a known best path whose last kernel/datapath install failed. `kind="vrf"` is tenant VRF routes, `kind="plain"` routes with no route target (egress shards, VIPs). Above zero means part of a VPC or shard is unreachable from this node | +| `galactic_router_bmp_station_up` | gauge | `router`, `station` | BMP session to the collector: `1` up, `0` down | + +`galactic-router` also exposes the standard controller-runtime metrics +(`controller_runtime_reconcile_total`, +`controller_runtime_reconcile_errors_total`, `workqueue_*`) and Go process +metrics. GoBGP session state is not a metric: read it from `BGPPeer` status +(`STATE=Established`) or the BMP stream. + +```promql +sum by (node, kind) (galactic_router_route_install_failing) > 0 +sum by (controller) (rate(controller_runtime_reconcile_errors_total{job=~"galactic-router.*"}[10m])) +``` + +### Private service routes — `galactic_service_route_*` + +The node-local `ServiceRoutePolicy` controller in plain-mode +`galactic-router`, which programs attachment-scoped eBPF service paths. +The route reflector doesn't run it. Resource names are kept in logs, not +labels, so the series stay bounded. + +| Metric | Type | Labels | Meaning | +| --------------------------------------------------- | --------- | -------------------------------------------------------------- | --------------------------------------------------------- | +| `galactic_service_route_reconciliations_total` | counter | `result` (`success`, `error`) | `ServiceRoutePolicy` reconciliations | +| `galactic_service_route_reconcile_duration_seconds` | histogram | none | Time per reconcile (default buckets) | +| `galactic_service_route_route_operations_total` | counter | `operation` (`apply`, `remove`), `result` (`success`, `error`) | Datapath writes and removals | +| `galactic_service_route_programmed_routes` | gauge | none | Attachment-scoped service paths the controller now tracks | +| `galactic_service_route_producers` | gauge | `state` (`Healthy`, `Unhealthy`, `Unknown`) | Producers of `Spread` endpoints this node probes | + +Datapath drops on these paths are the `service_route_*` reasons of +`galactic_usid_drops_total`. + +```promql +sum by (node, operation) (rate(galactic_service_route_route_operations_total{result="error"}[10m])) > 0 +``` diff --git a/docs/observability/traffic-policy.md b/docs/observability/traffic-policy.md new file mode 100644 index 000000000..519ff8d0e --- /dev/null +++ b/docs/observability/traffic-policy.md @@ -0,0 +1,76 @@ +# Traffic policy — `galactic_cni_traffic_policy_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +Interface traffic policy decisions in the uSID datapath. The counters live in +per-CPU BPF maps the datapath writes; `galactic-router`, which allocates +every counter row and knows the rule, policy and interface it belongs to, +reads and labels them, so they are served on its port (9179) and scraped by +the `galactic-router` PodMonitor. The prefix names the datapath, not the +process. Only routers running with `GALACTIC_ROUTER_TRAFFIC_POLICY=true` +export them. See [traffic-policy/node.md](../traffic-policy/node.md). + +| Metric | Type | Labels | Meaning | +| ------------------------------------------------------ | ------- | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| `galactic_cni_traffic_policy_rule_hits_total` | counter | namespace, vpc, attachment, interface, interface_uid, direction, policy, policy_uid, rule, action | Packets evaluated with this rule as the winning rule | +| `galactic_cni_traffic_policy_rule_bytes_total` | counter | the same | Tenant IP bytes evaluated with this rule as the winning rule | +| `galactic_cni_traffic_policy_fallback_packets_total` | counter | namespace, vpc, attachment, interface, interface_uid, direction, reason | Packets denied without a winning rule | +| `galactic_cni_traffic_policy_fallback_bytes_total` | counter | the same | Tenant IP bytes denied without a winning rule | +| `galactic_cni_traffic_policy_unattributed_drops_total` | counter | direction, reason | Policy denials whose interface or fallback row could not be resolved | +| `galactic_cni_traffic_policy_accounting_errors_total` | counter | direction, action, reason | Verdicts whose rule counter row was missing; the verdict stood, the count was lost | +| `galactic_cni_traffic_policy_counter_read_errors` | gauge | none | Counter rows the last scrape could not read, and so left out rather than reporting zero | + +- `direction` is `ingress` or `egress`; `action` is `allow` or `deny`. +- `reason` is one of `no_match`, `policy_unavailable`, `parse_error` or + `classification_error`; `accounting_errors_total` uses + `missing_rule_counter`. +- `interface_uid` is the VPCAttachment UID. For a Galactic Edge + attachment, `namespace`, `attachment` and `interface_uid` are the + EdgeAttachment's, `vpc` is its EdgeService's VPC and `interface` is its + host link. `policy_uid` is the policy's + UID, or `builtin:default-deny-all:v1` for a direction with no reference, + which gets the built-in default. Its deny-all rule is a rule hit, not a + fallback, so the default stays visible per interface and direction. +- One evaluation produces one outcome: a rule's hit and bytes, or one + fallback pair. A packet between two managed interfaces is two + evaluations, the sender's egress and the receiver's ingress. +- A hit is a policy decision, not forwarded traffic: an allowed packet + dropped later still counts. +- Bytes are the tenant IP packet at the evaluation point, without Ethernet + or outer SRv6. A GSO packet counts once, at its buffer length. A packet + whose IP boundary cannot be found adds zero bytes. +- A rule keeps its series while its name and action stay the same within + one policy and interface lifetime, so editing its match keeps counting. + Rename a rule to start a fresh measurement. Rebinding another policy, + removing a rule, flipping its action, or recreating the interface starts + from zero. +- A node reboot or a datapath reload resets them. Use `rate()` or + `increase()`. + +```promql +# Rule hits per second, aggregated across nodes and interfaces. +sum by (namespace, policy, rule, direction, action) ( + rate(galactic_cni_traffic_policy_rule_hits_total[5m]) +) + +# Tenant bytes per second explicitly denied by a rule on each interface. +sum by (namespace, attachment, interface, interface_uid, direction, rule) ( + rate(galactic_cni_traffic_policy_rule_bytes_total{action="deny"}[5m]) +) + +# Failures and no-match denies, which are not attributed to a winning rule. +sum by (namespace, direction, reason) ( + rate(galactic_cni_traffic_policy_fallback_packets_total[5m]) +) + +# Interfaces still on the built-in default deny. +count by (namespace, attachment, direction) ( + galactic_cni_traffic_policy_rule_hits_total{policy_uid="builtin:default-deny-all:v1"} +) + +# Counts the datapath lost or could not attribute. +sum by (node, direction, reason) ( + rate(galactic_cni_traffic_policy_unattributed_drops_total[5m]) + or rate(galactic_cni_traffic_policy_accounting_errors_total[5m]) +) > 0 +``` diff --git a/docs/observability/vpc-dataplane.md b/docs/observability/vpc-dataplane.md new file mode 100644 index 000000000..6e6841615 --- /dev/null +++ b/docs/observability/vpc-dataplane.md @@ -0,0 +1,157 @@ +# VPC dataplane — `galactic_usid_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +The SRv6 uSID datapath on every node, forwarding packets between the fabric +and tenant VRFs. + +### Traffic + +Each node keeps one VRF per VPC, so every series below is one VPC on one +node, keyed by its uSID (Block, Argument). `vpc_attachment` names the +attachment that registered the VRF last, not each attachment's own traffic. +`vrf_interface` is the name of the VPC's VRF device on the node, as +`ip link` shows it. + +| Metric | Type | Labels | Meaning | +| --------------------------------------------- | --------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `galactic_usid_vrf_forwarded_packets_total` | counter | `block`, `argument`, `vrf_table_id`, `vpc`, `vpc_attachment`, `vrf_interface`, `direction` | Packets forwarded into (`ingress`) or out of (`egress`) the VRF | +| `galactic_usid_vrf_forwarded_bytes_total` | counter | same | Tenant bytes of those packets: the IP header and payload, in both directions | +| `galactic_usid_vrf_dropped_packets_total` | counter | same | Packets dropped after the datapath resolved them to the VRF, by direction | +| `galactic_usid_vrf_packets_total` | counter | `block`, `argument`, `vrf_table_id`, `vpc`, `vpc_attachment`, `vrf_interface` | Inbound packets that matched the VRF, counted before any later drop | +| `galactic_usid_vrf_bytes_total` | counter | same | Bytes of those packets, measured as the whole tunneled frame with outer headers | + +What each `direction` counts: + +| `direction` | Counted when | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ingress` | `usid_ingress` decapsulates a packet and redirects it to an attachment, or another attachment on the same node sends one to it | +| `egress` | a tenant packet is encapsulated toward another node or an egress shard, sent unencapsulated out the public uplink (a VIP reply), or delivered to another attachment on the node | + +- A packet counts once, when the datapath has committed to forwarding it. + Traffic the datapath hands to the kernel to route (no matching egress + route) and fail-open paths are not counted. +- A packet too big for the fabric, answered with a Packet Too Big or + Fragmentation Needed, counts as neither forwarded nor dropped; see + `galactic_usid_pmtu_packets_total`. +- Traffic between two attachments of one VPC on the same node counts once + as `egress` and once as `ingress` on that VPC's series, when it is handed + to the kernel for delivery, so the kernel can still drop it. Traffic to the + sender's own gateway address counts in neither; traffic to another + attachment's gateway address in the same VPC counts as delivered. +- A private service route delivering to another attachment on the node + counts `egress` on the sender's VPC and `ingress` on the receiver's, which + may be a different VPC. +- A GSO or GRO super-packet counts as one packet carrying all its bytes. +- Drop reasons are in `galactic_usid_drops_total`, which has no VRF. + `galactic_usid_vrf_dropped_packets_total` has the VRF but no reason, and + covers drops in decapsulation, delivery, encapsulation and the PMTU check, + including inbound private service tunnels. Outbound private service route + drops (`service_route_*` from the sending attachment) and failed + public-uplink redirects appear only in `galactic_usid_drops_total`. +- The two older series keep their meaning: inbound only, claimed before any + drop, and the full frame. Prefer the `forwarded` series for throughput. +- Registering a VRF again never resets its counters. They reset when the + datapath reloads, or when the VRF's rows are removed and created again, + which `rate()` copes with. +- `vpc`, `vpc_attachment` and `vrf_interface` are empty when the VPC + attribution map has no entry for that Argument. Treat `vpc=""` traffic as + unattributed and watch for it. +- Cardinality is one series per active Argument per node for the older pair, + at most 4095 per Block, and twice that for each `direction` metric. + +```promql +# Throughput per VPC and direction, bits/s +sum by (vpc, direction) (rate(galactic_usid_vrf_forwarded_bytes_total[5m])) * 8 + +# Top 10 VPCs on a node by outbound packet rate +topk(10, sum by (node, vpc) (rate(galactic_usid_vrf_forwarded_packets_total{direction="egress"}[5m]))) + +# Share of a VPC's packets dropped after the datapath claimed them +sum by (vpc, direction) (rate(galactic_usid_vrf_dropped_packets_total[5m])) + / (sum by (vpc, direction) (rate(galactic_usid_vrf_forwarded_packets_total[5m])) + + sum by (vpc, direction) (rate(galactic_usid_vrf_dropped_packets_total[5m]))) + +# Traffic the datapath can't attribute to a VPC +sum by (node) (rate(galactic_usid_vrf_forwarded_bytes_total{vpc=""}[5m])) +``` + +### Drops + +`galactic_usid_drops_total{reason}` (counter) counts packets the uSID +datapath dropped, inbound and outbound. Every named reason is always +emitted, at zero when unused, plus `unknown_` for an index the binary +has no name for. + +| Reason group | Values | Usually means | +| ------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| Unknown SID | `unknown_function`, `unknown_argument` | Traffic for a VRF or Argument this node no longer, or never, registered: stale routes elsewhere | +| Malformed | `malformed_inner`, `unknown_inner_version`, `unexpected_nexthdr`, `unsupported_behavior`, `strip_failed` | Bad or unsupported packets; a sustained rate is a bug | +| FIB / forwarding | `fib_lookup_failed`, `fib_no_neigh`, `fib_unreachable`, `fib_frag_needed`, `redirect_failed` | Kernel route or neighbor missing for the inner destination | +| Egress | `egress_route_encap_failed`, `egress_route_fib_lookup_failed`, `egress_route_redirect_failed`, `public_uplink_redirect_failed` | Tenant traffic leaving the node couldn't be encapsulated or sent | +| Service routes | `service_route_denied`, `service_route_redirect_failed` | A private service route refused the sender, or its redirect to the target failed | +| IPv4 VIP | `vip_xlat_failed`, `vip_ipv4_fragment`, `vip_udp_no_checksum`, `vip_ipv4_backend`, `vip_ttl_exceeded` | An IPv4 VIP packet was untranslatable; `vip_ipv4_backend` means a pre-translation router | + +```promql +sum by (node, reason) (rate(galactic_usid_drops_total[5m])) > 0 +``` + +### SID capacity + +| Metric | Type | Labels | Meaning | +| -------------------------------------------------- | ------- | --------- | -------------------------------------------------------- | +| `galactic_usid_block_arguments_used` | gauge | `block` | Arguments (VRF entries) registered in the Block | +| `galactic_usid_block_argument_utilization_ratio` | gauge | `block` | `arguments_used / 4095`, the usable capacity per Block | + +```promql +max by (node, block) (galactic_usid_block_argument_utilization_ratio) > 0.8 +``` + +### MTU handling + +| Metric | Type | Labels | Meaning | +| ------------------------------------------- | --------- | ---------- | --------------------------------------------------------------------------- | +| `galactic_usid_tcp_mss_clamp_syns_total` | counter | `result` | TCP SYNs the MSS clamp examined | +| `galactic_usid_tcp_mss_clamp_limit_bytes` | gauge | `family` | MSS that SYNs are clamped to; `0` means clamping is off for that family | +| `galactic_usid_pmtu_packets_total` | counter | `result` | Tenant packets too big for the fabric once encapsulated | +| `galactic_usid_pmtu_limit_bytes` | gauge | none | Largest tenant packet the egress encapsulates; `0` means the check is off | + +`galactic_usid_tcp_mss_clamp_syns_total` result values: + +- **Clamping worked:** `clamped_ipv4`, `clamped_ipv6`, `within_limit`. +- **SYN crossed the fabric unclamped:** `no_mss_option`, + `skipped_extension_header`, `malformed_options`, `rewrite_failed`, + `walk_limit`. + +`galactic_usid_pmtu_packets_total` result values: + +- **Tenant got an ICMP error back:** `too_big_sent_ipv6`, + `frag_needed_sent_ipv4`. +- **Dropped without an ICMP error (black-hole risk):** `dropped_no_df`, + `dropped_icmp_error`, `rate_limited`, `no_gateway`, `build_failed`. + +```promql +# SYNs that crossed unclamped +sum by (node, result) (rate(galactic_usid_tcp_mss_clamp_syns_total{result!~"clamped_.*|within_limit"}[5m])) + +# PMTU drops with no ICMP error, the case that stalls connections silently +sum by (node, result) (rate(galactic_usid_pmtu_packets_total{result!~"too_big_sent_ipv6|frag_needed_sent_ipv4"}[5m])) + +# Clamp off for a family +galactic_usid_tcp_mss_clamp_limit_bytes == 0 +``` + +### Datapath lifecycle + +| Metric | Type | Labels | Meaning | +| ---------------------------------------------- | --------- | ------------------------------------------------------ | -------------------------------------------------------------------- | +| `galactic_usid_datapath_load_events_total` | counter | `result` (`success`, `failure`) | BPF program load attempts | +| `galactic_usid_datapath_attach_events_total` | counter | `interface`, `action` (`attach`, `detach`), `result` | TC ingress attach/detach, including every netlink-driven re-attach | + +```promql +increase(galactic_usid_datapath_load_events_total{result="failure"}[15m]) > 0 +increase(galactic_usid_datapath_attach_events_total{result="failure"}[15m]) > 0 + +# Re-attach churn: a flapping interface +sum by (node, interface) (increase(galactic_usid_datapath_attach_events_total{action="attach"}[1h])) > 5 +``` diff --git a/docs/observability/vpc-ingress.md b/docs/observability/vpc-ingress.md new file mode 100644 index 000000000..641580c94 --- /dev/null +++ b/docs/observability/vpc-ingress.md @@ -0,0 +1,353 @@ +# VPC ingress — `galactic_ingress_sidecar_*` + +See [scraping and component ports](README.md#where-the-metrics-come-from) and [shipped alerts](alerts.md). + +`galactic-vrf` installs per-VPC VRF devices and per-pod seg6 egress routes on +ingress nodes. It runs in the ingress proxy's pod, so each sidecar exports its +own copy of these. + +| Metric | Type | Labels | Meaning | +| ----------------------------------------------------- | --------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| `galactic_ingress_sidecar_vrf_active` | gauge | none | VRF devices the store tracks as installed, including those draining. Store state, not a kernel check | +| `galactic_ingress_sidecar_route_active` | gauge | none | Installed route claims, one per EndpointSlice, including draining ones. Claims sharing a prefix share one kernel route | +| `galactic_ingress_sidecar_vrf_teardown_pending` | gauge | none | VRFs past their last route at the last sweep: within their grace period, or whose removal failed | +| `galactic_ingress_sidecar_route_teardown_pending` | gauge | none | Route claims whose EndpointSlice is gone at the last sweep: within their grace period, or whose removal failed | +| `galactic_ingress_sidecar_reconcile_errors_total` | counter | `kind` | Backend errors: `ensure_vrf`, `ensure_route`, `remove_vrf`, `remove_route`, `reapply_vrf`, `reapply_route`, `prune_datapath`. No attempt denominator | +| `galactic_ingress_sidecar_reconcile_duration_seconds` | histogram | none | Each desired-state update, including waiting for the store's lock (default buckets). Not sweeps | +| `galactic_ingress_sidecar_reapply_total` | counter | none | Reapply passes: after a datapath reload, after this sidecar's rows went missing, and retries of a failed pass. Not unique reloads | + +`route_active` does not measure an apply backlog: a route stays counted as +installed while a later update to it is still unapplied. + +### Startup and sweep + +A sidecar serves `/metrics` from the moment it starts, before its startup has +finished and whether or not its sweep is still running, so `up` and the +gauges above cannot tell a working sidecar from a stuck one. Startup runs +three stages in order: list the selected EndpointSlices and apply them +(`seed`, retried until the list succeeds), adopt existing host state +(`inventory`), and remove an earlier pod's rows from the shared eBPF maps +(`prune`, skipped after a failed inventory). The sweep starts after the first +inventory attempt either way. A failed inventory is retried before each sweep +until it succeeds, and the prune runs once it does: on a node that has just +booted, the inventory fails until galactic-cni pins the shared eBPF maps. The +prune is not retried. + +| Metric | Type | Labels | Meaning | +| ----------------------------------------------------------------- | --------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `galactic_ingress_sidecar_startup_stage_status` | gauge | `stage`, `status` | 1 for each stage's current status, 0 for its others. `stage`: `seed`, `inventory`, `prune`. `status`: `pending`, `running`, `complete`, `failed`, `skipped` | +| `galactic_ingress_sidecar_startup_attempts_total` | counter | `stage`, `result` | Completed stage attempts, `result` `success` or `error`. The prune is not retried | +| `galactic_ingress_sidecar_startup_complete` | gauge | none | 1 once the seed succeeded, inventory and prune were handled, and the sweep started. A failed inventory or prune still reports 1 | +| `galactic_ingress_sidecar_sweep_last_completed_timestamp_seconds` | gauge | none | Unix time the last sweep finished, whatever its operations' results; 0 before the first | +| `galactic_ingress_sidecar_sweep_duration_seconds` | histogram | none | Each sweep, including waiting for the store's lock (1ms to 120s). One overrunning its interval absorbs the ticks it missed | +| `galactic_ingress_sidecar_sweep_interval_seconds` | gauge | none | Configured time between sweeps | +| `galactic_ingress_sidecar_teardown_grace_seconds` | gauge | none | Configured grace period, applied to a route and then, in turn, to its VRF | +| `galactic_ingress_sidecar_pruned_rows_total` | counter | none | Shared eBPF map rows the startup prune removed, including any removed before it failed | + +`startup_complete` is the startup procedure, not readiness: it says nothing +about whether routes are installed or traffic flows, and a degraded start +stays visible in `startup_stage_status`. These add 43 series per sidecar, +fixed: no label carries a VPC, route or error. + +```promql +sum by (node, kind) (rate(galactic_ingress_sidecar_reconcile_errors_total[10m])) > 0 +histogram_quantile(0.99, sum by (le, node) (rate(galactic_ingress_sidecar_reconcile_duration_seconds_bucket[5m]))) + +# Teardown backlog that never drains +min_over_time(galactic_ingress_sidecar_vrf_teardown_pending[1h]) > 0 + +# Startup still not complete two minutes after the sidecar process started. +# instance and job pick the sidecar's own process, not another container's. +galactic_ingress_sidecar_startup_complete == 0 + and on (instance, job) (time() - process_start_time_seconds > 120) + +# A stage that ended badly: the inventory is still failing, or the prune failed +# or was skipped +galactic_ingress_sidecar_startup_stage_status{status=~"failed|skipped"} == 1 + +# Sweep stalled: the last sweep finished more than three intervals ago. +(galactic_ingress_sidecar_sweep_last_completed_timestamp_seconds > 0) + and (time() - galactic_ingress_sidecar_sweep_last_completed_timestamp_seconds + > 3 * galactic_ingress_sidecar_sweep_interval_seconds) + +# Never swept: startup completed but no sweep has finished. The first sweep is +# due one interval after startup, so alert with a "for" well beyond three +# intervals. +galactic_ingress_sidecar_startup_complete == 1 + and galactic_ingress_sidecar_sweep_last_completed_timestamp_seconds == 0 + +histogram_quantile(0.99, sum by (le, namespace, pod) (rate(galactic_ingress_sidecar_sweep_duration_seconds_bucket[10m]))) +``` + +### Convergence + +How far a sidecar's host state is from what its EndpointSlices ask for. A +claim is one selected, ready EndpointSlice's route; claims sharing a prefix +share one kernel route. + +| Metric | Type | Labels | Meaning | +| ----------------------------------------------------------------------- | ------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `galactic_ingress_sidecar_route_claims_desired` | gauge | none | Claims the sidecar wants installed, including any whose install failed | +| `galactic_ingress_sidecar_route_claims_apply_pending` | gauge | none | Desired claims whose latest update is not applied, whether or not an earlier version of the route is installed | +| `galactic_ingress_sidecar_route_apply_oldest_pending_timestamp_seconds` | gauge | none | Unix time the longest-pending claim stopped being applied; 0 when none is pending | +| `galactic_ingress_sidecar_teardown_overdue` | gauge | `resource` | Routes or VRFs (`route`, `vrf`) whose own grace period ran out but whose removal has not completed, as of the last sweep | +| `galactic_ingress_sidecar_operations_total` | counter | `operation`, `result` | Completed backend operations: `ensure_vrf`, `ensure_route`, `remove_vrf`, `remove_route`, `reapply_vrf`, `reapply_route`; `success` or `error` | + +- A claim's pending age starts when it first fails to apply after being + applied or created, and survives failed retries and newer updates of the + same claim: the route has been unapplied since then. It clears when the + claim applies or stops being desired; a claim reactivated during its grace + period starts a new age. +- The claim counts and the oldest pending time are exact after every update + and sweep, at a constant cost per update however large the backlog. +- `teardown_overdue` counts only removals that failed after their own grace + period. Draining within the grace period is normal and shows only in the + `*_teardown_pending` gauges. A route's and then its VRF's grace periods run + one after the other. It is set at each sweep, so a claim reactivated after a + failed removal still counts until the next one: alert on it with a `for` + of at least one sweep interval. +- A reapply that fails after a datapath reload leaves the claim applied as + far as these gauges know; it shows in + `operations_total{operation=~"reapply_.*",result="error"}`. +- `operations_total{result="error"}` counts the same failures as + `reconcile_errors_total` for those six kinds, each failure once. Never add + the two. `reconcile_errors_total` alone also counts `prune_datapath`. +- These add 17 fixed series per sidecar. + +```promql +# Apply backlog: how long the oldest claim has been unapplied. 0 means none. +time() - galactic_ingress_sidecar_route_apply_oldest_pending_timestamp_seconds + and galactic_ingress_sidecar_route_apply_oldest_pending_timestamp_seconds > 0 + +# Teardown stuck past its grace period +galactic_ingress_sidecar_teardown_overdue > 0 + +# Backend error ratio by operation; absent, not zero, when nothing ran +sum by (namespace, pod, operation) (rate(galactic_ingress_sidecar_operations_total{result="error"}[5m])) + / sum by (namespace, pod, operation) (rate(galactic_ingress_sidecar_operations_total[5m])) +``` + +### EndpointSlice inputs + +The selected EndpointSlices a sidecar reads, whether or not they have a +route. A selected slice carries the tenant label. It is `ready` once it parses +into a route, `waiting_sid` while its node's SID annotation has not appeared +(normal for a freshly published slice), and `invalid` when it cannot be +parsed, for a malformed tenant identifier, SID or address, or a non-IPv6 +address type. Parsing reads only the first endpoint's first address. + +| Metric | Type | Labels | Meaning | +| ----------------------------------------------------------- | ------- | ------------------ | ---------------------------------------------------------------------------------------------------------- | +| `galactic_ingress_sidecar_endpoint_slices` | gauge | `state` | Selected slices by `state`: `ready`, `waiting_sid`, `invalid` | +| `galactic_ingress_sidecar_endpoint_slice_evaluations_total` | counter | `source`, `result` | Evaluations by `source` (`seed`, `watch`) and `result` (`ready`, `waiting_sid`, `invalid`, `not_selected`) | + +- A slice that turns `invalid` keeps any route it had: the sidecar keeps the + last good desired state rather than tearing the route down. A successful + reconcile therefore does not mean the slice was usable. +- The startup seed and the watch evaluate slices concurrently. Once the watch + has seen a slice during a seed, the seed's result for it counts as an + evaluation but does not set its state, so a list taken earlier can neither + overwrite a newer update nor bring back a deleted slice. +- The state is eventually consistent: a watch observation read from a + lagging cache can briefly hold older data than the seed's list, until the + slice's next event. +- One entry per selected slice is kept, removed when the reconciler finds the + slice deleted or without the tenant label. The watch currently drops an + update that only removes the label, so a deselected slice keeps its last + state here, and its route, until it is deleted or the sidecar restarts. + These add 11 fixed series per sidecar. + +```promql +# Slices that cannot be parsed, and slices still waiting for their SID +galactic_ingress_sidecar_endpoint_slices{state=~"invalid|waiting_sid"} > 0 +``` + +### Datapath checks + +Every sweep reads the shared eBPF datapath's generation and, when it has not +changed, reads this sidecar's rows back from the two registration maps +(`vrf_table`, `ifindex_vrf_table`). A changed generation, missing rows, or a +pass that left something unapplied makes it reapply every tracked VRF and +route. These checks do not cover every route, the TC attachment, the +gateway's local route or the host return path, so `ok` here is not full +datapath health. + +| Metric | Type | Labels | Meaning | +| -------------------------------------------------------------------------- | ------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | +| `galactic_ingress_sidecar_datapath_checks_total` | counter | `check`, `result` | Completed checks: `generation` (`ok`, `error`) and `registration_rows` (`ok`, `missing`, `error`) | +| `galactic_ingress_sidecar_datapath_check_status` | gauge | `check`, `status` | 1 for each check's latest status, 0 for its others: `unknown` (not read yet, or an `ok` not re-read this sweep), `ok`, `missing`, `error` | +| `galactic_ingress_sidecar_datapath_check_last_completed_timestamp_seconds` | gauge | `check` | Unix time each check last completed, whatever its result; 0 before the first | +| `galactic_ingress_sidecar_datapath_reapply_total` | counter | `reason`, `result` | Reapply passes by `reason` (`generation_changed`, `rows_missing`, `retry`) and `result` (`success` when every reapply succeeded, `error`) | +| `galactic_ingress_sidecar_datapath_reapply_pending` | gauge | none | 1 while a pass left something unapplied, until a later one succeeds | + +- A failed read is `error`, not `ok`: the state is unknown. Repair stays + conservative and does not reapply on a failed read; the next successful + read decides. +- The rows are read only while the generation is unchanged and no retry is + due, and only when there is a VRF to read back. On any other sweep, and + after a reapply rewrote them, a last `ok` becomes `unknown`; a `missing` or + `error` stays until a read replaces it, so a problem never turns into an + unverified healthy result. Its timestamp shows when the rows were last read. +- A pass's reason is `generation_changed` whenever the generation moved, even + if a retry was also due; otherwise `rows_missing` when this sweep found rows + gone, otherwise `retry`. `reapply_total` keeps counting every pass, of any + reason. These add 22 fixed series per sidecar. + +```promql +# A check that failed or found rows missing +galactic_ingress_sidecar_datapath_check_status{status=~"missing|error"} == 1 + +# A check that completed before but not in the last three sweeps (15s at the +# default 5s sweep interval) +(galactic_ingress_sidecar_datapath_check_last_completed_timestamp_seconds > 0) + and (time() - galactic_ingress_sidecar_datapath_check_last_completed_timestamp_seconds > 15) + +# Reapply churn by reason +sum by (namespace, pod, reason) (increase(galactic_ingress_sidecar_datapath_reapply_total[10m])) +``` + +### Return-path gateway + +With a node name configured, the sidecar publishes one return-path gateway +advertisement per VPC, so a backend's replies have a route back to this +node: it resolves the VPC's gateway address, then writes a +`BGPAdvertisement`. Either step can fail without failing the route that +triggered it. + +| Metric | Type | Labels | Meaning | +| ------------------------------------------------------------------- | ------- | --------------------- | ------------------------------------------------------------------------------------------------ | +| `galactic_ingress_sidecar_gateway_publication_enabled` | gauge | none | 1 when the sidecar publishes return-path advertisements | +| `galactic_ingress_sidecar_gateway_address_assignment_enabled` | gauge | none | 1 when the sidecar assigns each VPC's gateway address from its own gateway prefix | +| `galactic_ingress_sidecar_gateway_vrfs` | gauge | `state` | Installed, non-draining VRFs by `state`: `awaiting_address`, `awaiting_publication`, `published` | +| `galactic_ingress_sidecar_gateway_oldest_pending_timestamp_seconds` | gauge | none | Unix time the longest-unpublished VRF started waiting; 0 when none waits | +| `galactic_ingress_sidecar_gateway_operations_total` | counter | `operation`, `result` | `resolve` (`success`, `error`, `not_provisioned`), `publish` and `withdraw` (`success`, `error`) | + +- `published` is local publication only: the advertisement was written. + It does not show the route reached any BGP peer, or that the + advertisement still exists; nothing re-checks it after publication. +- With publication disabled every `gateway_vrfs` series is 0, so check + `gateway_publication_enabled` before reading 0 as healthy. Disabled, + idle (enabled with no VRFs), waiting and published are all distinct. +- With publication enabled but address assignment off, the sidecar only + finds an address something else provisioned, so VRFs waiting in + `awaiting_address` and `resolve{result="not_provisioned"}` counting up on + every attempt are expected there. +- A successful withdrawal clears a VRF's published state, so a VRF + withdrawn for teardown that then survives, because its removal failed, + and whose VPC comes back is published again, like any VRF waiting. +- A VRF waits from when it is first counted unpublished, through retries, + until it is published or starts draining. A failed withdrawal is counted + and teardown carries on; garbage collection removes the advertisement it + leaves. These add 13 fixed series per sidecar. + +```promql +# Gateway publication pending for more than a minute, only where the sidecar +# both publishes and assigns the address itself +(time() - galactic_ingress_sidecar_gateway_oldest_pending_timestamp_seconds > 60) + and (galactic_ingress_sidecar_gateway_oldest_pending_timestamp_seconds > 0) + and on (namespace, pod) (galactic_ingress_sidecar_gateway_publication_enabled == 1) + and on (namespace, pod) (galactic_ingress_sidecar_gateway_address_assignment_enabled == 1) + +# Resolve and publish failures, as opposed to waiting for an address +sum by (namespace, pod, operation) ( + rate(galactic_ingress_sidecar_gateway_operations_total{result="error"}[10m])) +``` + +### Node source address + +`node_src_addr_table` holds this node's SRv6 source address, which +`usid_egress` stamps on every packet it encapsulates. Until it holds one, +encapsulation fails open and nothing is counted. While any VRF is installed, +each sweep reads the table, writes the address resolved from this node's +`BGPRouter` when the table is unset or holds another, and reads the write +back. + +| Metric | Type | Labels | Meaning | +| ----------------------------------------------------------------------------- | ------- | -------- | --------------------------------------------------------------------------------------- | +| `galactic_ingress_sidecar_node_source_address_status` | gauge | `status` | 1 for the last check's result: `unknown`, `unconfigured`, `ok`, `unresolved` or `error` | +| `galactic_ingress_sidecar_node_source_address_last_checked_timestamp_seconds` | gauge | none | Unix time of the last sweep that checked the table; 0 before the first | +| `galactic_ingress_sidecar_node_source_address_repairs_total` | counter | none | Sweeps that found the table unset or holding another address and wrote this node's | + +- `unknown` means no VRF has been installed since the sidecar started, so + nothing has checked. Sweeps check only while a VRF is installed, so after + the last one is removed the status and timestamp keep their last values; + alert on the timestamp's age only where VRFs are installed. +- `unconfigured` means the sidecar has no node name, so it cannot resolve the + address. `unresolved` means this node's `BGPRouter` has no SRv6 locator and + node ID yet, and the table was left as it was. +- `error` covers a failed read or write, and a write that did not read back. + The status and timestamp are read from one snapshot. +- The repair count includes a sweep that sets the address after a restart, + when it could not be resolved as the VRF was created. A count that keeps + rising means something keeps changing the table: a datapath reload, + another writer, or galactic-cni writing an address that disagrees with this + node's `BGPRouter` as the sidecar reads it. These add 7 fixed series per + sidecar. + +```promql +# Encapsulation failing open: the source address is not set +max_over_time(galactic_ingress_sidecar_node_source_address_status{status=~"unresolved|error"}[10m]) == 1 +``` + +### Host return path — `galactic_sidecar_return_*` + +`galactic-cni` installs the host side of each sidecar's return path: for every +gateway address a sidecar on the node advertises, a route, a permanent +neighbor and a `vrf_table` entry that point a decapsulated reply at the +sidecar's pod. It runs one pass each tick, and these series report it. A +published advertisement only shows the sidecar's half; these show whether +replies can reach the pod. + +| Metric | Type | Labels | Meaning | +| ---------------------------------------------------------- | ------- | --------------------- | ----------------------------------------------------------------------------------------- | +| `galactic_sidecar_return_endpoints` | gauge | `state` | `desired` (advertised), `applied` (installed by the last pass), `pending` (not installed) | +| `galactic_sidecar_return_reconcile_total` | counter | `result` | Passes: `success`, `partial`, `waiting_identity`, `error` | +| `galactic_sidecar_return_last_completed_timestamp_seconds` | gauge | none | Unix time of the last pass that listed the advertisements; 0 before the first | +| `galactic_sidecar_return_operations_total` | counter | `operation`, `result` | `install` (per endpoint), `register`, `prune`, `reap`, each `success` or `error` | + +- `applied` and `pending` partition `desired`; do not add all three. A + scrape reads the three counts and the timestamp from one pass. +- `partial` means an endpoint failed to install or the prune failed. + `waiting_identity` means endpoints are advertised but this node's + `BGPRouter` has no SRv6 locator yet, so all are pending. `error` means + nothing could be installed: listing the advertisements, reading the node's + identity, or registering the node in the maps failed. A failed prune on a + `waiting_identity` or `error` pass shows only in `operations_total`. +- A pass that cannot list the advertisements leaves the counts and the + timestamp as they were. An ageing timestamp, not a zero count, is how a + failing or stalled pass shows. A node with no sidecar reports a fresh + timestamp and 0 desired. A node without a Kubernetes client or node name + never runs a pass, and its timestamp stays 0. +- `install` success means the route, neighbor and map entry were written. It + does not prove a reply reached the pod. These add 16 fixed series per node. + +```promql +# Return path not installed for some endpoint for 10 minutes; a fresh node +# waiting for its SRv6 locator is pending briefly +min_over_time(galactic_sidecar_return_endpoints{state="pending"}[10m]) > 0 + +# Return path pass stalled (passes run every 30s) +time() - galactic_sidecar_return_last_completed_timestamp_seconds > 300 +``` + +### Backend EndpointSlice repair — `galactic_endpointslice_repair_*` + +`galactic-cni` recreates the per-pod EndpointSlice of any Running pod on its +node that has a galactic IPv6 attachment but no slice, every 5 minutes (see +[conflist-reference.md](../cni/conflist-reference.md#endpointslice-publish-http-ingress-backend-discovery)). +The HTTP ingress sidecar finds a VPC backend only through that slice, so each +recreated slice is a pod whose HTTP ingress was down until the pass. + +| Metric | Type | Labels | Meaning | +| ---------------------------------------------- | ------- | ------ | ------------------------------------------------------------------------------ | +| `galactic_endpointslice_repair_restored_total` | counter | none | Missing EndpointSlices the repair recreated | +| `galactic_endpointslice_repair_failures_total` | counter | none | Passes that could not list the node's pods, or read or create an EndpointSlice | + +A pod the pass cannot resolve (no NetworkAttachmentDefinition, `BGPRouter` or +`BGPVRFInstance`) is logged and retried on the next pass, not counted as a +failure. + +```promql +# Slices going missing on a node: something removed them while their pods ran +increase(galactic_endpointslice_repair_restored_total[1h]) > 0 +``` diff --git a/docs/operations/README.md b/docs/operations/README.md new file mode 100644 index 000000000..8378e27d4 --- /dev/null +++ b/docs/operations/README.md @@ -0,0 +1,15 @@ +# Shared operations + +Use these guides for settings and changes that cross component boundaries. + +- [Node labels](node-labels.md): which roles and opt-ins place each DaemonSet. +- [XDP attach mode](xdp-attach-mode.md): host mode selection, readiness, migration and rollback. +- [Legacy API consolidation](migrations/galactic-api-consolidation.md): cutover for installations with legacy cloud or network API-group objects. +- [Observability](../observability/README.md): scrape configuration, metric interpretation and alerts. +- [Fabric routing operations](../fabric-routing/operations.md): staged FRR configuration changes and recovery. +- [Fabric-api operations](../fabric-api/operations.md): diagnostic rollout and verification. +- [NAT active/active rollout](../nat/active-active-rollout.md): prerequisites, draining and rollback. +- [Traffic-policy rollout](../traffic-policy/rollout.md): audit before enforcing interface grants. +- [Edge troubleshooting](../edge/troubleshooting.md): attachment and route lifecycle diagnosis. + +Use component deployment guides for installation. A migration guide applies only to installations in the starting state it names; it is not the default path for a fresh installation. diff --git a/docs/operations/migrations/galactic-api-consolidation.md b/docs/operations/migrations/galactic-api-consolidation.md new file mode 100644 index 000000000..45522f1f5 --- /dev/null +++ b/docs/operations/migrations/galactic-api-consolidation.md @@ -0,0 +1,84 @@ +# Consolidating the cloud and network APIs + +Applies to installations upgrading resources from the legacy cloud.datumapis.com or network.datumapis.com API groups. A fresh installation using galactic.datumapis.com does not need this cutover. Keep this procedure available while a supported installation can still contain legacy objects; do not infer migration completion from this document. + +This change moves the `cloud` and `network` main-branch API types and the cloud +API types into Galactic. The served API group for VPC, BGP, gateway, traffic +policy, and FabricQuery resources is `galactic.datumapis.com/v1alpha1`. +`NetworkRule` is now `NetworkService`, matching the network main branch. + +The source revisions are cloud `55c38b5`, network `5a51626`, and Galactic +`c1769cb`. The VPC, subnet status, and attachment reconcilers run in the NSO +cell manager with `galactic.enabled: true` and the cell's `attachmentMode`. +The Galactic cell role retains BGP status projection and traffic policy. The central fabric identity reconciler +runs in the same binary with `--role=fabric` and a separate deployment because +its hub and IPAM credentials do not belong in each cell. + +## Cutover sequence + +1. Export the existing `cloud.datumapis.com` and `network.datumapis.com` + resources, including their status, before changing any CRD or controller. + Keep the old CRDs installed throughout cutover. Kubernetes treats each new + group as a different resource; installing the Galactic CRDs does not copy + objects or convert owner references. +2. Apply `config/crd` on the hub and every cell that serves these kinds. + Apply `config/fabric-api/crd/galactic.datumapis.com_fabricqueries.yaml` + wherever FabricQuery is served. Install the `galactic-controller` cell + RBAC, webhook certificate, and both webhook configurations before routing + requests to the new controllers. Upgrade NSO's cell manager with Galactic + reconciliation disabled until the old cell writer is stopped. +3. Deploy `config/galactic-controller/fabric` centrally, with a hub credential + bound to `config/galactic-controller/fabric/hub-rbac.yaml` on the hub and an + IPAM credential for the platform project. Confirm the new + `NetworkFabricIdentity` objects have the same identity values as the old + objects and have propagated to their cells before stopping the old fabric + identity controller. The claim names are stable, so the allocator reuses + the retained IPAM claims. +4. Move the desired BGP, gateway, egress, and service resources to the new + group before replacing their node controllers. Use the new API schemas; + `NetworkRule` becomes `NetworkService`. Copy specs and selected labels and + annotations, not Kubernetes UIDs, resource versions, or status. The old + objects do not become visible to the new controllers automatically. +5. Stop the old cloud cell controller before enabling Galactic reconciliation + in NSO's cell manager, so only one controller writes each + NetworkAttachmentDefinition and NSO `NetworkInterface` status. Configure + the correct `galactic.attachmentMode` for the cell. NSO reuses the legacy NAD's VPC and + attachment IDs, transfers its owner reference to the new attachment, and + updates `NetworkInterface.status.attachmentRef.apiGroup` to + `galactic.datumapis.com`. On group change it sets `Programmed=Unknown` until + the new-group BGP advertisement proves programming again. +6. Reattach or roll existing workloads to republish their CNI-created + `BGPAdvertisement` objects under the new group. Keep old routing state + available until their new advertisements are present and the NSO interface + and claim conditions have reconverged. Verify every live interface reports + the Galactic attachment group and `Programmed=True`, and check gateway + and BGP node status before retiring old CRDs and controllers. + +NSO writes `NetworkInterfaceAttachmentRef.APIGroup` as +`galactic.datumapis.com` when its cell reconciler creates a new attachment. +The tenant-facing NSO CRDs remain in `networking.datumapis.com`. Galactic's +BGP reconciler projects data-plane programming status to the Galactic +attachment and NSO interface and claim. + +The old group's VPC finalizers require the old controller to finish deletion, +or an operator-reviewed cleanup after the old objects are no longer serving. +Do not remove old CRDs while objects still carry finalizers or while a node +still depends on their advertisements. + +## Retiring the old API groups + +The new Galactic binaries read and write `galactic.datumapis.com`. Old +`network.datumapis.com` BGP objects can remain after rollout, including objects +for a workload whose CNI ADD ran before the new group was installed. Their old +`Ready` conditions may be stale; do not treat that status as proof that the new +router still advertises their routes. + +Run `hack/audit-legacy-bgp.py --context ` for every migrated cell. It +flags old-only objects, different specs, and new counterparts without a Ready +condition. For each result, check whether its workload still needs a route. +Reattach or restart a live workload and confirm the new-group advertisement +and VRF become ready before removing the old object. Once the +old group has no users, export its objects for the migration record, remove the +old objects, then remove the old CRDs through infra's retirement procedure. +Never delete an old CRD while it still holds objects: Kubernetes deletes those +objects with the CRD. diff --git a/docs/operations/node-labels.md b/docs/operations/node-labels.md new file mode 100644 index 000000000..099645f60 --- /dev/null +++ b/docs/operations/node-labels.md @@ -0,0 +1,257 @@ +# Node Labeling Strategy + +> How Galactic decides which DaemonSets run on which nodes. + +_Last updated: 2026-10-06_ + +This document is cross-cutting — it covers the node-selection contract shared +by `galactic-cni`, `galactic-router`, `galactic-gateway`, `galactic-nat`, +and `fabric-router`, none of which owns it individually. See +[the documentation index](../README.md) for which component guide to read +for everything else about a given binary. + +--- + +## The labels + +| Label | Deploys | Kind | +| ------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------- | +| `galactic.datumapis.com/node=compute` | nothing exclusively (see below) | primary role enum | +| `galactic.datumapis.com/node=edge` | `galactic-vrf` (ingress sidecar pods); hosts `galactic-gateway`/`galactic-nat` | primary role enum | +| `galactic.datumapis.com/gateway=enabled` | `galactic-gateway`, on a `node=edge` node only | opt-in flag (edge only) | +| `galactic.datumapis.com/nat=enabled` | `galactic-nat`, on a `node=edge` node only | opt-in flag (edge only) | +| `galactic.datumapis.com/edge=enabled` | `galactic-edge`, on a `node=edge` node only | opt-in flag (edge only) | +| `galactic.datumapis.com/galactic=router` | `galactic-cni`, `galactic-router` (plain/tenant mode) | mode enum | +| `galactic.datumapis.com/galactic=control` | `galactic-router-rr` | mode enum | +| `galactic.datumapis.com/fabric=router` | `fabric-router` (plain mode) | mode enum | +| `galactic.datumapis.com/fabric=control` | `fabric-router` (reflector mode, same image) | mode enum | + +`galactic-gateway` and `galactic-nat` are **never deployed automatically**: a +node runs one only after an operator labels it, and their manifests live in +`base/` directories no default kustomization applies. Each requires +`galactic.datumapis.com/node=edge` *and* its own opt-in label, so they run +on edge nodes alongside `galactic-vrf`, and only on the edge nodes an +operator picks. They are independent of each other, so an edge node can +carry either opt-in label or both. + +Every affinity also excludes Kubernetes control-plane nodes +(`node-role.kubernetes.io/control-plane: DoesNotExist`), independently of +which of the above a node carries. + +--- + +## Two label families, each an enum, for two different reasons + +The `node` label selects the primary tenant-serving role. The `galactic` and +`fabric` labels independently select each routing family's mode. A node can +run both routing families, but one family cannot be both its plain router +and its reflector on the same node because the label has one value. + +Gateway, NAT and Galactic Edge are independent opt-ins. They may coexist, so +each uses its own `enabled` label and requires `node=edge`. Adding a new +primary role must not silently deploy a new packet-processing service. + +## What `edge` means, and how gateway and NAT opt in + +**`galactic.datumapis.com/node=edge` marks the nodes that host +`galactic-vrf`** — the ingress sidecar that runs next to Envoy and wires a +tenant VRF into the pod — **and the only nodes that may host +`galactic-gateway` and `galactic-nat`.** Like `compute`, an `edge` node also +runs `galactic-cni`, `galactic-router` and `fabric-router`, through their own +labels (`galactic=router`, `fabric=router`). + +`node=edge` alone does not deploy the gateway or a shard. Each needs its own +opt-in label on top (`gateway=enabled`, `nat=enabled`), so an operator picks +which edge nodes run which, and a cluster can have edge nodes that run +neither. Their affinities require both labels, so neither ever lands on a +`compute` node, a node with no `node` value, or a control-plane node. + +Earlier versions of this scheme went the other way twice. First `node=edge` +alone selected both, so they could never be placed independently (one label, +one value). Then they got their own labels but refused any node that carried +a `node` value at all, which kept them off `galactic-vrf`'s nodes. No +datapath reason required that: `galactic-vrf` claims nothing on the uplinks +(its replies arrive encapsulated to the node's own uSID, which the gateway +and the shard pass untouched), and egress shards are meant to run on edge +nodes. So all three now share the edge node. One configuration hazard +remains: an `EgressShard` whose SID reuses its node's router Block and +Node-ID captures that node's tenant ingress +([#711](https://github.com/datum-cloud/galactic/issues/711)). + +Note the historical wording elsewhere in this repo: "edge XDP" describes +`galactic-gateway`'s datapath and predates this scheme; it is unrelated to +`node=edge`. + +**Placement of `galactic-vrf` itself** is not defined in this repo yet (no +`config/galactic-vrf/`; see the note above `publish-galactic-vrf-image` in +`.github/workflows/publish.yaml`). Whatever defines its pods must require +`galactic.datumapis.com/node=edge`. + +--- + +## Per-role reference + +### `galactic.datumapis.com/node=compute` + +The ordinary tenant-serving node. Runs (via +`galactic.datumapis.com/galactic=router`, below) `galactic-cni` and +`galactic-router`, and nothing keyed on this label itself. + +`galactic-nat` used to run here, one egress shard per compute node. It now +runs on `nat=enabled` nodes (below): a compute node's tenant egress is +encapsulated toward its own site's shards instead +(`GALACTIC_CNI_EGRESS_SHARD_SIDS`, set per site, with no other site's shard as +a fallback). + +### `galactic.datumapis.com/node=edge` + +The nodes that host `galactic-vrf`. Runs (via +`galactic.datumapis.com/galactic=router` and +`galactic.datumapis.com/fabric=router`) `galactic-cni`, `galactic-router` and +`fabric-router`. A manifest in this repo deploys nothing on this label alone, +but it is required by `galactic-gateway` and `galactic-nat`, which run here +when the node also carries `gateway=enabled` or `nat=enabled` (below). + +### `galactic.datumapis.com/gateway=enabled` + +Runs `galactic-gateway`'s standalone, single-container pod +(`config/galactic-gateway/base/daemonset.yaml`). Opt-in, never automatic, and +independent of `nat`. The node must also carry +`galactic.datumapis.com/node=edge`. `galactic-router` and `galactic-cni` run +here too if the node also has `galactic=router`, as their own independent +DaemonSets. + +### `galactic.datumapis.com/nat=enabled` + +Runs `galactic-nat`, the egress shard +(`config/galactic-nat/base/daemonset.yaml`). Opt-in, never automatic, and +independent of `gateway`. The node must also carry +`galactic.datumapis.com/node=edge`. + +A node with no gateway can use the base, whose `GALACTIC_NAT_XDP_ATTACH` +defaults to `direct`: the shard attaches its own XDP program to its uplinks. +A node that also carries `gateway=enabled` must set +`GALACTIC_NAT_XDP_ATTACH=dispatch`. An interface takes one program, so the +shard and the gateway, which runs in dispatch mode by default, each run from +their own slot of the node's shared, pinned XDP dispatcher, and either can +restart without detaching the other (see +[docs/nat/configuration.md](../nat/configuration.md)). Compute nodes reach their +site's shards over SRv6 (`GALACTIC_CNI_EGRESS_SHARD_SIDS`). + +### `galactic.datumapis.com/edge=enabled` + +Runs `galactic-edge`, the Galactic Edge node agent +(`config/galactic-edge/base/daemonset.yaml`), which programs and releases the +host side of every `EdgeAttachment` admitted to the node. Opt-in, never +automatic, and independent of `gateway` and `nat`. The node must also carry +`galactic.datumapis.com/node=edge`, and `galactic=router`: an attachment joins +its VPC's canonical host VRF and uSID entry, which `galactic-cni` creates. + +### `galactic.datumapis.com/galactic=router` + +Runs `galactic-cni` and `galactic-router` in its plain (non-reflector) +mode, together, on every `compute` and every `edge` node. + +- `config/galactic-cni/daemonset.yaml` +- `config/galactic-router/overlays/router/daemonset-patch.yaml` + +### `galactic.datumapis.com/galactic=control` + +Runs `galactic-router-rr` (`GALACTIC_ROUTER_REFLECTOR=true`), the EVPN +route reflector every `galactic=router` node's `galactic-router` peers into +over iBGP. Mutually exclusive with `galactic=router` on the same node (one +label key, one value) — a route-reflector node never also runs plain-mode +`galactic-router`, and never runs `galactic-cni` either (a dedicated +route-reflector node hosts no tenant pods). See +`config/galactic-router/overlays/control/daemonset-patch.yaml`. + +### `galactic.datumapis.com/fabric=router` + +Runs `fabric-router`, the FRR underlay eBGP DaemonSet, independently of +whatever `node` or `galactic` value a node also carries. See +`config/fabric-router/daemonset.yaml`'s own affinity comment for the full +history of why this is a dedicated label rather than an enumerated list. + +### `galactic.datumapis.com/fabric=control` + +The underlay's own iBGP route reflector, distinct from the EVPN one above. +Unlike `galactic=control`, this has no separate binary or overlay to run -- +`fabric-router` has no Go code of its own at all (it's a plain FRR +container), so `control` runs the identical image `router` does. The +reflector-vs-plain distinction lives entirely in the per-node `frr.conf` +`infra`'s own renderer produces for this node: a `route-reflector-client` +peer-group instead of the four canonical ones. This DaemonSet's affinity +matches both values identically; only the rendered config differs. +Mutually exclusive with `fabric=router` on the same node, the same way +`galactic`'s two values are. + +--- + +## Worked example: the containerlab lab + +| Node | `node` | `galactic` | `fabric` | Runs | +| ------------------------------------------------------------ | ----------- | ------------ | ---------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `dfw-worker`, `sjc-worker`, `iad-worker` | `compute` | `router` | `router` | `galactic-cni`, `galactic-router`, `fabric-router` | +| `dfw-worker2`, `dfw-worker3`, `sjc-worker2`, `iad-worker2` | `edge` | `router` | `router` | `galactic-gateway` (`gateway=enabled`), `galactic-nat` (`nat=enabled`), `galactic-cni`, `galactic-router`, `fabric-router` | +| `iad-worker3` | — | `control` | `router` | `galactic-router-rr`, `fabric-router` | + +The lab's edge workers carry `node=edge` plus both `gateway=enabled` and +`nat=enabled`, which place a `galactic-gateway` and a `galactic-nat` shard on +each; the lab deploys no `galactic-vrf` yet. The shard runs with +`GALACTIC_NAT_XDP_ATTACH=dispatch`, so it and the gateway share the uplinks +through the node's XDP dispatcher. + +The reflector row is the one that shows why `galactic` is a mode enum rather +than a boolean: `iad-worker3` carries no `node` value at all. Both `node` +roles imply `galactic=router`, and `router`/`control` are mutually exclusive +values of one key, so a reflector structurally cannot also be a compute or +edge node — it needs a worker of its own. + +Every worker in the lab carries `fabric=router` today (see +`deploy/containerlab/node_files/{dfw,iad,sjc}/config.yaml`), since every +role in this topology needs the underlay. That's a property of this +particular lab's topology, not a rule the label scheme enforces — a real +deployment is free to have nodes with no galactic role at all (GPU, +monitoring, etc.), which correctly get none of these labels and none of +these DaemonSets. + +--- + +## Migrating gateway and NAT nodes onto `node=edge` + +The DaemonSet controller removes a pod from any node its affinity stops +matching, whether the node's labels or the DaemonSet's affinity changed. The +old manifests refuse a node carrying `galactic.datumapis.com/node` and the new +ones require `node=edge`, so no order avoids one restart of each gateway and +shard. Keep the gap to that restart: + +1. On each gateway or NAT node, add `galactic.datumapis.com/node=edge`, + keeping `galactic.datumapis.com/gateway=enabled` and/or + `galactic.datumapis.com/nat=enabled`. The old manifests remove the gateway + and shard pods from the node at once, and anything placed on `node=edge`, + such as `galactic-vrf` and the Envoy it serves, can now land on it. +2. Apply the new manifests straight away. They place the pods back on the + node. + +Production is not affected: infra sets its own placement and already requires +`node=edge`. A gateway or NAT node that should not become an edge node has no +place in the new scheme: move its role to an edge node instead. + +--- + +## Adding a new role + +1. Decide whether it's mutually exclusive with an existing enum value in + the same family (→ a new value of that key) or can coexist with an + existing role (→ its own independent label). Default to the independent + label unless you're certain the exclusivity is real and permanent — see + the bugs list above for what happens when that assumption turns out to + be wrong later. +2. If it needs the underlay, it still needs + `galactic.datumapis.com/fabric=router` set explicitly — nothing infers + this from the new label automatically. +3. If it needs `galactic-cni`/`galactic-router` (plain mode), set + `galactic.datumapis.com/galactic=router` — don't add it to an enumerated + list on `galactic-cni`'s or `galactic-router`'s own affinity. +4. Update the reference table at the top of this document and in + [AGENTS.md](../../AGENTS.md)'s "Node label strategy" section. diff --git a/docs/operations/xdp-attach-mode.md b/docs/operations/xdp-attach-mode.md new file mode 100644 index 000000000..00f639168 --- /dev/null +++ b/docs/operations/xdp-attach-mode.md @@ -0,0 +1,166 @@ +# XDP attach mode + +Every Galactic XDP attachment on a host uses one attach mode, chosen once per +process at startup by `internal/plumbing/ebpf/xdpmode`. That covers +`galactic-gateway`'s `edge_lb` and `edge_return`, `galactic-nat`'s +`nat_ingress`, and the shared dispatcher (`xdp_dispatch`) both of them use in +dispatch mode. + +| Host | Mode | Shown by `ip -d link show` as | +| --------------------------- | --------------- | ----------------------------- | +| Any NIC driven by `bnxt_en` | generic (SKB) | `xdpgeneric` | +| Every other host | native (driver) | `xdp` | + +## Why bnxt_en hosts run generic mode + +On `bnxt_en`, native XDP redirect traffic is associated with receive queues +that stop delivering and never recover (#673). The suspected driver defect is +that RX producer updates are suppressed while the paired XDP TX ring is busy. +That mechanism is a hypothesis, not a confirmed root cause. + +Generic mode runs the same programs after the driver has built an skb. Their +`XDP_TX` and `XDP_REDIRECT` verdicts then go through the kernel's ordinary +transmit path, so the driver's XDP TX ring is never used. A staging run with +generic mode saw zero NIC queue discards and zero stalls over 408 seconds of +NAT64 and NAT66 TCP, UDP and ping traffic. That is limited-duration evidence, +not proof that the stall is gone. + +The `GalacticNatUplinkRxQueueStalled` alert (`config/monitoring/`) still +watches for it, and `galactic-nat` still exports the `bnxt_en` ring counters +from #779. + +## What the selection looks at + +- **Drivers come from sysfs.** Each interface under `/sys/class/net` with a + `device` link is a physical NIC, and its driver is the last element of + `device/driver`. Bond masters, VLANs, veths and other virtual interfaces have + no `device` link and are ignored, but they still get the host's mode, so a + host never mixes native and generic redirect paths. +- **A bnxt_en NIC anywhere selects generic for everything.** It doesn't have + to be one of the datapath's own targets. +- **Unknown state fails startup.** A target interface that doesn't exist, a + target NIC whose driver can't be read, or any NIC whose driver link exists + but can't be read, stops the process at startup with the reason in the + error. None of them ever settles the mode by omission. +- **A NIC with no driver at all is skipped.** That happens while a driver + unbinds. If the NIC isn't one of the datapath's targets it carries no + driver traffic, so it is left out of the decision with a warning naming + it. +- **The decision is logged.** Each process logs + `Selected the XDP attach mode for this host` with `mode` and `reason`. The + reason names the matching NICs. +- **The mode is fixed for the life of the process.** A NIC hot-added later + doesn't change it, so restart both pods after adding one. +- **The latest decision is recorded on the host.** Each dispatch-mode process + that attaches records the mode it selected in a pinned record beside the + dispatcher (`/sys/fs/bpf/galactic-xdp/host_mode`). A datapath being turned + off only clears its slots and records nothing. A process whose mode no longer + matches the record doesn't move a link back. It logs the error, reports its + interfaces uncovered, and stays not-ready until it is restarted. Two + processes that disagree therefore never move one link back and forth. + +## Attach, readiness and coverage + +- **No fallback between modes.** Every attach requests its mode explicitly + (`XDPGenericMode` or `XDPDriverMode`) and returns an error rather than + trying the other one. +- **The native-support check runs only in native mode.** The netdev + `xdp-features` check is skipped in generic mode, which runs on any + interface. +- **Readiness reads the real attach mode.** Coverage, and so readiness, reads + the mode back from the kernel (`IFLA_XDP_ATTACHED`). An interface whose hook + holds the program in the other mode counts as uncovered. + - Direct mode: `xdpattach.Set.Attached` and `Reconcile`. + - Dispatch mode: `xdpdispatch.Dispatcher.Linked` and `Coverage`, which + report `ErrModeMismatch`. + - The gateway's `readiness` gRPC service reports NOT_SERVING, and the + shard's `EgressShard` reports `UplinksMissing`, until the mode matches. + +## Moving a running node to the selected mode + +**Direct mode** needs nothing special. Links aren't pinned, so the restart +that brings the new release detaches the old program and attaches in the +selected mode. That bounces each uplink, as every direct-mode restart does. + +**Dispatch mode** keeps its links pinned across restarts, so a node already +running the dispatcher in native mode is migrated in place. + +1. A link in the other mode isn't counted as linked. So the reconcile that + finds it runs the same guards as a first attach, under the node-wide + dispatch lock. +2. A bond member that is the only one carrying traffic is left for a later + pass. Its old link still carries traffic, but its coverage reads as + missing, so the pod stays not-ready until a sibling is up and the member + can be migrated. +3. The pinned link is detached and the root attached again in the selected + mode, then re-pinned. The kernel won't change a link's mode in place or + hold a native and a generic program on one interface at once. +4. The driver resets its rings, as on a first attach. The process waits for + the member to rejoin its bond before touching the next. A member that + doesn't rejoin in time defers every remaining member to the next pass. +5. The interface carries no program between the detach and the new attach. + +Only the link changes. The dispatch maps, the root program, every slot, lease +and role row survive, so each datapath's slot runs again as soon as the new +link is up. + +If the new attach fails, the root is attached again in the mode it was in, the +error is logged, and the interface stays uncovered for readiness. Retries for +that interface back off, from 30 seconds doubling up to 10 minutes, so a +failure that persists doesn't bounce the uplink on every reconcile. If even +the restore fails, the interface has no dispatcher until a later reconcile +attaches one fresh. + +A pinned link whose current mode can't be read is left alone with an error +rather than detached, and so is a foreign XDP program in either mode. + +## Performance + +Generic mode allocates an skb for every frame before the program runs, so +the program no longer sees frames straight from the driver's receive ring. +Expect fewer packets per second per core and +more CPU per packet than native mode on the same NIC. On `bnxt_en` hosts that +cost buys uplinks that keep receiving. + +Compare `galactic_nat_*` and `galactic_edge_*` packet rates and node CPU +before and after the change on the same traffic before relying on the old +capacity figures. + +## Rollback + +- **Rolling back to a release without mode selection doesn't restore native + mode by itself.** Those releases attach in native mode, but in dispatch mode + they accept any live pinned link without checking its mode, so a node + already migrated stays generic. To return such a node to native mode: + 1. Roll back the image. + 2. Run `hack/xdp-dispatch-release.sh` on the node to detach the dispatcher. + 3. Restart `galactic-gateway` and `galactic-nat`. + + Every uplink bounces once, so do this in a maintenance window. +- **In direct mode, rolling back and restarting is enough.** +- **There is no override variable.** The mode follows the host's NICs, so + every datapath on a host always agrees. + +## Staging validation + +On a `bnxt_en` edge node after the release reaches it: + +1. Both pods log `Selected the XDP attach mode for this host` with + `mode=generic` and a reason naming the `bnxt_en` NICs. +2. `ip -d link show` on the node shows `xdpgeneric` with + `prog/xdp ... name xdp_dispatch` on every bond member, and nothing in + native mode. +3. The gateway's readiness probe passes, the `EgressShard` is `Ready`, and + `galactic_nat_uplink_covered` is 1 for every uplink. +4. NAT64 and NAT66 TCP, UDP and ping through the shard, and VIP traffic + through the gateway, all pass. Use `task verify:nat-egress` and + `task verify:gateway-ingress` in the lab, and the same checks against + staging. +5. Over at least a day of normal traffic, neither + `GalacticNatUplinkRxQueueStalled` nor `GalacticNatUplinkRxQueueLossy` + fires, per-queue receive counters keep rising on every queue, and NIC + queue discards stay at zero. + +A node that already runs the dispatcher in generic mode, as the staging lab's +edge node did by hand before this change, needs no migration and sees no +bounce. diff --git a/docs/xdp-attach-mode.md b/docs/xdp-attach-mode.md index 00f639168..fcb2429bd 100644 --- a/docs/xdp-attach-mode.md +++ b/docs/xdp-attach-mode.md @@ -1,166 +1,31 @@ # XDP attach mode -Every Galactic XDP attachment on a host uses one attach mode, chosen once per -process at startup by `internal/plumbing/ebpf/xdpmode`. That covers -`galactic-gateway`'s `edge_lb` and `edge_return`, `galactic-nat`'s -`nat_ingress`, and the shared dispatcher (`xdp_dispatch`) both of them use in -dispatch mode. +This document moved to [xdp-attach-mode](operations/xdp-attach-mode.md). Update bookmarks to the maintained page. -| Host | Mode | Shown by `ip -d link show` as | -| --------------------------- | --------------- | ----------------------------- | -| Any NIC driven by `bnxt_en` | generic (SKB) | `xdpgeneric` | -| Every other host | native (driver) | `xdp` | + -## Why bnxt_en hosts run generic mode +See [Why bnxt_en hosts run generic mode](operations/xdp-attach-mode.md#why-bnxt_en-hosts-run-generic-mode). -On `bnxt_en`, native XDP redirect traffic is associated with receive queues -that stop delivering and never recover (#673). The suspected driver defect is -that RX producer updates are suppressed while the paired XDP TX ring is busy. -That mechanism is a hypothesis, not a confirmed root cause. + -Generic mode runs the same programs after the driver has built an skb. Their -`XDP_TX` and `XDP_REDIRECT` verdicts then go through the kernel's ordinary -transmit path, so the driver's XDP TX ring is never used. A staging run with -generic mode saw zero NIC queue discards and zero stalls over 408 seconds of -NAT64 and NAT66 TCP, UDP and ping traffic. That is limited-duration evidence, -not proof that the stall is gone. +See [What the selection looks at](operations/xdp-attach-mode.md#what-the-selection-looks-at). -The `GalacticNatUplinkRxQueueStalled` alert (`config/monitoring/`) still -watches for it, and `galactic-nat` still exports the `bnxt_en` ring counters -from #779. + -## What the selection looks at +See [Attach, readiness and coverage](operations/xdp-attach-mode.md#attach-readiness-and-coverage). -- **Drivers come from sysfs.** Each interface under `/sys/class/net` with a - `device` link is a physical NIC, and its driver is the last element of - `device/driver`. Bond masters, VLANs, veths and other virtual interfaces have - no `device` link and are ignored, but they still get the host's mode, so a - host never mixes native and generic redirect paths. -- **A bnxt_en NIC anywhere selects generic for everything.** It doesn't have - to be one of the datapath's own targets. -- **Unknown state fails startup.** A target interface that doesn't exist, a - target NIC whose driver can't be read, or any NIC whose driver link exists - but can't be read, stops the process at startup with the reason in the - error. None of them ever settles the mode by omission. -- **A NIC with no driver at all is skipped.** That happens while a driver - unbinds. If the NIC isn't one of the datapath's targets it carries no - driver traffic, so it is left out of the decision with a warning naming - it. -- **The decision is logged.** Each process logs - `Selected the XDP attach mode for this host` with `mode` and `reason`. The - reason names the matching NICs. -- **The mode is fixed for the life of the process.** A NIC hot-added later - doesn't change it, so restart both pods after adding one. -- **The latest decision is recorded on the host.** Each dispatch-mode process - that attaches records the mode it selected in a pinned record beside the - dispatcher (`/sys/fs/bpf/galactic-xdp/host_mode`). A datapath being turned - off only clears its slots and records nothing. A process whose mode no longer - matches the record doesn't move a link back. It logs the error, reports its - interfaces uncovered, and stays not-ready until it is restarted. Two - processes that disagree therefore never move one link back and forth. + -## Attach, readiness and coverage +See [Moving a running node to the selected mode](operations/xdp-attach-mode.md#moving-a-running-node-to-the-selected-mode). -- **No fallback between modes.** Every attach requests its mode explicitly - (`XDPGenericMode` or `XDPDriverMode`) and returns an error rather than - trying the other one. -- **The native-support check runs only in native mode.** The netdev - `xdp-features` check is skipped in generic mode, which runs on any - interface. -- **Readiness reads the real attach mode.** Coverage, and so readiness, reads - the mode back from the kernel (`IFLA_XDP_ATTACHED`). An interface whose hook - holds the program in the other mode counts as uncovered. - - Direct mode: `xdpattach.Set.Attached` and `Reconcile`. - - Dispatch mode: `xdpdispatch.Dispatcher.Linked` and `Coverage`, which - report `ErrModeMismatch`. - - The gateway's `readiness` gRPC service reports NOT_SERVING, and the - shard's `EgressShard` reports `UplinksMissing`, until the mode matches. + -## Moving a running node to the selected mode +See [Performance](operations/xdp-attach-mode.md#performance). -**Direct mode** needs nothing special. Links aren't pinned, so the restart -that brings the new release detaches the old program and attaches in the -selected mode. That bounces each uplink, as every direct-mode restart does. + -**Dispatch mode** keeps its links pinned across restarts, so a node already -running the dispatcher in native mode is migrated in place. +See [Rollback](operations/xdp-attach-mode.md#rollback). -1. A link in the other mode isn't counted as linked. So the reconcile that - finds it runs the same guards as a first attach, under the node-wide - dispatch lock. -2. A bond member that is the only one carrying traffic is left for a later - pass. Its old link still carries traffic, but its coverage reads as - missing, so the pod stays not-ready until a sibling is up and the member - can be migrated. -3. The pinned link is detached and the root attached again in the selected - mode, then re-pinned. The kernel won't change a link's mode in place or - hold a native and a generic program on one interface at once. -4. The driver resets its rings, as on a first attach. The process waits for - the member to rejoin its bond before touching the next. A member that - doesn't rejoin in time defers every remaining member to the next pass. -5. The interface carries no program between the detach and the new attach. + -Only the link changes. The dispatch maps, the root program, every slot, lease -and role row survive, so each datapath's slot runs again as soon as the new -link is up. - -If the new attach fails, the root is attached again in the mode it was in, the -error is logged, and the interface stays uncovered for readiness. Retries for -that interface back off, from 30 seconds doubling up to 10 minutes, so a -failure that persists doesn't bounce the uplink on every reconcile. If even -the restore fails, the interface has no dispatcher until a later reconcile -attaches one fresh. - -A pinned link whose current mode can't be read is left alone with an error -rather than detached, and so is a foreign XDP program in either mode. - -## Performance - -Generic mode allocates an skb for every frame before the program runs, so -the program no longer sees frames straight from the driver's receive ring. -Expect fewer packets per second per core and -more CPU per packet than native mode on the same NIC. On `bnxt_en` hosts that -cost buys uplinks that keep receiving. - -Compare `galactic_nat_*` and `galactic_edge_*` packet rates and node CPU -before and after the change on the same traffic before relying on the old -capacity figures. - -## Rollback - -- **Rolling back to a release without mode selection doesn't restore native - mode by itself.** Those releases attach in native mode, but in dispatch mode - they accept any live pinned link without checking its mode, so a node - already migrated stays generic. To return such a node to native mode: - 1. Roll back the image. - 2. Run `hack/xdp-dispatch-release.sh` on the node to detach the dispatcher. - 3. Restart `galactic-gateway` and `galactic-nat`. - - Every uplink bounces once, so do this in a maintenance window. -- **In direct mode, rolling back and restarting is enough.** -- **There is no override variable.** The mode follows the host's NICs, so - every datapath on a host always agrees. - -## Staging validation - -On a `bnxt_en` edge node after the release reaches it: - -1. Both pods log `Selected the XDP attach mode for this host` with - `mode=generic` and a reason naming the `bnxt_en` NICs. -2. `ip -d link show` on the node shows `xdpgeneric` with - `prog/xdp ... name xdp_dispatch` on every bond member, and nothing in - native mode. -3. The gateway's readiness probe passes, the `EgressShard` is `Ready`, and - `galactic_nat_uplink_covered` is 1 for every uplink. -4. NAT64 and NAT66 TCP, UDP and ping through the shard, and VIP traffic - through the gateway, all pass. Use `task verify:nat-egress` and - `task verify:gateway-ingress` in the lab, and the same checks against - staging. -5. Over at least a day of normal traffic, neither - `GalacticNatUplinkRxQueueStalled` nor `GalacticNatUplinkRxQueueLossy` - fires, per-queue receive counters keep rising on every queue, and NIC - queue discards stay at zero. - -A node that already runs the dispatcher in generic mode, as the staging lab's -edge node did by hand before this change, needs no migration and sees no -bounce. +See [Staging validation](operations/xdp-attach-mode.md#staging-validation).