From 79101d08350fbb020fda876311d72b904ce73a35 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Thu, 22 Oct 2026 12:50:57 -0400 Subject: [PATCH 1/3] fix: Keep installing traffic policy after a router restart galactic-router reads back every snapshot bound in tp_binding_table when it opens the traffic policy maps, so it can adopt their counter rows. Reading a map-of-maps value as an *ebpf.Map makes cilium/ebpf open the inner map by ID, and the kernel allows BPF_MAP_GET_FD_BY_ID only with CAP_SYS_ADMIN. The router runs with NET_ADMIN and BPF, so a router started while any binding existed failed every reconcile with "look up next key: operation not permitted": it installed no policy, wrote no status and exported no metrics on that node. A router started on an empty table worked, so the failure appeared only at the first restart. Maps opened from a pin directory now pin each snapshot they publish at tp_snapshots/-, swapped in by rename once bound, and Invalidate removes the pin, so the CNI plugins' DEL paths clean up too. BoundKeys and ReadSnapshot read the bound inner map's ID as a plain uint32, and ReadSnapshot reads from the pin only when the pinned map has that ID. Otherwise it opens the map by ID, which still works with CAP_SYS_ADMIN, and without it returns ErrSnapshotUnreadable. The reconciler adopts an unreadable snapshot, such as one bound by a release that did not pin, as empty. It stays bound, so traffic keeps its verdict, until the attachment's next reconcile republishes it with fresh counter rows or the sweep unbinds it. Until then its rules can count into rows another snapshot was given. internal/captest drops CAP_SYS_ADMIN on one locked OS thread, so the root test suite covers the router's capability set. The new tpmap tests read back, republish, unbind, and reject stale or missing pins without CAP_SYS_ADMIN. The reconciler's new restart step fails without the reconciler change ("the restarted reconciler did not open the maps") and passes with it. Fixes #1007 Co-Authored-By: Claude Opus 5.5 --- docs/traffic-policy/node.md | 12 ++ docs/traffic-policy/rollout.md | 7 + internal/captest/captest.go | 47 +++++ .../plumbing/ebpf/tpmap/snapshotpin_test.go | 187 ++++++++++++++++++ internal/plumbing/ebpf/tpmap/tpmap.go | 133 +++++++++++-- internal/trafficpolicy/node/reconciler.go | 22 ++- .../trafficpolicy/node/reconciler_test.go | 49 +++++ 7 files changed, 440 insertions(+), 17 deletions(-) create mode 100644 internal/captest/captest.go create mode 100644 internal/plumbing/ebpf/tpmap/snapshotpin_test.go diff --git a/docs/traffic-policy/node.md b/docs/traffic-policy/node.md index 662799286..8b13fa4db 100644 --- a/docs/traffic-policy/node.md +++ b/docs/traffic-policy/node.md @@ -57,6 +57,18 @@ compiled differently is republished, starting its rules from zero. A snapshot on an interface no attachment claims within one resync is unbound, and its rows are freed. +To read a snapshot back, galactic-router pins each one it publishes under +`tp_snapshots/` in the datapath's pin directory, beside the policy maps, and +the CNI plugins remove the pin when they unbind it. The kernel opens a map +by ID only for `CAP_SYS_ADMIN`, which galactic-router does not have (it runs +with `NET_ADMIN` and `BPF`), so a snapshot without a matching pin, such as +one bound by a release that did not pin, cannot be read. galactic-router +adopts it as empty and logs it: it stays bound, so traffic keeps its +current verdict, until the next reconcile republishes it with fresh counter +rows or the sweep unbinds it. Until then its rules can count into rows +another snapshot was given, so those counters can over-count for that +window; verdicts are unaffected. + A rebind that cannot be installed, such as one that runs out of counter rows, unbinds the direction rather than keeping the old policy's grants, and reports `Failed`. A failed update of the same policy keeps its last diff --git a/docs/traffic-policy/rollout.md b/docs/traffic-policy/rollout.md index 1567f307d..5b9aa5896 100644 --- a/docs/traffic-policy/rollout.md +++ b/docs/traffic-policy/rollout.md @@ -46,6 +46,13 @@ Check every node of the cell: which the cloud operator writes. An attachment without them is never bound on any node, and denies everything once enforced. +`galactic-router` needs `NET_ADMIN` and `BPF`, as `config/galactic-router/` +grants, and not `CAP_SYS_ADMIN`: it reads back the snapshots it bound before +a restart from their pins (see +[Traffic policy on the node](node.md#what-it-applies)). The first restart +after upgrading from a release that did not pin snapshots republishes every +snapshot bound on the node, so their rule counters start again from zero. + ## Steps 1. **Install the cell controller.** Apply `config/galactic-controller/` (its diff --git a/internal/captest/captest.go b/internal/captest/captest.go new file mode 100644 index 000000000..75654c9fe --- /dev/null +++ b/internal/captest/captest.go @@ -0,0 +1,47 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package captest runs test code with fewer capabilities than the root test +// process has, to check that code works under a container's narrower set. +// +// It is a regular importable package rather than a test file, since one +// package's test files cannot import another's. +package captest + +import ( + "runtime" + "testing" + + "golang.org/x/sys/unix" +) + +// WithoutSysAdmin runs fn on an OS thread whose effective capabilities lack +// CAP_SYS_ADMIN, as galactic-router's container does, and waits for it. +// Capabilities are per thread, so fn must make its system calls from its own +// goroutine; and since fn does not run on the test goroutine, it reports +// failures with t.Error rather than t.Fatal. The thread exits with fn, so the +// rest of the test keeps the full set. +func WithoutSysAdmin(t *testing.T, fn func()) { + t.Helper() + done := make(chan struct{}) + go func() { + defer close(done) + // Never unlocked: the runtime destroys a locked thread when its + // goroutine exits, so no other goroutine inherits the reduced set. + runtime.LockOSThread() + hdr := unix.CapUserHeader{Version: unix.LINUX_CAPABILITY_VERSION_3} + var data [2]unix.CapUserData + if err := unix.Capget(&hdr, &data[0]); err != nil { + t.Errorf("capget: %v", err) + return + } + data[unix.CAP_SYS_ADMIN/32].Effective &^= 1 << (unix.CAP_SYS_ADMIN % 32) + if err := unix.Capset(&hdr, &data[0]); err != nil { + t.Errorf("drop CAP_SYS_ADMIN: %v", err) + return + } + fn() + }() + <-done +} diff --git a/internal/plumbing/ebpf/tpmap/snapshotpin_test.go b/internal/plumbing/ebpf/tpmap/snapshotpin_test.go new file mode 100644 index 000000000..c04c3504f --- /dev/null +++ b/internal/plumbing/ebpf/tpmap/snapshotpin_test.go @@ -0,0 +1,187 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package tpmap + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "testing" + + "go.datum.net/galactic/internal/captest" + "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/trafficpolicy" +) + +// pinned pins f's traffic policy maps in a fresh bpffs directory and returns +// them opened from there, as galactic-router and the CNI plugins open them. +func (f *fixture) pinned(t *testing.T) (*Maps, string) { + t.Helper() + dir := filepath.Join("/sys/fs/bpf", fmt.Sprintf("galactic-tpmap-test-%d", os.Getpid())) + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + for name, mp := range map[string]interface{ Pin(string) error }{ + prog.UsidMapTpState: f.objs.TpState, + prog.UsidMapTpIfaceTable: f.objs.TpIfaceTable, + prog.UsidMapTpIfaceAddrTable: f.objs.TpIfaceAddrTable, + prog.UsidMapTpBindingTable: f.objs.TpBindingTable, + prog.UsidMapTpNatLocatorTable: f.objs.TpNatLocatorTable, + prog.UsidMapTpRuleCounters: f.objs.TpRuleCounters, + prog.UsidMapTpFallbackCounters: f.objs.TpFallbackCounters, + prog.UsidMapTpUnattributedCounters: f.objs.TpUnattributedCounters, + prog.UsidMapTpAccountingErrors: f.objs.TpAccountingErrors, + } { + if err := mp.Pin(filepath.Join(dir, name)); err != nil { + t.Fatal(err) + } + } + m, err := OpenPinned(dir) + if err != nil { + t.Fatal(err) + } + t.Cleanup(m.Close) + return m, dir +} + +func snapshotPins(t *testing.T, dir string) []string { + t.Helper() + entries, err := os.ReadDir(filepath.Join(dir, snapshotPinDir)) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + t.Fatal(err) + } + var names []string + for _, e := range entries { + names = append(names, e.Name()) + } + return names +} + +func publishRules(t *testing.T, m *Maps, rules string, base uint32) { + t.Helper() + snap := Snapshot{Token: token, CounterBase: base, Generation: 3} + entries, err := trafficpolicy.Compile(policy(t, rules)) + if err != nil { + t.Fatal(err) + } + snap.Entries = entries + if err := m.PublishSnapshot(ifindex, DirEgress, snap); err != nil { + t.Fatal(err) + } +} + +// TestReadSnapshotWithoutSysAdmin: a process without CAP_SYS_ADMIN, such as +// galactic-router after a restart, lists and reads back every snapshot bound +// through pinned maps. +func TestReadSnapshotWithoutSysAdmin(t *testing.T) { + f := newFixture(t, ModeAudit) + f.iface(t) + m, dir := f.pinned(t) + publishRules(t, m, `[{"name":"a","action":"Allow"},{"name":"b","action":"Deny"}]`, 5) + + captest.WithoutSysAdmin(t, func() { + restarted, err := OpenPinned(dir) + if err != nil { + t.Error(err) + return + } + defer restarted.Close() + keys, err := restarted.BoundKeys() + if err != nil || len(keys) != 1 || keys[0].Ifindex != ifindex || keys[0].Direction != DirEgress { + t.Errorf("BoundKeys = %v, %v; want ifindex %d egress", keys, err, ifindex) + } + snap, ok, err := restarted.ReadSnapshot(ifindex, DirEgress) + if err != nil || !ok { + t.Errorf("ReadSnapshot = %v, %v", ok, err) + return + } + if snap.Token != token || snap.CounterBase != 5 || snap.Generation != 3 || len(snap.Entries) != 2 { + t.Errorf("snapshot = %+v, want token %#x, base 5, generation 3, 2 entries", snap, token) + } + if _, ok, err := restarted.ReadSnapshot(ifindex, DirIngress); ok || err != nil { + t.Errorf("unbound direction: ReadSnapshot = %v, %v; want none", ok, err) + } + }) +} + +// TestRepublishReplacesPin: each key keeps exactly one pin, the bound one. +func TestRepublishReplacesPin(t *testing.T) { + f := newFixture(t, ModeAudit) + f.iface(t) + m, dir := f.pinned(t) + publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0) + publishRules(t, m, `[{"name":"a","action":"Allow"},{"name":"b","action":"Deny"}]`, 7) + if pins := snapshotPins(t, dir); len(pins) != 1 || pins[0] != fmt.Sprintf("%d-%d", ifindex, DirEgress) { + t.Fatalf("pins = %v, want one for ifindex %d egress", pins, ifindex) + } + captest.WithoutSysAdmin(t, func() { + snap, ok, err := m.ReadSnapshot(ifindex, DirEgress) + if err != nil || !ok || snap.CounterBase != 7 { + t.Errorf("ReadSnapshot = %+v, %v, %v; want the second snapshot", snap, ok, err) + } + }) +} + +// TestUnbindingRemovesPin: Invalidate and RemoveInterface, which the CNI +// plugins call on DEL, leave no pin holding an unbound snapshot. +func TestUnbindingRemovesPin(t *testing.T) { + f := newFixture(t, ModeAudit) + f.iface(t) + m, dir := f.pinned(t) + publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0) + if err := m.Invalidate(ifindex, DirEgress); err != nil { + t.Fatal(err) + } + if pins := snapshotPins(t, dir); len(pins) != 0 { + t.Errorf("after Invalidate: pins = %v, want none", pins) + } + publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0) + if err := RemovePinnedInterface(dir, ifindex); err != nil { + t.Fatal(err) + } + if pins := snapshotPins(t, dir); len(pins) != 0 { + t.Errorf("after RemovePinnedInterface: pins = %v, want none", pins) + } +} + +// TestUnmatchedSnapshotIsUnreadable: a snapshot bound without a pin, or whose +// pin holds another map, is reported unreadable without CAP_SYS_ADMIN rather +// than read from the wrong map, and is still read by ID with it. +func TestUnmatchedSnapshotIsUnreadable(t *testing.T) { + f := newFixture(t, ModeAudit) + f.iface(t) + m, dir := f.pinned(t) + publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0) + // f.maps has no pin directory, so this binding leaves the pin stale. + publishRules(t, f.maps, `[{"name":"a","action":"Allow"},{"name":"b","action":"Deny"}]`, 9) + if pins := snapshotPins(t, dir); len(pins) != 1 { + t.Fatalf("pins = %v, want the stale one", pins) + } + unreadable := func() { + captest.WithoutSysAdmin(t, func() { + if _, err := m.BoundKeys(); err != nil { + t.Errorf("BoundKeys: %v", err) + } + _, _, err := m.ReadSnapshot(ifindex, DirEgress) + if !errors.Is(err, ErrSnapshotUnreadable) { + t.Errorf("ReadSnapshot err = %v, want ErrSnapshotUnreadable", err) + } + }) + } + unreadable() + if snap, ok, err := m.ReadSnapshot(ifindex, DirEgress); err != nil || !ok || snap.CounterBase != 9 { + t.Errorf("with CAP_SYS_ADMIN: ReadSnapshot = %+v, %v, %v; want the bound snapshot", snap, ok, err) + } + + if err := os.Remove(filepath.Join(dir, snapshotPinDir, fmt.Sprintf("%d-%d", ifindex, DirEgress))); err != nil { + t.Fatal(err) + } + unreadable() +} diff --git a/internal/plumbing/ebpf/tpmap/tpmap.go b/internal/plumbing/ebpf/tpmap/tpmap.go index 51299a2cd..14ae4f6b9 100644 --- a/internal/plumbing/ebpf/tpmap/tpmap.go +++ b/internal/plumbing/ebpf/tpmap/tpmap.go @@ -13,6 +13,12 @@ // update returns (maybe_wait_bpf_programs in kernel/bpf/syscall.c), so once // Publish returns, counter rows only the old snapshot referenced can be // reused. See docs/enhancements/networking/interface-traffic-policy. +// +// Maps opened from a pin directory also pin each snapshot they publish under +// its tp_snapshots subdirectory. Reading a snapshot back needs a handle to its +// inner map, and the kernel hands one out by map ID only to CAP_SYS_ADMIN; a +// pin can be opened by any process with access to the bpffs, so +// galactic-router can adopt the snapshots bound before it restarted. package tpmap import ( @@ -79,6 +85,15 @@ var SnapshotSpec = ebpf.MapSpec{ MaxEntries: galacticv1alpha1.MaxCompiledEntries + 1, } +// snapshotPinDir is the subdirectory of the pin directory that holds one pin +// per bound snapshot. +const snapshotPinDir = "tp_snapshots" + +// ErrSnapshotUnreadable reports a bound snapshot that has no matching pin and +// whose inner map this process may not open by ID, such as one bound by a +// datapath writer that did not pin it. +var ErrSnapshotUnreadable = errors.New("bound snapshot is unreadable") + // Maps are the traffic policy maps of a loaded or pinned uSID datapath. type Maps struct { State *ebpf.Map @@ -91,6 +106,10 @@ type Maps struct { // Unattributed and AccountingErrorCounts are the node-level counters. Unattributed *ebpf.Map AccountingErrorCounts *ebpf.Map + + // pinDir is where the maps are pinned; empty for maps that are not, whose + // snapshots are not pinned either. + pinDir string } // FromObjects returns the traffic policy maps of objs. @@ -149,7 +168,7 @@ func (m *Maps) GetState() (State, error) { // OpenPinned opens the traffic policy maps pinned under pinDir, as a CNI // plugin does; Close releases them. func OpenPinned(pinDir string) (*Maps, error) { - m := &Maps{} + m := &Maps{pinDir: pinDir} for _, p := range []struct { name string dst **ebpf.Map @@ -350,24 +369,102 @@ func (m *Maps) PublishSnapshot(ifindex, dir uint32, snap Snapshot) error { return fmt.Errorf("write snapshot entry %d: %w", i, err) } } - if err := m.Bindings.Put(prog.UsidTpBindingKey{Ifindex: ifindex, Direction: dir}, inner); err != nil { + key := prog.UsidTpBindingKey{Ifindex: ifindex, Direction: dir} + tmp, err := m.pinTemp(key, inner) + if err != nil { + return err + } + if err := m.Bindings.Put(key, inner); err != nil { + if tmp != "" { + _ = os.Remove(tmp) + } return fmt.Errorf("bind snapshot to ifindex %d direction %d: %w", ifindex, dir, err) } + if tmp != "" { + // The snapshot is bound either way. A missing or stale pin only makes + // it unreadable, which ReadSnapshot reports, so it is not an error here. + if err := os.Rename(tmp, m.snapshotPin(key)); err != nil { + _ = os.Remove(tmp) + _ = os.Remove(m.snapshotPin(key)) + } + } return nil } +// pinTemp pins inner under a temporary name in the snapshot pin directory, +// returning "" for maps without a pin directory. Renaming it over the key's +// pin once bound replaces the previous snapshot's pin in one step. +func (m *Maps) pinTemp(key prog.UsidTpBindingKey, inner *ebpf.Map) (string, error) { + if m.pinDir == "" { + return "", nil + } + dir := filepath.Join(m.pinDir, snapshotPinDir) + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", fmt.Errorf("create snapshot pin directory: %w", err) + } + var b [8]byte + if _, err := rand.Read(b[:]); err != nil { + return "", fmt.Errorf("read random pin name: %w", err) + } + // bpffs refuses any name containing a dot. + tmp := filepath.Join(dir, fmt.Sprintf("tmp-%d-%d-%x", key.Ifindex, key.Direction, b)) + if err := inner.Pin(tmp); err != nil { + return "", fmt.Errorf("pin snapshot of ifindex %d direction %d: %w", key.Ifindex, key.Direction, err) + } + return tmp, nil +} + +// snapshotPin is the path of key's snapshot pin. +func (m *Maps) snapshotPin(key prog.UsidTpBindingKey) string { + return filepath.Join(m.pinDir, snapshotPinDir, fmt.Sprintf("%d-%d", key.Ifindex, key.Direction)) +} + +// openSnapshot opens the inner map bound with id: from key's pin when it is +// that map, otherwise by ID, which the kernel allows only with CAP_SYS_ADMIN +// and reports as ErrSnapshotUnreadable without it. +func (m *Maps) openSnapshot(key prog.UsidTpBindingKey, id ebpf.MapID) (*ebpf.Map, error) { + if m.pinDir != "" { + pinned, err := ebpf.LoadPinnedMap(m.snapshotPin(key), nil) + if err == nil { + if info, err := pinned.Info(); err == nil { + if pinnedID, ok := info.ID(); ok && pinnedID == id { + return pinned, nil + } + } + _ = pinned.Close() + } + } + inner, err := ebpf.NewMapFromID(id) + if errors.Is(err, os.ErrPermission) { + return nil, fmt.Errorf("%w: ifindex %d direction %d has no matching pin: %w", ErrSnapshotUnreadable, + key.Ifindex, key.Direction, err) + } + return inner, err +} + // ReadSnapshot reads ifindex's snapshot in dir, reporting false when none is // bound. Entries carry only each entry's Rule, which names its counter row, -// and its flags; Raw holds every entry in full. +// and its flags; Raw holds every entry in full. A bound snapshot this process +// cannot open returns an error wrapping ErrSnapshotUnreadable. func (m *Maps) ReadSnapshot(ifindex, dir uint32) (Snapshot, bool, error) { - var inner *ebpf.Map - err := m.Bindings.Lookup(prog.UsidTpBindingKey{Ifindex: ifindex, Direction: dir}, &inner) + key := prog.UsidTpBindingKey{Ifindex: ifindex, Direction: dir} + // A map-of-maps lookup read into a uint32 is the inner map's ID; reading + // it into an *ebpf.Map would open it by ID. + var id uint32 + err := m.Bindings.Lookup(key, &id) if errors.Is(err, ebpf.ErrKeyNotExist) || errors.Is(err, os.ErrNotExist) { return Snapshot{}, false, nil } if err != nil { return Snapshot{}, false, fmt.Errorf("look up binding of ifindex %d direction %d: %w", ifindex, dir, err) } + inner, err := m.openSnapshot(key, ebpf.MapID(id)) + if errors.Is(err, os.ErrNotExist) { + return Snapshot{}, false, nil // unbound since it was looked up + } + if err != nil { + return Snapshot{}, false, err + } defer inner.Close() //nolint:errcheck // read-only handle var header prog.UsidTpHeader if err := inner.Lookup(uint32(0), &header); err != nil { @@ -395,14 +492,13 @@ func (m *Maps) ReadSnapshot(ifindex, dir uint32) (Snapshot, bool, error) { // BoundKeys lists every bound interface direction. func (m *Maps) BoundKeys() ([]prog.UsidTpBindingKey, error) { var ( - key prog.UsidTpBindingKey - inner *ebpf.Map - out []prog.UsidTpBindingKey + key prog.UsidTpBindingKey + id uint32 // the inner map's ID, read without opening it + out []prog.UsidTpBindingKey ) it := m.Bindings.Iterate() - for it.Next(&key, &inner) { + for it.Next(&key, &id) { out = append(out, key) - _ = inner.Close() } if err := it.Err(); err != nil { return nil, fmt.Errorf("iterate tp_binding_table: %w", err) @@ -459,14 +555,27 @@ func sumPerCPU(m *ebpf.Map, key any) (packets, bytes uint64, err error) { return packets, bytes, nil } -// Invalidate removes ifindex's snapshot in dir, so it denies as +// Invalidate removes ifindex's snapshot in dir, and its pin, so it denies as // policy_unavailable. It needs no allocation, so it works when publishing a // replacement cannot. func (m *Maps) Invalidate(ifindex, dir uint32) error { - err := m.Bindings.Delete(prog.UsidTpBindingKey{Ifindex: ifindex, Direction: dir}) + key := prog.UsidTpBindingKey{Ifindex: ifindex, Direction: dir} + err := m.Bindings.Delete(key) if err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { return fmt.Errorf("unbind ifindex %d direction %d: %w", ifindex, dir, err) } + if m.pinDir == "" { + return nil + } + // Checked first so a caller whose bpffs mount is read-only, and that never + // pins, is not refused for a pin that does not exist. + pin := m.snapshotPin(key) + if _, err := os.Lstat(pin); errors.Is(err, os.ErrNotExist) { + return nil + } + if err := os.Remove(pin); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("unpin snapshot of ifindex %d direction %d: %w", ifindex, dir, err) + } return nil } diff --git a/internal/trafficpolicy/node/reconciler.go b/internal/trafficpolicy/node/reconciler.go index 6ac81b01c..885056ed1 100644 --- a/internal/trafficpolicy/node/reconciler.go +++ b/internal/trafficpolicy/node/reconciler.go @@ -189,7 +189,7 @@ func (r *Reconciler) reconcile(ctx context.Context, req ctrl.Request) (*statusUp log := ctrl.LoggerFrom(ctx) r.mu.Lock() defer r.mu.Unlock() - if err := r.open(); err != nil { + if err := r.open(ctx); err != nil { // The datapath pins its maps when galactic-cni loads it, which may be // after this process starts. log.Info("traffic policy maps are not available yet", "error", err.Error()) @@ -467,8 +467,12 @@ func (r *Reconciler) drop(ctx context.Context, ifindex uint32, att types.Namespa // bound, adopting them, on the first reconcile; it retries until the // datapath has pinned its maps. Nothing is kept unless every bound snapshot // was read, since a row left unreserved could be handed to another rule -// while a bound snapshot still counts into it. -func (r *Reconciler) open() error { +// while a bound snapshot still counts into it. The one exception is a +// snapshot this process cannot read at all (tpmap.ErrSnapshotUnreadable), such +// as one bound before snapshots were pinned: it is adopted as empty, so it +// stays bound until its attachment's reconcile replaces it or the sweep +// unbinds it, and its rows may count another rule's packets until then. +func (r *Reconciler) open(ctx context.Context) error { if r.maps != nil { return nil } @@ -486,7 +490,7 @@ func (r *Reconciler) open() error { } alloc := tpmap.NewCounterAllocator(rows) adopted := map[bindingKey]tpmap.Snapshot{} - if err := readBound(maps, alloc, adopted); err != nil { + if err := readBound(ctx, maps, alloc, adopted); err != nil { if r.openMaps == nil { maps.Close() } @@ -499,13 +503,21 @@ func (r *Reconciler) open() error { return nil } -func readBound(maps *tpmap.Maps, alloc *tpmap.CounterAllocator, adopted map[bindingKey]tpmap.Snapshot) error { +func readBound(ctx context.Context, maps *tpmap.Maps, alloc *tpmap.CounterAllocator, + adopted map[bindingKey]tpmap.Snapshot, +) error { keys, err := maps.BoundKeys() if err != nil { return err } for _, k := range keys { snap, ok, err := maps.ReadSnapshot(k.Ifindex, k.Direction) + if errors.Is(err, tpmap.ErrSnapshotUnreadable) { + ctrl.LoggerFrom(ctx).Info("adopting an unreadable traffic policy snapshot as empty until it is republished", + "ifindex", k.Ifindex, "direction", k.Direction, "error", err.Error()) + adopted[bindingKey{k.Ifindex, k.Direction}] = tpmap.Snapshot{} + continue + } if err != nil { return err } diff --git a/internal/trafficpolicy/node/reconciler_test.go b/internal/trafficpolicy/node/reconciler_test.go index f2ea0610f..556ffcf26 100644 --- a/internal/trafficpolicy/node/reconciler_test.go +++ b/internal/trafficpolicy/node/reconciler_test.go @@ -36,6 +36,7 @@ import ( cloudv1alpha1 "go.datum.net/galactic/api/cloud/v1alpha1" galacticv1alpha1 "go.datum.net/galactic/api/v1alpha1" + "go.datum.net/galactic/internal/captest" "go.datum.net/galactic/internal/plumbing/ebpf/prog" "go.datum.net/galactic/internal/plumbing/ebpf/tpmap" "go.datum.net/galactic/internal/trafficpolicy" @@ -331,6 +332,7 @@ func TestReconciler(t *testing.T) { p := stepInsertRule(t, f, r, httpRow) r = stepRestart(t, f, httpRow) stepRenameRule(t, f, r, httpRow) + stepRestartUnreadable(t, f) r = stepRebindFailure(t, f) stepMissingPolicy(t, f, r, p) stepNodeMove(t, f, r) @@ -499,6 +501,53 @@ func stepRestart(t *testing.T, f *fixture, httpRow uint32) *Reconciler { return r } +// stepRestartUnreadable: a reconciler restarted without CAP_SYS_ADMIN, as +// galactic-router runs, over snapshots it cannot read (f.maps pins none) +// still opens the maps, republishes the attachment's snapshots with the +// same policy, and sweeps one no attachment claims. +func stepRestartUnreadable(t *testing.T, f *fixture) { + t.Helper() + before, _ := f.snapshot(t, tpmap.DirEgress) + entries, err := trafficpolicy.Compile(trafficpolicy.Default()) + if err != nil { + t.Fatal(err) + } + if err := f.maps.Publish(foreignIfindex, tpmap.DirEgress, 1, 300, entries); err != nil { + t.Fatal(err) + } + r := f.reconciler() + req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: testNS, Name: testAtt}} + captest.WithoutSysAdmin(t, func() { + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Errorf("reconcile: %v", err) + } + }) + if r.maps == nil { + t.Fatal("the restarted reconciler did not open the maps") + } + if got := r.state[f.egressKey()]; got == nil { + t.Fatalf("after restart, egress state = %+v", got) + } + after, ok := f.snapshot(t, tpmap.DirEgress) + if !ok || after.Generation != before.Generation || after.PolicyUID != before.PolicyUID { + t.Errorf("egress snapshot = %+v, want policy generation %d republished", after, before.Generation) + } + foreign := bindingKey{foreignIfindex, tpmap.DirEgress} + if _, ok := r.adopted[foreign]; !ok || len(r.adopted) != 1 { + t.Fatalf("adopted = %v, want only the unclaimed snapshot", r.adopted) + } + + r.openedAt = r.openedAt.Add(-2 * resync) + captest.WithoutSysAdmin(t, func() { + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Errorf("reconcile: %v", err) + } + }) + if _, ok, _ := f.maps.ReadSnapshot(foreignIfindex, tpmap.DirEgress); ok { + t.Error("the unclaimed snapshot is still bound after a resync") + } +} + // stepRenameRule: renaming a rule starts a new series on a fresh, zeroed // row, and its old row is freed. func stepRenameRule(t *testing.T, f *fixture, r *Reconciler, httpRow uint32) { From 06b9a9836e5a90bab2f3c06b427f20edb4d200b0 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Thu, 22 Oct 2026 13:00:53 -0400 Subject: [PATCH 2/3] fix: Remove traffic policy snapshot pins that hold no binding galactic-cni's installer removes the policy state of interfaces that have gone, through maps built from the objects it loaded. Those maps had no pin directory, so the installer unbound a vanished interface's snapshot but left its pin, which kept the inner map alive until a later interface reused the same ifindex and direction. FromPinnedObjects gives the installer's maps the pin directory, so its RemoveInterface removes the pin as the CNI plugins' DEL does. Two other paths could still leave a pin with nothing bound: an interface's DEL unbinding a snapshot after galactic-router bound it but before it renamed the pin into place, and galactic-router stopping between pinning and renaming, which leaves a tmp- pin. SweepPins removes every temporary pin and every key's pin whose binding is gone or holds another map, keeping any whose binding cannot be read or that cannot be opened, so a transient error never removes a bound snapshot's pin. The node reconciler runs it on its first reconcile and once a resync after, under its mutex, so never during its own publish. ErrSnapshotUnreadable now carries why the pin could not be opened. That error is formatted rather than wrapped, so a missing pin does not read as os.ErrNotExist, which ReadSnapshot takes for an unbound snapshot. Related to #1007 Co-Authored-By: Claude Opus 5.5 --- docs/traffic-policy/node.md | 5 +- internal/captest/captest.go | 5 +- internal/installer/installer.go | 2 +- internal/installer/trafficpolicy.go | 4 +- .../plumbing/ebpf/tpmap/snapshotpin_test.go | 55 +++++++++ internal/plumbing/ebpf/tpmap/tpmap.go | 108 ++++++++++++++++-- internal/trafficpolicy/node/reconciler.go | 17 +++ 7 files changed, 179 insertions(+), 17 deletions(-) diff --git a/docs/traffic-policy/node.md b/docs/traffic-policy/node.md index 8b13fa4db..6ab3697fb 100644 --- a/docs/traffic-policy/node.md +++ b/docs/traffic-policy/node.md @@ -59,7 +59,10 @@ and its rows are freed. To read a snapshot back, galactic-router pins each one it publishes under `tp_snapshots/` in the datapath's pin directory, beside the policy maps, and -the CNI plugins remove the pin when they unbind it. The kernel opens a map +galactic-cni removes the pin when it unbinds the snapshot. On its first +reconcile and at most once every five minutes after, galactic-router removes +any pin that holds no bound snapshot, such as one left by a publish that an +interface's removal or a restart interrupted. The kernel opens a map by ID only for `CAP_SYS_ADMIN`, which galactic-router does not have (it runs with `NET_ADMIN` and `BPF`), so a snapshot without a matching pin, such as one bound by a release that did not pin, cannot be read. galactic-router diff --git a/internal/captest/captest.go b/internal/captest/captest.go index 75654c9fe..04aea0d53 100644 --- a/internal/captest/captest.go +++ b/internal/captest/captest.go @@ -19,8 +19,9 @@ import ( // WithoutSysAdmin runs fn on an OS thread whose effective capabilities lack // CAP_SYS_ADMIN, as galactic-router's container does, and waits for it. // Capabilities are per thread, so fn must make its system calls from its own -// goroutine; and since fn does not run on the test goroutine, it reports -// failures with t.Error rather than t.Fatal. The thread exits with fn, so the +// goroutine: a goroutine fn starts runs on other threads, with the full set. +// Since fn does not run on the test goroutine, it reports failures with +// t.Error rather than t.Fatal. The thread exits with fn, so the // rest of the test keeps the full set. func WithoutSysAdmin(t *testing.T, fn func()) { t.Helper() diff --git a/internal/installer/installer.go b/internal/installer/installer.go index 99d9efdc2..f6757b413 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -562,7 +562,7 @@ func startEBPFDatapath(ctx context.Context, m *metrics.Metrics) (ebpfDatapathSta // wiring below inert. if objs, ok := datapath.(*prog.UsidObjects); ok { state.objs = objs - state.trafficPolicy = startTrafficPolicy(objs, policyCfg) + state.trafficPolicy = startTrafficPolicy(objs, attach.PinDir, policyCfg) state.mssClamp = newMSSClampState(objs.MssClampTable, objs.EncapMtuTable) state.mssClamp.reconcile() state.egressGroup.counters = objs.EgressShardCounters diff --git a/internal/installer/trafficpolicy.go b/internal/installer/trafficpolicy.go index 0a1836337..ab98087bc 100644 --- a/internal/installer/trafficpolicy.go +++ b/internal/installer/trafficpolicy.go @@ -39,9 +39,9 @@ var trafficPolicyModes = map[string]uint32{ // startTrafficPolicy runs the traffic policy preflight and writes the node's // mode. The NAT locators start unsynced, so until setNATLocators runs an // encapsulating route's path is unknown and a rule naming a path denies it. -func startTrafficPolicy(objs *prog.UsidObjects, cfg config.TrafficPolicyConfig) *trafficPolicyState { +func startTrafficPolicy(objs *prog.UsidObjects, pinDir string, cfg config.TrafficPolicyConfig) *trafficPolicyState { s := &trafficPolicyState{ - maps: tpmap.FromObjects(objs), + maps: tpmap.FromPinnedObjects(objs, pinDir), state: tpmap.State{Mode: trafficPolicyModes[cfg.Mode], Mark: cfg.Mark, Capable: true}, } if err := preflight.CheckTrafficPolicy(cfg.KernelCheck); err != nil { diff --git a/internal/plumbing/ebpf/tpmap/snapshotpin_test.go b/internal/plumbing/ebpf/tpmap/snapshotpin_test.go index c04c3504f..b3f50f0ff 100644 --- a/internal/plumbing/ebpf/tpmap/snapshotpin_test.go +++ b/internal/plumbing/ebpf/tpmap/snapshotpin_test.go @@ -11,6 +11,8 @@ import ( "path/filepath" "testing" + "github.com/cilium/ebpf" + "go.datum.net/galactic/internal/captest" "go.datum.net/galactic/internal/plumbing/ebpf/prog" "go.datum.net/galactic/internal/trafficpolicy" @@ -149,6 +151,59 @@ func TestUnbindingRemovesPin(t *testing.T) { if pins := snapshotPins(t, dir); len(pins) != 0 { t.Errorf("after RemovePinnedInterface: pins = %v, want none", pins) } + // galactic-cni removes a vanished interface through the objects it loaded. + publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0) + if err := FromPinnedObjects(f.objs, dir).RemoveInterface(ifindex); err != nil { + t.Fatal(err) + } + if pins := snapshotPins(t, dir); len(pins) != 0 { + t.Errorf("after RemoveInterface on the loaded objects: pins = %v, want none", pins) + } +} + +// TestSweepPins: without CAP_SYS_ADMIN, the sweep keeps the pin of a bound +// snapshot and removes a temporary pin, the pin of an unbound key, and a pin +// whose key is bound to another map. +func TestSweepPins(t *testing.T) { + f := newFixture(t, ModeAudit) + f.iface(t) + m, dir := f.pinned(t) + const other uint32 = 2 + publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0) + if err := m.Publish(ifindex, DirIngress, token, 1, nil); err != nil { + t.Fatal(err) + } + if err := m.Publish(other, DirEgress, token, 2, nil); err != nil { + t.Fatal(err) + } + // f.maps manages no pins, so these leave an unbound and a stale pin. + if err := f.maps.Invalidate(ifindex, DirIngress); err != nil { + t.Fatal(err) + } + if err := f.maps.Publish(other, DirEgress, token, 3, nil); err != nil { + t.Fatal(err) + } + leftover, err := ebpf.NewMap(&SnapshotSpec) + if err != nil { + t.Fatal(err) + } + defer leftover.Close() //nolint:errcheck // test handle + if err := leftover.Pin(filepath.Join(dir, snapshotPinDir, "tmp-1-1-0123456789abcdef")); err != nil { + t.Fatal(err) + } + if pins := snapshotPins(t, dir); len(pins) != 4 { + t.Fatalf("pins before the sweep = %v, want 4", pins) + } + + captest.WithoutSysAdmin(t, func() { + if err := m.SweepPins(); err != nil { + t.Errorf("SweepPins: %v", err) + } + }) + want := fmt.Sprintf("%d-%d", ifindex, DirEgress) + if pins := snapshotPins(t, dir); len(pins) != 1 || pins[0] != want { + t.Errorf("pins after the sweep = %v, want only %s", pins, want) + } } // TestUnmatchedSnapshotIsUnreadable: a snapshot bound without a pin, or whose diff --git a/internal/plumbing/ebpf/tpmap/tpmap.go b/internal/plumbing/ebpf/tpmap/tpmap.go index 14ae4f6b9..282a6e08f 100644 --- a/internal/plumbing/ebpf/tpmap/tpmap.go +++ b/internal/plumbing/ebpf/tpmap/tpmap.go @@ -127,6 +127,14 @@ func FromObjects(objs *prog.UsidObjects) *Maps { } } +// FromPinnedObjects returns the traffic policy maps of objs, which the caller +// pinned under pinDir, so the maps manage snapshot pins as OpenPinned's do. +func FromPinnedObjects(objs *prog.UsidObjects, pinDir string) *Maps { + m := FromObjects(objs) + m.pinDir = pinDir + return m +} + // State is tp_state: the node's enforcement mode and what the datapath needs // to apply it. type State struct { @@ -423,25 +431,100 @@ func (m *Maps) snapshotPin(key prog.UsidTpBindingKey) string { // that map, otherwise by ID, which the kernel allows only with CAP_SYS_ADMIN // and reports as ErrSnapshotUnreadable without it. func (m *Maps) openSnapshot(key prog.UsidTpBindingKey, id ebpf.MapID) (*ebpf.Map, error) { + pinErr := errors.New("snapshot pins are not managed") if m.pinDir != "" { - pinned, err := ebpf.LoadPinnedMap(m.snapshotPin(key), nil) - if err == nil { - if info, err := pinned.Info(); err == nil { - if pinnedID, ok := info.ID(); ok && pinnedID == id { - return pinned, nil - } - } - _ = pinned.Close() + var pinned *ebpf.Map + if pinned, pinErr = m.loadPin(m.snapshotPin(key), id); pinErr == nil { + return pinned, nil } } inner, err := ebpf.NewMapFromID(id) if errors.Is(err, os.ErrPermission) { - return nil, fmt.Errorf("%w: ifindex %d direction %d has no matching pin: %w", ErrSnapshotUnreadable, - key.Ifindex, key.Direction, err) + // pinErr is formatted, not wrapped: a missing pin must not read as + // os.ErrNotExist, which callers take for an unbound snapshot. + return nil, fmt.Errorf("%w: ifindex %d direction %d: open pin: %s; open by ID: %w", ErrSnapshotUnreadable, + key.Ifindex, key.Direction, pinErr.Error(), err) } return inner, err } +// errPinMismatch reports a pin that holds a map other than the bound one. +var errPinMismatch = errors.New("pin holds a map other than the bound snapshot") + +// loadPin opens the map pinned at path if its ID is id. +func (m *Maps) loadPin(path string, id ebpf.MapID) (*ebpf.Map, error) { + pinned, err := ebpf.LoadPinnedMap(path, nil) + if err != nil { + return nil, err + } + info, err := pinned.Info() + if err != nil { + _ = pinned.Close() + return nil, fmt.Errorf("read pinned map info: %w", err) + } + if pinnedID, ok := info.ID(); !ok || pinnedID != id { + _ = pinned.Close() + return nil, errPinMismatch + } + return pinned, nil +} + +// SweepPins removes every snapshot pin that holds no bound snapshot: a +// temporary pin a publish left behind, and a key's pin whose binding is gone +// or holds another map, as when an interface's DEL unbinds it while a publish +// for it is still renaming its pin. Only the snapshot publisher may call it, +// and never during one of its own publishes, whose temporary pin it would +// remove. A pin whose binding cannot be read, or that cannot be opened, is +// kept. +func (m *Maps) SweepPins() error { + if m.pinDir == "" { + return nil + } + dir := filepath.Join(m.pinDir, snapshotPinDir) + entries, err := os.ReadDir(dir) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("list snapshot pins: %w", err) + } + var errs []error + for _, e := range entries { + if m.pinBound(e.Name()) { + continue + } + if err := os.Remove(filepath.Join(dir, e.Name())); err != nil && !errors.Is(err, os.ErrNotExist) { + errs = append(errs, fmt.Errorf("remove snapshot pin %s: %w", e.Name(), err)) + } + } + return errors.Join(errs...) +} + +// pinBound reports whether the snapshot pin name is its key's bound snapshot. +func (m *Maps) pinBound(name string) bool { + var key prog.UsidTpBindingKey + if _, err := fmt.Sscanf(name, "%d-%d", &key.Ifindex, &key.Direction); err != nil || + name != fmt.Sprintf("%d-%d", key.Ifindex, key.Direction) { + return false // a temporary pin, or nothing this package wrote + } + var id uint32 + err := m.Bindings.Lookup(key, &id) + if errors.Is(err, ebpf.ErrKeyNotExist) || errors.Is(err, os.ErrNotExist) { + return false + } + if err != nil { + return true + } + pinned, err := m.loadPin(filepath.Join(m.pinDir, snapshotPinDir, name), ebpf.MapID(id)) + if err != nil { + // Only a pin of another map is stale. One that failed to open, such + // as for want of a file descriptor, may be the bound snapshot's. + return !errors.Is(err, errPinMismatch) && !errors.Is(err, os.ErrNotExist) + } + _ = pinned.Close() + return true +} + // ReadSnapshot reads ifindex's snapshot in dir, reporting false when none is // bound. Entries carry only each entry's Rule, which names its counter row, // and its flags; Raw holds every entry in full. A bound snapshot this process @@ -460,7 +543,10 @@ func (m *Maps) ReadSnapshot(ifindex, dir uint32) (Snapshot, bool, error) { } inner, err := m.openSnapshot(key, ebpf.MapID(id)) if errors.Is(err, os.ErrNotExist) { - return Snapshot{}, false, nil // unbound since it was looked up + // Unbound since it was looked up. Only an open by ID tells: without + // CAP_SYS_ADMIN the kernel refuses before it finds the map gone, so + // that case returns ErrSnapshotUnreadable instead. + return Snapshot{}, false, nil } if err != nil { return Snapshot{}, false, err diff --git a/internal/trafficpolicy/node/reconciler.go b/internal/trafficpolicy/node/reconciler.go index 885056ed1..1234b2625 100644 --- a/internal/trafficpolicy/node/reconciler.go +++ b/internal/trafficpolicy/node/reconciler.go @@ -113,6 +113,7 @@ type Reconciler struct { adopted map[bindingKey]tpmap.Snapshot // bound before a restart, not yet reconciled ifaces map[types.NamespacedName]iface openedAt time.Time + sweptAt time.Time // the last snapshot pin sweep // openMaps opens the datapath's maps, and counterRows sizes the row // allocator, zero meaning the whole of tp_rule_counters; tests set both. @@ -196,6 +197,7 @@ func (r *Reconciler) reconcile(ctx context.Context, req ctrl.Request) (*statusUp return nil, ctrl.Result{RequeueAfter: pendingRetry}, nil } r.sweepAdopted(ctx) + r.sweepPins(ctx) var att cloudv1alpha1.VPCAttachment if err := r.Client.Get(ctx, req.NamespacedName, &att); err != nil { @@ -555,6 +557,21 @@ func (r *Reconciler) freeAdopted(key bindingKey) { delete(r.adopted, key) } +// sweepPins removes snapshot pins left holding no bound snapshot, on the +// first reconcile and once a resync after: those a publish left behind when +// galactic-router stopped during it, or when an interface's DEL unbound the +// snapshot while it was being pinned. It runs under r.mu, so never during one +// of this reconciler's publishes. +func (r *Reconciler) sweepPins(ctx context.Context) { + if time.Since(r.sweptAt) < resync { + return + } + r.sweptAt = time.Now() + if err := r.maps.SweepPins(); err != nil { + ctrl.LoggerFrom(ctx).Error(err, "remove stale traffic policy snapshot pins") + } +} + // sweepAdopted unbinds the snapshots bound before a restart that no // attachment has claimed within a full resync, such as one whose // VPCAttachment was deleted while galactic-router was down, so their rows From c44607c77586331eac2eacaa9e9c6449e147d05f Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Thu, 22 Oct 2026 13:22:17 -0400 Subject: [PATCH 3/3] docs: Note counter row reuse and pin memory in traffic policy docs Until a snapshot the router cannot read is republished, its rules can count into rows another snapshot was given, so rollout.md now says so. node.md now says a pin holding no bound snapshot keeps its snapshot's memory until the next sweep. Co-Authored-By: Claude Opus 5.5 --- docs/traffic-policy/node.md | 3 ++- docs/traffic-policy/rollout.md | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/traffic-policy/node.md b/docs/traffic-policy/node.md index 6ab3697fb..b50cf49db 100644 --- a/docs/traffic-policy/node.md +++ b/docs/traffic-policy/node.md @@ -62,7 +62,8 @@ To read a snapshot back, galactic-router pins each one it publishes under galactic-cni removes the pin when it unbinds the snapshot. On its first reconcile and at most once every five minutes after, galactic-router removes any pin that holds no bound snapshot, such as one left by a publish that an -interface's removal or a restart interrupted. The kernel opens a map +interface's removal or a restart interrupted. Until then, such a pin holds its +snapshot's memory. The kernel opens a map by ID only for `CAP_SYS_ADMIN`, which galactic-router does not have (it runs with `NET_ADMIN` and `BPF`), so a snapshot without a matching pin, such as one bound by a release that did not pin, cannot be read. galactic-router diff --git a/docs/traffic-policy/rollout.md b/docs/traffic-policy/rollout.md index 5b9aa5896..615c739bf 100644 --- a/docs/traffic-policy/rollout.md +++ b/docs/traffic-policy/rollout.md @@ -52,6 +52,8 @@ a restart from their pins (see [Traffic policy on the node](node.md#what-it-applies)). The first restart after upgrading from a release that did not pin snapshots republishes every snapshot bound on the node, so their rule counters start again from zero. +Until each one is republished, its rules can count into rows another snapshot +was given. ## Steps