From d48b13863849214f8d74673240760ef0b3b17780 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 12 Oct 2026 13:07:32 -0400 Subject: [PATCH] feat(usid): Count VRF traffic in both directions The uSID datapath counted per-VRF traffic only inbound, at the vrf_table match and including packets dropped afterwards, and never exported its per-VRF drop count. Outbound tenant traffic was not counted per VRF. Add vrf_traffic_counters, a per-CPU hash keyed like vrf_table, holding forwarded packets, tenant bytes and claimed drops for each direction: - ingress at usid_ingress's warm and cold-neighbor redirects - egress at usid_egress's encapsulating and VIP-reply redirects, which covers egress shards, and at the service path's redirects - same-node traffic, which never reaches usid_ingress, once in each direction at the receiver's local pass-through entry, except traffic to the sender's own gateway - drops at every count_claimed_drop site, split by direction Bytes are the tenant packet alone in both directions. The map is additive; no existing map changes layout. The datapath only looks rows up. VRFTable creates a row with BPF_NOEXIST on Register, removes it on Unregister and reconciles both maps on every GC pass, so every vrf_table writer keeps them in step, and galactic-cni syncs them once at load so an upgraded node counts from its first packet. Export galactic_usid_vrf_forwarded_packets_total, galactic_usid_vrf_forwarded_bytes_total and galactic_usid_vrf_dropped_packets_total, each with a direction label. The existing galactic_usid_vrf_{packets,bytes}_total are unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/agents/ARCHITECTURE-CNI.md | 1 + docs/metrics.md | 71 +++- internal/installer/installer.go | 6 + internal/plumbing/ebpf/attachreg/fill_test.go | 42 ++ .../shardgroup_datapath_test.go | 48 +++ internal/plumbing/ebpf/metrics/collector.go | 93 ++++- .../plumbing/ebpf/metrics/vrftraffic_test.go | 246 ++++++++++++ internal/plumbing/ebpf/prog/doc.go | 2 +- internal/plumbing/ebpf/prog/usid.c | 257 +++++++++++-- .../ebpf/prog/usid_vrftraffic_test.go | 268 +++++++++++++ internal/plumbing/ebpf/usidmap/kernel_test.go | 57 +++ internal/plumbing/ebpf/usidmap/registry.go | 33 +- internal/plumbing/ebpf/usidmap/vrf.go | 66 +++- internal/plumbing/ebpf/usidmap/vrftraffic.go | 224 +++++++++++ .../plumbing/ebpf/usidmap/vrftraffic_test.go | 364 ++++++++++++++++++ 15 files changed, 1717 insertions(+), 61 deletions(-) create mode 100644 internal/plumbing/ebpf/metrics/vrftraffic_test.go create mode 100644 internal/plumbing/ebpf/prog/usid_vrftraffic_test.go create mode 100644 internal/plumbing/ebpf/usidmap/vrftraffic.go create mode 100644 internal/plumbing/ebpf/usidmap/vrftraffic_test.go diff --git a/docs/agents/ARCHITECTURE-CNI.md b/docs/agents/ARCHITECTURE-CNI.md index 7965a508a..07359d97e 100644 --- a/docs/agents/ARCHITECTURE-CNI.md +++ b/docs/agents/ARCHITECTURE-CNI.md @@ -521,6 +521,7 @@ auto-detect directly (see Configuration above). - **Tenant egress can spread across every egress shard in the cluster (hashed mode).** With `GALACTIC_CNI_EGRESS_MODE=hashed`, a tenant VRF's `::/0` and NAT64 entries in `egress_route_table` are not a single shard SID but a group sentinel: `link_ifindex == 0xFFFFFFFF`, the group ID in the first four bytes of `sid` and the tenant's Argument in bytes 8 and 9. There is one group per translation class, NAT66 (group 0) and each configured NAT64 prefix (groups 1-3), and a group holds only the `EgressShard`s whose status can translate its class (an IPv6 masquerade address for NAT66; an IPv4 address and that `nat64Prefix`, or `translatesWellKnownPrefix` for `64:ff9b::/96`, for NAT64), so traffic can never be placed on a shard that would drop it. `usid_egress` resolves the sentinel in `resolve_egress_group`: it looks the group up in `egress_shard_groups`, an `ARRAY_OF_MAPS` whose slot holds the group's current snapshot (one immutable `struct egress_shard_group_value`: Maglev table plus every member's SID, next hop, flags and slot generation), hashes the tenant's source address (or the 5-tuple, `GALACTIC_CNI_EGRESS_HASH=flow`) with FNV-1a over `struct egress_shard_pin_key`, follows a live pin in `egress_shard_pin` or else the Maglev table, completes the member's base SID with the Argument and encapsulates as for an ordinary entry. Every read comes from one snapshot. `egressroutemap.KernelGroupStore` publishes a change by creating a new inner map, filling it and swapping it into the outer slot in one update, so a packet sees the old snapshot or the new one and the kernel frees the old one after RCU; an ordinary array value updated in place was measured to hand out torn records (17 of 55,000 packets mixed one shard's SID with another's MACs under concurrent updates), the snapshot swap none. `egress_shard_group_template`, an unused instance of the inner map type, exists only so clang older than 21 emits the value's full BTF. A pin is honoured only while its slot still carries the generation it recorded; generations come from `next_slot_generation`, published in the snapshot, and an in-process high-water mark that also covers failed publications, so a slot's generation is never reused (see `ShardGroupTable`'s doc comment and `docs/nat/configuration.md#how-the-groups-are-published`). The groups are written only by `galactic-cni run` (`internal/installer/egressgroup.go`): it watches the cluster's `EgressShard`s (a candidate needs `status.shardSID` with `Programmed` and `Ready` true and no deletion timestamp; `spec.drain` makes it draining), resolves each SID to an uplink neighbor (only a resolvable shard is alive), and rebuilds on any EgressShard, route or neighbor change as well as the 30 s sweep. CNI ADD (`attachreg.installVRFEgress`, also used by the datapath repair's `FillVRF`) writes each route to its class's group when any group is open, skips a class with no eligible shard, and fails like an unresolvable ordered list when a class's shards are all unreachable. Leaving hashed mode is a three-step protocol: the sweep marks every group `CLOSING` (still forwarding, but CNI ADD writes no new sentinel), then `EgressRouteTable.Refresh` moves every sentinel back to the first resolvable `GALACTIC_CNI_EGRESS_SHARD_SIDS` entry, and the groups are disabled only after a sweep that read and wrote every route without error and found none left; an ADD that read the groups open re-checks after writing and rewrites its routes in ordered mode if they closed, so no sentinel is written after the last scan. `galactic_cni_egress_group_routes` reports the sentinels left. An empty or disabled group drops (`egress_shard_stats`, `galactic_cni_egress_shard_selections_total`), never fails open. Privileged tests run the datapath under BPF_PROG_RUN against snapshots the Go side published: placement against `ShardHash` and `internal/maglev` (`shardgroup_datapath_test.go`), publication faults at each step, restart, class isolation and concurrent swaps against live packets (`shardgroup_publication_test.go`). See [docs/nat/configuration.md](../nat/configuration.md#active-active-egress). - **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](../metrics.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 bond for 6 to 14 seconds. 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. - **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. None of them delete the VRF, routes, the eBPF `vrf_table` entry, or `BGPAdvertisement`/`BGPVRFInstance` CRDs — those are keyed by `(vpc, vpcAttachment)` or `(vpc, node)` and may be shared/reused by another pod/VM (deleting them in DEL would race with a concurrent ADD during restarts). `galactic-router`'s GC controller (see [ARCHITECTURE-ROUTER.md](ARCHITECTURE-ROUTER.md)) reclaims orphaned CRDs, stale kernel VRFs, and stale eBPF entries once no live container still references them — see [docs/cni/gc-cmd-sequence.md](../cni/gc-cmd-sequence.md) for why the host veth/tap interface has no GC path of its own at all. diff --git a/docs/metrics.md b/docs/metrics.md index cd6c6fa7d..3a9bb1e73 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -40,28 +40,71 @@ and tenant VRFs. ### Traffic -| Metric | Type | Labels | Meaning | -|-----------------------------------|---------|--------------------------------------------------------------|--------------------------------------------------------------------------| -| `galactic_usid_vrf_packets_total` | counter | `block`, `argument`, `vrf_table_id`, `vpc`, `vpc_attachment` | Packets forwarded into a tenant VRF for one (uSID Block, Argument) entry | -| `galactic_usid_vrf_bytes_total` | counter | same | Bytes for the same entry | - -- Both reset when an entry is re-registered, not only on restart; `rate()` - copes with this. +Each node keeps one VRF per VPC, so every series below is one VPC on one +node, keyed by its uSID (Block, Argument). `vpc_attachment` names the +attachment that registered the VRF last, not each attachment's own traffic. + +| Metric | Type | Labels | Meaning | +|---------------------------------------------|---------|---------------------------------------------------------------------------|---------------------------------------------------------------------------------| +| `galactic_usid_vrf_forwarded_packets_total` | counter | `block`, `argument`, `vrf_table_id`, `vpc`, `vpc_attachment`, `direction` | Packets forwarded into (`ingress`) or out of (`egress`) the VRF | +| `galactic_usid_vrf_forwarded_bytes_total` | counter | same | Tenant bytes of those packets: the IP header and payload, in both directions | +| `galactic_usid_vrf_dropped_packets_total` | counter | same | Packets dropped after the datapath resolved them to the VRF, by direction | +| `galactic_usid_vrf_packets_total` | counter | `block`, `argument`, `vrf_table_id`, `vpc`, `vpc_attachment` | Inbound packets that matched the VRF, counted before any later drop | +| `galactic_usid_vrf_bytes_total` | counter | same | Bytes of those packets, measured as the whole tunneled frame with outer headers | + +What each `direction` counts: + +| `direction` | Counted when | +|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `ingress` | `usid_ingress` decapsulates a packet and redirects it to an attachment, or another attachment on the same node sends one to it | +| `egress` | a tenant packet is encapsulated toward another node or an egress shard, sent unencapsulated out the public uplink (a VIP reply), or delivered to another attachment on the node | + +- A packet counts once, when the datapath has committed to forwarding it. + Traffic the datapath hands to the kernel to route (no matching egress + route) and fail-open paths are not counted. +- A packet too big for the fabric, answered with a Packet Too Big or + Fragmentation Needed, counts as neither forwarded nor dropped; see + `galactic_usid_pmtu_packets_total`. +- Traffic between two attachments of one VPC on the same node counts once + as `egress` and once as `ingress` on that VPC's series, when it is handed + to the kernel for delivery, so the kernel can still drop it. Traffic to the + sender's own gateway address counts in neither; traffic to another + attachment's gateway address in the same VPC counts as delivered. +- A private service route delivering to another attachment on the node + counts `egress` on the sender's VPC and `ingress` on the receiver's, which + may be a different VPC. +- A GSO or GRO super-packet counts as one packet carrying all its bytes. +- Drop reasons are in `galactic_usid_drops_total`, which has no VRF. + `galactic_usid_vrf_dropped_packets_total` has the VRF but no reason, and + covers drops in decapsulation, delivery, encapsulation and the PMTU check, + including inbound private service tunnels. Outbound private service route + drops (`service_route_*` from the sending attachment) and failed + public-uplink redirects appear only in `galactic_usid_drops_total`. +- The two older series keep their meaning: inbound only, claimed before any + drop, and the full frame. Prefer the `forwarded` series for throughput. +- Registering a VRF again never resets its counters. They reset when the + datapath reloads, or when the VRF's rows are removed and created again, + which `rate()` copes with. - `vpc` and `vpc_attachment` are empty when the VPC attribution map has no entry for that Argument. Treat `vpc=""` traffic as unattributed and watch for it. -- Cardinality is one series per active Argument per node: at most 4095 per - Block. +- Cardinality is one series per active Argument per node for the older pair, + at most 4095 per Block, and twice that for each `direction` metric. ```promql -# Throughput per VPC, bits/s -sum by (vpc) (rate(galactic_usid_vrf_bytes_total[5m])) * 8 +# Throughput per VPC and direction, bits/s +sum by (vpc, direction) (rate(galactic_usid_vrf_forwarded_bytes_total[5m])) * 8 + +# Top 10 VPCs on a node by outbound packet rate +topk(10, sum by (node, vpc) (rate(galactic_usid_vrf_forwarded_packets_total{direction="egress"}[5m]))) -# Top 10 attachments by packet rate -topk(10, sum by (vpc, vpc_attachment) (rate(galactic_usid_vrf_packets_total[5m]))) +# Share of a VPC's packets dropped after the datapath claimed them +sum by (vpc, direction) (rate(galactic_usid_vrf_dropped_packets_total[5m])) + / (sum by (vpc, direction) (rate(galactic_usid_vrf_forwarded_packets_total[5m])) + + sum by (vpc, direction) (rate(galactic_usid_vrf_dropped_packets_total[5m]))) # Traffic the datapath can't attribute to a VPC -sum by (node) (rate(galactic_usid_vrf_bytes_total{vpc=""}[5m])) +sum by (node) (rate(galactic_usid_vrf_forwarded_bytes_total{vpc=""}[5m])) ``` ### Drops diff --git a/internal/installer/installer.go b/internal/installer/installer.go index f675b0d31..7bcac7879 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -38,6 +38,7 @@ import ( "go.datum.net/galactic/internal/plumbing/ebpf/attachreg" "go.datum.net/galactic/internal/plumbing/ebpf/metrics" "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" "go.datum.net/galactic/internal/plumbing/radv" bgpv1alpha1 "go.datum.net/network/api/v1alpha1" ) @@ -552,6 +553,11 @@ func startEBPFDatapath(ctx context.Context, m *metrics.Metrics) (ebpfDatapathSta state.mssClamp = newMSSClampState(objs.MssClampTable, objs.EncapMtuTable) state.mssClamp.reconcile() state.egressGroup.counters = objs.EgressShardCounters + // Give every registered VRF its traffic counter row now, rather than + // at the first GC sweep, so counting starts with the first packet. + if err := usidmap.NewRegistryFromObjects(objs).VRF.SyncTraffic(); err != nil { + slog.Warn("Failed to create per-VRF traffic counter rows; the next GC sweep retries", "err", err) + } if err := m.RegisterDatapathCollector(objs); err != nil { slog.Warn("Failed to register eBPF datapath metrics collector", "err", err) } diff --git a/internal/plumbing/ebpf/attachreg/fill_test.go b/internal/plumbing/ebpf/attachreg/fill_test.go index b502e79f6..6b17b75b3 100644 --- a/internal/plumbing/ebpf/attachreg/fill_test.go +++ b/internal/plumbing/ebpf/attachreg/fill_test.go @@ -239,3 +239,45 @@ func TestFillNode_NotConfiguredWritesNothing(t *testing.T) { t.Errorf("FillNode(zero) = %+v, %v, %v; want nothing", written, uplinkErr, err) } } + +// memCounterTable is memTable as a usidmap.CounterTable, creating a row only +// when it is absent. +type memCounterTable struct{ memTable } + +func (m memCounterTable) Create(key, value any) error { + if _, ok := m.memTable[key]; ok { + return ebpf.ErrKeyExist + } + m.memTable[key] = value + return nil +} + +// TestFillVRF_TrafficRowFollowsVRFRow checks the datapath repair creates a +// VRF's vrf_traffic_counters row with its vrf_table row, and that removing the +// VRF's rows removes it too. +func TestFillVRF_TrafficRowFollowsVRFRow(t *testing.T) { + recordRouteAdds(t, nil) + m := newMemMaps(true) + traffic := memCounterTable{memTable{}} + m.Registry.VRF.WithTraffic(usidmap.NewVRFTrafficTable(traffic)) + a := testAttachment() + + written, err := m.FillVRF(a, EgressConfig{}) + if err != nil { + t.Fatalf("FillVRF: %v", err) + } + key, err := uformat.NewVRFKey(a.Block, a.Argument) + if err != nil { + t.Fatal(err) + } + if _, ok := traffic.memTable[uint64(key)]; !ok || len(traffic.memTable) != 1 { + t.Fatalf("traffic rows after FillVRF = %v, want one row for the VRF", traffic.memTable) + } + + if err := m.RemoveVRFRows(a, written, nil, false); err != nil { + t.Fatalf("RemoveVRFRows: %v", err) + } + if len(traffic.memTable) != 0 { + t.Errorf("traffic rows after RemoveVRFRows = %v, want none", traffic.memTable) + } +} diff --git a/internal/plumbing/ebpf/egressroutemap/shardgroup_datapath_test.go b/internal/plumbing/ebpf/egressroutemap/shardgroup_datapath_test.go index 00fc04eb3..7fa67c5e3 100644 --- a/internal/plumbing/ebpf/egressroutemap/shardgroup_datapath_test.go +++ b/internal/plumbing/ebpf/egressroutemap/shardgroup_datapath_test.go @@ -520,3 +520,51 @@ func TestGroupDatapath_IPv4SourceHash(t *testing.T) { } } } + +// TestGroupDatapath_CountsVRFEgress checks tenant traffic placed on an egress +// shard counts once per packet as the VRF's outbound traffic, at the tenant +// packet's length rather than the encapsulated one. +func TestGroupDatapath_CountsVRFEgress(t *testing.T) { + dp := loadDatapath(t) + a := shardSID(0x10) + reachable(t, a) + dp.apply(t, GroupPolicy{}, candidates(nil, a)) + + vrfKey, err := uformat.NewVRFKey(dpBlock, dpArgument) + if err != nil { + t.Fatalf("NewVRFKey: %v", err) + } + cpus, err := ebpf.PossibleCPU() + if err != nil { + t.Fatalf("PossibleCPU: %v", err) + } + if err := dp.objs.VrfTrafficCounters.Put(uint64(vrfKey), make([]prog.UsidVrfTrafficValue, cpus)); err != nil { + t.Fatalf("populate vrf_traffic_counters: %v", err) + } + + const sent = 3 + pkt := udp6(tenant(1), internet, 1000, 443) + for range sent { + if verdict, shard, _ := dp.send(t, pkt); verdict != tcActRedirect || shard != a { + t.Fatalf("verdict %d to %s, want a redirect to %s", verdict, shard, a) + } + } + + var perCPU []prog.UsidVrfTrafficValue + if err := dp.objs.VrfTrafficCounters.Lookup(uint64(vrfKey), &perCPU); err != nil { + t.Fatalf("look up vrf_traffic_counters: %v", err) + } + var got prog.UsidVrfTrafficValue + for _, v := range perCPU { + got.Egress.Packets += v.Egress.Packets + got.Egress.Bytes += v.Egress.Bytes + got.Egress.DroppedPackets += v.Egress.DroppedPackets + got.Ingress.Packets += v.Ingress.Packets + } + want := prog.UsidVrfTrafficValue{Egress: prog.UsidVrfDirectionCounter{ + Packets: sent, Bytes: sent * uint64(len(pkt)-ethLen), + }} + if got != want { + t.Errorf("vrf_traffic_counters = %+v, want %+v", got, want) + } +} diff --git a/internal/plumbing/ebpf/metrics/collector.go b/internal/plumbing/ebpf/metrics/collector.go index 3d9072961..7e8a850e1 100644 --- a/internal/plumbing/ebpf/metrics/collector.go +++ b/internal/plumbing/ebpf/metrics/collector.go @@ -35,6 +35,10 @@ type Collector struct { dropReasons DropReasonsReader vpcAttribution *usidmap.VPCAttributionTable + // vrfTraffic is nil unless set by WithVRFTraffic, in which case each VRF's + // per-direction forwarded and dropped counters are collected too. + vrfTraffic *usidmap.VRFTrafficTable + // mssClampStats and mssClampTable are nil unless set by WithMSSClamp, in // which case the TCP MSS clamp's outcomes and limits are collected too. mssClampStats DropReasonsReader @@ -67,7 +71,15 @@ func NewCollectorFromObjects(objs *prog.UsidObjects) *Collector { objs.DropReasons, usidmap.NewVPCAttributionTable(usidmap.KernelTable{Map: objs.VpcAttributionTable}), ).WithMSSClamp(objs.MssClampStats, objs.MssClampTable). - WithPMTU(objs.PmtuStats, objs.EncapMtuTable) + WithPMTU(objs.PmtuStats, objs.EncapMtuTable). + WithVRFTraffic(usidmap.NewVRFTrafficTable(usidmap.KernelCounterTable{Map: objs.VrfTrafficCounters})) +} + +// WithVRFTraffic adds vrf_traffic_counters to c, so each VRF's per-direction +// forwarded and dropped counters are collected. It returns c. +func (c *Collector) WithVRFTraffic(traffic *usidmap.VRFTrafficTable) *Collector { + c.vrfTraffic = traffic + return c } // WithMSSClamp adds the TCP MSS clamp's maps to c: stats, the per-CPU @@ -89,6 +101,13 @@ func (c *Collector) WithPMTU(stats, table DropReasonsReader) *Collector { // metric below that carries one. const labelBlock = "block" +// vrfLabels are the identity labels of every per-VRF series, and +// vrfDirectionLabels adds the direction of travel. +var ( + vrfLabels = []string{labelBlock, "argument", "vrf_table_id", "vpc", "vpc_attachment"} + vrfDirectionLabels = append(append([]string(nil), vrfLabels...), "direction") +) + // labelResult is the Prometheus label name for an outcome, shared by the MSS // clamp series here and the datapath event counters in events.go. const labelResult = "result" @@ -97,12 +116,34 @@ var ( vrfPacketsDesc = prometheus.NewDesc( prometheus.BuildFQName(namespace, "vrf", "packets_total"), "Packets forwarded through vrf_table for this (uSID Block, Argument) entry since it was last (re-)registered.", - []string{labelBlock, "argument", "vrf_table_id", "vpc", "vpc_attachment"}, nil, + vrfLabels, nil, ) vrfBytesDesc = prometheus.NewDesc( prometheus.BuildFQName(namespace, "vrf", "bytes_total"), "Bytes forwarded through vrf_table for this (uSID Block, Argument) entry since it was last (re-)registered.", - []string{labelBlock, "argument", "vrf_table_id", "vpc", "vpc_attachment"}, nil, + vrfLabels, nil, + ) + vrfForwardedPacketsDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "vrf", "forwarded_packets_total"), + "Packets forwarded into (direction=ingress) or out of (direction=egress) this VRF: decapsulated and "+ + "delivered to an attachment, or encapsulated, sent out the public uplink, or delivered to another "+ + "attachment on this node. Counted once the datapath has committed to forwarding the packet. A GSO or "+ + "GRO super-packet counts once.", + vrfDirectionLabels, nil, + ) + vrfForwardedBytesDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "vrf", "forwarded_bytes_total"), + "Bytes of the packets in galactic_usid_vrf_forwarded_packets_total, measured as the tenant packet "+ + "alone: its IP header and payload, without the Ethernet header or any SRv6 outer header, in both "+ + "directions.", + vrfDirectionLabels, nil, + ) + vrfDroppedPacketsDesc = prometheus.NewDesc( + prometheus.BuildFQName(namespace, "vrf", "dropped_packets_total"), + "Packets usid_ingress or usid_egress dropped after resolving them to this VRF, by the direction they "+ + "were travelling. Outbound private service route drops and failed public-uplink redirects are "+ + "counted only in galactic_usid_drops_total, which has the reasons, without the VRF.", + vrfDirectionLabels, nil, ) dropsDesc = prometheus.NewDesc( prometheus.BuildFQName(namespace, "", "drops_total"), @@ -150,6 +191,9 @@ var ( func (c *Collector) Describe(ch chan<- *prometheus.Desc) { ch <- vrfPacketsDesc ch <- vrfBytesDesc + ch <- vrfForwardedPacketsDesc + ch <- vrfForwardedBytesDesc + ch <- vrfDroppedPacketsDesc ch <- dropsDesc ch <- blockArgumentsUsedDesc ch <- blockArgumentUtilizationDesc @@ -267,6 +311,8 @@ func (c *Collector) collectVRF(ch chan<- prometheus.Metric) { } } + traffic := c.listVRFTraffic(ch) + entries, err := c.vrf.List() if err != nil { ch <- prometheus.NewInvalidMetric(vrfPacketsDesc, fmt.Errorf("list vrf_table: %w", err)) @@ -282,6 +328,11 @@ func (c *Collector) collectVRF(ch chan<- prometheus.Metric) { vrfPacketsDesc, prometheus.CounterValue, float64(e.Packets), block, argument, vrfTableID, vpc, vpcAttachment) ch <- prometheus.MustNewConstMetric( vrfBytesDesc, prometheus.CounterValue, float64(e.Bytes), block, argument, vrfTableID, vpc, vpcAttachment) + if t, ok := traffic[e.VRFKey]; ok { + labels := []string{block, argument, vrfTableID, vpc, vpcAttachment} + emitVRFDirection(ch, t.Ingress, append(labels, directionIngress)) + emitVRFDirection(ch, t.Egress, append(labels, directionEgress)) + } perBlockUsed[e.Block]++ } @@ -293,6 +344,42 @@ func (c *Collector) collectVRF(ch chan<- prometheus.Metric) { } } +// direction label values for the per-direction VRF series. +const ( + directionIngress = "ingress" + directionEgress = "egress" +) + +// listVRFTraffic reads vrf_traffic_counters keyed by VRF, or returns nil when +// the collector has none. A read failure is reported on ch and also returns +// nil, so the per-VRF series that do not depend on it are still collected. +func (c *Collector) listVRFTraffic(ch chan<- prometheus.Metric) map[usidmap.VRFKey]usidmap.VRFTrafficEntry { + if c.vrfTraffic == nil { + return nil + } + entries, err := c.vrfTraffic.List() + if err != nil { + ch <- prometheus.NewInvalidMetric(vrfForwardedPacketsDesc, fmt.Errorf("list vrf_traffic_counters: %w", err)) + return nil + } + traffic := make(map[usidmap.VRFKey]usidmap.VRFTrafficEntry, len(entries)) + for _, e := range entries { + traffic[e.VRFKey] = e + } + return traffic +} + +// emitVRFDirection sends one direction's three per-VRF counters, labelled +// with labels, the VRF's identity labels followed by the direction. +func emitVRFDirection(ch chan<- prometheus.Metric, counters usidmap.VRFTrafficCounters, labels []string) { + ch <- prometheus.MustNewConstMetric( + vrfForwardedPacketsDesc, prometheus.CounterValue, float64(counters.Packets), labels...) + ch <- prometheus.MustNewConstMetric( + vrfForwardedBytesDesc, prometheus.CounterValue, float64(counters.Bytes), labels...) + ch <- prometheus.MustNewConstMetric( + vrfDroppedPacketsDesc, prometheus.CounterValue, float64(counters.DroppedPackets), labels...) +} + // vpcLabels re-encodes entry's VPC/VPCAttachment identifiers back to the // base62 form used everywhere else in this codebase (CNI conflist, // interface names). found is false when this key had no vpc_attribution_table diff --git a/internal/plumbing/ebpf/metrics/vrftraffic_test.go b/internal/plumbing/ebpf/metrics/vrftraffic_test.go new file mode 100644 index 000000000..a595c3398 --- /dev/null +++ b/internal/plumbing/ebpf/metrics/vrftraffic_test.go @@ -0,0 +1,246 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package metrics + +import ( + "errors" + "slices" + "testing" + + "github.com/prometheus/client_golang/prometheus" + dto "github.com/prometheus/client_model/go" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/ebpf/uformat" + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" +) + +const ( + forwardedPacketsName = "galactic_usid_vrf_forwarded_packets_total" + forwardedBytesName = "galactic_usid_vrf_forwarded_bytes_total" + droppedPacketsName = "galactic_usid_vrf_dropped_packets_total" +) + +// fakeTrafficTable is an in-memory usidmap.CounterTable whose rows are +// per-CPU slices, the shape the kernel's per-CPU hash map hands back. +type fakeTrafficTable struct { + keys []uint64 + rows map[uint64][]prog.UsidVrfTrafficValue + iterErr error +} + +func newFakeTrafficTable() *fakeTrafficTable { + return &fakeTrafficTable{rows: make(map[uint64][]prog.UsidVrfTrafficValue)} +} + +func (f *fakeTrafficTable) put(t *testing.T, argument uint16, perCPU ...prog.UsidVrfTrafficValue) { + t.Helper() + key, err := uformat.NewVRFKey(testBlock, argument) + if err != nil { + t.Fatalf("uformat.NewVRFKey: %v", err) + } + if _, ok := f.rows[uint64(key)]; !ok { + f.keys = append(f.keys, uint64(key)) + } + f.rows[uint64(key)] = perCPU +} + +func (f *fakeTrafficTable) Create(any, any) error { return errors.New("not implemented") } +func (f *fakeTrafficTable) Delete(any) error { return errors.New("not implemented") } + +func (f *fakeTrafficTable) Iterate() usidmap.Iterator { + return &fakeTrafficIterator{table: f} +} + +type fakeTrafficIterator struct { + table *fakeTrafficTable + idx int +} + +func (it *fakeTrafficIterator) Next(keyOut, valueOut any) bool { + if it.table.iterErr != nil || it.idx >= len(it.table.keys) { + return false + } + k := it.table.keys[it.idx] + it.idx++ + *keyOut.(*uint64) = k + *valueOut.(*[]prog.UsidVrfTrafficValue) = slices.Clone(it.table.rows[k]) + return true +} + +func (it *fakeTrafficIterator) Err() error { return it.table.iterErr } + +func trafficValue(inPackets, inBytes, inDrops, outPackets, outBytes, outDrops uint64) prog.UsidVrfTrafficValue { + return prog.UsidVrfTrafficValue{ + Ingress: prog.UsidVrfDirectionCounter{Packets: inPackets, Bytes: inBytes, DroppedPackets: inDrops}, + Egress: prog.UsidVrfDirectionCounter{Packets: outPackets, Bytes: outBytes, DroppedPackets: outDrops}, + } +} + +// sampleKey names one per-VRF, per-direction series. +type sampleKey struct { + name, argument, direction string +} + +// gatherTraffic collects c through a registry and returns the per-direction +// VRF samples by name, Argument and direction, with the vpc label of each. +func gatherTraffic(t *testing.T, c prometheus.Collector) (values map[sampleKey]float64, vpcs map[sampleKey]string) { + t.Helper() + reg := prometheus.NewPedanticRegistry() + reg.MustRegister(c) + families, err := reg.Gather() + if err != nil { + t.Fatalf("gather: %v", err) + } + values, vpcs = map[sampleKey]float64{}, map[sampleKey]string{} + for _, f := range families { + switch f.GetName() { + case forwardedPacketsName, forwardedBytesName, droppedPacketsName: + default: + continue + } + for _, m := range f.GetMetric() { + k := sampleKey{f.GetName(), labelValue(m, "argument"), labelValue(m, "direction")} + values[k] = metricValue(m) + vpcs[k] = labelValue(m, "vpc") + } + } + return values, vpcs +} + +func newTrafficCollector(vrf, attribution *fakeTable, traffic *fakeTrafficTable) *Collector { + var attr *usidmap.VPCAttributionTable + if attribution != nil { + attr = usidmap.NewVPCAttributionTable(attribution) + } + return NewCollector(usidmap.NewVRFTable(vrf), usidmap.NewLocatorTable(newFakeTable()), fakeDropReasons{}, attr). + WithVRFTraffic(usidmap.NewVRFTrafficTable(traffic)) +} + +func TestCollector_VRFTrafficSumsCPUsPerDirection(t *testing.T) { + vrfFake := newFakeTable() + putVRFEntry(t, vrfFake, testBlock, 0x001, 7, 0, 0) + putVRFEntry(t, vrfFake, testBlock, 0x002, 8, 0, 0) + + traffic := newFakeTrafficTable() + traffic.put(t, 0x001, + trafficValue(1, 100, 0, 2, 200, 1), + trafficValue(3, 300, 2, 4, 400, 0)) + traffic.put(t, 0x002, trafficValue(0, 0, 0, 5, 1500, 0)) + + values, _ := gatherTraffic(t, newTrafficCollector(vrfFake, nil, traffic)) + + want := map[sampleKey]float64{ + {forwardedPacketsName, "1", directionIngress}: 4, + {forwardedBytesName, "1", directionIngress}: 400, + {droppedPacketsName, "1", directionIngress}: 2, + {forwardedPacketsName, "1", directionEgress}: 6, + {forwardedBytesName, "1", directionEgress}: 600, + {droppedPacketsName, "1", directionEgress}: 1, + {forwardedPacketsName, "2", directionIngress}: 0, + {forwardedBytesName, "2", directionIngress}: 0, + {droppedPacketsName, "2", directionIngress}: 0, + {forwardedPacketsName, "2", directionEgress}: 5, + {forwardedBytesName, "2", directionEgress}: 1500, + {droppedPacketsName, "2", directionEgress}: 0, + } + if len(values) != len(want) { + t.Errorf("got %d per-direction samples, want %d: %v", len(values), len(want), values) + } + for k, w := range want { + if got, ok := values[k]; !ok || got != w { + t.Errorf("%v = %v (present %v), want %v", k, got, ok, w) + } + } +} + +func TestCollector_VRFTrafficAttribution(t *testing.T) { + vrfFake := newFakeTable() + putVRFEntry(t, vrfFake, testBlock, 0x001, 7, 0, 0) + putVRFEntry(t, vrfFake, testBlock, 0x002, 8, 0, 0) + attrFake := newFakeTable() + putVPCAttribution(t, attrFake, testBlock, 0x001, 0x2589, 0x07) + + traffic := newFakeTrafficTable() + traffic.put(t, 0x001, trafficValue(1, 1, 0, 1, 1, 0)) + traffic.put(t, 0x002, trafficValue(1, 1, 0, 1, 1, 0)) + + values, vpcs := gatherTraffic(t, newTrafficCollector(vrfFake, attrFake, traffic)) + + attributed := sampleKey{forwardedPacketsName, "1", directionEgress} + if vpcs[attributed] == "" { + t.Errorf("argument=1 has an attribution row but its vpc label is empty") + } + missed := sampleKey{forwardedPacketsName, "2", directionEgress} + if _, ok := values[missed]; !ok { + t.Fatalf("argument=2 has no attribution row and was not reported; a miss must not drop the series") + } + if vpcs[missed] != "" { + t.Errorf("argument=2 vpc label = %q, want empty for an attribution miss", vpcs[missed]) + } +} + +func TestCollector_VRFTrafficEmptyMapReportsNoDirectionSeries(t *testing.T) { + vrfFake := newFakeTable() + putVRFEntry(t, vrfFake, testBlock, 0x001, 7, 10, 1000) + + c := newTrafficCollector(vrfFake, nil, newFakeTrafficTable()) + values, _ := gatherTraffic(t, c) + if len(values) != 0 { + t.Errorf("got per-direction samples %v from an empty vrf_traffic_counters, want none", values) + } + + var sawPackets bool + for _, m := range collect(t, c) { + if labelValue(m, "argument") == "1" && labelValue(m, "direction") == "" && metricValue(m) == 10 { + sawPackets = true + } + } + if !sawPackets { + t.Error("galactic_usid_vrf_packets_total missing: the existing series must not depend on vrf_traffic_counters") + } +} + +func TestCollector_VRFTrafficRowWithoutVRFIsNotReported(t *testing.T) { + vrfFake := newFakeTable() + putVRFEntry(t, vrfFake, testBlock, 0x001, 7, 0, 0) + traffic := newFakeTrafficTable() + traffic.put(t, 0x001, trafficValue(1, 1, 0, 1, 1, 0)) + traffic.put(t, 0x003, trafficValue(9, 9, 9, 9, 9, 9)) + + values, _ := gatherTraffic(t, newTrafficCollector(vrfFake, nil, traffic)) + for k := range values { + if k.argument == "3" { + t.Errorf("reported %v for a counter row vrf_table no longer holds", k) + } + } +} + +func TestCollector_VRFTrafficListErrorReportsInvalidMetric(t *testing.T) { + vrfFake := newFakeTable() + putVRFEntry(t, vrfFake, testBlock, 0x001, 7, 10, 1000) + traffic := newFakeTrafficTable() + traffic.iterErr = errors.New("simulated map iteration failure") + + c := newTrafficCollector(vrfFake, nil, traffic) + ch := make(chan prometheus.Metric, 64) + c.collectVRF(ch) + close(ch) + + var invalid, vrfSamples int + for m := range ch { + if err := m.Write(new(dto.Metric)); err != nil { + invalid++ + continue + } + vrfSamples++ + } + if invalid != 1 { + t.Errorf("got %d invalid metrics, want 1 for the failed vrf_traffic_counters read", invalid) + } + if vrfSamples == 0 { + t.Error("a failed vrf_traffic_counters read suppressed every per-VRF sample") + } +} diff --git a/internal/plumbing/ebpf/prog/doc.go b/internal/plumbing/ebpf/prog/doc.go index 6b178e7fe..397e7a97e 100644 --- a/internal/plumbing/ebpf/prog/doc.go +++ b/internal/plumbing/ebpf/prog/doc.go @@ -40,4 +40,4 @@ package prog // -cc is deliberately omitted: bpf2go defaults to $BPF2GO_CC or "clang", so CI // can pin an exact version without this directive changing. // -//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type locator_value -type function_value -type vrf_value -type ifindex_vrf_value -type nptv6_value -type vip_xlat_key -type vip_xlat_value -type egress_route_key -type egress_route_value -type service_route_key -type service_route_value -type service_access_key -type service_access_value -type service_deny_key -type service_deny_value -type service_reverse_key -type service_reverse_value -type service_remote_grant_key -type service_remote_grant_value -type service_policy_state_value -type public_uplink_value -type egress_shard_group_value -type egress_shard_member -type egress_shard_pin_key -type egress_shard_pin_value -type egress_shard_counter -type mss_clamp_value -type tenant_gw_value -type vpc_attribution_value Usid usid.c +//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type locator_value -type function_value -type vrf_value -type ifindex_vrf_value -type nptv6_value -type vip_xlat_key -type vip_xlat_value -type egress_route_key -type egress_route_value -type service_route_key -type service_route_value -type service_access_key -type service_access_value -type service_deny_key -type service_deny_value -type service_reverse_key -type service_reverse_value -type service_remote_grant_key -type service_remote_grant_value -type service_policy_state_value -type public_uplink_value -type egress_shard_group_value -type egress_shard_member -type egress_shard_pin_key -type egress_shard_pin_value -type egress_shard_counter -type mss_clamp_value -type tenant_gw_value -type vpc_attribution_value -type vrf_direction_counter -type vrf_traffic_value Usid usid.c diff --git a/internal/plumbing/ebpf/prog/usid.c b/internal/plumbing/ebpf/prog/usid.c index c87feac13..03d606d75 100644 --- a/internal/plumbing/ebpf/prog/usid.c +++ b/internal/plumbing/ebpf/prog/usid.c @@ -429,6 +429,43 @@ struct vpc_attribution_value { __u64 generation; }; +// struct vrf_direction_counter is one direction's traffic for one VRF. +// +// packets and bytes count a packet once, when the program has committed to +// forwarding it: its redirect succeeded, or, for same-node delivery, it was +// handed to the kernel's VRF routing toward a local attachment. bytes is the +// tenant packet's own length, its IPv4 or IPv6 header and payload, without +// the Ethernet header or any SRv6 outer header, so the two directions measure +// the same thing. A GSO or GRO super-packet counts as one packet carrying all +// of its bytes. +// +// dropped_packets counts the packets dropped after the VRF was resolved, at +// the same points count_claimed_drop bumps vrf_value's own dropped_packets, +// split by the direction the packet was travelling. usid_service_egress's +// drops and a failed public-uplink redirect are counted in drop_reasons only. +struct vrf_direction_counter { + __u64 packets; + __u64 bytes; + __u64 dropped_packets; +}; + +// struct vrf_traffic_value is vrf_traffic_counters' value: one VRF's +// traffic in each direction. ingress is SRv6 traffic usid_ingress +// decapsulated into the VRF, plus same-node traffic delivered to one of its +// attachments. egress is tenant traffic leaving the VRF through usid_egress +// or usid_service_egress, encapsulated onto the fabric, sent to an egress +// shard, sent unencapsulated out the public uplink, or delivered to another +// attachment on this node. +struct vrf_traffic_value { + struct vrf_direction_counter ingress; + struct vrf_direction_counter egress; +}; + +enum vrf_direction { + VRF_DIRECTION_INGRESS = 0, + VRF_DIRECTION_EGRESS = 1, +}; + // --------------------------------------------------------------------- // Per-VRF stateless NPTv6 and the VIP-boundary substitution. Both are consulted // from two places: usid_ingress, inbound, after the strip and before the FIB @@ -1158,6 +1195,24 @@ struct { __type(value, struct vpc_attribution_value); } vpc_attribution_table SEC(".maps"); +// vrf_traffic_counters: see struct vrf_traffic_value. Keyed identically to +// vrf_table (Block<<12|Argument) and sized identically, one row per VRF. +// +// Per CPU: the hot path increments its own CPU's copy with no atomic +// operation and no cache line shared between CPUs, and userspace sums the +// copies. +// +// The datapath only looks rows up, and a missing row counts nothing. +// Userspace creates a row whenever it registers a vrf_table row, removes it +// with that row, and on every GC pass creates any row a vrf_table row lacks +// and removes any row without one. +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_HASH); + __uint(max_entries, 8192); // sized identically to vrf_table: one row per VRF. + __type(key, __u64); + __type(value, struct vrf_traffic_value); +} vrf_traffic_counters SEC(".maps"); + struct { __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); __uint(max_entries, __DROP_REASON_MAX); @@ -1664,13 +1719,95 @@ static USID_ALWAYS_INLINE void record_value(__u32 slot, __u64 value) *cell = value; } +// vrf_direction_counter_for returns this CPU's counter for direction in +// vrf_key's vrf_traffic_counters row, or 0 when the row does not exist. +// noinline keeps its key copy off the callers' stack frames, which the +// Packet-Too-Big call chain leaves little room in. +static USID_NOINLINE struct vrf_direction_counter *vrf_direction_counter_for(__u64 vrf_key, __u32 direction) +{ + struct vrf_traffic_value *v = bpf_map_lookup_elem(&vrf_traffic_counters, &vrf_key); + + if (!v) + return 0; + return direction == VRF_DIRECTION_EGRESS ? &v->egress : &v->ingress; +} + +// count_vrf_forwarded counts one packet of bytes tenant bytes as forwarded in +// direction for vrf_key. A plain increment: the counter is this CPU's own, and +// a TC program runs to completion on its CPU. +static USID_ALWAYS_INLINE void count_vrf_forwarded(__u64 vrf_key, __u32 direction, __u64 bytes) +{ + struct vrf_direction_counter *c = vrf_direction_counter_for(vrf_key, direction); + + if (c) { + c->packets++; + c->bytes += bytes; + } +} + +// count_attachment_forwarded is count_vrf_forwarded for the VRF of the +// attachment whose host-side interface is ifindex, resolved through +// ifindex_vrf_table. An unregistered ifindex counts nothing. +static USID_NOINLINE void count_attachment_forwarded(__u32 ifindex, __u32 direction, __u64 bytes) +{ + struct ifindex_vrf_value *iv = bpf_map_lookup_elem(&ifindex_vrf_table, &ifindex); + + if (iv) + count_vrf_forwarded((iv->block << 12) | iv->argument, direction, bytes); +} + +// tenant_len is the length of the tenant packet in skb, its L3 header and +// payload, for an skb carrying no outer header: everything after the Ethernet +// header. +static USID_ALWAYS_INLINE __u64 tenant_len(const struct __sk_buff *skb) +{ + return skb->len > sizeof(struct usid_ethhdr) ? skb->len - sizeof(struct usid_ethhdr) : 0; +} + +// is_own_gateway reports whether the destination usid_egress copied into +// service_fib_scratch's dest_addr, in family, is one of the IPAM gateway +// addresses of the attachment whose host-side interface is ifindex. An IPv4 +// address occupies the first four bytes. An attachment with no +// tenant_gw_table row has no gateway. It reads the destination itself rather +// than taking a pointer to it, which keeps the verifier's cost for its +// callers flat. +static USID_NOINLINE int is_own_gateway(__u32 ifindex, __u32 family) +{ + __u32 scratch_key = 0; + struct service_fib_scratch_value *scratch = bpf_map_lookup_elem(&service_fib_scratch, &scratch_key); + struct tenant_gw_value *gw = bpf_map_lookup_elem(&tenant_gw_table, &ifindex); + + if (!scratch || !gw) + return 0; + + __u8 diff = 0; + + if (family == USID_EGRESS_ROUTE_FAMILY_INET4) { +#pragma unroll + for (int i = 0; i < 4; i++) + diff |= scratch->dest_addr[i] ^ gw->gw4[i]; + return diff == 0; + } + +#pragma unroll + for (int i = 0; i < 16; i++) + diff |= scratch->dest_addr[i] ^ gw->gw6[i]; + return diff == 0; +} + // count_claimed_drop is count_drop plus the per-entry dropped_packets bump, for // every drop after step 6's vrf_table match, that is, every drop of a packet -// already claimed by a specific tenant. -static USID_ALWAYS_INLINE void count_claimed_drop(__u32 reason, struct vrf_value *vrf) +// already claimed by a specific tenant. It also counts the drop in direction +// for vrf_key in vrf_traffic_counters. +static USID_ALWAYS_INLINE void count_claimed_drop(__u32 reason, struct vrf_value *vrf, __u64 vrf_key, __u32 direction) { count_drop(reason); __sync_fetch_and_add(&vrf->dropped_packets, 1); + + struct vrf_direction_counter *c = vrf_direction_counter_for(vrf_key, direction); + + if (c) + c->dropped_packets++; } // read_be64 composes an 8-byte big-endian buffer into a host-native u64 byte by @@ -2662,11 +2799,11 @@ int usid_ingress(struct __sk_buff *skb) tunnel->version != SERVICE_TUNNEL_VERSION || tunnel->reserved != 0 || (tunnel->direction != SERVICE_TUNNEL_REQUEST && tunnel->direction != SERVICE_TUNNEL_REPLY) || (tunnel->inner_nexthdr != USID_IPPROTO_IPIP && tunnel->inner_nexthdr != USID_IPPROTO_IPV6)) { - count_claimed_drop(DROP_REASON_UNEXPECTED_NEXTHDR, vrf); + count_claimed_drop(DROP_REASON_UNEXPECTED_NEXTHDR, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } if (!service_policy_enabled()) { - count_claimed_drop(DROP_REASON_SERVICE_ROUTE_DENIED, vrf); + count_claimed_drop(DROP_REASON_SERVICE_ROUTE_DENIED, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } __builtin_memcpy(service_scratch->tunnel_grant_id, tunnel->grant_id, 16); @@ -2675,7 +2812,7 @@ int usid_ingress(struct __sk_buff *skb) service_scratch->tunnel_direction = tunnel->direction; } if (!service_tunnel && ip6->nexthdr != USID_IPPROTO_IPIP && ip6->nexthdr != USID_IPPROTO_IPV6) { - count_claimed_drop(DROP_REASON_UNEXPECTED_NEXTHDR, vrf); + count_claimed_drop(DROP_REASON_UNEXPECTED_NEXTHDR, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2684,14 +2821,14 @@ int usid_ingress(struct __sk_buff *skb) // after. __u8 *inner_peek = (__u8 *) (ip6 + 1) + (service_tunnel ? sizeof(struct service_tunnel_header) : 0); if ((void *) inner_peek + 1 > data_end) { - count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf); + count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } __u8 inner_version = (*inner_peek) >> 4; if (inner_version != 4 && inner_version != 6) { - count_claimed_drop(DROP_REASON_UNKNOWN_INNER_VERSION, vrf); + count_claimed_drop(DROP_REASON_UNKNOWN_INNER_VERSION, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2732,7 +2869,7 @@ int usid_ingress(struct __sk_buff *skb) if (inner_version == 4) { if (bpf_skb_change_proto(skb, __builtin_bswap16(USID_ETH_P_IP), 0)) { - count_claimed_drop(DROP_REASON_STRIP_FAILED, vrf); + count_claimed_drop(DROP_REASON_STRIP_FAILED, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } strip_len = (__s32) sizeof(struct usid_iphdr) + (service_tunnel ? (__s32) sizeof(struct service_tunnel_header) : 0); @@ -2741,7 +2878,7 @@ int usid_ingress(struct __sk_buff *skb) if (bpf_skb_adjust_room(skb, -strip_len, BPF_ADJ_ROOM_MAC, strip_flags | decap_flag) && bpf_skb_adjust_room(skb, -strip_len, BPF_ADJ_ROOM_MAC, strip_flags)) { - count_claimed_drop(DROP_REASON_STRIP_FAILED, vrf); + count_claimed_drop(DROP_REASON_STRIP_FAILED, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2771,7 +2908,7 @@ int usid_ingress(struct __sk_buff *skb) // removing the tag is part of the same carve step, and the only way it // fails is the allocation the carve can equally fail on. if (bpf_skb_vlan_pop(skb)) { - count_claimed_drop(DROP_REASON_STRIP_FAILED, vrf); + count_claimed_drop(DROP_REASON_STRIP_FAILED, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2787,7 +2924,7 @@ int usid_ingress(struct __sk_buff *skb) // helpers' invalidation too, and before the NPTv6 and VIP rewrites, whose // checksum updates are incremental and so independent of this one. if (clamp_tcp_mss(skb, inner_version, 0)) { - count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf); + count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2799,7 +2936,7 @@ int usid_ingress(struct __sk_buff *skb) struct usid_ethhdr *new_eth = data; if ((void *) (new_eth + 1) > data_end) { - count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf); + count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2812,7 +2949,7 @@ int usid_ingress(struct __sk_buff *skb) struct usid_ip6hdr *inner6 = (void *) inner; if ((void *) (inner6 + 1) > data_end) { - count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf); + count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2858,7 +2995,7 @@ int usid_ingress(struct __sk_buff *skb) if (apply_vip_xlat(skb, addr_off, port_off, csum_off, inner6->nexthdr, inner6->daddr, ports->dest, vv)) { - count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf); + count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } // The store calls invalidate every previously derived @@ -2870,7 +3007,7 @@ int usid_ingress(struct __sk_buff *skb) new_eth = data; inner6 = (void *) (new_eth + 1); if ((void *) (inner6 + 1) > data_end) { - count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf); + count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } } @@ -2894,7 +3031,7 @@ int usid_ingress(struct __sk_buff *skb) struct usid_iphdr *inner4 = (void *) inner; if ((void *) (inner4 + 1) > data_end) { - count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf); + count_claimed_drop(DROP_REASON_MALFORMED_INNER, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2940,16 +3077,16 @@ int usid_ingress(struct __sk_buff *skb) // peer the way step 9 does, which works for a veth and a tap alike. if (fib_rc != BPF_FIB_LKUP_RET_SUCCESS && fib_rc != BPF_FIB_LKUP_RET_NO_NEIGH) { if (fib_rc == BPF_FIB_LKUP_RET_NO_NEIGH) - count_claimed_drop(DROP_REASON_FIB_NO_NEIGH, vrf); + count_claimed_drop(DROP_REASON_FIB_NO_NEIGH, vrf, vrf_key, VRF_DIRECTION_INGRESS); else if (fib_rc == BPF_FIB_LKUP_RET_UNREACHABLE || fib_rc == BPF_FIB_LKUP_RET_BLACKHOLE || fib_rc == BPF_FIB_LKUP_RET_PROHIBIT) - count_claimed_drop(DROP_REASON_FIB_UNREACHABLE, vrf); + count_claimed_drop(DROP_REASON_FIB_UNREACHABLE, vrf, vrf_key, VRF_DIRECTION_INGRESS); else if (fib_rc == BPF_FIB_LKUP_RET_FRAG_NEEDED) // No ICMPv6 Packet Too Big is generated here, unlike the static // route path this replaces: an accepted PMTUD gap, recorded in // the CNI architecture doc's known constraints. - count_claimed_drop(DROP_REASON_FIB_FRAG_NEEDED, vrf); + count_claimed_drop(DROP_REASON_FIB_FRAG_NEEDED, vrf, vrf_key, VRF_DIRECTION_INGRESS); else - count_claimed_drop(DROP_REASON_FIB_LOOKUP_FAILED, vrf); + count_claimed_drop(DROP_REASON_FIB_LOOKUP_FAILED, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2959,7 +3096,7 @@ int usid_ingress(struct __sk_buff *skb) record_value(DROP_REASON_TRACE_ING_LAST_IFINDEX, (__u64) fib_params.ifindex); if (fib_params.ifindex <= 0) { - count_claimed_drop(DROP_REASON_FIB_NO_IFINDEX, vrf); + count_claimed_drop(DROP_REASON_FIB_NO_IFINDEX, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -2967,7 +3104,7 @@ int usid_ingress(struct __sk_buff *skb) int authorization = service_ingress_authorize(skb, new_eth->h_proto, fib_params.ifindex, service_scratch); if (authorization < 0) { - count_claimed_drop(DROP_REASON_SERVICE_ROUTE_DENIED, vrf); + count_claimed_drop(DROP_REASON_SERVICE_ROUTE_DENIED, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } service_reverse_installed = authorization; @@ -2988,11 +3125,13 @@ int usid_ingress(struct __sk_buff *skb) nh.ipv4_nh = fib_params.ipv4_dst; } long neigh_rc = bpf_redirect_neigh(fib_params.ifindex, &nh, sizeof(nh), 0); - if (neigh_rc == TC_ACT_REDIRECT) + if (neigh_rc == TC_ACT_REDIRECT) { + count_vrf_forwarded(vrf_key, VRF_DIRECTION_INGRESS, tenant_len(skb)); return neigh_rc; + } if (service_reverse_installed && service_scratch) bpf_map_delete_elem(&service_reverse_table, &service_scratch->reverse); - count_claimed_drop(DROP_REASON_FIB_NO_NEIGH, vrf); + count_claimed_drop(DROP_REASON_FIB_NO_NEIGH, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } @@ -3025,12 +3164,19 @@ int usid_ingress(struct __sk_buff *skb) if (redirect_rc != TC_ACT_REDIRECT) { if (service_reverse_installed && service_scratch) bpf_map_delete_elem(&service_reverse_table, &service_scratch->reverse); - count_claimed_drop(DROP_REASON_REDIRECT_FAILED, vrf); + count_claimed_drop(DROP_REASON_REDIRECT_FAILED, vrf, vrf_key, VRF_DIRECTION_INGRESS); return TC_ACT_SHOT; } count_drop(DROP_REASON_TRACE_ING_REDIRECT_OK); // TEMPORARY + // Inbound is counted here and on the cold-neighbor redirect above, once the + // packet is on its way to the attachment, and measured after the strip, so + // it is the tenant packet alone. vrf_value's own packets and bytes, bumped + // at step 6, count every claimed packet including the ones dropped since, + // and the whole tunneled frame. + count_vrf_forwarded(vrf_key, VRF_DIRECTION_INGRESS, tenant_len(skb)); + return redirect_rc; } @@ -3244,7 +3390,15 @@ static USID_NOINLINE long service_remote_encap(struct __sk_buff *skb, eth->h_proto = __builtin_bswap16(USID_ETH_P_IPV6); __builtin_memcpy(eth->h_dest, uplink->dmac, 6); __builtin_memcpy(eth->h_source, uplink->smac, 6); - return bpf_redirect(uplink->link_ifindex, 0); + + // Counted here rather than by the caller, which also sees TC_ACT_REDIRECT + // for a Packet Too Big sent back to the tenant instead of this packet. + long rc = bpf_redirect(uplink->link_ifindex, 0); + + if (rc == TC_ACT_REDIRECT) + count_vrf_forwarded(vrf_key, VRF_DIRECTION_EGRESS, + skb->len - sizeof(*eth) - sizeof(*outer) - sizeof(*tunnel)); + return rc; } static USID_NOINLINE int service_install_reverse(struct service_fib_scratch_value *s) @@ -3362,6 +3516,18 @@ static USID_ALWAYS_INLINE int service_rewrite_address(struct __sk_buff *skb, return 0; } +// count_service_local counts a service packet service_redirect delivered from +// the attachment on from_ifindex straight to the one on to_ifindex: outbound +// for the sender's VRF and inbound for the receiver's, which may belong to +// different VPCs. No other program sees the packet on its way. +static USID_ALWAYS_INLINE void count_service_local(const struct __sk_buff *skb, __u32 from_ifindex, __u32 to_ifindex) +{ + __u64 len = tenant_len(skb); + + count_attachment_forwarded(from_ifindex, VRF_DIRECTION_EGRESS, len); + count_attachment_forwarded(to_ifindex, VRF_DIRECTION_INGRESS, len); +} + // service_path is noinline so its transient tuple-building scalars do not // inflate usid_egress's already tight stack on the unrelated encapsulation and // Packet-Too-Big call chain. @@ -3493,6 +3659,7 @@ static USID_NOINLINE long service_path(struct __sk_buff *skb, __be16 h_proto, __ count_drop(DROP_REASON_SERVICE_ROUTE_REDIRECT_FAILED); return TC_ACT_SHOT; } + count_service_local(skb, ifindex, consumer_ifindex); return rc; } @@ -3586,6 +3753,7 @@ static USID_NOINLINE long service_path(struct __sk_buff *skb, __be16 h_proto, __ count_drop(DROP_REASON_SERVICE_ROUTE_REDIRECT_FAILED); return TC_ACT_SHOT; } + count_service_local(skb, ifindex, target_ifindex); return rc; } @@ -3932,9 +4100,9 @@ int usid_egress(struct __sk_buff *skb) // the client silently discards it. // // No claimed-drop count on failure here, unlike the - // egress route redirect path below: vrf_table's value is - // not resolved yet at this point, and this path is - // expected essentially never to fire. + // egress route redirect path below: this path is + // expected essentially never to fire, and its drop + // reason is enough to find it. // A DSR backend's SYN-ACK leaves here, and the // client's segments then reach the backend // encapsulated by the gateway. Clamping it is what @@ -3969,6 +4137,7 @@ int usid_egress(struct __sk_buff *skb) count_drop(DROP_REASON_PUBLIC_UPLINK_REDIRECT_FAILED); return TC_ACT_SHOT; } + count_vrf_forwarded(vrf_key, VRF_DIRECTION_EGRESS, tenant_len(skb)); return redirect_rc; } // public_uplink_table is not configured yet, so this node @@ -4065,8 +4234,22 @@ int usid_egress(struct __sk_buff *skb) // through the trie, not to be encapsulated toward. Defer to the kernel like // a genuine miss, before touching node_src_addr_table or doing any encap // work. + // + // Every pass-through prefix is a guest prefix or gateway address of an + // attachment in this same Linux VRF, and this node keeps one VRF, and one + // vrf_table row, per VPC. So a packet for anything but this attachment's + // own gateway is another attachment's on this node: it leaves the sender's + // VRF and arrives in the receiver's, which is the same row, and no other + // program sees it, usid_ingress included. It is counted here once in each + // direction, as handed to the kernel for delivery. if (rv->link_ifindex == 0) { count_drop(DROP_REASON_TRACE_PASSTHROUGH_ENTRY); + if (!is_own_gateway(ifindex, route_family)) { + __u64 len = tenant_len(skb); + + count_vrf_forwarded(vrf_key, VRF_DIRECTION_EGRESS, len); + count_vrf_forwarded(vrf_key, VRF_DIRECTION_INGRESS, len); + } return TC_ACT_UNSPEC; } @@ -4123,7 +4306,7 @@ int usid_egress(struct __sk_buff *skb) // is wrong, so it is dropped rather than sent, and counted with the encap // failure it is part of. mss_clamp_stats records which it was. if (clamp_tcp_mss(skb, route_family == USID_EGRESS_ROUTE_FAMILY_INET6 ? 6 : 4, 0)) { - count_claimed_drop(DROP_REASON_EGRESS_ROUTE_ENCAP_FAILED, vrf); + count_claimed_drop(DROP_REASON_EGRESS_ROUTE_ENCAP_FAILED, vrf, vrf_key, VRF_DIRECTION_EGRESS); return TC_ACT_SHOT; } @@ -4137,7 +4320,7 @@ int usid_egress(struct __sk_buff *skb) if (pmtu == PMTU_SENT) return TC_ACT_REDIRECT; if (pmtu == PMTU_DROPPED) { - count_claimed_drop(DROP_REASON_FIB_FRAG_NEEDED, vrf); + count_claimed_drop(DROP_REASON_FIB_FRAG_NEEDED, vrf, vrf_key, VRF_DIRECTION_EGRESS); return TC_ACT_SHOT; } @@ -4173,7 +4356,7 @@ int usid_egress(struct __sk_buff *skb) if (bpf_skb_adjust_room(skb, outer_len, BPF_ADJ_ROOM_MAC, USID_BPF_F_ADJ_ROOM_ENCAP_L3_IPV6) && bpf_skb_adjust_room(skb, outer_len, BPF_ADJ_ROOM_MAC, 0)) { - count_claimed_drop(DROP_REASON_EGRESS_ROUTE_ENCAP_FAILED, vrf); + count_claimed_drop(DROP_REASON_EGRESS_ROUTE_ENCAP_FAILED, vrf, vrf_key, VRF_DIRECTION_EGRESS); return TC_ACT_SHOT; } count_drop(DROP_REASON_TRACE_ADJUST_ROOM_OK); @@ -4184,14 +4367,14 @@ int usid_egress(struct __sk_buff *skb) struct usid_ethhdr *new_eth = data; if ((void *) (new_eth + 1) > data_end) { - count_claimed_drop(DROP_REASON_EGRESS_ROUTE_ENCAP_FAILED, vrf); + count_claimed_drop(DROP_REASON_EGRESS_ROUTE_ENCAP_FAILED, vrf, vrf_key, VRF_DIRECTION_EGRESS); return TC_ACT_SHOT; } struct usid_ip6hdr *outer = (void *) (new_eth + 1); if ((void *) (outer + 1) > data_end) { - count_claimed_drop(DROP_REASON_EGRESS_ROUTE_ENCAP_FAILED, vrf); + count_claimed_drop(DROP_REASON_EGRESS_ROUTE_ENCAP_FAILED, vrf, vrf_key, VRF_DIRECTION_EGRESS); return TC_ACT_SHOT; } @@ -4232,11 +4415,15 @@ int usid_egress(struct __sk_buff *skb) long redirect_rc = bpf_redirect(rv->link_ifindex, 0); if (redirect_rc != TC_ACT_REDIRECT) { - count_claimed_drop(DROP_REASON_EGRESS_ROUTE_REDIRECT_FAILED, vrf); + count_claimed_drop(DROP_REASON_EGRESS_ROUTE_REDIRECT_FAILED, vrf, vrf_key, VRF_DIRECTION_EGRESS); return TC_ACT_SHOT; } count_drop(DROP_REASON_TRACE_REDIRECT_OK); + // From skb->len rather than inner_len, whose 16 bits cannot hold a BIG TCP + // GSO packet's length. + count_vrf_forwarded(vrf_key, VRF_DIRECTION_EGRESS, + skb->len - sizeof(struct usid_ethhdr) - sizeof(struct usid_ip6hdr)); return redirect_rc; } diff --git a/internal/plumbing/ebpf/prog/usid_vrftraffic_test.go b/internal/plumbing/ebpf/prog/usid_vrftraffic_test.go new file mode 100644 index 000000000..813335658 --- /dev/null +++ b/internal/plumbing/ebpf/prog/usid_vrftraffic_test.go @@ -0,0 +1,268 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package prog + +import ( + "math/bits" + "net/netip" + "testing" + + "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/uformat" +) + +// putVRFTraffic creates key's zeroed vrf_traffic_counters row, as userspace +// does when it registers the vrf_table row. +func putVRFTraffic(t *testing.T, objs *UsidObjects, key uint64) { + t.Helper() + n, err := ebpf.PossibleCPU() + if err != nil { + t.Fatalf("PossibleCPU: %v", err) + } + if err := objs.VrfTrafficCounters.Put(key, make([]UsidVrfTrafficValue, n)); err != nil { + t.Fatalf("populate vrf_traffic_counters: %v", err) + } +} + +// vrfTraffic returns key's vrf_traffic_counters row summed across CPUs. +func vrfTraffic(t *testing.T, objs *UsidObjects, key uint64) UsidVrfTrafficValue { + t.Helper() + var perCPU []UsidVrfTrafficValue + if err := objs.VrfTrafficCounters.Lookup(key, &perCPU); err != nil { + t.Fatalf("look up vrf_traffic_counters: %v", err) + } + var sum UsidVrfTrafficValue + for _, v := range perCPU { + sum.Ingress.Packets += v.Ingress.Packets + sum.Ingress.Bytes += v.Ingress.Bytes + sum.Ingress.DroppedPackets += v.Ingress.DroppedPackets + sum.Egress.Packets += v.Egress.Packets + sum.Egress.Bytes += v.Egress.Bytes + sum.Egress.DroppedPackets += v.Egress.DroppedPackets + } + return sum +} + +func assertVRFTraffic(t *testing.T, objs *UsidObjects, key uint64, want UsidVrfTrafficValue, label string) { + t.Helper() + if got := vrfTraffic(t, objs, key); got != want { + t.Errorf("%s: vrf_traffic_counters = %+v, want %+v", label, got, want) + } +} + +func direction(packets, bytes, drops uint64) UsidVrfDirectionCounter { + return UsidVrfDirectionCounter{Packets: packets, Bytes: bytes, DroppedPackets: drops} +} + +func vrfKeyOf(t *testing.T, block uint64, argument uint16) uint64 { + t.Helper() + key, err := uformat.NewVRFKey(block, argument) + if err != nil { + t.Fatalf("NewVRFKey: %v", err) + } + return uint64(key) +} + +// redirectLabInnerLen is the tenant packet redirectLab.send builds toward an +// IPv4 destination: a 20-byte header and a 64-byte payload. +const redirectLabInnerLen = 20 + 64 + +// A decapsulated packet counts once as inbound, at its tenant length, for +// both a veth and a tap attachment. +func TestUsidIngress_VRFTrafficCountsDelivery(t *testing.T) { + lab := newRedirectLab(t) + lab.registerTap(t) + lab.registerVeth(t) + key := baseUSID.vrfKey() + putVRFTraffic(t, lab.objs, key) + + lab.assertVethDelivers(t, "veth", true) + assertVRFTraffic(t, lab.objs, key, + UsidVrfTrafficValue{Ingress: direction(1, redirectLabInnerLen, 0)}, "after one veth delivery") + + lab.assertTapDelivers(t, "tap") + assertVRFTraffic(t, lab.objs, key, + UsidVrfTrafficValue{Ingress: direction(2, 2*redirectLabInnerLen, 0)}, "after a tap delivery") +} + +// A packet dropped after its VRF was resolved counts as an inbound drop, not +// as forwarded. +func TestUsidIngress_VRFTrafficCountsClaimedDrop(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + + usid := testUSID{block: baseUSID.block, nodeID: baseUSID.nodeID, function: uformat.FunctionEndDT46, argument: 0x125} + if err := objs.LocatorTable.Put(usid.locatorKey(t), UsidLocatorValue{Generation: 1}); err != nil { + t.Fatalf("populate locator_table: %v", err) + } + if err := objs.FunctionTable.Put(usid.functionKey(t), UsidFunctionValue{Behavior: 1}); err != nil { + t.Fatalf("populate function_table: %v", err) + } + if err := objs.VrfTable.Put(usid.vrfKey(), UsidVrfValue{VrfTableId: 0x2C2C2C}); err != nil { + t.Fatalf("populate vrf_table: %v", err) + } + putVRFTraffic(t, objs, usid.vrfKey()) + + pkt := buildPacketWithInner(t, usid.addr(t), netip.MustParseAddr("2001:db8::1"), innerUnknownVersion) + if ret, _, err := objs.UsidIngress.Test(pkt); err != nil || ret != tcActShot { + t.Fatalf("verdict = %d, err = %v; want TC_ACT_SHOT", ret, err) + } + assertVRFTraffic(t, objs, usid.vrfKey(), UsidVrfTrafficValue{Ingress: direction(0, 0, 1)}, "after a claimed drop") +} + +// An unregistered row counts nothing and does not change the verdict. +func TestUsidIngress_VRFTrafficMissingRowCountsNothing(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + + usid := testUSID{block: baseUSID.block, nodeID: baseUSID.nodeID, function: uformat.FunctionEndDT46, argument: 0x125} + if err := objs.LocatorTable.Put(usid.locatorKey(t), UsidLocatorValue{Generation: 1}); err != nil { + t.Fatalf("populate locator_table: %v", err) + } + if err := objs.FunctionTable.Put(usid.functionKey(t), UsidFunctionValue{Behavior: 1}); err != nil { + t.Fatalf("populate function_table: %v", err) + } + if err := objs.VrfTable.Put(usid.vrfKey(), UsidVrfValue{VrfTableId: 0x2C2C2C}); err != nil { + t.Fatalf("populate vrf_table: %v", err) + } + + pkt := buildPacketWithInner(t, usid.addr(t), netip.MustParseAddr("2001:db8::1"), innerUnknownVersion) + if ret, _, err := objs.UsidIngress.Test(pkt); err != nil || ret != tcActShot { + t.Fatalf("verdict = %d, err = %v; want TC_ACT_SHOT", ret, err) + } + var perCPU []UsidVrfTrafficValue + if err := objs.VrfTrafficCounters.Lookup(usid.vrfKey(), &perCPU); err == nil { + t.Error("the datapath created a vrf_traffic_counters row; only userspace may") + } +} + +// An encapsulated packet counts once as outbound, at its tenant length, not +// the encapsulated length. +func TestUsidEgress_VRFTrafficCountsEncapsulation(t *testing.T) { + objs := egressClampFixture(t) + key := vrfKeyOf(t, 0x123456, 0x210) + putVRFTraffic(t, objs, key) + + runEgressExpect(t, objs, v6Packet(mssPodV6, mssRemoteV6, ipProtoUDP, 200), tcActRedirect) + assertVRFTraffic(t, objs, key, UsidVrfTrafficValue{Egress: direction(1, 200, 0)}, "after an IPv6 packet") + + runEgressExpect(t, objs, v4Packet(ipProtoUDP, nil, true, 120), tcActRedirect) + assertVRFTraffic(t, objs, key, UsidVrfTrafficValue{Egress: direction(2, 320, 0)}, "after an IPv4 packet") +} + +// A packet the PMTU check drops counts as an outbound drop. +func TestUsidEgress_VRFTrafficCountsClaimedDrop(t *testing.T) { + objs := pmtuFixture(t) + key := vrfKeyOf(t, 0x123456, 0x210) + putVRFTraffic(t, objs, key) + + runEgressExpect(t, objs, v4Packet(ipProtoUDP, nil, false, 1500), tcActShot) + assertVRFTraffic(t, objs, key, UsidVrfTrafficValue{Egress: direction(0, 0, 1)}, "after a claimed drop") +} + +// Traffic between two attachments on one node never reaches usid_ingress. +// The sender's usid_egress hands it to the kernel through the receiver's local +// pass-through entry, and both attachments share the VPC's VRF row, so it +// counts once in each direction there. Traffic to the sender's own gateway is +// for the host, not another attachment, and counts in neither. +func TestUsidEgress_VRFTrafficSameNodeCountsOncePerDirection(t *testing.T) { + const ( + block = 0xABCDEF + argument = 0x100 + tableID = 7 + ) + peer6 := netip.MustParseAddr("fd20:70::2") + peer4 := netip.MustParseAddr("172.21.1.6") + + for _, tt := range []struct { + name string + pkt []byte + counted bool + }{ + {name: "IPv6 peer", pkt: v6Packet(mssPodV6, peer6, ipProtoUDP, 100), counted: true}, + {name: "IPv4 peer", pkt: withEth(0x0800, ip4TCP(mssPodV4, peer4, nil, 0, l4Datagram(ipProtoUDP, 72))), counted: true}, + {name: "IPv6 own gateway", pkt: v6Packet(mssPodV6, pmtuGW6, ipProtoUDP, 100)}, + {name: "IPv4 own gateway", pkt: withEth(0x0800, ip4TCP(mssPodV4, pmtuGW4, nil, 0, l4Datagram(ipProtoUDP, 72)))}, + } { + t.Run(tt.name, func(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + setUpEgressRouteAttachment(t, objs, block, argument, tableID) + setUpNodeSIDBase(t, objs, netip.MustParseAddr("2001:db8:ff01:1:e000::"), argument) + if err := objs.TenantGwTable.Put(uint32(1), UsidTenantGwValue{Gw6: pmtuGW6.As16(), Gw4: pmtuGW4.As4()}); err != nil { + t.Fatalf("populate tenant_gw_table: %v", err) + } + for _, k := range []UsidEgressRouteKey{ + egressRouteKey(tableID, egressRouteFamilyINET6, peer6, 128), + egressRouteKey(tableID, egressRouteFamilyINET6, pmtuGW6, 128), + egressRouteKey(tableID, egressRouteFamilyINET4, peer4, 32), + egressRouteKey(tableID, egressRouteFamilyINET4, pmtuGW4, 32), + } { + if err := objs.EgressRouteTable.Put(k, UsidEgressRouteValue{}); err != nil { + t.Fatalf("populate pass-through route: %v", err) + } + } + key := vrfKeyOf(t, block, argument) + putVRFTraffic(t, objs, key) + + if ret, _, err := objs.UsidEgress.Test(tt.pkt); err != nil || ret != tcActUnspec { + t.Fatalf("verdict = %d, err = %v; want TC_ACT_UNSPEC", ret, err) + } + var want UsidVrfTrafficValue + if tt.counted { + l3 := uint64(len(tt.pkt) - ethHeaderLen) + want = UsidVrfTrafficValue{Ingress: direction(1, l3, 0), Egress: direction(1, l3, 0)} + } + assertVRFTraffic(t, objs, key, want, tt.name) + }) + } +} + +// A service packet delivered straight to another attachment on this node +// counts as outbound for the sender's VRF and inbound for the receiver's. In +// this fixture both are the attachment on ifindex 1. +func TestUsidServiceEgress_VRFTrafficCountsLocalDelivery(t *testing.T) { + requireRoot(t) + objs := loadObjects(t) + + const ( + tableID = uint32(7) + loopback = uint32(1) + servicePort = uint16(8443) + ) + setUpEgressRouteAttachment(t, objs, 0xABCDEF, 0x100, tableID) + setServiceIdentity(t, objs, 1) + key := vrfKeyOf(t, 0xABCDEF, 0x100) + putVRFTraffic(t, objs, key) + + service := netip.MustParseAddr("fd20:70::100") + frontend := netip.MustParseAddr("fd53::53") + if err := objs.ServiceRouteTable.Put( + serviceRouteKey(frontend), + UsidServiceRouteValue{ + TargetIfindex: loopback, Mode: 1, ConsumerToken: 1, ProducerToken: 1, BackendAddr: service.As16(), + }, + ); err != nil { + t.Fatalf("populate service_route_table: %v", err) + } + if err := objs.ServiceAccessTable.Put(UsidServiceAccessKey{ + IngressIfindex: loopback, + Family: egressRouteFamilyINET6, + Protocol: 6, + Port: bits.ReverseBytes16(servicePort), + Addr: frontend.As16(), + }, UsidServiceAccessValue{AttachmentToken: 1}); err != nil { + t.Fatalf("populate service_access_table: %v", err) + } + + pkt := buildPlainV6PacketWithL4Ports(t, netip.MustParseAddr("fd20:70::2"), frontend, 49152, servicePort) + if ret, _, err := objs.UsidServiceEgress.Test(pkt); err != nil || ret != tcActRedirect { + t.Fatalf("verdict = %d, err = %v; want TC_ACT_REDIRECT", ret, err) + } + l3 := uint64(len(pkt) - ethHeaderLen) + assertVRFTraffic(t, objs, key, + UsidVrfTrafficValue{Ingress: direction(1, l3, 0), Egress: direction(1, l3, 0)}, "after one local delivery") +} diff --git a/internal/plumbing/ebpf/usidmap/kernel_test.go b/internal/plumbing/ebpf/usidmap/kernel_test.go index 726010bcc..f5403f81c 100644 --- a/internal/plumbing/ebpf/usidmap/kernel_test.go +++ b/internal/plumbing/ebpf/usidmap/kernel_test.go @@ -170,3 +170,60 @@ func TestKernelTable_FunctionTable_RealMap(t *testing.T) { t.Errorf("Get after Unregister (real map): ok=%v err=%v, want ok=false", ok, err) } } + +// TestKernelCounterTable_VRFTraffic_RealMap exercises VRFTrafficTable against +// the kernel-loaded per-CPU vrf_traffic_counters through the registry: a row +// created at registration, a repeat registration that keeps the counts the +// datapath wrote on two CPUs, the per-CPU sum List reports, and removal at +// unregistration. +func TestKernelCounterTable_VRFTraffic_RealMap(t *testing.T) { + requireRoot(t) + objs := loadTestObjects(t) + reg := NewRegistryFromObjects(objs) + const argument = 0x0AB + + if err := reg.VRF.Register(testBlock, argument, 7, EgressKindVeth); err != nil { + t.Fatalf("Register: %v", err) + } + key, err := uformat.NewVRFKey(testBlock, argument) + if err != nil { + t.Fatal(err) + } + cpus, err := ebpf.PossibleCPU() + if err != nil { + t.Fatal(err) + } + if cpus < 2 { + t.Skip("needs two possible CPUs to show per-CPU summing") + } + perCPU := make([]prog.UsidVrfTrafficValue, cpus) + perCPU[0].Ingress = prog.UsidVrfDirectionCounter{Packets: 2, Bytes: 200} + perCPU[1].Ingress = prog.UsidVrfDirectionCounter{Packets: 3, Bytes: 300, DroppedPackets: 1} + perCPU[1].Egress = prog.UsidVrfDirectionCounter{Packets: 4, Bytes: 400} + if err := objs.VrfTrafficCounters.Put(uint64(key), perCPU); err != nil { + t.Fatalf("stand in for the datapath's counts: %v", err) + } + + if err := reg.VRF.Register(testBlock, argument, 7, EgressKindVeth); err != nil { + t.Fatalf("re-Register: %v", err) + } + entries, err := reg.Traffic.List() + if err != nil { + t.Fatalf("List: %v", err) + } + want := VRFTrafficEntry{ + VRFKey: VRFKey{Block: testBlock, Argument: argument}, + Ingress: VRFTrafficCounters{Packets: 5, Bytes: 500, DroppedPackets: 1}, + Egress: VRFTrafficCounters{Packets: 4, Bytes: 400}, + } + if len(entries) != 1 || entries[0] != want { + t.Fatalf("List = %+v, want [%+v]", entries, want) + } + + if err := reg.VRF.Unregister(testBlock, argument); err != nil { + t.Fatalf("Unregister: %v", err) + } + if entries, err := reg.Traffic.List(); err != nil || len(entries) != 0 { + t.Errorf("List after Unregister = %+v, %v; want no rows", entries, err) + } +} diff --git a/internal/plumbing/ebpf/usidmap/registry.go b/internal/plumbing/ebpf/usidmap/registry.go index 4f3981fa4..18ada1e01 100644 --- a/internal/plumbing/ebpf/usidmap/registry.go +++ b/internal/plumbing/ebpf/usidmap/registry.go @@ -5,7 +5,10 @@ package usidmap import ( + "errors" "fmt" + "log/slog" + "os" "path/filepath" "github.com/cilium/ebpf" @@ -25,16 +28,22 @@ type Registry struct { // counter-schema-independent companion to VRF, keyed identically. See // VPCAttributionTable's doc comment. VPCAttribution *VPCAttributionTable + + // Traffic is vrf_traffic_counters' read/write API, nil when the map is + // not pinned. VRF already keeps its rows in step with vrf_table's. + Traffic *VRFTrafficTable } // NewRegistryFromObjects builds a Registry backed by objs's kernel-loaded // maps. func NewRegistryFromObjects(objs *prog.UsidObjects) *Registry { + traffic := NewVRFTrafficTable(KernelCounterTable{Map: objs.VrfTrafficCounters}) return &Registry{ - VRF: NewVRFTable(KernelTable{Map: objs.VrfTable}), + VRF: NewVRFTable(KernelTable{Map: objs.VrfTable}).WithTraffic(traffic), Locator: NewLocatorTable(KernelTable{Map: objs.LocatorTable}), Function: NewFunctionTable(KernelTable{Map: objs.FunctionTable}), VPCAttribution: NewVPCAttributionTable(KernelTable{Map: objs.VpcAttributionTable}), + Traffic: traffic, } } @@ -51,7 +60,8 @@ func (p pinnedMaps) Close() error { return nil } -// OpenPinnedRegistry opens the four control-plane maps from their pinned paths +// OpenPinnedRegistry opens the four control-plane maps, and vrf_traffic_counters +// when it is pinned, from their pinned paths // under pinDir and returns a Registry wrapping them, for a short-lived process // that did not itself load the datapath but needs to read and write its maps. // The returned closer must be closed when the caller is done; the maps stay @@ -89,10 +99,25 @@ func OpenPinnedRegistry(pinDir string) (*Registry, pinnedMaps, error) { } closer := pinnedMaps{vrfMap, locatorMap, functionMap, vpcAttributionMap} - return &Registry{ + registry := &Registry{ VRF: NewVRFTable(KernelTable{Map: vrfMap}), Locator: NewLocatorTable(KernelTable{Map: locatorMap}), Function: NewFunctionTable(KernelTable{Map: functionMap}), VPCAttribution: NewVPCAttributionTable(KernelTable{Map: vpcAttributionMap}), - }, closer, nil + } + + // vrf_traffic_counters is optional: a datapath loaded by an older + // galactic-cni has not pinned it, and nothing that forwards depends on it, + // so no failure to open it fails the caller. + trafficMap, err := ebpf.LoadPinnedMap(filepath.Join(pinDir, prog.UsidMapVrfTrafficCounters), nil) + switch { + case err == nil: + closer = append(closer, trafficMap) + registry.Traffic = NewVRFTrafficTable(KernelCounterTable{Map: trafficMap}) + registry.VRF.WithTraffic(registry.Traffic) + case !errors.Is(err, os.ErrNotExist): + slog.Warn("usidmap: could not open the pinned per-VRF traffic counters; continuing without them", + "map", prog.UsidMapVrfTrafficCounters, "err", err) + } + return registry, closer, nil } diff --git a/internal/plumbing/ebpf/usidmap/vrf.go b/internal/plumbing/ebpf/usidmap/vrf.go index 11bff8e8b..d854af743 100644 --- a/internal/plumbing/ebpf/usidmap/vrf.go +++ b/internal/plumbing/ebpf/usidmap/vrf.go @@ -7,6 +7,7 @@ package usidmap import ( "errors" "fmt" + "log/slog" "github.com/cilium/ebpf" @@ -57,6 +58,11 @@ type VRFEntry struct { type VRFTable struct { table Table clock func() uint64 + + // traffic is nil unless set by WithTraffic, in which case Register, + // Unregister and Reconcile keep vrf_traffic_counters' rows in step with + // this table's. + traffic *VRFTrafficTable } // NewVRFTable wraps table as a VRFTable. Production callers pass a kernel table @@ -66,6 +72,14 @@ func NewVRFTable(table Table) *VRFTable { return &VRFTable{table: table, clock: clockFn} } +// WithTraffic makes t keep traffic's rows in step with its own: Register +// creates (block, argument)'s row when absent, Unregister removes it, and +// Reconcile brings every row into line with vrf_table. It returns t. +func (t *VRFTable) WithTraffic(traffic *VRFTrafficTable) *VRFTable { + t.traffic = traffic + return t +} + // Generation returns a snapshot of this table's monotonic clock. A caller must // read it immediately before listing CRDs to build Reconcile's live set, and // pass the result as that call's cutoff. See the package doc comment for why the @@ -118,6 +132,13 @@ func (t *VRFTable) Register(block uint64, argument uint16, vrfTableID uint32, eg if err := t.table.Put(uint64(key), value); err != nil { return fmt.Errorf("usidmap: vrf_table: register block=%#x argument=%#x: %w", block, argument, err) } + if t.traffic != nil { + if err := t.traffic.Ensure(block, argument); err != nil { + slog.Warn("usidmap: could not create this VRF's traffic counters; "+ + "its per-direction metrics stay absent until the next GC pass creates them", + "block", block, "argument", argument, "err", err) + } + } return nil } @@ -130,12 +151,15 @@ func (t *VRFTable) Unregister(block uint64, argument uint16) error { if err != nil { return fmt.Errorf("usidmap: vrf_table: unregister block=%#x argument=%#x: %w", block, argument, err) } - if err := t.table.Delete(uint64(key)); err != nil { - if errors.Is(err, ebpf.ErrKeyNotExist) { - return nil - } + if err := t.table.Delete(uint64(key)); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { return fmt.Errorf("usidmap: vrf_table: unregister block=%#x argument=%#x: %w", block, argument, err) } + if t.traffic != nil { + if err := t.traffic.Remove(block, argument); err != nil { + slog.Warn("usidmap: could not remove this VRF's traffic counters; the next GC pass removes them", + "block", block, "argument", argument, "err", err) + } + } return nil } @@ -210,6 +234,8 @@ func (t *VRFTable) List() ([]VRFEntry, error) { // // Every stale candidate is attempted even if deleting one fails, with the errors // joined; removed lists everything actually deleted regardless. +// +// It then calls SyncTraffic, whose error it joins to its own. func (t *VRFTable) Reconcile(live map[VRFKey]struct{}, cutoff uint64) (removed []VRFEntry, err error) { entries, err := t.List() if err != nil { @@ -217,6 +243,11 @@ func (t *VRFTable) Reconcile(live map[VRFKey]struct{}, cutoff uint64) (removed [ } var errs []error + defer func() { + if syncErr := t.SyncTraffic(); syncErr != nil { + err = errors.Join(err, fmt.Errorf("usidmap: vrf_table: reconcile: %w", syncErr)) + } + }() for _, e := range entries { if _, ok := live[e.VRFKey]; ok { continue // still has a live BGPVRFInstance per the CRD snapshot @@ -235,3 +266,30 @@ func (t *VRFTable) Reconcile(live map[VRFKey]struct{}, cutoff uint64) (removed [ } return removed, errors.Join(errs...) } + +// SyncTraffic brings vrf_traffic_counters into line with vrf_table when +// WithTraffic is set: it creates a zeroed row for every vrf_table row missing +// one, which covers rows registered before that map existed or while it was +// unavailable, and removes every row vrf_table has none for. Without +// WithTraffic it does nothing. +func (t *VRFTable) SyncTraffic() error { + if t.traffic == nil { + return nil + } + entries, err := t.List() + if err != nil { + return fmt.Errorf("usidmap: vrf_table: sync traffic counters: %w", err) + } + want := make(map[VRFKey]struct{}, len(entries)) + for _, e := range entries { + want[e.VRFKey] = struct{}{} + } + stillWanted := func(k VRFKey) (bool, error) { + _, ok, err := t.Get(k.Block, k.Argument) + return ok, err + } + if _, _, err := t.traffic.Sync(want, stillWanted); err != nil { + return fmt.Errorf("usidmap: vrf_table: sync traffic counters: %w", err) + } + return nil +} diff --git a/internal/plumbing/ebpf/usidmap/vrftraffic.go b/internal/plumbing/ebpf/usidmap/vrftraffic.go new file mode 100644 index 000000000..4687a4a48 --- /dev/null +++ b/internal/plumbing/ebpf/usidmap/vrftraffic.go @@ -0,0 +1,224 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package usidmap + +import ( + "errors" + "fmt" + + "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/ebpf/uformat" +) + +// VRFTrafficCounters is one direction's traffic for one VRF, summed across +// every CPU: packets and bytes forwarded, and packets dropped after the VRF +// was resolved. Bytes counts the tenant packet alone, its IP header and +// payload, in both directions. +type VRFTrafficCounters struct { + Packets uint64 + Bytes uint64 + DroppedPackets uint64 +} + +// VRFTrafficEntry is one decoded vrf_traffic_counters row. +type VRFTrafficEntry struct { + VRFKey + + // Ingress is traffic delivered into the VRF: decapsulated from the fabric, + // or sent by another attachment on this node. + Ingress VRFTrafficCounters + + // Egress is traffic leaving the VRF: encapsulated onto the fabric or toward + // an egress shard, sent out the public uplink, or delivered to another + // attachment on this node. + Egress VRFTrafficCounters +} + +// CounterTable is the map-operation surface VRFTrafficTable is written +// against. It differs from Table in creating rows only when absent, so +// registering a VRF again never resets the counters the datapath has +// accumulated for it. +type CounterTable interface { + // Create adds value at key, returning an error matching ebpf.ErrKeyExist + // when key is already present. + Create(key, value any) error + + // Delete removes the entry at key, returning an error matching + // ebpf.ErrKeyNotExist when key is absent. + Delete(key any) error + + // Iterate returns an Iterator over every entry, in unspecified order. + Iterate() Iterator +} + +// KernelCounterTable adapts a loaded per-CPU hash map to CounterTable. +type KernelCounterTable struct { + Map *ebpf.Map +} + +// Create adds value at key with BPF_NOEXIST. +func (k KernelCounterTable) Create(key, value any) error { + return k.Map.Update(key, value, ebpf.UpdateNoExist) +} + +// Delete removes the entry at key. +func (k KernelCounterTable) Delete(key any) error { return k.Map.Delete(key) } + +// Iterate returns an iterator over every entry. +func (k KernelCounterTable) Iterate() Iterator { return k.Map.Iterate() } + +// VRFTrafficTable is the read/write API for vrf_traffic_counters, the +// datapath's per-CPU, per-direction traffic counters for each vrf_table row. +// Its rows are created and removed alongside vrf_table's; VRFTable does so +// itself once given one with WithTraffic. +type VRFTrafficTable struct { + table CounterTable + cpus func() (int, error) +} + +// NewVRFTrafficTable wraps table as a VRFTrafficTable. Production callers pass +// a KernelCounterTable over the loaded map; tests pass a fake. +func NewVRFTrafficTable(table CounterTable) *VRFTrafficTable { + return &VRFTrafficTable{table: table, cpus: ebpf.PossibleCPU} +} + +// Ensure creates the zeroed row for (block, argument) if it is absent. An +// existing row, and the counts it holds, is left alone. +func (t *VRFTrafficTable) Ensure(block uint64, argument uint16) error { + key, err := uformat.NewVRFKey(block, argument) + if err != nil { + return fmt.Errorf("usidmap: vrf_traffic_counters: ensure block=%#x argument=%#x: %w", block, argument, err) + } + return t.ensure(uint64(key)) +} + +func (t *VRFTrafficTable) ensure(rawKey uint64) error { + n, err := t.cpus() + if err != nil { + return fmt.Errorf("usidmap: vrf_traffic_counters: ensure key=%#x: count possible CPUs: %w", rawKey, err) + } + if err := t.table.Create(rawKey, make([]prog.UsidVrfTrafficValue, n)); err != nil { + if errors.Is(err, ebpf.ErrKeyExist) { + return nil + } + return fmt.Errorf("usidmap: vrf_traffic_counters: ensure key=%#x: %w", rawKey, err) + } + return nil +} + +// Remove deletes the row for (block, argument). An already-absent row is not +// an error. +func (t *VRFTrafficTable) Remove(block uint64, argument uint16) error { + key, err := uformat.NewVRFKey(block, argument) + if err != nil { + return fmt.Errorf("usidmap: vrf_traffic_counters: remove block=%#x argument=%#x: %w", block, argument, err) + } + return t.remove(uint64(key)) +} + +func (t *VRFTrafficTable) remove(rawKey uint64) error { + if err := t.table.Delete(rawKey); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + return fmt.Errorf("usidmap: vrf_traffic_counters: remove key=%#x: %w", rawKey, err) + } + return nil +} + +// List returns every row, each direction's counters summed across CPUs, in +// unspecified order. +func (t *VRFTrafficTable) List() ([]VRFTrafficEntry, error) { + var ( + entries []VRFTrafficEntry + rawKey uint64 + perCPU []prog.UsidVrfTrafficValue + ) + it := t.table.Iterate() + for it.Next(&rawKey, &perCPU) { + e := VRFTrafficEntry{VRFKey: decodeVRFKey(rawKey)} + for _, v := range perCPU { + e.Ingress.add(v.Ingress) + e.Egress.add(v.Egress) + } + entries = append(entries, e) + } + if err := it.Err(); err != nil { + return nil, fmt.Errorf("usidmap: vrf_traffic_counters: list: %w", err) + } + return entries, nil +} + +// Sync makes the table's rows match want, the keys of every vrf_table row: +// it creates a zeroed row for each key missing one and removes every row +// whose key is absent from want and for which stillWanted, consulted just +// before the delete, reports false. stillWanted is consulted again after the +// delete, and a row it now wants is created again, so a VRF registered while +// Sync runs keeps a row. It returns how +// many rows it created and removed; every change is attempted, with the +// errors joined. +func (t *VRFTrafficTable) Sync( + want map[VRFKey]struct{}, stillWanted func(VRFKey) (bool, error), +) (created, removed int, err error) { + entries, err := t.List() + if err != nil { + return 0, 0, fmt.Errorf("usidmap: vrf_traffic_counters: sync: %w", err) + } + + var errs []error + have := make(map[VRFKey]struct{}, len(entries)) + for _, e := range entries { + have[e.VRFKey] = struct{}{} + if _, ok := want[e.VRFKey]; ok { + continue + } + keep, err := stillWanted(e.VRFKey) + if err != nil { + errs = append(errs, fmt.Errorf("usidmap: vrf_traffic_counters: sync: %w", err)) + continue + } + if keep { + continue + } + if err := t.Remove(e.Block, e.Argument); err != nil { + errs = append(errs, err) + continue + } + removed++ + // A registration landing between the check and the delete has already + // found its row present, so it is put back here. + if keep, err := stillWanted(e.VRFKey); err != nil { + errs = append(errs, fmt.Errorf("usidmap: vrf_traffic_counters: sync: %w", err)) + } else if keep { + if err := t.Ensure(e.Block, e.Argument); err != nil { + errs = append(errs, err) + } + } + } + for k := range want { + if _, ok := have[k]; ok { + continue + } + if err := t.Ensure(k.Block, k.Argument); err != nil { + errs = append(errs, err) + continue + } + created++ + } + return created, removed, errors.Join(errs...) +} + +func (c *VRFTrafficCounters) add(v prog.UsidVrfDirectionCounter) { + c.Packets += v.Packets + c.Bytes += v.Bytes + c.DroppedPackets += v.DroppedPackets +} + +// decodeVRFKey splits a raw vrf_table-style key back into Block and Argument. +func decodeVRFKey(rawKey uint64) VRFKey { + return VRFKey{ + Block: rawKey >> uformat.ArgumentBits, + Argument: uint16(rawKey & (1<= len(it.keys) { + return false + } + k := it.keys[it.idx] + it.idx++ + *keyOut.(*uint64) = k + *valueOut.(*[]prog.UsidVrfTrafficValue) = slices.Clone(it.table.rows[k]) + return true +} + +func (it *fakeCounterIterator) Err() error { return nil } + +// bump adds packets to one CPU's copy of key's row in direction dir, as the +// datapath does. +func (f *fakeCounterTable) bump(t *testing.T, key VRFKey, cpu int, ingress bool, packets, bytes, drops uint64) { + t.Helper() + raw, err := uformat.NewVRFKey(key.Block, key.Argument) + if err != nil { + t.Fatal(err) + } + row, ok := f.rows[uint64(raw)] + if !ok { + t.Fatalf("no row for %+v", key) + } + c := &row[cpu].Egress + if ingress { + c = &row[cpu].Ingress + } + c.Packets += packets + c.Bytes += bytes + c.DroppedPackets += drops +} + +func newTestTrafficTable(table CounterTable) *VRFTrafficTable { + t := NewVRFTrafficTable(table) + t.cpus = func() (int, error) { return testTrafficCPUs, nil } + return t +} + +func TestVRFTrafficTable_EnsureKeepsExistingCounts(t *testing.T) { + fake := newFakeCounterTable() + traffic := newTestTrafficTable(fake) + key := VRFKey{Block: testBlock, Argument: 0x21} + + if err := traffic.Ensure(key.Block, key.Argument); err != nil { + t.Fatalf("Ensure: %v", err) + } + fake.bump(t, key, 0, true, 3, 300, 1) + if err := traffic.Ensure(key.Block, key.Argument); err != nil { + t.Fatalf("second Ensure: %v", err) + } + + entries, err := traffic.List() + if err != nil { + t.Fatalf("List: %v", err) + } + want := []VRFTrafficEntry{{VRFKey: key, Ingress: VRFTrafficCounters{Packets: 3, Bytes: 300, DroppedPackets: 1}}} + if !slices.Equal(entries, want) { + t.Errorf("List = %+v, want %+v: a repeat Ensure must not reset the row", entries, want) + } +} + +func TestVRFTrafficTable_ListSumsEveryCPU(t *testing.T) { + fake := newFakeCounterTable() + traffic := newTestTrafficTable(fake) + key := VRFKey{Block: testBlock, Argument: 0x21} + if err := traffic.Ensure(key.Block, key.Argument); err != nil { + t.Fatal(err) + } + fake.bump(t, key, 0, true, 2, 200, 0) + fake.bump(t, key, 1, true, 5, 500, 1) + fake.bump(t, key, 0, false, 1, 64, 2) + fake.bump(t, key, 1, false, 4, 256, 0) + + entries, err := traffic.List() + if err != nil { + t.Fatalf("List: %v", err) + } + want := []VRFTrafficEntry{{ + VRFKey: key, + Ingress: VRFTrafficCounters{Packets: 7, Bytes: 700, DroppedPackets: 1}, + Egress: VRFTrafficCounters{Packets: 5, Bytes: 320, DroppedPackets: 2}, + }} + if !slices.Equal(entries, want) { + t.Errorf("List = %+v, want %+v", entries, want) + } +} + +func TestVRFTrafficTable_RemoveAbsentIsNotError(t *testing.T) { + traffic := newTestTrafficTable(newFakeCounterTable()) + if err := traffic.Remove(testBlock, 0x21); err != nil { + t.Errorf("Remove of an absent row: %v, want nil", err) + } +} + +func TestVRFTrafficTable_Sync(t *testing.T) { + keep := VRFKey{Block: testBlock, Argument: 0x10} + stale := VRFKey{Block: testBlock, Argument: 0x11} + racing := VRFKey{Block: testBlock, Argument: 0x12} + missing := VRFKey{Block: testBlock, Argument: 0x13} + + fake := newFakeCounterTable() + traffic := newTestTrafficTable(fake) + for _, k := range []VRFKey{keep, stale, racing} { + if err := traffic.Ensure(k.Block, k.Argument); err != nil { + t.Fatal(err) + } + } + fake.bump(t, keep, 0, false, 9, 900, 0) + + want := map[VRFKey]struct{}{keep: {}, missing: {}} + stillWanted := func(k VRFKey) (bool, error) { return k == racing, nil } + created, removed, err := traffic.Sync(want, stillWanted) + if err != nil { + t.Fatalf("Sync: %v", err) + } + if created != 1 || removed != 1 { + t.Errorf("Sync created %d removed %d, want 1 and 1", created, removed) + } + + got := map[VRFKey]VRFTrafficEntry{} + entries, err := traffic.List() + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + got[e.VRFKey] = e + } + if _, ok := got[stale]; ok { + t.Error("stale row survived Sync") + } + if _, ok := got[racing]; !ok { + t.Error("row registered while Sync ran was removed") + } + if _, ok := got[missing]; !ok { + t.Error("missing row was not created") + } + if got[keep].Egress.Packets != 9 { + t.Errorf("kept row's egress packets = %d, want 9: Sync must not reset a kept row", got[keep].Egress.Packets) + } +} + +func TestVRFTrafficTable_SyncKeepsRowWhenRecheckFails(t *testing.T) { + traffic := newTestTrafficTable(newFakeCounterTable()) + if err := traffic.Ensure(testBlock, 0x21); err != nil { + t.Fatal(err) + } + boom := errors.New("lookup failed") + _, removed, err := traffic.Sync(nil, func(VRFKey) (bool, error) { return false, boom }) + if !errors.Is(err, boom) { + t.Errorf("Sync error = %v, want it to wrap %v", err, boom) + } + if removed != 0 { + t.Errorf("Sync removed %d rows it could not re-check, want 0", removed) + } +} + +func newTrafficVRFTable() (*VRFTable, *fakeTable, *fakeCounterTable) { + vrfFake := newFakeTable() + trafficFake := newFakeCounterTable() + return NewVRFTable(vrfFake).WithTraffic(newTestTrafficTable(trafficFake)), vrfFake, trafficFake +} + +func TestVRFTable_TrafficRowFollowsRegisterAndUnregister(t *testing.T) { + vrf, _, trafficFake := newTrafficVRFTable() + + if err := vrf.Register(testBlock, 0x21, 7, EgressKindVeth); err != nil { + t.Fatalf("Register: %v", err) + } + if len(trafficFake.rows) != 1 { + t.Fatalf("traffic rows after Register = %d, want 1", len(trafficFake.rows)) + } + key := VRFKey{Block: testBlock, Argument: 0x21} + trafficFake.bump(t, key, 1, true, 4, 400, 0) + + if err := vrf.Register(testBlock, 0x21, 7, EgressKindVeth); err != nil { + t.Fatalf("re-Register: %v", err) + } + entries, err := vrf.traffic.List() + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Ingress.Packets != 4 { + t.Errorf("traffic after re-Register = %+v, want the 4 counted packets kept", entries) + } + + if err := vrf.Unregister(testBlock, 0x21); err != nil { + t.Fatalf("Unregister: %v", err) + } + if len(trafficFake.rows) != 0 { + t.Errorf("traffic rows after Unregister = %d, want 0", len(trafficFake.rows)) + } +} + +func TestVRFTable_RegisterSucceedsWhenTrafficRowFails(t *testing.T) { + vrf, vrfFake, trafficFake := newTrafficVRFTable() + trafficFake.createErr = errors.New("map full") + + if err := vrf.Register(testBlock, 0x21, 7, EgressKindVeth); err != nil { + t.Fatalf("Register = %v, want nil: the counters must never fail a registration", err) + } + if vrfFake.len() != 1 { + t.Errorf("vrf_table rows = %d, want 1", vrfFake.len()) + } +} + +func TestVRFTable_SyncTrafficRebuildsRows(t *testing.T) { + vrf, _, trafficFake := newTrafficVRFTable() + for _, arg := range []uint16{0x21, 0x22} { + if err := vrf.Register(testBlock, arg, 7, EgressKindVeth); err != nil { + t.Fatal(err) + } + } + // A recreated, empty vrf_traffic_counters next to rows that survived. + clear(trafficFake.rows) + orphan, err := uformat.NewVRFKey(testBlock, 0x30) + if err != nil { + t.Fatal(err) + } + trafficFake.rows[uint64(orphan)] = make([]prog.UsidVrfTrafficValue, testTrafficCPUs) + + if err := vrf.SyncTraffic(); err != nil { + t.Fatalf("SyncTraffic: %v", err) + } + entries, err := vrf.traffic.List() + if err != nil { + t.Fatal(err) + } + got := make([]uint16, 0, len(entries)) + for _, e := range entries { + got = append(got, e.Argument) + } + slices.Sort(got) + if want := []uint16{0x21, 0x22}; !slices.Equal(got, want) { + t.Errorf("traffic rows after SyncTraffic = %#x, want %#x", got, want) + } +} + +func TestVRFTable_ReconcileRemovesStaleTrafficRow(t *testing.T) { + vrf, _, trafficFake := newTrafficVRFTable() + vrf.clock = func() uint64 { return 1 } + if err := vrf.Register(testBlock, 0x21, 7, EgressKindVeth); err != nil { + t.Fatal(err) + } + if err := vrf.Register(testBlock, 0x22, 7, EgressKindVeth); err != nil { + t.Fatal(err) + } + + live := map[VRFKey]struct{}{{Block: testBlock, Argument: 0x22}: {}} + if _, err := vrf.Reconcile(live, 2); err != nil { + t.Fatalf("Reconcile: %v", err) + } + keep, err := uformat.NewVRFKey(testBlock, 0x22) + if err != nil { + t.Fatal(err) + } + if len(trafficFake.rows) != 1 { + t.Fatalf("traffic rows after Reconcile = %d, want 1", len(trafficFake.rows)) + } + if _, ok := trafficFake.rows[uint64(keep)]; !ok { + t.Error("live VRF's traffic row was removed") + } +} + +func TestVRFTable_WithoutTrafficIsUnchanged(t *testing.T) { + vrf := NewVRFTable(newFakeTable()) + if err := vrf.Register(testBlock, 0x21, 7, EgressKindVeth); err != nil { + t.Fatalf("Register: %v", err) + } + if err := vrf.SyncTraffic(); err != nil { + t.Errorf("SyncTraffic without a traffic table = %v, want nil", err) + } + if err := vrf.Unregister(testBlock, 0x21); err != nil { + t.Errorf("Unregister: %v", err) + } +} + +// A VRF registered between Sync's check and its delete has already found its +// row present, so Sync must put the row back. +func TestVRFTrafficTable_SyncRestoresRowRegisteredDuringDelete(t *testing.T) { + fake := newFakeCounterTable() + traffic := newTestTrafficTable(fake) + if err := traffic.Ensure(testBlock, 0x21); err != nil { + t.Fatal(err) + } + calls := 0 + stillWanted := func(VRFKey) (bool, error) { + calls++ + return calls > 1, nil + } + if _, _, err := traffic.Sync(nil, stillWanted); err != nil { + t.Fatalf("Sync: %v", err) + } + if len(fake.rows) != 1 { + t.Errorf("traffic rows = %d, want the row restored for the VRF registered mid-delete", len(fake.rows)) + } +}