diff --git a/cmd/galactic-nat/dispatch_test.go b/cmd/galactic-nat/dispatch_test.go new file mode 100644 index 000000000..5fa358211 --- /dev/null +++ b/cmd/galactic-nat/dispatch_test.go @@ -0,0 +1,252 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package main + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/asm" + "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" +) + +// testPinDirs returns per-test bpffs directories for the dispatcher and the +// shard's own maps. +func testPinDirs(t *testing.T) (dispatchDir, natDir string) { + t.Helper() + requireRoot(t) + name := strings.NewReplacer("/", "-", " ", "-").Replace(t.Name()) + base := filepath.Join("/sys/fs/bpf", "natdispatch-test-"+name) + _ = os.RemoveAll(base) + dispatchDir, natDir = filepath.Join(base, "xdp"), filepath.Join(base, "nat") + for _, d := range []string{dispatchDir, natDir} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Skipf("bpffs not writable at /sys/fs/bpf: %v", err) + } + } + t.Cleanup(func() { _ = os.RemoveAll(base) }) + return dispatchDir, natDir +} + +// testUplink creates an up veth pair and returns the first end's name. +func testUplink(t *testing.T, prefix string) string { + 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) + } + } + return name +} + +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 +} + +// loadShard loads the real shard objects under natDir, as a process start +// does. +func loadShard(t *testing.T, natDir string) *ebpf.Program { + t.Helper() + objs, err := natattach.Load(natDir) + 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) + } + return objs.NatIngress +} + +// joinForTest joins the dispatcher under dispatchDir and stops the lease and +// closes the dispatcher when the test ends, in that order. +func joinForTest(t *testing.T, dispatchDir string, program *ebpf.Program) (*xdpdispatch.Dispatcher, + *xdpattach.DispatchSet, func(), +) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + d, set, leaseDone, err := joinDispatcher(ctx, dispatchDir, program) + if err != nil { + cancel() + t.Fatalf("joinDispatcher: %v", err) + } + stopped := false + stop := func() { + if stopped { + return + } + stopped = true + cancel() + <-leaseDone + _ = d.Close() + } + t.Cleanup(stop) + return d, set, stop +} + +// TestJoinDispatcher_ARestartLeavesTheUplinkAttached is issue #717's restart +// case for the shard: a new process takes over the slot and the uplink keeps +// the same root, never detached or re-attached. +func TestJoinDispatcher_ARestartLeavesTheUplinkAttached(t *testing.T) { + dispatchDir, natDir := testPinDirs(t) + uplink := testUplink(t, "natd") + + _, set, stopFirst := joinForTest(t, dispatchDir, loadShard(t, natDir)) + if missing := set.Reconcile(context.Background(), []string{uplink}); len(missing) != 0 { + t.Fatalf("first process: missing %v", missing) + } + rootBefore := xdpProgID(t, uplink) + if rootBefore == 0 { + t.Fatal("no XDP program on the uplink after the first process joined") + } + + // The first process exits. + stopFirst() + if got := xdpProgID(t, uplink); got != rootBefore { + t.Fatalf("uplink runs program %d after the shard exited, want the root %d", got, rootBefore) + } + + _, set2, _ := joinForTest(t, dispatchDir, loadShard(t, natDir)) + if missing := set2.Reconcile(context.Background(), []string{uplink}); len(missing) != 0 { + t.Errorf("second process: missing %v", missing) + } + if got := xdpProgID(t, uplink); got != rootBefore { + t.Errorf("uplink runs program %d after the restart, want the same root %d", got, rootBefore) + } +} + +// TestReleaseIdleDispatcher_FreesTheUplinkForADirectAttach is a rollback to +// direct mode on a node only the shard used the dispatcher on. +func TestReleaseIdleDispatcher_FreesTheUplinkForADirectAttach(t *testing.T) { + dispatchDir, natDir := testPinDirs(t) + uplink := testUplink(t, "natr") + program := loadShard(t, natDir) + + _, set, _ := joinForTest(t, dispatchDir, program) + if missing := set.Reconcile(context.Background(), []string{uplink}); len(missing) != 0 { + t.Fatalf("missing %v", missing) + } + + if err := releaseIdleDispatcher(context.Background(), dispatchDir, []string{uplink}); err != nil { + t.Fatalf("releaseIdleDispatcher: %v", err) + } + if got := xdpProgID(t, uplink); got != 0 { + t.Fatalf("uplink still runs program %d after release", got) + } + links, err := natattach.Attach(program, []string{uplink}) + if err != nil { + t.Fatalf("direct attach after release: %v", err) + } + for _, l := range links { + _ = l.Close() + } +} + +// TestReleaseIdleDispatcher_RefusesWhileAnotherSlotIsLive: the gateway is on +// the same uplink, so a direct attach would cut its traffic. +func TestReleaseIdleDispatcher_RefusesWhileAnotherSlotIsLive(t *testing.T) { + dispatchDir, natDir := testPinDirs(t) + uplink := testUplink(t, "natg") + + d, set, _ := joinForTest(t, dispatchDir, loadShard(t, natDir)) + if missing := set.Reconcile(context.Background(), []string{uplink}); len(missing) != 0 { + t.Fatalf("missing %v", missing) + } + gateway := stubXDP(t) + lock, err := d.Lock(context.Background()) + if err != nil { + t.Fatalf("Lock: %v", err) + } + err = lock.Fill(xdpdispatch.SlotGatewayLB, gateway) + lock.Unlock() + if err != nil { + t.Fatalf("fill the gateway slot: %v", err) + } + root := xdpProgID(t, uplink) + + if err := releaseIdleDispatcher(context.Background(), dispatchDir, []string{uplink}); err == nil { + t.Fatal("releaseIdleDispatcher succeeded with the gateway's slot live") + } + if got := xdpProgID(t, uplink); got != root { + t.Errorf("uplink runs program %d after the refusal, want the root %d untouched", got, root) + } +} + +// TestTurnOffDatapath_EmptiesOnlyTheShardsSlot: turning the shard off +// takes it out of the dispatcher at once and leaves the gateway's slot alone. +func TestTurnOffDatapath_EmptiesOnlyTheShardsSlot(t *testing.T) { + dispatchDir, natDir := testPinDirs(t) + uplink := testUplink(t, "natx") + program := loadShard(t, natDir) + + d, set, _ := joinForTest(t, dispatchDir, program) + if missing := set.Reconcile(context.Background(), []string{uplink}); len(missing) != 0 { + t.Fatalf("missing %v", missing) + } + lock, err := d.Lock(context.Background()) + if err != nil { + t.Fatalf("Lock: %v", err) + } + err = lock.Fill(xdpdispatch.SlotGatewayLB, stubXDP(t)) + lock.Unlock() + if err != nil { + t.Fatalf("fill the gateway slot: %v", err) + } + + turnOffDatapath(context.Background(), dispatchDir) + live, err := d.LiveSlots() + if err != nil { + t.Fatalf("LiveSlots: %v", err) + } + if len(live) != 1 || live[0] != xdpdispatch.SlotGatewayLB { + t.Errorf("live slots = %v after disabling the shard, want only the gateway's", live) + } + if xdpProgID(t, uplink) == 0 { + t.Error("disabling the shard detached the dispatcher") + } +} + +// stubXDP stands in for another datapath's program. +func stubXDP(t *testing.T) *ebpf.Program { + t.Helper() + p, 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 stub program: %v", err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} diff --git a/cmd/galactic-nat/nat.go b/cmd/galactic-nat/nat.go index 85a429b97..7cb21de0e 100644 --- a/cmd/galactic-nat/nat.go +++ b/cmd/galactic-nat/nat.go @@ -10,6 +10,7 @@ import ( "fmt" "log/slog" "os" + "path/filepath" "slices" "sync" "time" @@ -18,6 +19,7 @@ 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" @@ -25,6 +27,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/natmap" "go.datum.net/galactic/internal/plumbing/ebpf/natprog" "go.datum.net/galactic/internal/plumbing/ebpf/xdpattach" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" "go.datum.net/galactic/internal/plumbing/nicstats" "go.datum.net/galactic/internal/plumbing/sysctl" ) @@ -41,8 +44,9 @@ import ( // shard's XDP attachment live on the wire, would eventually be collected and // silently detached while the shard's Ready condition still reported healthy. var natDatapathKeepAlive struct { - objs *natprog.NatObjects - set *xdpattach.Set + objs *natprog.NatObjects + set *xdpattach.Set + dispatch *xdpdispatch.Dispatcher } // natDatapath is this node's attached egress translation datapath, as @@ -80,7 +84,8 @@ func (d *natDatapath) Attached() bool { } // MissingUplinks reports the resolved uplinks the datapath does not cover: not -// attached in direct mode, not hooked by the edge gateway in chain mode. +// attached in direct mode, not reaching this shard's dispatcher slot in +// dispatch mode, not hooked by the edge gateway in chain mode. func (d *natDatapath) MissingUplinks() []string { d.mu.Lock() defer d.mu.Unlock() @@ -246,6 +251,17 @@ func (d *natDatapath) Programmed() (controller.EgressShardIdentity, bool) { // the rest as routing reveals them. onCoverage is called whenever the set of // uplinks the datapath misses changes, which MissingUplinks then reports. // +// In dispatch mode (config.NATXDPAttachDispatch) the program is not attached +// either. It fills this shard's slot in the node's shared XDP dispatcher, whose +// pinned root holds every uplink, and the slot's lease is renewed for the life +// of the process. The root and the slot outlive the process, so a restart +// never detaches anything; the next process swaps its program into the slot. +// Nothing here is all-or-nothing: an uplink the dispatcher cannot hold yet is +// reported missing and retried. +// +// 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 @@ -296,16 +312,31 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, d.shardConfig = natmap.NewShardConfigTable(natmap.KernelTable{Map: objs.ShardConfigTable}) var ( - set *xdpattach.Set - xdpLinks []link.Link + set *xdpattach.Set + dispatchSet *xdpattach.DispatchSet + dispatcher *xdpdispatch.Dispatcher + xdpLinks []link.Link ) - if cfg.XDPAttach == config.NATXDPAttachChain { + 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) - } else { + case config.NATXDPAttachDispatch: + // The lease runs for the life of the process, so its done channel + // is not needed here. + if dispatcher, dispatchSet, _, err = joinDispatcher(ctx, xdpdispatch.PinDir, objs.NatIngress); err != nil { + _ = objs.Close() + return nil, err + } + d.missing = dispatchSet.Reconcile(ctx, uplinks) + default: + if err := releaseIdleDispatcher(ctx, xdpdispatch.PinDir, uplinks); err != nil { + _ = objs.Close() + return nil, err + } xdpLinks, err = natattach.Attach(objs.NatIngress, uplinks) if err != nil { _ = objs.Close() @@ -329,6 +360,7 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, natDatapathKeepAlive.objs = objs natDatapathKeepAlive.set = set + natDatapathKeepAlive.dispatch = dispatcher slog.Info("Egress translation datapath attached", "interfaces", uplinks, @@ -337,7 +369,8 @@ func setupNatDatapath(ctx context.Context, cfg *config.NATConfig, ) d.attached = true - go d.watchUplinks(ctx, cfg.UplinkInterfaces, set, onCoverage) + go d.watchUplinks(ctx, cfg.UplinkInterfaces, coverageFor(ctx, set, dispatchSet), dispatchSet == nil && set == nil, + onCoverage) return d, nil } @@ -358,6 +391,125 @@ func registerUplinkQueueStats(metricsReg prometheus.Registerer, d *natDatapath) } } +// joinDispatcher opens the node's XDP dispatcher, fills this shard's slot with +// program, and starts renewing the slot's lease for the life of ctx. It +// returns the set that keeps the dispatcher on the uplinks, and a channel +// closed once the lease loop has stopped, which a caller waits on before +// closing the dispatcher. +func joinDispatcher(ctx context.Context, pinDir string, program *ebpf.Program) ( + *xdpdispatch.Dispatcher, *xdpattach.DispatchSet, <-chan struct{}, error, +) { + dispatcher, err := xdpdispatch.Open(ctx, pinDir) + if err != nil { + return nil, nil, nil, fmt.Errorf("open the node's XDP dispatcher: %w", err) + } + lock, err := dispatcher.Lock(ctx) + if err != nil { + _ = dispatcher.Close() + return nil, nil, nil, err + } + err = lock.Fill(xdpdispatch.SlotNAT, program) + lock.Unlock() + if err != nil { + _ = dispatcher.Close() + return nil, nil, nil, fmt.Errorf("install egress translation datapath in the XDP dispatcher: %w", err) + } + set, err := xdpattach.NewDispatchSet(dispatcher, xdpdispatch.SlotNAT, xdpdispatch.RoleEgress, program) + if err != nil { + _ = dispatcher.Close() + return nil, nil, nil, err + } + + // A lapsed lease shows as missing uplinks within one coverage resync, + // since every Reconcile reads the lease back. + leaseDone := make(chan struct{}) + go func() { + defer close(leaseDone) + dispatcher.Lease(ctx, xdpdispatch.SlotNAT, func(err error) { + slog.Error("Cannot renew the egress translation slot's lease in the XDP dispatcher; "+ + "the dispatcher skips the slot once it lapses", "err", err) + }) + }() + slog.Info("Egress translation datapath installed in the XDP dispatcher", "pinDir", pinDir) + 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. +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) + } + 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) +} + +// 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. +func coverageFor(ctx context.Context, set *xdpattach.Set, dispatchSet *xdpattach.DispatchSet) func([]string) []string { + switch { + case 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)) + } + } +} + // uplinkRetryInterval is how often waitForUplinks resolves again while none // resolve. const uplinkRetryInterval = 2 * time.Second @@ -390,12 +542,14 @@ 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. In -// direct mode set holds the attachments and an uplink found later is attached -// to it; in chain mode set is nil and the gateway owns the hook, so an uplink -// it does not cover can only be reported. Either way, onCoverage is called -// whenever the missing uplinks change. -func (d *natDatapath) watchUplinks(ctx context.Context, override []string, set *xdpattach.Set, onCoverage func()) { +// 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. +func (d *natDatapath) watchUplinks(ctx context.Context, override []string, cover func([]string) []string, + chained bool, onCoverage func(), +) { xdpattach.OnNetlinkChange(ctx, func() { uplinks, err := natattach.ResolveUplinks(override) if err != nil { @@ -404,14 +558,7 @@ func (d *natDatapath) watchUplinks(ctx context.Context, override []string, set * } ready := d.adoptUplinks(uplinks) - var covered []string - if set != nil { - set.Reconcile(ready) - covered = set.Attached() - } else { - covered = uncovered(ready, natattach.UnhookedUplinks(ready)) - } - missing := uncovered(uplinks, covered) + missing := uncovered(uplinks, cover(ready)) if !d.setMissing(missing) { return @@ -419,7 +566,7 @@ func (d *natDatapath) watchUplinks(ctx context.Context, override []string, set * switch { case len(missing) == 0: slog.Info("Egress translation datapath covers every uplink", "uplinks", uplinks) - case set == nil: + 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: @@ -517,3 +664,59 @@ func closeAll(links []link.Link) { _ = l.Close() } } + +// disabledDatapath is the datapath of a shard turned off by configuration +// (config.EnvNATDatapathEnabled). It holds nothing and translates nothing, and +// reports no missing uplinks, so the pod stays ready while the EgressShard +// reports the shard as disabled. +type disabledDatapath struct{} + +func (disabledDatapath) Attached() bool { return false } +func (disabledDatapath) MissingUplinks() []string { return nil } +func (disabledDatapath) Clear() error { return nil } + +func (disabledDatapath) Program(controller.EgressShardIdentity) error { + return errors.New("the egress translation datapath is turned off") +} + +func (disabledDatapath) Programmed() (controller.EgressShardIdentity, bool) { + return controller.EgressShardIdentity{}, false +} + +// turnOffDatapath turns this node's shard off; the shard then runs with +// disabledDatapath. A dispatch-mode +// predecessor left the shard's program in the XDP dispatcher with a live +// lease, so the slot is emptied here and the dispatcher passes the shard's +// traffic on at once rather than once the lease lapses. Every other slot, and +// the dispatcher itself, are left alone. A direct-mode predecessor's +// attachment ended with its process, so there is nothing to undo for it. +// +// A failure to empty the slot is logged, not returned: the shard is meant to +// be off, the lease lapses on its own within xdpdispatch.LeaseTTL, and a +// 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) + } + } + 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 3428581b0..94a60f80d 100644 --- a/cmd/galactic-nat/root.go +++ b/cmd/galactic-nat/root.go @@ -27,6 +27,7 @@ import ( "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/controller" "go.datum.net/galactic/internal/metadata" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" bgpv1alpha1 "go.datum.net/network/api/v1alpha1" ) @@ -122,20 +123,26 @@ func runCmd(cfg *config.NATConfig) error { // coverageChanged, possibly before setupNatDatapath has even returned, so // the callback only nudges and followCoverage below does the work. coverageChanged := make(chan struct{}, 1) - datapath, err := setupNatDatapath(ctx, cfg, ctrlmetrics.Registry, func() { - select { - case coverageChanged <- struct{}{}: - default: - } - }) + var datapath controller.EgressDatapath + if cfg.DatapathEnabled { + datapath, err = setupNatDatapath(ctx, cfg, ctrlmetrics.Registry, func() { + select { + case coverageChanged <- struct{}{}: + default: + } + }) + } else { + turnOffDatapath(ctx, xdpdispatch.PinDir) + datapath = disabledDatapath{} + } if err != nil { return fmt.Errorf("setup egress translation eBPF datapath: %w", err) } coverageEvents := make(chan event.GenericEvent, 1) go followCoverage(ctx, datapath, healthSrv, coverageChanged, coverageEvents) - // Only now is the datapath attached, or in chain mode installed in the - // edge gateway's XDP chain. Report serving from here on, not from + // Only now is the datapath attached, installed in the XDP dispatcher or, + // in chain mode, in the edge gateway's XDP chain, or turned off. Report serving from here on, not from // process start; readiness, on its own service, additionally needs every // uplink covered (followCoverage). Neither waits for an identity to be // programmed: a node whose shard has not been assigned one yet would @@ -149,6 +156,7 @@ func runCmd(cfg *config.NATConfig) error { Scheme: mgr.GetScheme(), NodeName: nodeName, Datapath: datapath, + Disabled: !cfg.DatapathEnabled, CoverageEvents: coverageEvents, }).SetupWithManager(mgr); err != nil { return fmt.Errorf("setup EgressShard controller: %w", err) @@ -231,8 +239,12 @@ func newRootCommand() *cobra.Command { "Comma-separated fabric-facing uplink interfaces this shard's XDP datapath attaches to, "+ "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, \"chain\" installs it "+ - "behind the edge gateway's programs on a node where the gateway holds the hook") + "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") + 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") cmd.Flags().Bool("nat-echo-responder", false, "Answer ICMP and ICMPv6 Echo Requests addressed to this shard's own masquerade addresses, "+ "rate-limited, instead of dropping them") diff --git a/config/galactic-nat/base/daemonset.yaml b/config/galactic-nat/base/daemonset.yaml index d91e0e112..31c6eeb30 100644 --- a/config/galactic-nat/base/daemonset.yaml +++ b/config/galactic-nat/base/daemonset.yaml @@ -103,10 +103,15 @@ spec: - name: GALACTIC_NAT_ECHO_RESPONDER value: "false" # GALACTIC_NAT_XDP_ATTACH is left at its default, "direct": the - # shard attaches its own program to the uplinks. On a node that - # also runs galactic-gateway, which already holds the native XDP - # hook, apply ../overlays/chained/ to set it to "chain". See + # 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 # internal/config/nat.go's EnvNATXDPAttach. + # GALACTIC_NAT_DATAPATH_ENABLED, default "true", turns the shard + # off without removing the pod; see EnvNATDatapathEnabled. # Nothing about this shard's identity is set here. Its SID, # masquerade addresses and NAT64 prefix come from the # EgressShard whose spec.targetRef names this node, which the @@ -205,7 +210,8 @@ spec: # would silently produce a regular filesystem path instead of a # real bpf filesystem, masking the failure instead of # surfacing it at load time). The galactic-nat/ subdirectory - # itself is created by this container on first pin. + # itself is created by this container on first pin, as is + # galactic-xdp/, the shared XDP dispatcher's, in dispatch mode. - name: bpf-fs mountPath: /sys/fs/bpf volumes: diff --git a/containers/galactic-gateway/Dockerfile b/containers/galactic-gateway/Dockerfile index bf0bf69fe..d0658f673 100644 --- a/containers/galactic-gateway/Dockerfile +++ b/containers/galactic-gateway/Dockerfile @@ -50,6 +50,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && rm -rf /var/lib/apt/lists/* RUN go generate ./internal/plumbing/ebpf/prog/... RUN go generate ./internal/plumbing/ebpf/edgeprog/... +# internal/plumbing/ebpf/xdpattach, which this binary attaches through, +# links the shared XDP dispatcher's bindings too. +RUN go generate ./internal/plumbing/ebpf/xdpdispatch/... # Build galactic-gateway RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build \ diff --git a/containers/galactic-nat/Dockerfile b/containers/galactic-nat/Dockerfile index d7100f930..75ac9dfc9 100644 --- a/containers/galactic-nat/Dockerfile +++ b/containers/galactic-nat/Dockerfile @@ -38,11 +38,12 @@ RUN go mod download COPY cmd/ cmd/ COPY internal/ internal/ -# galactic-nat's build graph reaches all three of this module's eBPF -# program packages, so all three must be generated here -- none of their +# galactic-nat's build graph reaches all four of this module's eBPF +# program packages, so all four must be generated here -- none of their # bpf2go output (*_bpfel.go/.o, *_bpfeb.go/.o) is committed to git (see each -# package's doc.go). Only the first is loaded by this binary; the other two -# arrive transitively and still have to compile: +# package's doc.go). natprog, and in dispatch mode xdpdispatch, are loaded +# by this binary; the other two arrive transitively and still have to +# compile: # - natprog -- the sharded NAT66 egress XDP program, loaded directly # via internal/plumbing/ebpf/natattach. # - prog -- the SRv6 uSID TC-BPF program, via @@ -51,6 +52,8 @@ COPY internal/ internal/ # and internal/controller -> .../edgemap. galactic-nat # never loads it, but shares those packages with # galactic-gateway, so it links against the bindings. +# - xdpdispatch -- the node's shared XDP dispatcher, loaded in +# GALACTIC_NAT_XDP_ATTACH=dispatch mode. # Dropping any one of these turns into an "undefined: " build # failure in the go build step below, not a missing-file error. RUN apt-get update && apt-get install -y --no-install-recommends \ @@ -59,6 +62,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ RUN go generate ./internal/plumbing/ebpf/prog/... RUN go generate ./internal/plumbing/ebpf/edgeprog/... RUN go generate ./internal/plumbing/ebpf/natprog/... +RUN go generate ./internal/plumbing/ebpf/xdpdispatch/... # Build galactic-nat RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build \ diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 4971d6820..0748154c9 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -45,9 +45,10 @@ runs there too, as its own independent DaemonSet (the same one that runs on 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), 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 +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 +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` publish their own BGP reachability by writing a `BGPAdvertisement` CRD that diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index d08edf4cd..e01d8f460 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -43,13 +43,16 @@ flags, or a combination of both (CLI flags take precedence), with the | 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 | | 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` sets `GALACTIC_NAT_XDP_ATTACH=chain`, -since every edge node runs `galactic-gateway`; the binary's own default is -`direct`. +`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. That is the whole process configuration. The shard's identity — its SID, masquerade addresses and NAT64 prefix — is not process configuration: it @@ -121,18 +124,55 @@ 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 chain mode nothing is attached, so the uplinks are used for the -forwarding sysctls and to check coverage: an uplink that carries no XDP -program is reported missing the same way, since traffic the gateway never -hooks is traffic the chained shard never sees. +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 +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` or `chain`. Any -other value fails validation at startup. +How the datapath reaches its uplinks' XDP hook: `direct`, `dispatch` or +`chain`. Any other value fails validation at startup. - **`direct`** (the binary's default) attaches `nat_ingress` to every - resolved uplink in native driver mode, as described above. Use it on a - node with no `galactic-gateway`. + resolved uplink in native driver mode, as described above. The attachment + is not pinned, so it detaches when the process exits, and every restart + bounces each uplink, once on the detach and again on the attach. On a + node where an earlier `dispatch`-mode shard left the node's XDP + dispatcher on the uplinks, direct mode detaches it + first, if no other datapath's slot is live there. If one is, direct mode + fails to start and names the uplink, since detaching the dispatcher would + cut that datapath's traffic. Only the uplinks resolved at startup are + released: an uplink found later that still carries the dispatcher is + reported missing until `hack/xdp-dispatch-release.sh` frees it. +- **`dispatch`** puts the node's shared XDP dispatcher on every resolved + 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 + maps and root under `v1/`, one link per interface under `links/`. + + Because the links are pinned, the root stays attached when the shard's + process exits. The next process swaps its program into the slot, which the + kernel does atomically, so a restart neither bounces an uplink nor misses a + packet. The shard renews its slot's lease every 10s; a slot whose lease is + more than 120s old is skipped, so a shard that was removed, or that has been + down that long, stops claiming packets instead of translating with state + nothing maintains. + + Nothing in dispatch mode is all-or-nothing. An uplink the dispatcher cannot + hold yet, because another XDP program is attached there, the driver has no + native XDP, or attaching would take a bond down, is reported missing and + retried on the next link or route change. The first attach to each bond + member, and the wait for it to rejoin its bond, run under a node-wide lock, + so two datapaths sharing the dispatcher never bounce two members of one bond + at once. + + The dispatcher stays attached after the shard is removed from a node. + `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 @@ -156,6 +196,16 @@ other value fails validation at startup. 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 +an earlier process filled one, and keeps the node's `EgressShard` +unprogrammed: `Ready` and `Programmed` both read `False` with reason +`DatapathDisabled`, no identity is published, and its `BGPAdvertisement` is +withdrawn, so the fabric stops sending egress traffic to the node. Any other +datapath on the node, and the dispatcher itself, are left alone. Turning it +back on takes a pod restart, which in dispatch mode bounces nothing. + **`--nat-echo-responder` / `GALACTIC_NAT_ECHO_RESPONDER`** Whether the shard answers an ICMP or ICMPv6 Echo Request addressed to one of its own masquerade addresses. Off by default, and set explicitly to `false` in @@ -182,9 +232,10 @@ and nothing else. 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 chain mode it also opens the gateway's -`/sys/fs/bpf/galactic-edge/xdp_chain`, which the same `/sys/fs/bpf` mount -covers. +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. ## `EgressShard` CRD (`network.datumapis.com/v1alpha1`) @@ -519,10 +570,10 @@ kubectl exec -n galactic-system -- \ wget -qO- http://localhost:9182/metrics | grep galactic_nat_ ``` -Confirm the eBPF program is attached (in chain mode, installed in the -gateway's `xdp_chain` slot) and translating — on the `EgressShard` object, -`Ready` should read `DatapathAttached` and `Programmed` should read -`AddressesProgrammed`. `Ready` reading `UplinksMissing` names the uplinks +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 +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: ```sh @@ -615,6 +666,9 @@ knowing before you rely on this component in production: bounce the affected member (`ip link set down; ip link set up`). The bond partner carries traffic meanwhile, and the queue's discards stop at once. Nothing bounces it automatically. +- **The dispatcher outlives the shard.** In dispatch mode the root stays on + the uplinks after the shard is removed, passing every packet once the + slot's lease lapses. `hack/xdp-dispatch-release.sh` detaches it. - **The CNI's shard list is a second copy of every shard SID.** `GALACTIC_CNI_EGRESS_SHARD_SIDS` is set by hand and is not derived from `EgressShard` status, so the two can disagree. diff --git a/docs/node-labels.md b/docs/node-labels.md index 8766c27de..cac3536cd 100644 --- a/docs/node-labels.md +++ b/docs/node-labels.md @@ -184,8 +184,11 @@ 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. Compute nodes reach their site's shards over SRv6 -(`GALACTIC_CNI_EGRESS_SHARD_SIDS`). +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 +[docs/nat/configuration.md](nat/configuration.md)). Compute nodes reach their +site's shards over SRv6 (`GALACTIC_CNI_EGRESS_SHARD_SIDS`). ### `galactic.datumapis.com/galactic=router` diff --git a/galactic-nat b/galactic-nat new file mode 100755 index 000000000..e3f973546 Binary files /dev/null and b/galactic-nat differ diff --git a/internal/config/nat.go b/internal/config/nat.go index 43aff9c54..b05c95ffa 100644 --- a/internal/config/nat.go +++ b/internal/config/nat.go @@ -54,16 +54,30 @@ const ( EnvNATUplinkInterfaces = "GALACTIC_NAT_UPLINK_INTERFACES" // EnvNATXDPAttach selects how the datapath reaches its uplinks' XDP hook: - // NATXDPAttachDirect or NATXDPAttachChain. Optional, defaulting to direct. + // NATXDPAttachDirect, NATXDPAttachDispatch or NATXDPAttachChain. Optional, + // defaulting to direct. // - // An interface takes one native XDP program. On an edge node the gateway - // already holds that hook on the interfaces this shard needs, so the shard - // runs chained -- installed in the gateway's xdp_chain slot, receiving - // every packet the gateway does not claim -- instead of attaching itself. - // Direct mode there fails at attach; chain mode on a node with no gateway - // waits for a map that never appears. + // 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. + // + // Switching a node back from dispatch to direct is safe while nothing else + // uses the dispatcher there: direct mode detaches an idle dispatcher before + // attaching. While another datapath's slot is live it refuses to start. EnvNATXDPAttach = "GALACTIC_NAT_XDP_ATTACH" + // EnvNATDatapathEnabled turns the shard's datapath on or off. Optional, + // defaulting to true. Off, the process stays up and healthy but attaches + // nothing, empties its dispatcher slot, clears its identity and withdraws + // its BGPAdvertisement, so no traffic is drawn to a shard that does not + // translate. Every other datapath on the node keeps running. + EnvNATDatapathEnabled = "GALACTIC_NAT_DATAPATH_ENABLED" + // EnvNATEchoResponder makes the shard answer an ICMP or ICMPv6 Echo // Request addressed to one of its own masquerade addresses. Optional, // defaulting to false, under which the datapath drops such a request and @@ -77,10 +91,11 @@ const ( EnvNATEchoResponder = "GALACTIC_NAT_ECHO_RESPONDER" ) -// NATXDPAttachDirect and NATXDPAttachChain are EnvNATXDPAttach's values. +// EnvNATXDPAttach's values. const ( - NATXDPAttachDirect = "direct" - NATXDPAttachChain = "chain" + NATXDPAttachDirect = "direct" + NATXDPAttachDispatch = "dispatch" + NATXDPAttachChain = "chain" ) // --- NATConfig --------------------------------------------------------- @@ -102,10 +117,12 @@ type NATConfig struct { // comma-separated EnvNATUplinkInterfaces. Empty means auto-detect. UplinkInterfaces []string - // XDPAttach is NATXDPAttachDirect or NATXDPAttachChain, from - // EnvNATXDPAttach. + // XDPAttach is one of the NATXDPAttach values, from EnvNATXDPAttach. XDPAttach string + // DatapathEnabled is EnvNATDatapathEnabled. + DatapathEnabled bool + // EchoResponder is EnvNATEchoResponder. EchoResponder bool } @@ -123,6 +140,7 @@ func NewNATConfig() *NATConfig { v.SetDefault(KeyGRPCHealthPort, DefaultNATGRPCHealthPort) v.SetDefault("uplink_interfaces", "") v.SetDefault("xdp_attach", NATXDPAttachDirect) + v.SetDefault("datapath_enabled", true) v.SetDefault("echo_responder", false) cfg := &NATConfig{ @@ -145,6 +163,7 @@ func (c *NATConfig) BindFlags(flags *pflag.FlagSet) { {FlagGRPCHealthPort, KeyGRPCHealthPort}, {"nat-uplink-interfaces", "uplink_interfaces"}, {"nat-xdp-attach", "xdp_attach"}, + {"nat-datapath-enabled", "datapath_enabled"}, {"nat-echo-responder", "echo_responder"}, } for _, b := range bindings { @@ -165,6 +184,7 @@ 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.DatapathEnabled = c.v.GetBool("datapath_enabled") c.EchoResponder = c.v.GetBool("echo_responder") } @@ -179,9 +199,11 @@ func (c *NATConfig) Validate() error { if c.GRPCHealthPort < 1 || c.GRPCHealthPort > 65535 { return errors.New("grpc health port must be between 1 and 65535") } - if c.XDPAttach != NATXDPAttachDirect && c.XDPAttach != NATXDPAttachChain { - return fmt.Errorf("%s must be %q or %q, got %q", - EnvNATXDPAttach, NATXDPAttachDirect, NATXDPAttachChain, c.XDPAttach) + switch c.XDPAttach { + case NATXDPAttachDirect, NATXDPAttachDispatch, NATXDPAttachChain: + default: + return fmt.Errorf("%s must be %q, %q or %q, got %q", EnvNATXDPAttach, + NATXDPAttachDirect, NATXDPAttachDispatch, NATXDPAttachChain, c.XDPAttach) } return nil } diff --git a/internal/config/nat_test.go b/internal/config/nat_test.go index ce0e03623..a533699bd 100644 --- a/internal/config/nat_test.go +++ b/internal/config/nat_test.go @@ -204,6 +204,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: "tc", set: true, wantErr: true}, } @@ -270,3 +271,47 @@ func TestNATConfigEchoResponder(t *testing.T) { }) } } + +// TestNATConfigDatapathEnabled covers the datapath switch's three tiers. On is +// the default that matters: a shard that came up disabled after an upgrade +// would withdraw its advertisement and stop translating. +func TestNATConfigDatapathEnabled(t *testing.T) { + tests := []struct { + name string + env string + flag string + want bool + }{ + {name: "default", want: true}, + {name: "env off", env: testBoolFalse, want: false}, + {name: "env on", env: testBoolTrue, want: true}, + {name: "flag off over env on", env: testBoolTrue, flag: testBoolFalse, want: false}, + {name: "flag on over env off", env: testBoolFalse, flag: testBoolTrue, want: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.env != "" { + t.Setenv(EnvNATDatapathEnabled, tt.env) + } + flags := pflag.NewFlagSet("test", pflag.ContinueOnError) + flags.String(FlagNodeName, "", "") + flags.Int(FlagMetricsPort, DefaultNATMetricsPort, "") + flags.Int(FlagGRPCHealthPort, DefaultNATGRPCHealthPort, "") + flags.String("nat-uplink-interfaces", "", "") + flags.String("nat-xdp-attach", NATXDPAttachDirect, "") + flags.Bool("nat-datapath-enabled", true, "") + flags.Bool("nat-echo-responder", false, "") + if tt.flag != "" { + if err := flags.Set("nat-datapath-enabled", tt.flag); err != nil { + t.Fatalf("set flag: %v", err) + } + } + + cfg := NewNATConfig() + cfg.BindFlags(flags) + if cfg.DatapathEnabled != tt.want { + t.Errorf("DatapathEnabled = %v, want %v", cfg.DatapathEnabled, tt.want) + } + }) + } +} diff --git a/internal/controller/egressshard_controller.go b/internal/controller/egressshard_controller.go index f02649818..0bdecd540 100644 --- a/internal/controller/egressshard_controller.go +++ b/internal/controller/egressshard_controller.go @@ -85,6 +85,10 @@ const ( // the datapath is attached but not to every uplink it should cover. reasonEgressDatapathUplinksMissing = "UplinksMissing" + // reasonEgressDatapathDisabled is the Ready and Programmed condition reason + // while this node's datapath is turned off by configuration. + reasonEgressDatapathDisabled = "DatapathDisabled" + // reasonEgressShardConflict is the Programmed condition reason on every // EgressShard targeting a node that more than one targets. The datapath // holds one identity, so none of them is programmed until the conflict is @@ -121,6 +125,13 @@ type EgressShardReconciler struct { // EgressDatapath's doc comment. Datapath EgressDatapath + // Disabled is set when this node's datapath is turned off by + // configuration. The reconciler then keeps the datapath cleared and every + // shard targeting the node unprogrammed, which withdraws its + // advertisement, so the fabric stops sending egress traffic to a node that + // will not translate it. + Disabled bool + // CoverageEvents, when non-nil, delivers an event whenever the datapath's // uplink coverage changes, so Ready follows it without waiting for an // unrelated EgressShard or BGPRouter event. @@ -177,6 +188,8 @@ func (r *EgressShardReconciler) Reconcile(ctx context.Context, req ctrl.Request) // syncNode drives the datapath from every live EgressShard targeting this node // and publishes the result on each of them: // +// - the datapath turned off (Disabled): it is cleared and every one of them +// reports it, so each withdraws its advertisement. // - none: the datapath is cleared. Nothing assigns this node an identity, so // it must not keep translating with one a deleted shard left behind. // - one: the datapath is programmed from its spec. @@ -203,13 +216,23 @@ func (r *EgressShardReconciler) syncNode(ctx context.Context) error { } var programmed metav1.Condition - switch len(mine) { - case 0: + switch { + case r.Disabled: + if err := r.Datapath.Clear(); err != nil { + return fmt.Errorf("clear egress translation datapath: %w", err) + } + programmed = metav1.Condition{ + Type: bgpv1alpha1.ConditionTypeProgrammed, + Status: metav1.ConditionFalse, + Reason: reasonEgressDatapathDisabled, + Message: fmt.Sprintf("The egress translation datapath on node %s is turned off", r.NodeName), + } + case len(mine) == 0: if err := r.Datapath.Clear(); err != nil { return fmt.Errorf("clear egress translation datapath: %w", err) } return nil - case 1: + case len(mine) == 1: var err error if programmed, err = r.program(mine[0]); err != nil { // Publish why before returning the error for a retry. @@ -329,7 +352,7 @@ func (r *EgressShardReconciler) publish(ctx context.Context, shard *bgpv1alpha1. // A conflicting shard publishes no identity even while the datapath holds // one, which it cannot here: syncNode clears it first. Checking the // condition rather than relying on that keeps the two from drifting. - if programmed.Reason != reasonEgressShardConflict { + if programmed.Reason != reasonEgressShardConflict && programmed.Reason != reasonEgressDatapathDisabled { if identity, ok := r.Datapath.Programmed(); ok { shardCopy.Status.ShardSID = addrString(identity.ShardSID) shardCopy.Status.ShardAddressIPv6 = addrString(identity.ShardAddressIPv6) @@ -505,6 +528,14 @@ func withdrawShardAdvertisement(ctx context.Context, c client.Client, namespace, // attachment state. A nil datapath, not expected in production, is treated as // not attached rather than a panic. func (r *EgressShardReconciler) readyCondition() metav1.Condition { + if r.Disabled { + return metav1.Condition{ + Type: bgpv1alpha1.ConditionTypeReady, + Status: metav1.ConditionFalse, + Reason: reasonEgressDatapathDisabled, + Message: "Egress translation datapath is turned off on this node", + } + } if r.Datapath != nil && r.Datapath.Attached() { if missing := r.Datapath.MissingUplinks(); len(missing) > 0 { return metav1.Condition{ diff --git a/internal/controller/egressshard_controller_test.go b/internal/controller/egressshard_controller_test.go index 426312718..40a1ca652 100644 --- a/internal/controller/egressshard_controller_test.go +++ b/internal/controller/egressshard_controller_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -748,3 +749,45 @@ func TestEgressShardReconciler_WithdrawsAdvertisementWhenShardObjectAlreadyGone( t.Error("datapath still programmed after its EgressShard object disappeared") } } + +// TestEgressShardReconciler_DisabledWithdrawsAndProgramsNothing: a node whose +// datapath is turned off must stop drawing egress traffic, so the identity it +// held is cleared, its advertisement withdrawn, and both conditions say why. +func TestEgressShardReconciler_DisabledWithdrawsAndProgramsNothing(t *testing.T) { + scheme := nat66TestScheme(t) + shard := newEgressShard(testNAT66NodeA) + router := newTestNAT66Router() + c := newIndexedClientBuilder(scheme).WithObjects(shard, router).WithStatusSubresource(shard).Build() + datapath := &fakeEgressDatapath{attached: true} + r := newNAT66Reconciler(c, scheme, datapath) + + // Enabled first, so there is an identity and an advertisement to lose. + if _, err := reconcileShard(t, r, c); err != nil { + t.Fatalf("enabled Reconcile() error = %v", err) + } + advKey := client.ObjectKey{Namespace: testNAT66Namespace, Name: shardAdvertisementName(testNAT66ShardName)} + if err := c.Get(context.Background(), advKey, &bgpv1alpha1.BGPAdvertisement{}); err != nil { + t.Fatalf("advertisement not created while enabled: %v", err) + } + + r.Disabled = true + programsBefore := datapath.programs + got, err := reconcileShard(t, r, c) + if err != nil { + t.Fatalf("disabled Reconcile() error = %v", err) + } + if datapath.programs != programsBefore { + t.Errorf("disabled reconciler programmed the datapath") + } + if _, ok := datapath.Programmed(); ok { + t.Errorf("datapath still holds an identity while disabled") + } + if got.Status.ShardSID != "" || got.Status.ShardAddressIPv6 != "" { + t.Errorf("status publishes identity %q/%q while disabled", got.Status.ShardSID, got.Status.ShardAddressIPv6) + } + assertCondition(t, got, bgpv1alpha1.ConditionTypeProgrammed, metav1.ConditionFalse, reasonEgressDatapathDisabled) + assertCondition(t, got, bgpv1alpha1.ConditionTypeReady, metav1.ConditionFalse, reasonEgressDatapathDisabled) + if err := c.Get(context.Background(), advKey, &bgpv1alpha1.BGPAdvertisement{}); !apierrors.IsNotFound(err) { + t.Errorf("advertisement still present while disabled: err = %v", err) + } +} diff --git a/internal/plumbing/ebpf/xdpattach/dispatchset.go b/internal/plumbing/ebpf/xdpattach/dispatchset.go new file mode 100644 index 000000000..c6d4fd9b4 --- /dev/null +++ b/internal/plumbing/ebpf/xdpattach/dispatchset.go @@ -0,0 +1,237 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpattach + +import ( + "context" + "errors" + "fmt" + "log/slog" + "slices" + "sync" + + "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" +) + +// DispatchSet keeps one datapath's slot reachable on a set of interfaces +// through the node's shared XDP dispatcher (xdpdispatch), in place of the +// datapath's own attachments. It is Set's counterpart for a datapath that +// shares the hook. +// +// It never attaches the datapath's program to an interface. It makes sure the +// dispatcher's root is there, and that the interface carries the datapath's +// role, and reads coverage back from the pinned state. The datapath fills its +// slot and renews the slot's lease itself. +// +// Unlike Set, nothing here is all-or-nothing and nothing is ever detached: an +// interface the dispatcher cannot hold yet is reported missing and tried again +// on the next Reconcile, and an interface that leaves the set keeps the root +// (another datapath may still use it) and its role (an auto-detected uplink +// set is often partial while routing converges). +type DispatchSet struct { + backend dispatchBackend + + mu sync.Mutex + missing []string +} + +// dispatchBackend is what DispatchSet needs from the dispatcher, so its tests +// can run without loading anything into the kernel. +type dispatchBackend interface { + // linked reports whether the root already holds ifindex. + linked(ifindex int) (bool, error) + // ensure, under the dispatch lock, attaches the root to ifindex if it is + // not there and adds the datapath's role. It calls guard first, under the + // lock, when the root is not there yet, and gives up if guard fails. When + // it attached, it calls afterBounce before releasing the lock, even if a + // later step failed, since the interface bounced either way. + ensure(ctx context.Context, ifindex int, guard, afterBounce func() error) (bounced bool, err error) + // coverage is nil when the datapath's slot sees ifindex's traffic. + coverage(ifindex int) error + // prune releases pinned links whose interface is gone. + prune(ctx context.Context) error +} + +// NewDispatchSet returns a DispatchSet putting program's slot on interfaces +// with role. +func NewDispatchSet(d *xdpdispatch.Dispatcher, slot xdpdispatch.Slot, + role xdpdispatch.Role, program *ebpf.Program, +) (*DispatchSet, error) { + if d == nil { + return nil, errors.New("xdpattach: dispatcher is nil") + } + if program == nil { + return nil, errors.New("xdpattach: program is nil") + } + return &DispatchSet{backend: &kernelDispatch{d: d, slot: slot, role: role, program: program}}, nil +} + +// Reconcile brings every interface in desired under the dispatcher with this +// datapath's role, and returns the ones its slot does not cover afterwards. +// +// The guards Set applies before an attach apply here too, and only when the +// root is not on the interface yet, since nothing else bounces it: a +// definite lack of native XDP support leaves the interface missing, and so +// does a bond member whose bounce would take the bond down. The guards, the +// attach, and the wait for a bounced bond member to rejoin its aggregate all +// run under the dispatch lock, so no other process bounces a second member of +// the same bond in between. +func (s *DispatchSet) Reconcile(ctx context.Context, desired []string) []string { + if err := s.backend.prune(ctx); err != nil { + slog.Warn("xdpattach: cannot prune dispatcher links of removed interfaces", "err", err) + } + + var missing []string + blocked := false + for _, name := range desired { + l, err := linkByNameFn(name) + if err != nil { + slog.Warn("xdpattach: cannot find interface for the XDP dispatcher, will retry", "interface", name, "err", err) + missing = append(missing, name) + continue + } + ifindex := l.Attrs().Index + + linked, err := s.backend.linked(ifindex) + if err != nil { + slog.Warn("xdpattach: cannot read the XDP dispatcher link, will retry", "interface", name, "err", err) + missing = append(missing, name) + continue + } + if !linked && blocked { + missing = append(missing, name) + continue + } + + var bondErr error + bounced, err := s.backend.ensure(ctx, ifindex, + func() error { return s.attachable(name) }, + func() error { + bondErr = waitBondSlaveReady(name, BondReadyTimeout) + return nil + }) + if bondErr != nil { + slog.Warn("xdpattach: dispatcher interface has not rejoined its bond; deferring the rest", + "interface", name, "err", bondErr) + blocked = true + } + if err != nil { + slog.Warn("xdpattach: cannot put the XDP dispatcher on interface yet, will retry", + "interface", name, "err", err) + missing = append(missing, name) + continue + } + if bounced { + slog.Info("xdpattach: attached the XDP dispatcher to interface", "interface", name) + } + } + + for _, name := range desired { + if slices.Contains(missing, name) { + continue + } + l, err := linkByNameFn(name) + if err != nil { + missing = append(missing, name) + continue + } + if err := s.backend.coverage(l.Attrs().Index); err != nil { + slog.Warn("xdpattach: datapath does not see this interface's traffic through the XDP dispatcher", + "interface", name, "reason", err) + missing = append(missing, name) + } + } + + s.mu.Lock() + s.missing = slices.Clone(missing) + s.mu.Unlock() + return missing +} + +// attachable applies the pre-attach guards to name. +func (s *DispatchSet) attachable(name string) error { + if err := checkNativeXDPSupport([]string{name}); err != nil { + return err + } + isolates, err := bounceIsolatesBond(name) + if err != nil { + return err + } + if isolates { + return fmt.Errorf("xdpattach: %q is the only member of its bond carrying traffic; "+ + "attaching now would take the bond down", name) + } + return nil +} + +// Missing returns what the last Reconcile reported missing. +func (s *DispatchSet) Missing() []string { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.missing) +} + +// kernelDispatch is dispatchBackend over the pinned dispatcher. +type kernelDispatch struct { + d *xdpdispatch.Dispatcher + slot xdpdispatch.Slot + role xdpdispatch.Role + program *ebpf.Program +} + +func (k *kernelDispatch) linked(ifindex int) (bool, error) { return k.d.Linked(ifindex) } + +func (k *kernelDispatch) ensure(ctx context.Context, ifindex int, guard, afterBounce func() error) (bool, error) { + // Nothing to do, and no reason to contend for the node-wide lock, when the + // root is there and the interface already carries the role. + if linked, err := k.d.Linked(ifindex); err == nil && linked { + if roles, err := k.d.Roles(ifindex); err == nil && roles&k.role == k.role { + return false, nil + } + } + + l, err := k.d.Lock(ctx) + if err != nil { + return false, err + } + defer l.Unlock() + + linked, err := k.d.Linked(ifindex) + if err != nil { + return false, err + } + if !linked { + if err := guard(); err != nil { + return false, err + } + } + bounced, err := l.EnsureLink(ifindex) + if bounced { + if bounceErr := afterBounce(); bounceErr != nil && err == nil { + err = bounceErr + } + } + if err != nil { + return bounced, err + } + if err := l.SetRole(ifindex, k.role); err != nil { + return bounced, err + } + return bounced, nil +} + +func (k *kernelDispatch) coverage(ifindex int) error { return k.d.Coverage(ifindex, k.slot, k.program) } + +func (k *kernelDispatch) prune(ctx context.Context) error { + l, err := k.d.Lock(ctx) + if err != nil { + return err + } + defer l.Unlock() + _, err = l.PruneDefunct() + return err +} diff --git a/internal/plumbing/ebpf/xdpattach/dispatchset_test.go b/internal/plumbing/ebpf/xdpattach/dispatchset_test.go new file mode 100644 index 000000000..e51869650 --- /dev/null +++ b/internal/plumbing/ebpf/xdpattach/dispatchset_test.go @@ -0,0 +1,208 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package xdpattach + +import ( + "context" + "errors" + "slices" + "testing" + + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/ebpf/edgepreflight" + "go.datum.net/galactic/internal/plumbing/ebpf/xdpdispatch" +) + +// fakeDispatch is a dispatchBackend over in-memory state. +type fakeDispatch struct { + linkedIdx map[int]bool + ensureErr map[int]error + // afterAttachErr fails ensure after the attach, as a failed pin does. + afterAttachErr map[int]error + coverageErr map[int]error + ensured []int + prunes int +} + +func newFakeDispatch() *fakeDispatch { + return &fakeDispatch{ + linkedIdx: map[int]bool{}, ensureErr: map[int]error{}, afterAttachErr: map[int]error{}, + coverageErr: map[int]error{}, + } +} + +func (f *fakeDispatch) linked(ifindex int) (bool, error) { return f.linkedIdx[ifindex], nil } + +func (f *fakeDispatch) ensure(_ context.Context, ifindex int, guard, afterBounce func() error) (bool, error) { + if !f.linkedIdx[ifindex] { + if err := guard(); err != nil { + return false, err + } + } + if err := f.ensureErr[ifindex]; err != nil { + return false, err + } + f.ensured = append(f.ensured, ifindex) + if f.linkedIdx[ifindex] { + return false, nil + } + f.linkedIdx[ifindex] = true + bounceErr := afterBounce() + if err := f.afterAttachErr[ifindex]; err != nil { + return true, err + } + return true, bounceErr +} + +func (f *fakeDispatch) coverage(ifindex int) error { + if !f.linkedIdx[ifindex] { + return xdpdispatch.ErrNoLink + } + return f.coverageErr[ifindex] +} + +func (f *fakeDispatch) prune(context.Context) error { + f.prunes++ + return nil +} + +func TestDispatchSet_PutsTheDispatcherOnEveryInterface(t *testing.T) { + newSetHost(t, plainLink(testUplink0, 10), plainLink(testUplink1, 11)) + fake := newFakeDispatch() + s := &DispatchSet{backend: fake} + + if missing := s.Reconcile(context.Background(), []string{testUplink0, testUplink1}); len(missing) != 0 { + t.Fatalf("missing = %v, want none", missing) + } + if !slices.Equal(fake.ensured, []int{10, 11}) { + t.Errorf("ensured %v, want [10 11]", fake.ensured) + } + if fake.prunes != 1 { + t.Errorf("pruned %d times, want once per Reconcile", fake.prunes) + } +} + +// TestDispatchSet_ALinkedInterfaceSkipsTheAttachGuards: another datapath +// already put the root there, so nothing bounces and the native-support check +// has nothing to protect. +func TestDispatchSet_ALinkedInterfaceSkipsTheAttachGuards(t *testing.T) { + newSetHost(t, plainLink(testUplink0, 10)) + edgepreflight.InterfaceXDPFn = func(string) (bool, error) { + t.Fatal("native support checked for an interface the root already holds") + return false, nil + } + fake := newFakeDispatch() + fake.linkedIdx[10] = true + s := &DispatchSet{backend: fake} + + if missing := s.Reconcile(context.Background(), []string{testUplink0}); len(missing) != 0 { + t.Errorf("missing = %v, want none", missing) + } +} + +func TestDispatchSet_NoNativeSupportIsMissingAndUntouched(t *testing.T) { + newSetHost(t, plainLink(testUplink0, 10)) + edgepreflight.InterfaceXDPFn = func(string) (bool, error) { return false, nil } + fake := newFakeDispatch() + s := &DispatchSet{backend: fake} + + if missing := s.Reconcile(context.Background(), []string{testUplink0}); !slices.Equal(missing, []string{testUplink0}) { + t.Errorf("missing = %v, want [%s]", missing, testUplink0) + } + if len(fake.ensured) != 0 || fake.linkedIdx[10] { + t.Errorf("ensured %v on an interface with no native XDP support", fake.ensured) + } +} + +// TestDispatchSet_AForeignProgramIsMissingUntilItGoes is issue #717's +// coverage case at this layer: an interface another XDP program holds is +// reported, then covered once that program is gone. +func TestDispatchSet_AForeignProgramIsMissingUntilItGoes(t *testing.T) { + newSetHost(t, plainLink(testUplink0, 10)) + fake := newFakeDispatch() + fake.ensureErr[10] = xdpdispatch.ErrForeignProgram + s := &DispatchSet{backend: fake} + + if missing := s.Reconcile(context.Background(), []string{testUplink0}); !slices.Equal(missing, []string{testUplink0}) { + t.Fatalf("missing = %v under a foreign program, want [%s]", missing, testUplink0) + } + if got := s.Missing(); !slices.Equal(got, []string{testUplink0}) { + t.Errorf("Missing() = %v, want [%s]", got, testUplink0) + } + + delete(fake.ensureErr, 10) + if missing := s.Reconcile(context.Background(), []string{testUplink0}); len(missing) != 0 { + t.Errorf("missing = %v after the foreign program went, want none", missing) + } +} + +func TestDispatchSet_UncoveredSlotIsMissing(t *testing.T) { + newSetHost(t, plainLink(testUplink0, 10)) + fake := newFakeDispatch() + fake.coverageErr[10] = xdpdispatch.ErrLeaseExpired + s := &DispatchSet{backend: fake} + + if missing := s.Reconcile(context.Background(), []string{testUplink0}); !slices.Equal(missing, []string{testUplink0}) { + t.Errorf("missing = %v with the slot's lease expired, want [%s]", missing, testUplink0) + } +} + +// TestDispatchSet_WaitsForABondMemberBeforeTheNext: the first member the root +// is attached to never rejoins its aggregate, so the second is left alone +// rather than bounced too. +func TestDispatchSet_WaitsForABondMemberBeforeTheNext(t *testing.T) { + first := slaveLink(gateSlave, netlink.BondLinkUp, lacpSyncOnly) + first.Attrs().Index = 20 + second := slaveLink(gateSlaveSib, netlink.BondLinkUp, lacpCarrying) + second.Attrs().Index = 21 + newSetHost(t, lacpMaster(), first, second) + orig := BondReadyTimeout + BondReadyTimeout = 0 + t.Cleanup(func() { BondReadyTimeout = orig }) + + fake := newFakeDispatch() + s := &DispatchSet{backend: fake} + missing := s.Reconcile(context.Background(), []string{gateSlave, gateSlaveSib}) + + if !slices.Equal(fake.ensured, []int{20}) { + t.Errorf("ensured %v, want only the first member [20]", fake.ensured) + } + if !slices.Equal(missing, []string{gateSlaveSib}) { + t.Errorf("missing = %v, want the deferred member [%s]", missing, gateSlaveSib) + } +} + +func TestNewDispatchSet_RejectsNil(t *testing.T) { + if _, err := NewDispatchSet(nil, xdpdispatch.SlotNAT, xdpdispatch.RoleEgress, nil); err == nil { + t.Error("NewDispatchSet(nil dispatcher) succeeded") + } +} + +// TestDispatchSet_AFailedPinStillWaitsForTheBond: the attach bounced the +// member even though pinning then failed, so the bond wait must still gate +// the next member. +func TestDispatchSet_AFailedPinStillWaitsForTheBond(t *testing.T) { + first := slaveLink(gateSlave, netlink.BondLinkUp, lacpSyncOnly) + first.Attrs().Index = 20 + second := slaveLink(gateSlaveSib, netlink.BondLinkUp, lacpCarrying) + second.Attrs().Index = 21 + newSetHost(t, lacpMaster(), first, second) + orig := BondReadyTimeout + BondReadyTimeout = 0 + t.Cleanup(func() { BondReadyTimeout = orig }) + + fake := newFakeDispatch() + fake.afterAttachErr[20] = errors.New("pin link: permission denied") + s := &DispatchSet{backend: fake} + missing := s.Reconcile(context.Background(), []string{gateSlave, gateSlaveSib}) + + if !slices.Equal(fake.ensured, []int{20}) { + t.Errorf("ensured %v, want only the first member [20]", fake.ensured) + } + if !slices.Equal(missing, []string{gateSlave, gateSlaveSib}) { + t.Errorf("missing = %v, want both members", missing) + } +} diff --git a/internal/plumbing/ebpf/xdpdispatch/dispatcher.go b/internal/plumbing/ebpf/xdpdispatch/dispatcher.go index 0a2aa9d45..846426f00 100644 --- a/internal/plumbing/ebpf/xdpdispatch/dispatcher.go +++ b/internal/plumbing/ebpf/xdpdispatch/dispatcher.go @@ -311,6 +311,25 @@ func (d *Dispatcher) linkPath(ifindex int) string { return filepath.Join(d.dir, linksDirName, strconv.Itoa(ifindex)) } +// Linked reports whether a live pinned dispatcher link holds ifindex, which +// is when EnsureLink would neither attach nor bounce it. +func (d *Dispatcher) Linked(ifindex int) (bool, error) { + pinned, err := link.LoadPinnedLink(d.linkPath(ifindex), nil) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("xdpdispatch: load pinned link for ifindex %d: %w", ifindex, err) + } + defer pinned.Close() //nolint:errcheck // our own descriptor + info, err := pinned.Info() + if err != nil { + return false, fmt.Errorf("xdpdispatch: read link info for ifindex %d: %w", ifindex, err) + } + xdp := info.XDP() + return xdp != nil && int(xdp.Ifindex) == ifindex, nil +} + // Locked is the dispatch lock, held. Every call that changes shared state // other than a datapath's own slot program or lease is a method here, so it // cannot run without the lock. Release it with Unlock. diff --git a/internal/plumbing/ebpf/xdpdispatch/link_test.go b/internal/plumbing/ebpf/xdpdispatch/link_test.go index 0339e11ac..03044cb04 100644 --- a/internal/plumbing/ebpf/xdpdispatch/link_test.go +++ b/internal/plumbing/ebpf/xdpdispatch/link_test.go @@ -374,9 +374,15 @@ func TestRelease_DetachesTheRoot(t *testing.T) { t.Fatalf("SetRole: %v", err) } + if linked, err := d.Linked(ifindex); err != nil || !linked { + t.Fatalf("Linked before Release = %v, %v; want true", linked, err) + } if err := locked(t, d).Release(ifindex); err != nil { t.Fatalf("Release: %v", err) } + if linked, err := d.Linked(ifindex); err != nil || linked { + t.Errorf("Linked after Release = %v, %v; want false", linked, err) + } if got := attachedProgID(t, ifindex); got != 0 { t.Errorf("ifindex %d still runs program %d after Release", ifindex, got) }