diff --git a/docs/cni/architecture.md b/docs/cni/architecture.md index 88a90c227..6daea67c4 100644 --- a/docs/cni/architecture.md +++ b/docs/cni/architecture.md @@ -202,7 +202,7 @@ The [ADD and DEL sequences](cni-cmd-sequence.md) describe attachment; the [GC se - **A packet too big for the fabric gets an ICMP error from the datapath, not a silent drop at the uplink.** `usid_egress` calls `send_too_big` after the MSS clamp and before it encapsulates. A packet longer than `encap_mtu_table`'s limit (the uplink MTU less 40, so 1460 at a 1500-byte fabric) is rewritten in place into an ICMPv6 Packet Too Big, or an ICMPv4 Fragmentation Needed for an IPv4 tenant with DF set, and redirected back out the interface it arrived on. The error carries the limit, comes from the attachment's own IPAM gateway (`tenant_gw_table`, keyed by host-side ifindex and written by `galactic-bgp` at ADD, removed by `galactic-veth`/`galactic-tap` at DEL), and quotes the packet's first 68 bytes with NPTv6 undone, so the tenant's path MTU discovery matches it to the socket that sent it. A GSO packet is judged by its segment length. No error is sent for an IPv4 packet without DF, for an ICMP error, past a per-CPU token bucket of 1,000 a second with a burst of 100 (`pmtu_icmp_bucket`), or for an attachment with no gateway in that family; those are dropped and counted as `fib_frag_needed`. Each outcome is counted in `pmtu_stats`, exported as `galactic_usid_pmtu_packets_total{result}`, and the limit as `galactic_usid_pmtu_limit_bytes`. The same `mssclamp.Reconciler` writes `encap_mtu_table` and `mss_clamp_table` from one `GALACTIC_CNI_TCP_MSS_CLAMP` setting, so the two cannot disagree. A pod's or guest's TCP and UDP packets usually arrive `CHECKSUM_PARTIAL`, which no BPF helper can clear, and a device without checksum offload (a tap whose guest did not negotiate it) would finish that checksum into the middle of the error. So the error is laid out with room pushed at the front until the kernel's checksum spot (the original transport header plus 16 for TCP, 6 otherwise) lands on a trailing slot word, with a pad word chosen so the sum the kernel writes there equals what is already there. `usid_pmtu_tap_test.go` checks this against the kernel through a `virtio_net_hdr` tap, with offload on and off. - **Per-VRF traffic is counted in each direction in its own per-CPU map, not in `vrf_value`.** `vrf_traffic_counters` is a `BPF_MAP_TYPE_PERCPU_HASH` keyed like `vrf_table` (Block<<12|Argument, so one VPC per node) holding packets, tenant bytes and claimed drops for `ingress` and `egress`. Per CPU, because the hot path then increments its own copy with no atomic and no shared cache line; a new map, because changing `vrf_value`'s layout would make `attach.Load` recreate `vrf_table` empty. The datapath only looks rows up: `VRFTable.Register` creates a VRF's row with `BPF_NOEXIST`, so registering again never resets it, `Unregister` removes it, and `Reconcile` ends with `SyncTraffic`, which creates rows for VRFs that predate the map and removes orphans, re-checking `vrf_table` before each delete and again after it, so a VRF registered while it runs keeps its row. `galactic-cni run` also calls `SyncTraffic` once the datapath loads, so an upgraded node counts from its first packet rather than its first 5-minute GC sweep. Every writer of `vrf_table` rows (CNI ADD, the datapath repair, the GC sweep, the ingress sidecar) goes through `VRFTable`, so none needs code of its own. Inbound counts at `usid_ingress`'s two redirects (warm FIB and `bpf_redirect_neigh`). Outbound counts at `usid_egress`'s encapsulating redirect, which covers egress shards, and its VIP reply redirect, and at the service path's redirects, remote ones inside `service_remote_encap` because its caller cannot tell a forwarded packet from a Packet Too Big. Same-node traffic between two attachments never reaches `usid_ingress`: the sender's `usid_egress` matches the receiver's local pass-through entry and hands the packet to the kernel, so that hit counts once in each direction on the shared VPC row, except a destination equal to the sender's own `tenant_gw_table` gateway. Bytes are the tenant packet's own length in both directions, unlike `vrf_value.bytes`, which counts the whole frame at step 6 and stays for `galactic_usid_vrf_bytes_total` and make-before-break checks. Exported as `galactic_usid_vrf_{forwarded_packets,forwarded_bytes,dropped_packets}_total{direction}`; see [docs/metrics.md](../observability/vpc-dataplane.md#traffic). The gateway check reads the destination from `service_fib_scratch` itself rather than taking a pointer to it: passed a map-value pointer as a subprogram argument, `usid_egress`'s verifier cost went past the kernel's 1M-instruction limit. -- **An uplink that drops out of auto-detection keeps `usid_ingress` for 60 seconds.** `attach.Watch` re-resolves the uplink set on every netlink link or route event, and an uplink found only through BGP-learned routes leaves that set whenever FRR withdraws them, which it does for every restart (#778). Detaching on the first miss dropped SRv6 traffic still arriving on that uplink until FRR re-learned the routes. An attached interface whose link still exists now keeps its hook, and its place in the published uplink list, until it has been missing for `detachHoldDown`. Watch re-evaluates on its own when the hold-down ends, so an uplink that really stops carrying fabric routes is still detached. A deleted link is dropped at once. +- **An uplink that drops out of auto-detection keeps `usid_ingress` for 60 seconds.** `attach.Watch` re-resolves the uplink set on every netlink link or route event, and an uplink found only through BGP-learned routes leaves that set whenever FRR withdraws them, which it does for every restart (#778). Detaching on the first miss dropped SRv6 traffic still arriving on that uplink until FRR re-learned the routes. An attached interface whose link still exists now keeps its hook, and its place in the published uplink list, until it has been missing for `detachHoldDown`. Watch re-evaluates on its own when the hold-down ends, so an uplink that really stops carrying fabric routes is still detached. A deleted link is dropped at once. A held uplink also stays a valid egress link: `attach.UplinkIndexes` accepts the attached set as well as the resolved one, so an egress shard routed over it is not marked dead while its routes are reinstalled (#1570). When the last uplink loses its routes, so that auto-detection finds none at all, the attached set goes through the same hold-down and is detached when it ends. - **CRD-driven config, no sidecar gRPC.** `galactic-bgp` writes `BGPVRFInstance`/`BGPAdvertisement` CRDs directly via a bare controller-runtime client; `galactic-router`'s reconciler picks them up. No in-node gRPC calls between any of the CNI-chain binaries and `galactic-router`. - **DEL is intentionally minimal everywhere in the CNI chain; GC reclaims shared state asynchronously.** Every binary's own `cmdDel` only cleans up what it itself created *and* is safe to release immediately per-container: IPAM deallocation via `galactic-ipam`'s own on-disk marker file; guest-netns flush/host-device DEL in `galactic-veth`; and, in both `galactic-veth`/`galactic-tap`, deleting this attachment's own host/guest veth pair or tap device outright, since that interface is private to one attachment and no sibling pod/VM can ever depend on it. `galactic-bgp` removes its container's entries from this node's `BGPAdvertisement` and deletes it once no container it records is alive, so a replacement whose ADD ran first keeps it. None of them delete the VRF, routes, the eBPF `vrf_table` entry, or the `BGPVRFInstance` — those are keyed by `(vpc, node)` and shared by every attachment on the VPC and node. `galactic-router`'s GC controller (see [ARCHITECTURE-ROUTER.md](../router/architecture.md)) reclaims orphaned CRDs and stale kernel VRFs once no live container still references them; the installer separately sweeps stale eBPF VRF entries — see [docs/cni/gc-cmd-sequence.md](../cni/gc-cmd-sequence.md) for why the host veth/tap interface is reclaimed only with a dead attachment's `BGPAdvertisement`, when its DEL never removed it. - **A DSR backend's node translates the VIP, and its replies leave out the fabric uplink unencapsulated.** `galactic-gateway` carries a client's packet unmodified inside the outer IPv6 header, with Next Header 41 for an IPv6 client and 4 for an IPv4 one, to the backend node's End.DT46 uSID with the backend's slot in bits 81–96. Workloads are IPv6 only, so every backend is IPv6. For an IPv6 client, `usid_ingress` decapsulates the packet and, before the VRF FIB lookup, looks up `vip_xlat_table`'s ingress row by (Block, Argument, slot, protocol, destination address, destination port) and rewrites the destination to the backend's address and port, leaving the client's source alone. On the way back, `usid_egress` (TC ingress of the backend's host-side veth or tap, the same code for both kinds) looks up the egress row by the reply's source address and port, rewrites the source to the VIP, clamps a SYN-ACK's MSS to the IPv6 limit, and redirects the frame unencapsulated to the node's fabric uplink neighbor from `public_uplink_table`, skipping NPTv6 and `egress_route_table` entirely: that table's `::/0` and IPv4 entries would encapsulate the reply toward a NAT shard, which would translate an already correctly addressed reply. The reply is then ordinary routed traffic with the VIP as its source; where the compute node's uplink neighbor is an edge node, as in the containerlab topology, that node's `edge_return` forwards it because its source is in `vip_addr_table` (see [ARCHITECTURE-GATEWAY.md](../gateway/packet-paths.md#return-path-edgedsrc-program-edge_return)). Where the first public uplink's neighbor is the hosting provider's ToR/VRRP gateway, the reply goes straight to the provider and no edge forwards it; `edge_return` applies there only if that uplink loses its neighbor and the row falls back to an interface whose neighbor is an edge. An egress shard never claims it: `nat_ingress` takes only its own SID and masquerade addresses as destinations. Until `public_uplink_table` is written the reply falls through to the ordinary egress path. A packet to a multicast or link-local destination never takes this path: `usid_egress` hands it to the kernel before the VIP lookup and NPTv6, as well as `egress_route_table`, since a VIP's client is never link-local. A host-side TCP probe of the backend's bound port, sourced from the host interface's link-local address, gets its reply that way (see [the backend health design](../gateway/backend-health.md#reply-path)). The row holds one next hop, used for IPv4 frames too: the first resolved IPv6 neighbor of the first eBPF interface, in `attach.ResolveInterfaces` order, that has carrier (`srv6.ResolvePublicUplink`). Every reply from the node takes that uplink, whichever gateway node took the request, so on a compute node dual-homed to two edge nodes the row must follow the uplinks. `galactic-cni run` re-resolves it on every link change and IPv6 neighbor change (`installer.watchPublicUplink`, debounced 250 ms) and on every datapath repair pass (`attachreg.FillNode`), and rewrites it when it differs. A pass that resolves nothing keeps the row it has. `task verify:gateway-node-loss` in `deploy/containerlab/` takes one of `dfw-worker`'s two edge nodes off the fabric and checks the VIP still serves through the other. diff --git a/internal/plumbing/ebpf/attach/uplinks.go b/internal/plumbing/ebpf/attach/uplinks.go index 1c72af893..b6abbbbb5 100644 --- a/internal/plumbing/ebpf/attach/uplinks.go +++ b/internal/plumbing/ebpf/attach/uplinks.go @@ -6,6 +6,8 @@ package attach import ( "fmt" + "log/slog" + "slices" "sync" "time" ) @@ -29,8 +31,46 @@ var uplinkIndexCache struct { resolved time.Time } +// watchedUplinks is the attached set the running Watch loop last reconciled to, +// held interfaces included. Nil when no loop runs. Only one Watch loop may run +// per process. +var watchedUplinks struct { + mu sync.Mutex + names []string +} + +// setWatchedUplinks records names as the attached set and drops the cached +// ifindexes, so the next UplinkIndexes call sees the change. Nil clears it. +func setWatchedUplinks(names []string) { + watchedUplinks.mu.Lock() + if len(names) == 0 { + watchedUplinks.names = nil + } else { + watchedUplinks.names = slices.Clone(names) + } + watchedUplinks.mu.Unlock() + InvalidateUplinkIndexes() +} + +// watchedUplinkNames returns the attached set setWatchedUplinks last recorded. +func watchedUplinkNames() []string { + watchedUplinks.mu.Lock() + defer watchedUplinks.mu.Unlock() + return slices.Clone(watchedUplinks.names) +} + // UplinkIndexes returns the ifindexes of the interfaces the SRv6 datapath -// attaches to, the set ResolveInterfaces names. +// attaches to: the set ResolveInterfaces names, plus every interface the +// running Watch loop keeps attached through its detach hold-down. +// +// The hold-down exists because the underlay routing daemon withdraws an +// uplink's BGP routes while it restarts or reinstalls them, and that uplink +// drops out of ResolveInterfaces until they return. The datapath keeps +// forwarding through it meanwhile, so a route leaving through it is still +// good. Judging routes against ResolveInterfaces alone rejected every egress +// shard reached over that uplink for as long as it was missing, and emptied +// every egress shard group on the node. When resolution fails outright, the +// attached set alone is used, if there is one. // // It exists so a caller resolving where to send an encapsulated packet can // reject a route that leaves through some other interface. A node's management @@ -60,8 +100,19 @@ func UplinkIndexes() (map[int]struct{}, error) { } names, err := ResolveInterfaces() + watched := watchedUplinkNames() if err != nil { - return nil, fmt.Errorf("attach: resolve SRv6 uplink interfaces: %w", err) + if len(watched) == 0 { + return nil, fmt.Errorf("attach: resolve SRv6 uplink interfaces: %w", err) + } + slog.Warn("attach: could not resolve SRv6 uplink interfaces; judging egress routes against the attached set", + "attached", watched, "err", err) + names = nil + } + for _, name := range watched { + if !slices.Contains(names, name) { + names = append(names, name) + } } indexes := make(map[int]struct{}, len(names)) diff --git a/internal/plumbing/ebpf/attach/uplinks_test.go b/internal/plumbing/ebpf/attach/uplinks_test.go index 0776f7d24..5c2732522 100644 --- a/internal/plumbing/ebpf/attach/uplinks_test.go +++ b/internal/plumbing/ebpf/attach/uplinks_test.go @@ -134,6 +134,62 @@ func TestUplinkIndexesServesTheCacheUntilItExpires(t *testing.T) { } } +// recordWatchedUplinks records names as a running Watch loop's attached set +// for the length of the test. +func recordWatchedUplinks(t *testing.T, names ...string) { + t.Helper() + setWatchedUplinks(names) + t.Cleanup(func() { setWatchedUplinks(nil) }) +} + +// TestUplinkIndexesKeepsAHeldUplink reproduces #1570: an uplink the watch loop +// keeps attached through its hold-down, while its BGP routes are reinstalled, +// is missing from ResolveInterfaces. Every egress shard reached over it was +// rejected, and every shard group published with no alive member. +func TestUplinkIndexesKeepsAHeldUplink(t *testing.T) { + stubUplinkLinks(t, testIfaceEth1, map[string]int{testIfaceEth1: 1060, testIfaceEth2: 1061}) + recordWatchedUplinks(t, testIfaceEth1, testIfaceEth2) + + got, err := UplinkIndexes() + if err != nil { + t.Fatalf("UplinkIndexes() = %v, want success", err) + } + for _, want := range []int{1060, 1061} { + if _, ok := got[want]; !ok { + t.Errorf("UplinkIndexes() = %v, want it to contain ifindex %d", got, want) + } + } + + // Once no loop holds it, the resolved set alone decides again. + setWatchedUplinks(nil) + got, err = UplinkIndexes() + if err != nil { + t.Fatalf("UplinkIndexes() after the record cleared = %v, want success", err) + } + if _, ok := got[1061]; ok { + t.Errorf("UplinkIndexes() = %v, want ifindex 1061 gone once no watch loop holds it", got) + } +} + +// TestUplinkIndexesFallsBackToTheWatchedSet covers a resolution that fails +// outright while a watch loop runs: the attached set still names the links +// the datapath forwards on. +func TestUplinkIndexesFallsBackToTheWatchedSet(t *testing.T) { + stubUplinkLinks(t, " ", map[string]int{testIfaceEth1: 1060}) + if _, err := UplinkIndexes(); err == nil { + t.Fatal("UplinkIndexes() with a malformed override and no watch loop = nil error, want a failure") + } + + recordWatchedUplinks(t, testIfaceEth1) + got, err := UplinkIndexes() + if err != nil { + t.Fatalf("UplinkIndexes() = %v, want the watched set", err) + } + if _, ok := got[1060]; !ok || len(got) != 1 { + t.Errorf("UplinkIndexes() = %v, want only ifindex 1060", got) + } +} + func TestInvalidateUplinkIndexesForcesAFreshResolve(t *testing.T) { stubUplinkLinks(t, testIfaceEth1, map[string]int{testIfaceEth1: 1060}) diff --git a/internal/plumbing/ebpf/attach/watch.go b/internal/plumbing/ebpf/attach/watch.go index 1318c3d2b..795ec566b 100644 --- a/internal/plumbing/ebpf/attach/watch.go +++ b/internal/plumbing/ebpf/attach/watch.go @@ -214,7 +214,10 @@ func logDegradedSubscription(kind string, otherKindAlreadyNil bool) { // A per-interface attach or detach failure is logged and retried on the next // re-evaluation, for as long as the mismatch persists. A resolution failure is // likewise logged and skipped, leaving the previous attachment set in place -// rather than tearing anything down on a transient error. +// rather than tearing anything down on a transient error. ErrNoUplinkRoute is +// not one: it means no interface carries a default or fabric route, so it is +// reconciled as an empty set, and every attached interface goes through the +// hold-down and is detached once it ends. // // w, when non-nil, is marked alive while this loop runs, supplies the // out-of-band re-evaluation trigger, and receives the attached set, initial @@ -268,6 +271,10 @@ func Watch(ctx context.Context, program *ebpf.Program, initial []string, w *Watc current := toSet(initial) order := slices.Clone(initial) w.publish(initial) + // UplinkIndexes accepts what this loop keeps attached, held interfaces + // included, and only while it runs. + setWatchedUplinks(order) + defer setWatchedUplinks(nil) // missingSince records when each attached interface left the resolved set. missingSince := make(map[string]time.Time) @@ -343,7 +350,15 @@ func Watch(ctx context.Context, program *ebpf.Program, initial []string, w *Watc case <-debounceC: debounceC = nil next, err := resolveInterfacesFn() - if err != nil { + switch { + case errors.Is(err, ErrNoUplinkRoute): + // The last uplink lost its routes. Skipping this pass, as for a + // transient error, would keep every held interface attached, + // and accepted by UplinkIndexes, for good. + slog.Warn("attach: no interface carries an uplink route; holding the attached set until the hold-down ends", + "err", err) + next = nil + case err != nil: slog.Warn("attach: re-evaluate interface set failed, keeping previous attachment", "err", err) onReconcileDone() continue @@ -361,10 +376,11 @@ func Watch(ctx context.Context, program *ebpf.Program, initial []string, w *Watc w.publish(order) resetHoldTimer(expiry) // The uplink set just moved, or a link/route event says it may - // have. Drop the cached ifindexes so an egress route resolved - // right after an interface appears is judged against the new set - // rather than waiting out the TTL. - InvalidateUplinkIndexes() + // have. Record it, which also drops the cached ifindexes, so an + // egress route resolved right after an interface appears or is + // held is judged against the new set rather than waiting out the + // TTL. + setWatchedUplinks(order) onReconcileDone() } } diff --git a/internal/plumbing/ebpf/attach/watch_test.go b/internal/plumbing/ebpf/attach/watch_test.go index 337eebfe3..906899af2 100644 --- a/internal/plumbing/ebpf/attach/watch_test.go +++ b/internal/plumbing/ebpf/attach/watch_test.go @@ -11,6 +11,7 @@ import ( "os" "path/filepath" "reflect" + "slices" "sort" "sync" "testing" @@ -906,6 +907,133 @@ func TestWatch_HoldsFabricBondThroughRouteWithdrawal(t *testing.T) { } } +// TestWatch_HeldUplinkStaysAnEgressLink reproduces #1570 through the loop: while +// bond1 is held through a route withdrawal, UplinkIndexes still accepts it, +// though ResolveInterfaces no longer names it. Once the loop exits, it does +// not. +func TestWatch_HeldUplinkStaysAnEgressLink(t *testing.T) { + withWatchTestDefaults(t) + detachHoldDown = time.Minute + + // ResolveInterfaces, which UplinkIndexes calls directly, names only bond0, + // as it does while bond1's BGP routes are being reinstalled. + stubUplinkLinks(t, primaryUplink, map[string]int{primaryUplink: 1002, lateUplink: 1016}) + + trigger := make(chan struct{}, 1) + routeSubscribeFn = stubRouteSubscribe(trigger) + resolveInterfacesFn = func() ([]string, error) { return []string{primaryUplink}, nil } + reconcileFn = func(_ *ebpf.Program, _, next map[string]struct{}) map[string]struct{} { return next } + reconciled := make(chan struct{}, 1) + onReconcileDone = func() { reconciled <- struct{}{} } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- Watch(ctx, &ebpf.Program{}, []string{primaryUplink, lateUplink}, newWatcher()) }() + + trigger <- struct{}{} + select { + case <-reconciled: + case <-time.After(5 * time.Second): + t.Fatal("watch loop never re-evaluated") + } + + got, err := UplinkIndexes() + if err != nil { + t.Fatalf("UplinkIndexes() during the hold-down = %v, want success", err) + } + if _, ok := got[1016]; !ok { + t.Errorf("UplinkIndexes() during the hold-down = %v, want the held bond1 (ifindex 1016)", got) + } + + cancel() + if err := <-done; err != nil { + t.Fatalf("Watch: %v", err) + } + got, err = UplinkIndexes() + if err != nil { + t.Fatalf("UplinkIndexes() after the loop exited = %v, want success", err) + } + if _, ok := got[1016]; ok { + t.Errorf("UplinkIndexes() after the loop exited = %v, want bond1 gone", got) + } +} + +// TestWatch_LastUplinkMissingExpiresTheHold covers the last uplink losing its +// routes, so that ResolveInterfaces fails with ErrNoUplinkRoute. The attached +// set is held, and accepted by UplinkIndexes, only until the hold-down ends. +// Then it is detached and no longer accepted. +func TestWatch_LastUplinkMissingExpiresTheHold(t *testing.T) { + withWatchTestDefaults(t) + detachHoldDown = 100 * time.Millisecond + + // A malformed override makes ResolveInterfaces fail for UplinkIndexes, as + // it does once no interface carries an uplink route. + stubUplinkLinks(t, " ", map[string]int{primaryUplink: 1002, lateUplink: 1016}) + + trigger := make(chan struct{}, 1) + routeSubscribeFn = stubRouteSubscribe(trigger) + resolveInterfacesFn = func() ([]string, error) { return nil, ErrNoUplinkRoute } + var mu sync.Mutex + var detached []string + reconcileFn = func(_ *ebpf.Program, current, next map[string]struct{}) map[string]struct{} { + _, removed := diffSets(current, next) + mu.Lock() + detached = append(detached, removed...) + mu.Unlock() + return next + } + reconciled := make(chan struct{}, 4) + onReconcileDone = func() { reconciled <- struct{}{} } + wait := func() { + t.Helper() + select { + case <-reconciled: + case <-time.After(5 * time.Second): + t.Fatal("watch loop never re-evaluated") + } + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- Watch(ctx, &ebpf.Program{}, []string{primaryUplink, lateUplink}, newWatcher()) }() + + // Routes gone: both uplinks are held, still attached and still accepted. + trigger <- struct{}{} + wait() + mu.Lock() + if len(detached) != 0 { + t.Errorf("detached %v on the first miss, want both held", detached) + } + mu.Unlock() + got, err := UplinkIndexes() + if err != nil { + t.Fatalf("UplinkIndexes() during the hold-down = %v, want the held set", err) + } + if _, ok := got[1016]; !ok { + t.Errorf("UplinkIndexes() during the hold-down = %v, want the held bond1 (ifindex 1016)", got) + } + + // Still no route when the hold-down ends: both are detached, and nothing + // is accepted any more. + wait() + mu.Lock() + slices.Sort(detached) + if want := []string{primaryUplink, lateUplink}; !reflect.DeepEqual(detached, want) { + t.Errorf("detached %v after the hold-down, want %v", detached, want) + } + mu.Unlock() + if got, err := UplinkIndexes(); err == nil { + t.Errorf("UplinkIndexes() after the hold-down = %v, want a failure: no uplink is held or resolved", got) + } + + cancel() + if err := <-done; err != nil { + t.Fatalf("Watch: %v", err) + } +} + // TestWatch_DetachesWhenHoldDownEnds covers an uplink that really stops // carrying fabric routes: once the hold-down passes it is detached, with no // further netlink event to prompt the re-evaluation.