From 3376c250122c1b3de134dec727ebc5ecbd41e906 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Tue, 6 Oct 2026 06:50:55 -0400 Subject: [PATCH] feat(gateway): Run the edge gateway from the shared XDP dispatcher The gateway attaches edge_lb and edge_return to its uplinks itself, unpinned, so a restart detaches them, bounces every uplink, and cuts egress for a shard chained behind it through the gateway's own xdp_chain map (#710). #742 and #743 put the egress shard on the node's shared dispatcher; this moves the gateway onto it too and retires chain mode, so the two share an uplink and either can restart without touching the other's traffic. - edgedsr.c includes the dispatcher's header and passes every packet it does not claim to the later slots with dispatch_next, in place of xdp_chain and its tail call. Attached directly, the programs hold their own empty copies of the dispatcher maps, so an unclaimed packet passes to the kernel as before. - edgeattach.Load takes the dispatcher's maps as MapReplacements and never pins, recreates or unpins them. - GALACTIC_GATEWAY_XDP_ATTACH defaults to dispatch: the gateway fills slots 0 and 1, renews both leases, and keeps the dispatcher on the public targets with the public role and on the internal targets with the return role, through xdpattach.DispatchSet. direct attaches the programs as before, after releasing an idle dispatcher, and refuses to start while another datapath's slot is live there. - An internal interface that resolves to a public one is refused at startup and dropped from the return set on a later re-resolve, since edge_return forwards anything sourced from a VIP. - GALACTIC_GATEWAY_DATAPATH_ENABLED=false loads nothing, empties the gateway's slots, and makes NetworkGatewayReconciler withdraw this node's VIP advertisements and report DatapathDisabled without driving the engine. The public interface and SRv6 address are not required while it is off. - Chain mode is gone: natattach's chain code, galactic-nat's waitForChain/keepChain, the chained overlay and its placement test. GALACTIC_NAT_XDP_ATTACH=chain is read as dispatch with a warning. Nothing in infra uses the overlay. - xdpattach.ReleaseIdleDispatcher and ClearDispatcherSlots replace the NAT-only helpers, so both binaries release and empty slots the same way. - A disabled gateway withdraws its VIPs on every reconcile, so it matches its own advertisements exactly by their rule label, "--v4/-v6", and never claims another node's whose name shares the suffix ("edge1" against "pop-edge1"), which would turn the old suffix match into a delete/recreate loop. Unlabelled legacy advertisements keep the suffix match. - edgeattach.Load removes the retired /sys/fs/bpf/galactic-edge/xdp_chain pin, so it no longer keeps an old shard program loaded or lets a shard not yet upgraded install itself into a map no datapath runs. - A setup step that fails after the gateway joined the dispatcher stops its leases and empties its slots before the process exits. - The gateway architecture and configuration docs, the NAT and node-label docs, the overview docs, AGENTS.md, the lab NAT README and the manifest comments describe the dispatcher in place of xdp_chain, and the NAT doc says a node that ran chain mode upgrades the gateway and the shard together. Root tests run the gateway and the shard on one veth uplink and show a gateway restart leaves the root program and the shard's coverage in place, and that a direct-mode gateway refuses an uplink the shard runs on. edgedsr's tests show an unclaimed packet reaches the shard's slot and a claimed one never does. The containerlab lab ran both on dfw-worker2 in dispatch mode: egress passed with the gateway in front, a gateway restart under traffic kept the root program and lost no requests, a NAT restart kept the gateway ready, and turning the gateway off emptied only its slots. Fixes #717 Fixes #710 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- cmd/galactic-gateway/dispatch_test.go | 222 ++++++++++++++ cmd/galactic-gateway/gateway.go | 290 +++++++++++++++--- cmd/galactic-gateway/gateway_test.go | 2 +- cmd/galactic-gateway/root.go | 23 +- cmd/galactic-nat/nat.go | 192 ++---------- cmd/galactic-nat/root.go | 8 +- config/galactic-gateway/base/daemonset.yaml | 11 +- config/galactic-nat/base/daemonset.yaml | 16 +- .../overlays/chained/daemonset-patch.yaml | 12 - .../overlays/chained/kustomization.yaml | 14 - .../monitoring/podmonitor-galactic-nat.yaml | 4 +- deploy/containerlab/README.md | 2 +- .../resources/galactic-nat/README.md | 5 +- docs/README.md | 2 +- docs/agents/ARCHITECTURE-GATEWAY.md | 107 ++++--- docs/architecture/README.md | 8 +- docs/gateway/configuration.md | 47 ++- docs/nat/configuration.md | 59 +--- docs/node-labels.md | 24 +- internal/config/gateway.go | 63 +++- internal/config/gateway_test.go | 51 +++ internal/config/nat.go | 31 +- internal/config/nat_test.go | 8 +- .../controller/networkgateway_controller.go | 45 ++- .../networkgateway_controller_test.go | 66 ++++ internal/manifests/placement_test.go | 13 +- internal/plumbing/ebpf/edgeattach/attach.go | 52 +++- .../plumbing/ebpf/edgeattach/attach_test.go | 48 ++- internal/plumbing/ebpf/edgeprog/edgedsr.c | 72 ++--- .../ebpf/edgeprog/edgedsr_chain_test.go | 74 ++++- internal/plumbing/ebpf/natattach/chain.go | 117 ------- .../plumbing/ebpf/natattach/chain_test.go | 131 -------- internal/plumbing/ebpf/natattach/doc.go | 18 +- .../plumbing/ebpf/natattach/uplinks_test.go | 17 - internal/plumbing/ebpf/xdpattach/release.go | 109 +++++++ 36 files changed, 1185 insertions(+), 780 deletions(-) create mode 100644 cmd/galactic-gateway/dispatch_test.go delete mode 100644 config/galactic-nat/overlays/chained/daemonset-patch.yaml delete mode 100644 config/galactic-nat/overlays/chained/kustomization.yaml delete mode 100644 internal/plumbing/ebpf/natattach/chain.go delete mode 100644 internal/plumbing/ebpf/natattach/chain_test.go create mode 100644 internal/plumbing/ebpf/xdpattach/release.go diff --git a/AGENTS.md b/AGENTS.md index dc94e4d63..6ca92662a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,7 +92,7 @@ See [docs/node-labels.md](docs/node-labels.md) for the full strategy — why `ga - **`config/galactic-router/overlays/control/`** — the BGP route-reflector role (`galactic-router-rr`, `GALACTIC_ROUTER_REFLECTOR=true`); opt-in only, requires `galactic.datumapis.com/galactic: control` (stays at zero replicas otherwise). Mutually exclusive with `router`'s `galactic: router` value on the same node — one label key, single-valued, so a route-reflector node structurally can't also run plain-mode `galactic-router`. `GALACTIC_ROUTER_BGP_LOCAL_ADDRESS` is auto-detected from the host's `lo` interface by default; see the comments in `daemonset-patch.yaml` for when to override it. - Apply both roles with `kubectl apply -k config/galactic-router/`, or a single role with e.g. `kubectl apply -k config/galactic-router/overlays/router/`. `galactic-router` no longer runs bundled inside `galactic-gateway`'s pod — see `config/galactic-gateway/` below. - **`config/galactic-gateway/`** — the edge XDP NAT+LB gateway control plane, a single-container `galactic-gateway` DaemonSet — `galactic-router` used to run as a second container in this same pod; it's now a fully independent DaemonSet (via `galactic.datumapis.com/galactic: router`, which a gateway node may carry like any other), so a crash on either side no longer takes the other's *pod* down with it, not just the other's binary. `config/galactic-gateway/{serviceaccount.yaml,rbac.yaml}` (safe/idempotent to apply cluster-wide) are what `kubectl apply -k config/galactic-gateway/` applies; `config/galactic-gateway/base/` (requiring nodes labeled `galactic.datumapis.com/gateway: enabled` and carrying no `galactic.datumapis.com/node` label, so it never shares a node with `galactic-vrf`) is **not** included in that kustomization and is **not** applied as-is — the same exemption as `config/fabric-router/` below, for the same reason: `GALACTIC_GATEWAY_SRV6_ADDRESS` must be unique per gateway node and has no generic default (no in-cluster mechanism yet derives it automatically — see `internal/config/gateway.go`'s `EnvGatewaySRv6Address` doc comment). It's designed to be instantiated once per gateway node by a further overlay that pins it to one node (`kubernetes.io/hostname`) and sets that node's own public-interface/SRv6-address values; see `deploy/containerlab/resources/galactic-gateway/` as of commit `abdd665b` for a worked example (the containerlab lab no longer deploys the gateway). Also **not** part of the root `config/kustomization.yaml`'s default resource list, matching `config/fabric-router/`'s exemption. -- **`config/galactic-nat/`** — the sharded egress translation (NAT66/NAT64) control plane, one `galactic-nat` DaemonSet per cluster on every node labeled `galactic.datumapis.com/nat: enabled` (and carrying no `galactic.datumapis.com/node` label). It is independent of `galactic-gateway`. A shard's identity (SID, masquerade addresses, NAT64 prefix) comes from the `EgressShard` targeting its node, not from the DaemonSet. The base leaves `GALACTIC_NAT_XDP_ATTACH` at its default, `direct`. On a node that also runs the gateway, which already holds the native XDP hook on the uplinks the shard needs, apply `config/galactic-nat/overlays/chained/`, which sets `chain`: the shard installs its dispatcher in the gateway's pinned `xdp_chain` program array and receives every packet the gateway does not claim. Compute nodes reach their own site's shards over SRv6 via `GALACTIC_CNI_EGRESS_SHARD_SIDS`. `kubectl apply -k config/galactic-nat/` applies only the ServiceAccount/RBAC; `base/` is excluded because uplink auto-detection is deployment-specific (see `config/galactic-nat/kustomization.yaml`). Not part of the root `config/kustomization.yaml`. +- **`config/galactic-nat/`** — the sharded egress translation (NAT66/NAT64) control plane, one `galactic-nat` DaemonSet per cluster on every node labeled `galactic.datumapis.com/nat: enabled` (and carrying no `galactic.datumapis.com/node` label). It is independent of `galactic-gateway`. A shard's identity (SID, masquerade addresses, NAT64 prefix) comes from the `EgressShard` targeting its node, not from the DaemonSet. The base leaves `GALACTIC_NAT_XDP_ATTACH` at its default, `direct`. On a node that also runs the gateway, set it to `dispatch`: an interface takes one native XDP program, so the shard and the gateway (which defaults to `GALACTIC_GATEWAY_XDP_ATTACH=dispatch`) each run from their own slot of the node's shared, pinned XDP dispatcher (`internal/plumbing/ebpf/xdpdispatch`), and either can restart or be turned off (`GALACTIC_*_DATAPATH_ENABLED=false`) without touching the other's traffic. `hack/xdp-dispatch-release.sh` detaches the dispatcher from a node. Compute nodes reach their own site's shards over SRv6 via `GALACTIC_CNI_EGRESS_SHARD_SIDS`. `kubectl apply -k config/galactic-nat/` applies only the ServiceAccount/RBAC; `base/` is excluded because uplink auto-detection is deployment-specific (see `config/galactic-nat/kustomization.yaml`). Not part of the root `config/kustomization.yaml`. - **`config/fabric-router/`** — the FRR underlay eBGP DaemonSet (`fabric-router`; `galactic-router` needs a working underlay before it can start). Unlike `config/galactic-router/`, this is a single flat DaemonSet with no `default`/`rr`-style role split — its affinity matches any node labeled `galactic.datumapis.com/fabric: router` (a dedicated mode-enum label, independent of whatever `galactic.datumapis.com/node` role value or `galactic.datumapis.com/galactic` mode that node also carries) directly, since there's no env/config difference between running on a regular node vs. those roles — fabric-router itself is identical everywhere; only the per-node BGP underlay config it reads from the ConfigMap differs. That affinity can legitimately match more than one node per cluster, and BGP underlay config (hostname, router-id, interface addresses, remote-AS) inherently differs per physical node — so each node's config lives in its own `fabric-router.` ConfigMap (a `frr.conf` key, plus optional `daemons`/`vtysh.conf` overrides of the image defaults) rather than one shared ConfigMap for the whole DaemonSet. `fabric-config-agent` (`cmd/fabric-config-agent`, `internal/fabricconfig`, built into the `fabric-router` image) reads it from the API: as the `frr-init` init container it validates (`vtysh -C`) and installs it, holding the pod in `Init` until a valid one exists; as the `config-agent` sidecar it applies later changes live with `frr-reload.py`, so an edit to one node's ConfigMap neither restarts the pod nor touches other nodes, and reports `Applied`/`Rejected`/`ReloadFailed`/`RestartRequired` events on the ConfigMap. The sidecar also hard-resets any IPv6 session announcing an IPv4-mapped next hop (`internal/fabricconfig/nexthop.go`) and serves that check's metrics on the node's port `9343`. A third container, `frr-exporter` (upstream `tynany/frr_exporter`, pinned by digest), reads the daemons' vty sockets in the same pod-scoped `/run/frr` and serves BGP peer state, message counters and prefix counts for both underlay families on the node's port `9342` (`hostNetwork`); `task verify:fabric-metrics` in `deploy/containerlab/` checks it on every lab node. The image's default `daemons` loads bgpd's BMP module (`-M bmp`), so a node's `frr.conf` can stream to a BMP collector (`config/bmp-collector/`) with a `bmp targets` block; loading it alone streams nothing, and a change to the modules needs a pod restart rather than a reload. Every lab node's `frr.conf` streams its pre-policy Adj-RIB-In and Loc-RIB for both families, sourced from `lo` (`source-interface lo`), since the underlay carries loopbacks but not link subnets. Production `frr.conf`s come from infra's renderer, which has to emit the same block for production nodes to stream. A node with no ConfigMap of its own falls back, with a `DeprecatedConfigSource` warning, to key `frr.conf.` of the legacy shared `fabric-config` ConfigMap. **Not** part of the root `config/kustomization.yaml` and not covered by `kubectl apply -k config/` — unlike every other component here, it has no generic default: the deployer must hand-author one `fabric-router.` ConfigMap per matching node before applying `kubectl apply -k config/fabric-router/` (which also applies the agent's ServiceAccount and namespaced Role). - **`config/bmp-collector/`** — a single-replica GoBMP Deployment and its `bmp-collector` Service (TCP `5000`), the BMP (RFC 7854) collector `galactic-router` and `fabric-router` stream to; `galactic-router` does so when `GALACTIC_ROUTER_BMP_STATIONS` names it (`bmp-collector.galactic-system.svc:5000`; see [docs/router/configuration.md](docs/router/configuration.md)). It parses every Peer Up/Down, route-monitoring and statistics message to JSON on stdout, so the cluster's log pipeline is its store; an overlay swapping `--dump=console` for `--kafka-server` publishes to Kafka instead. Opt-in, like `config/fabric-router/`: not part of the root `config/kustomization.yaml`, since nothing streams to it until a router is configured to. The containerlab lab runs one on `iad-worker3`'s host network (`deploy/containerlab/resources/bmp-collector/iad/`), because its three clusters cannot reach each other's Services, and points every node's `fabric-router` and the EVPN route reflector at it. Of the `galactic-router`s, only the reflector streams: its pre-policy Adj-RIB-In already holds every node's advertisements. - **`config/monitoring/`** — Prometheus Operator resources for BGP and NAT: a `fabric-router` PodMonitor (frr-exporter, port `frr-metrics`/`9342`, as `job=fabric-router`; fabric-config-agent, port `agent-metrics`/`9343`, as `job=fabric-config-agent`), a `galactic-router` PodMonitor covering both roles (port `metrics`/`9179`), a `galactic-nat` PodMonitor for the egress shards (port `metrics`/`9182`), each adding a `node` label, and the `galactic-bgp` PrometheusRule: underlay session down, administratively down for an hour, flapping, received prefixes halved, exporter collector or scrape failing, a session announcing an IPv4-mapped next hop, BGP routes not installed, the agent's metrics scrape down, a `galactic-router` BMP station or metrics scrape down, `galactic-router` routes failing to install, an egress shard's session table evicting live sessions, a single stalled NIC receive queue on a `galactic-nat` uplink (#673), and a `galactic-nat` metrics scrape down. Requires the `monitoring.coreos.com` CRDs, which this repo does not install, so it is not part of the root `config/kustomization.yaml`. `task test:alerts` unit-tests the rules with `promtool` (`config/monitoring/tests/`). Every alert carries what infra's alerting standard checks for (`service: galactic`, `team: connect`, `runbook_url` into infra's `docs/runbooks/galactic/README.md`). The PrometheusRule here is the tested source, not where the rules run on Datum's infra: there the PodMonitors are converted and scraped on each edge cluster, but edge vmalert never notifies, so infra evaluates a copy of the rules centrally. Change the rules here first, with their tests, then update infra's copy. diff --git a/cmd/galactic-gateway/dispatch_test.go b/cmd/galactic-gateway/dispatch_test.go new file mode 100644 index 000000000..5448cf665 --- /dev/null +++ b/cmd/galactic-gateway/dispatch_test.go @@ -0,0 +1,222 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/cilium/ebpf/rlimit" + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/ebpf/natattach" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpattach" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" +) + +func requireRoot(t *testing.T) { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("test requires root (CAP_BPF/CAP_NET_ADMIN) to load and attach XDP programs; re-run via sudo") + } + if err := rlimit.RemoveMemlock(); err != nil { + t.Fatalf("rlimit.RemoveMemlock: %v", err) + } +} + +// pinDirs are per-test bpffs directories for the dispatcher, the gateway's +// own maps and the egress shard's. +type pinDirs struct{ dispatch, edge, nat string } + +func testPinDirs(t *testing.T) pinDirs { + t.Helper() + requireRoot(t) + name := strings.NewReplacer("/", "-", " ", "-").Replace(t.Name()) + base := filepath.Join("/sys/fs/bpf", "gwdispatch-test-"+name) + _ = os.RemoveAll(base) + d := pinDirs{filepath.Join(base, "xdp"), filepath.Join(base, "edge"), filepath.Join(base, "nat")} + for _, dir := range []string{d.dispatch, d.edge, d.nat} { + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Skipf("bpffs not writable at /sys/fs/bpf: %v", err) + } + } + t.Cleanup(func() { _ = os.RemoveAll(base) }) + return d +} + +func testUplink(t *testing.T, prefix string) (string, int) { + t.Helper() + name := fmt.Sprintf("%s%d", prefix, os.Getpid()%10000) + veth := &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: name}, PeerName: name + "p"} + if err := netlink.LinkAdd(veth); err != nil { + t.Fatalf("add veth %s: %v", name, err) + } + t.Cleanup(func() { _ = netlink.LinkDel(veth) }) + for _, n := range []string{name, name + "p"} { + l, err := netlink.LinkByName(n) + if err != nil { + t.Fatalf("find %s: %v", n, err) + } + if err := netlink.LinkSetUp(l); err != nil { + t.Fatalf("set %s up: %v", n, err) + } + } + l, _ := netlink.LinkByName(name) + return name, l.Attrs().Index +} + +func xdpProgID(t *testing.T, name string) uint32 { + t.Helper() + l, err := netlink.LinkByName(name) + if err != nil { + t.Fatalf("find %s: %v", name, err) + } + if xdp := l.Attrs().Xdp; xdp != nil && xdp.Attached { + return xdp.ProgId + } + return 0 +} + +// gatewayProcess is one gateway process joined to the dispatcher; stop is its +// exit. +type gatewayProcess struct { + public targetSet + stop func() +} + +func startGateway(t *testing.T, d pinDirs) gatewayProcess { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + objs, dispatcher, public, _, leaseDone, err := joinDispatcher(ctx, d.dispatch, d.edge, false) + if err != nil { + cancel() + t.Fatalf("gateway joinDispatcher: %v", err) + } + stopped := false + stop := func() { + if stopped { + return + } + stopped = true + cancel() + <-leaseDone + _ = dispatcher.Close() + _ = objs.Close() + } + t.Cleanup(stop) + return gatewayProcess{public: public, stop: stop} +} + +// startShard joins the egress shard to the dispatcher the way galactic-nat's +// dispatch mode does, and returns its coverage check. +func startShard(t *testing.T, d pinDirs, uplink string) func() error { + t.Helper() + objs, err := natattach.Load(d.nat) + if err != nil { + t.Fatalf("load shard objects: %v", err) + } + t.Cleanup(func() { _ = objs.Close() }) + if err := natattach.PopulateProgArray(objs); err != nil { + t.Fatalf("populate nat_progs: %v", err) + } + dispatcher, err := xdpdispatch.Open(context.Background(), d.dispatch) + if err != nil { + t.Fatalf("shard open dispatcher: %v", err) + } + t.Cleanup(func() { _ = dispatcher.Close() }) + lock, err := dispatcher.Lock(context.Background()) + if err != nil { + t.Fatalf("Lock: %v", err) + } + err = lock.Fill(xdpdispatch.SlotNAT, objs.NatIngress) + lock.Unlock() + if err != nil { + t.Fatalf("fill the egress slot: %v", err) + } + set, err := xdpattach.NewDispatchSet(dispatcher, xdpdispatch.SlotNAT, xdpdispatch.RoleEgress, objs.NatIngress) + if err != nil { + t.Fatalf("NewDispatchSet: %v", err) + } + if missing := set.Reconcile(context.Background(), []string{uplink}); len(missing) != 0 { + t.Fatalf("shard missing %v", missing) + } + l, _ := netlink.LinkByName(uplink) + return func() error { return dispatcher.Coverage(l.Attrs().Index, xdpdispatch.SlotNAT, objs.NatIngress) } +} + +// TestGatewayAndShardShareAnUplink is issue #717's acceptance case: the gateway +// and the egress shard hold one uplink through the dispatcher, and the gateway +// restarting leaves the shard's traffic and the uplink's program untouched. +func TestGatewayAndShardShareAnUplink(t *testing.T) { + d := testPinDirs(t) + uplink, ifindex := testUplink(t, "gwsh") + + gw := startGateway(t, d) + if missing := gw.public.reconcile(context.Background(), []string{uplink}); len(missing) != 0 { + t.Fatalf("gateway missing %v", missing) + } + shardCovered := startShard(t, d, uplink) + root := xdpProgID(t, uplink) + + probe, err := xdpdispatch.Open(context.Background(), d.dispatch) + if err != nil { + t.Fatalf("open dispatcher: %v", err) + } + t.Cleanup(func() { _ = probe.Close() }) + if roles, _ := probe.Roles(ifindex); roles != xdpdispatch.RolePublicLB|xdpdispatch.RoleEgress { + t.Errorf("uplink roles = %#x, want public and egress", roles) + } + + // The gateway process exits and a new one starts. + gw.stop() + if got := xdpProgID(t, uplink); got != root { + t.Fatalf("uplink runs %d after the gateway exited, want the root %d", got, root) + } + if err := shardCovered(); err != nil { + t.Fatalf("shard lost its uplink when the gateway exited: %v", err) + } + gw2 := startGateway(t, d) + if missing := gw2.public.reconcile(context.Background(), []string{uplink}); len(missing) != 0 { + t.Errorf("restarted gateway missing %v", missing) + } + if got := xdpProgID(t, uplink); got != root { + t.Errorf("uplink runs %d after the gateway restarted, want the same root %d", got, root) + } + if err := shardCovered(); err != nil { + t.Errorf("shard lost its uplink across the gateway restart: %v", err) + } +} + +// TestAttachDirect_RefusesAnUplinkTheShardRunsOn: a gateway set to direct mode +// on a node whose shard runs from the dispatcher must not take the hook. +func TestAttachDirect_RefusesAnUplinkTheShardRunsOn(t *testing.T) { + d := testPinDirs(t) + uplink, _ := testUplink(t, "gwdr") + startShard(t, d, uplink) + root := xdpProgID(t, uplink) + + _, _, _, err := attachDirect(context.Background(), d.dispatch, d.edge, []string{uplink}, nil) + if !errors.Is(err, xdpattach.ErrDispatcherInUse) { + t.Fatalf("attachDirect over a live shard slot = %v, want ErrDispatcherInUse", err) + } + if got := xdpProgID(t, uplink); got != root { + t.Errorf("uplink runs %d after the refusal, want the root %d untouched", got, root) + } +} + +func TestPublicReturnOverlap(t *testing.T) { + const shared = "eth2" + if got := publicReturnOverlap([]string{"eth1", shared}, []string{shared, "eth3"}); len(got) != 1 || got[0] != shared { + t.Errorf("publicReturnOverlap = %v, want [%s]", got, shared) + } + if got := publicReturnOverlap([]string{"eth1"}, []string{"eth3"}); len(got) != 0 { + t.Errorf("publicReturnOverlap = %v, want none", got) + } +} diff --git a/cmd/galactic-gateway/gateway.go b/cmd/galactic-gateway/gateway.go index 12e78f64c..42601ef21 100644 --- a/cmd/galactic-gateway/gateway.go +++ b/cmd/galactic-gateway/gateway.go @@ -6,6 +6,7 @@ package main import ( "context" + "errors" "fmt" "log/slog" "net/netip" @@ -15,11 +16,13 @@ import ( "github.com/cilium/ebpf/link" "github.com/prometheus/client_golang/prometheus" + "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/gateway" "go.datum.net/galactic/internal/plumbing/ebpf/edgeattach" "go.datum.net/galactic/internal/plumbing/ebpf/edgemetrics" "go.datum.net/galactic/internal/plumbing/ebpf/edgeprog" "go.datum.net/galactic/internal/plumbing/ebpf/xdpattach" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" "go.datum.net/galactic/internal/plumbing/sysctl" ) @@ -39,9 +42,10 @@ import ( // a registered rule is never intercepted at all and routes past the node // ordinarily. var gatewayDatapathKeepAlive struct { - objs *edgeprog.EdgedsrObjects - publicSet *xdpattach.Set - returnSet *xdpattach.Set + objs *edgeprog.EdgedsrObjects + publicSet targetSet + returnSet targetSet + dispatcher *xdpdispatch.Dispatcher } // setupGatewayDatapath loads and attaches the edge Maglev datapath to @@ -79,7 +83,7 @@ var gatewayDatapathKeepAlive struct { // metricsReg additionally gets a collector registered against it once the // objects are loaded, reading the maps live at every scrape. func setupGatewayDatapath( - ctx context.Context, publicInterface string, internalInterfaces []string, srv6Address string, + ctx context.Context, publicInterface string, internalInterfaces []string, srv6Address, attachMode string, metricsReg prometheus.Registerer, coverage *datapathCoverage, ) (gateway.Datapath, error) { encapSrc, err := netip.ParseAddr(srv6Address) @@ -96,6 +100,14 @@ func setupGatewayDatapath( if err != nil { return nil, err } + // edge_return forwards anything sourced from a VIP. On a public uplink an + // external client could source a packet from a VIP and have it forwarded + // unexamined, so an internal interface may never resolve to a public one. + if overlap := publicReturnOverlap(targets, returnTargets); len(overlap) > 0 { + return nil, fmt.Errorf("edge gateway internal interfaces %v resolve to %v, which the public interface %q "+ + "also resolves to; the return program must never run on a public uplink", internalInterfaces, + overlap, publicInterface) + } // Required for the FIB lookup in the datapath's header push to succeed // on the interface the program actually runs on. The lookup uses the @@ -120,66 +132,239 @@ func setupGatewayDatapath( } } - objs, err := edgeattach.Load(edgeattach.PinDir) + var ( + objs *edgeprog.EdgedsrObjects + publicSet, returnSet targetSet + dispatcher *xdpdispatch.Dispatcher + ) + // abandon undoes a dispatcher join when a later setup step fails: the + // leases stop and the slots are emptied, so a half-set-up gateway never + // claims packets while the process exits. + abandon := func() {} + if attachMode == config.GatewayXDPAttachDispatch { + leaseCtx, stopLeases := context.WithCancel(ctx) + var leaseDone <-chan struct{} + objs, dispatcher, publicSet, returnSet, leaseDone, err = joinDispatcher(leaseCtx, xdpdispatch.PinDir, + edgeattach.PinDir, len(returnTargets) > 0) + if err != nil { + stopLeases() + return nil, err + } + abandon = func() { + stopLeases() + <-leaseDone + if err := xdpattach.ClearDispatcherSlots(ctx, xdpdispatch.PinDir, xdpdispatch.SlotGatewayLB, + xdpdispatch.SlotGatewayReturn); err != nil { + slog.Warn("Cannot empty the edge gateway's dispatcher slots after a failed setup", "err", err) + } + } + } else { + objs, publicSet, returnSet, err = attachDirect(ctx, xdpdispatch.PinDir, edgeattach.PinDir, targets, + returnTargets) + } if err != nil { - return nil, fmt.Errorf("load edge gateway eBPF datapath: %w", err) + return nil, err } - xdpLinks, err := edgeattach.Attach(objs.EdgeLb, targets) + datapath, err := gateway.NewKernelDatapath(objs, encapSrc) if err != nil { - _ = objs.Close() - return nil, fmt.Errorf("attach edge gateway datapath to public interface %q: %w", publicInterface, err) + abandon() + return nil, fmt.Errorf("construct kernel datapath: %w", err) + } + if err := metricsReg.Register(edgemetrics.NewCollectorFromObjects(objs)); err != nil { + abandon() + return nil, fmt.Errorf("register edge gateway metrics collector: %w", err) } - if len(returnTargets) > 0 { - returnLinks, err := edgeattach.Attach(objs.EdgeReturn, returnTargets) - if err != nil { - closeAll(xdpLinks) - _ = objs.Close() - return nil, fmt.Errorf("attach edge gateway return datapath to internal interfaces %v: %w", - internalInterfaces, err) - } - xdpLinks = append(xdpLinks, returnLinks...) + gatewayDatapathKeepAlive.objs = objs + gatewayDatapathKeepAlive.publicSet = publicSet + gatewayDatapathKeepAlive.returnSet = returnSet + gatewayDatapathKeepAlive.dispatcher = dispatcher + + for _, target := range append(slices.Clone(targets), returnTargets...) { + coverage.configured[target] = true + } + missing := publicSet.reconcile(ctx, targets) + if returnSet != nil { + missing = append(missing, returnSet.reconcile(ctx, returnTargets)...) } + coverage.set(missing) + go watchTargets(ctx, publicInterface, internalInterfaces, publicSet, returnSet, coverage) - datapath, err := gateway.NewKernelDatapath(objs, encapSrc) + return datapath, nil +} + +// targetSet keeps one of the gateway's programs on a set of interfaces and +// reports the ones it does not cover: xdpattach.Set in direct mode, +// xdpattach.DispatchSet in dispatch mode. +type targetSet interface { + reconcile(ctx context.Context, targets []string) (missing []string) +} + +type directSet struct{ *xdpattach.Set } + +func (s directSet) reconcile(_ context.Context, targets []string) []string { + s.Reconcile(targets) + return uncovered(targets, s.Attached()) +} + +type dispatchSet struct{ *xdpattach.DispatchSet } + +func (s dispatchSet) reconcile(ctx context.Context, targets []string) []string { + return s.Reconcile(ctx, targets) +} + +// attachDirect loads the programs with their own dispatcher maps and attaches +// them to the targets themselves, unpinned, after releasing an idle +// dispatcher from those targets. A dispatcher still serving the egress shard +// there is refused rather than taken: detaching it would cut egress. +// Attachment is all-or-nothing, as it has always been in this mode. +func attachDirect(ctx context.Context, dispatchDir, edgeDir string, targets, returnTargets []string) ( + *edgeprog.EdgedsrObjects, targetSet, targetSet, error, +) { + if err := xdpattach.ReleaseIdleDispatcher(ctx, dispatchDir, append(slices.Clone(targets), returnTargets...), + xdpdispatch.SlotGatewayLB, xdpdispatch.SlotGatewayReturn); err != nil { + return nil, nil, nil, fmt.Errorf("%w; set %s=%s", err, config.EnvGatewayXDPAttach, + config.GatewayXDPAttachDispatch) + } + + objs, err := edgeattach.Load(edgeDir, nil) + if err != nil { + return nil, nil, nil, fmt.Errorf("load edge gateway eBPF datapath: %w", err) + } + + xdpLinks, err := edgeattach.Attach(objs.EdgeLb, targets) + if err != nil { + _ = objs.Close() + return nil, nil, nil, fmt.Errorf("attach edge gateway datapath to public interfaces %v: %w", targets, err) + } + publicSet, err := xdpattach.NewSet(objs.EdgeLb, targets, xdpLinks) if err != nil { closeAll(xdpLinks) _ = objs.Close() - return nil, fmt.Errorf("construct kernel datapath: %w", err) + return nil, nil, nil, err + } + if len(returnTargets) == 0 { + return objs, directSet{publicSet}, nil, nil } - if err := metricsReg.Register(edgemetrics.NewCollectorFromObjects(objs)); err != nil { + returnLinks, err := edgeattach.Attach(objs.EdgeReturn, returnTargets) + if err != nil { closeAll(xdpLinks) _ = objs.Close() - return nil, fmt.Errorf("register edge gateway metrics collector: %w", err) + return nil, nil, nil, fmt.Errorf("attach edge gateway return datapath to internal interfaces %v: %w", + returnTargets, err) } + returnSet, err := xdpattach.NewSet(objs.EdgeReturn, returnTargets, returnLinks) + if err != nil { + closeAll(append(xdpLinks, returnLinks...)) + _ = objs.Close() + return nil, nil, nil, err + } + return objs, directSet{publicSet}, directSet{returnSet}, nil +} - publicSet, err := xdpattach.NewSet(objs.EdgeLb, targets, xdpLinks[:len(targets)]) +// joinDispatcher opens the node's XDP dispatcher under dispatchDir, loads the +// programs against its maps, with their own maps pinned under edgeDir, fills +// the gateway's slots, and renews both slots' leases for the life of ctx. The +// return slot is filled whether or not this node has internal interfaces: +// without the role on any interface it never runs. Nothing is attached here; +// the returned sets put the dispatcher on the targets and read coverage back. +// The returned channel closes once both lease loops have stopped, which a +// caller waits on before closing the dispatcher. +func joinDispatcher(ctx context.Context, dispatchDir, edgeDir string, withReturn bool) ( + *edgeprog.EdgedsrObjects, *xdpdispatch.Dispatcher, targetSet, targetSet, <-chan struct{}, error, +) { + dispatcher, err := xdpdispatch.Open(ctx, dispatchDir) + if err != nil { + return nil, nil, nil, nil, nil, fmt.Errorf("open the node's XDP dispatcher: %w", err) + } + fail := func(err error) (*edgeprog.EdgedsrObjects, *xdpdispatch.Dispatcher, targetSet, targetSet, + <-chan struct{}, error, + ) { + _ = dispatcher.Close() + return nil, nil, nil, nil, nil, err + } + + objs, err := edgeattach.Load(edgeDir, dispatcher.Maps()) + if err != nil { + return fail(fmt.Errorf("load edge gateway eBPF datapath: %w", err)) + } + lock, err := dispatcher.Lock(ctx) if err != nil { - closeAll(xdpLinks) _ = objs.Close() - return nil, err + return fail(err) + } + err = errors.Join(lock.Fill(xdpdispatch.SlotGatewayLB, objs.EdgeLb), + lock.Fill(xdpdispatch.SlotGatewayReturn, objs.EdgeReturn)) + lock.Unlock() + if err != nil { + _ = objs.Close() + return fail(fmt.Errorf("install edge gateway datapath in the XDP dispatcher: %w", err)) } - var returnSet *xdpattach.Set - if len(returnTargets) > 0 { - if returnSet, err = xdpattach.NewSet(objs.EdgeReturn, returnTargets, xdpLinks[len(targets):]); err != nil { - closeAll(xdpLinks) + + public, err := xdpattach.NewDispatchSet(dispatcher, xdpdispatch.SlotGatewayLB, xdpdispatch.RolePublicLB, + objs.EdgeLb) + if err != nil { + _ = objs.Close() + return fail(err) + } + var ret targetSet + if withReturn { + rs, err := xdpattach.NewDispatchSet(dispatcher, xdpdispatch.SlotGatewayReturn, + xdpdispatch.RoleInternalReturn, objs.EdgeReturn) + if err != nil { _ = objs.Close() - return nil, err + return fail(err) } + ret = dispatchSet{rs} } - gatewayDatapathKeepAlive.objs = objs - gatewayDatapathKeepAlive.publicSet = publicSet - gatewayDatapathKeepAlive.returnSet = returnSet + // A lapsed lease shows as missing interfaces within one coverage resync, + // since every Reconcile reads the lease back. + var leases sync.WaitGroup + for _, slot := range []xdpdispatch.Slot{xdpdispatch.SlotGatewayLB, xdpdispatch.SlotGatewayReturn} { + leases.Go(func() { + dispatcher.Lease(ctx, slot, func(err error) { + slog.Error("Cannot renew an edge gateway slot's lease in the XDP dispatcher; "+ + "the dispatcher skips the slot once it lapses", "slot", slot, "err", err) + }) + }) + } + leaseDone := make(chan struct{}) + go func() { + leases.Wait() + close(leaseDone) + }() + slog.Info("Edge gateway datapath installed in the XDP dispatcher", "pinDir", dispatchDir) + return objs, dispatcher, dispatchSet{public}, ret, leaseDone, nil +} - for _, target := range append(slices.Clone(targets), returnTargets...) { - coverage.configured[target] = true +// publicReturnOverlap returns the return targets that are also public targets. +func publicReturnOverlap(targets, returnTargets []string) []string { + var overlap []string + for _, t := range returnTargets { + if slices.Contains(targets, t) { + overlap = append(overlap, t) + } } - go watchTargets(ctx, publicInterface, internalInterfaces, publicSet, returnSet, coverage) + return overlap +} - return datapath, nil +// turnOffDatapath turns this node's gateway off. A dispatch-mode predecessor +// left the gateway's programs in the XDP dispatcher with live leases, so its +// slots are emptied here and the dispatcher passes their traffic on at once. +// Every other slot, and the dispatcher itself, are left alone. A failure is +// logged, not returned: the leases lapse on their own within +// xdpdispatch.LeaseTTL. +func turnOffDatapath(ctx context.Context, pinDir string) { + if err := xdpattach.ClearDispatcherSlots(ctx, pinDir, xdpdispatch.SlotGatewayLB, + xdpdispatch.SlotGatewayReturn); err != nil { + slog.Error("Cannot empty the edge gateway's slots in the XDP dispatcher; "+ + "they stop claiming packets once their leases lapse", "lease", xdpdispatch.LeaseTTL, "err", err) + } + slog.Info("Edge gateway datapath is turned off; this node attaches nothing and advertises no VIP", + "env", config.EnvGatewayDatapathEnabled) } // datapathCoverage is which of the datapath's resolved targets it is not @@ -252,7 +437,7 @@ func (c *datapathCoverage) configure(targets []string) []string { // bond in the moment between losing a member and enslaving its replacement, // keeps every attachment and skips that pass. func watchTargets(ctx context.Context, publicInterface string, internalInterfaces []string, - publicSet, returnSet *xdpattach.Set, coverage *datapathCoverage, + publicSet, returnSet targetSet, coverage *datapathCoverage, ) { xdpattach.OnNetlinkChange(ctx, func() { targets, err := edgeattach.ResolveTargets(publicInterface) @@ -268,18 +453,37 @@ func watchTargets(ctx context.Context, publicInterface string, internalInterface "err", err) return } + if overlap := publicReturnOverlap(targets, returnTargets); len(overlap) > 0 { + slog.Warn("Internal interfaces now resolve to public ones; keeping the return program off them", + "interfaces", overlap) + returnTargets = slices.DeleteFunc(returnTargets, func(t string) bool { return slices.Contains(overlap, t) }) + } } - publicSet.Reconcile(coverage.configure(targets)) - missing := uncovered(targets, publicSet.Attached()) + // A target whose forwarding sysctls failed is left out of the set and + // counted missing; configure retries it on the next pass. + ready := coverage.configure(targets) + missing := append(publicSet.reconcile(ctx, ready), uncovered(targets, ready)...) if returnSet != nil { - returnSet.Reconcile(coverage.configure(returnTargets)) - missing = append(missing, uncovered(returnTargets, returnSet.Attached())...) + ready := coverage.configure(returnTargets) + missing = append(missing, returnSet.reconcile(ctx, ready)...) + missing = append(missing, uncovered(returnTargets, ready)...) } - coverage.set(missing) + coverage.set(dedupe(missing)) }) } +// dedupe drops repeated names, keeping the first of each. +func dedupe(names []string) []string { + var out []string + for _, n := range names { + if !slices.Contains(out, n) { + out = append(out, n) + } + } + return out +} + // uncovered returns every one of targets not in covered, in targets' order. func uncovered(targets, covered []string) []string { var out []string diff --git a/cmd/galactic-gateway/gateway_test.go b/cmd/galactic-gateway/gateway_test.go index de6d2b655..1059d1264 100644 --- a/cmd/galactic-gateway/gateway_test.go +++ b/cmd/galactic-gateway/gateway_test.go @@ -18,7 +18,7 @@ import ( // binary's config.GatewayConfig.Validate rejects an empty // PublicInterface/SRv6Address before setupGatewayDatapath is ever called. func TestSetupGatewayDatapath_InvalidAddressIsError(t *testing.T) { - _, err := setupGatewayDatapath(context.Background(), "eth0", nil, "not-an-ip-address", + _, err := setupGatewayDatapath(context.Background(), "eth0", nil, "not-an-ip-address", "dispatch", prometheus.NewRegistry(), newDatapathCoverage(nil)) if err == nil { t.Error("setupGatewayDatapath with an invalid SRv6 address: want an error, got nil") diff --git a/cmd/galactic-gateway/root.go b/cmd/galactic-gateway/root.go index 225514fa4..6369fec5b 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -27,6 +27,7 @@ import ( "go.datum.net/galactic/internal/controller" "go.datum.net/galactic/internal/gateway" "go.datum.net/galactic/internal/metadata" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" bgpv1alpha1 "go.datum.net/network/api/v1alpha1" ) @@ -132,10 +133,17 @@ func runCmd(cfg *config.GatewayConfig) error { default: } }) - gwDatapath, err := setupGatewayDatapath(ctx, - cfg.PublicInterface, cfg.InternalInterfaces, cfg.SRv6Address, ctrlmetrics.Registry, coverage) - if err != nil { - return fmt.Errorf("setup edge gateway eBPF datapath: %w", err) + var gwDatapath gateway.Datapath = gateway.NoopDatapath{} + if cfg.DatapathEnabled { + gwDatapath, err = setupGatewayDatapath(ctx, cfg.PublicInterface, cfg.InternalInterfaces, cfg.SRv6Address, + cfg.XDPAttach, ctrlmetrics.Registry, coverage) + if err != nil { + return fmt.Errorf("setup edge gateway eBPF datapath: %w", err) + } + } else { + // Nothing to attach and nothing to load: the reconciler below keeps + // this node's VIPs withdrawn, so no rule reaches this datapath. + turnOffDatapath(ctx, xdpdispatch.PinDir) } // Only now is the datapath attached and its rule table reachable. Report // serving from here on, not from process start. @@ -157,6 +165,7 @@ func runCmd(cfg *config.GatewayConfig) error { Scheme: mgr.GetScheme(), Engine: gwEngine, NodeName: nodeName, + Disabled: !cfg.DatapathEnabled, }).SetupWithManager(mgr); err != nil { return fmt.Errorf("setup NetworkGateway controller: %w", err) } @@ -245,6 +254,12 @@ func newRootCommand() *cobra.Command { "forwards before netfilter (optional; empty means this node carries no return traffic)") cmd.Flags().StringP("gateway-srv6-address", "", "", "This gateway node's own SRv6-reachable address, used as the Maglev/DSR encap source (required)") + cmd.Flags().StringP("gateway-xdp-attach", "", config.GatewayXDPAttachDispatch, + "How the datapath reaches its interfaces' XDP hook: \"dispatch\" runs it from the node's shared, "+ + "pinned XDP dispatcher, \"direct\" attaches it") + cmd.Flags().Bool("gateway-datapath-enabled", true, + "Run the edge gateway datapath; false keeps the process up but attaches nothing and withdraws "+ + "this node's VIP advertisements") cmd.Flags().Bool("build-info", false, "Print build information and exit") cmd.Flags().BoolP("version", "V", false, "Print version and exit") return cmd diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 7cb21de0e..e11553174 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -9,8 +9,6 @@ import ( "errors" "fmt" "log/slog" - "os" - "path/filepath" "slices" "sync" "time" @@ -19,7 +17,6 @@ import ( "github.com/cilium/ebpf/link" "github.com/prometheus/client_golang/prometheus" "github.com/safchain/ethtool" - "github.com/vishvananda/netlink" "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/controller" @@ -262,12 +259,6 @@ func (d *natDatapath) Programmed() (controller.EgressShardIdentity, bool) { // In direct mode, an idle dispatcher on the resolved uplinks is released // first (releaseIdleDispatcher). // -// In chain mode (config.NATXDPAttachChain) nothing is attached: the program is -// installed in the edge gateway's xdp_chain slot instead, waiting for the -// gateway to create it, and kept there for the life of the process by -// keepChain. The uplinks are still resolved, for the forwarding sysctls and to -// report any the gateway does not hook as missing. -// // The loaded objects and the attachment set are stashed in // natDatapathKeepAlive rather than closed here: they, and the attachment // itself, must survive for the life of this process. @@ -318,12 +309,6 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, xdpLinks []link.Link ) switch cfg.XDPAttach { - case config.NATXDPAttachChain: - if err := waitForChain(ctx, objs.NatIngress, natattach.EdgeChainMapPath); err != nil { - _ = objs.Close() - return nil, err - } - go keepChain(ctx, objs.NatIngress, natattach.EdgeChainMapPath) case config.NATXDPAttachDispatch: // The lease runs for the life of the process, so its done channel // is not needed here. @@ -369,8 +354,7 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, ) d.attached = true - go d.watchUplinks(ctx, cfg.UplinkInterfaces, coverageFor(ctx, set, dispatchSet), dispatchSet == nil && set == nil, - onCoverage) + go d.watchUplinks(ctx, cfg.UplinkInterfaces, coverageFor(ctx, set, dispatchSet), onCoverage) return d, nil } @@ -434,79 +418,28 @@ func joinDispatcher(ctx context.Context, pinDir string, program *ebpf.Program) ( return dispatcher, set, leaseDone, nil } -// releaseIdleDispatcher detaches the node's XDP dispatcher from uplinks, so a -// shard switched back from dispatch to direct mode can attach its own program. -// It does nothing on a node that never ran the dispatcher. -// -// It refuses, returning an error, while another datapath's slot is live: the -// dispatcher is serving that datapath on these uplinks, and detaching it would -// cut that datapath's traffic. Such a node needs dispatch mode. +// releaseIdleDispatcher detaches an idle XDP dispatcher from uplinks before a +// direct attach (xdpattach.ReleaseIdleDispatcher), refusing while another +// datapath's slot is live there. func releaseIdleDispatcher(ctx context.Context, pinDir string, uplinks []string) error { - if _, err := os.Stat(filepath.Join(pinDir, "links")); errors.Is(err, os.ErrNotExist) { - return nil - } - dispatcher, err := xdpdispatch.Open(ctx, pinDir) - if err != nil { - return fmt.Errorf("open the node's XDP dispatcher to release it: %w", err) + if err := xdpattach.ReleaseIdleDispatcher(ctx, pinDir, uplinks, xdpdispatch.SlotNAT); err != nil { + return fmt.Errorf("%w; set %s=%s", err, config.EnvNATXDPAttach, config.NATXDPAttachDispatch) } - defer dispatcher.Close() //nolint:errcheck // our own descriptors; the pins are what matter - - // Under the lock, which every Fill takes too, so no other datapath can - // take its slot between this read and the releases below. - lock, err := dispatcher.Lock(ctx) - if err != nil { - return err - } - defer lock.Unlock() - live, err := dispatcher.LiveSlots() - if err != nil { - return err - } - others := slices.DeleteFunc(live, func(s xdpdispatch.Slot) bool { return s == xdpdispatch.SlotNAT }) - for _, name := range uplinks { - l, err := netlink.LinkByName(name) - if err != nil { - return fmt.Errorf("find uplink %q: %w", name, err) - } - ifindex := l.Attrs().Index - linked, err := dispatcher.Linked(ifindex) - if err != nil { - return err - } - if !linked { - continue - } - if len(others) > 0 { - return fmt.Errorf("the XDP dispatcher on uplink %q is also running dispatcher slots %v for "+ - "another datapath, so direct mode cannot take the uplink without cutting that datapath's "+ - "traffic; set %s=%s", name, others, config.EnvNATXDPAttach, config.NATXDPAttachDispatch) - } - if err := lock.Release(ifindex); err != nil { - return err - } - slog.Info("Released the idle XDP dispatcher from uplink for a direct attach", "interface", name) - } - return lock.Clear(xdpdispatch.SlotNAT) + return nil } // coverageFor returns how watchUplinks brings the ready uplinks under the -// datapath and reads back which it covers: through set in direct mode, -// dispatchSet in dispatch mode, and the gateway's hooks in chain mode. +// datapath and reads back which it covers: through set in direct mode, and +// dispatchSet in dispatch mode. func coverageFor(ctx context.Context, set *xdpattach.Set, dispatchSet *xdpattach.DispatchSet) func([]string) []string { - switch { - case set != nil: + if set != nil { return func(ready []string) []string { set.Reconcile(ready) return set.Attached() } - case dispatchSet != nil: - return func(ready []string) []string { - return uncovered(ready, dispatchSet.Reconcile(ctx, ready)) - } - default: - return func(ready []string) []string { - return uncovered(ready, natattach.UnhookedUplinks(ready)) - } + } + return func(ready []string) []string { + return uncovered(ready, dispatchSet.Reconcile(ctx, ready)) } } @@ -544,11 +477,9 @@ func waitForUplinks(ctx context.Context, override []string) ([]string, error) { // watchUplinks keeps the datapath on every uplink ResolveUplinks returns, for // the life of ctx, re-resolving on every netlink link or route change. cover // brings the ready uplinks under the datapath and returns the ones it covers -// (coverageFor). chained says the shard runs in the gateway's xdp_chain, -// which changes what a missing uplink means. onCoverage is called whenever the -// missing uplinks change. +// (coverageFor). onCoverage is called whenever the missing uplinks change. func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover func([]string) []string, - chained bool, onCoverage func(), + onCoverage func(), ) { xdpattach.OnNetlinkChange(ctx, func() { uplinks, err := natattach.ResolveUplinks(override) @@ -566,9 +497,6 @@ func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover switch { case len(missing) == 0: slog.Info("Egress translation datapath covers every uplink", "uplinks", uplinks) - case chained: - slog.Warn("Uplinks carry no XDP program, so the chained shard sees none of their traffic; "+ - "the edge gateway is not attached to them", "missing", missing) default: slog.Warn("Egress translation datapath does not cover every uplink; traffic arriving on these "+ "leaves untranslated", "missing", missing) @@ -590,73 +518,6 @@ func uncovered(uplinks, covered []string) []string { return out } -// chainRetryInterval is how often waitForChain looks for the gateway's map, -// and chainCheckInterval how often keepChain confirms the slot still holds -// this process's program. -const ( - chainRetryInterval = 2 * time.Second - chainCheckInterval = 10 * time.Second -) - -// waitForChain installs program in the gateway's xdp_chain at mapPath, -// retrying while the map does not exist yet -- the gateway loading after this -// process on a fresh node is ordinary, and the startup probe bounds the wait. -// Any other failure, an incompatible program above all, is returned at once: -// retrying cannot fix it. -func waitForChain(ctx context.Context, program *ebpf.Program, mapPath string) error { - logged := false - for { - err := natattach.AttachChain(program, mapPath) - if err == nil { - slog.Info("Egress translation datapath installed in the edge gateway's XDP chain", "map", mapPath) - return nil - } - if !errors.Is(err, os.ErrNotExist) { - return fmt.Errorf("install egress translation datapath in the edge gateway's XDP chain: %w", err) - } - if !logged { - slog.Info("Waiting for the edge gateway to create its XDP chain map", "map", mapPath) - logged = true - } - select { - case <-ctx.Done(): - return fmt.Errorf("waiting for the edge gateway's XDP chain map %q: %w", mapPath, ctx.Err()) - case <-time.After(chainRetryInterval): - } - } -} - -// keepChain re-installs program whenever the slot stops holding it, until ctx -// is done. A gateway restart normally reuses its pinned map and leaves the -// slot alone, but one that had to recreate the map (a layout change) leaves it -// empty, and without this the shard would stop translating with nothing -// reporting it. -func keepChain(ctx context.Context, program *ebpf.Program, mapPath string) { - ticker := time.NewTicker(chainCheckInterval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - } - held, err := natattach.ChainHolds(program, mapPath) - if err != nil { - slog.Warn("Cannot read the edge gateway's XDP chain slot", "map", mapPath, "err", err) - continue - } - if held { - continue - } - if err := natattach.AttachChain(program, mapPath); err != nil { - slog.Error("Egress translation datapath is out of the edge gateway's XDP chain and cannot be "+ - "re-installed; this shard translates nothing until it is", "map", mapPath, "err", err) - continue - } - slog.Warn("Re-installed the egress translation datapath in the edge gateway's XDP chain", "map", mapPath) - } -} - // closeAll best-effort closes every link, to unwind a partially set-up datapath // when attaching succeeded but a later step failed. func closeAll(links []link.Link) { @@ -696,27 +557,10 @@ func (disabledDatapath) Programmed() (controller.EgressShardIdentity, bool) { // shard that crash-looped instead would keep its advertisement up no longer // but would page for nothing. func turnOffDatapath(ctx context.Context, pinDir string) { - if _, err := os.Stat(filepath.Join(pinDir, "links")); err == nil { - if err := emptyDispatcherSlot(ctx, pinDir); err != nil { - slog.Error("Cannot empty the egress translation slot in the XDP dispatcher; "+ - "it stops claiming packets once its lease lapses", "lease", xdpdispatch.LeaseTTL, "err", err) - } + if err := xdpattach.ClearDispatcherSlots(ctx, pinDir, xdpdispatch.SlotNAT); err != nil { + slog.Error("Cannot empty the egress translation slot in the XDP dispatcher; "+ + "it stops claiming packets once its lease lapses", "lease", xdpdispatch.LeaseTTL, "err", err) } slog.Info("Egress translation datapath is turned off; this shard attaches nothing and translates nothing", "env", config.EnvNATDatapathEnabled) } - -// emptyDispatcherSlot clears this shard's slot in the dispatcher under pinDir. -func emptyDispatcherSlot(ctx context.Context, pinDir string) error { - dispatcher, err := xdpdispatch.Open(ctx, pinDir) - if err != nil { - return fmt.Errorf("open the node's XDP dispatcher: %w", err) - } - defer dispatcher.Close() //nolint:errcheck // our own descriptors - lock, err := dispatcher.Lock(ctx) - if err != nil { - return err - } - defer lock.Unlock() - return lock.Clear(xdpdispatch.SlotNAT) -} diff --git a/cmd/galactic-nat/root.go b/cmd/galactic-nat/root.go index 94a60f80d..8abaa2af2 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -8,6 +8,7 @@ import ( "context" "errors" "fmt" + "log/slog" "net" "strings" @@ -224,6 +225,10 @@ func newRootCommand() *cobra.Command { if err := cfg.Validate(); err != nil { return err } + if cfg.XDPAttachDeprecated { + slog.Warn("GALACTIC_NAT_XDP_ATTACH=chain is retired and runs as dispatch; set it to dispatch", + "env", config.EnvNATXDPAttach) + } return runCmd(cfg) }, } @@ -240,8 +245,7 @@ func newRootCommand() *cobra.Command { "overriding auto-detection; name every fabric uplink, not just the primary") cmd.Flags().StringP("nat-xdp-attach", "", config.NATXDPAttachDirect, "How the datapath reaches its uplinks' XDP hook: \"direct\" attaches it, \"dispatch\" runs it "+ - "from the node's shared, pinned XDP dispatcher, \"chain\" installs it behind the edge "+ - "gateway's programs on a node where the gateway holds the hook") + "from the node's shared, pinned XDP dispatcher (\"chain\" is read as dispatch)") cmd.Flags().Bool("nat-datapath-enabled", true, "Run the egress translation datapath; false keeps the process up but attaches nothing, "+ "clears the shard's identity and withdraws its advertisement") diff --git a/config/galactic-gateway/base/daemonset.yaml b/config/galactic-gateway/base/daemonset.yaml index 8c93d7d69..55c477c01 100644 --- a/config/galactic-gateway/base/daemonset.yaml +++ b/config/galactic-gateway/base/daemonset.yaml @@ -23,7 +23,8 @@ spec: # deploys it automatically -- see ../kustomization.yaml for why this # base is meant to be instantiated once per gateway node rather than # applied as-is. It is independent of galactic-nat: a node can carry - # either label or both (galactic-nat's chained overlay needs both). + # either label or both; on a node with both, each runs from its own + # slot of the node's shared XDP dispatcher. # # It never shares a node with galactic-vrf. That sidecar's pods are # placed on galactic.datumapis.com/node=edge nodes, and the affinity @@ -97,6 +98,14 @@ spec: # no compute tier behind it leaves it unset and attaches no # return program. # + # GALACTIC_GATEWAY_XDP_ATTACH is left at its default, + # "dispatch": the programs run from the node's shared, pinned + # XDP dispatcher, so a restart detaches nothing and the egress + # shard can share the uplinks. "direct" attaches them + # unpinned instead. GALACTIC_GATEWAY_DATAPATH_ENABLED, default + # "true", turns the datapath off and withdraws this node's VIPs + # without removing the pod. See internal/config/gateway.go. + # # GALACTIC_GATEWAY_PUBLIC_INTERFACE/_SRV6_ADDRESS are # intentionally left unset here: the interface name is # deployment-specific and the SRv6 address must be unique per diff --git a/config/galactic-nat/base/daemonset.yaml b/config/galactic-nat/base/daemonset.yaml index 31c6eeb30..7569049cc 100644 --- a/config/galactic-nat/base/daemonset.yaml +++ b/config/galactic-nat/base/daemonset.yaml @@ -21,11 +21,10 @@ spec: # Opt-in only: runs on a node an operator has explicitly labeled # galactic.datumapis.com/nat=enabled, and nowhere else. Nothing # deploys it automatically. It is independent of galactic-gateway: a - # node can carry either label or both. With no gateway on the node - # the shard attaches its own XDP program (the default, - # GALACTIC_NAT_XDP_ATTACH=direct); alongside a gateway, apply - # ../overlays/chained/ instead, which chains the shard behind the - # gateway's programs because an interface takes only one. + # node can carry either label or both. The shard attaches its own XDP + # program by default (GALACTIC_NAT_XDP_ATTACH=direct); alongside a + # gateway, set dispatch, so both run from the node's shared XDP + # dispatcher, since an interface takes only one program. # # It never shares a node with galactic-vrf. That sidecar's pods are # placed on galactic.datumapis.com/node=edge nodes, and the affinity @@ -105,10 +104,9 @@ spec: # GALACTIC_NAT_XDP_ATTACH is left at its default, "direct": the # shard attaches its own program to the uplinks. "dispatch" runs # it from the node's shared, pinned XDP dispatcher instead, so a - # restart bounces no uplink, and so the gateway can share the - # uplinks once it moves onto the dispatcher too. On a - # node where the gateway holds the hook directly, apply - # ../overlays/chained/ to set it to "chain". See + # restart bounces no uplink and the gateway can share the + # uplinks. A node that also runs the gateway needs it. The + # retired "chain" is read as "dispatch". See # internal/config/nat.go's EnvNATXDPAttach. # GALACTIC_NAT_DATAPATH_ENABLED, default "true", turns the shard # off without removing the pod; see EnvNATDatapathEnabled. diff --git a/config/galactic-nat/overlays/chained/daemonset-patch.yaml b/config/galactic-nat/overlays/chained/daemonset-patch.yaml deleted file mode 100644 index a8b8c7f96..000000000 --- a/config/galactic-nat/overlays/chained/daemonset-patch.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: apps/v1 -kind: DaemonSet -metadata: - name: galactic-nat -spec: - template: - spec: - containers: - - name: galactic-nat - env: - - name: GALACTIC_NAT_XDP_ATTACH - value: chain diff --git a/config/galactic-nat/overlays/chained/kustomization.yaml b/config/galactic-nat/overlays/chained/kustomization.yaml deleted file mode 100644 index 3ab9393c6..000000000 --- a/config/galactic-nat/overlays/chained/kustomization.yaml +++ /dev/null @@ -1,14 +0,0 @@ -# galactic-nat on a node that also runs galactic-gateway (labeled -# galactic.datumapis.com/gateway=enabled as well as .../nat=enabled). -# The gateway already holds the native XDP hook on every uplink, and an -# interface takes one native program, so the shard installs itself in the -# gateway's pinned xdp_chain slot instead of attaching. It waits for that -# map at startup, so the gateway must run on this node too. Like ../../base/, -# this is not applied as-is; see ../../kustomization.yaml. -resources: - - ../../base -patches: - - path: daemonset-patch.yaml - target: - kind: DaemonSet - name: galactic-nat diff --git a/config/monitoring/podmonitor-galactic-nat.yaml b/config/monitoring/podmonitor-galactic-nat.yaml index 61ce21562..9dec1adc6 100644 --- a/config/monitoring/podmonitor-galactic-nat.yaml +++ b/config/monitoring/podmonitor-galactic-nat.yaml @@ -1,8 +1,8 @@ # Scrapes each egress shard's galactic-nat metrics port (metrics, 9182), which # serves the session table, the NAT datapath's drop counters and the uplinks' # per-queue NIC receive counters. The pod uses hostNetwork, so its pod IP is -# the node's own. The chained overlay keeps the same pod labels, so this -# covers shards in either XDP attach mode. +# the node's own. The pod labels do not depend on the XDP attach mode, so +# this covers shards in either. apiVersion: monitoring.coreos.com/v1 kind: PodMonitor metadata: diff --git a/deploy/containerlab/README.md b/deploy/containerlab/README.md index 0392be8e8..48b609344 100644 --- a/deploy/containerlab/README.md +++ b/deploy/containerlab/README.md @@ -129,7 +129,7 @@ on either, only DaemonSets with a blanket toleration. Edge nodes run `galactic-c plain-mode `galactic-router` as their own independent DaemonSets, exactly like compute nodes, plus `galactic-nat`, the egress shard, which attaches its own XDP program to the node's uplinks (`GALACTIC_NAT_XDP_ATTACH=direct`, the default). No node in the lab runs -`galactic-gateway`, so nothing else holds those hooks and the shard never chains. +`galactic-gateway`, so nothing else holds those hooks and the shard needs no dispatcher. Compute nodes run no shard: each egresses through its own site's edge shards only. The reflector runs neither `galactic-cni` nor a shard — its `galactic=control` label is mutually exclusive with the `galactic=router` value that pulls diff --git a/deploy/containerlab/resources/galactic-nat/README.md b/deploy/containerlab/resources/galactic-nat/README.md index f0ce4b99b..27edf8956 100644 --- a/deploy/containerlab/resources/galactic-nat/README.md +++ b/deploy/containerlab/resources/galactic-nat/README.md @@ -45,9 +45,8 @@ Node-ID is service `0x2` over the edge node's own index, beside its router The lab base leaves `GALACTIC_NAT_XDP_ATTACH` at its default, `direct`: with no gateway on any node, nothing else holds the uplinks' native XDP hook, so the shard attaches its own program to every member of `bond0` -and `bond1`. The lab therefore no longer exercises -`config/galactic-nat/overlays/chained/`, the mode for a node that also -runs `galactic-gateway`; see +and `bond1`. A node that also runs `galactic-gateway` needs +`GALACTIC_NAT_XDP_ATTACH=dispatch` instead; see [docs/nat/configuration.md](../../../../docs/nat/configuration.md) for both modes. diff --git a/docs/README.md b/docs/README.md index 7fb0bbfe3..24e78d8bb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -36,7 +36,7 @@ data flow, module reference, known constraints): deployment (node labeling, RBAC, per-node overlay), its config reference, and the `NetworkGateway`/`NetworkRule`/`ServiceVIPBinding` CRD fields. - [nat/configuration.md](nat/configuration.md) — `galactic-nat` placement - (edge nodes, chained behind the gateway's XDP programs), config + (edge nodes, sharing the uplinks' XDP hook with the gateway), config reference, the `EgressShard` CRD, and the `galactic-cni`-side shard membership settings that point tenant nodes at it. - [cni/README.md](cni/README.md) — entry point for the `galactic-cni` docs diff --git a/docs/agents/ARCHITECTURE-GATEWAY.md b/docs/agents/ARCHITECTURE-GATEWAY.md index 2625ba449..265dee2c5 100644 --- a/docs/agents/ARCHITECTURE-GATEWAY.md +++ b/docs/agents/ARCHITECTURE-GATEWAY.md @@ -24,10 +24,10 @@ VPC-attached workloads reaching the internet — see `cmd/galactic-nat`, (`internal/controller/egressshard_controller.go`, which registers with `galactic-nat`'s own manager (`cmd/galactic-nat/root.go`) — a separate binary from both this one and `galactic-router`) rather than this file for -egress. It runs on the same edge nodes as this binary, chained behind its -XDP programs through `xdp_chain` — see -[Chaining the egress shard](#chaining-the-egress-shard-xdp_chain) below for -the part of that contract this binary owns. This file, +egress. It can run on the same edge nodes as this binary, each from its own +slot of the node's shared XDP dispatcher; see +[Sharing the XDP hook](#sharing-the-xdp-hook-xdpdispatch) below for the part +of that contract this binary owns. This file, together with the other two architecture docs, supersedes the former monolithic `ARCHITECTURE.md` — see [AGENTS.md](../../AGENTS.md) for which document to start from for a given task. @@ -266,9 +266,10 @@ attach point — see below. 1. **Parse** the outer Ethernet + IPv6 header, then the L4 header (TCP or UDP only). Not IPv6, unparseable, or not TCP/UDP — unclaimed: handed to - the program in `xdp_chain`'s slot if one is installed (see - [below](#chaining-the-egress-shard-xdp_chain)), otherwise `XDP_PASS` to - the kernel stack, e.g. BGP/SSH to the node itself. Only the + the dispatcher's later slots, in practice the egress shard's, if the + interface carries their role (see + [below](#sharing-the-xdp-hook-xdpdispatch)), otherwise `XDP_PASS` to the + kernel stack, e.g. BGP/SSH to the node itself. Only the source/destination port are ever read; nothing is rewritten, so there is no pointer-to-field resolution the way a rewrite would need. 2. **Match** `(proto, dst port, dst addr)` against `vip_table` (keyed @@ -323,39 +324,47 @@ length-validating intermediate hop or receiver to reject every packet this datapath ever pushed — found via live-kernel investigation, not `BPF_PROG_TEST_RUN`, and covered by regression tests in `edgedsr_test.go`. -### Chaining the egress shard (`xdp_chain`) +### Sharing the XDP hook (`xdpdispatch`) An interface takes one native XDP program, and `galactic-nat`'s egress shard -runs on the same edge nodes and needs the same interfaces: tenant egress +can run on the same edge nodes, needing the same interfaces: tenant egress arrives on the compute-facing bond (`edge_return`'s) and its replies on the -public uplink (`edge_lb`'s). Rather than attach, the shard runs as a tail -call from this datapath. - -- `edgedsr.c` declares `xdp_chain`, a one-slot `BPF_MAP_TYPE_PROG_ARRAY`. - Every unclaimed exit in both `edge_lb` and `edge_return` — - including the non-IPv6 early returns, which is how NAT64's IPv4 replies - reach the shard — goes through `pass_unclaimed`: - `bpf_tail_call(ctx, &xdp_chain, 0)`, then `XDP_PASS` if the slot is - empty. A claimed packet never reaches the slot. -- This binary owns and pins the map: `edgeattach.Load` pins every map by - name, so it lives at `/sys/fs/bpf/galactic-edge/xdp_chain` and survives a - gateway restart with its slot intact. An incompatible pin is recreated - like any other map here, which empties the slot; the shard notices and - re-installs itself. -- `galactic-nat` fills the slot from its own process - (`GALACTIC_NAT_XDP_ATTACH=chain`, `natattach.AttachChain`), waiting for - the map at startup and re-checking it every 10s. The path is spelled out - in `natattach.EdgeChainMapPath` rather than imported; - `edgeattach`'s `TestChainMapPathMatchesTheShardsCopy` holds the two in - step. -- The two datapaths claim disjoint traffic — a VIP destination or source - here, a shard SID or masquerade-address destination there — so running - the shard second changes no verdict. +public uplink (`edge_lb`'s). Neither binary owns the hook. The node's shared +XDP dispatcher (`internal/plumbing/ebpf/xdpdispatch`) holds it, and each +datapath runs from its own slot. + +- `GALACTIC_GATEWAY_XDP_ATTACH=dispatch`, the default, opens the dispatcher, + loads `edgedsr.c` against its maps (`edgeattach.Load` with + `CollectionOptions.MapReplacements`), fills slot 0 with `edge_lb` and slot + 1 with `edge_return`, and renews both slots' leases. `xdpattach.DispatchSet` + puts the dispatcher on the public targets with the public role and on the + internal targets with the return role. The links are pinned under + `/sys/fs/bpf/galactic-xdp`, so a gateway restart swaps its programs into + the slots without detaching anything. +- Every unclaimed exit in `edge_lb` and `edge_return`, including the + non-IPv6 early returns that carry NAT64's IPv4 replies, goes through + `dispatch_next` (`dispatch.h`), which tail-calls the later slots the + interface's roles allow. A claimed packet never reaches them. +- The return slot never runs on an interface that also carries the public + role: the dispatcher's root and `SetRole` both refuse it, and + `setupGatewayDatapath` refuses an internal interface that resolves to a + public one at startup. +- `GALACTIC_GATEWAY_XDP_ATTACH=direct` attaches the programs themselves, + unpinned. It first detaches an idle dispatcher from the targets and + refuses to start while another datapath's slot is live there. + Attached directly, the programs hold their own empty copies of the + dispatcher maps, so every unclaimed packet passes to the kernel. +- `GALACTIC_GATEWAY_DATAPATH_ENABLED=false` loads nothing, empties the + gateway's slots, and makes `NetworkGatewayReconciler` withdraw this + node's VIP advertisements and report `DatapathDisabled`. +- The two datapaths claim disjoint traffic, a VIP destination or source here + and a shard SID or masquerade-address destination there, so the slot + order changes no verdict. - The kernel ties a program array to its first user's program type, JIT state, frags support and expected attach type, and rejects any other - program with a bare `EINVAL`. `edge_lb`/`edge_return` and the shard's - `nat_ingress` are all ELF `SEC("xdp")` programs (`AttachXDP`), so they - match; a hand-built program needs `AttachType: ebpf.AttachXDP` to be + program with a bare `EINVAL`. The root, `edge_lb`/`edge_return` and the + shard's `nat_ingress` are all ELF `SEC("xdp")` programs (`AttachXDP`), so + they match; a hand-built program needs `AttachType: ebpf.AttachXDP` to be accepted (see `edgedsr_chain_test.go`). ### Return path (`edgedsr.c`, program `edge_return`) @@ -778,20 +787,20 @@ single-container and references no `galactic-router` image at all — see **Where to start for each concern:** -| Concern | Start here | -| --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| Node-scoped aggregate reconcile (desired-state assembly, BGP wiring, crash recovery) | `internal/controller/networkgateway_controller.go:Reconcile` | -| Per-object lifecycle (finalizer teardown ordering, `Accepted`-condition maintenance) | `internal/controller/networkrule_controller.go:Reconcile`, `updateAcceptedCondition`, `reconcileDelete` | -| Backend address → SRv6 uSID resolution (with tenant-ownership verification) | `internal/controller/usidresolver.go:buildBackendSIDIndex`, `resolveUSID`, `verifyTenantOwnership` | -| Engine convergence loop | `internal/gateway/engine.go:Reconcile`, `applyRuleLocked`, `removeRuleLocked` | -| Real datapath implementation (vip_table read/write, Maglev table construction) | `internal/gateway/kerneldatapath.go:ApplyRule`, `RemoveRule`, `buildMaglevTable` | -| Maglev consistent-hash ring | `internal/maglev/table.go:New`, `Lookup`, `Backends` | -| Crash recovery (orphaned vip_table state) | `internal/gateway/recovery.go`, `internal/plumbing/ebpf/edgemap/viptable.go`'s `Generation`/`Reconcile` | -| Quota enforcement | `internal/gateway/quota.go:NodeQuotaEnforcer.CheckAndReserve` | -| XDP packet path | `internal/plumbing/ebpf/edgeprog/edgedsr.c` (start with its own header comment) | -| Datapath load/attach lifecycle | `internal/plumbing/ebpf/edgeattach/attach.go`, `cmd/galactic-gateway/gateway.go:setupGatewayDatapath` | -| Egress shard chained behind this datapath | `edgedsr.c`'s `xdp_chain`/`pass_unclaimed`, `internal/plumbing/ebpf/natattach/chain.go` | -| Startup sequencing / gRPC health ordering | `cmd/galactic-gateway/root.go:runCmd` | +| Concern | Start here | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | +| Node-scoped aggregate reconcile (desired-state assembly, BGP wiring, crash recovery) | `internal/controller/networkgateway_controller.go:Reconcile` | +| Per-object lifecycle (finalizer teardown ordering, `Accepted`-condition maintenance) | `internal/controller/networkrule_controller.go:Reconcile`, `updateAcceptedCondition`, `reconcileDelete` | +| Backend address → SRv6 uSID resolution (with tenant-ownership verification) | `internal/controller/usidresolver.go:buildBackendSIDIndex`, `resolveUSID`, `verifyTenantOwnership` | +| Engine convergence loop | `internal/gateway/engine.go:Reconcile`, `applyRuleLocked`, `removeRuleLocked` | +| Real datapath implementation (vip_table read/write, Maglev table construction) | `internal/gateway/kerneldatapath.go:ApplyRule`, `RemoveRule`, `buildMaglevTable` | +| Maglev consistent-hash ring | `internal/maglev/table.go:New`, `Lookup`, `Backends` | +| Crash recovery (orphaned vip_table state) | `internal/gateway/recovery.go`, `internal/plumbing/ebpf/edgemap/viptable.go`'s `Generation`/`Reconcile` | +| Quota enforcement | `internal/gateway/quota.go:NodeQuotaEnforcer.CheckAndReserve` | +| XDP packet path | `internal/plumbing/ebpf/edgeprog/edgedsr.c` (start with its own header comment) | +| Datapath load/attach lifecycle | `internal/plumbing/ebpf/edgeattach/attach.go`, `cmd/galactic-gateway/gateway.go:setupGatewayDatapath` | +| Sharing the XDP hook with the egress shard | `edgedsr.c`'s `pass_unclaimed_*`, `internal/plumbing/ebpf/xdpdispatch`, `xdpattach/dispatchset.go` | +| Startup sequencing / gRPC health ordering | `cmd/galactic-gateway/root.go:runCmd` | **Stable vs. frequently changed:** - Stable: `internal/maglev/table.go` (a settled, well-tested algorithm — Google's published Maglev construction), `internal/plumbing/ebpf/edgemap` (mirrors `usidmap`'s already-settled crash-safety pattern) diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 0748154c9..f7abf27d7 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -43,11 +43,9 @@ runs there too, as its own independent DaemonSet (the same one that runs on `compute` nodes), not co-located in the same pod. `galactic-nat` runs on those same `edge` nodes: its own single-container DaemonSet running unconditionally on every edge node, alongside — again not co-located with — both of them. -It shares the node's XDP hook with `galactic-gateway` by running chained -behind the gateway's programs (`GALACTIC_NAT_XDP_ATTACH=chain`, through -the gateway's pinned `xdp_chain` program array), or from the node's -shared, pinned XDP dispatcher (`GALACTIC_NAT_XDP_ATTACH=dispatch`), and -each site's compute nodes send their egress to that site's edge shards +It shares the node's XDP hook with `galactic-gateway`, each running from +its own slot of the node's shared, pinned XDP dispatcher +(`GALACTIC_NAT_XDP_ATTACH=dispatch`), and each site's compute nodes send their egress to that site's edge shards over SRv6. It used to run on compute nodes instead. The diagram shows each pairing co-located on the node but connected by no direct RPC — a crash in one does not take down the other; both `galactic-gateway` and `galactic-nat` diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index b0d202535..9d7fdceaf 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -30,10 +30,11 @@ so a crash on either side no longer takes the other's *pod* down with it, not just the other's binary. You need `galactic-gateway` only on nodes that terminate external ingress traffic for tenant VPCs — every other node in the fleet (`galactic-router` default role, `galactic-cni`) has no dependency on -it. `galactic-nat` is the exception: it runs on the same edge nodes, chained -behind this binary's XDP programs through the pinned `xdp_chain` program -array (`GALACTIC_NAT_XDP_ATTACH=chain`), and waits for that map at startup — -see [docs/nat/configuration.md](../nat/configuration.md). See +it. `galactic-nat` is the exception: it can run on the same edge nodes, and +the two share each uplink's XDP hook through the node's shared dispatcher, +each from its own slot (`GALACTIC_GATEWAY_XDP_ATTACH=dispatch` here, +`GALACTIC_NAT_XDP_ATTACH=dispatch` there). See +[docs/nat/configuration.md](../nat/configuration.md). See [ARCHITECTURE-GATEWAY.md](../agents/ARCHITECTURE-GATEWAY.md) for the full design (DSR vs. the removed Full-NAT design, the anycast BGP model, the XDP packet path) and @@ -152,14 +153,32 @@ flags, or a combination of both (CLI flags take precedence), with the `GALACTIC_GATEWAY` env prefix — the same three-tier precedence pattern `galactic-router` uses (see [docs/router/configuration.md](../router/configuration.md)). -| Option | Environment Variable | CLI Flag | Default | Required | -| ------------------- | -------------------------------------- | ------------------------------- | ------- | -------- | -| Node name | `GALACTIC_GATEWAY_NODE_NAME` | `--node-name`, `-n` | — | Yes | -| Public interface | `GALACTIC_GATEWAY_PUBLIC_INTERFACE` | `--gateway-public-interface` | — | Yes | -| SRv6 address | `GALACTIC_GATEWAY_SRV6_ADDRESS` | `--gateway-srv6-address` | — | Yes | -| Internal interfaces | `GALACTIC_GATEWAY_INTERNAL_INTERFACES` | `--gateway-internal-interfaces` | — | No | -| Metrics port | `GALACTIC_GATEWAY_METRICS_PORT` | `--metrics-port` | `8081` | No | -| gRPC health port | `GALACTIC_GATEWAY_GRPC_HEALTH_PORT` | `--grpc-health-port` | `5181` | No | +| Option | Environment Variable | CLI Flag | Default | Required | +| ------------------- | -------------------------------------- | ------------------------------- | ---------- | ----------------- | +| Node name | `GALACTIC_GATEWAY_NODE_NAME` | `--node-name`, `-n` | — | Yes | +| Public interface | `GALACTIC_GATEWAY_PUBLIC_INTERFACE` | `--gateway-public-interface` | — | While enabled | +| SRv6 address | `GALACTIC_GATEWAY_SRV6_ADDRESS` | `--gateway-srv6-address` | — | While enabled | +| Internal interfaces | `GALACTIC_GATEWAY_INTERNAL_INTERFACES` | `--gateway-internal-interfaces` | — | No | +| XDP attach mode | `GALACTIC_GATEWAY_XDP_ATTACH` | `--gateway-xdp-attach` | `dispatch` | No | +| Datapath enabled | `GALACTIC_GATEWAY_DATAPATH_ENABLED` | `--gateway-datapath-enabled` | `true` | No | +| Metrics port | `GALACTIC_GATEWAY_METRICS_PORT` | `--metrics-port` | `8081` | No | +| gRPC health port | `GALACTIC_GATEWAY_GRPC_HEALTH_PORT` | `--grpc-health-port` | `5181` | No | + +`GALACTIC_GATEWAY_XDP_ATTACH` is `dispatch` or `direct`. `dispatch` runs +`edge_lb` and `edge_return` from the gateway slots of the node's shared, +pinned XDP dispatcher, so a restart swaps the programs in place without +detaching anything, and the egress shard can share the uplinks. `direct` +attaches the programs themselves, unpinned, so they detach when the process +exits. It first detaches an idle dispatcher from its interfaces, and refuses +to start while another datapath's slot is live there. See +[Sharing the XDP hook](../agents/ARCHITECTURE-GATEWAY.md#sharing-the-xdp-hook-xdpdispatch). + +`GALACTIC_GATEWAY_DATAPATH_ENABLED=false` keeps the process up and its pod +ready but loads nothing, empties the gateway's dispatcher slots, and +withdraws every one of this node's VIP advertisements. The NetworkGateway's +`Ready` reads `False` with reason `DatapathDisabled`. The public interface +and SRv6 address are not required while it is off. + `GALACTIC_GATEWAY_INTERNAL_INTERFACES` is a comma-separated list of this node's compute-facing interfaces, and it is what puts the return path in @@ -371,7 +390,7 @@ spec: name: dfw-worker2 ``` -`spec.targetRef.name` must equal the Kubernetes node name — by this repo's +| `spec.targetRef.name` must equal the Kubernetes node name — by this repo's | own convention every `NetworkGateway` fixture and overlay names the object after the node it targets. `NetworkGatewayReconciler` matches this against `--node-name`/`GALACTIC_GATEWAY_NODE_NAME` to decide whether it owns this @@ -387,7 +406,7 @@ object. | Field | Required | Type | Description | | --------------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `spec.targetRef.name` | Yes | `string` | Kubernetes node name this gateway engine executes on. | -| `status.conditions` | — | — | `Ready` condition, reason `EngineHealthy` (converged and fully advertised), `AdvertisementFailed` (converged but couldn't publish one or more rule routes), or `Terminating`. | +| `status.conditions` | — | — | `Ready` condition, reason `EngineHealthy` (converged and fully advertised), `AdvertisementFailed` (converged but couldn't publish one or more rule routes), `DatapathDisabled`, or `Terminating`. | There is deliberately **no** self-address or primary-node field on this status — DSR has nothing analogous to publish. Create one object per diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index e01d8f460..3a591e38e 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -50,9 +50,8 @@ flags, or a combination of both (CLI flags take precedence), with the `config/galactic-nat/base/daemonset.yaml` leaves `GALACTIC_NAT_XDP_ATTACH` at the binary's default, `direct`. `dispatch` is the mode to move to: it is -what lets a shard restart without bouncing its uplinks, and what will let it -share them with `galactic-gateway` once the gateway moves onto the dispatcher -too. +what lets a shard restart without bouncing its uplinks, and what lets it share +them with `galactic-gateway`, which runs from the same dispatcher by default. That is the whole process configuration. The shard's identity — its SID, masquerade addresses and NAT64 prefix — is not process configuration: it @@ -124,14 +123,18 @@ condition reads `False` with reason `UplinksMissing`, naming them, and the pod's `readiness` gRPC health service, which the readinessProbe checks, reports not serving. Liveness is unaffected, so the pod is not restarted. -In dispatch and chain mode the shard attaches nothing of its own, so the -uplinks are used for the forwarding sysctls and to check coverage. An uplink +In dispatch mode the shard attaches nothing of its own, so the uplinks are +used for the forwarding sysctls and to check coverage. An uplink whose traffic does not reach the shard's program is reported missing the same way. **`--nat-xdp-attach` / `GALACTIC_NAT_XDP_ATTACH`** -How the datapath reaches its uplinks' XDP hook: `direct`, `dispatch` or -`chain`. Any other value fails validation at startup. +How the datapath reaches its uplinks' XDP hook: `direct` or `dispatch`. The +retired `chain` is read as `dispatch`, with a warning. Any other value fails +validation at startup. A node that ran `chain` upgrades the gateway and the +shard together: a shard on this release cannot share an uplink with a gateway +that still holds the hook directly, and reports those uplinks missing until +the gateway joins the dispatcher. - **`direct`** (the binary's default) attaches `nat_ingress` to every resolved uplink in native driver mode, as described above. The attachment @@ -148,9 +151,8 @@ How the datapath reaches its uplinks' XDP hook: `direct`, `dispatch` or uplink and runs `nat_ingress` from the dispatcher's egress slot. The dispatcher is one small root program, `xdp_dispatch`, that holds the hook for every datapath on the node and hands each packet to the slots its - interface's roles allow. Slots are reserved for the gateway's load balancer - and return program, ahead of the shard's, though the gateway does not use - the dispatcher yet. Its state is pinned under `/sys/fs/bpf/galactic-xdp`: the + interface's roles allow: the gateway's load balancer and return program, + then the shard. Its state is pinned under `/sys/fs/bpf/galactic-xdp`: the maps and root under `v1/`, one link per interface under `links/`. Because the links are pinned, the root stays attached when the shard's @@ -173,29 +175,6 @@ How the datapath reaches its uplinks' XDP hook: `direct`, `dispatch` or `hack/xdp-dispatch-release.sh` detaches it. Run it before rolling back to an image that predates dispatch mode, which would otherwise fail to attach with `EBUSY`. -- **`chain`** attaches nothing. An interface takes one native XDP program, - and on an edge node `galactic-gateway` already holds that hook on the - interfaces the shard needs (a direct attach there fails outright). The - gateway pins a one-slot program array, `xdp_chain`, at - `/sys/fs/bpf/galactic-edge/xdp_chain`, and both of its programs - (`edge_lb`, `edge_return`) tail-call into it with every packet they do not - claim — non-IPv6 frames included, so NAT64 replies reach the shard. The - shard installs `nat_ingress` in that slot (`natattach.AttachChain`). The - two datapaths claim disjoint traffic — a VIP destination or source for the - gateway, a shard SID or masquerade address for the shard — so the order - they run in changes no verdict. - - At startup the shard waits for the map, retrying every 2s while it does - not exist (the startup probe bounds the wait), and reports healthy once its - program is in the slot. Any other install failure is fatal: the kernel - refuses a program whose type, JIT state, frags support or expected attach - type differ from the array owner's, with a bare `EINVAL`. After that it - re-checks the slot every 10s and re-installs its program if the slot no - longer holds it — a gateway restart normally reuses its pinned map, but one - that had to recreate the map empties the slot. The slot keeps the program - alive across a `galactic-nat` restart, and the next process replaces it in - place, so a shard restart leaves no gap in translation. - **`--nat-datapath-enabled` / `GALACTIC_NAT_DATAPATH_ENABLED`** Whether the shard runs its datapath. On by default. Off, the process stays up and its pod ready, but it attaches nothing, empties its dispatcher slot if @@ -233,9 +212,8 @@ It also needs a real bpffs already mounted at `/sys/fs/bpf` on the host (`type: Directory`, not `DirectoryOrCreate` — a missing mount must fail loudly, not silently pin maps to a plain directory). Every map is pinned under `/sys/fs/bpf/galactic-nat`. In dispatch mode it also pins the node's -XDP dispatcher under `/sys/fs/bpf/galactic-xdp`, and in chain mode it opens -the gateway's `/sys/fs/bpf/galactic-edge/xdp_chain`. The same `/sys/fs/bpf` -mount covers both. +XDP dispatcher under `/sys/fs/bpf/galactic-xdp`, which the same `/sys/fs/bpf` +mount covers. ## `EgressShard` CRD (`network.datumapis.com/v1alpha1`) @@ -571,7 +549,7 @@ kubectl exec -n galactic-system -- \ ``` Confirm the eBPF program is attached (in dispatch mode, in the dispatcher's -egress slot; in chain mode, in the gateway's `xdp_chain` slot) and +egress slot) and translating. On the `EgressShard` object, `Ready` should read `DatapathAttached` and `Programmed` should read `AddressesProgrammed`. `Ready` reading `UplinksMissing` names the uplinks whose traffic the shard is not translating: @@ -646,11 +624,6 @@ knowing before you rely on this component in production: allocates `spec.shardSID` or the masquerade addresses, and nothing checks that a chosen SID's Node-ID doesn't collide with a real node's own — see the "Node-ID collision hazard" callout above. -- **A chained shard depends on the gateway on its node.** In chain mode - the shard sees only what `galactic-gateway`'s programs see, on exactly the - interfaces the gateway attaches to, and waits at startup for a map only - the gateway creates. With the gateway gone, the slot keeps the shard's - program alive but nothing calls it. - **One NIC receive queue on a `bnxt_en` uplink can stall.** The queue drops a steady share of its packets while the CPU sits idle, and every flow hashed to it fails on each retry: tenant egress times out per flow, @@ -683,7 +656,7 @@ knowing before you rely on this component in production: `GALACTIC_ROUTER_*` environment variables a NAT66 shard node's co-located `galactic-router` process also needs. - [docs/agents/ARCHITECTURE-GATEWAY.md](../agents/ARCHITECTURE-GATEWAY.md) — - the edge XDP programs the shard is chained behind. + the edge XDP programs that share the dispatcher with the shard. - [docs/cni/configuration.md](../cni/configuration.md) — the full `galactic-cni` conflist/runtime configuration surface `GALACTIC_CNI_EGRESS_SHARD_SIDS` is one part of. diff --git a/docs/node-labels.md b/docs/node-labels.md index cac3536cd..b80b3a3b2 100644 --- a/docs/node-labels.md +++ b/docs/node-labels.md @@ -100,8 +100,8 @@ bug, not a hypothetical: 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 — every edge node now runs - `galactic-nat` unconditionally, chained behind `galactic-gateway`'s XDP - programs. + `galactic-nat` unconditionally, 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` @@ -178,15 +178,13 @@ Runs `galactic-nat`, the egress shard independent of `gateway`. The node must carry no `galactic.datumapis.com/node` label. -A node with no gateway uses 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 apply -`config/galactic-nat/overlays/chained/` instead. The gateway already holds the -node's native XDP hook, an interface takes one program, and the shard installs -itself in the gateway's pinned `xdp_chain` array, so the gateway has to be -running on that node too. `GALACTIC_NAT_XDP_ATTACH=dispatch` runs the shard -from the node's shared, pinned XDP dispatcher instead, which survives a shard -restart without bouncing an uplink (see +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`). @@ -271,8 +269,8 @@ that matches its affinity. Order matters, or a restart leaves no pod at all: 2. Apply the new manifests. Running pods stay put. 3. On each of those nodes, remove `galactic.datumapis.com/node=edge`, then restart its `galactic-gateway` / `galactic-nat` pods. -4. On a node running both, use `config/galactic-nat/overlays/chained/` for - the shard, or it will try to attach over the gateway's XDP program. +4. On a node running both, set `GALACTIC_NAT_XDP_ATTACH=dispatch` for the + shard, or it will refuse to attach over the gateway's dispatcher. Skipping step 1 and removing `node=edge` first leaves the DaemonSets with no matching node the next time the pod restarts, which blackholes ingress or diff --git a/internal/config/gateway.go b/internal/config/gateway.go index 985fca924..657b8d9b2 100644 --- a/internal/config/gateway.go +++ b/internal/config/gateway.go @@ -55,6 +55,32 @@ const ( // never a translation source and is never compared against anything on a // receive path. Required. EnvGatewaySRv6Address = "GALACTIC_GATEWAY_SRV6_ADDRESS" + + // EnvGatewayXDPAttach selects how the datapath reaches its interfaces' XDP + // hook: GatewayXDPAttachDispatch, the default, or GatewayXDPAttachDirect. + // + // Dispatch runs edge_lb and edge_return from the gateway slots of the + // node's shared XDP dispatcher (xdpdispatch), whose attachments are pinned: + // a restart swaps the programs in place without detaching anything, and the + // egress shard can share the same uplinks. Direct attaches the programs + // themselves, unpinned, so they detach when the process exits; it releases + // an idle dispatcher first and refuses to start while another datapath's + // slot is live, since taking the hook would cut that datapath's traffic. + EnvGatewayXDPAttach = "GALACTIC_GATEWAY_XDP_ATTACH" + + // EnvGatewayDatapathEnabled turns the gateway's datapath on or off. + // Optional, defaulting to true. Off, the process stays up and healthy but + // attaches nothing, empties its dispatcher slots, and withdraws this + // node's VIP advertisements, so no traffic is drawn to a node that will not + // load-balance it. Every other datapath on the node keeps running. The + // public interface and SRv6 address are not required while it is off. + EnvGatewayDatapathEnabled = "GALACTIC_GATEWAY_DATAPATH_ENABLED" +) + +// EnvGatewayXDPAttach's values. +const ( + GatewayXDPAttachDispatch = "dispatch" + GatewayXDPAttachDirect = "direct" ) // --- GatewayConfig ----------------------------------------------------- @@ -81,6 +107,12 @@ type GatewayConfig struct { // the comma-separated environment value. Empty is valid and means this node // carries no return traffic -- see EnvGatewayInternalInterfaces. InternalInterfaces []string + + // XDPAttach is one of the GatewayXDPAttach values, from EnvGatewayXDPAttach. + XDPAttach string + + // DatapathEnabled is EnvGatewayDatapathEnabled. + DatapathEnabled bool } // NewGatewayConfig creates a config resolver reading the GALACTIC_GATEWAY @@ -96,6 +128,8 @@ func NewGatewayConfig() *GatewayConfig { v.SetDefault(KeyGRPCHealthPort, DefaultGatewayGRPCHealthPort) v.SetDefault("public_interface", "") v.SetDefault("srv6_address", "") + v.SetDefault("xdp_attach", GatewayXDPAttachDispatch) + v.SetDefault("datapath_enabled", true) cfg := &GatewayConfig{ v: v, @@ -118,13 +152,15 @@ func (c *GatewayConfig) BindFlags(flags *pflag.FlagSet) { {"gateway-public-interface", "public_interface"}, {"gateway-internal-interfaces", "internal_interfaces"}, {"gateway-srv6-address", "srv6_address"}, + {"gateway-xdp-attach", "xdp_attach"}, + {"gateway-datapath-enabled", "datapath_enabled"}, } for _, b := range bindings { if flags.Changed(b.flag) { c.v.Set(b.key, flags.Lookup(b.flag).Value.String()) - } else { + } else if f := flags.Lookup(b.flag); f != nil { //nolint:errcheck // controlled keys, BindPFlag cannot fail here - c.v.BindPFlag(b.key, flags.Lookup(b.flag)) + c.v.BindPFlag(b.key, f) } } c.readFields() @@ -138,6 +174,8 @@ func (c *GatewayConfig) readFields() { c.PublicInterface = c.v.GetString("public_interface") c.InternalInterfaces = splitCommaList(c.v.GetString("internal_interfaces")) c.SRv6Address = c.v.GetString("srv6_address") + c.XDPAttach = c.v.GetString("xdp_attach") + c.DatapathEnabled = c.v.GetBool("datapath_enabled") } // splitCommaList parses a comma-separated list, such as interface names or BMP @@ -158,6 +196,21 @@ func (c *GatewayConfig) Validate() error { if c.NodeName == "" { return fmt.Errorf("node name is required (use --node-name flag or %s env var)", EnvGatewayNodeName) } + switch c.XDPAttach { + case GatewayXDPAttachDispatch, GatewayXDPAttachDirect: + default: + return fmt.Errorf("%s must be %q or %q, got %q", EnvGatewayXDPAttach, + GatewayXDPAttachDispatch, GatewayXDPAttachDirect, c.XDPAttach) + } + if c.MetricsPort < 1 || c.MetricsPort > 65535 { + return errors.New(errMetricsPortRange) + } + if c.GRPCHealthPort < 1 || c.GRPCHealthPort > 65535 { + return errors.New("grpc health port must be between 1 and 65535") + } + if !c.DatapathEnabled { + return nil + } if c.PublicInterface == "" { return fmt.Errorf( "public interface is required (use --gateway-public-interface flag or %s env var)", @@ -177,11 +230,5 @@ func (c *GatewayConfig) Validate() error { if !addr.Is6() || addr.Is4In6() { return fmt.Errorf("SRv6 address %q must be a native IPv6 address, not IPv4", c.SRv6Address) } - if c.MetricsPort < 1 || c.MetricsPort > 65535 { - return errors.New(errMetricsPortRange) - } - if c.GRPCHealthPort < 1 || c.GRPCHealthPort > 65535 { - return errors.New("grpc health port must be between 1 and 65535") - } return nil } diff --git a/internal/config/gateway_test.go b/internal/config/gateway_test.go index ff7b78fc4..7b1270c09 100644 --- a/internal/config/gateway_test.go +++ b/internal/config/gateway_test.go @@ -156,3 +156,54 @@ func TestGatewayConfigValidate(t *testing.T) { }) } } + +// TestGatewayConfigXDPAttach covers the attach mode: dispatch unless set, +// direct when asked for, and anything else refused at startup. +func TestGatewayConfigXDPAttach(t *testing.T) { + tests := []struct { + value string + want string + wantErr bool + }{ + {want: GatewayXDPAttachDispatch}, + {value: GatewayXDPAttachDirect, want: GatewayXDPAttachDirect}, + {value: "chain", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.value, func(t *testing.T) { + t.Setenv(EnvGatewayNodeName, testEnvNode) + t.Setenv(EnvGatewayPublicInterface, testGatewayIface) + t.Setenv(EnvGatewaySRv6Address, testGatewaySRv6) + if tt.value != "" { + t.Setenv(EnvGatewayXDPAttach, tt.value) + } + cfg := NewGatewayConfig() + err := cfg.Validate() + if (err != nil) != tt.wantErr { + t.Fatalf("Validate() = %v, wantErr %v", err, tt.wantErr) + } + if !tt.wantErr && cfg.XDPAttach != tt.want { + t.Errorf("XDPAttach = %q, want %q", cfg.XDPAttach, tt.want) + } + }) + } +} + +// TestGatewayConfigDisabledNeedsNoInterface: a node with its datapath off has +// nothing to attach, so it starts without a public interface or SRv6 address. +func TestGatewayConfigDisabledNeedsNoInterface(t *testing.T) { + t.Setenv(EnvGatewayNodeName, testEnvNode) + t.Setenv(EnvGatewayDatapathEnabled, "false") + cfg := NewGatewayConfig() + if cfg.DatapathEnabled { + t.Fatal("DatapathEnabled = true with the env set to false") + } + if err := cfg.Validate(); err != nil { + t.Errorf("Validate() = %v for a disabled datapath with no interface", err) + } + + t.Setenv(EnvGatewayDatapathEnabled, "true") + if err := NewGatewayConfig().Validate(); err == nil { + t.Error("Validate() = nil for an enabled datapath with no public interface") + } +} diff --git a/internal/config/nat.go b/internal/config/nat.go index b05c95ffa..8f3eaed40 100644 --- a/internal/config/nat.go +++ b/internal/config/nat.go @@ -54,17 +54,18 @@ const ( EnvNATUplinkInterfaces = "GALACTIC_NAT_UPLINK_INTERFACES" // EnvNATXDPAttach selects how the datapath reaches its uplinks' XDP hook: - // NATXDPAttachDirect, NATXDPAttachDispatch or NATXDPAttachChain. Optional, - // defaulting to direct. + // NATXDPAttachDirect or NATXDPAttachDispatch. Optional, defaulting to + // direct. NATXDPAttachChain is still accepted and runs as dispatch. // // An interface takes one native XDP program. Direct attaches the shard's // own program, unpinned, so it detaches when the process exits and every // restart bounces each uplink. Dispatch puts the node's shared XDP // dispatcher (xdpdispatch) on the uplinks instead and runs the shard from // its slot: the attachment is pinned, so a restart swaps the program in - // place, and the edge gateway can share the same uplinks. Chain installs - // the shard in the gateway's xdp_chain slot, on a node where the gateway - // holds the hook directly; it is superseded by dispatch. + // place, and the edge gateway can share the same uplinks. Chain, which + // installed the shard in the gateway's own xdp_chain map, is gone: the + // gateway now runs from the same dispatcher, so the value is read as + // dispatch. // // Switching a node back from dispatch to direct is safe while nothing else // uses the dispatcher there: direct mode detaches an idle dispatcher before @@ -91,7 +92,8 @@ const ( EnvNATEchoResponder = "GALACTIC_NAT_ECHO_RESPONDER" ) -// EnvNATXDPAttach's values. +// EnvNATXDPAttach's values. NATXDPAttachChain is deprecated and read as +// NATXDPAttachDispatch. const ( NATXDPAttachDirect = "direct" NATXDPAttachDispatch = "dispatch" @@ -117,9 +119,14 @@ type NATConfig struct { // comma-separated EnvNATUplinkInterfaces. Empty means auto-detect. UplinkInterfaces []string - // XDPAttach is one of the NATXDPAttach values, from EnvNATXDPAttach. + // XDPAttach is NATXDPAttachDirect or NATXDPAttachDispatch, from + // EnvNATXDPAttach. XDPAttach string + // XDPAttachDeprecated is set when EnvNATXDPAttach named the retired chain + // mode, which XDPAttach reads as dispatch, so the caller can warn. + XDPAttachDeprecated bool + // DatapathEnabled is EnvNATDatapathEnabled. DatapathEnabled bool @@ -184,6 +191,10 @@ func (c *NATConfig) readFields() { c.GRPCHealthPort = c.v.GetInt(KeyGRPCHealthPort) c.UplinkInterfaces = splitCommaList(c.v.GetString("uplink_interfaces")) c.XDPAttach = c.v.GetString("xdp_attach") + c.XDPAttachDeprecated = c.XDPAttach == NATXDPAttachChain + if c.XDPAttachDeprecated { + c.XDPAttach = NATXDPAttachDispatch + } c.DatapathEnabled = c.v.GetBool("datapath_enabled") c.EchoResponder = c.v.GetBool("echo_responder") } @@ -200,10 +211,10 @@ func (c *NATConfig) Validate() error { return errors.New("grpc health port must be between 1 and 65535") } switch c.XDPAttach { - case NATXDPAttachDirect, NATXDPAttachDispatch, NATXDPAttachChain: + case NATXDPAttachDirect, NATXDPAttachDispatch: default: - return fmt.Errorf("%s must be %q, %q or %q, got %q", EnvNATXDPAttach, - NATXDPAttachDirect, NATXDPAttachDispatch, NATXDPAttachChain, c.XDPAttach) + return fmt.Errorf("%s must be %q or %q, got %q", EnvNATXDPAttach, + NATXDPAttachDirect, NATXDPAttachDispatch, c.XDPAttach) } return nil } diff --git a/internal/config/nat_test.go b/internal/config/nat_test.go index a533699bd..5403a76a3 100644 --- a/internal/config/nat_test.go +++ b/internal/config/nat_test.go @@ -192,9 +192,9 @@ func TestNATConfigUplinkInterfacesOptional(t *testing.T) { } } -// TestNATConfigXDPAttach covers the attach mode: direct unless set, chain when -// asked for, and anything else refused at startup rather than read as one of -// the two -- a shard on the wrong mode either fails to attach or waits forever. +// TestNATConfigXDPAttach covers the attach mode: direct unless set, dispatch +// when asked for, the retired chain read as dispatch, and anything else +// refused at startup rather than read as one of them. func TestNATConfigXDPAttach(t *testing.T) { tests := []struct { value string @@ -205,7 +205,7 @@ func TestNATConfigXDPAttach(t *testing.T) { {want: NATXDPAttachDirect}, {value: NATXDPAttachDirect, set: true, want: NATXDPAttachDirect}, {value: NATXDPAttachDispatch, set: true, want: NATXDPAttachDispatch}, - {value: NATXDPAttachChain, set: true, want: NATXDPAttachChain}, + {value: NATXDPAttachChain, set: true, want: NATXDPAttachDispatch}, {value: "tc", set: true, wantErr: true}, } for _, tt := range tests { diff --git a/internal/controller/networkgateway_controller.go b/internal/controller/networkgateway_controller.go index afbd365fd..d8292ed65 100644 --- a/internal/controller/networkgateway_controller.go +++ b/internal/controller/networkgateway_controller.go @@ -73,6 +73,13 @@ type NetworkGatewayReconciler struct { Engine GatewayEngine NodeName string + + // Disabled is set when this node's datapath is turned off by + // configuration. The reconciler then keeps every one of this node's VIP + // advertisements withdrawn and reports the node not ready, so the fabric + // stops sending VIP traffic to a node that will not load-balance it. The + // engine is never driven. + Disabled bool } const ( @@ -86,6 +93,10 @@ const ( // it must not report reasonEngineHealthy. reasonAdvertisementFailed = "AdvertisementFailed" + // reasonDatapathDisabled is the Ready reason while this node's datapath is + // turned off by configuration. + reasonDatapathDisabled = "DatapathDisabled" + // reasonTerminating is the Ready reason for a NetworkGateway being deleted, // whether observed on a live object carrying a deletion timestamp or // reconstructed for the case where the object is already gone. @@ -170,6 +181,22 @@ func (r *NetworkGatewayReconciler) Reconcile(ctx context.Context, req ctrl.Reque return ctrl.Result{}, withdrawErr } + if r.Disabled { + withdrawErr := withdrawNodeAdvertisements(ctx, r.Client, gw.Namespace, r.NodeName) + gwCopy := gw.DeepCopy() + gwCopy.Status.ObservedGeneration = gw.Generation + setGatewayCondition(gwCopy, metav1.Condition{ + Type: bgpv1alpha1.ConditionTypeReady, + Status: metav1.ConditionFalse, + Reason: reasonDatapathDisabled, + Message: fmt.Sprintf("The edge gateway datapath on node %s is turned off", r.NodeName), + }) + if updateErr := r.Status().Update(ctx, gwCopy); updateErr != nil { + logger.Error(updateErr, "update status for disabled NetworkGateway") + } + return ctrl.Result{}, withdrawErr + } + // Advertisement failures are collected rather than returned on the spot, so // one bad rule does not stop the others. They are then reported on the // object and returned, so controller-runtime retries with backoff instead @@ -569,6 +596,19 @@ func isGatewayNode(ctx context.Context, c client.Client, namespace, nodeName str return false, nil } +// isNodeAdvertisement reports whether adv is one applyBGPAdvertisements created +// on node nodeName. An advertisement carrying networkRuleLabel must be named +// exactly "--v4" or "-v6" for its own rule, so a node named "edge1" +// never claims "ruleX-pop-edge1-v4", which belongs to node "pop-edge1". One +// without the label, created before the label existed, falls back to the +// name suffix alone. +func isNodeAdvertisement(adv *bgpv1alpha1.BGPAdvertisement, nodeName string) bool { + if rule, ok := adv.Labels[networkRuleLabel]; ok { + return adv.Name == rule+"-"+nodeName+"-v4" || adv.Name == rule+"-"+nodeName+"-v6" + } + return strings.HasSuffix(adv.Name, "-"+nodeName+"-v4") || strings.HasSuffix(adv.Name, "-"+nodeName+"-v6") +} + // withdrawNodeAdvertisements deletes every BGPAdvertisement that gateway node // nodeName created in namespace: each per-rule, per-address-family route it // advertised, found by the "--v4"/"-v6" names applyBGPAdvertisements @@ -593,13 +633,10 @@ func withdrawNodeAdvertisements(ctx context.Context, c client.Client, namespace, return fmt.Errorf("list BGPAdvertisements for departed gateway node %s: %w", nodeName, err) } - v4Suffix := "-" + nodeName + "-v4" - v6Suffix := "-" + nodeName + "-v6" - var errs []error for i := range advList.Items { adv := &advList.Items[i] - if !strings.HasSuffix(adv.Name, v4Suffix) && !strings.HasSuffix(adv.Name, v6Suffix) { + if !isNodeAdvertisement(adv, nodeName) { continue } if err := c.Delete(ctx, adv); err != nil && !apierrors.IsNotFound(err) { diff --git a/internal/controller/networkgateway_controller_test.go b/internal/controller/networkgateway_controller_test.go index 43bf60357..76c4f94e1 100644 --- a/internal/controller/networkgateway_controller_test.go +++ b/internal/controller/networkgateway_controller_test.go @@ -735,3 +735,69 @@ func TestPrefixesByFamily(t *testing.T) { t.Errorf("v6 = %v", v6) } } + +// TestNetworkGatewayReconciler_DisabledWithdrawsAndSkipsTheEngine: a node with +// its datapath turned off withdraws its own VIP advertisements, leaves another +// node's alone, never drives the engine, and says why on Ready. +func TestNetworkGatewayReconciler_DisabledWithdrawsAndSkipsTheEngine(t *testing.T) { + scheme := newRuleTestScheme(t) + gwA := newTestGateway(testNodeGWA) + own := newAdvertisement(testRuleName + "-" + testNodeGWA + "-v6") + other := newAdvertisement(testRuleName + "-" + testNodeGWB + "-v6") + + fakeClient := newIndexedClientBuilder(scheme). + WithStatusSubresource(&bgpv1alpha1.NetworkGateway{}). + WithObjects(gwA, own, other). + Build() + + engine := newFakeGatewayEngine() + r := newGatewayReconciler(fakeClient, scheme, engine, testNodeGWA) + r.Disabled = true + if _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: testRuleKey(testNodeGWA)}); err != nil { + t.Fatalf("Reconcile: unexpected error: %v", err) + } + + if engine.reconciled != 0 { + t.Errorf("engine reconciled %d times while disabled, want 0", engine.reconciled) + } + ctx := context.Background() + if err := fakeClient.Get(ctx, testRuleKey(own.Name), &bgpv1alpha1.BGPAdvertisement{}); !apierrors.IsNotFound(err) { + t.Errorf("own advertisement %s still exists (err=%v), want withdrawn", own.Name, err) + } + if err := fakeClient.Get(ctx, testRuleKey(other.Name), &bgpv1alpha1.BGPAdvertisement{}); err != nil { + t.Errorf("another node's advertisement %s was touched: %v", other.Name, err) + } + cond := gatewayReadyCondition(t, fakeClient) + if cond.Status != metav1.ConditionFalse || cond.Reason != reasonDatapathDisabled { + t.Errorf("Ready = %v/%q, want False/%q", cond.Status, cond.Reason, reasonDatapathDisabled) + } +} + +// TestIsNodeAdvertisement_LabelledNamesMatchExactly: a disabled node "edge1" +// withdraws its own advertisements on every reconcile, so it must never match +// a labelled advertisement of node "pop-edge1", or the two would fight. +func TestIsNodeAdvertisement_LabelledNamesMatchExactly(t *testing.T) { + labelled := func(name, rule string) *bgpv1alpha1.BGPAdvertisement { + adv := newAdvertisement(name) + adv.Labels = map[string]string{networkRuleLabel: rule} + return adv + } + tests := []struct { + name string + adv *bgpv1alpha1.BGPAdvertisement + want bool + }{ + {"own labelled v4", labelled("rulex-edge1-v4", "rulex"), true}, + {"own labelled v6", labelled("rulex-edge1-v6", "rulex"), true}, + {"other node sharing the suffix", labelled("rulex-pop-edge1-v4", "rulex"), false}, + {"unlabelled legacy name", newAdvertisement("rulex-edge1-v6"), true}, + {"unrelated", labelled("rulex-edge2-v4", "rulex"), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isNodeAdvertisement(tt.adv, "edge1"); got != tt.want { + t.Errorf("isNodeAdvertisement(%s, edge1) = %v, want %v", tt.adv.Name, got, tt.want) + } + }) + } +} diff --git a/internal/manifests/placement_test.go b/internal/manifests/placement_test.go index 675242eed..76df12e7e 100644 --- a/internal/manifests/placement_test.go +++ b/internal/manifests/placement_test.go @@ -135,17 +135,12 @@ func natXDPAttach(ds appsv1.DaemonSet) (string, bool) { return "", false } -// TestNATChainedOverlay pins the base to the binary's default (attach its own -// program) so it works with no gateway, and leaves chaining to the overlay for -// nodes that also run galactic-gateway. -func TestNATChainedOverlay(t *testing.T) { +// TestNATBaseLeavesTheAttachModeDefault pins the base to the binary's +// default (attach its own program), so it works on a node with no gateway. +// A node that also runs the gateway sets dispatch in its own overlay. +func TestNATBaseLeavesTheAttachModeDefault(t *testing.T) { base := loadDaemonSet(t, "galactic-nat", "base", "daemonset.yaml") if v, ok := natXDPAttach(base); ok { t.Errorf("base sets GALACTIC_NAT_XDP_ATTACH=%q; it must be left to the default so a node with no gateway works", v) } - - patch := loadDaemonSet(t, "galactic-nat", "overlays", "chained", "daemonset-patch.yaml") - if v, ok := natXDPAttach(patch); !ok || v != "chain" { - t.Errorf("chained overlay GALACTIC_NAT_XDP_ATTACH = %q (set=%v), want chain", v, ok) - } } diff --git a/internal/plumbing/ebpf/edgeattach/attach.go b/internal/plumbing/ebpf/edgeattach/attach.go index 9bfd7c295..ed29cdafa 100644 --- a/internal/plumbing/ebpf/edgeattach/attach.go +++ b/internal/plumbing/ebpf/edgeattach/attach.go @@ -39,10 +39,25 @@ const PinDir = "/sys/fs/bpf/galactic-edge" // failure path without touching the real kernel. var preflightCheckFn = edgepreflight.Check +// dispatchMapNames are the maps edgedsr.c shares with the node's XDP +// dispatcher (xdpdispatch's dispatch.h). They belong to the dispatcher, never +// to this package: they are not pinned under pinDir, never recreated here, and +// in dispatch mode are replaced with the dispatcher's own pinned maps. +var dispatchMapNames = map[string]bool{ + edgeprog.EdgedsrMapDispatchProgs: true, + edgeprog.EdgedsrMapIfaceRoles: true, + edgeprog.EdgedsrMapSlotLease: true, +} + // Load runs the kernel preflight check and, only if it passes, loads the edge -// program with every map pinned under pinDir. A map already pinned there by a -// previous process is reused as-is. -func Load(pinDir string) (*edgeprog.EdgedsrObjects, error) { +// program with every map of its own pinned under pinDir. A map already pinned +// there by a previous process is reused as-is. +// +// dispatchMaps is the node's XDP dispatcher's maps (xdpdispatch.Dispatcher.Maps) +// when the programs run from the dispatcher's slots, and nil when they are +// attached directly. Nil leaves the programs their own empty, unpinned copies, +// so every packet they do not claim passes to the kernel. +func Load(pinDir string, dispatchMaps map[string]*ebpf.Map) (*edgeprog.EdgedsrObjects, error) { if err := preflightCheckFn(); err != nil { return nil, fmt.Errorf( "edgeattach: kernel preflight check failed, refusing to load the edge gateway datapath: %w", err) @@ -54,26 +69,40 @@ func Load(pinDir string) (*edgeprog.EdgedsrObjects, error) { return nil, fmt.Errorf("edgeattach: create bpf map pin directory %q: %w", pinDir, err) } + // Gateways before the shared dispatcher pinned a one-slot program array + // here, xdp_chain, that the egress shard filled. Nothing reads it now, so + // it only keeps a retired shard program loaded, and a shard not yet + // upgraded would install itself into a map no datapath runs and look + // healthy. Remove it. + legacyChain := filepath.Join(pinDir, "xdp_chain") + if err := os.Remove(legacyChain); err == nil { + slog.Info("edgeattach: removed the retired xdp_chain pin; the egress shard now runs from the XDP dispatcher", + "path", legacyChain) + } else if !errors.Is(err, os.ErrNotExist) { + slog.Warn("edgeattach: cannot remove the retired xdp_chain pin", "path", legacyChain, "err", err) + } + spec, err := edgeprog.LoadEdgedsr() if err != nil { return nil, fmt.Errorf("edgeattach: load compiled edgedsr collection spec: %w", err) } - for _, m := range spec.Maps { - m.Pinning = ebpf.PinByName + for name, m := range spec.Maps { + if !dispatchMapNames[name] { + m.Pinning = ebpf.PinByName + } } var loaded edgeprog.EdgedsrObjects - opts := &ebpf.CollectionOptions{Maps: ebpf.MapOptions{PinPath: pinDir}} + opts := &ebpf.CollectionOptions{Maps: ebpf.MapOptions{PinPath: pinDir}, MapReplacements: dispatchMaps} loadErr := spec.LoadAndAssign(&loaded, opts) if loadErr != nil && errors.Is(loadErr, ebpf.ErrMapIncompatible) { // Every map here is control-plane-owned and reconstructable: the VIP // table is repopulated from live CRDs, the statistics map is a // pure cache the datapath refills from traffic, and the // encapsulation config is a single entry rewritten at process - // startup. xdp_chain is filled by another process, the egress - // shard, which re-asserts its slot periodically and so refills a - // recreated one on its own. A stale pin from an incompatible layout - // is safe to recreate rather than fatal. + // startup. A stale pin from an incompatible layout is safe to + // recreate rather than fatal. The dispatcher's maps are not ours and + // are never touched here. slog.Warn("edgeattach: pinned eBPF map incompatible with the newly compiled map spec, recreating "+ "(control-plane state will repopulate on the next NetworkRule reconcile)", "pinDir", pinDir, "err", loadErr) if unpinErr := unpinIncompatibleMaps(spec, pinDir); unpinErr != nil { @@ -96,6 +125,9 @@ func Load(pinDir string) (*edgeprog.EdgedsrObjects, error) { func unpinIncompatibleMaps(spec *ebpf.CollectionSpec, pinDir string) error { var errs []error for name := range spec.Maps { + if dispatchMapNames[name] { + continue + } path := filepath.Join(pinDir, name) m, err := ebpf.LoadPinnedMap(path, nil) if err != nil { diff --git a/internal/plumbing/ebpf/edgeattach/attach_test.go b/internal/plumbing/ebpf/edgeattach/attach_test.go index 67e39083b..285163efc 100644 --- a/internal/plumbing/ebpf/edgeattach/attach_test.go +++ b/internal/plumbing/ebpf/edgeattach/attach_test.go @@ -19,7 +19,6 @@ import ( "go.datum.net/galactic/internal/plumbing/bond" "go.datum.net/galactic/internal/plumbing/ebpf/edgeprog" - "go.datum.net/galactic/internal/plumbing/ebpf/natattach" ) func requireRoot(t *testing.T) { @@ -41,7 +40,7 @@ func TestLoad_PreflightBlocksLoad(t *testing.T) { pinDir := filepath.Join(t.TempDir(), "does-not-exist", "galactic-edge") - objs, err := Load(pinDir) + objs, err := Load(pinDir, nil) if err == nil { t.Fatal("Load() error = nil, want a preflight failure") } @@ -241,7 +240,7 @@ func TestLoadAttach_SurvivesRestartWithMapsIntact(t *testing.T) { // --- pre-restart: first load, attach, and populate a map entry. --- var firstLink interface{ Close() error } err = nsObj.Do(func(_ ns.NetNS) error { - objs, err := Load(pinDir) + objs, err := Load(pinDir, nil) if err != nil { return fmt.Errorf("load: %w", err) } @@ -275,7 +274,7 @@ func TestLoadAttach_SurvivesRestartWithMapsIntact(t *testing.T) { // --- simulate a container restart: fresh Load+Attach against the // same pinDir/interface, as a brand new process would do. --- err = nsObj.Do(func(_ ns.NetNS) error { - objs, err := Load(pinDir) + objs, err := Load(pinDir, nil) if err != nil { return fmt.Errorf("reload after restart: %w", err) } @@ -357,7 +356,7 @@ func TestAttach_MultipleInterfacesRollsBackOnPartialFailure(t *testing.T) { } err = nsObj.Do(func(_ ns.NetNS) error { - objs, err := Load(pinDir) + objs, err := Load(pinDir, nil) if err != nil { return fmt.Errorf("load: %w", err) } @@ -479,7 +478,7 @@ func TestResolveTargetsAndAttach_RealBondDevice(t *testing.T) { return fmt.Errorf("ResolveTargets(%q) = %v, want %v", bondName, got, want) } - objs, err := Load(pinDir) + objs, err := Load(pinDir, nil) if err != nil { return fmt.Errorf("load: %w", err) } @@ -501,12 +500,35 @@ func TestResolveTargetsAndAttach_RealBondDevice(t *testing.T) { } } -// TestChainMapPathMatchesTheShardsCopy holds natattach's spelled-out copy of -// where this package pins xdp_chain in step with the real thing. The egress -// shard opens that path to install itself; a drift here leaves it retrying -// against a map that is never created. -func TestChainMapPathMatchesTheShardsCopy(t *testing.T) { - if got := filepath.Join(PinDir, edgeprog.EdgedsrMapXdpChain); got != natattach.EdgeChainMapPath { - t.Errorf("xdp_chain pins at %q, natattach.EdgeChainMapPath = %q", got, natattach.EdgeChainMapPath) +// TestLoad_RemovesTheRetiredChainPin: a gateway upgraded from the xdp_chain +// era must not leave that map pinned, where a shard not yet upgraded would +// install itself into a map no datapath runs. +func TestLoad_RemovesTheRetiredChainPin(t *testing.T) { + requireRoot(t) + pinDir := filepath.Join("/sys/fs/bpf", fmt.Sprintf("galactic-edge-test-chain-%d", os.Getpid())) + if err := os.MkdirAll(pinDir, 0o755); err != nil { + t.Skipf("bpffs not writable at /sys/fs/bpf: %v", err) + } + t.Cleanup(func() { _ = os.RemoveAll(pinDir) }) + + legacy, err := ebpf.NewMap(&ebpf.MapSpec{ + Type: ebpf.ProgramArray, KeySize: 4, ValueSize: 4, MaxEntries: 1, + }) + if err != nil { + t.Fatalf("create legacy chain map: %v", err) + } + t.Cleanup(func() { _ = legacy.Close() }) + chainPin := filepath.Join(pinDir, "xdp_chain") + if err := legacy.Pin(chainPin); err != nil { + t.Fatalf("pin legacy chain map: %v", err) + } + + objs, err := Load(pinDir, nil) + if err != nil { + t.Fatalf("Load: %v", err) + } + t.Cleanup(func() { _ = objs.Close() }) + if _, err := os.Stat(chainPin); !errors.Is(err, os.ErrNotExist) { + t.Errorf("retired xdp_chain pin still present after Load (stat err = %v)", err) } } diff --git a/internal/plumbing/ebpf/edgeprog/edgedsr.c b/internal/plumbing/ebpf/edgeprog/edgedsr.c index a6c57dce2..f97f30b31 100644 --- a/internal/plumbing/ebpf/edgeprog/edgedsr.c +++ b/internal/plumbing/ebpf/edgeprog/edgedsr.c @@ -29,8 +29,9 @@ // Packet path: // // 1. Parse the outer Ethernet and IPv6 header, bounds-checked. Not IPv6, or -// unparseable: unclaimed. Every unclaimed packet goes to xdp_chain's -// program if one is installed, and otherwise XDP_PASS to the kernel stack. +// unparseable: unclaimed. Every unclaimed packet goes on to the later +// slots of the node's XDP dispatcher (dispatch_next), and past the last +// one, or with no dispatcher, XDP_PASS to the kernel stack. // 2. Parse the L4 header, TCP or UDP only. Only the ports are read, and // nothing is ever rewritten. // 3. Match (proto, destination port, destination address) against vip_table. A @@ -85,7 +86,6 @@ static __u64 (*bpf_ktime_get_ns)(void) = (void *) BPF_FUNC_ktime_get_ns; // bpf_redirect, not bpf_redirect_peer: the latter is TC-only, and every egress // interface here is in this node's own namespace anyway. static long (*bpf_redirect)(__u32 ifindex, __u64 flags) = (void *) BPF_FUNC_redirect; -static long (*bpf_tail_call)(void *ctx, void *prog_array_map, __u32 index) = (void *) BPF_FUNC_tail_call; // --------------------------------------------------------------------- // Constants. @@ -278,36 +278,26 @@ struct { __type(value, __u64); } drop_reasons SEC(".maps"); -// EDGE_CHAIN_SLOT is xdp_chain's one slot. -#define EDGE_CHAIN_SLOT 0 - -// xdp_chain hands every packet this node's gateway does not claim to one -// further XDP program sharing the same interfaces -- in practice the egress -// translation shard (internal/plumbing/ebpf/natprog), which runs on the same -// edge nodes and needs both of the interfaces these programs hold. An -// interface takes one native XDP program, so the second datapath runs as a -// tail call from here rather than as an attachment of its own. -// -// This program owns the map and pins it (edgeattach.Load); the other datapath -// only fills the slot, from its own process (natattach.AttachChain). The two -// claim disjoint traffic -- a VIP destination or source here, a shard SID or -// masquerade address there -- so the order they run in changes no verdict. -// -// An empty slot makes bpf_tail_call return, and the packet passes to the -// kernel exactly as it did before this map existed. -struct { - __uint(type, BPF_MAP_TYPE_PROG_ARRAY); - __uint(max_entries, 1); - __type(key, __u32); - __type(value, __u32); -} xdp_chain SEC(".maps"); +// The node's XDP dispatcher (internal/plumbing/ebpf/xdpdispatch). edge_lb and +// edge_return run from its gateway slots, and a packet either does not claim +// goes on to the later slots, in practice the egress translation shard, which +// shares these interfaces. The two claim disjoint traffic, a VIP destination +// or source here and a shard SID or masquerade address there, so the order +// they run in changes no verdict. Attached directly instead, with no +// dispatcher on the node, these programs see an empty iface_roles and every +// unclaimed packet passes to the kernel. +#include "../xdpdispatch/dispatch.h" + +// pass_unclaimed_lb and pass_unclaimed_return are every exit for a packet the +// gateway does not claim, from edge_lb and edge_return. +static EDGE_ALWAYS_INLINE int pass_unclaimed_lb(struct xdp_md *ctx) +{ + return dispatch_next(ctx, XDPD_SLOT_GATEWAY_LB); +} -// pass_unclaimed is every exit for a packet this gateway does not claim. It -// never returns when the chained program runs, and otherwise yields XDP_PASS. -static EDGE_ALWAYS_INLINE int pass_unclaimed(struct xdp_md *ctx) +static EDGE_ALWAYS_INLINE int pass_unclaimed_return(struct xdp_md *ctx) { - bpf_tail_call(ctx, &xdp_chain, EDGE_CHAIN_SLOT); - return XDP_PASS; + return dispatch_next(ctx, XDPD_SLOT_GATEWAY_RETURN); } static EDGE_ALWAYS_INLINE void count_drop(__u32 reason) @@ -505,20 +495,20 @@ int edge_lb(struct xdp_md *ctx) struct edge_ethhdr *eth = data; if ((void *) (eth + 1) > data_end) - return pass_unclaimed(ctx); + return pass_unclaimed_lb(ctx); if (eth->h_proto != __builtin_bswap16(EDGE_ETH_P_IPV6)) - return pass_unclaimed(ctx); + return pass_unclaimed_lb(ctx); struct edge_ip6hdr *ip6 = (void *) (eth + 1); if ((void *) (ip6 + 1) > data_end) - return pass_unclaimed(ctx); + return pass_unclaimed_lb(ctx); if (ip6->nexthdr != EDGE_IPPROTO_TCP && ip6->nexthdr != EDGE_IPPROTO_UDP) - return pass_unclaimed(ctx); + return pass_unclaimed_lb(ctx); struct edge_l4ports *ports = (void *) (ip6 + 1); if ((void *) (ports + 1) > data_end) - return pass_unclaimed(ctx); + return pass_unclaimed_lb(ctx); struct vip_key vk; __builtin_memset(&vk, 0, sizeof(vk)); @@ -528,7 +518,7 @@ int edge_lb(struct xdp_md *ctx) struct vip_value *rule = bpf_map_lookup_elem(&vip_table, &vk); if (!rule) - return pass_unclaimed(ctx); // not one of this gateway's VIPs + return pass_unclaimed_lb(ctx); // not one of this gateway's VIPs // Claimed past this point -- every subsequent failure is a drop, not // a pass-through (this gateway owns this VIP+port+protocol). @@ -625,20 +615,20 @@ int edge_return(struct xdp_md *ctx) struct edge_ethhdr *eth = data; if ((void *) (eth + 1) > data_end) - return pass_unclaimed(ctx); + return pass_unclaimed_return(ctx); if (eth->h_proto != __builtin_bswap16(EDGE_ETH_P_IPV6)) - return pass_unclaimed(ctx); + return pass_unclaimed_return(ctx); struct edge_ip6hdr *ip6 = (void *) (eth + 1); if ((void *) (ip6 + 1) > data_end) - return pass_unclaimed(ctx); + return pass_unclaimed_return(ctx); struct vip_addr_key ak; __builtin_memset(&ak, 0, sizeof(ak)); __builtin_memcpy(ak.vip, ip6->saddr, 16); if (!bpf_map_lookup_elem(&vip_addr_table, &ak)) - return pass_unclaimed(ctx); // not sourced from one of this gateway's VIPs + return pass_unclaimed_return(ctx); // not sourced from one of this gateway's VIPs // Claimed past this point: this node owns the source address, so every // subsequent failure is a counted drop rather than a pass-through that diff --git a/internal/plumbing/ebpf/edgeprog/edgedsr_chain_test.go b/internal/plumbing/ebpf/edgeprog/edgedsr_chain_test.go index 35715e41e..93e314307 100644 --- a/internal/plumbing/ebpf/edgeprog/edgedsr_chain_test.go +++ b/internal/plumbing/ebpf/edgeprog/edgedsr_chain_test.go @@ -7,25 +7,39 @@ package edgeprog import ( "net/netip" "testing" + "time" "github.com/cilium/ebpf" "github.com/cilium/ebpf/asm" + "golang.org/x/sys/unix" ) -// chainStubVerdict is what the stub chained program returns. XDP_TX, because -// neither test path below can produce it from the gateway's own programs: a -// claimed packet there is a counted drop, so a TX verdict can only have come -// from the stub. +// chainStubVerdict is what the stub in the dispatcher's egress slot returns. +// XDP_TX, because neither test path below can produce it from the gateway's +// own programs: a claimed packet there is a counted drop, so a TX verdict can +// only have come from the stub. const chainStubVerdict = xdpTx -// installChainStub loads a one-instruction XDP program returning -// chainStubVerdict and puts it in xdp_chain's slot, standing in for the egress -// translation shard that fills it in production. +// Dispatcher constants, mirroring dispatch.h. BPF_PROG_TEST_RUN with no +// context reports the loopback device, ifindex 1, as the ingress interface. +const ( + testRunIfindex = uint32(1) + slotNAT = uint32(2) + roleGatewayLB = uint32(1 << 0) + roleGatewayReturn = uint32(1 << 1) + roleEgress = uint32(1 << 2) +) + +// installChainStub stands in for the egress shard running from the node's XDP +// dispatcher: a one-instruction program returning chainStubVerdict in the +// egress slot with a live lease, and roles on the test-run interface. The +// gateway's programs here hold their own copies of the dispatcher maps, as +// they do when loaded without a dispatcher. // // AttachType must be AttachXDP, as an ELF SEC("xdp") program's is: the kernel // refuses a program into a prog array whose owner's expected attach type // differs, with a bare EINVAL. -func installChainStub(t *testing.T, objs *EdgedsrObjects) { +func installChainStub(t *testing.T, objs *EdgedsrObjects, roles uint32) { t.Helper() stub, err := ebpf.NewProgram(&ebpf.ProgramSpec{ Type: ebpf.XDP, @@ -40,11 +54,24 @@ func installChainStub(t *testing.T, objs *EdgedsrObjects) { t.Fatalf("load chain stub program: %v", err) } t.Cleanup(func() { _ = stub.Close() }) - if err := objs.XdpChain.Put(uint32(0), stub); err != nil { - t.Fatalf("install chain stub in xdp_chain: %v", err) + if err := objs.DispatchProgs.Put(slotNAT, stub); err != nil { + t.Fatalf("install chain stub in dispatch_progs: %v", err) + } + if err := objs.SlotLease.Put(slotNAT, monotonicNow()+uint64(time.Minute)); err != nil { + t.Fatalf("lease the egress slot: %v", err) + } + if err := objs.IfaceRoles.Put(testRunIfindex, roles); err != nil { + t.Fatalf("set test-run interface roles: %v", err) } } +// monotonicNow reads CLOCK_MONOTONIC, the clock the dispatcher's leases use. +func monotonicNow() uint64 { + var ts unix.Timespec + _ = unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts) + return uint64(ts.Sec)*1e9 + uint64(ts.Nsec) +} + // buildIPv4Frame is a minimal Ethernet+IPv4 frame. Neither gateway program // parses IPv4, and a NAT64 reply arriving on the public uplink is exactly this // shape, so the chained program must still see it. @@ -60,12 +87,12 @@ func buildIPv4Frame() []byte { } // TestEdgeLB_ChainsUnclaimedTraffic proves that every packet edge_lb does not -// claim reaches the chained program -- a miss in vip_table and a frame that is -// not IPv6 at all -- and that a claimed one never does. +// claim reaches the dispatcher's egress slot, a miss in vip_table and a frame +// that is not IPv6 at all, and that a claimed one never does. func TestEdgeLB_ChainsUnclaimedTraffic(t *testing.T) { requireRoot(t) objs := loadObjects(t) - installChainStub(t, objs) + installChainStub(t, objs, roleGatewayLB|roleEgress) vip := netip.MustParseAddr("2001:db8::100") client := netip.MustParseAddr("2001:db8:ffff::1") @@ -104,7 +131,7 @@ func TestEdgeLB_ChainsUnclaimedTraffic(t *testing.T) { func TestEdgeReturn_ChainsUnclaimedTraffic(t *testing.T) { requireRoot(t) objs := loadObjects(t) - installChainStub(t, objs) + installChainStub(t, objs, roleGatewayReturn|roleEgress) vip := netip.MustParseAddr("2001:db8:6060::1") client := netip.MustParseAddr("2001:db8:1:40::2") @@ -136,3 +163,22 @@ func TestEdgeReturn_ChainsUnclaimedTraffic(t *testing.T) { }) } } + +// TestEdgeLB_UnclaimedPassesWithoutTheEgressRole: an interface the egress +// shard does not run on hands it nothing, and the packet passes to the kernel +// as it does with no dispatcher at all. +func TestEdgeLB_UnclaimedPassesWithoutTheEgressRole(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + installChainStub(t, objs, roleGatewayLB) + + pkt := buildL4Packet(t, ipprotoUDP, netip.MustParseAddr("2001:db8::200"), + netip.MustParseAddr("2001:db8:ffff::1"), 5000, 443, nil) + ret, _, err := objs.EdgeLb.Test(pkt) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + if ret != xdpPass { + t.Errorf("verdict = %d, want XDP_PASS (%d)", ret, xdpPass) + } +} diff --git a/internal/plumbing/ebpf/natattach/chain.go b/internal/plumbing/ebpf/natattach/chain.go deleted file mode 100644 index 091244203..000000000 --- a/internal/plumbing/ebpf/natattach/chain.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2026 Datum Cloud, Inc. -// -// SPDX-License-Identifier: AGPL-3.0-or-later - -package natattach - -import ( - "errors" - "fmt" - "log/slog" - - "github.com/cilium/ebpf" -) - -// EdgeChainMapPath is where the edge gateway pins xdp_chain: the edge attach -// package's PinDir joined with the map's name, spelled out here so this binary -// does not link the gateway's datapath to learn one path. edgeattach's tests -// hold the two in step. -const EdgeChainMapPath = "/sys/fs/bpf/galactic-edge/xdp_chain" - -// chainSlot is xdp_chain's one slot, EDGE_CHAIN_SLOT in edgedsr.c. -const chainSlot = uint32(0) - -// AttachChain installs program in the edge gateway's xdp_chain slot, pinned at -// mapPath, so the gateway's programs hand it every packet they do not claim. -// -// This is how the shard runs on an edge node. The gateway already holds the -// native XDP hook on the interfaces the shard needs, and an interface takes -// one native program, so a second Attach there fails outright. Chained, the -// shard sees exactly the traffic it would have seen attached: the gateway's -// claimed set (VIP destination or source) is disjoint from the shard's (shard -// SID or masquerade address destination). -// -// There is no link to hold and none is returned. The slot keeps program alive -// on its own, across this process's exit, and the next process's AttachChain -// replaces it in place, with no window where the shard claims nothing. A slot -// holding a program whose shard has since been cleared is harmless: an -// unprogrammed shard claims no packet. -// -// A missing map means the gateway has not loaded yet, and is returned as an -// error wrapping ebpf's not-exist error for the caller to retry. -func AttachChain(program *ebpf.Program, mapPath string) error { - if program == nil { - return errors.New("natattach: program is nil") - } - m, err := ebpf.LoadPinnedMap(mapPath, nil) - if err != nil { - return fmt.Errorf("natattach: open edge chain map %q: %w", mapPath, err) - } - defer m.Close() //nolint:errcheck // best-effort close of our own fd, immediately after use - - if m.Type() != ebpf.ProgramArray { - return fmt.Errorf("natattach: edge chain map %q is a %s, not a program array", mapPath, m.Type()) - } - // The kernel checks program against the array's owner -- type, JIT state, - // frags support and expected attach type -- and refuses a mismatch with a - // bare EINVAL, so say which check that is. - if err := m.Put(chainSlot, program); err != nil { - return fmt.Errorf("natattach: install program in edge chain map %q "+ - "(EINVAL here means the program is incompatible with the gateway's): %w", mapPath, err) - } - return nil -} - -// ChainHolds reports whether the xdp_chain slot pinned at mapPath currently -// holds program. It is false, not an error, for an empty slot or a slot -// holding another program -- the state a gateway restart that recreated the -// map leaves behind, and what a caller re-asserting the slot looks for. -func ChainHolds(program *ebpf.Program, mapPath string) (bool, error) { - info, err := program.Info() - if err != nil { - return false, fmt.Errorf("natattach: read program info: %w", err) - } - want, ok := info.ID() - if !ok { - return false, errors.New("natattach: kernel reports no program ID") - } - - m, err := ebpf.LoadPinnedMap(mapPath, nil) - if err != nil { - return false, fmt.Errorf("natattach: open edge chain map %q: %w", mapPath, err) - } - defer m.Close() //nolint:errcheck // best-effort close of our own fd, immediately after use - - // A program array read from user space yields the installed program's ID. - var got uint32 - if err := m.Lookup(chainSlot, &got); err != nil { - if errors.Is(err, ebpf.ErrKeyNotExist) { - return false, nil - } - return false, fmt.Errorf("natattach: read edge chain map %q: %w", mapPath, err) - } - return ebpf.ProgramID(got) == want, nil -} - -// UnhookedUplinks returns every one of ifaceNames that carries no XDP program. -// Chained, the shard sees only what the gateway's programs see, so an uplink -// the gateway is not attached to is one whose traffic this shard never -// translates -- the same silent gap an unattached uplink is in direct mode. -// Which interfaces the gateway attaches to is its own configuration, so the -// caller can only report the gap, not close it. An uplink that cannot be -// inspected counts as unhooked. -func UnhookedUplinks(ifaceNames []string) []string { - var unhooked []string - for _, name := range ifaceNames { - l, err := linkByNameFn(name) - if err != nil { - slog.Warn("natattach: cannot inspect uplink for an XDP program", "interface", name, "err", err) - unhooked = append(unhooked, name) - continue - } - if xdp := l.Attrs().Xdp; xdp == nil || !xdp.Attached { - unhooked = append(unhooked, name) - } - } - return unhooked -} diff --git a/internal/plumbing/ebpf/natattach/chain_test.go b/internal/plumbing/ebpf/natattach/chain_test.go deleted file mode 100644 index 1659bd149..000000000 --- a/internal/plumbing/ebpf/natattach/chain_test.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2026 Datum Cloud, Inc. -// -// SPDX-License-Identifier: AGPL-3.0-or-later - -package natattach - -import ( - "errors" - "os" - "path/filepath" - "testing" - - "github.com/cilium/ebpf" - "github.com/cilium/ebpf/asm" - - "go.datum.net/galactic/internal/plumbing/ebpf/edgeprog" - "go.datum.net/galactic/internal/plumbing/ebpf/natprog" -) - -// pinEdgeChain loads the real edge gateway objects and pins their xdp_chain -// under a per-test bpffs directory, standing in for a running galactic-gateway. -// The real objects rather than a hand-made program array matter: the kernel -// ties an array to its first user's program type and expected attach type, and -// that owner is what AttachChain's program has to be compatible with. -func pinEdgeChain(t *testing.T) (*edgeprog.EdgedsrObjects, string) { - t.Helper() - requireRoot(t) - - var edge edgeprog.EdgedsrObjects - if err := edgeprog.LoadEdgedsrObjects(&edge, nil); err != nil { - t.Fatalf("load edge objects: %v", err) - } - t.Cleanup(func() { _ = edge.Close() }) - - dir := filepath.Join("/sys/fs/bpf", "natattach-chain-test-"+filepath.Base(t.Name())) - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Skipf("bpffs not writable at /sys/fs/bpf: %v", err) - } - t.Cleanup(func() { _ = os.RemoveAll(dir) }) - path := filepath.Join(dir, "xdp_chain") - if err := edge.XdpChain.Pin(path); err != nil { - t.Fatalf("pin xdp_chain: %v", err) - } - t.Cleanup(func() { _ = edge.XdpChain.Unpin() }) - return &edge, path -} - -func loadNatObjects(t *testing.T) *natprog.NatObjects { - t.Helper() - var objs natprog.NatObjects - if err := natprog.LoadNatObjects(&objs, nil); err != nil { - t.Fatalf("load nat objects: %v", err) - } - t.Cleanup(func() { _ = objs.Close() }) - return &objs -} - -// TestAttachChain_InstallsTheShardInTheGatewaysSlot is the property the edge -// placement rests on: the shard's real dispatcher is accepted into the real -// gateway's array, and ChainHolds reads that back. -func TestAttachChain_InstallsTheShardInTheGatewaysSlot(t *testing.T) { - _, path := pinEdgeChain(t) - nat := loadNatObjects(t) - - if held, err := ChainHolds(nat.NatIngress, path); err != nil || held { - t.Fatalf("ChainHolds before AttachChain = %v, %v; want false, nil", held, err) - } - if err := AttachChain(nat.NatIngress, path); err != nil { - t.Fatalf("AttachChain: %v", err) - } - if held, err := ChainHolds(nat.NatIngress, path); err != nil || !held { - t.Fatalf("ChainHolds after AttachChain = %v, %v; want true, nil", held, err) - } - // Idempotent, since the re-assert loop calls it again on every miss. - if err := AttachChain(nat.NatIngress, path); err != nil { - t.Fatalf("second AttachChain: %v", err) - } -} - -// TestChainHolds_ReportsASlotSomethingElseTook covers what a re-assert has to -// notice: the slot now holding a different program, as after a gateway -// restart that recreated its map. -func TestChainHolds_ReportsASlotSomethingElseTook(t *testing.T) { - edge, path := pinEdgeChain(t) - nat := loadNatObjects(t) - if err := AttachChain(nat.NatIngress, path); err != nil { - t.Fatalf("AttachChain: %v", err) - } - - other, err := ebpf.NewProgram(&ebpf.ProgramSpec{ - Type: ebpf.XDP, - AttachType: ebpf.AttachXDP, - Instructions: asm.Instructions{asm.Mov.Imm(asm.R0, 2), asm.Return()}, - License: "GPL", - }) - if err != nil { - t.Fatalf("load other program: %v", err) - } - t.Cleanup(func() { _ = other.Close() }) - if err := edge.XdpChain.Put(chainSlot, other); err != nil { - t.Fatalf("replace slot: %v", err) - } - - if held, err := ChainHolds(nat.NatIngress, path); err != nil || held { - t.Fatalf("ChainHolds with another program in the slot = %v, %v; want false, nil", held, err) - } - if err := AttachChain(nat.NatIngress, path); err != nil { - t.Fatalf("re-assert AttachChain: %v", err) - } - if held, err := ChainHolds(nat.NatIngress, path); err != nil || !held { - t.Fatalf("ChainHolds after re-assert = %v, %v; want true, nil", held, err) - } -} - -// TestAttachChain_MissingMapIsNotExist lets the caller tell "the gateway has -// not loaded yet", which it retries, from a real failure. -func TestAttachChain_MissingMapIsNotExist(t *testing.T) { - requireRoot(t) - nat := loadNatObjects(t) - - err := AttachChain(nat.NatIngress, "/sys/fs/bpf/natattach-chain-test-absent/xdp_chain") - if !errors.Is(err, os.ErrNotExist) { - t.Fatalf("AttachChain on a missing map = %v, want an error wrapping os.ErrNotExist", err) - } -} - -func TestAttachChain_NilProgramIsError(t *testing.T) { - if err := AttachChain(nil, EdgeChainMapPath); err == nil { - t.Fatal("AttachChain(nil, _) error = nil, want an error") - } -} diff --git a/internal/plumbing/ebpf/natattach/doc.go b/internal/plumbing/ebpf/natattach/doc.go index 5a186485a..82527769b 100644 --- a/internal/plumbing/ebpf/natattach/doc.go +++ b/internal/plumbing/ebpf/natattach/doc.go @@ -10,16 +10,14 @@ // native-driver-mode attach with no generic-mode fallback. See that package for // the rationale behind each, which applies here unchanged. // -// # Chained behind the edge gateway -// -// On an edge node the gateway's programs already hold the native XDP hook on -// the interfaces a shard needs, and an interface takes one native program. -// There the shard is not attached at all: AttachChain installs its dispatcher -// in the gateway's pinned xdp_chain slot, and the gateway tail-calls it with -// every packet it does not claim. The two datapaths claim disjoint traffic, so -// the shard sees what it would have seen attached, on exactly the interfaces -// the gateway is attached to. The caller keeps the slot filled with -// ChainHolds, since a gateway that recreates its map empties it. +// # Sharing the hook with the edge gateway +// +// An interface takes one native XDP program. On a node where the gateway runs +// too, the shard does not attach itself: it runs from the egress slot of the +// node's shared XDP dispatcher (internal/plumbing/ebpf/xdpdispatch), whose root +// holds every uplink for both datapaths. cmd/galactic-nat drives that through +// xdpattach.DispatchSet; Load and PopulateProgArray here are the same in +// either mode. // // # No kernel preflight check // diff --git a/internal/plumbing/ebpf/natattach/uplinks_test.go b/internal/plumbing/ebpf/natattach/uplinks_test.go index a348e791b..9c1784bed 100644 --- a/internal/plumbing/ebpf/natattach/uplinks_test.go +++ b/internal/plumbing/ebpf/natattach/uplinks_test.go @@ -111,20 +111,3 @@ func TestResolveUplinks_NoRouteYetIsErrNoUplinks(t *testing.T) { t.Errorf("ResolveUplinks() error = %v; a real detection failure must not read as ErrNoUplinks", err) } } - -func TestUnhookedUplinks(t *testing.T) { - fakeUplinkHost(t, nil, nil) - hooked := &fakeLink{attrs: netlink.LinkAttrs{Name: "hooked0", Xdp: &netlink.LinkXdp{Attached: true}}} - byName := linkByNameFn - linkByNameFn = func(name string) (netlink.Link, error) { - if name == hooked.attrs.Name { - return hooked, nil - } - return byName(name) - } - - got := UnhookedUplinks([]string{"hooked0", testUplink, "gone0"}) - if want := []string{testUplink, "gone0"}; !slices.Equal(got, want) { - t.Errorf("UnhookedUplinks() = %v, want %v", got, want) - } -} diff --git a/internal/plumbing/ebpf/xdpattach/release.go b/internal/plumbing/ebpf/xdpattach/release.go new file mode 100644 index 000000000..ee4baaa90 --- /dev/null +++ b/internal/plumbing/ebpf/xdpattach/release.go @@ -0,0 +1,109 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpattach + +import ( + "context" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "slices" + + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" +) + +// ErrDispatcherInUse is ReleaseIdleDispatcher refusing to detach a dispatcher +// that another datapath's live slot still depends on. +var ErrDispatcherInUse = errors.New("xdpattach: the XDP dispatcher is serving another datapath") + +// ReleaseIdleDispatcher detaches the node's XDP dispatcher under pinDir from +// ifaces, so a datapath switched back from dispatch to direct mode can attach +// its own program, and empties own, the caller's slots. It does nothing on a +// node that never ran the dispatcher. +// +// It refuses, with ErrDispatcherInUse, while any slot outside own is live and +// the dispatcher holds one of ifaces: that datapath runs from the dispatcher +// on the interface, and detaching it would cut its traffic. The live slots are +// read under the dispatch lock, which every Fill takes too, so no datapath can +// take a slot between the check and the release. +func ReleaseIdleDispatcher(ctx context.Context, pinDir string, ifaces []string, own ...xdpdispatch.Slot) error { + if _, err := os.Stat(filepath.Join(pinDir, "links")); errors.Is(err, os.ErrNotExist) { + return nil + } + dispatcher, err := xdpdispatch.Open(ctx, pinDir) + if err != nil { + return fmt.Errorf("xdpattach: open the node's XDP dispatcher to release it: %w", err) + } + defer dispatcher.Close() //nolint:errcheck // our own descriptors; the pins are what matter + + lock, err := dispatcher.Lock(ctx) + if err != nil { + return err + } + defer lock.Unlock() + live, err := dispatcher.LiveSlots() + if err != nil { + return err + } + others := slices.DeleteFunc(live, func(s xdpdispatch.Slot) bool { return slices.Contains(own, s) }) + + for _, name := range ifaces { + l, err := linkByNameFn(name) + if err != nil { + return fmt.Errorf("xdpattach: find interface %q: %w", name, err) + } + ifindex := l.Attrs().Index + linked, err := dispatcher.Linked(ifindex) + if err != nil { + return err + } + if !linked { + continue + } + if len(others) > 0 { + return fmt.Errorf("%w: dispatcher slots %v are live on interface %q, so a direct attach would "+ + "cut that datapath's traffic; run in dispatch mode", ErrDispatcherInUse, others, name) + } + if err := lock.Release(ifindex); err != nil { + return err + } + slog.Info("Released the idle XDP dispatcher from interface for a direct attach", "interface", name) + } + for _, slot := range own { + if err := lock.Clear(slot); err != nil { + return err + } + } + return nil +} + +// ClearDispatcherSlots empties slots in the node's XDP dispatcher under +// pinDir, for a datapath turned off, so the dispatcher passes its traffic on +// at once rather than once the slots' leases lapse. Every other slot, and the +// dispatcher itself, are left alone. It does nothing on a node that never ran +// the dispatcher. +func ClearDispatcherSlots(ctx context.Context, pinDir string, slots ...xdpdispatch.Slot) error { + if _, err := os.Stat(filepath.Join(pinDir, "links")); errors.Is(err, os.ErrNotExist) { + return nil + } + dispatcher, err := xdpdispatch.Open(ctx, pinDir) + if err != nil { + return fmt.Errorf("xdpattach: open the node's XDP dispatcher: %w", err) + } + defer dispatcher.Close() //nolint:errcheck // our own descriptors + lock, err := dispatcher.Lock(ctx) + if err != nil { + return err + } + defer lock.Unlock() + for _, slot := range slots { + if err := lock.Clear(slot); err != nil { + return err + } + } + return nil +}