From cdeda23511eaf610f49a4b78f1e150b41fbfb755 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Tue, 1 Dec 2026 19:49:04 -0500 Subject: [PATCH] fix(attach): Attach usid_ingress to uplinks through tcx Cilium deletes every classic tc filter on a device it attaches to through tcx, after each reload of its own programs, without checking whose they are. It reloads on pod and link churn, so galactic_usid_ingress vanished from shared uplinks for about a second at a time until the watch loop put it back. In that window the CNI health check and the gateway's local delivery check both failed, and core stopped serving the node's backends. usid_ingress now attaches through a tcx link pinned under /sys/fs/bpf/galactic/links/usid_ingress, which Cilium does not touch. The link goes at the head of the chain. Cilium's cil_from_netdev returns TC_ACT_OK, which tcx treats as final, so a program behind it never sees the packets it passes; the classic filter had the same blind spot. usid_ingress returns TC_ACT_UNSPEC for packets it does not handle, so Cilium still sees all other traffic. A restart updates the pinned link in place and removes any classic filter an earlier version left. Kernels without tcx keep the classic filter. A renamed device's pin is adopted under the new name. Pins whose device is gone are removed on every attach and reconcile. When another program's link lands ahead of ours, the health check asks for a reconcile, which moves ours back to the head. Cilium attaches its own links at the tail and updates them in place, so it never triggers this. The kernel refuses one program twice on a hook, so the classic filter stands in during the move and stays when the move fails. A failed move is logged, not returned, since Start treats attach errors as fatal. The health check and IngressAttachedTo accept either attachment. Fixes #1561 --- internal/plumbing/ebpf/attach/attach.go | 82 +-- internal/plumbing/ebpf/attach/attach_test.go | 16 +- internal/plumbing/ebpf/attach/doc.go | 21 +- .../ebpf/attach/egress_reattach_test.go | 4 +- internal/plumbing/ebpf/attach/health.go | 30 +- internal/plumbing/ebpf/attach/tcx.go | 480 ++++++++++++++++++ .../plumbing/ebpf/attach/tcx_root_test.go | 331 ++++++++++++ internal/plumbing/ebpf/attach/tcx_test.go | 479 +++++++++++++++++ internal/plumbing/ebpf/attach/watch.go | 3 +- internal/plumbing/ebpf/attach/watch_test.go | 102 ++-- 10 files changed, 1428 insertions(+), 120 deletions(-) create mode 100644 internal/plumbing/ebpf/attach/tcx.go create mode 100644 internal/plumbing/ebpf/attach/tcx_root_test.go create mode 100644 internal/plumbing/ebpf/attach/tcx_test.go diff --git a/internal/plumbing/ebpf/attach/attach.go b/internal/plumbing/ebpf/attach/attach.go index f90c4f34c..93633829e 100644 --- a/internal/plumbing/ebpf/attach/attach.go +++ b/internal/plumbing/ebpf/attach/attach.go @@ -333,13 +333,13 @@ func HasDeliver(ifaceName string) (bool, error) { } // Attach attaches program to the ingress hook of each named interface, through a -// clsact qdisc and a direct-action BPF filter, creating the qdisc if it does not -// exist. +// pinned tcx link at the head of the tcx chain, or through a clsact qdisc and a +// direct-action BPF filter on a kernel without tcx. tcx.go says why. // -// Re-running against an interface that already carries this package's filter -// replaces it rather than stacking a duplicate, so repeated calls are -// idempotent. Every interface is attempted even if one fails, and the failures -// are joined and returned together. +// Re-running against an interface that already carries this package's link or +// filter updates it in place rather than stacking a duplicate, so repeated +// calls are idempotent. Every interface is attempted even if one fails, and the +// failures are joined and returned together. func Attach(program *ebpf.Program, ifaceNames []string) error { if program == nil { return errors.New("attach: program is nil") @@ -348,9 +348,10 @@ func Attach(program *ebpf.Program, ifaceNames []string) error { return errors.New("attach: no interfaces to attach to") } + sweepIngressLinks() var errs []error for _, name := range ifaceNames { - if err := attachOne(program, name, filterName, netlink.HANDLE_MIN_INGRESS); err != nil { + if err := attachIngressOne(program, name); err != nil { errs = append(errs, fmt.Errorf("interface %q: %w", name, err)) } } @@ -688,10 +689,17 @@ func attachOneAtPriority(program *ebpf.Program, name, tcFilterName string, paren err = fmt.Errorf("find link: %w", err) return err } + err = replaceFilter(program, link, tcFilterName, parent, priority, handle) + return err +} - if err = ensureClsact(link); err != nil { - err = fmt.Errorf("ensure clsact qdisc: %w", err) - return err +// replaceFilter attaches program to link as the direct-action filter +// tcFilterName, creating the clsact qdisc if needed. Unlike attachOneAtPriority +// it reports nothing to the attach hook, for callers that report on their own. +func replaceFilter(program *ebpf.Program, link netlink.Link, tcFilterName string, parent uint32, + priority uint16, handle uint32) error { + if err := ensureClsact(link); err != nil { + return fmt.Errorf("ensure clsact qdisc: %w", err) } filter := &netlink.BpfFilter{ @@ -706,63 +714,67 @@ func attachOneAtPriority(program *ebpf.Program, name, tcFilterName string, paren Name: tcFilterName, DirectAction: true, } - if err = filterReplaceFn(filter); err != nil { - err = fmt.Errorf("attach tc-bpf filter: %w", err) - return err + if err := filterReplaceFn(filter); err != nil { + return fmt.Errorf("attach tc-bpf filter: %w", err) } return nil } -// Detach removes this package's ingress filter from each named interface, -// leaving the clsact qdisc in place since another filter or a future attach may -// still need it. +// Detach removes this package's ingress tcx link and filter from each named +// interface, leaving the clsact qdisc in place since another filter or a future +// attach may still need it. // -// An interface that already lacks the filter, or no longer exists at all, is not -// an error: the watch loop detaches interfaces that just left the resolved set, +// An interface that already lacks both, or no longer exists at all, is not an +// error: the watch loop detaches interfaces that just left the resolved set, // by which time one may already be gone. Every interface is attempted even if // one fails, and the failures are joined and returned together. func Detach(ifaceNames []string) error { var errs []error for _, name := range ifaceNames { - if err := detachOne(name, filterName, netlink.HANDLE_MIN_INGRESS); err != nil { + if err := detachIngressOne(name); err != nil { errs = append(errs, fmt.Errorf("interface %q: %w", name, err)) } } return errors.Join(errs...) } -// detachOne removes the filter named tcFilterName from one interface's TC hook -// at parent, if present. Like attachOne it is the choke point every detach path -// goes through, so instrumenting it here observes every attempt whatever the -// caller. An interface that already lacks the filter, or no longer exists, is -// not an error. -func detachOne(name, tcFilterName string, parent uint32) (err error) { +// detachIngressOne removes usid_ingress from one interface, whichever way it +// was attached. +func detachIngressOne(name string) (err error) { defer func() { detachHook(name, err) }() + err = errors.Join(detachIngressLink(name), detachFilter(name, filterName, netlink.HANDLE_MIN_INGRESS)) + return err +} +// detachFilter removes the filter named tcFilterName from one interface's TC +// hook at parent, if present. An interface that already lacks the filter, or no +// longer exists, is not an error. +func detachFilter(name, tcFilterName string, parent uint32) error { link, err := netlink.LinkByName(name) if err != nil { var notFound netlink.LinkNotFoundError if errors.As(err, ¬Found) { - err = nil return nil } - err = fmt.Errorf("find link: %w", err) - return err + return fmt.Errorf("find link: %w", err) } + return deleteFilters(link, tcFilterName, parent) +} - filters, listErr := netlink.FilterList(link, parent) - if listErr != nil { - err = fmt.Errorf("list filters: %w", listErr) - return err +// deleteFilters removes every BPF filter named tcFilterName from link's hook at +// parent. It reports nothing to the detach hook. +func deleteFilters(link netlink.Link, tcFilterName string, parent uint32) error { + filters, err := filterListFn(link, parent) + if err != nil { + return fmt.Errorf("list filters: %w", err) } for _, f := range filters { bpfFilter, ok := f.(*netlink.BpfFilter) if !ok || bpfFilter.Name != tcFilterName { continue } - if delErr := filterDeleteFn(f); delErr != nil { - err = fmt.Errorf("delete tc-bpf filter: %w", delErr) - return err + if err := filterDeleteFn(f); err != nil { + return fmt.Errorf("delete tc-bpf filter: %w", err) } } return nil diff --git a/internal/plumbing/ebpf/attach/attach_test.go b/internal/plumbing/ebpf/attach/attach_test.go index a0e401d17..bc86d2894 100644 --- a/internal/plumbing/ebpf/attach/attach_test.go +++ b/internal/plumbing/ebpf/attach/attach_test.go @@ -152,8 +152,8 @@ func TestLoadAttach_SurvivesRestartWithMapsIntact(t *testing.T) { return fmt.Errorf("locator_table entry after restart: generation = %d, want 1", val.Generation) } - // Re-attach must replace the existing filter, not stack a second - // one alongside it. + // Re-attach must update the existing tcx link or replace the + // existing filter, not stack a second attachment alongside it. link, err := netlink.LinkByName(ifaceName) if err != nil { return fmt.Errorf("find link: %w", err) @@ -162,11 +162,15 @@ func TestLoadAttach_SurvivesRestartWithMapsIntact(t *testing.T) { if err != nil { return fmt.Errorf("list filters: %w", err) } - if len(filters) != 1 { - return fmt.Errorf("filter count after re-attach = %d, want 1 (idempotent replace, not a duplicate)", - len(filters)) + tcx, err := tcxIngressIDs(ifaceName) + if err != nil && !errors.Is(err, ebpf.ErrNotSupported) { + return fmt.Errorf("query tcx ingress chain: %w", err) } - return nil + if n := len(filters) + len(tcx); n != 1 { + return fmt.Errorf("attachments after re-attach = %d (%d filters, %d tcx), want 1 "+ + "(idempotent replace, not a duplicate)", n, len(filters), len(tcx)) + } + return Detach([]string{ifaceName}) }) if err != nil { t.Fatalf("post-restart verification: %v", err) diff --git a/internal/plumbing/ebpf/attach/doc.go b/internal/plumbing/ebpf/attach/doc.go index 00776d242..ecb603730 100644 --- a/internal/plumbing/ebpf/attach/doc.go +++ b/internal/plumbing/ebpf/attach/doc.go @@ -22,17 +22,18 @@ // pinned there instead of recreating them empty. // 3. Resolves the interface set, from an explicit override or by // auto-detection, and attaches usid_ingress to each one's ingress hook -// through a clsact qdisc and a direct-action filter. Classic TC-BPF rather -// than the newer tcx link mechanism, which keeps the attach path working -// across the kernel range the preflight check targets. Re-attaching -// replaces an existing galactic filter rather than stacking a duplicate, -// which together with the pins makes Start idempotent across a restart. +// through a pinned tcx link at the head of the tcx chain. A kernel without +// tcx gets a clsact qdisc and a direct-action filter instead. tcx.go says +// why tcx: a cluster CNI on the same uplink deletes classic filters it +// does not own. Re-attaching updates the existing link or replaces the +// existing filter rather than stacking a duplicate, which together with +// the pins makes Start idempotent across a restart. // -// Once attached, the filter holds its own kernel reference to the program, -// independent of the process that loaded it. The returned objects can therefore -// stay open for the life of the process and be closed on shutdown without -// disrupting forwarding: closing releases this process's descriptors, and does -// not detach the filter or unpin the maps. +// Once attached, the pinned link or the filter holds its own kernel reference +// to the program, independent of the process that loaded it. The returned +// objects can therefore stay open for the life of the process and be closed on +// shutdown without disrupting forwarding: closing releases this process's +// descriptors, and does not detach the program or unpin the maps. // // This package populates none of the maps with real data and owns no // health-check surface beyond Health itself. It builds the lifecycle the diff --git a/internal/plumbing/ebpf/attach/egress_reattach_test.go b/internal/plumbing/ebpf/attach/egress_reattach_test.go index 09d8547e0..d6f4161cc 100644 --- a/internal/plumbing/ebpf/attach/egress_reattach_test.go +++ b/internal/plumbing/ebpf/attach/egress_reattach_test.go @@ -157,8 +157,8 @@ func TestReattachEgress_MovesAttachmentsToTheNewProgram(t *testing.T) { //nolint if tokenAfter != tokenBefore { t.Errorf("idempotent CNI ADD rotated token from %d to %d", tokenBefore, tokenAfter) } - if got, want := filterProgID(t, uplinkLink, filterName), progID(t, previous.UsidIngress); got != want { - t.Errorf("uplink0's usid_ingress filter runs program %d, want it untouched at %d", got, want) + if got, want := ingressProgID(t, uplinkLink), progID(t, previous.UsidIngress); got != want { + t.Errorf("uplink0's usid_ingress runs program %d, want it untouched at %d", got, want) } replaced, err = ReattachEgress(current.UsidServiceEgress, current.UsidEgress, current.AttachmentIdentityTable) diff --git a/internal/plumbing/ebpf/attach/health.go b/internal/plumbing/ebpf/attach/health.go index cf96b3e6a..0f3134711 100644 --- a/internal/plumbing/ebpf/attach/health.go +++ b/internal/plumbing/ebpf/attach/health.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log/slog" + "slices" "github.com/cilium/ebpf" "github.com/cilium/ebpf/link" @@ -89,9 +90,10 @@ func checkMapsReachable(objs *prog.UsidObjects) error { return errors.Join(errs...) } -// IngressAttachedTo reports whether usid_ingress's filter is on the ingress of -// iface, or of every member of iface where it is a bond or a VLAN on one, -// since tc ingress classifies a bond's traffic on its members. A nil error +// IngressAttachedTo reports whether usid_ingress, through its pinned tcx link or +// its classic filter, is on the ingress of iface, or of every member of iface +// where it is a bond or a VLAN on one, since tc ingress classifies a bond's +// traffic on its members. A nil error // means a packet received on iface, or handed up from its XDP hook, reaches // usid_ingress. galactic-gateway checks its public interface this way before // it reports that it delivers to backends on its own node. @@ -121,25 +123,31 @@ func checkAttached(ifaces []string) error { return errors.Join(errs...) } -// checkAttachedOne confirms the filter is present among name's ingress filters, -// matched by name rather than by descriptor number, which is process-local and -// not comparable against a netlink query result. +// checkAttachedOne confirms usid_ingress is on name's ingress, through this +// package's pinned tcx link or its classic filter. The filter is matched by +// name rather than by descriptor number, which is process-local and not +// comparable against a netlink query result. func checkAttachedOne(name string) error { iface, err := linkByNameFn(name) if err != nil { return fmt.Errorf("find link: %w", err) } + onTCX, tcxErr := tcxIngressAttached(name, iface.Attrs().Index) + if onTCX { + return nil + } + filters, err := filterListFn(iface, netlink.HANDLE_MIN_INGRESS) if err != nil { - return fmt.Errorf("list filters: %w", err) + return errors.Join(fmt.Errorf("list filters: %w", err), tcxErr) } for _, f := range filters { if bpfFilter, ok := f.(*netlink.BpfFilter); ok && bpfFilter.Name == filterName { return nil } } - return errors.New("galactic uSID ingress filter not attached") + return errors.Join(errors.New("galactic uSID ingress program not attached (no tcx link or tc filter)"), tcxErr) } // Handle bundles loaded objects with a health check, so a caller can query @@ -193,7 +201,11 @@ func (h *Handle) Healthy() error { reportPreemption(h.Objs) healthErr := Health(h.Objs, ifaces) - if healthErr != nil { + if healthErr != nil || slices.ContainsFunc(ifaces, ingressLinkMisplaced) { + // A misplaced tcx link is still attached, so it is not unhealthy, but + // only a reconcile moves it back to the head. Nothing else asks for + // one when another program's link is created on an otherwise quiet + // node. h.Watcher.Reconcile() // nil-safe no-op if no Watcher is wired up } if h.Watcher != nil && !h.Watcher.Alive() { diff --git a/internal/plumbing/ebpf/attach/tcx.go b/internal/plumbing/ebpf/attach/tcx.go new file mode 100644 index 000000000..ec2cd2036 --- /dev/null +++ b/internal/plumbing/ebpf/attach/tcx.go @@ -0,0 +1,480 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "slices" + "strings" + "sync" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/link" + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" +) + +// usid_ingress reaches an uplink through a tcx link where the kernel has tcx, +// and through the classic clsact filter filterName where it does not. +// +// The reason is a cluster CNI sharing the uplink. Cilium, on a device it +// attaches to through tcx, deletes every classic tc filter on that device +// after each of its own program reloads, without checking whose they are, and +// it reloads whenever links or pods change on the node. A classic filter +// therefore vanished for about a second at a time until the watch loop put it +// back. Nothing outside this package deletes another program's tcx link that +// way. +// +// The link goes at the head of the tcx chain, ahead of Cilium's. Cilium +// v1.20.4 attaches its own tcx links with Anchor: link.Tail() and updates an +// existing link in place (pkg/datapath/loader/tcx.go, line 63, +// https://github.com/cilium/cilium/blob/v1.20.4/pkg/datapath/loader/tcx.go#L63), +// so it does not move ahead of this one. tcx runs the +// next program only after a TC_ACT_UNSPEC verdict, and Cilium's +// cil_from_netdev returns TC_ACT_OK for the packets it passes, so anything +// behind it, the classic filter included, never sees them. usid_ingress +// returns TC_ACT_UNSPEC for every packet it does not handle, so the programs +// behind it still see all other traffic. The SRv6 packets it decapsulates for +// galactic locators no longer reach Cilium in their outer form. +// +// Each link is pinned, so it outlives the process that created it the way a +// classic filter does, and so galactic-gateway can find it from its own +// process. The pin name carries the network namespace's inode as well as the +// interface name, because one bpffs serves every namespace on a host. + +// IngressLinkDir is the bpffs directory usid_ingress's tcx links are pinned in. +const IngressLinkDir = PinDir + "/links/usid_ingress" + +// ingressLinkDir is IngressLinkDir, a variable so tests pin somewhere of their +// own. +var ingressLinkDir = IngressLinkDir + +// errNoIngressLink reports that no tcx link is pinned for an interface. +var errNoIngressLink = errors.New("no usid_ingress tcx link pinned") + +// ingressLink is the part of a tcx link this package uses. It exists so tests +// can fake a link, since link.Info cannot be built outside its package. +type ingressLink interface { + Update(*ebpf.Program) error + Pin(string) error + Unpin() error + Detach() error + Close() error + // target returns the link's ID and the ifindex of the device it is + // attached to, which the kernel reports as 0 once that device is gone. + target() (link.ID, int, error) +} + +type tcxLink struct{ link.Link } + +func (l tcxLink) target() (link.ID, int, error) { + info, err := l.Info() + if err != nil { + return 0, 0, err + } + tcx := info.TCX() + if tcx == nil { + return 0, 0, fmt.Errorf("link %d is not a tcx link", info.ID) + } + return info.ID, int(tcx.Ifindex), nil +} + +// Override points, so tests need neither root nor a tcx kernel. +var ( + attachTCXIngressFn = func(program *ebpf.Program, ifindex int) (ingressLink, error) { + l, err := link.AttachTCX(link.TCXOptions{ + Program: program, + Attach: ebpf.AttachTCXIngress, + Interface: ifindex, + Anchor: link.Head(), + }) + if err != nil { + return nil, err + } + return tcxLink{l}, nil + } + + loadIngressLinkFn = func(path string) (ingressLink, error) { + if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) { + return nil, errNoIngressLink + } else if err != nil { + return nil, err + } + l, err := link.LoadPinnedLink(path, nil) + if err != nil { + return nil, err + } + return tcxLink{l}, nil + } + + // tcxIngressLinkIDsFn returns the link IDs on ifindex's tcx ingress + // chain, in the order the kernel runs them. A program attached without a + // link reads as ID 0. + tcxIngressLinkIDsFn = func(ifindex int) ([]link.ID, error) { + res, err := link.QueryPrograms(link.QueryOptions{Target: ifindex, Attach: ebpf.AttachTCXIngress}) + if err != nil { + return nil, err + } + ids := make([]link.ID, 0, len(res.Programs)) + for _, p := range res.Programs { + id, _ := p.LinkID() + ids = append(ids, id) + } + return ids, nil + } + + netnsInodeFn = func() (uint64, error) { + // thread-self, not self: a test switches namespaces on one locked + // thread, and self reports the thread group leader's. + var st unix.Stat_t + if err := unix.Stat("/proc/thread-self/ns/net", &st); err != nil { + return 0, err + } + return st.Ino, nil + } + + readIngressLinkDirFn = os.ReadDir + renameIngressPinFn = os.Rename + + replaceFilterFn = replaceFilter + attachClassicIngressFn = func(program *ebpf.Program, name string) error { + return attachOne(program, name, filterName, netlink.HANDLE_MIN_INGRESS) + } +) + +// ingressLinkPath returns where name's tcx link is pinned in the calling +// thread's network namespace. +func ingressLinkPath(name string) (string, error) { + ino, err := netnsInodeFn() + if err != nil { + return "", fmt.Errorf("read network namespace: %w", err) + } + return filepath.Join(ingressLinkDir, fmt.Sprintf("%d_%s", ino, name)), nil +} + +var tcxFallbackOnce sync.Once + +// attachIngressOne attaches usid_ingress to name's ingress through a pinned +// tcx link, or through the classic filter where the kernel has no tcx. +func attachIngressOne(program *ebpf.Program, name string) error { + err := attachIngressTCX(program, name) + if errors.Is(err, ebpf.ErrNotSupported) { + tcxFallbackOnce.Do(func() { + slog.Info("attach: kernel has no tcx, attaching usid_ingress as a classic tc filter") + }) + return attachClassicIngressFn(program, name) + } + attachHook(name, err) + return err +} + +func attachIngressTCX(program *ebpf.Program, name string) error { + iface, err := linkByNameFn(name) + if err != nil { + return fmt.Errorf("find link: %w", err) + } + ifindex := iface.Attrs().Index + path, err := ingressLinkPath(name) + if err != nil { + return err + } + + current, err := openIngressLink(path, ifindex) + if err != nil { + return err + } + if current == nil { + if err := pinNewIngressLink(program, ifindex, path); err != nil { + return err + } + } else { + defer current.Close() //nolint:errcheck // the pin holds the link + if err := current.Update(program); err != nil { + return fmt.Errorf("update tcx link program: %w", err) + } + // The link carries the new program from here on, so an ordering + // failure is logged rather than returned: Start treats any attach + // error as fatal, and the health check asks for another reconcile + // while the link stays out of place. + if err := ensureIngressLinkFirst(program, iface, path, current); err != nil { + slog.Warn("attach: usid_ingress tcx link is attached but could not be moved to the head of the chain", + "interface", name, "err", err) + // A failed move may have dropped the old link before the new + // one was pinned, leaving the classic filter as the only + // attachment, so it stays until a later attach succeeds. + return nil + } + } + + // The link now carries usid_ingress, so a classic filter left by an + // earlier version or by the fallback is redundant. It is harmless while + // it stays, since usid_ingress hands on every packet it does not handle, + // so a failure to remove it is logged and retried on the next attach. + if err := deleteFilters(iface, filterName, netlink.HANDLE_MIN_INGRESS); err != nil { + slog.Warn("attach: could not remove the classic usid_ingress filter after attaching through tcx", + "interface", name, "err", err) + } + return nil +} + +func ensureIngressLinkFirst(program *ebpf.Program, iface netlink.Link, path string, l ingressLink) error { + first, err := ingressLinkIsFirst(l, iface.Attrs().Index) + if err != nil || first { + return err + } + return moveIngressLinkToHead(program, iface, path, l) +} + +// openIngressLink loads the link pinned at path when it is still attached to +// ifindex. With no pin at path it adopts one this namespace pinned for the +// same device under another name. It returns nil when there is neither, and +// drops a pin whose device is gone or whose name now belongs to a different +// interface. +func openIngressLink(path string, ifindex int) (ingressLink, error) { + l, err := loadIngressLinkFn(path) + if errors.Is(err, errNoIngressLink) { + return adoptRenamedIngressLink(path, ifindex) + } + if err != nil { + return nil, fmt.Errorf("load pinned tcx link: %w", err) + } + _, idx, err := l.target() + if err == nil && idx == ifindex { + return l, nil + } + slog.Info("attach: dropping a usid_ingress tcx link pinned for an interface that is gone", + "pin", path, "ifindex", idx, "want", ifindex, "err", err) + if err := dropIngressLink(l); err != nil { + return nil, fmt.Errorf("drop stale tcx link: %w", err) + } + return nil, nil +} + +// adoptRenamedIngressLink looks, in the calling thread's namespace, for a pin +// whose link is attached to ifindex, and moves that pin to path. A renamed +// device keeps its link, and the kernel would refuse a second one carrying +// the same program, so without this the attach under the new name fails until +// the old name is detached. +func adoptRenamedIngressLink(path string, ifindex int) (ingressLink, error) { + entries, err := readIngressLinkDirFn(filepath.Dir(path)) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("list tcx link pins: %w", err) + } + prefix, _, _ := strings.Cut(filepath.Base(path), "_") + for _, e := range entries { + if !strings.HasPrefix(e.Name(), prefix+"_") { + continue + } + old := filepath.Join(filepath.Dir(path), e.Name()) + if old == path { + continue + } + l, err := loadIngressLinkFn(old) + if err != nil { + continue + } + if _, idx, err := l.target(); err != nil || idx != ifindex { + _ = l.Close() + continue + } + _ = l.Close() + if err := renameIngressPinFn(old, path); err != nil { + return nil, fmt.Errorf("move tcx link pin from %s: %w", old, err) + } + slog.Info("attach: adopted the usid_ingress tcx link of a renamed interface", "from", old, "to", path) + return loadIngressLinkFn(path) + } + return nil, nil +} + +// pinNewIngressLink attaches program at the head of ifindex's tcx ingress +// chain and pins the link at path. Errors wrap ebpf.ErrNotSupported on a +// kernel without tcx. +func pinNewIngressLink(program *ebpf.Program, ifindex int, path string) error { + l, err := attachTCXIngressFn(program, ifindex) + if err != nil { + return fmt.Errorf("attach tcx link: %w", err) + } + defer l.Close() //nolint:errcheck // the pin holds the link + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + _ = l.Detach() + return fmt.Errorf("create tcx link pin directory: %w", err) + } + if err := l.Pin(path); err != nil { + _ = l.Detach() + return fmt.Errorf("pin tcx link: %w", err) + } + return nil +} + +// ingressLinkIsFirst reports whether l is the first link on ifindex's tcx +// ingress chain. +func ingressLinkIsFirst(l ingressLink, ifindex int) (bool, error) { + id, _, err := l.target() + if err != nil { + return false, fmt.Errorf("read tcx link: %w", err) + } + ids, err := tcxIngressLinkIDsFn(ifindex) + if err != nil { + return false, fmt.Errorf("query tcx ingress chain: %w", err) + } + if !slices.Contains(ids, id) { + return false, fmt.Errorf("tcx link %d is missing from the ingress chain", id) + } + return ids[0] == id, nil +} + +// moveIngressLinkToHead re-creates old at the head of the chain. That happens +// when another program's link was put ahead of this one. Cilium v1.20.4 +// attaches at link.Tail() and updates existing links in place +// (https://github.com/cilium/cilium/blob/v1.20.4/pkg/datapath/loader/tcx.go#L63), +// so it never does this, but another agent anchoring at the head would. +// +// The kernel refuses one program twice on the same hook, so the new link +// cannot go in before the old one leaves. The classic filter stands in for +// the few syscalls between: it reaches the packets the remaining tcx programs +// hand on. Those a program returning TC_ACT_OK keeps, and those arriving after +// a Cilium reload deletes the filter, miss usid_ingress until the new link is +// in. Nothing closes that window short of loading a second copy of the +// program. +// +// Two agents that both insist on the head would keep moving each other. This +// one moves only when a health check or a netlink event asks for a reconcile, +// which bounds how often. +func moveIngressLinkToHead(program *ebpf.Program, iface netlink.Link, path string, old ingressLink) error { + name := iface.Attrs().Name + if err := replaceFilterFn(program, iface, filterName, netlink.HANDLE_MIN_INGRESS, + filterPriorityFn(), netlink.MakeHandle(0, 1)); err != nil { + return fmt.Errorf("attach classic filter before moving the tcx link: %w", err) + } + if err := dropIngressLink(old); err != nil { + return fmt.Errorf("detach tcx link to move it: %w", err) + } + if err := pinNewIngressLink(program, iface.Attrs().Index, path); err != nil { + return err + } + slog.Info("attach: moved usid_ingress to the head of the tcx ingress chain", "interface", name) + return nil +} + +// dropIngressLink detaches l and removes its pin. +func dropIngressLink(l ingressLink) error { + defer l.Close() //nolint:errcheck // nothing left to release + // Detach explicitly rather than relying on the last reference going away: + // another process, such as galactic-gateway checking attachment, may hold + // the link open for a moment. + detachErr := l.Detach() + if errors.Is(detachErr, unix.ENOLINK) || errors.Is(detachErr, unix.EINVAL) { + detachErr = nil // already detached, its device gone + } + return errors.Join(detachErr, l.Unpin()) +} + +// detachIngressLink removes name's tcx link, if one is pinned. +func detachIngressLink(name string) error { + path, err := ingressLinkPath(name) + if err != nil { + return err + } + l, err := loadIngressLinkFn(path) + if errors.Is(err, errNoIngressLink) { + return nil + } + if err != nil { + return fmt.Errorf("load pinned tcx link: %w", err) + } + if err := dropIngressLink(l); err != nil { + return fmt.Errorf("detach tcx link: %w", err) + } + return nil +} + +// tcxIngressAttached reports whether name's pinned tcx link is on the tcx +// ingress chain of the interface with ifindex. +func tcxIngressAttached(name string, ifindex int) (bool, error) { + path, err := ingressLinkPath(name) + if err != nil { + return false, err + } + l, err := loadIngressLinkFn(path) + if errors.Is(err, errNoIngressLink) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("load pinned tcx link: %w", err) + } + defer l.Close() //nolint:errcheck // the pin holds the link + id, idx, err := l.target() + if err != nil { + return false, fmt.Errorf("read tcx link: %w", err) + } + if idx != ifindex { + return false, nil + } + ids, err := tcxIngressLinkIDsFn(ifindex) + if err != nil { + return false, fmt.Errorf("query tcx ingress chain: %w", err) + } + return slices.Contains(ids, id), nil +} + +// ingressLinkMisplaced reports whether name carries this package's tcx link +// somewhere other than the head of its chain. Any failure to tell reads as +// false: the caller only uses a true answer, to ask for a reconcile. +func ingressLinkMisplaced(name string) bool { + iface, err := linkByNameFn(name) + if err != nil { + return false + } + path, err := ingressLinkPath(name) + if err != nil { + return false + } + l, err := loadIngressLinkFn(path) + if err != nil { + return false + } + defer l.Close() //nolint:errcheck // the pin holds the link + if _, idx, err := l.target(); err != nil || idx != iface.Attrs().Index { + return false + } + first, err := ingressLinkIsFirst(l, iface.Attrs().Index) + return err == nil && !first +} + +// sweepIngressLinks removes the pins of links whose device is gone, which the +// kernel has already detached. Without it, every deleted interface, and every +// test namespace, would leave its pin behind. +func sweepIngressLinks() { + entries, err := readIngressLinkDirFn(ingressLinkDir) + if err != nil { + if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, os.ErrPermission) { + slog.Warn("attach: could not list usid_ingress tcx link pins", "dir", ingressLinkDir, "err", err) + } + return + } + for _, e := range entries { + path := filepath.Join(ingressLinkDir, e.Name()) + l, err := loadIngressLinkFn(path) + if err != nil { + continue + } + if _, idx, err := l.target(); err == nil && idx == 0 { + if err := dropIngressLink(l); err != nil { + slog.Warn("attach: could not remove a usid_ingress tcx link pin for a deleted interface", + "pin", path, "err", err) + } + continue + } + _ = l.Close() + } +} diff --git a/internal/plumbing/ebpf/attach/tcx_root_test.go b/internal/plumbing/ebpf/attach/tcx_root_test.go new file mode 100644 index 000000000..06078d75a --- /dev/null +++ b/internal/plumbing/ebpf/attach/tcx_root_test.go @@ -0,0 +1,331 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/asm" + "github.com/cilium/ebpf/link" + "github.com/containernetworking/plugins/pkg/ns" + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" +) + +// tcxRootFixture is a dummy interface in its own network namespace with +// usid_ingress loaded and attached to it. +type tcxRootFixture struct { + netns ns.NetNS + iface string + objs *prog.UsidObjects +} + +func newTCXRootFixture(t *testing.T, iface string) *tcxRootFixture { + t.Helper() + requireRoot(t) + + pinDir := filepath.Join("/sys/fs/bpf", fmt.Sprintf("galactic-tcx-test-%s-%d", iface, os.Getpid())) + t.Cleanup(func() { _ = os.RemoveAll(pinDir) }) + + netns, err := ns.TempNetNS() + if err != nil { + t.Fatalf("create test netns: %v", err) + } + t.Cleanup(func() { _ = netns.Close() }) + + f := &tcxRootFixture{netns: netns, iface: iface} + f.do(t, func() error { + dummy := &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: iface}} + if err := netlink.LinkAdd(dummy); err != nil { + return fmt.Errorf("add dummy link: %w", err) + } + if err := netlink.LinkSetUp(dummy); err != nil { + return err + } + objs, err := Load(pinDir) + if err != nil { + return fmt.Errorf("load: %w", err) + } + f.objs = objs + return Attach(objs.UsidIngress, []string{iface}) + }) + t.Cleanup(func() { + _ = netns.Do(func(ns.NetNS) error { return Detach([]string{iface}) }) + if f.objs != nil { + _ = f.objs.Close() + } + }) + + f.do(t, func() error { + if _, err := tcxIngressIDs(iface); errors.Is(err, ebpf.ErrNotSupported) { + return errSkipNoTCX + } + return nil + }) + return f +} + +var errSkipNoTCX = errors.New("kernel has no tcx") + +func (f *tcxRootFixture) do(t *testing.T, fn func() error) { + t.Helper() + if err := f.netns.Do(func(ns.NetNS) error { return fn() }); err != nil { + if errors.Is(err, errSkipNoTCX) { + t.Skip("kernel has no tcx; the classic filter path is covered by the other root tests") + } + t.Fatal(err) + } +} + +// tcxIngressIDs returns the program IDs on iface's tcx ingress chain in run +// order. +func tcxIngressIDs(iface string) ([]ebpf.ProgramID, error) { + l, err := netlink.LinkByName(iface) + if err != nil { + return nil, err + } + res, err := link.QueryPrograms(link.QueryOptions{Target: l.Attrs().Index, Attach: ebpf.AttachTCXIngress}) + if err != nil { + return nil, err + } + ids := make([]ebpf.ProgramID, 0, len(res.Programs)) + for _, p := range res.Programs { + ids = append(ids, p.ID) + } + return ids, nil +} + +func programID(t *testing.T, p *ebpf.Program) ebpf.ProgramID { + t.Helper() + info, err := p.Info() + if err != nil { + t.Fatal(err) + } + id, ok := info.ID() + if !ok { + t.Fatal("kernel reports no program ID") + } + return id +} + +// ingressAttachmentCount counts the programs on iface's ingress: classic +// filters plus tcx links. Tests that predate tcx counted filters alone. +func ingressAttachmentCount(iface string) (int, error) { + l, err := netlink.LinkByName(iface) + if err != nil { + return 0, err + } + filters, err := netlink.FilterList(l, netlink.HANDLE_MIN_INGRESS) + if err != nil { + return 0, err + } + ids, err := tcxIngressIDs(iface) + if err != nil && !errors.Is(err, ebpf.ErrNotSupported) { + return 0, err + } + return len(filters) + len(ids), nil +} + +// ingressProgID returns the ID of the program usid_ingress runs as on iface, +// from its tcx link or its classic filter, or 0 if it has neither. +func ingressProgID(t *testing.T, iface string) uint32 { + t.Helper() + path, err := ingressLinkPath(iface) + if err != nil { + t.Fatal(err) + } + if l, err := link.LoadPinnedLink(path, nil); err == nil { + defer l.Close() //nolint:errcheck // the pin holds the link + info, err := l.Info() + if err != nil { + t.Fatalf("tcx link info: %v", err) + } + return uint32(info.Program) + } + return filterProgID(t, iface, filterName) +} + +// clearIngressAttachment removes usid_ingress from iface the way something +// outside this package would. It deletes the classic filter, and detaches +// the tcx link through its pin but leaves the pin, which then names a +// detached link the next attach has to notice and replace. +func clearIngressAttachment(iface string) error { + if err := deleteEveryIngressFilter(iface); err != nil { + return err + } + path, err := ingressLinkPath(iface) + if err != nil { + return err + } + l, err := link.LoadPinnedLink(path, nil) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + defer l.Close() //nolint:errcheck // the pin stays on purpose + return l.Detach() +} + +// deleteEveryIngressFilter does what Cilium's removeTCFilters does after each +// tcx reload: it lists every classic ingress filter on iface and deletes each, +// without checking whose it is. +func deleteEveryIngressFilter(iface string) error { + l, err := netlink.LinkByName(iface) + if err != nil { + return err + } + filters, err := netlink.FilterList(l, netlink.HANDLE_MIN_INGRESS) + if err != nil { + return err + } + for _, f := range filters { + if err := netlink.FilterDel(f); err != nil { + return err + } + } + return nil +} + +// TestAttach_SurvivesForeignClassicFilterDeletion is the regression test for +// Cilium deleting every classic tc filter on an uplink it reloads on. Before +// usid_ingress moved to tcx, this left it detached until the next reconcile. +func TestAttach_SurvivesForeignClassicFilterDeletion(t *testing.T) { + f := newTCXRootFixture(t, "usidtcx0") + ours := programID(t, f.objs.UsidIngress) + + f.do(t, func() error { + if err := deleteEveryIngressFilter(f.iface); err != nil { + return fmt.Errorf("delete every ingress filter: %w", err) + } + if err := IngressAttachedTo(f.iface); err != nil { + return fmt.Errorf("IngressAttachedTo after a foreign filter purge = %w, want nil", err) + } + ids, err := tcxIngressIDs(f.iface) + if err != nil { + return err + } + if !slices.Equal(ids, []ebpf.ProgramID{ours}) { + return fmt.Errorf("tcx ingress chain = %v, want [%d]", ids, ours) + } + return nil + }) +} + +// TestAttach_RestartUpdatesPinnedLink covers a galactic-cni restart: a second +// Load and Attach in a new process finds the pinned link and updates it, so +// the chain still holds exactly one usid_ingress and no classic filter. +func TestAttach_RestartUpdatesPinnedLink(t *testing.T) { + f := newTCXRootFixture(t, "usidtcx1") + f.do(t, func() error { + if err := Attach(f.objs.UsidIngress, []string{f.iface}); err != nil { + return fmt.Errorf("re-attach: %w", err) + } + ids, err := tcxIngressIDs(f.iface) + if err != nil { + return err + } + if len(ids) != 1 { + return fmt.Errorf("tcx ingress chain after re-attach = %v, want one program", ids) + } + l, err := netlink.LinkByName(f.iface) + if err != nil { + return err + } + filters, err := netlink.FilterList(l, netlink.HANDLE_MIN_INGRESS) + if err != nil { + return err + } + if len(filters) != 0 { + return fmt.Errorf("%d classic ingress filters after re-attach, want 0", len(filters)) + } + return nil + }) +} + +// TestAttach_MovesAheadOfForeignHeadTCXLink covers another program's tcx link +// put at the head after ours. The next attach puts usid_ingress back at the +// head and leaves the other program attached. +func TestAttach_MovesAheadOfForeignHeadTCXLink(t *testing.T) { + f := newTCXRootFixture(t, "usidtcx2") + ours := programID(t, f.objs.UsidIngress) + + foreign, err := ebpf.NewProgram(&ebpf.ProgramSpec{ + Type: ebpf.SchedCLS, + License: "Apache-2.0", + Instructions: asm.Instructions{asm.Mov.Imm(asm.R0, -1), asm.Return()}, + }) + if err != nil { + t.Fatalf("load foreign program: %v", err) + } + t.Cleanup(func() { _ = foreign.Close() }) + theirs := programID(t, foreign) + + f.do(t, func() error { + l, err := netlink.LinkByName(f.iface) + if err != nil { + return err + } + fl, err := link.AttachTCX(link.TCXOptions{ + Program: foreign, Attach: ebpf.AttachTCXIngress, Interface: l.Attrs().Index, Anchor: link.Head(), + }) + if err != nil { + return fmt.Errorf("attach foreign tcx link: %w", err) + } + t.Cleanup(func() { _ = fl.Close() }) + + if !ingressLinkMisplaced(f.iface) { + return errors.New("ingressLinkMisplaced() = false with a foreign link ahead of ours") + } + if err := Attach(f.objs.UsidIngress, []string{f.iface}); err != nil { + return fmt.Errorf("re-attach: %w", err) + } + ids, err := tcxIngressIDs(f.iface) + if err != nil { + return err + } + if want := []ebpf.ProgramID{ours, theirs}; !slices.Equal(ids, want) { + return fmt.Errorf("tcx ingress chain = %v, want %v", ids, want) + } + return IngressAttachedTo(f.iface) + }) +} + +// TestDetach_RemovesTCXLink covers Detach on a tcx attachment: the link +// leaves the chain and its pin goes with it. +func TestDetach_RemovesTCXLink(t *testing.T) { + f := newTCXRootFixture(t, "usidtcx3") + f.do(t, func() error { + path, err := ingressLinkPath(f.iface) + if err != nil { + return err + } + if err := Detach([]string{f.iface}); err != nil { + return fmt.Errorf("detach: %w", err) + } + ids, err := tcxIngressIDs(f.iface) + if err != nil { + return err + } + if len(ids) != 0 { + return fmt.Errorf("tcx ingress chain after detach = %v, want empty", ids) + } + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("pin %s after detach: stat err = %w, want not exist", path, err) + } + if IngressAttachedTo(f.iface) == nil { + return errors.New("IngressAttachedTo after detach = nil, want an error") + } + return nil + }) +} diff --git a/internal/plumbing/ebpf/attach/tcx_test.go b/internal/plumbing/ebpf/attach/tcx_test.go new file mode 100644 index 000000000..8eb2eabd8 --- /dev/null +++ b/internal/plumbing/ebpf/attach/tcx_test.go @@ -0,0 +1,479 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/link" + "github.com/vishvananda/netlink" +) + +// TestMain points tcx link pins at a directory of this run's own, so no test +// touches the pins a node's galactic-cni keeps under IngressLinkDir. Root runs +// need a bpffs directory; others get a plain one, where nothing is ever +// pinned. +func TestMain(m *testing.M) { + dir := filepath.Join(os.TempDir(), fmt.Sprintf("galactic-attach-test-links-%d", os.Getpid())) + if os.Geteuid() == 0 { + dir = filepath.Join("/sys/fs/bpf", fmt.Sprintf("galactic-attach-test-links-%d", os.Getpid())) + } + ingressLinkDir = dir + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} + +// fakeChain holds the tcx ingress chains and the bpffs pins, as the fakes +// below see them. +type fakeChain struct { + t *testing.T + nextID link.ID + chain map[int][]link.ID // ifindex -> link IDs in run order + pins map[string]*fakeTCXLink + attached []int // ifindexes attachTCXIngressFn attached to +} + +type fakeTCXLink struct { + c *fakeChain + id link.ID + ifindex int + program *ebpf.Program + path string +} + +func (l *fakeTCXLink) Update(p *ebpf.Program) error { l.program = p; return nil } + +func (l *fakeTCXLink) Pin(path string) error { + l.c.pins[path] = l + l.path = path + return nil +} + +func (l *fakeTCXLink) Unpin() error { + delete(l.c.pins, l.path) + l.path = "" + return nil +} + +func (l *fakeTCXLink) Detach() error { + l.c.chain[l.ifindex] = slices.DeleteFunc(l.c.chain[l.ifindex], func(id link.ID) bool { return id == l.id }) + return nil +} + +func (l *fakeTCXLink) Close() error { return nil } + +func (l *fakeTCXLink) target() (link.ID, int, error) { return l.id, l.ifindex, nil } + +// newFakeChain installs the tcx fakes for one test. +func newFakeChain(t *testing.T) *fakeChain { + c := &fakeChain{t: t, nextID: 100, chain: map[int][]link.ID{}, pins: map[string]*fakeTCXLink{}} + + prevAttach, prevLoad, prevIDs, prevNetns := attachTCXIngressFn, loadIngressLinkFn, tcxIngressLinkIDsFn, netnsInodeFn + prevReadDir, prevDir, prevRename := readIngressLinkDirFn, ingressLinkDir, renameIngressPinFn + t.Cleanup(func() { + attachTCXIngressFn, loadIngressLinkFn, tcxIngressLinkIDsFn, netnsInodeFn = prevAttach, prevLoad, prevIDs, prevNetns + readIngressLinkDirFn, ingressLinkDir, renameIngressPinFn = prevReadDir, prevDir, prevRename + }) + renameIngressPinFn = func(from, to string) error { + l, ok := c.pins[from] + if !ok { + return os.ErrNotExist + } + delete(c.pins, from) + c.pins[to] = l + l.path = to + return nil + } + + ingressLinkDir = t.TempDir() + netnsInodeFn = func() (uint64, error) { return 4026531840, nil } + attachTCXIngressFn = func(p *ebpf.Program, ifindex int) (ingressLink, error) { + c.nextID++ + l := &fakeTCXLink{c: c, id: c.nextID, ifindex: ifindex, program: p} + c.chain[ifindex] = append([]link.ID{l.id}, c.chain[ifindex]...) // link.Head() + c.attached = append(c.attached, ifindex) + return l, nil + } + loadIngressLinkFn = func(path string) (ingressLink, error) { + if l, ok := c.pins[path]; ok { + return l, nil + } + return nil, errNoIngressLink + } + tcxIngressLinkIDsFn = func(ifindex int) ([]link.ID, error) { return slices.Clone(c.chain[ifindex]), nil } + readIngressLinkDirFn = func(string) ([]fs.DirEntry, error) { + out := make([]fs.DirEntry, 0, len(c.pins)) + for path := range c.pins { + out = append(out, fakeDirEntry(filepath.Base(path))) + } + return out, nil + } + return c +} + +// addForeign puts another program's link at the tail of ifindex's chain, as +// Cilium attaches its own. +func (c *fakeChain) addForeign(ifindex int) link.ID { + c.nextID++ + c.chain[ifindex] = append(c.chain[ifindex], c.nextID) + return c.nextID +} + +// addForeignAtHead puts another program's link at the head of ifindex's +// chain, ahead of ours. +func (c *fakeChain) addForeignAtHead(ifindex int) link.ID { + c.nextID++ + c.chain[ifindex] = append([]link.ID{c.nextID}, c.chain[ifindex]...) + return c.nextID +} + +// pinned returns the link pinned for the test interface, failing the test if +// there is none. +func (c *fakeChain) pinned() *fakeTCXLink { + c.t.Helper() + path, err := ingressLinkPath(testIfaceEth0) + if err != nil { + c.t.Fatal(err) + } + l, ok := c.pins[path] + if !ok { + c.t.Fatalf("no tcx link pinned for %q", testIfaceEth0) + } + return l +} + +type fakeDirEntry string + +func (e fakeDirEntry) Name() string { return string(e) } +func (e fakeDirEntry) IsDir() bool { return false } +func (e fakeDirEntry) Type() fs.FileMode { return 0 } +func (e fakeDirEntry) Info() (fs.FileInfo, error) { return nil, errors.New("not implemented") } + +// fakeFilters fakes one interface's classic ingress filters and records which +// were attached. +type fakeFilters struct { + filters []netlink.Filter + attached []string +} + +func installFakeFilters(t *testing.T, ff *fakeFilters, iface netlink.Link) { + prevByName, prevList, prevDelete := linkByNameFn, filterListFn, filterDeleteFn + prevReplace, prevClassic := replaceFilterFn, attachClassicIngressFn + t.Cleanup(func() { + linkByNameFn, filterListFn, filterDeleteFn = prevByName, prevList, prevDelete + replaceFilterFn, attachClassicIngressFn = prevReplace, prevClassic + }) + add := func(name string) { + ff.attached = append(ff.attached, name) + ff.filters = append(ff.filters, &netlink.BpfFilter{Name: name}) + } + linkByNameFn = func(name string) (netlink.Link, error) { + if name == iface.Attrs().Name { + return iface, nil + } + return nil, netlink.LinkNotFoundError{} + } + filterListFn = func(netlink.Link, uint32) ([]netlink.Filter, error) { return slices.Clone(ff.filters), nil } + filterDeleteFn = func(f netlink.Filter) error { + ff.filters = slices.DeleteFunc(ff.filters, func(g netlink.Filter) bool { return g == f }) + return nil + } + replaceFilterFn = func(_ *ebpf.Program, _ netlink.Link, name string, _ uint32, _ uint16, _ uint32) error { + add(name) + return nil + } + attachClassicIngressFn = func(_ *ebpf.Program, _ string) error { + add(filterName) + return nil + } +} + +func (ff *fakeFilters) hasClassic() bool { + return slices.ContainsFunc(ff.filters, func(f netlink.Filter) bool { + b, ok := f.(*netlink.BpfFilter) + return ok && b.Name == filterName + }) +} + +const tcxTestIfindex = 7 + +func tcxTestIface() netlink.Link { + return &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: testIfaceEth0, Index: tcxTestIfindex}} +} + +// TestAttachIngressTCX_UpgradesClassicFilter covers the first attach after an +// upgrade: the tcx link goes in at the head, ahead of a Cilium link already +// there, and the classic filter left by the earlier version comes out. +func TestAttachIngressTCX_UpgradesClassicFilter(t *testing.T) { + c := newFakeChain(t) + ff := &fakeFilters{filters: []netlink.Filter{&netlink.BpfFilter{Name: filterName}}} + installFakeFilters(t, ff, tcxTestIface()) + foreign := c.addForeign(tcxTestIfindex) + + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("attachIngressTCX() = %v", err) + } + + ours := c.pinned() + if want := []link.ID{ours.id, foreign}; !slices.Equal(c.chain[tcxTestIfindex], want) { + t.Errorf("chain = %v, want %v (ours at the head)", c.chain[tcxTestIfindex], want) + } + if ff.hasClassic() { + t.Error("classic filter still attached after the tcx link took over") + } +} + +// TestAttachIngressTCX_UpdatesPinnedLinkInPlace covers a restart: the pinned +// link already at the head gets the new program, and nothing is re-attached, +// even with a Cilium link added behind it since. +func TestAttachIngressTCX_UpdatesPinnedLinkInPlace(t *testing.T) { + c := newFakeChain(t) + installFakeFilters(t, &fakeFilters{}, tcxTestIface()) + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("first attach: %v", err) + } + first := c.pinned() + c.addForeign(tcxTestIfindex) + + next := &ebpf.Program{} + if err := attachIngressTCX(next, testIfaceEth0); err != nil { + t.Fatalf("second attach: %v", err) + } + + if got := c.pinned(); got != first || got.program != next { + t.Error("second attach did not update the pinned link in place") + } + if len(c.attached) != 1 { + t.Errorf("attachTCXIngressFn called %d times, want 1", len(c.attached)) + } +} + +// TestAttachIngressTCX_MovesLinkAheadOfForeignHeadLink covers another agent +// putting its tcx link at the head after galactic-cni attached: the next +// attach moves ours back to the head, holding the classic filter in place +// while it does, and removes the filter once the move is done. +func TestAttachIngressTCX_MovesLinkAheadOfForeignHeadLink(t *testing.T) { + c := newFakeChain(t) + ff := &fakeFilters{} + installFakeFilters(t, ff, tcxTestIface()) + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("first attach: %v", err) + } + old := c.pinned() + foreign := c.addForeignAtHead(tcxTestIfindex) + + if !ingressLinkMisplaced(testIfaceEth0) { + t.Fatal("ingressLinkMisplaced() = false with a foreign link ahead of ours") + } + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("second attach: %v", err) + } + + ours := c.pinned() + if ours == old { + t.Fatal("link was not re-created") + } + if want := []link.ID{ours.id, foreign}; !slices.Equal(c.chain[tcxTestIfindex], want) { + t.Errorf("chain = %v, want %v", c.chain[tcxTestIfindex], want) + } + if !slices.Equal(ff.attached, []string{filterName}) { + t.Errorf("classic filters attached during the move = %v, want [%s]", ff.attached, filterName) + } + if ff.hasClassic() { + t.Error("classic filter still attached after the move") + } + if ingressLinkMisplaced(testIfaceEth0) { + t.Error("ingressLinkMisplaced() = true after the move") + } +} + +// TestAttachIngressTCX_KeepsClassicFilterWhenMoveFails covers a move that +// drops the old link and then fails to attach the new one: the classic filter +// is the only attachment left, so the attach must not remove it. +func TestAttachIngressTCX_KeepsClassicFilterWhenMoveFails(t *testing.T) { + c := newFakeChain(t) + ff := &fakeFilters{} + installFakeFilters(t, ff, tcxTestIface()) + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("first attach: %v", err) + } + c.addForeignAtHead(tcxTestIfindex) + + attachTCXIngressFn = func(*ebpf.Program, int) (ingressLink, error) { + return nil, errors.New("attach refused") + } + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("second attach = %v, want nil", err) + } + if !ff.hasClassic() { + t.Error("classic filter removed although the move failed and no tcx link carries the program") + } +} + +// TestAttachIngressTCX_ReplacesPinForRecreatedInterface covers an interface +// deleted and created again under the same name: the old pin points at a +// device that is gone, so it is dropped and a fresh link attached. +func TestAttachIngressTCX_ReplacesPinForRecreatedInterface(t *testing.T) { + c := newFakeChain(t) + installFakeFilters(t, &fakeFilters{}, tcxTestIface()) + path, err := ingressLinkPath(testIfaceEth0) + if err != nil { + t.Fatal(err) + } + stale := &fakeTCXLink{c: c, id: 5, ifindex: 0} + if err := stale.Pin(path); err != nil { + t.Fatal(err) + } + + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("attachIngressTCX() = %v", err) + } + if got := c.pinned(); got == stale || got.ifindex != tcxTestIfindex { + t.Errorf("pinned link = %+v, want a new link on ifindex %d", got, tcxTestIfindex) + } +} + +// TestAttachIngressTCX_AdoptsRenamedInterfacePin covers a device renamed +// while attached: its link stays on the device under the old name's pin, and +// the kernel would refuse a second link with the same program, so the attach +// under the new name takes over the old pin instead of attaching again. +func TestAttachIngressTCX_AdoptsRenamedInterfacePin(t *testing.T) { + c := newFakeChain(t) + installFakeFilters(t, &fakeFilters{}, tcxTestIface()) + ino, _ := netnsInodeFn() + renamed := &fakeTCXLink{c: c, id: 9, ifindex: tcxTestIfindex} + c.chain[tcxTestIfindex] = []link.ID{renamed.id} + if err := renamed.Pin(filepath.Join(ingressLinkDir, fmt.Sprintf("%d_oldname", ino))); err != nil { + t.Fatal(err) + } + + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("attachIngressTCX() = %v", err) + } + if got := c.pinned(); got != renamed { + t.Error("attach under the new name did not adopt the renamed device's link") + } + if len(c.attached) != 0 { + t.Errorf("attachTCXIngressFn called %d times, want 0", len(c.attached)) + } + if len(c.pins) != 1 { + t.Errorf("%d pins after adopting, want 1", len(c.pins)) + } +} + +// TestAttachIngressTCX_OrderingFailureIsNotFatal covers a chain query failing +// after the pinned link already carries the new program. Start treats an +// attach error as fatal, so this must not become one. +func TestAttachIngressTCX_OrderingFailureIsNotFatal(t *testing.T) { + newFakeChain(t) + installFakeFilters(t, &fakeFilters{}, tcxTestIface()) + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("first attach: %v", err) + } + tcxIngressLinkIDsFn = func(int) ([]link.ID, error) { return nil, errors.New("simulated ENOSPC") } + + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Errorf("attachIngressTCX() with a failing chain query = %v, want nil", err) + } +} + +// TestDetachIngressLink covers Detach through the tcx path: the link leaves +// the chain and its pin goes, and a pin this process cannot read is reported +// rather than taken as absent, since the link would stay attached. +func TestDetachIngressLink(t *testing.T) { + c := newFakeChain(t) + installFakeFilters(t, &fakeFilters{}, tcxTestIface()) + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("attach: %v", err) + } + + if err := detachIngressLink(testIfaceEth0); err != nil { + t.Fatalf("detachIngressLink() = %v", err) + } + if len(c.chain[tcxTestIfindex]) != 0 || len(c.pins) != 0 { + t.Errorf("after detach: chain %v, %d pins, want both empty", c.chain[tcxTestIfindex], len(c.pins)) + } + + loadIngressLinkFn = func(string) (ingressLink, error) { + return nil, fmt.Errorf("simulated: %w", os.ErrPermission) + } + if err := detachIngressLink(testIfaceEth0); err == nil { + t.Error("detachIngressLink() with an unreadable pin = nil, want an error") + } +} + +// TestAttachIngressOne_FallsBackWithoutTCX covers a kernel without tcx: the +// classic filter is attached as before, and nothing is pinned. +func TestAttachIngressOne_FallsBackWithoutTCX(t *testing.T) { + c := newFakeChain(t) + ff := &fakeFilters{} + installFakeFilters(t, ff, tcxTestIface()) + attachTCXIngressFn = func(*ebpf.Program, int) (ingressLink, error) { + return nil, fmt.Errorf("simulated old kernel: %w", ebpf.ErrNotSupported) + } + + if err := attachIngressOne(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("attachIngressOne() = %v", err) + } + if !slices.Equal(ff.attached, []string{filterName}) { + t.Errorf("classic filters attached = %v, want [%s]", ff.attached, filterName) + } + if len(c.pins) != 0 { + t.Errorf("%d tcx links pinned on a kernel without tcx, want 0", len(c.pins)) + } +} + +// TestCheckAttachedOne_TCX covers the health check against a tcx attachment: +// a link on the chain passes with no classic filter at all, which is the state +// Cilium leaves after deleting every filter, and a pinned link that has left +// the chain fails. +func TestCheckAttachedOne_TCX(t *testing.T) { + c := newFakeChain(t) + installFakeFilters(t, &fakeFilters{}, tcxTestIface()) + if err := attachIngressTCX(&ebpf.Program{}, testIfaceEth0); err != nil { + t.Fatalf("attach: %v", err) + } + + if err := checkAttachedOne(testIfaceEth0); err != nil { + t.Errorf("checkAttachedOne() with the tcx link on the chain = %v, want nil", err) + } + + c.chain[tcxTestIfindex] = nil + err := checkAttachedOne(testIfaceEth0) + if err == nil || !strings.Contains(err.Error(), "not attached") { + t.Errorf("checkAttachedOne() with the link off the chain = %v, want a not-attached error", err) + } +} + +// TestSweepIngressLinks_DropsOnlyDefunctPins covers the pin sweep: a link +// whose device is gone loses its pin, a live one keeps it. +func TestSweepIngressLinks_DropsOnlyDefunctPins(t *testing.T) { + c := newFakeChain(t) + live := &fakeTCXLink{c: c, id: 1, ifindex: tcxTestIfindex} + gone := &fakeTCXLink{c: c, id: 2, ifindex: 0} + for name, l := range map[string]*fakeTCXLink{"1_live": live, "1_gone": gone} { + if err := l.Pin(filepath.Join(ingressLinkDir, name)); err != nil { + t.Fatal(err) + } + } + + sweepIngressLinks() + + if _, ok := c.pins[filepath.Join(ingressLinkDir, "1_live")]; !ok { + t.Error("sweep removed a live link's pin") + } + if _, ok := c.pins[filepath.Join(ingressLinkDir, "1_gone")]; ok { + t.Error("sweep kept the pin of a link whose device is gone") + } +} diff --git a/internal/plumbing/ebpf/attach/watch.go b/internal/plumbing/ebpf/attach/watch.go index 1318c3d2b..168bed618 100644 --- a/internal/plumbing/ebpf/attach/watch.go +++ b/internal/plumbing/ebpf/attach/watch.go @@ -530,8 +530,9 @@ func reconcile(program *ebpf.Program, current, next map[string]struct{}) map[str result[name] = struct{}{} } + sweepIngressLinks() for name := range next { - if err := attachOne(program, name, filterName, netlink.HANDLE_MIN_INGRESS); err != nil { + if err := attachIngressOne(program, name); err != nil { slog.Warn("attach: failed to (re)attach resolved interface, will retry on next re-evaluation", "interface", name, "err", err) delete(result, name) diff --git a/internal/plumbing/ebpf/attach/watch_test.go b/internal/plumbing/ebpf/attach/watch_test.go index 337eebfe3..a78e3f621 100644 --- a/internal/plumbing/ebpf/attach/watch_test.go +++ b/internal/plumbing/ebpf/attach/watch_test.go @@ -420,30 +420,22 @@ func TestWatch_ReEvaluatesAndReattachesOnInterfaceSetChange(t *testing.T) { // Verify the re-attachment actually happened at the kernel level: B now // carries the filter, A no longer does. err = nsObj.Do(func(_ ns.NetNS) error { - linkB, err := netlink.LinkByName(ifaceB) + nB, err := ingressAttachmentCount(ifaceB) if err != nil { - return fmt.Errorf("find link %q: %w", ifaceB, err) + return fmt.Errorf("count attachments on %q: %w", ifaceB, err) } - filtersB, err := netlink.FilterList(linkB, netlink.HANDLE_MIN_INGRESS) - if err != nil { - return fmt.Errorf("list filters on %q: %w", ifaceB, err) - } - if len(filtersB) != 1 { - return fmt.Errorf("filter count on %q = %d, want 1 (re-attached after the interface-set change)", - ifaceB, len(filtersB)) + if nB != 1 { + return fmt.Errorf("attachment count on %q = %d, want 1 (re-attached after the interface-set change)", + ifaceB, nB) } - linkA, err := netlink.LinkByName(ifaceA) - if err != nil { - return fmt.Errorf("find link %q: %w", ifaceA, err) - } - filtersA, err := netlink.FilterList(linkA, netlink.HANDLE_MIN_INGRESS) + nA, err := ingressAttachmentCount(ifaceA) if err != nil { - return fmt.Errorf("list filters on %q: %w", ifaceA, err) + return fmt.Errorf("count attachments on %q: %w", ifaceA, err) } - if len(filtersA) != 0 { - return fmt.Errorf("filter count on %q = %d, want 0 (detached after dropping out of the resolved set)", - ifaceA, len(filtersA)) + if nA != 0 { + return fmt.Errorf("attachment count on %q = %d, want 0 (detached after dropping out of the resolved set)", + ifaceA, nA) } return nil }) @@ -511,22 +503,24 @@ func TestWatch_HealsExternallyClearedFilterWithoutSetChange(t *testing.T) { return fmt.Errorf("initial attach to %q: %w", ifaceA, err) } - // Simulate the external drift: clear the filter kernel-side without - // going through this package's own Detach, so Watch's internal - // bookkeeping still believes ifaceA is attached. - link, err := netlink.LinkByName(ifaceA) + // Simulate the external drift: clear the attachment kernel-side + // without going through this package's own Detach, so Watch's + // internal bookkeeping still believes ifaceA is attached. + n, err := ingressAttachmentCount(ifaceA) if err != nil { - return fmt.Errorf("find link %q: %w", ifaceA, err) + return fmt.Errorf("count attachments on %q: %w", ifaceA, err) } - filters, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS) - if err != nil { - return fmt.Errorf("list filters on %q: %w", ifaceA, err) + if n != 1 { + return fmt.Errorf("attachment count on %q = %d, want 1 before simulated drift", ifaceA, n) + } + if err := clearIngressAttachment(ifaceA); err != nil { + return fmt.Errorf("simulate external clear on %q: %w", ifaceA, err) } - if len(filters) != 1 { - return fmt.Errorf("filter count on %q = %d, want 1 before simulated drift", ifaceA, len(filters)) + if n, err = ingressAttachmentCount(ifaceA); err != nil { + return fmt.Errorf("count attachments on %q after simulated drift: %w", ifaceA, err) } - if err := netlink.FilterDel(filters[0]); err != nil { - return fmt.Errorf("simulate external filter clear on %q: %w", ifaceA, err) + if n != 0 { + return fmt.Errorf("attachment count on %q after simulated drift = %d, want 0", ifaceA, n) } trigger := make(chan struct{}, 1) @@ -564,18 +558,14 @@ func TestWatch_HealsExternallyClearedFilterWithoutSetChange(t *testing.T) { } err = nsObj.Do(func(_ ns.NetNS) error { - link, err := netlink.LinkByName(ifaceA) + n, err := ingressAttachmentCount(ifaceA) if err != nil { - return fmt.Errorf("find link %q: %w", ifaceA, err) + return fmt.Errorf("count attachments on %q: %w", ifaceA, err) } - filters, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS) - if err != nil { - return fmt.Errorf("list filters on %q: %w", ifaceA, err) - } - if len(filters) != 1 { + if n != 1 { return fmt.Errorf( - "filter count on %q = %d, want 1 (self-healed after external drift, with no interface-set change)", - ifaceA, len(filters)) + "attachment count on %q = %d, want 1 (self-healed after external drift, with no interface-set change)", + ifaceA, n) } return nil }) @@ -636,19 +626,21 @@ func TestWatch_HealsExternallyClearedFilterViaWatcherReconcile(t *testing.T) { } // Simulate the external drift, same as the netlink-event variant. - link, err := netlink.LinkByName(ifaceA) + n, err := ingressAttachmentCount(ifaceA) if err != nil { - return fmt.Errorf("find link %q: %w", ifaceA, err) + return fmt.Errorf("count attachments on %q: %w", ifaceA, err) } - filters, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS) - if err != nil { - return fmt.Errorf("list filters on %q: %w", ifaceA, err) + if n != 1 { + return fmt.Errorf("attachment count on %q = %d, want 1 before simulated drift", ifaceA, n) } - if len(filters) != 1 { - return fmt.Errorf("filter count on %q = %d, want 1 before simulated drift", ifaceA, len(filters)) + if err := clearIngressAttachment(ifaceA); err != nil { + return fmt.Errorf("simulate external clear on %q: %w", ifaceA, err) } - if err := netlink.FilterDel(filters[0]); err != nil { - return fmt.Errorf("simulate external filter clear on %q: %w", ifaceA, err) + if n, err = ingressAttachmentCount(ifaceA); err != nil { + return fmt.Errorf("count attachments on %q after simulated drift: %w", ifaceA, err) + } + if n != 0 { + return fmt.Errorf("attachment count on %q after simulated drift = %d, want 0", ifaceA, n) } resolveInterfacesFn = func() ([]string, error) { return []string{ifaceA}, nil } @@ -686,18 +678,14 @@ func TestWatch_HealsExternallyClearedFilterViaWatcherReconcile(t *testing.T) { } err = nsObj.Do(func(_ ns.NetNS) error { - link, err := netlink.LinkByName(ifaceA) - if err != nil { - return fmt.Errorf("find link %q: %w", ifaceA, err) - } - filters, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS) + n, err := ingressAttachmentCount(ifaceA) if err != nil { - return fmt.Errorf("list filters on %q: %w", ifaceA, err) + return fmt.Errorf("count attachments on %q: %w", ifaceA, err) } - if len(filters) != 1 { + if n != 1 { return fmt.Errorf( - "filter count on %q = %d, want 1 (self-healed via Watcher.Reconcile(), with no netlink event at all)", - ifaceA, len(filters)) + "attachment count on %q = %d, want 1 (self-healed via Watcher.Reconcile(), with no netlink event at all)", + ifaceA, n) } return nil })