diff --git a/cmd/galactic-gateway/gateway.go b/cmd/galactic-gateway/gateway.go index 37d0f96d2..12230fd24 100644 --- a/cmd/galactic-gateway/gateway.go +++ b/cmd/galactic-gateway/gateway.go @@ -49,6 +49,21 @@ var gatewayDatapathKeepAlive struct { returnSet targetSet dispatcher *xdpdispatch.Dispatcher xmitDrops *xmitdrops.Counter + // modeClaim holds this host's XDP attach mode for the gateway until the + // process exits. + modeClaim *xdpmode.HostClaim +} + +// xdpModeComponent names the gateway in this host's XDP attach mode claims +// (xdpmode.Claim). +const xdpModeComponent = "galactic-gateway" + +// xdpConfig is how the gateway attaches its XDP programs: attach is one of +// the config.GatewayXDPAttach values, and mode is config.EnvXDPMode's +// setting. +type xdpConfig struct { + attach string + mode xdpmode.Setting } // setupGatewayDatapath loads and attaches the edge Maglev datapath to @@ -64,7 +79,7 @@ var gatewayDatapathKeepAlive struct { // // See installGateway for the attachment itself. func setupGatewayDatapath( - ctx context.Context, publicInterface string, internalInterfaces []string, srv6Address, attachMode string, + ctx context.Context, publicInterface string, internalInterfaces []string, srv6Address string, xdp xdpConfig, ipv4 *ipv4Forwarding, coverage *datapathCoverage, ) (gateway.Datapath, error) { encapSrc, err := netip.ParseAddr(srv6Address) @@ -72,7 +87,7 @@ func setupGatewayDatapath( return nil, fmt.Errorf("parse gateway SRv6 address %q: %w", srv6Address, err) } var datapath *gateway.KernelDatapath - err = installGateway(ctx, publicInterface, internalInterfaces, attachMode, ipv4, coverage, + err = installGateway(ctx, publicInterface, internalInterfaces, xdp, ipv4, coverage, func(objs *edgeprog.EdgedsrObjects) (edgemetrics.VPCAttribution, error) { dp, err := gateway.NewKernelDatapath(objs, encapSrc) if err != nil { @@ -95,11 +110,11 @@ func setupGatewayDatapath( // load-balancing slot is emptied and only the return slot is filled and // leased. See installGateway for the attachment itself. func setupReturnPath( - ctx context.Context, internalInterfaces []string, attachMode string, ipv4 *ipv4Forwarding, + ctx context.Context, internalInterfaces []string, xdp xdpConfig, ipv4 *ipv4Forwarding, coverage *datapathCoverage, ) (*gateway.KernelReturnPath, error) { var returnPath *gateway.KernelReturnPath - err := installGateway(ctx, "", internalInterfaces, attachMode, ipv4, coverage, + err := installGateway(ctx, "", internalInterfaces, xdp, ipv4, coverage, func(objs *edgeprog.EdgedsrObjects) (edgemetrics.VPCAttribution, error) { returnPath = gateway.NewKernelReturnPath(objs) return nil, nil @@ -138,7 +153,7 @@ func setupReturnPath( // (see edgedsr.c's edge_return comment). An empty list attaches nothing and // leaves the packet path unchanged. func installGateway( - ctx context.Context, publicInterface string, internalInterfaces []string, attachMode string, + ctx context.Context, publicInterface string, internalInterfaces []string, xdp xdpConfig, ipv4 *ipv4Forwarding, coverage *datapathCoverage, build func(*edgeprog.EdgedsrObjects) (edgemetrics.VPCAttribution, error), ) error { @@ -167,16 +182,19 @@ func installGateway( // One attach mode for every XDP attachment on the host, the public and // internal targets alike (xdpmode). A target that does not exist, or a // NIC whose driver cannot be read, fails startup rather than settling the - // mode without it. - modeDecision, err := xdpmode.Select(append(slices.Clone(targets), returnTargets...)...) + // mode without it, and so does the egress shard on this host attaching in + // the other mode. + modeDecision, err := xdpmode.Select(xdp.mode, append(slices.Clone(targets), returnTargets...)...) if err != nil { return fmt.Errorf("select the XDP attach mode for this host: %w", err) } - mode := modeDecision.Mode - slog.Info("Selected the XDP attach mode for this host", "mode", mode.String(), "reason", modeDecision.Reason) - for _, skipped := range modeDecision.Skipped { - slog.Warn("Left a NIC with no driver out of the XDP attach mode decision", "reason", skipped) + modeDecision.Log() + claim, err := xdpmode.Claim(ctx, xdpmode.ClaimDir, xdpModeComponent, modeDecision) + if err != nil { + return fmt.Errorf("claim the XDP attach mode for this host: %w", err) } + gatewayDatapathKeepAlive.modeClaim = claim + mode := modeDecision.Mode // 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 @@ -215,7 +233,7 @@ func installGateway( // 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 { + if xdp.attach == config.GatewayXDPAttachDispatch { leaseCtx, stopLeases := context.WithCancel(ctx) var leaseDone <-chan struct{} lease := xdpdispatch.NewLeaseMetrics(edgemetrics.Namespace) diff --git a/cmd/galactic-gateway/gateway_test.go b/cmd/galactic-gateway/gateway_test.go index c25150260..7d8f5a27a 100644 --- a/cmd/galactic-gateway/gateway_test.go +++ b/cmd/galactic-gateway/gateway_test.go @@ -16,7 +16,8 @@ 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", "dispatch", nil, + _, err := setupGatewayDatapath(context.Background(), "eth0", nil, "not-an-ip-address", + xdpConfig{attach: "dispatch"}, nil, 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 47b9d81f3..b1faf6bea 100644 --- a/cmd/galactic-gateway/root.go +++ b/cmd/galactic-gateway/root.go @@ -32,6 +32,7 @@ import ( "go.datum.net/galactic/internal/logging" "go.datum.net/galactic/internal/metadata" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" "go.datum.net/galactic/internal/plumbing/sysctl" ) @@ -187,7 +188,7 @@ func runCmd(cfg *config.GatewayConfig) error { }, } gwDatapath, err = setupGatewayDatapath(ctx, cfg.PublicInterface, cfg.InternalInterfaces, encapSrc, - cfg.XDPAttach, ipv4, coverage) + xdpConfig{attach: cfg.XDPAttach, mode: cfg.XDPModeSetting}, ipv4, coverage) if err != nil { return fmt.Errorf("setup edge gateway eBPF datapath: %w", err) } @@ -196,7 +197,8 @@ func runCmd(cfg *config.GatewayConfig) error { // is load-balanced here, but backend nodes can still send replies // through it, which only edge_return lets past connection tracking. turnOffDatapath(ctx, xdpdispatch.PinDir, xdpdispatch.SlotGatewayLB) - rp, err := setupReturnPath(ctx, cfg.InternalInterfaces, cfg.XDPAttach, ipv4, coverage) + rp, err := setupReturnPath(ctx, cfg.InternalInterfaces, + xdpConfig{attach: cfg.XDPAttach, mode: cfg.XDPModeSetting}, ipv4, coverage) if err != nil { return fmt.Errorf("setup edge gateway return path: %w", err) } @@ -328,6 +330,9 @@ func newRootCommand() *cobra.Command { 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().String(config.FlagXDPMode, xdpmode.SettingAutoValue, + "XDP attach mode for every Galactic XDP attachment on this host: \"auto\" decides from the NIC "+ + "drivers, \"native\" or \"generic\" forces that mode; galactic-nat on the host must resolve the same") 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") diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 24d63a6a9..530500fef 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -46,8 +46,15 @@ var natDatapathKeepAlive struct { objs *natprog.NatObjects set *xdpattach.Set dispatch *xdpdispatch.Dispatcher + // modeClaim holds this host's XDP attach mode for the shard until the + // process exits. + modeClaim *xdpmode.HostClaim } +// xdpModeComponent names the shard in this host's XDP attach mode claims +// (xdpmode.Claim). +const xdpModeComponent = "galactic-nat" + // natDatapath is this node's attached egress translation datapath, as // controller.EgressShardReconciler drives it (controller.EgressDatapath). // @@ -290,16 +297,19 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, // One attach mode for every XDP attachment on the host, shared with the // edge gateway's (xdpmode). An uplink that does not exist, or a NIC whose // driver cannot be read, fails startup rather than settling the mode - // without it. - modeDecision, err := xdpmode.Select(uplinks...) + // without it, and so does the edge gateway on this host attaching in the + // other mode. + modeDecision, err := xdpmode.Select(cfg.XDPModeSetting, uplinks...) if err != nil { return nil, fmt.Errorf("select the XDP attach mode for this host: %w", err) } - mode := modeDecision.Mode - slog.Info("Selected the XDP attach mode for this host", "mode", mode.String(), "reason", modeDecision.Reason) - for _, skipped := range modeDecision.Skipped { - slog.Warn("Left a NIC with no driver out of the XDP attach mode decision", "reason", skipped) + modeDecision.Log() + claim, err := xdpmode.Claim(ctx, xdpmode.ClaimDir, xdpModeComponent, modeDecision) + if err != nil { + return nil, fmt.Errorf("claim the XDP attach mode for this host: %w", err) } + natDatapathKeepAlive.modeClaim = claim + mode := modeDecision.Mode // Required for the FIB lookup in both the forward and return paths to // succeed on the interface the program actually runs on. The lookup uses diff --git a/cmd/galactic-nat/root.go b/cmd/galactic-nat/root.go index ca3f38c9c..6800876cb 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -30,6 +30,7 @@ import ( "go.datum.net/galactic/internal/logging" "go.datum.net/galactic/internal/metadata" "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" "go.datum.net/galactic/internal/plumbing/sysctl" ) @@ -253,6 +254,9 @@ func newRootCommand() *cobra.Command { 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\" is read as dispatch)") + cmd.Flags().String(config.FlagXDPMode, xdpmode.SettingAutoValue, + "XDP attach mode for every Galactic XDP attachment on this host: \"auto\" decides from the NIC "+ + "drivers, \"native\" or \"generic\" forces that mode; galactic-gateway on the host must resolve the same") 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/deploy/containerlab/README.md b/deploy/containerlab/README.md index 24cca5eeb..222d8c995 100644 --- a/deploy/containerlab/README.md +++ b/deploy/containerlab/README.md @@ -493,6 +493,27 @@ cd deploy/containerlab task deploy # build all images, apply host sysctls, deploy lab end-to-end ``` +### Generic XDP mode + +The lab's veths select native XDP, so by default Galactic's programs never run +in generic mode here. `XDP_MODE` forces a mode on every edge node by setting +`GALACTIC_XDP_MODE` on every `galactic-nat` and `galactic-gateway` DaemonSet +(see [XDP attach mode](../../docs/operations/xdp-attach-mode.md#forcing-a-mode)): + +```bash +task deploy XDP_MODE=generic # deploy the lab in generic mode +task lab:xdp-mode XDP_MODE=generic # switch a running lab +task verify:xdp-mode EXPECT=generic # every Galactic attachment shows xdpgeneric +task lab:xdp-mode # back to the drivers' choice, native here +task verify:xdp-mode EXPECT=native +``` + +`lab:xdp-mode` sets the gateways and the shard in each site together, since +the two refuse to start beside each other in different modes, and dispatch +links migrate in place, bouncing each uplink once. `deploy:galactic-nat` and +`deploy:galactic-gateway` apply `XDP_MODE` too, and remove the variable when +it is unset, so pass the same value on a redeploy to stay in generic mode. + To tear down and start fresh: ```bash @@ -530,6 +551,7 @@ task deploy | `deploy:bmp-collector` | Install the BMP collector on iad-worker3, where the route reflector streams to it | | `deploy:galactic-router` | Apply galactic-router DaemonSets and BGP CRs | | `deploy:galactic-gateway` | Install galactic-gateway on every edge node, with each site's VIP rules (after `deploy:scenarios`) | +| `lab:xdp-mode` | Set every edge node's Galactic XDP attach mode to `XDP_MODE` (`generic`, `native`, or empty for the drivers' choice) | | `deploy:scenarios` | Deploy all VPC test scenarios | | `deploy:ns10` | Deploy ns10 test VPC (IPv6-only, fd20 ULA) | | `deploy:ns20` | Deploy ns20 test VPC (dual-stack, fd20 ULA + IPv4) | @@ -545,6 +567,7 @@ task deploy | `verify:gateway-ingress-ipv4` | IPv4 TCP and UDP to each site's IPv4 VIP through every gateway node, translated to the IPv6-only backends | | `verify:gateway-backend-health` | Stops a dfw backend's listener; both gateways must drop it, keep it out across restarts, and take it back once it listens | | `verify:gateway-node-loss` | Take dfw-worker2's fabric links down: ingress through dfw-worker3 must pass, then through dfw-worker2 once restored (not in `verify`) | +| `verify:xdp-mode` | Check every Galactic XDP attachment on every edge node, and every pod's logged decision, is in `EXPECT` mode (not in `verify`) | | `verify:gateway-restart` | Restart dfw-worker2's gateway and shard in turn while the other carries traffic (#710) | | `verify:gateway-detach` | Turn dfw-worker2's gateway datapath off: ingress through it must fail and through dfw-worker3 pass, then through it pass (not in `verify`) | | `verify:nat-datapath` | Full egress round trip to the off-fabric host, IPv6 (NAT66) and IPv4 (NAT64) | diff --git a/deploy/containerlab/Taskfile.yaml b/deploy/containerlab/Taskfile.yaml index 928660157..f0736756c 100644 --- a/deploy/containerlab/Taskfile.yaml +++ b/deploy/containerlab/Taskfile.yaml @@ -6,6 +6,13 @@ vars: TOPO: sh: echo *.clab.yaml FABRIC_ROUTER_IMAGE: fabric-router:latest + # XDP_MODE sets GALACTIC_XDP_MODE on every galactic-nat and galactic-gateway + # DaemonSet: "generic" or "native" forces that XDP attach mode on every edge + # node, and empty (the default) or "auto" leaves it to the NIC drivers, + # native on the lab's veths. deploy, deploy:galactic-nat, + # deploy:galactic-gateway and lab:xdp-mode read it, as in + # `task deploy XDP_MODE=generic`. + XDP_MODE: '' tasks: default: @@ -413,12 +420,17 @@ tasks: "deploy:galactic-nat": desc: Install the NAT egress DaemonSet and shards cmds: - - ./scripts/deploy-galactic-nat.sh + - LAB_XDP_MODE={{.XDP_MODE}} ./scripts/deploy-galactic-nat.sh "deploy:galactic-gateway": desc: Install galactic-gateway on every edge node, with each site's VIP rules cmds: - - ./scripts/deploy-galactic-gateway.sh + - LAB_XDP_MODE={{.XDP_MODE}} ./scripts/deploy-galactic-gateway.sh + + "lab:xdp-mode": + desc: Switch every edge node's Galactic XDP attach mode to XDP_MODE (generic, native, or empty for auto) + cmds: + - LAB_XDP_MODE={{.XDP_MODE}} ./scripts/xdp-mode.sh "deploy:galactic-edge": desc: Run Galactic Edge on dfw's edge nodes (node agent, galactic-controller --edge, VPC objects) @@ -737,6 +749,14 @@ tasks: # #710: the gateway and the egress shard share each edge node's uplinks # through its XDP dispatcher, so restarting either must leave the other's # traffic flowing. + # Not part of `verify`: it needs the mode the lab was deployed in. + "verify:xdp-mode": + desc: Check every Galactic XDP attachment on every edge node runs in EXPECT mode (native or generic) + requires: + vars: [EXPECT] + cmds: + - ./scripts/verify-xdp-mode.sh {{.EXPECT}} + "verify:gateway-restart": desc: Restart dfw-worker2's gateway and shard in turn while the other carries traffic cmds: diff --git a/deploy/containerlab/scripts/deploy-galactic-gateway.sh b/deploy/containerlab/scripts/deploy-galactic-gateway.sh index c0da65057..3d548b142 100755 --- a/deploy/containerlab/scripts/deploy-galactic-gateway.sh +++ b/deploy/containerlab/scripts/deploy-galactic-gateway.sh @@ -80,6 +80,9 @@ for site in dfw sjc iad; do # rules. docker exec "${node}" kubectl -n galactic-system delete servicevipbindings \ -l "app.kubernetes.io/managed-by!=galactic-router" --ignore-not-found + # GALACTIC_XDP_MODE from XDP_MODE, on the shard too, so the two keep + # resolving one mode (lib.sh apply_xdp_mode). + apply_xdp_mode "${node}" for gw in ${GATEWAY_NODES[${site}]}; do docker exec "${node}" kubectl -n galactic-system rollout status daemonset "galactic-gateway-${gw}" --timeout=180s done diff --git a/deploy/containerlab/scripts/deploy-galactic-nat.sh b/deploy/containerlab/scripts/deploy-galactic-nat.sh index 19c46b984..a8ad0a77b 100755 --- a/deploy/containerlab/scripts/deploy-galactic-nat.sh +++ b/deploy/containerlab/scripts/deploy-galactic-nat.sh @@ -57,6 +57,9 @@ for site in dfw sjc iad; do copy_to "${node}" galactic-nat copy_nat_config "${node}" apply_k "${node}" "/galactic/resources/galactic-nat/${site}/" + # GALACTIC_XDP_MODE from XDP_MODE, on the gateways too, so the two keep + # resolving one mode (lib.sh apply_xdp_mode). + apply_xdp_mode "${node}" docker exec "${node}" kubectl -n galactic-system rollout status daemonset galactic-nat # Rollout means attached, not translating: a shard turns ready before its # identity is programmed. Programmed is what a tenant's egress route needs. diff --git a/deploy/containerlab/scripts/lib.sh b/deploy/containerlab/scripts/lib.sh index 6faf912f1..9e3fcbe2c 100755 --- a/deploy/containerlab/scripts/lib.sh +++ b/deploy/containerlab/scripts/lib.sh @@ -73,6 +73,43 @@ apply_f() { docker exec -i "${node}" kubectl apply -f "${path}" } +# apply_xdp_mode NODE sets GALACTIC_XDP_MODE, from LAB_XDP_MODE (the +# Taskfile's XDP_MODE), on every DaemonSet in NODE's cluster that attaches +# Galactic XDP programs: galactic-nat and each edge node's +# galactic-gateway-. Empty or "auto" removes the variable, so the +# processes decide from the NIC drivers and the lab's veths run native, as +# before the option existed; "native" or "generic" forces that mode. Every +# such DaemonSet is set together, since a gateway and a shard on one node +# refuse to start beside each other in different modes (xdpmode.Claim), and +# the call waits for each to roll out. +# +# kubectl apply -k leaves an env var set this way in place, so every deploy +# calls this, removing the variable again when XDP_MODE is unset. +apply_xdp_mode() { + local node="$1" mode="${LAB_XDP_MODE:-}" ds + local -a daemonsets + case "${mode}" in + "" | auto | native | generic) ;; + *) + echo "error: XDP_MODE must be empty, auto, native or generic, got \"${mode}\"" >&2 + return 1 + ;; + esac + mapfile -t daemonsets < <(docker exec "${node}" kubectl -n galactic-system get daemonsets \ + -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' | grep -E '^galactic-(nat|gateway-.+)$') + for ds in "${daemonsets[@]}"; do + if [ -z "${mode}" ] || [ "${mode}" = auto ]; then + docker exec "${node}" kubectl -n galactic-system set env "daemonset/${ds}" -c 'galactic-*' GALACTIC_XDP_MODE- + else + docker exec "${node}" kubectl -n galactic-system set env "daemonset/${ds}" -c 'galactic-*' \ + "GALACTIC_XDP_MODE=${mode}" + fi + done + for ds in "${daemonsets[@]}"; do + docker exec "${node}" kubectl -n galactic-system rollout status "daemonset/${ds}" --timeout=300s + done +} + ensure_namespace() { local node="$1" ns="$2" docker exec "${node}" sh -c "kubectl create namespace ${ns} --dry-run=client -o yaml | kubectl apply -f -" diff --git a/deploy/containerlab/scripts/verify-xdp-mode.sh b/deploy/containerlab/scripts/verify-xdp-mode.sh new file mode 100755 index 000000000..04335bfcd --- /dev/null +++ b/deploy/containerlab/scripts/verify-xdp-mode.sh @@ -0,0 +1,105 @@ +#!/bin/bash +# verify-xdp-mode.sh EXPECT — Check that every Galactic XDP attachment on +# every edge node runs in EXPECT mode, native or generic: the shared +# dispatcher (xdp_dispatch) and any program galactic-gateway or galactic-nat +# attached directly (edge_lb, edge_return, nat_ingress). It reads the mode +# from the kernel, as `ip -d link show` reports it (xdp or xdpgeneric), and +# fails on any attachment in the other mode or a node with none at all. It +# then checks that every galactic-gateway and galactic-nat pod logged the +# same mode, and prints the source each logged (driver or forced). +# +# The lab's own pass-through program, on the transit routers and the compute +# nodes' veths, is not Galactic's and is not checked. +set -euo pipefail + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +source "${SCRIPT_DIR}/lib.sh" + +EXPECT="${1:-}" +case "${EXPECT}" in + native | generic) ;; + *) + echo "usage: $0 native|generic" >&2 + exit 2 + ;; +esac + +# check_node NODE prints NODE's Galactic XDP attachments, one per line, and +# fails unless there is at least one and every one is in EXPECT mode. +check_node() { + local node="$1" + docker exec "${node}" ip -j -d link show | python3 -I -c "${CHECK_LINKS}" "${node}" "${EXPECT}" +} + +# CHECK_LINKS reads `ip -j -d link show` on stdin. IFLA_XDP_ATTACHED is 1 for +# driver (native), 2 for generic (SKB), 3 for offload and 4 for several. +read -r -d '' CHECK_LINKS <<'PY' || true +import json, sys +node, expect = sys.argv[1], sys.argv[2] +galactic = {"xdp_dispatch", "edge_lb", "edge_return", "nat_ingress"} +modes = {1: "native", 2: "generic", 3: "offload", 4: "multi"} +seen = bad = 0 +for link in json.load(sys.stdin): + xdp = link.get("xdp") + if not xdp: + continue + if "prog" in xdp: + progs = [xdp["prog"]] + else: + progs = [a["prog"] for a in xdp.get("attached", []) if "prog" in a] + names = {p.get("name", "") for p in progs} + if not names & galactic: + continue + seen += 1 + mode = modes.get(xdp.get("mode"), str(xdp.get("mode"))) + ok = mode == expect + bad += not ok + verdict = "ok" if ok else "WRONG MODE" + print(" %s %s: %s %s %s" % (node, link["ifname"], mode, ",".join(sorted(names)), verdict)) +if seen == 0: + print(" %s: no Galactic XDP attachment found" % node) + sys.exit(1) +sys.exit(1 if bad else 0) +PY + +# check_logs CONTROL_PLANE checks the latest XDP attach mode decision every +# galactic-gateway and galactic-nat pod in that cluster logged. +check_logs() { + local cp="$1" pod line rc=0 + for pod in $(docker exec "${cp}" kubectl -n galactic-system get pods -o name | + grep -E '^pod/galactic-(nat|gateway)-'); do + line=$(docker exec "${cp}" kubectl -n galactic-system logs "${pod}" | + grep 'Selected the XDP attach mode for this host' | tail -n1 || true) + if [ -z "${line}" ]; then + echo " ${cp} ${pod#pod/}: logged no XDP attach mode decision" + rc=1 + continue + fi + if grep -Eq "\"mode\": ?\"${EXPECT}\"|mode=${EXPECT}( |$)" <<<"${line}"; then + echo " ${pod#pod/}: mode ${EXPECT}, source $(grep -Eo '"source": ?"[a-z]+"|source=[a-z]+' <<<"${line}" | + tr -d '"' | grep -Eo '[a-z]+$')" + else + echo " ${pod#pod/}: WRONG MODE: ${line}" + rc=1 + fi + done + return "${rc}" +} + +rc=0 +for site in dfw sjc iad; do + cp=$(control_plane "${site}") + echo "--- ${site}: XDP attachments (want ${EXPECT})" + for node in $(docker exec "${cp}" kubectl get nodes -l galactic.datumapis.com/node=edge \ + -o jsonpath='{.items[*].metadata.name}'); do + check_node "${node}" || rc=1 + done + echo "--- ${site}: logged decisions" + check_logs "${cp}" || rc=1 +done + +if [ "${rc}" -ne 0 ]; then + echo "FAIL: not every Galactic XDP attachment runs in ${EXPECT} mode" + exit 1 +fi +echo "PASS: every Galactic XDP attachment runs in ${EXPECT} mode" diff --git a/deploy/containerlab/scripts/xdp-mode.sh b/deploy/containerlab/scripts/xdp-mode.sh new file mode 100755 index 000000000..ba6aa9b70 --- /dev/null +++ b/deploy/containerlab/scripts/xdp-mode.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# xdp-mode.sh — Switch a running lab's Galactic XDP attach mode to +# LAB_XDP_MODE (the Taskfile's XDP_MODE): "generic" or "native" forces it on +# every edge node, and empty or "auto" returns the lab to the drivers' +# choice, native on the lab's veths. Sets GALACTIC_XDP_MODE on every +# galactic-nat and galactic-gateway DaemonSet in each site together and waits +# for them to roll out (lib.sh apply_xdp_mode). Dispatch-mode links migrate in +# place, bouncing each uplink once. A later deploy:galactic-nat or +# deploy:galactic-gateway reapplies XDP_MODE, so pass the same value there or +# the lab returns to the drivers' choice. +set -euo pipefail + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +source "${SCRIPT_DIR}/lib.sh" + +for site in dfw sjc iad; do + node=$(control_plane "${site}") + echo "Setting the XDP attach mode in ${site} to ${LAB_XDP_MODE:-auto}..." + apply_xdp_mode "${node}" +done + +echo "Done." diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index 4b90e38fe..f4cf0c786 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -11,23 +11,24 @@ flags, or a combination of both (CLI flags take precedence), with the Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_GATEWAY` prefix and the standard `--zap-*` flags; see [Logging](../observability/logging.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` | — | While enabled | -| SRv6 address | `GALACTIC_GATEWAY_SRV6_ADDRESS` | `--gateway-srv6-address` | Derived | No | -| 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 | -| IPv4 VIPs | `GALACTIC_GATEWAY_IPV4_VIPS` | `--gateway-ipv4-vips` | `false` | No | -| Backend health | `GALACTIC_GATEWAY_BACKEND_HEALTH` | `--gateway-backend-health` | `false` | No | -| Local delivery | `GALACTIC_GATEWAY_LOCAL_DELIVERY` | `--gateway-local-delivery` | `false` | No | -| Procfs sysctl root | `GALACTIC_GATEWAY_PROC_SYS_PATH` | `--gateway-proc-sys-path` | `/proc/sys` | No | -| Project services | `GALACTIC_GATEWAY_PROJECT_SERVICES` | `--gateway-project-services` | `false` | No | -| Gateway namespace | `GALACTIC_GATEWAY_NAMESPACE` | `--gateway-namespace` | — | With project services | -| Project VIP prefixes | `GALACTIC_GATEWAY_PROJECT_VIP_PREFIXES` | `--gateway-project-vip-prefixes` | — | With project services | -| 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` | Derived | No | +| Internal interfaces | `GALACTIC_GATEWAY_INTERNAL_INTERFACES` | `--gateway-internal-interfaces` | — | No | +| XDP attach mode | `GALACTIC_GATEWAY_XDP_ATTACH` | `--gateway-xdp-attach` | `dispatch` | No | +| XDP native or generic | `GALACTIC_XDP_MODE` | `--xdp-mode` | `auto` | No | +| Datapath enabled | `GALACTIC_GATEWAY_DATAPATH_ENABLED` | `--gateway-datapath-enabled` | `true` | No | +| IPv4 VIPs | `GALACTIC_GATEWAY_IPV4_VIPS` | `--gateway-ipv4-vips` | `false` | No | +| Backend health | `GALACTIC_GATEWAY_BACKEND_HEALTH` | `--gateway-backend-health` | `false` | No | +| Local delivery | `GALACTIC_GATEWAY_LOCAL_DELIVERY` | `--gateway-local-delivery` | `false` | No | +| Procfs sysctl root | `GALACTIC_GATEWAY_PROC_SYS_PATH` | `--gateway-proc-sys-path` | `/proc/sys` | No | +| Project services | `GALACTIC_GATEWAY_PROJECT_SERVICES` | `--gateway-project-services` | `false` | No | +| Gateway namespace | `GALACTIC_GATEWAY_NAMESPACE` | `--gateway-namespace` | — | With project services | +| Project VIP prefixes | `GALACTIC_GATEWAY_PROJECT_VIP_PREFIXES` | `--gateway-project-vip-prefixes` | — | With project services | +| 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, @@ -38,6 +39,13 @@ 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](packet-paths.md#sharing-the-xdp-hook-xdpdispatch). +`GALACTIC_XDP_MODE` has no `GALACTIC_GATEWAY` prefix. `galactic-nat` reads the +same name, and both must resolve the same mode on a host. `auto` decides native +or generic from the host's NIC drivers, and `native` or `generic` forces that +mode. A process that resolves a different mode from a live `galactic-nat` on +the same host fails at startup. See +[Forcing a mode](../operations/xdp-attach-mode.md#forcing-a-mode). + `GALACTIC_GATEWAY_IPV4_VIPS=true` serves IPv4 VIPs on this node. It is off by default and is set per gateway node. It does three things: diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index fed611a87..23f288985 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -12,16 +12,17 @@ flags, or a combination of both (CLI flags take precedence), with the Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_NAT` prefix and the standard `--zap-*` flags; see [Logging](../observability/logging.md). -| Option | Environment Variable | CLI Flag | Default | Required | -| ------------------ | -------------------------------- | ------------------------- | ------------- | -------- | -| Node name | `GALACTIC_NAT_NODE_NAME` | `--node-name` | — | Yes | -| Uplink interfaces | `GALACTIC_NAT_UPLINK_INTERFACES` | `--nat-uplink-interfaces` | auto-detected | No | -| XDP attach mode | `GALACTIC_NAT_XDP_ATTACH` | `--nat-xdp-attach` | `direct` | No | -| Datapath enabled | `GALACTIC_NAT_DATAPATH_ENABLED` | `--nat-datapath-enabled` | `true` | No | -| Echo responder | `GALACTIC_NAT_ECHO_RESPONDER` | `--nat-echo-responder` | `false` | No | -| Procfs sysctl root | `GALACTIC_NAT_PROC_SYS_PATH` | `--nat-proc-sys-path` | `/proc/sys` | No | -| Metrics port | `GALACTIC_NAT_METRICS_PORT` | `--metrics-port` | `9182` | No | -| gRPC health port | `GALACTIC_NAT_GRPC_HEALTH_PORT` | `--grpc-health-port` | `5182` | No | +| Option | Environment Variable | CLI Flag | Default | Required | +| --------------------- | -------------------------------- | ------------------------- | ------------- | -------- | +| Node name | `GALACTIC_NAT_NODE_NAME` | `--node-name` | — | Yes | +| Uplink interfaces | `GALACTIC_NAT_UPLINK_INTERFACES` | `--nat-uplink-interfaces` | auto-detected | No | +| XDP attach mode | `GALACTIC_NAT_XDP_ATTACH` | `--nat-xdp-attach` | `direct` | No | +| XDP native or generic | `GALACTIC_XDP_MODE` | `--xdp-mode` | `auto` | No | +| Datapath enabled | `GALACTIC_NAT_DATAPATH_ENABLED` | `--nat-datapath-enabled` | `true` | No | +| Echo responder | `GALACTIC_NAT_ECHO_RESPONDER` | `--nat-echo-responder` | `false` | No | +| Procfs sysctl root | `GALACTIC_NAT_PROC_SYS_PATH` | `--nat-proc-sys-path` | `/proc/sys` | No | +| Metrics port | `GALACTIC_NAT_METRICS_PORT` | `--metrics-port` | `9182` | No | +| gRPC health port | `GALACTIC_NAT_GRPC_HEALTH_PORT` | `--grpc-health-port` | `5182` | No | `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 @@ -106,6 +107,15 @@ 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. +**`--xdp-mode` / `GALACTIC_XDP_MODE`** +Whether every XDP attachment on the host runs in native or generic mode: +`auto` (the default) decides from the host's NIC drivers, and `native` or +`generic` forces that mode. It has no `GALACTIC_NAT` prefix: `galactic-gateway` +reads the same name, and both must resolve the same mode on a host. A shard +that resolves a different mode from a live `galactic-gateway` on the same host +fails at startup. Any other value fails validation. See +[Forcing a mode](../operations/xdp-attach-mode.md#forcing-a-mode). + **`--nat-xdp-attach` / `GALACTIC_NAT_XDP_ATTACH`** 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 diff --git a/docs/operations/xdp-attach-mode.md b/docs/operations/xdp-attach-mode.md index 0ff01e194..830ef76af 100644 --- a/docs/operations/xdp-attach-mode.md +++ b/docs/operations/xdp-attach-mode.md @@ -6,10 +6,15 @@ process at startup by `internal/plumbing/ebpf/xdpmode`. That covers `nat_ingress`, and the shared dispatcher (`xdp_dispatch`) both of them use in dispatch mode. -| Host | Mode | Shown by `ip -d link show` as | -| --------------------------- | --------------- | ----------------------------- | -| Any NIC driven by `bnxt_en` | generic (SKB) | `xdpgeneric` | -| Every other host | native (driver) | `xdp` | +| Host | Mode | Shown by `ip -d link show` as | +| ---------------------------------- | --------------- | ----------------------------- | +| `GALACTIC_XDP_MODE=generic` | generic (SKB) | `xdpgeneric` | +| `GALACTIC_XDP_MODE=native` | native (driver) | `xdp` | +| Unset: any NIC driven by `bnxt_en` | generic (SKB) | `xdpgeneric` | +| Unset: every other host | native (driver) | `xdp` | + +`GALACTIC_XDP_MODE` is unset by default, and the drivers decide. See +[Forcing a mode](#forcing-a-mode). ## Why bnxt_en hosts run generic mode @@ -46,17 +51,90 @@ from #779. driver traffic, so it is left out of the decision with a warning naming it. - **The decision is logged.** Each process logs - `Selected the XDP attach mode for this host` with `mode` and `reason`. The - reason names the matching NICs. + `Selected the XDP attach mode for this host` with `mode`, `source` and + `reason`. `source` is `driver` or `forced`. For a driver decision the reason + names the matching NICs; for a forced one it names the setting and the mode + the drivers alone would select. - **The mode is fixed for the life of the process.** A NIC hot-added later - doesn't change it, so restart both pods after adding one. + doesn't change it, so restart both pods after adding one. Restart them + together: the [host-wide claim](#one-mode-per-host) stops the first one + restarted while the other still runs in the old mode. - **The latest decision is recorded on the host.** Each dispatch-mode process that attaches records the mode it selected in a pinned record beside the dispatcher (`/sys/fs/bpf/galactic-xdp/host_mode`). A datapath being turned off only clears its slots and records nothing. A process whose mode no longer matches the record doesn't move a link back. It logs the error, reports its interfaces uncovered, and stays not-ready until it is restarted. Two - processes that disagree therefore never move one link back and forth. + processes that disagree therefore never move one link back and forth. Since + the [host-wide claim](#one-mode-per-host), two live processes that disagree + no longer both start, so this record matters only beside a release older + than claims. + +## Forcing a mode + +`GALACTIC_XDP_MODE` (flag `--xdp-mode`) forces the mode of every Galactic XDP +attachment on a host. Its use is testing, such as running a host without +`bnxt_en` in generic mode. + +| Value | Mode | Logged `source` | +| --------------- | ---------------------------- | --------------- | +| unset or `auto` | decided from the NIC drivers | `driver` | +| `native` | native | `forced` | +| `generic` | generic | `forced` | + +- **One name for every component.** `galactic-gateway` and `galactic-nat` + read the same variable, with no component prefix. Set it to the same value + on both DaemonSets. +- **Any other value fails startup.** The error names the variable and the + accepted values. +- **A forced mode skips no check.** A missing target or an unreadable driver + still fails startup. +- **Forcing `native` on a `bnxt_en` host is allowed but warned about.** Each + process logs `Forced native XDP on NICs whose native XDP redirect stalls + receive queues (#673)` with the NICs, and those NICs' receive queues can + stall again. +- **Changing it moves a running node.** It works like any other mode change: + direct mode reattaches on restart, and dispatch mode + [migrates in place](#moving-a-running-node-to-the-selected-mode), bouncing + each uplink once. Change both DaemonSets together. + +## One mode per host + +Each process that attaches claims the host's mode before it attaches anything. +That covers direct and dispatch mode, and every mode source. + +1. It records its mode and source under + `/sys/fs/bpf/galactic-xdp/modes//`, as a directory named + `_` such as `generic_forced`. +2. It holds a lock on that directory until it exits. The kernel drops the lock + when the process ends, however it ends. +3. Before recording, it reads every other component's claim. If one is held + by a live process in the other mode, it fails startup with + `another Galactic XDP component on this host attaches in a different XDP + mode`, naming both components, modes and sources. +4. A claim whose process has exited is stale, and the next claim replaces it. + +So two components on one host never attach in mixed modes, whatever each +decision came from. That includes a `bnxt_en` NIC hot-added while one pod +runs: the pod restarted next, now deciding generic, fails beside the other +pod's native claim until the other restarts too. + +Before claims, the later process migrated the dispatcher links it covers and +the earlier one went not-ready. Interfaces only the earlier one covered, such +as the gateway's internal interfaces, stayed in the old mode, so the host was +mixed until the earlier process restarted. + +When both DaemonSets roll to a new mode together, the pod that starts first +may fail once beside the other's old pod. Its restart succeeds once the other +pod is replaced. + +**Upgrading from a release without claims.** An old pod writes no claim, so +it blocks nothing, and a new pod beside it starts. The dispatcher's +`host_mode` record from the old release is not a claim and is never read as +one. The new pod's dispatcher overwrites it, and the +[migration rules](#moving-a-running-node-to-the-selected-mode) apply as +before. Roll out the release before setting `GALACTIC_XDP_MODE`, so every pod +on the host makes a claim. ## Attach, readiness and coverage @@ -137,8 +215,9 @@ capacity figures. Every uplink bounces once, so do this in a maintenance window. - **In direct mode, rolling back and restarting is enough.** -- **There is no override variable.** The mode follows the host's NICs, so - every datapath on a host always agrees. +- **Unset `GALACTIC_XDP_MODE` before rolling back past it.** Older releases + ignore it, so a host forced generic without `bnxt_en` would return to + native. Older releases also ignore claims. ## Detaching the dispatcher @@ -182,10 +261,12 @@ dispatcher again. ## Validation -On a host with a `bnxt_en` NIC after the release reaches it: +On a host with a `bnxt_en` NIC after the release reaches it (in the +containerlab lab, `task lab:xdp-mode XDP_MODE=generic` and +`task verify:xdp-mode EXPECT=generic` cover steps 1 and 2): 1. Both pods log `Selected the XDP attach mode for this host` with - `mode=generic` and a reason naming the `bnxt_en` NICs. + `mode=generic`, `source=driver` and a reason naming the `bnxt_en` NICs. 2. `ip -d link show` on the node shows `xdpgeneric` with `prog/xdp ... name xdp_dispatch` on every bond member, and nothing in native mode. diff --git a/internal/config/config.go b/internal/config/config.go index 015f9128c..f8e031251 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -11,6 +11,10 @@ package config import ( "os" "strings" + + "github.com/spf13/pflag" + + "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" ) // --- Shared defaults ------------------------------------------------------- @@ -66,6 +70,34 @@ const ( KeyGRPCHealthPort = "grpc_health_port" ) +// --- Shared XDP attach mode setting --------------------------------------- + +// EnvXDPMode forces the XDP attach mode (xdpmode) of every Galactic XDP +// component on a host: "native" or "generic". Optional, defaulting to "auto", +// which decides from the host's NIC drivers. Unlike every other setting it +// carries no component prefix: galactic-gateway and galactic-nat read the same +// name, since every XDP attachment on a host must use one mode, and each +// refuses to start beside the other in a different mode (xdpmode.Claim). +const EnvXDPMode = xdpmode.SettingEnv + +// FlagXDPMode is EnvXDPMode's CLI flag, the same for each component. +const FlagXDPMode = "xdp-mode" + +// resolveXDPMode returns EnvXDPMode's value as a component reads it: flag +// when the CLI flag was set, then the environment variable, then auto. It +// reads the variable itself rather than through Viper, whose environment +// prefix would also accept a component-prefixed spelling such as +// GALACTIC_GATEWAY_XDP_MODE, and the setting has exactly one name. +func resolveXDPMode(flags *pflag.FlagSet) string { + if flags != nil && flags.Changed(FlagXDPMode) { + return flags.Lookup(FlagXDPMode).Value.String() + } + if v, ok := os.LookupEnv(EnvXDPMode); ok { + return v + } + return xdpmode.SettingAutoValue +} + // --- Shared gRPC health services ------------------------------------------- // GRPCReadinessService is the gRPC health service an XDP datapath binary diff --git a/internal/config/gateway.go b/internal/config/gateway.go index dee0c205d..440265558 100644 --- a/internal/config/gateway.go +++ b/internal/config/gateway.go @@ -12,6 +12,8 @@ import ( "github.com/spf13/pflag" "github.com/spf13/viper" + + "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" ) // --- Gateway defaults -------------------------------------------------- @@ -163,6 +165,9 @@ const ( type GatewayConfig struct { v *viper.Viper prefix string + // flags is the flag set BindFlags bound, for the settings Viper does not + // resolve. Nil until then. + flags *pflag.FlagSet // Resolved fields. NodeName string @@ -183,6 +188,11 @@ type GatewayConfig struct { // XDPAttach is one of the GatewayXDPAttach values, from EnvGatewayXDPAttach. XDPAttach string + // XDPMode is EnvXDPMode as given, and XDPModeSetting its value, parsed by + // Validate. + XDPMode string + XDPModeSetting xdpmode.Setting + // DatapathEnabled is EnvGatewayDatapathEnabled. DatapathEnabled bool @@ -266,6 +276,7 @@ func (c *GatewayConfig) BindFlags(flags *pflag.FlagSet) { {"gateway-namespace", keyGatewayNamespace}, {"gateway-project-vip-prefixes", "project_vip_prefixes"}, } + c.flags = flags for _, b := range bindings { if flags.Changed(b.flag) { c.v.Set(b.key, flags.Lookup(b.flag).Value.String()) @@ -286,6 +297,7 @@ func (c *GatewayConfig) readFields() { c.InternalInterfaces = splitCommaList(c.v.GetString("internal_interfaces")) c.SRv6Address = c.v.GetString("srv6_address") c.XDPAttach = c.v.GetString("xdp_attach") + c.XDPMode = resolveXDPMode(c.flags) c.DatapathEnabled = c.v.GetBool("datapath_enabled") c.IPv4VIPs = c.v.GetBool("ipv4_vips") c.BackendHealth = c.v.GetBool("backend_health") @@ -320,6 +332,11 @@ func (c *GatewayConfig) Validate() error { return fmt.Errorf("%s must be %q or %q, got %q", EnvGatewayXDPAttach, GatewayXDPAttachDispatch, GatewayXDPAttachDirect, c.XDPAttach) } + setting, err := xdpmode.ParseSetting(c.XDPMode) + if err != nil { + return err + } + c.XDPModeSetting = setting if c.MetricsPort < 1 || c.MetricsPort > 65535 { return errors.New(errMetricsPortRange) } diff --git a/internal/config/nat.go b/internal/config/nat.go index 7e18e0b46..3e9a3695d 100644 --- a/internal/config/nat.go +++ b/internal/config/nat.go @@ -10,6 +10,8 @@ import ( "github.com/spf13/pflag" "github.com/spf13/viper" + + "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" ) // --- NAT defaults ----------------------------------------------------- @@ -116,6 +118,9 @@ const ( type NATConfig struct { v *viper.Viper prefix string + // flags is the flag set BindFlags bound, for the settings Viper does not + // resolve. Nil until then. + flags *pflag.FlagSet // Resolved fields. NodeName string @@ -130,6 +135,11 @@ type NATConfig struct { // EnvNATXDPAttach. XDPAttach string + // XDPMode is EnvXDPMode as given, and XDPModeSetting its value, parsed by + // Validate. + XDPMode string + XDPModeSetting xdpmode.Setting + // XDPAttachDeprecated is set when EnvNATXDPAttach named the retired chain // mode, which XDPAttach reads as dispatch, so the caller can warn. XDPAttachDeprecated bool @@ -185,6 +195,7 @@ func (c *NATConfig) BindFlags(flags *pflag.FlagSet) { {"nat-echo-responder", "echo_responder"}, {"nat-proc-sys-path", "proc_sys_path"}, } + c.flags = flags for _, b := range bindings { if flags.Changed(b.flag) { c.v.Set(b.key, flags.Lookup(b.flag).Value.String()) @@ -207,6 +218,7 @@ func (c *NATConfig) readFields() { if c.XDPAttachDeprecated { c.XDPAttach = NATXDPAttachDispatch } + c.XDPMode = resolveXDPMode(c.flags) c.DatapathEnabled = c.v.GetBool("datapath_enabled") c.EchoResponder = c.v.GetBool("echo_responder") c.ProcSysPath = c.v.GetString("proc_sys_path") @@ -229,5 +241,10 @@ func (c *NATConfig) Validate() error { return fmt.Errorf("%s must be %q or %q, got %q", EnvNATXDPAttach, NATXDPAttachDirect, NATXDPAttachDispatch, c.XDPAttach) } + setting, err := xdpmode.ParseSetting(c.XDPMode) + if err != nil { + return err + } + c.XDPModeSetting = setting return nil } diff --git a/internal/config/xdpmode_test.go b/internal/config/xdpmode_test.go new file mode 100644 index 000000000..5b08defb6 --- /dev/null +++ b/internal/config/xdpmode_test.go @@ -0,0 +1,126 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package config + +import ( + "strings" + "testing" + + "github.com/spf13/pflag" + + "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" +) + +// xdpModeResolver builds one component's resolver for the XDP mode tests, +// with the flag bound when flag is non-empty, and returns its validated +// setting. +type xdpModeResolver struct { + name string + setEnv func(t *testing.T) + resolve func(flag string) (xdpmode.Setting, string, error) +} + +func xdpModeResolvers() []xdpModeResolver { + return []xdpModeResolver{ + { + name: "galactic-gateway", + setEnv: func(t *testing.T) { + t.Setenv(EnvGatewayNodeName, testEnvNode) + t.Setenv(EnvGatewayPublicInterface, testGatewayIface) + t.Setenv(EnvGatewaySRv6Address, testGatewaySRv6) + }, + resolve: func(flag string) (xdpmode.Setting, string, error) { + cfg := NewGatewayConfig() + cfg.BindFlags(xdpModeFlags(flag)) + err := cfg.Validate() + return cfg.XDPModeSetting, cfg.XDPMode, err + }, + }, + { + name: "galactic-nat", + setEnv: func(t *testing.T) { t.Setenv(EnvNATNodeName, testNATNodeName) }, + resolve: func(flag string) (xdpmode.Setting, string, error) { + cfg := NewNATConfig() + cfg.BindFlags(xdpModeFlags(flag)) + err := cfg.Validate() + return cfg.XDPModeSetting, cfg.XDPMode, err + }, + }, + } +} + +// xdpModeFlags returns a flag set holding --xdp-mode, set to value when value +// is non-empty. +func xdpModeFlags(value string) *pflag.FlagSet { + flags := pflag.NewFlagSet("test", pflag.ContinueOnError) + flags.String(FlagXDPMode, xdpmode.SettingAutoValue, "") + if value != "" { + _ = flags.Set(FlagXDPMode, value) + } + return flags +} + +// TestXDPMode covers the shared setting in every component that reads it: +// auto unless set, the one unprefixed variable forcing either mode, the flag +// winning over it, and anything else refused at startup. +func TestXDPMode(t *testing.T) { + tests := []struct { + name string + env string + flag string + want xdpmode.Setting + wantErr bool + }{ + {name: "unset", want: xdpmode.SettingAuto}, + {name: "env auto", env: "auto", want: xdpmode.SettingAuto}, + {name: "env generic", env: "generic", want: xdpmode.SettingGeneric}, + {name: "env native", env: "native", want: xdpmode.SettingNative}, + {name: "flag wins over env", env: "native", flag: "generic", want: xdpmode.SettingGeneric}, + {name: "invalid env", env: "skb", wantErr: true}, + {name: "invalid flag", flag: "driver", wantErr: true}, + } + for _, r := range xdpModeResolvers() { + for _, tt := range tests { + t.Run(r.name+"/"+tt.name, func(t *testing.T) { + r.setEnv(t) + if tt.env != "" { + t.Setenv(EnvXDPMode, tt.env) + } + got, raw, err := r.resolve(tt.flag) + if tt.wantErr { + if err == nil || !strings.Contains(err.Error(), EnvXDPMode) { + t.Fatalf("Validate() = %v, want an error naming %s", err, EnvXDPMode) + } + return + } + if err != nil { + t.Fatalf("Validate(): %v", err) + } + if got != tt.want { + t.Errorf("XDPModeSetting = %s (from %q), want %s", got, raw, tt.want) + } + }) + } + } +} + +// TestXDPModeIgnoresPrefixedNames shows the setting is one host-wide name: a +// component-prefixed spelling is not read. +func TestXDPModeIgnoresPrefixedNames(t *testing.T) { + t.Setenv("GALACTIC_GATEWAY_XDP_MODE", "generic") + t.Setenv("GALACTIC_NAT_XDP_MODE", "generic") + for _, r := range xdpModeResolvers() { + t.Run(r.name, func(t *testing.T) { + r.setEnv(t) + got, _, err := r.resolve("") + if err != nil { + t.Fatalf("Validate(): %v", err) + } + if got != xdpmode.SettingAuto { + t.Errorf("XDPModeSetting = %s, want auto", got) + } + }) + } +} diff --git a/internal/plumbing/ebpf/xdpdispatch/claim_test.go b/internal/plumbing/ebpf/xdpdispatch/claim_test.go new file mode 100644 index 000000000..3e40ee9ba --- /dev/null +++ b/internal/plumbing/ebpf/xdpdispatch/claim_test.go @@ -0,0 +1,59 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpdispatch + +import ( + "context" + "errors" + "path/filepath" + "testing" + + "go.datum.net/galactic/internal/plumbing/ebpf/xdpmode" +) + +// TestClaim_OnBpffsBesideTheDispatcher runs xdpmode.Claim on a real bpffs, in +// the claim directory under the dispatcher's own pins, as galactic-gateway and +// galactic-nat do. +// +// It also covers an upgrade. A dispatcher opened in native mode by a release +// older than claims leaves a host_mode record and no claim. A new component +// forced to generic claims past it, since that record is never read as a +// claim, and its own Open then overwrites the record as before, so the +// dispatcher's migration rules are unchanged. +func TestClaim_OnBpffsBesideTheDispatcher(t *testing.T) { + dir := testPinDir(t) + claimDir := filepath.Join(dir, "modes") + + old := openDispatcherInMode(t, dir, xdpmode.Native) + if recorded, ok, err := old.recordedHostMode(); err != nil || !ok || recorded != xdpmode.Native { + t.Fatalf("host mode before the upgrade = %s, %v, %v; want native", recorded, ok, err) + } + + forced := xdpmode.Decision{Mode: xdpmode.Generic, Source: xdpmode.SourceForced, Reason: "test"} + nat, err := xdpmode.Claim(context.Background(), claimDir, "galactic-nat", forced) + if err != nil { + t.Fatalf("Claim beside a dispatcher with no claims: %v", err) + } + t.Cleanup(func() { _ = nat.Release() }) + + upgraded := openDispatcherInMode(t, dir, xdpmode.Generic) + if recorded, ok, err := upgraded.recordedHostMode(); err != nil || !ok || recorded != xdpmode.Generic { + t.Errorf("host mode after the upgrade = %s, %v, %v; want generic", recorded, ok, err) + } + + driver := xdpmode.Decision{Mode: xdpmode.Native, Source: xdpmode.SourceDriver, Reason: "test"} + if _, err := xdpmode.Claim(context.Background(), claimDir, "galactic-gateway", driver); !errors.Is(err, + xdpmode.ErrHostModeConflict) { + t.Errorf("Claim in the other mode on bpffs: got %v, want ErrHostModeConflict", err) + } + if err := nat.Release(); err != nil { + t.Fatal(err) + } + gateway, err := xdpmode.Claim(context.Background(), claimDir, "galactic-gateway", driver) + if err != nil { + t.Fatalf("Claim after the peer released: %v", err) + } + _ = gateway.Release() +} diff --git a/internal/plumbing/ebpf/xdpmode/claim.go b/internal/plumbing/ebpf/xdpmode/claim.go new file mode 100644 index 000000000..aabef0973 --- /dev/null +++ b/internal/plumbing/ebpf/xdpmode/claim.go @@ -0,0 +1,255 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpmode + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +// ClaimDir is where every Galactic XDP component on a host records the mode it +// attaches in. It sits beside the shared XDP dispatcher's pins, on the bpffs +// mount every such component already has, so the record lives exactly as long +// as the host's boot. +const ClaimDir = "/sys/fs/bpf/galactic-xdp/modes" + +// ErrHostModeConflict is Claim's error when another live Galactic XDP +// component on the host attaches in a different mode. +var ErrHostModeConflict = errors.New("another Galactic XDP component on this host attaches in a different XDP mode") + +// claimRetryInterval is how often Claim tries again while a lock it needs is +// held. +const claimRetryInterval = 100 * time.Millisecond + +// HostClaim is a component's live claim on the host's attach mode. It holds an +// exclusive flock on the component's directory under the claim directory +// until Release or until the process exits, when the kernel drops it. Other +// components read a claim whose lock is held as live, and one whose lock is +// free as stale. +type HostClaim struct { + fd int +} + +// Release drops the claim. Its record stays behind, stale, until the +// component claims again. +func (c *HostClaim) Release() error { + if c == nil || c.fd < 0 { + return nil + } + err := unix.Close(c.fd) + c.fd = -1 + return err +} + +// Claim records d's mode for component under dir (ClaimDir) and keeps the +// claim for the life of the process, after checking that every other +// component with a live claim there attaches in the same mode. A live claim in +// another mode fails with ErrHostModeConflict, naming both sides, so two +// components on one host never attach in mixed modes. This holds whatever +// either decision came from, forced or driver-based. +// +// A claim whose holder has exited is stale and ignored, so a component that +// restarts in a new mode is not blocked by its own old claim or by a peer that +// is down. A component that writes no claim at all, as a release older than +// claims does, is not seen and blocks nothing. +// +// Claim waits, until ctx is done, for an earlier process of the same component +// still holding its claim, as while an old pod terminates. The caller keeps +// the returned claim reachable for as long as it attaches; the descriptor has +// no finalizer, so dropping the value does not release it. +func Claim(ctx context.Context, dir, component string, d Decision) (*HostClaim, error) { + if component == "" || strings.ContainsAny(component, "/.") { + return nil, fmt.Errorf("xdpmode: invalid component name %q", component) + } + own := filepath.Join(dir, component) + if err := os.MkdirAll(own, 0o755); err != nil { + return nil, fmt.Errorf("xdpmode: create claim directory: %w", err) + } + + unlock, fd, err := lockOwn(ctx, dir, own) + if err != nil { + return nil, err + } + defer unlock() + + if err := checkPeers(dir, component, d); err != nil { + _ = unix.Close(fd) + return nil, err + } + if err := writeRecord(own, d); err != nil { + _ = unix.Close(fd) + return nil, err + } + return &HostClaim{fd: fd}, nil +} + +// lockOwn takes dir's lock, which serializes claims on the host, and then the +// exclusive lock on own, the component's directory. While another process of +// the component holds own, it drops dir's lock and tries again, so that +// process's peers can still claim. It returns dir's unlock and own's +// descriptor, which holds the claim. +func lockOwn(ctx context.Context, dir, own string) (func(), int, error) { + for { + unlock, err := lockDir(ctx, dir) + if err != nil { + return nil, -1, err + } + fd, err := unix.Open(own, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + if err != nil { + unlock() + return nil, -1, fmt.Errorf("xdpmode: open claim directory %q: %w", own, err) + } + err = unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB) + if err == nil { + return unlock, fd, nil + } + _ = unix.Close(fd) + unlock() + if !errors.Is(err, unix.EWOULDBLOCK) && !errors.Is(err, unix.EINTR) { + return nil, -1, fmt.Errorf("xdpmode: lock claim directory %q: %w", own, err) + } + select { + case <-ctx.Done(): + return nil, -1, fmt.Errorf("xdpmode: waiting for an earlier process of this component to "+ + "release its claim on %q: %w", own, ctx.Err()) + case <-time.After(claimRetryInterval): + } + } +} + +// checkPeers returns ErrHostModeConflict, wrapped with every disagreeing +// component, when a live claim under dir other than component's holds a +// different mode from d's. The caller holds dir's lock. +func checkPeers(dir, component string, d Decision) error { + entries, err := os.ReadDir(dir) + if err != nil { + return fmt.Errorf("xdpmode: list claims in %q: %w", dir, err) + } + var conflicts []string + for _, e := range entries { + if !e.IsDir() || e.Name() == component { + continue + } + peer := filepath.Join(dir, e.Name()) + live, err := claimLive(peer) + if err != nil { + return err + } + if !live { + continue + } + mode, source, err := readRecord(peer) + if err != nil { + return fmt.Errorf("xdpmode: %s holds a live claim on this host's XDP mode: %w", e.Name(), err) + } + if mode != d.Mode { + conflicts = append(conflicts, fmt.Sprintf("%s attaches in %s mode (%s)", e.Name(), mode, source)) + } + } + if len(conflicts) == 0 { + return nil + } + return fmt.Errorf("%w: %s, but %s resolved %s mode (%s: %s). Set %s to the same value for every "+ + "Galactic XDP component on this host, and restart them together after adding or removing a NIC", + ErrHostModeConflict, strings.Join(conflicts, "; "), component, d.Mode, d.Source, d.Reason, SettingEnv) +} + +// claimLive reports whether a process holds the claim in dir, which is when +// dir's exclusive lock is taken. +func claimLive(dir string) (bool, error) { + fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + if err != nil { + return false, fmt.Errorf("xdpmode: open claim directory %q: %w", dir, err) + } + defer unix.Close(fd) //nolint:errcheck // read-only probe + err = unix.Flock(fd, unix.LOCK_SH|unix.LOCK_NB) + switch { + case err == nil: + return false, nil + case errors.Is(err, unix.EWOULDBLOCK): + return true, nil + default: + return false, fmt.Errorf("xdpmode: probe claim directory %q: %w", dir, err) + } +} + +// A claim's record is one subdirectory of the component's directory named +// _, such as generic_forced. bpffs holds only directories and +// pins, and a name is all a reader needs. bpffs refuses a name with a dot in +// it, so neither the record nor a component name may have one. + +// recordSep separates a record's mode from its source. +const recordSep = "_" + +// writeRecord replaces the record in own with d's mode and source. +func writeRecord(own string, d Decision) error { + entries, err := os.ReadDir(own) + if err != nil { + return fmt.Errorf("xdpmode: list claim record in %q: %w", own, err) + } + for _, e := range entries { + if err := os.Remove(filepath.Join(own, e.Name())); err != nil { + return fmt.Errorf("xdpmode: remove old claim record: %w", err) + } + } + if err := os.Mkdir(filepath.Join(own, d.Mode.String()+recordSep+string(d.Source)), 0o755); err != nil { + return fmt.Errorf("xdpmode: write claim record: %w", err) + } + return nil +} + +// readRecord returns the mode and source recorded in dir. +func readRecord(dir string) (Mode, Source, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return 0, "", fmt.Errorf("list its record: %w", err) + } + if len(entries) != 1 { + return 0, "", fmt.Errorf("its record has %d entries, want 1", len(entries)) + } + name, source, _ := strings.Cut(entries[0].Name(), recordSep) + switch name { + case Native.String(): + return Native, Source(source), nil + case Generic.String(): + return Generic, Source(source), nil + default: + return 0, "", fmt.Errorf("its record names unknown mode %q", entries[0].Name()) + } +} + +// lockDir locks dir, waiting until ctx is done. +func lockDir(ctx context.Context, dir string) (func(), error) { + fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + if err != nil { + return nil, fmt.Errorf("xdpmode: open %q for locking: %w", dir, err) + } + for { + err := unix.Flock(fd, unix.LOCK_EX|unix.LOCK_NB) + if err == nil { + return func() { + _ = unix.Flock(fd, unix.LOCK_UN) + _ = unix.Close(fd) + }, nil + } + if !errors.Is(err, unix.EWOULDBLOCK) && !errors.Is(err, unix.EINTR) { + _ = unix.Close(fd) + return nil, fmt.Errorf("xdpmode: lock %q: %w", dir, err) + } + select { + case <-ctx.Done(): + _ = unix.Close(fd) + return nil, fmt.Errorf("xdpmode: waiting for the claim lock on %q: %w", dir, ctx.Err()) + case <-time.After(claimRetryInterval): + } + } +} diff --git a/internal/plumbing/ebpf/xdpmode/claim_test.go b/internal/plumbing/ebpf/xdpmode/claim_test.go new file mode 100644 index 000000000..df8dbdf8b --- /dev/null +++ b/internal/plumbing/ebpf/xdpmode/claim_test.go @@ -0,0 +1,190 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpmode + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// The claim tests run on a temp directory. A flock belongs to an open file +// description, so two claims made in one test process contend exactly as two +// processes would. + +const ( + testGateway = "galactic-gateway" + testNAT = "galactic-nat" +) + +var ( + driverNative = Decision{Mode: Native, Source: SourceDriver, Reason: "no NIC needs generic"} + driverGeneric = Decision{Mode: Generic, Source: SourceDriver, Reason: testBnxt3} + forcedGeneric = Decision{Mode: Generic, Source: SourceForced, Reason: "forced by GALACTIC_XDP_MODE=generic"} + forcedNative = Decision{Mode: Native, Source: SourceForced, Reason: "forced by GALACTIC_XDP_MODE=native"} +) + +func mustClaim(t *testing.T, dir, component string, d Decision) *HostClaim { + t.Helper() + c, err := Claim(t.Context(), dir, component, d) + if err != nil { + t.Fatalf("Claim(%s, %s): %v", component, d.Mode, err) + } + t.Cleanup(func() { _ = c.Release() }) + return c +} + +func TestClaim_SameModeCoexists(t *testing.T) { + dir := t.TempDir() + mustClaim(t, dir, testGateway, forcedGeneric) + // The sources differ, the modes agree: nothing is mixed. + mustClaim(t, dir, testNAT, driverGeneric) +} + +// TestClaim_RejectsMixedModes covers two live components resolving different +// modes, whatever each decision came from. +func TestClaim_RejectsMixedModes(t *testing.T) { + tests := []struct { + name string + first, second Decision + wantPeer string + }{ + {"forced generic beside driver native", driverNative, forcedGeneric, + "galactic-gateway attaches in native mode (driver)"}, + {"driver native beside forced generic", forcedGeneric, driverNative, + "galactic-gateway attaches in generic mode (forced)"}, + {"forced native beside forced generic", forcedGeneric, forcedNative, + "galactic-gateway attaches in generic mode (forced)"}, + // A bnxt_en NIC hot-added while the first component runs: both are + // driver-based and still disagree. + {"driver generic beside driver native", driverNative, driverGeneric, + "galactic-gateway attaches in native mode (driver)"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + mustClaim(t, dir, testGateway, tt.first) + _, err := Claim(t.Context(), dir, testNAT, tt.second) + if !errors.Is(err, ErrHostModeConflict) { + t.Fatalf("Claim: got %v, want ErrHostModeConflict", err) + } + for _, want := range []string{ + tt.wantPeer, + "galactic-nat resolved " + tt.second.Mode.String() + " mode (" + string(tt.second.Source), + tt.second.Reason, + SettingEnv, + } { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q does not mention %q", err, want) + } + } + // The refused component recorded nothing, so the live one's + // record is the only one a third component would compare with. + if _, _, err := readRecord(filepath.Join(dir, testNAT)); err == nil { + t.Error("the refused component left a record behind") + } + }) + } +} + +// TestClaim_StaleClaimIsReplaced covers a component that exited and a peer +// that then starts in a new mode: the exited claim blocks nothing, and the +// component's own next claim takes the new mode. +func TestClaim_StaleClaimIsReplaced(t *testing.T) { + dir := t.TempDir() + old := mustClaim(t, dir, testGateway, driverNative) + if err := old.Release(); err != nil { + t.Fatal(err) + } + mustClaim(t, dir, testNAT, forcedGeneric) + mustClaim(t, dir, testGateway, forcedGeneric) + mode, source, err := readRecord(filepath.Join(dir, testGateway)) + if err != nil || mode != Generic || source != SourceForced { + t.Fatalf("gateway record = %s, %q, %v; want generic, forced", mode, source, err) + } +} + +// TestClaim_PeerWithoutClaimIsNotSeen covers an upgrade: a pod of a release +// older than claims runs beside a new one. It writes no claim, so the new pod +// starts. The dispatcher's own pins beside the claim directory, the host_mode +// record among them, are not claims and are never read as one. +func TestClaim_PeerWithoutClaimIsNotSeen(t *testing.T) { + pinDir := t.TempDir() + for _, sub := range []string{"abi", "links"} { + if err := os.Mkdir(filepath.Join(pinDir, sub), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(pinDir, "host_mode"), nil, 0o644); err != nil { + t.Fatal(err) + } + dir := filepath.Join(pinDir, "modes") + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + mustClaim(t, dir, testNAT, forcedGeneric) +} + +// TestClaim_WaitsForTheSameComponent covers a restart whose old process still +// holds the component's claim: the new one waits for it rather than racing +// it, and gives up when its context ends. +func TestClaim_WaitsForTheSameComponent(t *testing.T) { + dir := t.TempDir() + old := mustClaim(t, dir, testGateway, driverNative) + + ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond) + defer cancel() + if _, err := Claim(ctx, dir, testGateway, forcedGeneric); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Claim while the old process holds it: got %v, want a deadline", err) + } + + // A peer can still claim while the new process waits. + mustClaim(t, dir, testNAT, driverNative) + + released := make(chan error, 1) + go func() { + time.Sleep(2 * claimRetryInterval) + released <- old.Release() + }() + mustClaim(t, dir, testGateway, driverNative) + if err := <-released; err != nil { + t.Fatal(err) + } +} + +func TestClaim_ReadsAnUnreadableLiveRecordAsAnError(t *testing.T) { + dir := t.TempDir() + mustClaim(t, dir, testGateway, driverNative) + // A second entry makes the live record ambiguous. + if err := os.Mkdir(filepath.Join(dir, testGateway, "generic_forced"), 0o755); err != nil { + t.Fatal(err) + } + _, err := Claim(t.Context(), dir, testNAT, driverNative) + if err == nil || errors.Is(err, ErrHostModeConflict) || !strings.Contains(err.Error(), "2 entries") { + t.Fatalf("Claim: got %v, want an unreadable-record error", err) + } +} + +func TestClaim_RejectsAnInvalidComponent(t *testing.T) { + for _, name := range []string{"", "a/b", "..", "gw.1"} { + if _, err := Claim(t.Context(), t.TempDir(), name, driverNative); err == nil { + t.Errorf("Claim(%q): want an error", name) + } + } +} + +func TestHostClaim_ReleaseTwice(t *testing.T) { + c := mustClaim(t, t.TempDir(), testGateway, driverNative) + if err := c.Release(); err != nil { + t.Fatal(err) + } + if err := c.Release(); err != nil { + t.Fatalf("second Release: %v", err) + } +} diff --git a/internal/plumbing/ebpf/xdpmode/mode.go b/internal/plumbing/ebpf/xdpmode/mode.go index 74f93414b..8dbcc4280 100644 --- a/internal/plumbing/ebpf/xdpmode/mode.go +++ b/internal/plumbing/ebpf/xdpmode/mode.go @@ -14,11 +14,16 @@ // the same programs after the driver has built an skb, so the XDP TX ring is // never used. The cost is per-packet throughput, since generic mode allocates // an skb for every frame. +// +// An operator can force either mode for the whole host with SettingEnv, as to +// run a host without bnxt_en in generic mode for testing. Every Galactic XDP +// component on a host must then resolve the same mode, which Claim enforces. package xdpmode import ( "errors" "fmt" + "log/slog" "os" "path/filepath" "slices" @@ -44,9 +49,9 @@ const ( func (m Mode) String() string { switch m { case Native: - return "native" + return nameNative case Generic: - return "generic" + return nameGeneric default: return fmt.Sprintf("Mode(%d)", int(m)) } @@ -87,6 +92,77 @@ func FromAttachMode(attachMode uint32) (Mode, bool) { } } +// SettingEnv is the environment variable that forces the attach mode for every +// Galactic XDP component on a host. config binds it for each component. +const SettingEnv = "GALACTIC_XDP_MODE" + +// Setting is SettingEnv's value: SettingAuto decides from the host's NIC +// drivers, and the others force a mode whatever the drivers are. +type Setting int + +const ( + // SettingAuto decides from the drivers of the host's NICs. + SettingAuto Setting = iota + // SettingNative forces native mode. + SettingNative + // SettingGeneric forces generic mode. + SettingGeneric +) + +// nameNative and nameGeneric name the modes, in logs, in SettingEnv and in +// claim records. +const ( + nameNative = "native" + nameGeneric = "generic" +) + +// SettingAuto's, SettingNative's and SettingGeneric's values as SettingEnv +// takes them. +const ( + SettingAutoValue = "auto" + SettingNativeValue = nameNative + SettingGenericValue = nameGeneric +) + +// ParseSetting reads SettingEnv's value. Empty means SettingAuto. +func ParseSetting(value string) (Setting, error) { + switch value { + case "", SettingAutoValue: + return SettingAuto, nil + case SettingNativeValue: + return SettingNative, nil + case SettingGenericValue: + return SettingGeneric, nil + default: + return 0, fmt.Errorf("%s must be %q, %q or %q, got %q", SettingEnv, + SettingAutoValue, SettingNativeValue, SettingGenericValue, value) + } +} + +// String returns the setting as SettingEnv takes it. +func (s Setting) String() string { + switch s { + case SettingAuto: + return SettingAutoValue + case SettingNative: + return SettingNativeValue + case SettingGeneric: + return SettingGenericValue + default: + return fmt.Sprintf("Setting(%d)", int(s)) + } +} + +// Source says what a Decision's mode came from. +type Source string + +const ( + // SourceDriver is a mode decided from the host's NIC drivers. + SourceDriver Source = "driver" + // SourceForced is a mode SettingEnv forced. + SourceForced Source = "forced" +) + // GenericDrivers are the NIC drivers whose presence on a host selects generic // mode for every attachment on it. var GenericDrivers = []string{"bnxt_en"} @@ -94,6 +170,8 @@ var GenericDrivers = []string{"bnxt_en"} // Decision is Select's result: the mode, why, and what it was based on. type Decision struct { Mode Mode + // Source says whether SettingEnv forced Mode or the drivers decided it. + Source Source // Drivers maps every physical NIC on the host to its driver. Drivers map[string]string // Reason says, in a sentence for a log line, why Mode was chosen. @@ -101,6 +179,10 @@ type Decision struct { // Skipped lists physical NICs left out because their driver link was // gone, as while a driver unbinds, each with why. None is a target. Skipped []string + // ForcedOverDrivers lists, as name=driver, the NICs whose driver would + // have selected generic mode when SettingEnv forced native instead. Their + // receive queues can stall (#673). + ForcedOverDrivers []string } // sysClassNet is where Select reads interfaces and their drivers from. @@ -108,8 +190,10 @@ type Decision struct { // host's interfaces. Tests point it elsewhere. var sysClassNet = "/sys/class/net" -// Select decides the host's attach mode from the drivers of its physical NICs -// in sysfs. required lists the interfaces the caller is about to attach to; +// Select decides the host's attach mode. With SettingAuto it decides from the +// drivers of the host's physical NICs in sysfs; any other setting forces its +// mode, but the same checks below still run, so a forced mode never hides a +// missing target. required lists the interfaces the caller is about to attach to; // one that does not exist fails the decision, as does a required NIC whose // driver cannot be read, or any NIC whose driver link exists but cannot be // read, so none of them ever settles a mode by omission. A NIC that is not a @@ -118,7 +202,10 @@ var sysClassNet = "/sys/class/net" // no device link, such as a bond master, a veth or a VLAN, is virtual and has // no driver of its own to consider. A regular file, such as the bonding // driver's bonding_masters, is not an interface. -func Select(required ...string) (Decision, error) { +func Select(setting Setting, required ...string) (Decision, error) { + if setting < SettingAuto || setting > SettingGeneric { + return Decision{}, fmt.Errorf("xdpmode: unknown setting %s", setting) + } entries, err := os.ReadDir(sysClassNet) if err != nil { return Decision{}, fmt.Errorf("xdpmode: list interfaces in %s: %w", sysClassNet, err) @@ -154,10 +241,56 @@ func Select(required ...string) (Decision, error) { return Decision{}, errors.Join(errs...) } d := decide(drivers) + if setting != SettingAuto { + d = force(setting, d) + } d.Skipped = skipped return d, nil } +// force replaces driver's mode, the drivers' decision, with the one setting +// forces. +func force(setting Setting, driver Decision) Decision { + d := Decision{Mode: Native, Source: SourceForced, Drivers: driver.Drivers} + if setting == SettingGeneric { + d.Mode = Generic + } + d.Reason = fmt.Sprintf("forced by %s=%s; the drivers alone would select %s", SettingEnv, setting, driver.Mode) + if d.Mode == Native && driver.Mode == Generic { + d.ForcedOverDrivers = genericDriverNICs(driver.Drivers) + } + return d +} + +// genericDriverNICs lists, as sorted name=driver pairs, the NICs whose driver +// is one of GenericDrivers. +func genericDriverNICs(drivers map[string]string) []string { + var matched []string + for name, driver := range drivers { + if slices.Contains(GenericDrivers, driver) { + matched = append(matched, name+"="+driver) + } + } + slices.Sort(matched) + return matched +} + +// Log writes the decision to the default logger: the mode, where it came +// from and why, a warning for each NIC left out of it, and a warning when a +// forced native mode runs over NICs that need generic. +func (d Decision) Log() { + slog.Info("Selected the XDP attach mode for this host", + "mode", d.Mode.String(), "source", string(d.Source), "reason", d.Reason) + for _, skipped := range d.Skipped { + slog.Warn("Left a NIC with no driver out of the XDP attach mode decision", "reason", skipped) + } + if len(d.ForcedOverDrivers) > 0 { + slog.Warn("Forced native XDP on NICs whose native XDP redirect stalls receive queues (#673); "+ + "unset "+SettingEnv+" to return them to generic mode", + "nics", strings.Join(d.ForcedOverDrivers, ", ")) + } +} + // interfaceDriver returns name's driver and whether it is a physical NIC, // which is when sysfs gives it a device link. func interfaceDriver(name string) (driver string, physical bool, err error) { @@ -177,18 +310,12 @@ func interfaceDriver(name string) (driver string, physical bool, err error) { // decide picks the mode for a host whose physical NICs have drivers. func decide(drivers map[string]string) Decision { - var matched []string - for name, driver := range drivers { - if slices.Contains(GenericDrivers, driver) { - matched = append(matched, name+"="+driver) - } - } + matched := genericDriverNICs(drivers) if len(matched) == 0 { - return Decision{Mode: Native, Drivers: drivers, + return Decision{Mode: Native, Source: SourceDriver, Drivers: drivers, Reason: "no NIC on this host uses a driver that needs generic mode"} } - slices.Sort(matched) - return Decision{Mode: Generic, Drivers: drivers, + return Decision{Mode: Generic, Source: SourceDriver, Drivers: drivers, Reason: "NICs on this host use a driver whose native XDP redirect stalls receive queues (#673): " + strings.Join(matched, ", ")} } diff --git a/internal/plumbing/ebpf/xdpmode/mode_test.go b/internal/plumbing/ebpf/xdpmode/mode_test.go index 83421f520..3b8565554 100644 --- a/internal/plumbing/ebpf/xdpmode/mode_test.go +++ b/internal/plumbing/ebpf/xdpmode/mode_test.go @@ -18,6 +18,8 @@ import ( const ( testNIC1 = "eno1" testNIC2 = "eno2" + // testBnxt3 is how a decision names ens3 driven by bnxt_en. + testBnxt3 = "ens3=bnxt_en" ) // fakeSysfs builds a /sys/class/net look-alike under a temp dir and points @@ -131,7 +133,7 @@ func TestSelect(t *testing.T) { }, required: []string{testNIC1}, want: Generic, - wantReason: "ens3=bnxt_en", + wantReason: testBnxt3, }, { name: "virtual targets follow the host's NICs", @@ -156,10 +158,13 @@ func TestSelect(t *testing.T) { t.Run(tt.name, func(t *testing.T) { f := newFakeSysfs(t) tt.build(f) - got, err := Select(tt.required...) + got, err := Select(SettingAuto, tt.required...) if err != nil { t.Fatalf("Select: %v", err) } + if got.Source != SourceDriver { + t.Errorf("Source = %q, want %q", got.Source, SourceDriver) + } if got.Mode != tt.want { t.Errorf("Mode = %s, want %s (reason %q)", got.Mode, tt.want, got.Reason) } @@ -206,7 +211,7 @@ func TestSelect_ReportsWhatItCannotDecideOn(t *testing.T) { t.Run(tt.name, func(t *testing.T) { f := newFakeSysfs(t) tt.build(f) - _, err := Select(tt.required...) + _, err := Select(SettingAuto, tt.required...) if err == nil { t.Fatal("Select: want an error") } @@ -223,7 +228,7 @@ func TestSelect_UnreadableSysfs(t *testing.T) { old := sysClassNet sysClassNet = filepath.Join(t.TempDir(), "missing") t.Cleanup(func() { sysClassNet = old }) - if _, err := Select(); err == nil { + if _, err := Select(SettingAuto); err == nil { t.Fatal("Select over a missing sysfs: want an error") } } @@ -269,7 +274,7 @@ func TestSelect_SkipsANonTargetNICWithNoDriver(t *testing.T) { f.physical("ens3", "bnxt_en") f.unbound(testNIC2) - got, err := Select("ens3") + got, err := Select(SettingAuto, "ens3") if err != nil { t.Fatalf("Select: %v", err) } diff --git a/internal/plumbing/ebpf/xdpmode/setting_test.go b/internal/plumbing/ebpf/xdpmode/setting_test.go new file mode 100644 index 000000000..2053ac8b1 --- /dev/null +++ b/internal/plumbing/ebpf/xdpmode/setting_test.go @@ -0,0 +1,150 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpmode + +import ( + "slices" + "strings" + "testing" +) + +func TestParseSetting(t *testing.T) { + for _, tt := range []struct { + value string + want Setting + }{ + {"", SettingAuto}, + {"auto", SettingAuto}, + {SettingNativeValue, SettingNative}, + {SettingGenericValue, SettingGeneric}, + } { + got, err := ParseSetting(tt.value) + if err != nil { + t.Errorf("ParseSetting(%q): %v", tt.value, err) + continue + } + if got != tt.want { + t.Errorf("ParseSetting(%q) = %s, want %s", tt.value, got, tt.want) + } + if tt.value != "" && got.String() != tt.value { + t.Errorf("%s.String() = %q, want %q", got, got.String(), tt.value) + } + } +} + +func TestParseSetting_RejectsAnInvalidValue(t *testing.T) { + for _, value := range []string{"skb", "drv", "Generic", " native", "auto,generic"} { + _, err := ParseSetting(value) + if err == nil { + t.Errorf("ParseSetting(%q): want an error", value) + continue + } + for _, want := range []string{SettingEnv, `"auto"`, `"native"`, `"generic"`, value} { + if !strings.Contains(err.Error(), want) { + t.Errorf("ParseSetting(%q) error %q does not mention %q", value, err, want) + } + } + } +} + +// TestSelect_Forced covers every forced decision, with and without a NIC +// whose driver selects generic mode on its own. +func TestSelect_Forced(t *testing.T) { + tests := []struct { + name string + build func(f *fakeSysfs) + setting Setting + want Mode + wantReason string + wantForcedOver []string + wantDriversSeen int + }{ + { + name: "generic on a host without bnxt_en", + build: func(f *fakeSysfs) { f.physical(testNIC1, "igb"); f.virtual("veth0") }, + setting: SettingGeneric, + want: Generic, + wantReason: "forced by GALACTIC_XDP_MODE=generic; the drivers alone would select native", + wantDriversSeen: 1, + }, + { + name: "generic on a bnxt_en host agrees with the drivers", + build: func(f *fakeSysfs) { f.physical("ens3", "bnxt_en") }, + setting: SettingGeneric, + want: Generic, + wantReason: "forced by GALACTIC_XDP_MODE=generic; the drivers alone would select generic", + wantDriversSeen: 1, + }, + { + name: "native on a host without bnxt_en", + build: func(f *fakeSysfs) { f.physical(testNIC1, "igb") }, + setting: SettingNative, + want: Native, + wantReason: "forced by GALACTIC_XDP_MODE=native; the drivers alone would select native", + wantDriversSeen: 1, + }, + { + name: "native on a bnxt_en host names the NICs it runs over", + build: func(f *fakeSysfs) { + f.physical(testNIC1, "igb") + f.physical("ens3", "bnxt_en") + f.physical("ens7", "bnxt_en") + }, + setting: SettingNative, + want: Native, + wantReason: "forced by GALACTIC_XDP_MODE=native; the drivers alone would select generic", + wantForcedOver: []string{testBnxt3, "ens7=bnxt_en"}, + wantDriversSeen: 3, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newFakeSysfs(t) + tt.build(f) + got, err := Select(tt.setting) + if err != nil { + t.Fatalf("Select: %v", err) + } + if got.Mode != tt.want || got.Source != SourceForced { + t.Errorf("Mode, Source = %s, %q; want %s, %q", got.Mode, got.Source, tt.want, SourceForced) + } + if got.Reason != tt.wantReason { + t.Errorf("Reason = %q, want %q", got.Reason, tt.wantReason) + } + if !slices.Equal(got.ForcedOverDrivers, tt.wantForcedOver) { + t.Errorf("ForcedOverDrivers = %v, want %v", got.ForcedOverDrivers, tt.wantForcedOver) + } + if len(got.Drivers) != tt.wantDriversSeen { + t.Errorf("Drivers = %v, want %d", got.Drivers, tt.wantDriversSeen) + } + }) + } +} + +// TestSelect_ForcedStillChecksTargets shows that forcing a mode skips none of +// the checks a driver-based decision makes. +func TestSelect_ForcedStillChecksTargets(t *testing.T) { + f := newFakeSysfs(t) + f.physical(testNIC1, "igb") + f.unbound("eno3") + for _, setting := range []Setting{SettingNative, SettingGeneric} { + _, err := Select(setting, "eno3", "eno9") + if err == nil { + t.Fatalf("Select(%s): want an error", setting) + } + for _, want := range []string{"read driver of eno3", "interface eno9 does not exist"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("Select(%s) error %q does not mention %q", setting, err, want) + } + } + } +} + +func TestSelect_RejectsAnUnknownSetting(t *testing.T) { + newFakeSysfs(t) + if _, err := Select(Setting(7)); err == nil { + t.Fatal("Select with an unknown setting: want an error") + } +}