diff --git a/deploy/containerlab/scripts/verify-gateway-backend-health.sh b/deploy/containerlab/scripts/verify-gateway-backend-health.sh index e3efc15d0..4575cd8b8 100755 --- a/deploy/containerlab/scripts/verify-gateway-backend-health.sh +++ b/deploy/containerlab/scripts/verify-gateway-backend-health.sh @@ -190,16 +190,10 @@ flows_through() { } # mapping GATEWAY prints "port backend" for each fixed UDP source port -# through GATEWAY. One TCP request goes first: edge_lb drops a packet whose -# next hop has no neighbor entry yet (fib_no_neigh), and only TCP's -# retransmits ride that out, so on a path idle long enough for the entry to -# expire the first UDP probes would be lost for a reason this check does not -# test. +# through GATEWAY. mapping() { local p pin "$1" - pick_port - request tcp "${PORT_PICKED}" >/dev/null for p in "${PORTS[@]}"; do echo "${p} $(request udp "${p}")" done diff --git a/docs/agents/ARCHITECTURE-GATEWAY.md b/docs/agents/ARCHITECTURE-GATEWAY.md index 8a3971c6b..7e1a7abfb 100644 --- a/docs/agents/ARCHITECTURE-GATEWAY.md +++ b/docs/agents/ARCHITECTURE-GATEWAY.md @@ -456,7 +456,15 @@ forward half, so it has exactly one branch, not two. Replies are differ on every gateway that reaches its clients and its compute nodes over separate links, which is this role's normal shape — see [Known Constraints](#known-constraints) for the bug that came from returning - `XDP_TX` unconditionally. The inner packet travels completely unmodified — + `XDP_TX` unconditionally. A next hop with no neighbor entry, as after a + link flap or a node rejoining the fabric, sends the encapsulated packet to + the kernel with `XDP_PASS` instead, since XDP cannot start neighbor + resolution: the kernel solicits the neighbor and forwards the packet, and + later packets stay in XDP. Those packets are counted in `neigh_fallbacks` + (`galactic_edge_neigh_fallbacks_total`), not as drops. Unlike the XDP + path, they cross the node's netfilter FORWARD hook, as new flows from the + node's own encapsulation source, so a host firewall that drops forwarded + traffic drops them too. The inner packet travels completely unmodified — this is DSR's entire premise: no address or port rewriting and no checksum touch anywhere. diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index 9700ad71b..c741e95a7 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -1181,7 +1181,11 @@ Relevant series: `galactic_edge_rule_packets_total`, by `reason`; `ipv4_fragment` counts IPv4 fragments addressed to a VIP, which are dropped because a later fragment has no ports to pick a backend by; the drop applies to any TCP or UDP port on a VIP address, and it is not -counted in a VIP's own dropped packets because the port is unknown), and `galactic_edge_control_plane_drops_total` (rule +counted in a VIP's own dropped packets because the port is unknown), +`galactic_edge_neigh_fallbacks_total` (load-balanced packets handed to the +kernel because the next hop toward the backend had no neighbor entry, for it +to resolve the neighbor and forward them; not counted as drops), and +`galactic_edge_control_plane_drops_total` (rule applications rejected before ever reaching the datapath, e.g. quota denials). In dispatch mode, `galactic_edge_dispatch_lease_renewals_total` (labeled by `slot` and `result`) and diff --git a/docs/metrics.md b/docs/metrics.md index 16789c0f9..33b662176 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -633,6 +633,7 @@ so there is no connection table to report. See | `galactic_edge_return_bytes_total` | counter | same | Bytes of those replies | | `galactic_edge_return_dropped_packets_total` | counter | same | Replies sourced from the VIP that the datapath dropped. A subset of `return_packets_total` | | `galactic_edge_drops_total` | counter | `reason` | Packets `edge_lb` and `edge_return` dropped, by reason | +| `galactic_edge_neigh_fallbacks_total` | counter | none | Packets `edge_lb` handed to the kernel to resolve the next hop. Not counted as drops | | `galactic_edge_control_plane_drops_total` | counter | `rule`, `reason` (`quota_exceeded`) | Rule applications refused before they reached the datapath | | `galactic_edge_dispatch_lease_renewals_total` | counter | `slot`, `result` | Renewals of the gateway's XDP dispatcher slot leases. Dispatch mode only | | `galactic_edge_dispatch_lease_expiry_timestamp_seconds` | gauge | `slot` | Unix time each lease, as last renewed, expires. Dispatch mode only | @@ -650,6 +651,15 @@ so there is no connection table to report. See `fib_lookup_failed`, `adjust_head_failed`, `no_egress_ifindex`, `redirect_failed`, `return_hop_limit`, `icmp_rate_limited`, plus `unknown_` for an index the binary has no name for. +- `fib_no_neigh` counts only replies `edge_return` forwards and ICMP errors + the gateway sends. A load-balanced packet whose next hop has no neighbor + entry goes to the kernel, which resolves the neighbor and forwards it, and + is counted in `galactic_edge_neigh_fallbacks_total` instead. That counter + rises briefly after a link or node rejoins the fabric. Steady growth means + neighbor entries keep expiring or a next hop does not answer, and the + kernel drops what it cannot resolve. The counter records the handoff, not + delivery: these packets cross the node's netfilter FORWARD hook, unlike the + XDP path, so a host firewall that drops forwarded traffic drops them too. The port also serves controller-runtime's metrics for the `NetworkGateway`/`NetworkService` reconcilers. diff --git a/internal/plumbing/ebpf/edgemetrics/collector.go b/internal/plumbing/ebpf/edgemetrics/collector.go index 7d92127a9..72d74f20a 100644 --- a/internal/plumbing/ebpf/edgemetrics/collector.go +++ b/internal/plumbing/ebpf/edgemetrics/collector.go @@ -43,9 +43,10 @@ type VPCAttribution interface { // counters and drops by reason. There is no connection table here at all, direct // server return keeping no per-flow state to report. type Collector struct { - vipTable *edgemap.VIPTable - dropReasons DropReasonsReader - attribution VPCAttribution + vipTable *edgemap.VIPTable + dropReasons DropReasonsReader + neighFallbacks DropReasonsReader + attribution VPCAttribution } // NewCollector builds a Collector from already-constructed values, so tests can @@ -56,6 +57,13 @@ func NewCollector(vipTable *edgemap.VIPTable, dropReasons DropReasonsReader, att return &Collector{vipTable: vipTable, dropReasons: dropReasons, attribution: attribution} } +// WithNeighFallbacks adds the neigh_fallbacks map, a single-entry per-CPU +// array, as galactic_edge_neigh_fallbacks_total. +func (c *Collector) WithNeighFallbacks(m DropReasonsReader) *Collector { + c.neighFallbacks = m + return c +} + // NewCollectorFromObjects builds a Collector reading directly from a loaded // object set's maps. func NewCollectorFromObjects(objs *edgeprog.EdgedsrObjects, attribution VPCAttribution) *Collector { @@ -65,7 +73,7 @@ func NewCollectorFromObjects(objs *edgeprog.EdgedsrObjects, attribution VPCAttri edgemap.KernelTable{Map: objs.VipAddrTable}, edgemap.KernelTable{Map: objs.VipReturnStatsTable}), objs.DropReasons, attribution, - ) + ).WithNeighFallbacks(objs.NeighFallbacks) } const ( @@ -120,6 +128,15 @@ var ( "direction.", []string{"reason"}, nil, ) + neighFallbacksDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "", "neigh_fallbacks_total"), + "Encapsulated packets edge_lb handed to the kernel because the next hop toward the "+ + "backend had no neighbor entry, for the kernel to resolve the neighbor and forward them. "+ + "Counts the handoff, not delivery: the kernel drops what it cannot resolve, and these "+ + "packets cross the node's netfilter FORWARD hook, where a host firewall can drop them. "+ + "Not counted in drops_total.", + nil, nil, + ) returnPacketsDesc = prometheus.NewDesc( prometheus.BuildFQName(namespace, "return", "packets_total"), "Reply packets this node forwarded for traffic sourced from this VIP, bypassing the kernel "+ @@ -149,6 +166,7 @@ func (c *Collector) Describe(ch chan<- *prometheus.Desc) { ch <- ruleBackendsDesc ch <- ruleSecondsSinceLastPacketDesc ch <- dropsDesc + ch <- neighFallbacksDesc ch <- returnPacketsDesc ch <- returnBytesDesc ch <- returnDroppedDesc @@ -159,6 +177,7 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric) { c.collectRules(ch) c.collectReturn(ch) c.collectDrops(ch) + c.collectNeighFallbacks(ch) } // vpcs snapshots the attribution. Callers take it after listing a map: the @@ -257,3 +276,19 @@ func (c *Collector) collectDrops(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric(dropsDesc, prometheus.CounterValue, float64(total), name) } } + +func (c *Collector) collectNeighFallbacks(ch chan<- prometheus.Metric) { + if c.neighFallbacks == nil { + return + } + var perCPU []uint64 + if err := c.neighFallbacks.Lookup(uint32(0), &perCPU); err != nil { + ch <- prometheus.NewInvalidMetric(neighFallbacksDesc, fmt.Errorf("lookup neigh_fallbacks: %w", err)) + return + } + var total uint64 + for _, v := range perCPU { + total += v + } + ch <- prometheus.MustNewConstMetric(neighFallbacksDesc, prometheus.CounterValue, float64(total)) +} diff --git a/internal/plumbing/ebpf/edgemetrics/collector_test.go b/internal/plumbing/ebpf/edgemetrics/collector_test.go index 0a874537a..ab2b9e576 100644 --- a/internal/plumbing/ebpf/edgemetrics/collector_test.go +++ b/internal/plumbing/ebpf/edgemetrics/collector_test.go @@ -437,6 +437,22 @@ func TestCollector_CollectsDropsByReason(t *testing.T) { } } +// TestCollector_CollectsNeighFallbacks covers the packets edge_lb handed to the +// kernel for neighbor resolution, which are counted apart from every drop. +func TestCollector_CollectsNeighFallbacks(t *testing.T) { + vt := edgemap.NewVIPTable( + newFakeVIPTable(), newFakeStatsTable(), newFakeAddrTable(), newFakeReturnStatsTable()) + c := NewCollector(vt, fakeDropReasons{}, nil).WithNeighFallbacks(fakeDropReasons{0: 5}) + metrics := collect(t, c) + + if got := metricValue(findMetric(t, metrics, neighFallbacksDesc, "", "")); got != 5 { + t.Errorf("neigh_fallbacks_total = %v, want 5", got) + } + if got := metricValue(findMetric(t, metrics, dropsDesc, "reason", "fib_no_neigh")); got != 0 { + t.Errorf("drops_total{reason=fib_no_neigh} = %v, want 0", got) + } +} + // TestCollector_CollectsReturnCounters covers the return path's own counters. // They are keyed by VIP address alone, with no port or protocol, since // edge_return matches a reply on its source address -- so one series covers diff --git a/internal/plumbing/ebpf/edgeprog/edgedsr.c b/internal/plumbing/ebpf/edgeprog/edgedsr.c index f0b9de689..8fcf0ef0d 100644 --- a/internal/plumbing/ebpf/edgeprog/edgedsr.c +++ b/internal/plumbing/ebpf/edgeprog/edgedsr.c @@ -59,6 +59,9 @@ // ingress interface, bpf_redirect and XDP_REDIRECT where it is not. The // two differ on every gateway that reaches its clients and its compute // nodes over different links, which is this role's normal shape. +// Where the next hop has no neighbor entry, the encapsulated packet goes +// to the kernel instead, which resolves the neighbor and forwards it; +// see push_outer_header. // 7. A packet the route refuses for size, too big once the outer header is // on, is answered with an ICMPv6 Packet Too Big, or for an IPv4 packet // with Don't Fragment set an ICMPv4 Fragmentation Needed, to the client @@ -364,6 +367,16 @@ struct { __type(value, __u64); } drop_reasons SEC(".maps"); +// neigh_fallbacks counts the encapsulated packets edge_lb passed to the kernel +// because their next hop had no neighbor entry; see push_outer_header. They +// are not drops, so they have their own map rather than a drop_reasons bucket. +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, __u64); +} neigh_fallbacks SEC(".maps"); + // struct icmp_bucket is one CPU's token bucket, held as nanoseconds of credit // rather than whole tokens so a refill is an addition, with no division on the // packet path: each message costs EDGE_ICMP_COST_NS, and credit accrues one @@ -648,11 +661,31 @@ static EDGE_ALWAYS_INLINE long resolve_fib4_and_write_eth(void *ctx, __u32 ifind // // outer_payload_len is the whole inner packet's length, header included, and // nexthdr says what that packet is: EDGE_IPPROTO_IPV6 or EDGE_IPPROTO_IPIP. +// +// A next hop with no neighbor entry is not a failure. XDP has no way to start +// neighbor resolution, so a drop here repeats for every packet until something +// else resolves the neighbor, as after a link flap, a neighbor table purge or +// a gateway restart, for as long as the kernel takes to notice. The +// encapsulated packet goes to the kernel instead, framed as the original was +// so the stack takes it as addressed to this host: the kernel forwards it to +// the backend's uSID, queuing it while it solicits the neighbor, and every +// later packet finds the entry and stays in XDP. That case returns +// EDGE_PUSH_TO_KERNEL and is counted in neigh_fallbacks, not as a drop. +#define EDGE_PUSH_TO_KERNEL 1 + static EDGE_ALWAYS_INLINE int push_outer_header(struct xdp_md *ctx, const __u8 src[16], const __u8 dst[16], __be16 outer_payload_len, __u8 nexthdr, struct vip_stats_value *stats, __u32 *egress_ifindex, __u16 *frag_mtu) { + struct edge_ethhdr orig_eth; + void *orig = (void *) (long) ctx->data; + if (orig + sizeof(orig_eth) > (void *) (long) ctx->data_end) { + count_claimed_drop(DROP_REASON_ADJUST_HEAD_FAILED, stats); + return -1; + } + __builtin_memcpy(&orig_eth, orig, sizeof(orig_eth)); + if (bpf_xdp_adjust_head(ctx, -40) != 0) { count_claimed_drop(DROP_REASON_ADJUST_HEAD_FAILED, stats); return -1; @@ -685,6 +718,16 @@ static EDGE_ALWAYS_INLINE int push_outer_header(struct xdp_md *ctx, const __u8 s long fib_rc = resolve_fib_and_write_eth(ctx, ctx->ingress_ifindex, src, dst, (__u16) (sizeof(*outer) + __builtin_bswap16(outer_payload_len)), eth, egress_ifindex, frag_mtu); + if (fib_rc == BPF_FIB_LKUP_RET_NO_NEIGH) { + __builtin_memcpy(eth->h_dest, orig_eth.h_dest, sizeof(eth->h_dest)); + __builtin_memcpy(eth->h_source, orig_eth.h_source, sizeof(eth->h_source)); + eth->h_proto = __builtin_bswap16(EDGE_ETH_P_IPV6); + __u32 key = 0; + __u64 *counter = bpf_map_lookup_elem(&neigh_fallbacks, &key); + if (counter) + *counter += 1; + return EDGE_PUSH_TO_KERNEL; + } if (fib_rc != BPF_FIB_LKUP_RET_SUCCESS) { count_fib_drop(fib_rc, stats); return -1; @@ -944,8 +987,11 @@ static EDGE_ALWAYS_INLINE int lb_forward(struct xdp_md *ctx, struct vip_value *r // checksum touch, the client's packet travelling inside untouched to the // backend, which replies to the client directly. __u32 egress_ifindex = 0; - if (push_outer_header(ctx, cfg->encap_src, b->usid, outer_payload_len, nexthdr, stats, - &egress_ifindex, frag_mtu) != 0) + int pushed = push_outer_header(ctx, cfg->encap_src, b->usid, outer_payload_len, nexthdr, stats, + &egress_ifindex, frag_mtu); + if (pushed == EDGE_PUSH_TO_KERNEL) + return XDP_PASS; + if (pushed != 0) return -1; return leave_via(ctx, egress_ifindex, stats); } diff --git a/internal/plumbing/ebpf/edgeprog/edgedsr_neigh_test.go b/internal/plumbing/ebpf/edgeprog/edgedsr_neigh_test.go new file mode 100644 index 000000000..f6a88d2ce --- /dev/null +++ b/internal/plumbing/ebpf/edgeprog/edgedsr_neigh_test.go @@ -0,0 +1,398 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package edgeprog + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "net" + "net/netip" + "os" + "runtime" + "testing" + "time" + + "github.com/cilium/ebpf/link" + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" +) + +// These tests cover a backend whose route resolves to a next hop with no +// neighbor entry, as on a gateway that has just rejoined the fabric. XDP +// cannot start neighbor resolution, so edge_lb hands the encapsulated packet +// to the kernel instead of dropping it. + +// ipprotoIPv6Encap is the outer Next Header of an encapsulated IPv6 packet. +const ipprotoIPv6Encap = 41 + +var ( + // unresolvedLocal and unresolvedNextHop share the link the backend's + // uSID is routed over; the gateway holds no neighbor entry for the next + // hop. unresolvedLocal is also the gateway's encapsulation source. + unresolvedLocal = netip.MustParseAddr("fd00:5::1") + unresolvedNextHop = netip.MustParseAddr("fd00:5::2") +) + +// TestEdgeLB_UnresolvedNextHopGoesToKernel covers both VIP families through +// a test run: the packet leaves encapsulated, framed as it arrived, as +// XDP_PASS straight to the kernel rather than through the dispatcher's later +// slots, and counts as a fallback rather than a drop. +func TestEdgeLB_UnresolvedNextHopGoesToKernel(t *testing.T) { + for _, tt := range []struct { + name string + build func(t *testing.T, objs *EdgedsrObjects) (EdgedsrVipKey, []byte, int) + }{ + {name: "IPv6 VIP", build: func(t *testing.T, objs *EdgedsrObjects) (EdgedsrVipKey, []byte, int) { + vip := netip.MustParseAddr("2001:db8::100") + // putIPv4VIP loads a VIP of either family; only its name is IPv4. + key := putIPv4VIP(t, objs, ipprotoTCP, 443, vip, testUSID) + pkt := buildL4Packet(t, ipprotoTCP, vip, netip.MustParseAddr("2001:db8:ffff::1"), 41000, 443, nil) + return key, pkt, ipprotoIPv6Encap + }}, + {name: "IPv4 VIP", build: func(t *testing.T, objs *EdgedsrObjects) (EdgedsrVipKey, []byte, int) { + key := putIPv4VIP(t, objs, ipprotoTCP, 443, testVIP4, testUSID) + pkt := buildIPv4Packet(t, ipprotoTCP, testVIP4, testClient4, 41000, 443, nil, ip4Opts{}) + return key, pkt, ipprotoIPIP + }}, + } { + t.Run(tt.name, func(t *testing.T) { + requireRoot(t) + narrowFabric(t, fabricMTU) + routeViaUnresolvedNextHop(t, testUSID) + objs := loadObjects(t) + installChainStub(t, objs, roleGatewayLB|roleEgress) + key, pkt, nexthdr := tt.build(t, objs) + + ret, out := runLB(t, objs, pkt) + if ret != xdpPass { + t.Fatalf("verdict = %d, want XDP_PASS (%d)", ret, xdpPass) + } + if len(out) < ethLen+ip6Len { + t.Fatalf("output is %d bytes, too short for Ethernet and an outer IPv6 header", len(out)) + } + if !bytes.Equal(out[:12], pkt[:12]) { + t.Errorf("MAC addresses = % x, want the arriving frame's % x", out[:12], pkt[:12]) + } + if got := binary.BigEndian.Uint16(out[12:14]); got != 0x86DD { + t.Errorf("EtherType = %#04x, want IPv6", got) + } + if got := out[ethLen+6]; got != byte(nexthdr) { + t.Errorf("outer next header = %d, want %d", got, nexthdr) + } + if got := netip.AddrFrom16([16]byte(out[ethLen+24 : ethLen+40])); got != testUSID { + t.Errorf("outer destination = %v, want the backend's uSID %v", got, testUSID) + } + if !bytes.Equal(out[ethLen+ip6Len:], pkt[ethLen:]) { + t.Errorf("inner packet changed:\n got: % x\nwant: % x", out[ethLen+ip6Len:], pkt[ethLen:]) + } + + if got := sumPerCPU(t, objs.NeighFallbacks, 0); got != 1 { + t.Errorf("neigh_fallbacks = %d, want 1", got) + } + if got := sumPerCPU(t, objs.DropReasons, DropReasonFibNoNeigh); got != 0 { + t.Errorf("drop_reasons[fib_no_neigh] = %d, want 0", got) + } + var stats EdgedsrVipStatsValue + if err := objs.VipStatsTable.Lookup(key, &stats); err != nil { + t.Fatalf("lookup vip_stats_table: %v", err) + } + if stats.Packets != 1 || stats.DroppedPackets != 0 { + t.Errorf("vip stats packets/dropped = %d/%d, want 1/0", stats.Packets, stats.DroppedPackets) + } + }) + } +} + +// TestEdgeLB_KernelResolvesUnresolvedNextHop proves the fallback on a real +// kernel, which a test run cannot: with edge_lb attached to the uplink, the +// first packet to a backend behind an unresolved next hop reaches that next +// hop, and the neighbor entry the kernel resolved for it keeps the next packet +// in XDP. +func TestEdgeLB_KernelResolvesUnresolvedNextHop(t *testing.T) { + requireRoot(t) + if _, err := os.Stat("/dev/net/tun"); err != nil { + t.Skipf("test requires /dev/net/tun: %v", err) + } + + // The gateway's namespace holds the uplink tap, where client frames are + // written, and one end of a veth pair whose other end, in the next hop's + // namespace, holds unresolvedNextHop. + runtime.LockOSThread() + origNS := openThreadNetns(t) + t.Cleanup(func() { + if err := unix.Setns(origNS, unix.CLONE_NEWNET); err != nil { + t.Errorf("restore original network namespace: %v", err) + return + } + _ = unix.Close(origNS) + runtime.UnlockOSThread() + }) + if err := unix.Unshare(unix.CLONE_NEWNET); err != nil { + t.Fatalf("unshare gateway network namespace: %v", err) + } + gatewayNS := openThreadNetns(t) + t.Cleanup(func() { _ = unix.Close(gatewayNS) }) + if err := unix.Unshare(unix.CLONE_NEWNET); err != nil { + t.Fatalf("unshare next hop network namespace: %v", err) + } + nextHopNS := openThreadNetns(t) + t.Cleanup(func() { _ = unix.Close(nextHopNS) }) + setNetns(t, gatewayNS) + + for _, path := range []string{"/proc/sys/net/ipv6/conf/all/forwarding", "/proc/sys/net/ipv6/conf/default/forwarding"} { + if err := os.WriteFile(path, []byte("1"), 0o644); err != nil { + t.Fatalf("enable forwarding via %s: %v", path, err) + } + } + uplinkFd, uplink := openTap(t, "up0") + + if err := netlink.LinkAdd(&netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: "nh0"}, PeerName: "nh1"}); err != nil { + t.Fatalf("add veth pair: %v", err) + } + peer, err := netlink.LinkByName("nh1") + if err != nil { + t.Fatalf("look up veth peer: %v", err) + } + if err := netlink.LinkSetNsFd(peer, nextHopNS); err != nil { + t.Fatalf("move veth peer into the next hop's namespace: %v", err) + } + setNetns(t, nextHopNS) + peer = setLinkUp(t, "nh1") + addLinkAddr(t, peer, unresolvedNextHop, 64) + capture := openCapture(t, peer.Attrs().Index) + setNetns(t, gatewayNS) + fabric := setLinkUp(t, "nh0") + addLinkAddr(t, fabric, unresolvedLocal, 64) + awaitLinkLocal(t, fabric.Attrs().Index) + routeOver(t, fabric, testUSID, unresolvedNextHop) + + objs := loadObjects(t) + vip := netip.MustParseAddr("2001:db8::100") + putIPv4VIP(t, objs, ipprotoUDP, 443, vip, testUSID) + if err := objs.EncapConfigTable.Put(uint32(0), EdgedsrEncapConfig{EncapSrc: unresolvedLocal.As16()}); err != nil { + t.Fatalf("populate encap_config_table: %v", err) + } + xdp, err := link.AttachXDP(link.XDPOptions{Program: objs.EdgeLb, Interface: uplink.Attrs().Index}) + if err != nil { + t.Fatalf("attach edge_lb to the uplink: %v", err) + } + t.Cleanup(func() { _ = xdp.Close() }) + + send := func(label string) []byte { + marker := fmt.Appendf(nil, "edge-neigh:%s:%d", label, time.Now().UnixNano()) + pkt := buildL4Packet(t, ipprotoUDP, vip, netip.MustParseAddr("2001:db8:ffff::1"), 41000, 443, marker) + copy(pkt[0:6], uplink.Attrs().HardwareAddr) + if _, err := unix.Write(uplinkFd, pkt); err != nil { + t.Fatalf("write frame into the uplink tap: %v", err) + } + return marker + } + + if neighborValid(t, fabric.Attrs().Index, unresolvedNextHop) { + t.Fatalf("a neighbor entry for %v exists before the first packet, so nothing is left to resolve", unresolvedNextHop) + } + if !awaitMarker(t, capture, send("unresolved"), 2*time.Second) { + t.Fatalf("the packet sent while the next hop was unresolved never reached it "+ + "(neigh_fallbacks=%d, fib_no_neigh=%d)", + sumPerCPU(t, objs.NeighFallbacks, 0), sumPerCPU(t, objs.DropReasons, DropReasonFibNoNeigh)) + } + if !neighborValid(t, fabric.Attrs().Index, unresolvedNextHop) { + t.Fatalf("no valid neighbor entry for %v after the first packet, want one the kernel resolved", unresolvedNextHop) + } + if got := sumPerCPU(t, objs.NeighFallbacks, 0); got != 1 { + t.Errorf("neigh_fallbacks after the first packet = %d, want 1", got) + } + + // The second packet finds the neighbor and is redirected in XDP. Its + // delivery over a veth depends on the peer's own XDP setup, so only the + // counters are checked. + send("resolved") + if got := sumPerCPU(t, objs.NeighFallbacks, 0); got != 1 { + t.Errorf("neigh_fallbacks after the second packet = %d, want 1: a resolved next hop stays in XDP", got) + } + for i := range DropReasonCount { + if got := sumPerCPU(t, objs.DropReasons, i); got != 0 { + t.Errorf("drop_reasons[%s] = %d, want 0", DropReasonNames[i], got) + } + } +} + +// routeViaUnresolvedNextHop routes dst over a veth pair, in the current +// namespace, through unresolvedNextHop, for which no neighbor entry exists. +// A dummy link would not do: it needs no neighbor resolution at all. +func routeViaUnresolvedNextHop(t *testing.T, dst netip.Addr) { + t.Helper() + if err := netlink.LinkAdd(&netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: "nh0"}, PeerName: "nh1"}); err != nil { + t.Fatalf("add veth pair: %v", err) + } + setLinkUp(t, "nh1") + fabric := setLinkUp(t, "nh0") + addLinkAddr(t, fabric, unresolvedLocal, 64) + routeOver(t, fabric, dst, unresolvedNextHop) +} + +func routeOver(t *testing.T, l netlink.Link, dst, via netip.Addr) { + t.Helper() + if err := netlink.RouteAdd(&netlink.Route{ + LinkIndex: l.Attrs().Index, + Dst: &net.IPNet{IP: net.IP(dst.AsSlice()), Mask: net.CIDRMask(128, 128)}, + Gw: net.IP(via.AsSlice()), + }); err != nil { + t.Fatalf("route %v via %v: %v", dst, via, err) + } +} + +// addLinkAddr assigns addr/bits to l, without duplicate address detection, so +// it can send and answer solicitations at once. +func addLinkAddr(t *testing.T, l netlink.Link, addr netip.Addr, bits int) { + t.Helper() + a := &netlink.Addr{ + IPNet: &net.IPNet{IP: net.IP(addr.AsSlice()), Mask: net.CIDRMask(bits, 128)}, + Flags: unix.IFA_F_NODAD, + } + if err := netlink.AddrAdd(l, a); err != nil { + t.Fatalf("address %s with %v: %v", l.Attrs().Name, addr, err) + } +} + +// awaitLinkLocal waits for the link's link-local address to leave duplicate +// address detection: the kernel solicits a neighbor only from a usable one. +func awaitLinkLocal(t *testing.T, ifindex int) { + t.Helper() + l := &netlink.Device{LinkAttrs: netlink.LinkAttrs{Index: ifindex}} + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + addrs, err := netlink.AddrList(l, netlink.FAMILY_V6) + if err != nil { + t.Fatalf("list addresses on ifindex %d: %v", ifindex, err) + } + for _, a := range addrs { + if a.IP.IsLinkLocalUnicast() && a.Flags&unix.IFA_F_TENTATIVE == 0 { + return + } + } + time.Sleep(50 * time.Millisecond) + } + t.Fatalf("ifindex %d's link-local address was still tentative after 5s", ifindex) +} + +func neighborValid(t *testing.T, ifindex int, dst netip.Addr) bool { + t.Helper() + neighs, err := netlink.NeighList(ifindex, netlink.FAMILY_V6) + if err != nil { + t.Fatalf("list neighbors on ifindex %d: %v", ifindex, err) + } + const valid = netlink.NUD_PERMANENT | netlink.NUD_NOARP | netlink.NUD_REACHABLE | + netlink.NUD_STALE | netlink.NUD_DELAY | netlink.NUD_PROBE + for _, n := range neighs { + if n.IP.Equal(net.IP(dst.AsSlice())) && n.State&valid != 0 { + return true + } + } + return false +} + +func openThreadNetns(t *testing.T) int { + t.Helper() + fd, err := unix.Open("/proc/thread-self/ns/net", unix.O_RDONLY|unix.O_CLOEXEC, 0) + if err != nil { + t.Fatalf("open thread network namespace: %v", err) + } + return fd +} + +func setNetns(t *testing.T, fd int) { + t.Helper() + if err := unix.Setns(fd, unix.CLONE_NEWNET); err != nil { + t.Fatalf("setns: %v", err) + } +} + +// openTap creates a non-persistent tap owned by the returned descriptor and +// brings it up. Holding the descriptor open is what gives the tap carrier. +func openTap(t *testing.T, name string) (int, netlink.Link) { + t.Helper() + fd, err := unix.Open("/dev/net/tun", unix.O_RDWR|unix.O_CLOEXEC, 0) + if err != nil { + t.Fatalf("open /dev/net/tun: %v", err) + } + t.Cleanup(func() { _ = unix.Close(fd) }) + ifr, err := unix.NewIfreq(name) + if err != nil { + t.Fatalf("ifreq for %s: %v", name, err) + } + ifr.SetUint16(unix.IFF_TAP | unix.IFF_NO_PI) + if err := unix.IoctlIfreq(fd, unix.TUNSETIFF, ifr); err != nil { + t.Fatalf("create tap %s: %v", name, err) + } + return fd, setLinkUp(t, name) +} + +func setLinkUp(t *testing.T, name string) netlink.Link { + t.Helper() + l, err := netlink.LinkByName(name) + if err != nil { + t.Fatalf("look up %s: %v", name, err) + } + if err := netlink.LinkSetUp(l); err != nil { + t.Fatalf("set %s up: %v", name, err) + } + if l, err = netlink.LinkByName(name); err != nil { + t.Fatalf("re-read %s: %v", name, err) + } + return l +} + +func openCapture(t *testing.T, ifindex int) int { + t.Helper() + proto := bswap16(unix.ETH_P_ALL) + fd, err := unix.Socket(unix.AF_PACKET, unix.SOCK_RAW|unix.SOCK_CLOEXEC, int(proto)) + if err != nil { + t.Fatalf("open packet socket: %v", err) + } + t.Cleanup(func() { _ = unix.Close(fd) }) + if err := unix.Bind(fd, &unix.SockaddrLinklayer{Protocol: proto, Ifindex: ifindex}); err != nil { + t.Fatalf("bind packet socket to ifindex %d: %v", ifindex, err) + } + return fd +} + +// awaitMarker reports whether a frame containing marker arrives on the +// capture socket fd within wait, skipping unrelated frames such as neighbor +// discovery. +func awaitMarker(t *testing.T, fd int, marker []byte, wait time.Duration) bool { + t.Helper() + deadline := time.Now().Add(wait) + buf := make([]byte, 65536) + for { + remaining := time.Until(deadline) + if remaining <= 0 { + return false + } + fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} + ready, err := unix.Poll(fds, int(remaining.Milliseconds())+1) + if errors.Is(err, unix.EINTR) { + continue + } + if err != nil { + t.Fatalf("poll fd %d: %v", fd, err) + } + if ready == 0 { + return false + } + n, _, err := unix.Recvfrom(fd, buf, unix.MSG_DONTWAIT) + if errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EINTR) { + continue + } + if err != nil { + t.Fatalf("read fd %d: %v", fd, err) + } + if bytes.Contains(buf[:n], marker) { + return true + } + } +}