From 4d7d51022a1f8ae29181c380587dbfbb31f7b64f Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Fri, 30 Oct 2026 00:02:58 -0400 Subject: [PATCH 1/2] fix(cni): Keep a VPC's VRF table ID until nothing references it vrf_table rows, egress_route_table rows and galactic-router's route installs are keyed by a VRF's routing table ID and outlive the VRF. Table IDs were allocated lowest-free from live VRF links only, so a VPC whose VRF was deleted and recreated could get a new ID while the next VPC created on the node was given the old one, inheriting the first VPC's inbound mapping, routes and egress rows. Each node now records a reservation per host VRF in tables.json, beside the VRF lock and only changed under it. A recreated VRF gets its reserved table back and a new VPC never takes a reserved one. A missing or unreadable file is rebuilt from the VRFs that exist, so no migration step is needed. The ingress sidecar reserves in its own range and releases on removal, including a retry after the VRF is already gone, since it owns its namespace's state; a VRF that a failed listing could not see is never treated as gone. On each eBPF GC tick, under the VRF lock, galactic-cni releases a reservation once its VRF is gone, no BGPVRFInstance names the VPC and no vrf_table row maps to the table, and that has held for two minutes. The wait outlasts galactic-router's 30-second reconcile, which keeps a deleted VPC's route targets mapped to the table until it runs. The table's egress_route_table rows are removed before the release. The same pass removes egress rows for a host-range table that no VRF and no reservation holds, and the vrf_table sweep rewrites a row whose table ID is not its kernel VRF's, keeping the egress kind ADD wrote. These two cover a VRF deleted outside Galactic or a lost reservation file. Related to #1270 --- docs/cni/architecture.md | 10 + internal/gc/gc.go | 160 ++++++++---- internal/gc/main_test.go | 8 + internal/gc/vrftables.go | 263 ++++++++++++++++++++ internal/gc/vrftables_root_test.go | 211 ++++++++++++++++ internal/gc/vrftables_test.go | 271 ++++++++++++++++++++ internal/ingresssidecar/backend.go | 14 +- internal/installer/installer.go | 6 +- internal/plumbing/vrf/reservation.go | 270 ++++++++++++++++++++ internal/plumbing/vrf/reservation_test.go | 288 ++++++++++++++++++++++ internal/plumbing/vrf/vrf.go | 102 ++++++-- 11 files changed, 1530 insertions(+), 73 deletions(-) create mode 100644 internal/gc/vrftables.go create mode 100644 internal/gc/vrftables_root_test.go create mode 100644 internal/gc/vrftables_test.go create mode 100644 internal/plumbing/vrf/reservation.go create mode 100644 internal/plumbing/vrf/reservation_test.go diff --git a/docs/cni/architecture.md b/docs/cni/architecture.md index 787d902c1..30ea474f8 100644 --- a/docs/cni/architecture.md +++ b/docs/cni/architecture.md @@ -168,6 +168,16 @@ A host link, the tap or the host end of a veth, must stay enslaved to its VPC's The repair restores only what the link still carries when it runs. A VRF deletion flushes the VRF's table and cycles the link, which drops its IPv6 gateway address and its pod-subnet routes. Those come back with the attachment's next ADD, which carries the IPAM result the repair does not have. +### VRF table IDs + +`vrf_table` rows, `egress_route_table` rows and `galactic-router`'s route installs are all keyed by a VRF's routing table ID, and they outlive the VRF that owned it. A table ID therefore stays with its VPC on a node until nothing references it (#1270): + +- **Table IDs are reserved per VPC.** `vrf.EnsureAndEnslave` and `vrf.Add` record each host VRF's table in `tables.json`, beside the VRF lock and changed only under it. A VRF recreated on the node gets its reserved table back, and a new VPC is given the lowest table that neither a VRF nor a reservation holds. A missing or unreadable file is rebuilt from the VRFs that exist, so a node needs no migration. The ingress sidecar reserves in its own range and releases its reservation when it deletes its VRF. +- **GC releases a reservation once nothing references it.** On each eBPF GC tick, after the `vrf_table` sweep, `galactic-cni` takes the VRF lock and releases the reservation of every host VRF whose interface is gone, whose VPC no live `BGPVRFInstance` names, and whose table no `vrf_table` row maps to, once it has stayed that way for two minutes. The wait outlasts `galactic-router`'s 30-second reconcile, which keeps a deleted VPC's route targets mapped to its table until it runs. It removes the table's `egress_route_table` rows first. The same pass removes the `egress_route_table` rows of any host-range table no VRF and no reservation holds. +- **Each holder follows the kernel's table.** The `vrf_table` sweep rewrites a row whose table ID is not its kernel VRF's, keeping the egress kind ADD wrote. `galactic-router` re-reads each applied VRF's table from one VRF listing per reconcile; when the table changed, it re-applies the VRF and withdraws its routes from the old table, removing only entries that still point at the SIDs it installed. A VRF that is only absent keeps its table, which its reservation holds for it. + +With reservations in place, the last two do not act in normal operation. They correct a VRF deleted outside Galactic, or a node whose reservation file was lost. + ## Known Constraints - **No binary's `cmdDel` tears down shared kernel/CRD state.** By design (see Key Design Decisions above) — cleanup of the VRF, routes, the eBPF `vrf_table` entry, and BGP CRDs is deferred to `galactic-router`'s asynchronous GC controller, not performed synchronously in any chain binary's `cmdDel`. The per-attachment host veth/tap interface is the one exception: it is private, not shared, so `cmdDel` deletes it directly instead of deferring it. diff --git a/internal/gc/gc.go b/internal/gc/gc.go index 0867321d9..36bf603cf 100644 --- a/internal/gc/gc.go +++ b/internal/gc/gc.go @@ -104,6 +104,16 @@ type CleanupResult struct { // EBPFVRFEntriesRegistered counts vrf_table entries SweepEBPFVRFTable // re-registered for a live BGPVRFInstance CRD that had no matching row. EBPFVRFEntriesRegistered int + // EBPFVRFEntriesRewritten counts vrf_table entries SweepEBPFVRFTable + // rewrote because their table ID was not their kernel VRF's. + EBPFVRFEntriesRewritten int + // VRFTableReservationsReleased counts VRF table ID reservations + // SweepEBPFVRFTable released once nothing on the node referenced them. + VRFTableReservationsReleased int + // EgressRouteTablesRemoved counts table IDs whose egress_route_table + // entries SweepEBPFVRFTable removed, for a released reservation or a + // table no VRF and no reservation holds. + EgressRouteTablesRemoved int // EBPFNPTv6EntriesRemoved counts stale eBPF uSID datapath nptv6_table // map entries removed by SweepEBPFNPTv6Table. EBPFNPTv6EntriesRemoved int @@ -787,9 +797,9 @@ func SweepEBPFVRFTable(ctx context.Context, k8s client.Client, namespace, nodeNa result.Errors++ return result } - existingKeys := make(map[usidmap.VRFKey]struct{}, len(existing)) + existingRows := make(map[usidmap.VRFKey]usidmap.VRFEntry, len(existing)) for _, e := range existing { - existingKeys[e.VRFKey] = struct{}{} + existingRows[e.VRFKey] = e if e.Block == uformat.BlockIngressSidecar { live[e.VRFKey] = struct{}{} } @@ -812,40 +822,7 @@ func SweepEBPFVRFTable(ctx context.Context, k8s client.Client, namespace, nodeNa live[key] = struct{}{} } - // Repair entries a live BGPVRFInstance expects but vrf_table lacks. A - // reload that changes vrf_table's layout recreates it empty, and CNI ADD - // never re-registers an attachment that already succeeded. - // RepairAttachmentDatapath, started on the same tick, rebuilds them from - // each attachment's interface; this covers a VRF it skipped, such as one - // whose attachment interface is mid-replacement. - for key, instName := range liveCRDNames { - if _, ok := existingKeys[key]; ok { - continue // already present -- Reconcile above is what handles this one - } - vrfTableID, egressKind, ok, err := resolveVRFKernelState(nodeName, instName) - if err != nil { - slog.Error("GC: failed to resolve kernel VRF state while repairing eBPF vrf_table entry", - "vrfInstance", instName, "block", key.Block, "argument", key.Argument, "err", err) - result.Errors++ - continue - } - if !ok { - // No matching kernel VRF interface right now, because teardown is - // in flight or the CNI ADD that creates it has not run. Nothing - // to repopulate from this tick. - continue - } - if err := reg.VRF.Register(key.Block, key.Argument, vrfTableID, egressKind); err != nil { - slog.Error("GC: failed to repair missing eBPF vrf_table entry", - "vrfInstance", instName, "block", key.Block, "argument", key.Argument, "err", err) - result.Errors++ - continue - } - slog.Info("GC: repaired missing eBPF vrf_table entry", - "vrfInstance", instName, "block", key.Block, "argument", key.Argument, - "vrfTableID", vrfTableID, "egressKind", egressKind) - result.EBPFVRFEntriesRegistered++ - } + repairVRFRows(reg.VRF, nodeName, liveCRDNames, existingRows, &result) removed, err := reg.VRF.Reconcile(live, cutoff) for _, e := range removed { @@ -872,9 +849,75 @@ func SweepEBPFVRFTable(ctx context.Context, k8s client.Client, namespace, nodeNa result.Errors++ } + // Last, once the entries of VPCs gone from the node are removed above, so + // their table IDs can be released on this same pass. + instNames := make(map[string]struct{}, len(liveCRDNames)) + for _, name := range liveCRDNames { + instNames[name] = struct{}{} + } + sweepVRFTableState(reg.VRF, pinDir, nodeName, instNames, &result) + return result } +// repairVRFRows registers the vrf_table entry each live BGPVRFInstance in +// liveCRDNames expects but vrf_table lacks. A reload that changes vrf_table's +// layout recreates it empty, and CNI ADD never re-registers an attachment that +// already succeeded. RepairAttachmentDatapath, started on the same tick, +// rebuilds them from each attachment's interface; this covers a VRF it +// skipped, such as one whose attachment interface is mid-replacement. +// +// It also rewrites an entry whose table ID is not its kernel VRF's: the VRF +// was recreated on another table with no CNI ADD to re-register it, and the +// datapath would otherwise route the VPC through a table another VPC can be +// given (#1270). The egress kind the CNI wrote is kept. +func repairVRFRows(table *usidmap.VRFTable, nodeName string, liveCRDNames map[usidmap.VRFKey]string, + existingRows map[usidmap.VRFKey]usidmap.VRFEntry, result *CleanupResult) { + if len(liveCRDNames) == 0 { + return + } + kernel, err := listKernelVRFs() + if err != nil { + slog.Error("GC: failed to list kernel VRFs while repairing eBPF vrf_table entries", "err", err) + result.Errors++ + return + } + for key, instName := range liveCRDNames { + vrfTableID, egressKind, ok := kernel.resolve(nodeName, instName) + if !ok { + // No matching kernel VRF interface right now, because teardown is + // in flight or the CNI ADD that creates it has not run. Nothing + // to repopulate from this tick. + continue + } + row, present := existingRows[key] + switch { + case !present: + if err := table.Register(key.Block, key.Argument, vrfTableID, egressKind); err != nil { + slog.Error("GC: failed to repair missing eBPF vrf_table entry", + "vrfInstance", instName, "block", key.Block, "argument", key.Argument, "err", err) + result.Errors++ + continue + } + slog.Info("GC: repaired missing eBPF vrf_table entry", + "vrfInstance", instName, "block", key.Block, "argument", key.Argument, + "vrfTableID", vrfTableID, "egressKind", egressKind) + result.EBPFVRFEntriesRegistered++ + case row.VRFTableID != vrfTableID: + if err := table.Register(key.Block, key.Argument, vrfTableID, row.EgressKind); err != nil { + slog.Error("GC: failed to rewrite eBPF vrf_table entry with a stale table ID", + "vrfInstance", instName, "block", key.Block, "argument", key.Argument, "err", err) + result.Errors++ + continue + } + slog.Warn("GC: rewrote eBPF vrf_table entry with a stale table ID", + "vrfInstance", instName, "block", key.Block, "argument", key.Argument, + "from", row.VRFTableID, "to", vrfTableID) + result.EBPFVRFEntriesRewritten++ + } + } +} + // instanceVPC returns the VPC of the kernel VRF among links that the // BGPVRFInstance named instName serves on nodeName, in either CRD name form, // or "" when none does. @@ -964,13 +1007,42 @@ var ( // yet falls back to EgressKindVeth, the common case and vrf_table's zero // value. func resolveVRFKernelState(nodeName, instName string) (vrfTableID uint32, egressKind uint32, ok bool, err error) { - links, err := listVRFLinksFn() + kernel, err := listKernelVRFs() if err != nil { - return 0, 0, false, fmt.Errorf("list kernel VRF interfaces: %w", err) + return 0, 0, false, err } + vrfTableID, egressKind, ok = kernel.resolve(nodeName, instName) + return vrfTableID, egressKind, ok, nil +} +// kernelVRFs is one listing of the node's kernel VRF interfaces and of every +// link, so that resolving many BGPVRFInstances costs two link dumps rather +// than two each. +type kernelVRFs struct { + vrfs []*netlink.Vrf + all []netlink.Link +} + +// listKernelVRFs lists the node's kernel VRF interfaces and every link. +func listKernelVRFs() (kernelVRFs, error) { + vrfs, err := listVRFLinksFn() + if err != nil { + return kernelVRFs{}, fmt.Errorf("list kernel VRF interfaces: %w", err) + } + if len(vrfs) == 0 { + return kernelVRFs{}, nil + } + all, err := listAllLinksFn() + if err != nil { + return kernelVRFs{}, fmt.Errorf("list kernel interfaces: %w", err) + } + return kernelVRFs{vrfs: vrfs, all: all}, nil +} + +// resolve is resolveVRFKernelState against this listing. +func (k kernelVRFs) resolve(nodeName, instName string) (vrfTableID uint32, egressKind uint32, ok bool) { var match *netlink.Vrf - for _, link := range links { + for _, link := range k.vrfs { vpc, vpcOK := parseVRFName(link.Name) if !vpcOK { continue @@ -986,15 +1058,11 @@ func resolveVRFKernelState(nodeName, instName string) (vrfTableID uint32, egress } } if match == nil { - return 0, 0, false, nil + return 0, 0, false } kind := usidmap.EgressKindVeth - allLinks, err := listAllLinksFn() - if err != nil { - return 0, 0, false, fmt.Errorf("list kernel interfaces: %w", err) - } - for _, l := range allLinks { + for _, l := range k.all { if l.Attrs().MasterIndex != match.Attrs().Index { continue } @@ -1004,7 +1072,7 @@ func resolveVRFKernelState(nodeName, instName string) (vrfTableID uint32, egress break } - return match.Table, kind, true, nil + return match.Table, kind, true } // SweepEBPFNPTv6Table reconciles the eBPF nptv6_table map against the NPTv6 diff --git a/internal/gc/main_test.go b/internal/gc/main_test.go index 70dba2e9c..4b7172d3a 100644 --- a/internal/gc/main_test.go +++ b/internal/gc/main_test.go @@ -7,13 +7,21 @@ package gc import ( "os" "testing" + + "go.datum.net/galactic/internal/plumbing/vrf" ) // TestMain runs unprivileged tests without the node-wide VRF lock, whose // directory only root can create. Root tests keep the real lock. +// +// No test reads the node's real VRF table reservations: a sweep finding the +// test machine's reservations could release them. A test exercising +// reservations substitutes its own. func TestMain(m *testing.M) { if os.Geteuid() != 0 { vrfLockedFn = func(fn func() error) error { return fn() } } + vrfReservationsFn = func() ([]vrf.Reservation, error) { return nil, nil } + vrfReleaseFn = func(string, uint32) error { return nil } os.Exit(m.Run()) } diff --git a/internal/gc/vrftables.go b/internal/gc/vrftables.go new file mode 100644 index 000000000..ecb3c9d68 --- /dev/null +++ b/internal/gc/vrftables.go @@ -0,0 +1,263 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gc + +import ( + "errors" + "fmt" + "io" + "io/fs" + "log/slog" + "net" + "sync" + "time" + + "go.datum.net/galactic/internal/plumbing/ebpf/egressroutemap" + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" + "go.datum.net/galactic/internal/plumbing/vrf" +) + +// VRF table ID reservations (see vrf.Reservation) keep a deleted VRF's table +// ID from going to another VPC while node state still references it (#1270). +// This file releases them once nothing does, and removes egress_route_table +// entries keyed by a table no VRF and no reservation holds. + +// egressRoutes is the part of the egress_route_table API sweepVRFTableState +// uses; an interface so unprivileged tests can substitute a fake map. +type egressRoutes interface { + Prefixes() (map[uint32]map[string]struct{}, error) + Unregister(tableID uint32, prefix *net.IPNet) error +} + +// vrfRows lists vrf_table's entries. +type vrfRows interface { + List() ([]usidmap.VRFEntry, error) +} + +// Seams for unprivileged tests, which have no reservation file, lock or pinned +// map. +var ( + vrfReservationsFn = vrf.ReservationsLocked + vrfReleaseFn = vrf.ReleaseLocked + openEgressRoutesFn = func(pinDir string) (egressRoutes, io.Closer, error) { + return egressroutemap.OpenPinnedEgressRouteTable(pinDir) + } +) + +// reservationReleaseGrace is how long a reservation stays unreferenced before +// it is released. galactic-router keeps a deleted VPC's route targets mapped +// to its table until its next reconcile, at most 30 seconds later, and +// installs remote routes there meanwhile; releasing sooner could hand those +// to the next VPC given the table. +const reservationReleaseGrace = 2 * time.Minute + +// nowFn is the clock the release grace is measured on; a variable for tests. +var nowFn = time.Now + +// unreferenced records when each reservation was first seen unreferenced. +// It lives for the process, so a restart only restarts the grace. +var unreferenced = &unreferencedSince{seen: map[vrf.Reservation]time.Time{}} + +type unreferencedSince struct { + mu sync.Mutex + seen map[vrf.Reservation]time.Time +} + +// elapsed records r as unreferenced at now if it was not already, and reports +// whether it has been for at least grace. +func (u *unreferencedSince) elapsed(r vrf.Reservation, now time.Time, grace time.Duration) bool { + u.mu.Lock() + defer u.mu.Unlock() + first, ok := u.seen[r] + if !ok { + u.seen[r] = now + return false + } + return now.Sub(first) >= grace +} + +// forget drops r, referenced again or released. +func (u *unreferencedSince) forget(r vrf.Reservation) { + u.mu.Lock() + defer u.mu.Unlock() + delete(u.seen, r) +} + +// referenced reports whether anything on the node still references +// reservation r: its VRF interface, a VRF holding its table, a vrf_table entry +// mapping to its table, or a live BGPVRFInstance naming its VPC. A reservation +// outside the host range counts as referenced, since its owner releases it. +func referenced(r vrf.Reservation, liveNames map[string]struct{}, liveTables, rowTables map[uint32]struct{}, + nodeName string, instNames map[string]struct{}) bool { + if !hostTable(r.Table) { + return true + } + if _, ok := liveNames[r.Name]; ok { + return true + } + if _, ok := liveTables[r.Table]; ok { + return true + } + if _, ok := rowTables[r.Table]; ok { + return true + } + return vrfNamedByInstance(r.Name, nodeName, instNames) +} + +// hostTable reports whether table is in the range host VRFs are allocated +// from. Other ranges belong to the ingress sidecar and the installer's +// sidecar return path, which manage their own tables. +func hostTable(table uint32) bool { + return table >= vrf.HostTableIDMin && table <= vrf.HostTableIDMax +} + +// sweepVRFTableState releases the table ID reservation of every host VRF that +// nothing on the node references any more, and removes the egress_route_table +// entries of every host table no VRF and no reservation holds. +// +// A reservation is released only once its VRF interface is gone, no live +// BGPVRFInstance in instNames names its VPC, and no vrf_table entry maps to +// its table, on sweeps at least reservationReleaseGrace apart. Its +// egress_route_table entries are removed first, so the next VPC given the +// table starts with none of them. +// +// It all runs under the VRF lock, so no CNI ADD creates a VRF or reserves a +// table meanwhile. The CNI and galactic-router write a table's +// egress_route_table entries only once its VRF exists, so a table with no VRF +// and no reservation under the lock has no writer. +func sweepVRFTableState(rows vrfRows, pinDir, nodeName string, instNames map[string]struct{}, result *CleanupResult) { + err := vrfLockedFn(func() error { + reservations, err := vrfReservationsFn() + if err != nil { + return fmt.Errorf("read VRF table reservations: %w", err) + } + links, err := listVRFLinksFn() + if err != nil { + return fmt.Errorf("list kernel VRF interfaces: %w", err) + } + entries, err := rows.List() + if err != nil { + return fmt.Errorf("list eBPF vrf_table: %w", err) + } + egress, closer, err := openEgressRoutesFn(pinDir) + if errors.Is(err, fs.ErrNotExist) { + return nil // not pinned yet; nothing can be keyed by a table + } + if err != nil { + return fmt.Errorf("open pinned egress_route_table: %w", err) + } + defer func() { _ = closer.Close() }() + byTable, err := egress.Prefixes() + if err != nil { + return err + } + + liveNames := make(map[string]struct{}, len(links)) + liveTables := make(map[uint32]struct{}, len(links)) + for _, l := range links { + liveNames[l.Name] = struct{}{} + liveTables[l.Table] = struct{}{} + } + rowTables := make(map[uint32]struct{}, len(entries)) + for _, e := range entries { + rowTables[e.VRFTableID] = struct{}{} + } + + reserved := make(map[uint32]int, len(reservations)) + for _, r := range reservations { + reserved[r.Table]++ + } + now := nowFn() + for _, r := range reservations { + if referenced(r, liveNames, liveTables, rowTables, nodeName, instNames) { + unreferenced.forget(r) + continue + } + if !unreferenced.elapsed(r, now, reservationReleaseGrace) { + continue + } + removed, err := removeEgressTable(egress, r.Table, byTable[r.Table]) + if err != nil { + slog.Error("GC: failed to remove a released VRF table's egress_route_table entries", + "vrf", r.Name, "table", r.Table, "err", err) + result.Errors++ + continue + } + delete(byTable, r.Table) + if removed > 0 { + result.EgressRouteTablesRemoved++ + } + if err := vrfReleaseFn(r.Name, r.Table); err != nil { + slog.Error("GC: failed to release VRF table reservation", "vrf", r.Name, "table", r.Table, "err", err) + result.Errors++ + continue + } + reserved[r.Table]-- + unreferenced.forget(r) + slog.Info("GC: released VRF table reservation", "vrf", r.Name, "table", r.Table, + "egressRoutesRemoved", removed) + result.VRFTableReservationsReleased++ + } + + for table, prefixes := range byTable { + if !hostTable(table) || reserved[table] > 0 { + continue + } + if _, ok := liveTables[table]; ok { + continue + } + if _, ok := rowTables[table]; ok { + continue + } + removed, err := removeEgressTable(egress, table, prefixes) + if err != nil { + slog.Error("GC: failed to remove egress_route_table entries of a table no VRF holds", + "table", table, "err", err) + result.Errors++ + continue + } + slog.Warn("GC: removed egress_route_table entries of a table no VRF holds", + "table", table, "removed", removed) + result.EgressRouteTablesRemoved++ + } + return nil + }) + if err != nil { + slog.Error("GC: failed to sweep VRF table reservations", "err", err) + result.Errors++ + } +} + +// vrfNamedByInstance reports whether a BGPVRFInstance in instNames serves the +// VPC of the VRF interface vrfName on nodeName, in either CRD name form. +func vrfNamedByInstance(vrfName, nodeName string, instNames map[string]struct{}) bool { + vpc, ok := vpcFromVRFName(vrfName) + if !ok { + return false + } + for _, key := range vpcKeys(vpc) { + if _, ok := instNames[key+"-"+nodeName]; ok { + return true + } + } + return false +} + +// removeEgressTable removes table's egress_route_table entries, given by +// prefix, and returns how many it removed. +func removeEgressTable(egress egressRoutes, table uint32, prefixes map[string]struct{}) (int, error) { + removed := 0 + for p := range prefixes { + _, prefix, err := net.ParseCIDR(p) + if err != nil { + return removed, fmt.Errorf("parse egress_route_table prefix %q: %w", p, err) + } + if err := egress.Unregister(table, prefix); err != nil { + return removed, err + } + removed++ + } + return removed, nil +} diff --git a/internal/gc/vrftables_root_test.go b/internal/gc/vrftables_root_test.go new file mode 100644 index 000000000..7e4bd6545 --- /dev/null +++ b/internal/gc/vrftables_root_test.go @@ -0,0 +1,211 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gc + +import ( + "context" + "fmt" + "net" + "os" + "testing" + + "github.com/vishvananda/netlink" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + "go.datum.net/galactic/internal/crdnames" + "go.datum.net/galactic/internal/plumbing/ebpf/attach" + "go.datum.net/galactic/internal/plumbing/ebpf/egressroutemap" + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" + "go.datum.net/galactic/internal/plumbing/intf" + "go.datum.net/galactic/internal/plumbing/vrf" +) + +// Root tests for issue #1270 against the real pinned maps. + +const vrfTablesRouter = "router-a" + +func vrfTablesRouterObj() *bgpv1alpha1.BGPRouter { + return &bgpv1alpha1.BGPRouter{ + ObjectMeta: metav1.ObjectMeta{Name: vrfTablesRouter, Namespace: "default"}, + Spec: bgpv1alpha1.BGPRouterSpec{ + TargetRef: bgpv1alpha1.TargetRef{Kind: targetKindNode, Name: vrfTablesNode}, + LocalASN: 65000, + SRv6Locator: testLocator, + NodeID: 5, + }, + } +} + +func vrfTablesInstance(vpc string, argument int32) *bgpv1alpha1.BGPVRFInstance { + return &bgpv1alpha1.BGPVRFInstance{ + ObjectMeta: metav1.ObjectMeta{Name: crdnames.BGPVRFInstanceName(vpc, vrfTablesNode), Namespace: "default"}, + Spec: bgpv1alpha1.BGPVRFInstanceSpec{ + RouterTarget: bgpv1alpha1.RouterTarget{RouterRef: &bgpv1alpha1.RouterRef{Name: vrfTablesRouter}}, + VRFID: argument, + ImportRouteTargets: []bgpv1alpha1.RouteTarget{{Value: testRouteTarget}}, + ExportRouteTargets: []bgpv1alpha1.RouteTarget{{Value: testRouteTarget}}, + }, + } +} + +// loadVRFTablesMaps loads the uSID datapath's maps under a fresh pin +// directory and opens vrf_table and egress_route_table from it. +func loadVRFTablesMaps(t *testing.T, name string) (string, *usidmap.Registry, *egressroutemap.EgressRouteTable) { + t.Helper() + pinDir := fmt.Sprintf("/sys/fs/bpf/galactic-gcsweep-%s-%d", name, os.Getpid()) + t.Cleanup(func() { _ = os.RemoveAll(pinDir) }) + objs, err := attach.Load(pinDir) + if err != nil { + t.Fatalf("attach.Load: %v", err) + } + t.Cleanup(func() { _ = objs.Close() }) + reg, regCloser, err := usidmap.OpenPinnedRegistry(pinDir) + if err != nil { + t.Fatalf("OpenPinnedRegistry: %v", err) + } + t.Cleanup(func() { _ = regCloser.Close() }) + egress, egressCloser, err := egressroutemap.OpenPinnedEgressRouteTable(pinDir) + if err != nil { + t.Fatalf("OpenPinnedEgressRouteTable: %v", err) + } + t.Cleanup(func() { _ = egressCloser.Close() }) + return pinDir, reg, egress +} + +// TestSweepEBPFVRFTable_RewritesStaleTableID registers a VPC's vrf_table +// entry on a table its kernel VRF no longer has, as after the VRF was +// recreated with no CNI ADD to re-register it, and checks that the sweep +// moves the entry to the VRF's table and keeps its egress kind. +func TestSweepEBPFVRFTable_RewritesStaleTableID(t *testing.T) { + requireRoot(t) + const argument = int32(10) + withFakeLinks(t, []*netlink.Vrf{{LinkAttrs: netlink.LinkAttrs{Name: testVRFName, Index: 42}, Table: 9}}, nil) + k8s := fake.NewClientBuilder().WithScheme(gcTestScheme(t)). + WithObjects(vrfTablesRouterObj(), vrfTablesInstance("jU", argument)).Build() + pinDir, reg, _ := loadVRFTablesMaps(t, "rewrite") + + block, err := blockFromLocator(t) + if err != nil { + t.Fatalf("derive block: %v", err) + } + if err := reg.VRF.Register(block, uint16(argument), 7, usidmap.EgressKindTap); err != nil { + t.Fatalf("seed entry: %v", err) + } + + result := SweepEBPFVRFTable(context.Background(), k8s, "default", vrfTablesNode, pinDir) + if result.Errors != 0 || result.EBPFVRFEntriesRewritten != 1 { + t.Errorf("result = %+v, want 1 entry rewritten and no errors", result) + } + entry, ok, err := reg.VRF.Get(block, uint16(argument)) + if err != nil || !ok { + t.Fatalf("entry after sweep: ok=%v err=%v", ok, err) + } + if entry.VRFTableID != 9 || entry.EgressKind != usidmap.EgressKindTap { + t.Errorf("entry = table %d kind %d, want table 9 kind %d (the CNI's egress kind kept)", + entry.VRFTableID, entry.EgressKind, usidmap.EgressKindTap) + } +} + +// TestRecreatedVRFKeepsItsTableWhileAnotherVPCIsCreated deletes VPC A's kernel +// VRF the way garbage collection does, creates VPC B, then recreates A, with +// real VRFs and the real pinned maps. B must not be given A's table while A's +// state still references it, A must get its own table back, and after a +// sweep vrf_table and egress_route_table must route each VPC through its own +// table. +func TestRecreatedVRFKeepsItsTableWhileAnotherVPCIsCreated(t *testing.T) { + requireRoot(t) + const ( + vpcA, vpcB = "vtrka", "vtrkb" + argA, argB = int32(10), int32(11) + ) + t.Cleanup(func() { _ = vrf.Delete(vpcA); _ = vrf.Delete(vpcB) }) + k8s := fake.NewClientBuilder().WithScheme(gcTestScheme(t)).WithObjects( + vrfTablesRouterObj(), vrfTablesInstance(vpcA, argA), vrfTablesInstance(vpcB, argB), + ).Build() + pinDir, reg, egress := loadVRFTablesMaps(t, "recreate") + block, err := blockFromLocator(t) + if err != nil { + t.Fatalf("derive block: %v", err) + } + _, prefixA, _ := net.ParseCIDR("2001:db8:a::/64") + _, prefixB, _ := net.ParseCIDR("2001:db8:b::/64") + + // A attaches: its VRF, its vrf_table entry and an egress entry. + if err := vrf.Add(vpcA); err != nil { + t.Fatalf("Add(A): %v", err) + } + tableA, err := vrf.TableID(vpcA) + if err != nil { + t.Fatalf("TableID(A): %v", err) + } + if err := reg.VRF.Register(block, uint16(argA), tableA, usidmap.EgressKindVeth); err != nil { + t.Fatalf("register A: %v", err) + } + if err := egress.RegisterPassThrough(tableA, prefixA); err != nil { + t.Fatalf("egress entry for A: %v", err) + } + + // A's VRF is deleted while its BGPVRFInstance and map state remain. + if _, err := vrf.DeleteIfUnused(intf.GenerateInterfaceNameVRF(vpcA)); err != nil { + t.Fatalf("DeleteIfUnused(A): %v", err) + } + + // B attaches meanwhile. + if err := vrf.Add(vpcB); err != nil { + t.Fatalf("Add(B): %v", err) + } + tableB, err := vrf.TableID(vpcB) + if err != nil { + t.Fatalf("TableID(B): %v", err) + } + if tableB == tableA { + t.Fatalf("B was given table %d, which A's vrf_table and egress_route_table entries still use", tableA) + } + if err := reg.VRF.Register(block, uint16(argB), tableB, usidmap.EgressKindVeth); err != nil { + t.Fatalf("register B: %v", err) + } + if err := egress.RegisterPassThrough(tableB, prefixB); err != nil { + t.Fatalf("egress entry for B: %v", err) + } + + // A's VRF is recreated without a CNI ADD re-registering it. + if err := vrf.Add(vpcA); err != nil { + t.Fatalf("re-Add(A): %v", err) + } + if got, err := vrf.TableID(vpcA); err != nil || got != tableA { + t.Fatalf("recreated A's table = %d, %v; want its own table %d", got, err, tableA) + } + + result := SweepEBPFVRFTable(context.Background(), k8s, "default", vrfTablesNode, pinDir) + if result.Errors != 0 { + t.Errorf("result.Errors = %d, want 0", result.Errors) + } + for _, c := range []struct { + name string + arg int32 + table uint32 + }{{"A", argA, tableA}, {"B", argB, tableB}} { + entry, ok, err := reg.VRF.Get(block, uint16(c.arg)) + if err != nil || !ok || entry.VRFTableID != c.table { + t.Errorf("vrf_table entry for %s = table %d (ok=%v err=%v), want %d", + c.name, entry.VRFTableID, ok, err, c.table) + } + } + prefixes, err := egress.Prefixes() + if err != nil { + t.Fatalf("egress Prefixes: %v", err) + } + if _, ok := prefixes[tableA][prefixA.String()]; !ok { + t.Errorf("A's egress entry left table %d", tableA) + } + if _, ok := prefixes[tableB][prefixA.String()]; ok { + t.Errorf("A's egress entry is in B's table %d", tableB) + } + if _, ok := prefixes[tableB][prefixB.String()]; !ok { + t.Errorf("B's egress entry left table %d", tableB) + } +} diff --git a/internal/gc/vrftables_test.go b/internal/gc/vrftables_test.go new file mode 100644 index 000000000..95bc5cc33 --- /dev/null +++ b/internal/gc/vrftables_test.go @@ -0,0 +1,271 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gc + +import ( + "fmt" + "io" + "io/fs" + "net" + "reflect" + "sort" + "testing" + "time" + + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/crdnames" + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" + "go.datum.net/galactic/internal/plumbing/vrf" +) + +// These tests guard issue #1270: a VRF table ID must not go to another VPC +// while node state still references it, and egress_route_table entries keyed +// by a table nothing holds must not wait for another VPC to inherit them. + +const ( + vrfTablesNode = "worker-a" + // defaultRoute is an egress_route_table prefix every fixture table holds. + defaultRoute = "::/0" +) + +// fakeEgressRoutes is an in-memory egress_route_table, by table and prefix. +type fakeEgressRoutes struct { + rows map[uint32]map[string]struct{} +} + +func newFakeEgressRoutes(rows map[uint32][]string) *fakeEgressRoutes { + f := &fakeEgressRoutes{rows: map[uint32]map[string]struct{}{}} + for table, prefixes := range rows { + f.rows[table] = map[string]struct{}{} + for _, p := range prefixes { + f.rows[table][p] = struct{}{} + } + } + return f +} + +func (f *fakeEgressRoutes) Prefixes() (map[uint32]map[string]struct{}, error) { + out := make(map[uint32]map[string]struct{}, len(f.rows)) + for table, prefixes := range f.rows { + out[table] = map[string]struct{}{} + for p := range prefixes { + out[table][p] = struct{}{} + } + } + return out, nil +} + +func (f *fakeEgressRoutes) Unregister(table uint32, prefix *net.IPNet) error { + delete(f.rows[table], prefix.String()) + if len(f.rows[table]) == 0 { + delete(f.rows, table) + } + return nil +} + +// tables returns the table IDs f holds entries for, sorted. +func (f *fakeEgressRoutes) tables() []uint32 { + out := make([]uint32, 0, len(f.rows)) + for table := range f.rows { + out = append(out, table) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +type fakeVRFRows []usidmap.VRFEntry + +func (r fakeVRFRows) List() ([]usidmap.VRFEntry, error) { return r, nil } + +// vrfTablesFixture substitutes the reservations, the egress_route_table and +// the kernel VRF links sweepVRFTableState reads, and records releases. +type vrfTablesFixture struct { + reservations []vrf.Reservation + released []vrf.Reservation + egress *fakeEgressRoutes + now time.Time +} + +// advance moves the fixture's clock past the release grace. +func (f *vrfTablesFixture) advance() { f.now = f.now.Add(reservationReleaseGrace) } + +func newVRFTablesFixture( + t *testing.T, res []vrf.Reservation, egress map[uint32][]string, links ...*netlink.Vrf, +) *vrfTablesFixture { + t.Helper() + f := &vrfTablesFixture{ + reservations: res, egress: newFakeEgressRoutes(egress), + now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), + } + origRes, origRelease, origOpen := vrfReservationsFn, vrfReleaseFn, openEgressRoutesFn + origNow, origSeen := nowFn, unreferenced + t.Cleanup(func() { + vrfReservationsFn, vrfReleaseFn, openEgressRoutesFn = origRes, origRelease, origOpen + nowFn, unreferenced = origNow, origSeen + }) + nowFn = func() time.Time { return f.now } + unreferenced = &unreferencedSince{seen: map[vrf.Reservation]time.Time{}} + vrfReservationsFn = func() ([]vrf.Reservation, error) { return f.reservations, nil } + vrfReleaseFn = func(name string, table uint32) error { + f.released = append(f.released, vrf.Reservation{Name: name, Table: table}) + return nil + } + openEgressRoutesFn = func(string) (egressRoutes, io.Closer, error) { return f.egress, io.NopCloser(nil), nil } + withFakeLinks(t, links, nil) + return f +} + +// otherVRFName is a VRF interface name for a second VPC. +const otherVRFName = "G0000000kVV" + +func TestSweepVRFTableState_ReleasesUnreferencedReservation(t *testing.T) { + f := newVRFTablesFixture(t, + []vrf.Reservation{{Name: testVRFName, Table: 7}}, + map[uint32][]string{7: {defaultRoute, "2001:db8:100::/64"}, 8: {defaultRoute}}, + &netlink.Vrf{LinkAttrs: netlink.LinkAttrs{Name: otherVRFName}, Table: 8}, + ) + var result CleanupResult + sweepVRFTableState(fakeVRFRows{}, "", vrfTablesNode, nil, &result) + f.now = f.now.Add(reservationReleaseGrace - time.Second) + sweepVRFTableState(fakeVRFRows{}, "", vrfTablesNode, nil, &result) + if len(f.released) != 0 || len(f.egress.tables()) != 2 { + t.Fatalf("released = %v, egress tables = %v within the grace; want nothing released or removed", + f.released, f.egress.tables()) + } + + f.advance() + sweepVRFTableState(fakeVRFRows{}, "", vrfTablesNode, nil, &result) + if want := []vrf.Reservation{{Name: testVRFName, Table: 7}}; !reflect.DeepEqual(f.released, want) { + t.Errorf("released = %v, want %v", f.released, want) + } + if got, want := f.egress.tables(), []uint32{8}; !reflect.DeepEqual(got, want) { + t.Errorf("egress_route_table tables = %v, want %v: table 7's entries go before its ID is released", got, want) + } + if result.VRFTableReservationsReleased != 1 || result.EgressRouteTablesRemoved != 1 || result.Errors != 0 { + t.Errorf("result = %+v, want 1 released, 1 egress table removed, no errors", result) + } +} + +func TestSweepVRFTableState_KeepsReferencedReservation(t *testing.T) { + instName := crdnames.BGPVRFInstanceName("jU", vrfTablesNode) + cases := []struct { + name string + links []*netlink.Vrf + rows fakeVRFRows + instNames map[string]struct{} + res vrf.Reservation + }{ + { + name: "its VRF interface exists", + links: []*netlink.Vrf{{LinkAttrs: netlink.LinkAttrs{Name: testVRFName}, Table: 7}}, + res: vrf.Reservation{Name: testVRFName, Table: 7}, + }, + { + name: "a vrf_table entry still maps to its table", + rows: fakeVRFRows{{VRFKey: usidmap.VRFKey{Block: 1, Argument: 10}, VRFTableID: 7}}, + res: vrf.Reservation{Name: testVRFName, Table: 7}, + }, + { + name: "a live BGPVRFInstance names its VPC", + instNames: map[string]struct{}{instName: {}}, + res: vrf.Reservation{Name: testVRFName, Table: 7}, + }, + { + name: "another VRF holds its table", + links: []*netlink.Vrf{{LinkAttrs: netlink.LinkAttrs{Name: otherVRFName}, Table: 7}}, + res: vrf.Reservation{Name: testVRFName, Table: 7}, + }, + { + name: "it is outside the host range", + res: vrf.Reservation{Name: testVRFName, Table: vrf.SidecarTableIDBase + 1}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newVRFTablesFixture(t, []vrf.Reservation{tc.res}, + map[uint32][]string{tc.res.Table: {defaultRoute}}, tc.links...) + var result CleanupResult + sweepVRFTableState(tc.rows, "", vrfTablesNode, tc.instNames, &result) + f.advance() + sweepVRFTableState(tc.rows, "", vrfTablesNode, tc.instNames, &result) + if len(f.released) != 0 { + t.Errorf("released = %v, want none", f.released) + } + if got, want := f.egress.tables(), []uint32{tc.res.Table}; !reflect.DeepEqual(got, want) { + t.Errorf("egress_route_table tables = %v, want %v kept", got, want) + } + if result.Errors != 0 { + t.Errorf("result.Errors = %d, want 0", result.Errors) + } + }) + } +} + +func TestSweepVRFTableState_RemovesOrphanedEgressTables(t *testing.T) { + const ( + liveTable = 3 + reservedTable = 4 + rowTable = 5 + orphanTable = 6 + ) + returnTable := vrf.HostTableIDMax + 1 // the installer's sidecar return path + sidecarTable := vrf.SidecarTableIDBase + 1 // the ingress sidecar's own range + f := newVRFTablesFixture(t, + []vrf.Reservation{{Name: otherVRFName, Table: liveTable}, {Name: testVRFName, Table: reservedTable}}, + map[uint32][]string{ + liveTable: {defaultRoute}, reservedTable: {defaultRoute}, rowTable: {defaultRoute}, + orphanTable: {defaultRoute, "198.51.100.0/24"}, returnTable: {defaultRoute}, sidecarTable: {defaultRoute}, + }, + &netlink.Vrf{LinkAttrs: netlink.LinkAttrs{Name: otherVRFName}, Table: liveTable}, + ) + instName := crdnames.BGPVRFInstanceName("jU", vrfTablesNode) + rows := fakeVRFRows{{VRFKey: usidmap.VRFKey{Block: 1, Argument: 10}, VRFTableID: rowTable}} + + var result CleanupResult + sweepVRFTableState(rows, "", vrfTablesNode, map[string]struct{}{instName: {}}, &result) + + want := []uint32{liveTable, reservedTable, rowTable, returnTable, sidecarTable} + if got := f.egress.tables(); !reflect.DeepEqual(got, want) { + t.Errorf("egress_route_table tables = %v, want %v: only the orphaned host table goes", got, want) + } + if result.EgressRouteTablesRemoved != 1 || result.VRFTableReservationsReleased != 0 || result.Errors != 0 { + t.Errorf("result = %+v, want 1 egress table removed, nothing released, no errors", result) + } +} + +func TestSweepVRFTableState_NoPinnedEgressMapIsNoOp(t *testing.T) { + f := newVRFTablesFixture(t, []vrf.Reservation{{Name: testVRFName, Table: 7}}, nil) + openEgressRoutesFn = func(string) (egressRoutes, io.Closer, error) { + return nil, nil, fmt.Errorf("open pinned map: %w", fs.ErrNotExist) + } + var result CleanupResult + sweepVRFTableState(fakeVRFRows{}, "", vrfTablesNode, nil, &result) + if len(f.released) != 0 || result.Errors != 0 { + t.Errorf("released = %v, errors = %d; want nothing released and no error", f.released, result.Errors) + } +} + +// TestSweepVRFTableState_ReferenceRestartsGrace checks that a reservation +// referenced again within the grace, as when galactic-router or the CNI +// catches up, waits a full grace from its next unreferenced sweep. +func TestSweepVRFTableState_ReferenceRestartsGrace(t *testing.T) { + f := newVRFTablesFixture(t, []vrf.Reservation{{Name: testVRFName, Table: 7}}, map[uint32][]string{7: {defaultRoute}}) + instName := crdnames.BGPVRFInstanceName("jU", vrfTablesNode) + var result CleanupResult + + sweepVRFTableState(fakeVRFRows{}, "", vrfTablesNode, nil, &result) + f.advance() + sweepVRFTableState(fakeVRFRows{}, "", vrfTablesNode, map[string]struct{}{instName: {}}, &result) + sweepVRFTableState(fakeVRFRows{}, "", vrfTablesNode, nil, &result) + if len(f.released) != 0 { + t.Fatalf("released = %v right after the reservation was referenced again, want none", f.released) + } + f.advance() + sweepVRFTableState(fakeVRFRows{}, "", vrfTablesNode, nil, &result) + if want := []vrf.Reservation{{Name: testVRFName, Table: 7}}; !reflect.DeepEqual(f.released, want) { + t.Errorf("released = %v, want %v once a full grace passed unreferenced", f.released, want) + } +} diff --git a/internal/ingresssidecar/backend.go b/internal/ingresssidecar/backend.go index 8dbfa69a2..9a6f362f1 100644 --- a/internal/ingresssidecar/backend.go +++ b/internal/ingresssidecar/backend.go @@ -109,15 +109,23 @@ func (kernelBackend) RemoveVRF(vpc string) error { return fmt.Errorf("remove gateway reply redirect for vpc %s: %w", vpc, err) } tableID, err := vrf.TableID(vpc) - if err != nil { - return nil // VRF already gone — idempotent, matching vrf.Delete's own stance + switch { + case errors.Is(err, vrf.ErrNotFound): + // VRF already gone, which is idempotent, but a removal that failed + // after deleting it may have left its table ID reserved. + if err := vrf.DeleteInRange(vpc, sidecarTableIDMin, sidecarTableIDMax); err != nil { + return fmt.Errorf("release VRF table for vpc %s: %w", vpc, err) + } + return nil + case err != nil: + return fmt.Errorf("resolve VRF table ID for vpc %s: %w", vpc, err) } // Torn down before the interface is removed below, while its ifindex can // still be resolved. if err := removeEgressDatapath(tableID); err != nil { return fmt.Errorf("detach eBPF egress datapath for vpc %s: %w", vpc, err) } - if err := vrf.Delete(vpc); err != nil { + if err := vrf.DeleteInRange(vpc, sidecarTableIDMin, sidecarTableIDMax); err != nil { return fmt.Errorf("delete VRF for vpc %s: %w", vpc, err) } return nil diff --git a/internal/installer/installer.go b/internal/installer/installer.go index 7cdff0d8a..943d42606 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -1393,10 +1393,12 @@ func reportEBPFHealth(st ebpfDatapathState, healthSrv *health.Server, lastHealth // worth logging. Split out of Run's select to keep it within the gocyclo // budget. func logEBPFVRFSweepResult(result gc.CleanupResult) { - if result.EBPFVRFEntriesRemoved > 0 || result.EBPFVRFEntriesRegistered > 0 || result.Errors > 0 { + if result.EBPFVRFEntriesRemoved > 0 || result.EBPFVRFEntriesRegistered > 0 || result.EBPFVRFEntriesRewritten > 0 || + result.VRFTableReservationsReleased > 0 || result.EgressRouteTablesRemoved > 0 || result.Errors > 0 { slog.Info("eBPF vrf_table GC sweep complete", "removed", result.EBPFVRFEntriesRemoved, "registered", result.EBPFVRFEntriesRegistered, - "errors", result.Errors) + "rewritten", result.EBPFVRFEntriesRewritten, "reservationsReleased", result.VRFTableReservationsReleased, + "egressTablesRemoved", result.EgressRouteTablesRemoved, "errors", result.Errors) } } diff --git a/internal/plumbing/vrf/reservation.go b/internal/plumbing/vrf/reservation.go new file mode 100644 index 000000000..d0a5d8bff --- /dev/null +++ b/internal/plumbing/vrf/reservation.go @@ -0,0 +1,270 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package vrf + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "log/slog" + "os" + "path/filepath" + "sort" +) + +// Table ID reservations keep a VPC's routing table ID stable on a node. +// +// State keyed by table ID outlives the VRF that owned it: vrf_table rows, +// egress_route_table rows, and galactic-router's cached table ID. Allocating +// only from live VRF links hands a freed ID to the next VPC created, which then +// inherits that state and receives the first VPC's traffic and routes (#1270). +// A reservation keeps the ID for its VRF until garbage collection has confirmed +// nothing still references it and released it, so a VRF recreated meanwhile +// gets its own ID back and no other VPC can be given it. +// +// Reservations are keyed by VRF interface name and are only meaningful inside +// the table ID range the caller allocates from. The host and the ingress +// sidecar allocate from disjoint ranges, so one VPC can hold a reservation in +// each without either seeing the other's. + +// reservationsFileName names the reservation file, kept beside the lock that +// serializes every change to it. +const reservationsFileName = "tables.json" + +// reservationsVersion is the file format version written to the file. +const reservationsVersion = 1 + +// reservationsDir is the directory holding the reservation file; a variable +// so unprivileged tests can use a temporary directory. +var reservationsDir = lockDir + +// listVRFLinksFn lists the VRF links in this network namespace; a variable so +// unprivileged tests can substitute fabricated links. +var listVRFLinksFn = ListVRFLinks + +// Reservation records the routing table ID reserved for the VRF interface +// Name on this node. +type Reservation struct { + Name string `json:"name"` + Table uint32 `json:"table"` +} + +type reservationFile struct { + Version int `json:"version"` + Tables []Reservation `json:"tables"` +} + +// ReservationsLocked returns the node's table ID reservations. The caller +// holds the lock (see Locked) when it acts on the result, so that no Add can +// change it meanwhile. +// +// A missing or unreadable file is rebuilt from the VRF links that exist, so a +// node upgraded from a version without reservations, or whose file was lost, +// still reserves the table of every VRF it has. +func ReservationsLocked() ([]Reservation, error) { + return loadReservations() +} + +// ReservedTables returns every reserved table ID. It does not take the lock: +// the file is replaced atomically, so it reads either the old or the new set. +// A sweep that removes state for unreserved tables reads it before and after +// its scan, so a table reserved during the scan is never treated as orphaned. +func ReservedTables() (map[uint32]struct{}, error) { + res, err := loadReservations() + if err != nil { + return nil, err + } + tables := make(map[uint32]struct{}, len(res)) + for _, r := range res { + tables[r.Table] = struct{}{} + } + return tables, nil +} + +// ReleaseLocked removes the reservation of table for the VRF interface name. +// The caller holds the lock (see Locked) and has confirmed that nothing on the +// node still references the table. Releasing a reservation that does not +// exist is not an error. +func ReleaseLocked(name string, table uint32) error { + res, err := loadReservations() + if err != nil { + return err + } + kept, changed := releaseTable(res, name, table) + if !changed { + return nil + } + return saveReservations(kept) +} + +// releaseNameLocked removes every reservation of the VRF interface name in +// [minID, maxID]. The caller holds the lock. +func releaseNameLocked(name string, minID, maxID uint32) error { + res, err := loadReservations() + if err != nil { + return err + } + kept := make([]Reservation, 0, len(res)) + for _, r := range res { + if r.Name == name && r.Table >= minID && r.Table <= maxID { + continue + } + kept = append(kept, r) + } + if len(kept) == len(res) { + return nil + } + return saveReservations(kept) +} + +// loadReservations reads the reservation file, rebuilding it from the VRF +// links that exist when it is missing or unreadable. A rebuilt set is not +// written back here; the next change writes it. +func loadReservations() ([]Reservation, error) { + path := filepath.Join(reservationsDir, reservationsFileName) + data, err := os.ReadFile(path) + switch { + case errors.Is(err, fs.ErrNotExist): + return seedReservations() + case err != nil: + return nil, fmt.Errorf("read VRF table reservations %q: %w", path, err) + } + var file reservationFile + if err := json.Unmarshal(data, &file); err != nil || file.Version != reservationsVersion { + slog.Warn("vrf: table ID reservations unreadable, rebuilding them from the VRFs on this node", + "path", path, "version", file.Version, "err", err) + return seedReservations() + } + return file.Tables, nil +} + +// seedReservations reserves the table of every VRF link that exists. +func seedReservations() ([]Reservation, error) { + links, err := listVRFLinksFn() + if err != nil { + return nil, fmt.Errorf("list VRF links to rebuild table ID reservations: %w", err) + } + res := make([]Reservation, 0, len(links)) + for _, l := range links { + res = append(res, Reservation{Name: l.Name, Table: l.Table}) + } + return res, nil +} + +// saveReservations writes res, replacing the file atomically so a reader +// without the lock never sees a partial write. +func saveReservations(res []Reservation) error { + if err := os.MkdirAll(reservationsDir, 0o700); err != nil { + return fmt.Errorf("create VRF table reservation dir %q: %w", reservationsDir, err) + } + sorted := append([]Reservation{}, res...) + sort.Slice(sorted, func(i, j int) bool { + if sorted[i].Table != sorted[j].Table { + return sorted[i].Table < sorted[j].Table + } + return sorted[i].Name < sorted[j].Name + }) + data, err := json.Marshal(reservationFile{Version: reservationsVersion, Tables: sorted}) + if err != nil { + return fmt.Errorf("encode VRF table reservations: %w", err) + } + + tmp, err := os.CreateTemp(reservationsDir, reservationsFileName+".*") + if err != nil { + return fmt.Errorf("write VRF table reservations: %w", err) + } + defer func() { _ = os.Remove(tmp.Name()) }() + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + return fmt.Errorf("write VRF table reservations: %w", err) + } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return fmt.Errorf("sync VRF table reservations: %w", err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("write VRF table reservations: %w", err) + } + path := filepath.Join(reservationsDir, reservationsFileName) + if err := os.Rename(tmp.Name(), path); err != nil { + return fmt.Errorf("replace VRF table reservations %q: %w", path, err) + } + return nil +} + +// reserveTable returns the table ID in [minID, maxID] for a new VRF named +// name, and res with that reservation recorded. live maps the table of every +// VRF link that exists to its name. +// +// name's own reservation in the range is reused unless another live VRF holds +// that table, which happens only when reservations were rebuilt after being +// lost. Otherwise the lowest ID that neither a live VRF nor any reservation +// holds is reserved. +func reserveTable(res []Reservation, live map[uint32]string, name string, minID, maxID uint32) ( + uint32, []Reservation, error, +) { + used := make(map[uint32]struct{}, len(res)+len(live)) + for table := range live { + used[table] = struct{}{} + } + kept := make([]Reservation, 0, len(res)+1) + for _, r := range res { + if r.Name == name && r.Table >= minID && r.Table <= maxID { + if owner, ok := live[r.Table]; !ok || owner == name { + return r.Table, res, nil + } + slog.Warn("vrf: reserved table ID is held by another VRF, allocating a new one", + "vrf", name, "table", r.Table, "holder", live[r.Table]) + continue + } + kept = append(kept, r) + used[r.Table] = struct{}{} + } + table, err := nextFreeTableID(used, minID, maxID) + if err != nil { + return 0, res, err + } + return table, append(kept, Reservation{Name: name, Table: table}), nil +} + +// recordTable returns res with table recorded as name's reservation, for a +// VRF that already exists, and whether that changed res. The live link is the +// truth: name's other reservations in [minID, maxID], and any other name's +// reservation of table, are dropped. +func recordTable(res []Reservation, name string, table, minID, maxID uint32) ([]Reservation, bool) { + kept := make([]Reservation, 0, len(res)+1) + found, changed := false, false + for _, r := range res { + switch { + case r.Name == name && r.Table == table: + found = true + kept = append(kept, r) + case r.Name == name && r.Table >= minID && r.Table <= maxID, + r.Name != name && r.Table == table: + changed = true + default: + kept = append(kept, r) + } + } + if !found { + kept = append(kept, Reservation{Name: name, Table: table}) + changed = true + } + return kept, changed +} + +// releaseTable returns res without name's reservation of table, and whether +// it held one. +func releaseTable(res []Reservation, name string, table uint32) ([]Reservation, bool) { + kept := make([]Reservation, 0, len(res)) + for _, r := range res { + if r.Name == name && r.Table == table { + continue + } + kept = append(kept, r) + } + return kept, len(kept) != len(res) +} diff --git a/internal/plumbing/vrf/reservation_test.go b/internal/plumbing/vrf/reservation_test.go new file mode 100644 index 000000000..3af0d2215 --- /dev/null +++ b/internal/plumbing/vrf/reservation_test.go @@ -0,0 +1,288 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package vrf + +import ( + "os" + "path/filepath" + "reflect" + "sort" + "testing" + + "github.com/vishvananda/netlink" +) + +// These tests guard issue #1270: a VRF recreated on a node took the lowest +// free table ID, so its old ID went to the next VPC created, which inherited +// the vrf_table, egress_route_table and galactic-router state still keyed by +// it. + +// useReservationsDir points the reservation file at a temporary directory and +// the link listing at links, for the duration of t. +func useReservationsDir(t *testing.T, links ...*netlink.Vrf) string { + t.Helper() + dir := t.TempDir() + origDir, origList := reservationsDir, listVRFLinksFn + t.Cleanup(func() { reservationsDir, listVRFLinksFn = origDir, origList }) + reservationsDir = dir + listVRFLinksFn = func() ([]*netlink.Vrf, error) { return links, nil } + return dir +} + +func vrfLink(name string, table uint32) *netlink.Vrf { + return &netlink.Vrf{LinkAttrs: netlink.LinkAttrs{Name: name}, Table: table} +} + +func sortedReservations(res []Reservation) []Reservation { + out := append([]Reservation(nil), res...) + sort.Slice(out, func(i, j int) bool { return out[i].Table < out[j].Table }) + return out +} + +func TestReserveTable(t *testing.T) { + cases := []struct { + name string + res []Reservation + live map[uint32]string + vrf string + min, max uint32 + wantTable uint32 + wantRes []Reservation + }{ + { + name: "a recreated VRF gets its reserved table back", + res: []Reservation{{Name: "GA", Table: 1}, {Name: "GB", Table: 2}}, + live: map[uint32]string{2: "GB"}, + vrf: "GA", min: 1, max: 100, + wantTable: 1, + wantRes: []Reservation{{Name: "GA", Table: 1}, {Name: "GB", Table: 2}}, + }, + { + name: "a new VRF never takes a table another VRF has reserved", + res: []Reservation{{Name: "GA", Table: 1}}, + live: map[uint32]string{}, + vrf: "GB", min: 1, max: 100, + wantTable: 2, + wantRes: []Reservation{{Name: "GA", Table: 1}, {Name: "GB", Table: 2}}, + }, + { + name: "a new VRF skips live tables as well as reserved ones", + res: []Reservation{{Name: "GA", Table: 2}}, + live: map[uint32]string{1: "GX"}, + vrf: "GB", min: 1, max: 100, + wantTable: 3, + wantRes: []Reservation{{Name: "GA", Table: 2}, {Name: "GB", Table: 3}}, + }, + { + name: "a reserved table another live VRF holds is given up", + res: []Reservation{{Name: "GA", Table: 1}}, + live: map[uint32]string{1: "GX"}, + vrf: "GA", min: 1, max: 100, + wantTable: 2, + wantRes: []Reservation{{Name: "GA", Table: 2}}, + }, + { + name: "a reservation in another range is neither reused nor in the way", + res: []Reservation{{Name: "GA", Table: SidecarTableIDBase + 1}}, + live: map[uint32]string{}, + vrf: "GA", min: HostTableIDMin, max: HostTableIDMax, + wantTable: 1, + wantRes: []Reservation{{Name: "GA", Table: 1}, {Name: "GA", Table: SidecarTableIDBase + 1}}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + table, res, err := reserveTable(tc.res, tc.live, tc.vrf, tc.min, tc.max) + if err != nil { + t.Fatalf("reserveTable() error = %v", err) + } + if table != tc.wantTable { + t.Errorf("table = %d, want %d", table, tc.wantTable) + } + if got, want := sortedReservations(res), sortedReservations(tc.wantRes); !reflect.DeepEqual(got, want) { + t.Errorf("reservations = %v, want %v", got, want) + } + }) + } +} + +func TestReserveTable_FullRange(t *testing.T) { + res := []Reservation{{Name: "GA", Table: 10}} + if _, _, err := reserveTable(res, map[uint32]string{11: "GB"}, "GC", 10, 11); err == nil { + t.Fatal("reserveTable() error = nil, want an error with every table reserved or live") + } +} + +func TestRecordTable(t *testing.T) { + cases := []struct { + name string + res []Reservation + wantRes []Reservation + wantChanged bool + }{ + { + name: "already recorded", + res: []Reservation{{Name: "GA", Table: 5}}, + wantRes: []Reservation{{Name: "GA", Table: 5}}, + wantChanged: false, + }, + { + name: "unrecorded VRF from before reservations", + res: nil, + wantRes: []Reservation{{Name: "GA", Table: 5}}, + wantChanged: true, + }, + { + name: "the live link replaces a different reservation of its own", + res: []Reservation{{Name: "GA", Table: 3}}, + wantRes: []Reservation{{Name: "GA", Table: 5}}, + wantChanged: true, + }, + { + name: "the live link takes its table from another VRF's reservation", + res: []Reservation{{Name: "GB", Table: 5}}, + wantRes: []Reservation{{Name: "GA", Table: 5}}, + wantChanged: true, + }, + { + name: "a reservation in another range is kept", + res: []Reservation{{Name: "GA", Table: SidecarTableIDBase + 1}}, + wantRes: []Reservation{{Name: "GA", Table: 5}, {Name: "GA", Table: SidecarTableIDBase + 1}}, + wantChanged: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + res, changed := recordTable(tc.res, "GA", 5, HostTableIDMin, HostTableIDMax) + if changed != tc.wantChanged { + t.Errorf("changed = %v, want %v", changed, tc.wantChanged) + } + if got, want := sortedReservations(res), sortedReservations(tc.wantRes); !reflect.DeepEqual(got, want) { + t.Errorf("reservations = %v, want %v", got, want) + } + }) + } +} + +func TestReleaseLocked(t *testing.T) { + useReservationsDir(t) + if err := saveReservations([]Reservation{{Name: "GA", Table: 1}, {Name: "GB", Table: 2}}); err != nil { + t.Fatalf("saveReservations() error = %v", err) + } + + // A name and table that do not match one reservation release nothing. + if err := ReleaseLocked("GA", 2); err != nil { + t.Fatalf("ReleaseLocked(GA, 2) error = %v", err) + } + if err := ReleaseLocked("GA", 1); err != nil { + t.Fatalf("ReleaseLocked(GA, 1) error = %v", err) + } + got, err := ReservationsLocked() + if err != nil { + t.Fatalf("ReservationsLocked() error = %v", err) + } + if want := []Reservation{{Name: "GB", Table: 2}}; !reflect.DeepEqual(got, want) { + t.Errorf("reservations = %v, want %v", got, want) + } + + // Once released, the table is free for another VRF. + table, _, err := reserveTable(got, map[uint32]string{}, "GC", 1, 100) + if err != nil || table != 1 { + t.Errorf("reserveTable() = %d, %v; want 1, nil", table, err) + } +} + +func TestLoadReservations_RebuildsFromLiveVRFs(t *testing.T) { + want := []Reservation{{Name: "GA", Table: 4}, {Name: "GB", Table: 9}} + + t.Run("missing file", func(t *testing.T) { + useReservationsDir(t, vrfLink("GA", 4), vrfLink("GB", 9)) + got, err := loadReservations() + if err != nil { + t.Fatalf("loadReservations() error = %v", err) + } + if !reflect.DeepEqual(sortedReservations(got), want) { + t.Errorf("reservations = %v, want %v", got, want) + } + }) + + t.Run("corrupt file", func(t *testing.T) { + dir := useReservationsDir(t, vrfLink("GA", 4), vrfLink("GB", 9)) + if err := os.WriteFile(filepath.Join(dir, reservationsFileName), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + got, err := loadReservations() + if err != nil { + t.Fatalf("loadReservations() error = %v", err) + } + if !reflect.DeepEqual(sortedReservations(got), want) { + t.Errorf("reservations = %v, want %v", got, want) + } + }) + + t.Run("unknown version", func(t *testing.T) { + dir := useReservationsDir(t, vrfLink("GA", 4), vrfLink("GB", 9)) + data := []byte(`{"version":99,"tables":[{"name":"GZ","table":1}]}`) + if err := os.WriteFile(filepath.Join(dir, reservationsFileName), data, 0o600); err != nil { + t.Fatal(err) + } + got, err := loadReservations() + if err != nil { + t.Fatalf("loadReservations() error = %v", err) + } + if !reflect.DeepEqual(sortedReservations(got), want) { + t.Errorf("reservations = %v, want %v", got, want) + } + }) +} + +func TestSaveReservations_RoundTrip(t *testing.T) { + dir := useReservationsDir(t) + in := []Reservation{{Name: "GB", Table: 7}, {Name: "GA", Table: 3}} + if err := saveReservations(in); err != nil { + t.Fatalf("saveReservations() error = %v", err) + } + got, err := loadReservations() + if err != nil { + t.Fatalf("loadReservations() error = %v", err) + } + if want := []Reservation{{Name: "GA", Table: 3}, {Name: "GB", Table: 7}}; !reflect.DeepEqual(got, want) { + t.Errorf("reservations = %v, want %v", got, want) + } + tables, err := ReservedTables() + if err != nil { + t.Fatalf("ReservedTables() error = %v", err) + } + if want := map[uint32]struct{}{3: {}, 7: {}}; !reflect.DeepEqual(tables, want) { + t.Errorf("ReservedTables() = %v, want %v", tables, want) + } + + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != reservationsFileName { + t.Errorf("directory holds %v, want only %s: a temporary file was left behind", entries, reservationsFileName) + } +} + +func TestReleaseNameLocked_OnlyInRange(t *testing.T) { + useReservationsDir(t) + sidecar := SidecarTableIDBase + 1 + in := []Reservation{{Name: "GA", Table: 3}, {Name: "GA", Table: sidecar}, {Name: "GB", Table: sidecar + 1}} + if err := saveReservations(in); err != nil { + t.Fatalf("saveReservations() error = %v", err) + } + if err := releaseNameLocked("GA", SidecarTableIDBase, SidecarTableIDBase+0xFFF); err != nil { + t.Fatalf("releaseNameLocked() error = %v", err) + } + got, err := ReservationsLocked() + if err != nil { + t.Fatalf("ReservationsLocked() error = %v", err) + } + if want := []Reservation{{Name: "GA", Table: 3}, {Name: "GB", Table: sidecar + 1}}; !reflect.DeepEqual(got, want) { + t.Errorf("reservations = %v, want %v: only GA's reservation in the sidecar range goes", got, want) + } +} diff --git a/internal/plumbing/vrf/vrf.go b/internal/plumbing/vrf/vrf.go index 8d2204f42..1d41adce0 100644 --- a/internal/plumbing/vrf/vrf.go +++ b/internal/plumbing/vrf/vrf.go @@ -11,6 +11,7 @@ package vrf import ( "errors" "fmt" + "log/slog" "net" "sync" @@ -73,9 +74,11 @@ var ErrInUse = errors.New("vrf: a link is still enslaved to the VRF") // (see Locked). var vrfMu sync.Mutex -// Add creates the Linux VRF interface for a base62-encoded VPC, allocating the -// next available routing table ID in [HostTableIDMin, HostTableIDMax] and -// applying the required sysctls. +// Add creates the Linux VRF interface for a base62-encoded VPC, with a routing +// table ID in [HostTableIDMin, HostTableIDMax], and applies the required +// sysctls. The ID is the VPC's reserved one when it has a reservation on this +// node, and otherwise the lowest that no VRF and no reservation holds (see +// Reservation). // // The VRF is shared by every attachment on this VPC on this node, so concurrent // calls, from goroutines here or from separate plugin processes attaching @@ -152,10 +155,17 @@ func addLocked(vpc string, minID, maxID uint32) (*netlink.Vrf, error) { return nil, fmt.Errorf("VRF %q has table %d, not in [%d,%d]: %w", name, existing.Table, minID, maxID, ErrTableOutOfRange) } + // Record the table this VRF holds, so a VRF created before + // reservations existed keeps its table if it is ever recreated. A + // failure here does not fail an ADD onto a VRF that works. + if err := recordExistingTable(name, existing.Table, minID, maxID); err != nil { + slog.Warn("vrf: could not record existing VRF's table ID reservation", + "vrf", name, "table", existing.Table, "err", err) + } return existing, ensureUnreachableDefaults(existing.Table) } - vrfID, err := findNextAvailableVRFID(minID, maxID) + vrfID, err := reserveVRFTable(name, minID, maxID) if err != nil { return nil, err } @@ -240,24 +250,43 @@ func ensureUnreachableDefaults(tableID uint32) error { // every link in the VRF. Anything deleting a VRF in the host namespace, where // CNI ADDs enslave links concurrently, uses DeleteIfUnused instead. func Delete(vpc string) error { + return DeleteInRange(vpc, HostTableIDMin, HostTableIDMax) +} + +// DeleteInRange is Delete for a VRF whose table was allocated from [minID, +// maxID], as AddInRange does. Its table ID reservation in that range is +// released whether or not the VRF still exists: the caller owns every link in +// this namespace's VRF and removes the state keyed by its table itself, so the +// table is released here rather than quarantined for garbage collection, and +// a retry after a failed release still releases it. +func DeleteInRange(vpc string, minID, maxID uint32) error { return Locked(func() error { name := intf.GenerateInterfaceNameVRF(vpc) + // Only a VRF known to be gone releases its table: one a failed + // listing could not see may still route through it. vrfID, err := getVRFIDForInterface(name) - if err != nil { - return nil // VRF already gone — idempotent - } - - if err := FlushTable(vrfID); err != nil { + switch { + case errors.Is(err, ErrNotFound): + case err != nil: return err + default: + if err := FlushTable(vrfID); err != nil { + return err + } + link, err := netlink.LinkByName(name) + var notFound netlink.LinkNotFoundError + switch { + case errors.As(err, ¬Found): + case err != nil: + return err + default: + if err := netlink.LinkDel(link); err != nil { + return err + } + } } - - link, err := netlink.LinkByName(name) - if err != nil { - return nil // interface already gone — idempotent - } - - return netlink.LinkDel(link) + return releaseNameLocked(name, minID, maxID) }) } @@ -388,17 +417,46 @@ func listVRFLinks() ([]*netlink.Vrf, error) { return ListVRFLinks() } -func findNextAvailableVRFID(minID, maxID uint32) (uint32, error) { - vrfs, err := listVRFLinks() +// recordExistingTable records table as the reservation of the existing VRF +// named name, writing the file only when that changes it (see recordTable). +// Called with the lock held. +func recordExistingTable(name string, table, minID, maxID uint32) error { + res, err := loadReservations() if err != nil { - return 0, err + return err + } + res, changed := recordTable(res, name, table, minID, maxID) + if !changed { + return nil } + return saveReservations(res) +} - used := make(map[uint32]struct{}, len(vrfs)) +// reserveVRFTable reserves the table ID in [minID, maxID] for a new VRF named +// name, which is name's own earlier reservation when it has one (see +// reserveTable). The reservation is saved before the caller creates the VRF, +// so a VRF never exists without one. Called with the lock held. +func reserveVRFTable(name string, minID, maxID uint32) (uint32, error) { + vrfs, err := listVRFLinksFn() + if err != nil { + return 0, err + } + live := make(map[uint32]string, len(vrfs)) for _, vrf := range vrfs { - used[vrf.Table] = struct{}{} + live[vrf.Table] = vrf.Name + } + res, err := loadReservations() + if err != nil { + return 0, err + } + table, res, err := reserveTable(res, live, name, minID, maxID) + if err != nil { + return 0, err + } + if err := saveReservations(res); err != nil { + return 0, err } - return nextFreeTableID(used, minID, maxID) + return table, nil } // nextFreeTableID returns the lowest table ID in [minID, maxID] that is From ee08af3efca238c6286f38aa04909187c14fee1f Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Fri, 30 Oct 2026 00:04:01 -0400 Subject: [PATCH 2/2] fix(router): Move a VRF's routes when its kernel table changes applyVRFs resolved a VRF's kernel table once and reused it for as long as the VRF stayed desired. A VRF deleted and recreated on another table kept receiving its remote EVPN routes in the old table, which the node could give to another VPC, until galactic-router restarted. A CNI ADD did not correct it. applyVRFs now re-reads the table of every applied VRF on each reconcile, from one VRF listing. When the table changed, the VRF is applied again, the route-target index moves to the new table, and the routes of its best paths are withdrawn from the old table. Each is removed only while it still points at the SID that path names, so an entry another writer has since put in that table stays. A VRF that is only absent, a failed lookup or a failed listing keeps the current table. Withdrawing routes then would only cut the VRF's traffic, and an absent VRF's table stays reserved for it on the node. Related to #1270 --- docs/router/architecture.md | 1 + internal/plumbing/srv6/egress.go | 21 +++ internal/runtime/gobgp/monitor.go | 90 +++++++--- internal/runtime/gobgp/runtime.go | 37 ++++ internal/runtime/gobgp/vrf_status_test.go | 8 +- internal/runtime/gobgp/vrfmove.go | 94 ++++++++++ internal/runtime/gobgp/vrfmove_test.go | 204 ++++++++++++++++++++++ 7 files changed, 430 insertions(+), 25 deletions(-) create mode 100644 internal/runtime/gobgp/vrfmove.go create mode 100644 internal/runtime/gobgp/vrfmove_test.go diff --git a/docs/router/architecture.md b/docs/router/architecture.md index 4ca9d8080..0146ade67 100644 --- a/docs/router/architecture.md +++ b/docs/router/architecture.md @@ -118,6 +118,7 @@ there instead. - **Peer FSM transitions are logged by a dedicated GoBGP event watcher, which also drives real-time BGPPeer Kubernetes Events.** GoBGP's own logger writes through the process's `slog` default under logger `gobgp` (`internal/runtime/gobgp/server.go`'s `buildServerOptions`), at the binary's `--log-level`. On top of it, `internal/runtime/gobgp/peer_monitor.go` runs a shared `BgpServer.WatchEvent(..., WatchPeer())` goroutine (the same one-goroutine-per-runtime pattern `monitor.go`'s `watchEVPNRIB` uses for EVPN best-path) that diffs each peer's FSM state against `lastPeerState` and logs a `slog.Info` line on every real transition, including `disconnectReason`/`disconnectMessage` when a peer drops out of Established. The same transition is also handed to an optional `model.PeerStateObserver` (set via `gobgp.NewRuntimeFactory`'s `observer` parameter): in production this is `internal/controller/peer_events.go`'s `PeerStateEventEmitter`, a `manager.Runnable` that resolves the peer's address to its `BGPPeer` object and raises a `SessionEstablished`/`SessionDown` Kubernetes Event on it — but only for transitions into/out of Established, not every intermediate FSM hop (see the emitter's own doc comments for why). This is independent of, and does not replace, the periodic (`peerStatusRequeue`, 30s) `BGPPeer.Status` update in `internal/controller/bgprouter_controller.go`'s `updatePeerStatuses`: that keeps the CRD's status current on a poll and can miss a transition that reverts between two polls; the `slog` line and the Event are both real-time and don't have that gap. See `docs/plans/router-bgp-peer-session-events.md` for the full design. - **Routes for route-target-less EVPN paths defer to the underlay.** A path with no route target (the gateway's anycast VIPs, and each egress shard's SID `/64` and masquerade address) becomes a plain kernel route toward its BGP next hop, with no encapsulation. These routes live in their own table, `srv6.PlainRouteTable` (`0xFFFE0000`), marked `proto 250`, and are reached through two policy rules ahead of the main table's own: `32000: lookup main suppress_prefixlength 0`, then `32001: lookup 0xFFFE0000`. An underlay route for the same destination, or for anything more specific than the default route, therefore always wins. Keeping them out of the main table is required, not cosmetic: zebra imports every main-table route it did not install as a `kernel` route with distance 0, so a plain route there stopped FRR installing its own BGP route for the same prefix (#670). The kernel cannot resolve an IPv6 next hop recursively, so each route is written with the link and next hop the gateway resolves to at the time. `internal/runtime/gobgp/plainroutes.go` re-resolves every route whenever the main table changes and every 30s, and retries one that cannot resolve yet. It removes owned routes no path asks for once a two-minute startup grace has passed, and deletes the unmarked main-table route an earlier version left for each prefix. `ip route show table all proto 250` lists every route it owns. XDP datapaths that call `bpf_fib_lookup` with `BPF_FIB_LOOKUP_DIRECT` (`natprog`, `edgeprog`) read the main table only and do not see these routes. - **A tenant VRF route that fails to install is retried, not dropped.** `processEVPNPath` writes a VRF-scoped path's route into `egress_route_table` through `internal/runtime/gobgp/vrfroutes.go`. `Register` resolves the SID's uplink and neighbor MAC at write time, which fails while an uplink is still coming up after a restart, and BGP never redelivers an unchanged best path, so before #676 such a route stayed missing until the path changed upstream. `vrfRoutes` keeps each failed route in a pending set and retries it whenever the main table changes (1s debounce) and every 30s, until it installs or its path is withdrawn; removing a VRF drops its pending routes. One mutex serializes every write to the map from this runtime, taken per route during a retry so an unresolvable neighbor (up to 2s) does not hold up the RIB watcher for the whole pass. `EgressRouteTable.Refresh` cannot cover this: it walks existing entries only. The pending count, and the plain-route reconciler's failing count, are exported as `galactic_router_route_install_failing{kind="vrf"|"plain"}`, and `GalacticRouterRoutesNotInstalled` fires when either stays above 0 for 10 minutes. +- **A VRF's routes follow its kernel table.** `applyVRFs` re-reads the table of every VRF it has applied on each reconcile, from one VRF listing. When the kernel VRF was recreated on another table, the VRF is applied again, the route-target index moves to the new table, and `withdrawMovedVRFRoutes` removes the routes of the VRF's best paths from the old table, deleting only entries that still point at the SID each path names (#1270). A VRF that is absent, or a listing that fails, keeps the table it has. A VPC's table normally survives recreation through its node reservation; see [VRF table IDs](../cni/architecture.md#vrf-table-ids). - **`ServiceVIPBinding`s are generated, one per node per backend.** `NetworkServiceBindingReconciler` (`internal/controller/networkservice_binding_controller.go`) runs on every node and writes a binding for each VIP of each accepted `NetworkService`, at most one per family (`ruleTranslatedVIPs`) and, for the IPv4 VIP, only while some gateway node's `/IPv4Served` condition reports it loaded (`ipv4LoadedOnSomeNode`; a status change to that signal passes `ruleBindingInputsChanged`, and the node deletes its IPv4 bindings once no gateway does), and each backend the rule's `backendSelector` places on this node, through the same `selectRuleBackends` the gateway uses, so the gateway never sends a backend's flows to a node with no binding planned for it. Workloads are IPv6 only, so both VIPs' backends are the selected attachments' IPv6 addresses: an IPv4 VIP's binding pairs the IPv4 `vipAddress` with an IPv6 `backendAddress`, which the backend node serves by translating the flows (see [ARCHITECTURE-CNI.md](../cni/architecture.md#key-design-decisions)). `ServiceVIPBindingReconciler` refuses an IPv4 `backendAddress` with `BindFailed`. Each node writes and deletes only its own bindings (labelled `galactic.datum.net/binding-node` and `app.kubernetes.io/managed-by: galactic-router`), so there is one writer per object and no leader election. A binding is owned by its rule, records the rule's `vpcRef` (which names the VRF its rows go in) and takes `egressKind` from the attachment's interface mode. `ServiceVIPBindingReconciler` programs a binding only when a `BGPAdvertisement` on this node's `BGPRouter` with that VRF's ID has a prefix containing `backendAddress`, and otherwise reports `BindFailed`; it watches advertisements on its own router so a binding written before its advertisement converges, and teardown skips the check. A backend serves only the oldest rule (by creation time, then namespace/name) selecting it on the same backend port and protocol, since its node translates the backend's replies back to only one VIP; a claim (`backendClaim`) carries the VIP's family, since a reply to an IPv4 client takes the IPv4 VIP's egress-translated row and any other reply the IPv6 VIP's egress row, so one backend socket answers for one VIP of each family, an IPv4 rule never competes with an IPv6 one, and two rules with IPv4 VIPs on one socket do; both sides compute that owner with `ruleBackendOwners` over every rule in the namespace, so a newer rule gets no binding for the backend and no flows for it from the gateway, and every rule in a namespace is re-queued when one of them changes. Rules compete only within a VPC, so the per-VPC `VPCAttachment` fan-out still reaches every rule an attachment change can affect. The node summarizes its bindings on the rule as `/BackendsBound` (`BackendsClaimed` names a backend an older rule serves); a rule whose spec cannot be built into bindings (a second IPv6 VIP, or a selector that does not parse) keeps the node's existing bindings, the same as a rule that loses `Accepted`, so an invalid edit does not drop the backend nodes' `vip_xlat_table` rows; a second IPv4 VIP does the same for the IPv4 family alone, writing no IPv4 binding and keeping the IPv4 ones it had while the IPv6 VIP's bindings stay current, and both report `InvalidRule`. Only the nodes that hold bindings for such a rule report `InvalidRule`, since the gateways already report the error and a condition from every node would be a status write per node per edit. Each rule reconcile lists only its own VPC's attachments, through the VPCAttachment→`status.vpc` field index (`listVPCAttachmentsInVPC`), and skips the cache's deep copy because nothing it does writes to them. Several backends of one VIP can share a node: the gateway writes each backend's slot into the uSID and `usid.c` keys the ingress row on it (#799). - **Each node probes its own backends and publishes their health.** For a `NetworkService` with `spec.healthCheck`, `BackendHealthReconciler` (`internal/controller/backendhealth_controller.go`) runs one TCP probe loop per backend on its node (`internal/healthprobe`), over the backend's host-side interface (the attachment's `status.hostInterface`) from that interface's link-local address, on `healthCheck.port` or the rule's `backendPort`. The link-local source is what lets the SYN-ACK back: `usid_egress` hands a reply to a link-local destination to the kernel before its VIP rewrite (see [ARCHITECTURE-CNI.md](../cni/architecture.md#key-design-decisions)). A decision moves after `unhealthyThreshold` consecutive failures or `healthyThreshold` consecutive successes; a probe that cannot be sent (no interface, no link-local address) counts toward `Unknown`/`ProbeUnavailable`, never toward `Unhealthy`. The decision goes into `status.health` of each of the backend's bindings, with the attachment UID and probed port, by a merge patch of that field alone and only when it changes, so it never races the `Bound` condition. Every binding of one backend shares one loop. A restarted router seeds each loop from the published decision when its attachment UID and port still match, so a restart changes no gateway's table. A rule losing its `healthCheck` clears `status.health` and stops the loops. The design is [docs/gateway/backend-health.md](../gateway/backend-health.md). - **A `Spread` service endpoint's producers are probed by their own node, and a consumer's route reads a producer set.** `ServiceProducerHealthReconciler` (`internal/controller/serviceproducerhealth_controller.go`) runs one `internal/healthprobe` loop per producer on its node of each `ServiceEndpoint` with `spec.distribution: Spread`, to the producer attachment's first IPv6 address on `healthCheck.port`, and server-side applies that node's `ServiceEndpointProducerReport` for the endpoint (at most 16 entries, owned by the endpoint) under its own field manager (`galactic-router/`), so no object grows with the number of nodes. It deletes its report when it has no producers left, deletes reports of other nodes not renewed for 10 minutes, and removes its own entries from the endpoint's `status.producers`, where routers that predate reports write. Each node renews its entries every 15 seconds (`renewTime`); an entry not renewed for 60 seconds is expired, drains nothing, and ranks a remote producer after every currently reported one (`serviceroute.ProducerReportCurrent`). `ServiceRoutePolicyReconciler` requeues for the next expiry and ignores report and endpoint updates that only renew current entries. `ServiceRoutePolicyReconciler` reads them, through `serviceroute.WithProducerReports`, which keeps, for each producer and node, the more recently renewed of its report entry and its `status.producers` entry: for a Spread endpoint, `serviceroute.Compile` emits one `LocalSet` intent per consumer holding every producer on the consumer's node, `Unhealthy` ones marked draining unless all are. `EBPFRouteProgrammer` writes it as a mode-3 `service_route_table` row plus a `service_producer_set_table` row under the same key; `usid_egress` pins each TCP flow in `service_flow_table` and picks a producer per UDP datagram (see [docs/router/private-service-routes.md](../private-services/README.md#several-producers-on-one-node)). A changed `LocalSet` intent is applied before the old one is removed, and the programmer keeps the newest of a key's producer sets in the map, so a health or membership change never drops the consumer's route. A datapath without the producer set map gets `serviceroute.ErrProducerSetsUnavailable` for `LocalSet` intents only. diff --git a/internal/plumbing/srv6/egress.go b/internal/plumbing/srv6/egress.go index 1d5b5f759..1e980f65a 100644 --- a/internal/plumbing/srv6/egress.go +++ b/internal/plumbing/srv6/egress.go @@ -71,6 +71,27 @@ func RouteEgressDel(prefix *net.IPNet, tableID uint32) error { return table.UnregisterUnlessPassThroughAs(tableID, prefix, egressroutemap.PassThroughEdge) } +// RouteEgressDelIfSID is RouteEgressDel for an entry that still encapsulates +// toward sid, and leaves any other entry for prefix in tableID alone. A caller +// removing routes from a table it no longer owns uses it, so that an entry +// another writer has since installed there is kept. The entry is read just +// before it is deleted, as the map offers no compare-and-delete. +func RouteEgressDelIfSID(prefix *net.IPNet, tableID uint32, sid net.IP) error { + if sid == nil || sid.IsUnspecified() { + return nil // no SID was ever installed toward, so no entry is this caller's + } + table, closer, err := egressroutemap.OpenPinnedEgressRouteTable(pinDir) + if err != nil { + return fmt.Errorf("srv6: RouteEgressDelIfSID: %w", err) + } + defer closer.Close() //nolint:errcheck // best-effort close of our own fd, immediately after use + current, ok, err := table.Lookup(tableID, prefix) + if err != nil || !ok || !current.Equal(sid) { + return err + } + return table.UnregisterUnlessPassThroughAs(tableID, prefix, egressroutemap.PassThroughEdge) +} + // EgressDefaultRouteAdd installs egress_route_table's default (::/0) entry for // Linux VRF table tableID, encapsulating toward the first usable address in // shardSIDs. It gives a tenant VRF a route out for any destination with no diff --git a/internal/runtime/gobgp/monitor.go b/internal/runtime/gobgp/monitor.go index fadc872fa..e23507e55 100644 --- a/internal/runtime/gobgp/monitor.go +++ b/internal/runtime/gobgp/monitor.go @@ -38,11 +38,13 @@ var pinDir = attach.PinDir var errVRFNotInThisNetns = errors.New("kernel VRF interface is not in this process's network namespace") // resolveVRFTable and probeVRFDatapath are the kernel-facing steps applyVRFs -// runs for a VRF not yet applied. Package vars so tests can make them fail +// runs for a VRF not yet applied, and snapshotVRFTables the listing it +// re-checks applied VRFs against. Package vars so tests can make them fail // and then succeed without real VRF devices or bpffs. var ( - resolveVRFTable = vrfTableID - probeVRFDatapath = probeEgressRouteWrite + resolveVRFTable = vrfTableID + probeVRFDatapath = probeEgressRouteWrite + snapshotVRFTables = vrfTableSnapshot ) // startRIBMonitor starts the shared EVPN best-path watcher goroutine, once per @@ -166,20 +168,7 @@ func (r *GoBGPRuntime) processEVPNPath(path *apiutil.Path, logPrefix string) { return } - // The destination SID travels in the BGP Prefix-SID attribute, not the EVPN - // route's Gateway IP field. That field cannot carry an IPv6 SID for an IPv4 - // prefix, since RFC 9136 requires the Gateway IP and Prefix to share an - // address family, so reading it installs a garbage segment for every IPv4 - // VPC prefix. Fall back to the transit next hop for non-SRv6 - // advertisements, which carry no Prefix-SID. - gw, ok := evpnPrefixSID(path.Attrs) - if !ok { - if nh := evpnMpReachNexthop(path.Attrs); nh != "" { - if addr, err := netip.ParseAddr(nh); err == nil { - gw = addrToNetIP(addr) - } - } - } + gw := evpnGateway(path.Attrs) slog.Info(logPrefix+": installing route", "prefix", prefix, "gw", gw, "table", tableID, "plain", install.plain) if install.plain { @@ -192,6 +181,26 @@ func (r *GoBGPRuntime) processEVPNPath(path *apiutil.Path, logPrefix string) { r.vrf.install(vrfRouteKey{tableID: tableID, prefix: routePrefix}, gw) } +// evpnGateway returns the SID an EVPN Type 5 path's route encapsulates toward. +// +// The destination SID travels in the BGP Prefix-SID attribute, not the EVPN +// route's Gateway IP field. That field cannot carry an IPv6 SID for an IPv4 +// prefix, since RFC 9136 requires the Gateway IP and Prefix to share an +// address family, so reading it installs a garbage segment for every IPv4 +// VPC prefix. Fall back to the transit next hop for non-SRv6 +// advertisements, which carry no Prefix-SID. +func evpnGateway(attrs []bgp.PathAttributeInterface) net.IP { + gw, ok := evpnPrefixSID(attrs) + if !ok { + if nh := evpnMpReachNexthop(attrs); nh != "" { + if addr, err := netip.ParseAddr(nh); err == nil { + gw = addrToNetIP(addr) + } + } + } + return gw +} + // routeInstall is matchTableID's result: which kernel table the route belongs // in, and which installer to use. plain selects an ordinary next-hop route for // a path with no route target, owned by the plain-route reconciler, which @@ -269,13 +278,9 @@ func (r *GoBGPRuntime) matchTableID(attrs []bgp.PathAttributeInterface) (routeIn // sidecar itself, and Envoy only connects to backends those slices published, // so there is nothing for this process to add. func vrfTableID(vrfName string) (uint32, error) { - parts := strings.SplitN(vrfName, "-", 2) - if len(parts) != 2 { - return 0, fmt.Errorf("VRF name %q does not contain '-'", vrfName) - } - vpc, err := intf.HexToBase62(parts[0]) + vpc, err := vrfVPC(vrfName) if err != nil { - return 0, fmt.Errorf("VRF name %q: could not decode VPC segment %q back to base62: %w", vrfName, parts[0], err) + return 0, err } tableID, err := vrfpkg.TableID(vpc) @@ -288,6 +293,45 @@ func vrfTableID(vrfName string) (uint32, error) { return tableID, nil } +// vrfVPC returns the base62 VPC of a VRF named "{vpc}-{node}"; see +// vrfTableID. +func vrfVPC(vrfName string) (string, error) { + parts := strings.SplitN(vrfName, "-", 2) + if len(parts) != 2 { + return "", fmt.Errorf("VRF name %q does not contain '-'", vrfName) + } + vpc, err := intf.HexToBase62(parts[0]) + if err != nil { + return "", fmt.Errorf("VRF name %q: could not decode VPC segment %q back to base62: %w", vrfName, parts[0], err) + } + return vpc, nil +} + +// vrfTableSnapshot lists this namespace's VRFs once and returns a resolver +// that answers as vrfTableID does from that listing, so applyVRFs re-checks +// every applied VRF for the cost of one link dump. +func vrfTableSnapshot() (func(vrfName string) (uint32, error), error) { + links, err := vrfpkg.ListVRFLinks() + if err != nil { + return nil, err + } + tables := make(map[string]uint32, len(links)) + for _, l := range links { + tables[l.Name] = l.Table + } + return func(vrfName string) (uint32, error) { + vpc, err := vrfVPC(vrfName) + if err != nil { + return 0, err + } + table, ok := tables[intf.GenerateInterfaceNameVRF(vpc)] + if !ok { + return 0, fmt.Errorf("VRF %q: %w", vrfName, errVRFNotInThisNetns) + } + return table, nil + }, nil +} + // evpnMpReachNexthop returns the MpReachNLRI next-hop address from attrs, or "" // when none is found. It identifies locally-originated paths, and serves as the // gateway for a path carrying no Prefix-SID attribute. diff --git a/internal/runtime/gobgp/runtime.go b/internal/runtime/gobgp/runtime.go index 808c337c6..6b390ed02 100644 --- a/internal/runtime/gobgp/runtime.go +++ b/internal/runtime/gobgp/runtime.go @@ -404,12 +404,43 @@ func (r *GoBGPRuntime) applyVRFs( rtIndex := make(map[string]uint32, len(vrfs)) needsBackfill := false + var moved []movedVRFTable + + // The kernel VRF can be deleted and recreated, on a different table, + // while it stays desired. Its remote routes must follow it rather than + // keep installing into the old table, which another VPC can be given + // (#1270). One VRF listing per reconcile serves every applied VRF. + var currentTable func(string) (uint32, error) + if len(r.appliedVRFs) > 0 { + snapshot, err := snapshotVRFTables() + if err != nil { + slog.Warn("applyVRFs: could not list kernel VRFs, keeping every applied VRF's table", "err", err) + } + currentTable = snapshot + } + for _, v := range vrfs { if err := applyVRF(ctx, b, &v, routerID); err != nil { return fmt.Errorf("apply VRF %s: %w", v.Name, err) } tableID, ok := r.appliedVRFs[v.Name] + if ok && currentTable != nil { + // Only a different table moves the VRF. One that is momentarily + // absent keeps its table, which its reservation keeps from any + // other VPC, and comes back on the same one; withdrawing its + // routes meanwhile would only cut its traffic. + if current, err := currentTable(v.Name); err == nil && current != tableID { + slog.Warn("applyVRFs: VRF's kernel table changed, moving its routes", + "vrf", v.Name, "from", tableID, "to", current) + moved = append(moved, movedVRFTable{ + name: v.Name, tableID: tableID, + importRTs: append([]string(nil), r.appliedVRFImportRTs[v.Name]...), + }) + delete(r.appliedVRFs, v.Name) + ok = false + } + } if !ok { var st model.VRFStatus tableID, st = resolveVRF(v.Name) @@ -439,6 +470,12 @@ func (r *GoBGPRuntime) applyVRFs( r.rtIndex = rtIndex r.rtIndexMu.Unlock() + // Only once the index no longer names a moved VRF's old table, so the + // watcher installs nothing new there. + for _, m := range moved { + r.withdrawMovedVRFRoutes(b, m) + } + // A newly registered VRF's targets, or a changed set on an existing one, may // match paths that were already best path before the index held that // target. The shared watcher replays the RIB only once, at its own startup, diff --git a/internal/runtime/gobgp/vrf_status_test.go b/internal/runtime/gobgp/vrf_status_test.go index 7a594835b..5ba837ddc 100644 --- a/internal/runtime/gobgp/vrf_status_test.go +++ b/internal/runtime/gobgp/vrf_status_test.go @@ -29,8 +29,12 @@ var testVRFRuntimeKey = types.NamespacedName{Namespace: "vrf-status", Name: "r1" // repeating. func stubVRFKernel(t *testing.T, resolve []error, probe []error) { t.Helper() - origResolve, origProbe := resolveVRFTable, probeVRFDatapath - t.Cleanup(func() { resolveVRFTable, probeVRFDatapath = origResolve, origProbe }) + origResolve, origProbe, origSnapshot := resolveVRFTable, probeVRFDatapath, snapshotVRFTables + t.Cleanup(func() { resolveVRFTable, probeVRFDatapath, snapshotVRFTables = origResolve, origProbe, origSnapshot }) + // The re-check of applied VRFs answers from the same stubbed resolver. + snapshotVRFTables = func() (func(string) (uint32, error), error) { + return func(name string) (uint32, error) { return resolveVRFTable(name) }, nil + } next := func(errs []error, i *int) error { if len(errs) == 0 { diff --git a/internal/runtime/gobgp/vrfmove.go b/internal/runtime/gobgp/vrfmove.go new file mode 100644 index 000000000..3fdfc1fd3 --- /dev/null +++ b/internal/runtime/gobgp/vrfmove.go @@ -0,0 +1,94 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gobgp + +import ( + "log/slog" + + api "github.com/osrg/gobgp/v4/api" + "github.com/osrg/gobgp/v4/pkg/apiutil" + bgp "github.com/osrg/gobgp/v4/pkg/packet/bgp" + gobgpserver "github.com/osrg/gobgp/v4/pkg/server" + + "go.datum.net/galactic/internal/plumbing/srv6" +) + +// movedVRFTable is a VRF whose kernel table changed while it stayed desired: +// the table its routes were installed in, and the import route targets that +// selected them. +type movedVRFTable struct { + name string + tableID uint32 + importRTs []string +} + +// vrfRouteDelIfSID removes a tenant route only while it still encapsulates +// toward the given SID; a package var so tests can drive it without a pinned +// egress_route_table. +var vrfRouteDelIfSID = srv6.RouteEgressDelIfSID + +// withdrawMovedVRFRoutes removes the routes this runtime installed in m's old +// table: those of every remote best path carrying one of m's import route +// targets. Each is removed only while it still encapsulates toward that path's +// SID, so an entry another writer has since put in the table, such as another +// VPC given the same table ID, is kept. Retries pending for the old table are +// dropped. +func (r *GoBGPRuntime) withdrawMovedVRFRoutes(b *gobgpserver.BgpServer, m movedVRFTable) { + if r.vrf != nil { + r.vrf.forgetTable(m.tableID) + } + rts := make(map[string]struct{}, len(m.importRTs)) + for _, rt := range m.importRTs { + rts[rt] = struct{}{} + } + var withdrawn int + err := b.ListPath(apiutil.ListPathRequest{ + TableType: api.TableType_TABLE_TYPE_GLOBAL, + Family: bgp.RF_EVPN, + }, func(_ bgp.NLRI, paths []*apiutil.Path) { + for _, path := range paths { + if !path.Best || evpnMpReachNexthop(path.Attrs) == r.localAddress || !hasRouteTarget(path.Attrs, rts) { + continue + } + evpnNLRI, ok := path.Nlri.(*bgp.EVPNNLRI) + if !ok { + continue + } + ipPrefix, ok := evpnNLRI.RouteTypeData.(*bgp.EVPNIPPrefixRoute) + if !ok { + continue + } + prefix := addrToIPNet(ipPrefix.IPPrefix, int(ipPrefix.IPPrefixLength)) + if err := vrfRouteDelIfSID(prefix, m.tableID, evpnGateway(path.Attrs)); err != nil { + slog.Error("withdrawMovedVRFRoutes: route delete failed", + "vrf", m.name, "prefix", prefix, "table", m.tableID, "err", err) + continue + } + withdrawn++ + } + }) + if err != nil { + slog.Error("withdrawMovedVRFRoutes: ListPath failed", "vrf", m.name, "err", err) + return + } + slog.Info("withdrawMovedVRFRoutes: removed routes from the VRF's old table", + "vrf", m.name, "table", m.tableID, "routes", withdrawn) +} + +// hasRouteTarget reports whether attrs carry any route target in rts. +func hasRouteTarget(attrs []bgp.PathAttributeInterface, rts map[string]struct{}) bool { + for _, attr := range attrs { + ec, ok := attr.(*bgp.PathAttributeExtendedCommunities) + if !ok { + continue + } + for _, community := range ec.Value { + if _, ok := rts[community.String()]; ok { + return true + } + } + } + return false +} diff --git a/internal/runtime/gobgp/vrfmove_test.go b/internal/runtime/gobgp/vrfmove_test.go new file mode 100644 index 000000000..8c58f5a44 --- /dev/null +++ b/internal/runtime/gobgp/vrfmove_test.go @@ -0,0 +1,204 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package gobgp + +import ( + "context" + "errors" + "fmt" + "net" + "net/netip" + "testing" + + "go.datum.net/galactic/internal/model" +) + +// These tests guard issue #1270: applyVRFs resolved a VRF's kernel table once +// and reused it while the VRF stayed desired, so a VRF recreated on another +// table kept receiving its remote routes in the old one, which the node could +// give to another VPC. + +const ( + movedRoutePrefix = "2001:db8:100::/64" + movedRouteSID = "2001:db8:f00:1::" +) + +// stubVRFTable makes resolveVRFTable report *table, or err when *err is set, +// for the duration of t. +func stubVRFTable(t *testing.T, table *uint32, err *error) { + t.Helper() + stubVRFKernel(t, nil, nil) + resolveVRFTable = func(string) (uint32, error) { + if *err != nil { + return 0, *err + } + return *table, nil + } +} + +// stubDelIfSID routes vrfRouteDelIfSID to f, removing an entry only while it +// still names sid. +func stubDelIfSID(t *testing.T, f *fakeEgressTable) { + t.Helper() + prev := vrfRouteDelIfSID + t.Cleanup(func() { vrfRouteDelIfSID = prev }) + vrfRouteDelIfSID = func(prefix *net.IPNet, tableID uint32, sid net.IP) error { + f.mu.Lock() + defer f.mu.Unlock() + key := vrfRouteKey{tableID: tableID, prefix: mustPrefixFromIPNet(t, prefix)} + if f.entries[key] == sid.String() { + delete(f.entries, key) + } + return nil + } +} + +func movedKey(table uint32) vrfRouteKey { + return vrfRouteKey{tableID: table, prefix: netip.MustParsePrefix(movedRoutePrefix)} +} + +func (f *fakeEgressTable) put(table uint32, prefix, gw string) { + f.mu.Lock() + defer f.mu.Unlock() + f.entries[vrfRouteKey{tableID: table, prefix: netip.MustParsePrefix(prefix)}] = gw +} + +func remoteVRFAdvertisement() model.DesiredAdvertisement { + return model.DesiredAdvertisement{ + Name: "remote-vpc-prefix", + AddressFamily: model.AddressFamily{AFI: afiL2VPN, SAFI: safiEVPN}, + Prefixes: []string{movedRoutePrefix}, + Communities: []string{testRT100}, + NextHop: testPeerAddr, + SRv6SID: movedRouteSID, + } +} + +// TestApplyVRFsFollowsRecreatedVRFTable recreates a VRF on another table while +// it stays desired, and checks that the router moves to the new table: the +// cache, the route-target index and the installed route, which leaves the old +// table. +func TestApplyVRFsFollowsRecreatedVRFTable(t *testing.T) { + table, resolveErr := uint32(7), error(nil) + stubVRFTable(t, &table, &resolveErr) + f := newFakeEgressTable(t) + f.setUsable(net.ParseIP(movedRouteSID)) + stubDelIfSID(t, f) + + r := newTestVRFRuntime(t) + b := newTestBgpServer(t) + ctx := context.Background() + if err := buildEVPNPaths(b, remoteVRFAdvertisement(), "192.0.2.1", false); err != nil { + t.Fatalf("buildEVPNPaths() error = %v", err) + } + + if err := r.applyVRFs(ctx, b, testVRFs(), testRouterID1); err != nil { + t.Fatalf("first applyVRFs() error = %v", err) + } + if gw, ok := f.entry(movedKey(7)); !ok || gw != movedRouteSID { + t.Fatalf("route in table 7 = %q, %v; want %s installed by the first apply", gw, ok, movedRouteSID) + } + + table = 9 // the kernel VRF was deleted and recreated on table 9 + if err := r.applyVRFs(ctx, b, testVRFs(), testRouterID1); err != nil { + t.Fatalf("second applyVRFs() error = %v", err) + } + if got := r.appliedVRFs[testVRFName]; got != 9 { + t.Errorf("appliedVRFs[%s] = %d, want 9", testVRFName, got) + } + if got := r.rtIndex[testRT100]; got != 9 { + t.Errorf("rtIndex[%s] = %d, want 9", testRT100, got) + } + if gw, ok := f.entry(movedKey(9)); !ok || gw != movedRouteSID { + t.Errorf("route in table 9 = %q, %v; want %s", gw, ok, movedRouteSID) + } + if gw, ok := f.entry(movedKey(7)); ok { + t.Errorf("route in table 7 = %q, want it withdrawn from the VRF's old table", gw) + } +} + +// TestApplyVRFsKeepsAnotherWritersRouteInOldTable checks that moving a VRF off +// a table leaves an entry there that no longer names the moved VRF's SID, as +// when another VPC has since been given the table. +func TestApplyVRFsKeepsAnotherWritersRouteInOldTable(t *testing.T) { + table, resolveErr := uint32(7), error(nil) + stubVRFTable(t, &table, &resolveErr) + f := newFakeEgressTable(t) + f.setUsable(net.ParseIP(movedRouteSID)) + stubDelIfSID(t, f) + + r := newTestVRFRuntime(t) + b := newTestBgpServer(t) + ctx := context.Background() + if err := buildEVPNPaths(b, remoteVRFAdvertisement(), "192.0.2.1", false); err != nil { + t.Fatalf("buildEVPNPaths() error = %v", err) + } + if err := r.applyVRFs(ctx, b, testVRFs(), testRouterID1); err != nil { + t.Fatalf("first applyVRFs() error = %v", err) + } + + const otherSID = "2001:db8:f00:2::" + f.put(7, movedRoutePrefix, otherSID) + table = 9 + if err := r.applyVRFs(ctx, b, testVRFs(), testRouterID1); err != nil { + t.Fatalf("second applyVRFs() error = %v", err) + } + if gw, ok := f.entry(movedKey(7)); !ok || gw != otherSID { + t.Errorf("route in table 7 = %q, %v; want the other writer's %s kept", gw, ok, otherSID) + } +} + +// TestApplyVRFsKeepsTableUnlessItChanged checks that an applied VRF keeps its +// table, its route-target index entry and its routes when the re-check does +// not show a different table: the VRF is momentarily absent, a lookup fails, +// or the VRF listing itself fails. Withdrawing routes then would only cut the +// VRF's traffic; an absent VRF's table stays reserved for it. +func TestApplyVRFsKeepsTableUnlessItChanged(t *testing.T) { + cases := []struct { + name string + resolveErr error + snapshotErr error + }{ + {name: "VRF momentarily absent", resolveErr: fmt.Errorf("VRF %q: %w", testVRFName, errVRFNotInThisNetns)}, + {name: "lookup fails", resolveErr: errors.New("netlink: interrupted dump")}, + {name: "VRF listing fails", snapshotErr: errors.New("netlink: interrupted dump")}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + table, resolveErr := uint32(7), error(nil) + stubVRFTable(t, &table, &resolveErr) + f := newFakeEgressTable(t) + f.setUsable(net.ParseIP(movedRouteSID)) + stubDelIfSID(t, f) + + r := newTestVRFRuntime(t) + b := newTestBgpServer(t) + ctx := context.Background() + if err := buildEVPNPaths(b, remoteVRFAdvertisement(), "192.0.2.1", false); err != nil { + t.Fatalf("buildEVPNPaths() error = %v", err) + } + if err := r.applyVRFs(ctx, b, testVRFs(), testRouterID1); err != nil { + t.Fatalf("first applyVRFs() error = %v", err) + } + + resolveErr = tc.resolveErr + if tc.snapshotErr != nil { + snapshotVRFTables = func() (func(string) (uint32, error), error) { return nil, tc.snapshotErr } + } + if err := r.applyVRFs(ctx, b, testVRFs(), testRouterID1); err != nil { + t.Fatalf("second applyVRFs() error = %v", err) + } + if got := r.appliedVRFs[testVRFName]; got != 7 { + t.Errorf("appliedVRFs[%s] = %d, want 7 kept", testVRFName, got) + } + if got := r.rtIndex[testRT100]; got != 7 { + t.Errorf("rtIndex[%s] = %d, want 7 kept", testRT100, got) + } + if gw, ok := f.entry(movedKey(7)); !ok || gw != movedRouteSID { + t.Errorf("route in table 7 = %q, %v; want it kept", gw, ok) + } + }) + } +}