From 46221749b40f98883418eeeb131f037a9d0cd73a Mon Sep 17 00:00:00 2001 From: Benedikt Iltisberger Date: Fri, 13 Nov 2026 12:34:31 +0100 Subject: [PATCH] fix: load eBPF counters again, count with TC only and skip lo Since v0.4.0 no eBPF program loaded anywhere: the EbpfLogger returned by aya_log::EbpfLogger::init_with_logger was dropped right away, which closed the AYA_LOGS ring buffer that every program references, so each BPF_PROG_LOAD failed with EBADF. The attach results were discarded with `.is_ok()`, so every interface reported `none` and the operator silently fell back to /proc/net/dev. - drop aya-log from the eBPF program and userspace: the only error path was a lookup of index 0 in a 1-entry array, and each loaded object paid a 128 KiB ring buffer for it - count ingress with a TC classifier instead of XDP: an XDP program on a veth clears TSO on its peer (`tx-tcp-segmentation: off [fixed]`) and on lo it ran as generic XDP on every loopback packet - skip lo by default (`--exclude-interface`, repeatable) - report attach errors; if both directions fail, emit InterfaceBpfInitializationFailed - detach on SIGTERM/SIGINT instead of dying with programs left attached (netlink TC filters outlive the process on kernels without tcx) - count egress with skb->len instead of the linear head only Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 98 +++++---------------- Cargo.toml | 2 - snoopy-ebpf/Cargo.toml | 1 - snoopy-ebpf/src/main.rs | 119 +++++-------------------- snoopy/Cargo.toml | 3 +- snoopy/src/main.rs | 187 ++++++++++++++++++++++------------------ 6 files changed, 145 insertions(+), 265 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b677982..fa1027d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -161,60 +161,6 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "aya-log" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "425a0093e7b0f87ef6fd0fcc33c33c7e9658dc2a2693b657195785c8b36efb04" -dependencies = [ - "aya", - "aya-log-common", - "log", - "thiserror", -] - -[[package]] -name = "aya-log-common" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab343b69a6419491a44f99d37e1782226f0c59bcf1c26e00e3df537a5f87d676" -dependencies = [ - "num_enum", -] - -[[package]] -name = "aya-log-ebpf" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8effcef81d5ab7f5eff3a967e798040ffbdb91ef5fdcb2b885eb93412a6f5d77" -dependencies = [ - "aya-ebpf", - "aya-log-common", - "aya-log-ebpf-macros", -] - -[[package]] -name = "aya-log-ebpf-macros" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfe1f6fbd691b3bc4f4dd381d1d5f1cfbac34a542613deb557f9aa2c38eeffd4" -dependencies = [ - "aya-log-common", - "aya-log-parser", - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "aya-log-parser" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f69a4f6f99011e722c53c77afecb24dbf02d87d9cd93ae6ef541cbbf814cdcd1" -dependencies = [ - "aya-log-common", -] - [[package]] name = "aya-obj" version = "0.6.0" @@ -457,6 +403,16 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -714,27 +670,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "num_enum" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" -dependencies = [ - "num_enum_derive", - "rustversion", -] - -[[package]] -name = "num_enum_derive" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "object" version = "0.40.0" @@ -1083,6 +1018,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "slab" version = "0.4.12" @@ -1096,7 +1041,6 @@ dependencies = [ "anyhow", "aya", "aya-build", - "aya-log", "cargo_metadata", "clap", "env_logger", @@ -1115,7 +1059,6 @@ name = "snoopy-ebpf" version = "0.1.0" dependencies = [ "aya-ebpf", - "aya-log-ebpf", "which", ] @@ -1222,6 +1165,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", "windows-sys", diff --git a/Cargo.toml b/Cargo.toml index 8612638..efa0c45 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,8 +11,6 @@ anyhow = { version = "1.0.100" } aya = { version = "0.16.0", default-features = false } aya-build = { version = "0.2.1", default-features = false } aya-ebpf = { version = "0.3.0", default-features = false } -aya-log = { version = "0.4.0", default-features = false } -aya-log-ebpf = { version = "0.3.0", default-features = false } cargo_metadata = { version = "0.23.1", default-features = false } log = { version = "0.4.28", default-features = false } which = { version = "8.0.0", features=["real-sys"], default-features = false } diff --git a/snoopy-ebpf/Cargo.toml b/snoopy-ebpf/Cargo.toml index 842bb43..081c1f4 100644 --- a/snoopy-ebpf/Cargo.toml +++ b/snoopy-ebpf/Cargo.toml @@ -5,7 +5,6 @@ edition.workspace = true [dependencies] aya-ebpf = { workspace = true } -aya-log-ebpf = { workspace = true } [build-dependencies] which = { workspace = true } diff --git a/snoopy-ebpf/src/main.rs b/snoopy-ebpf/src/main.rs index 15327b5..d60e926 100644 --- a/snoopy-ebpf/src/main.rs +++ b/snoopy-ebpf/src/main.rs @@ -1,12 +1,9 @@ #![no_std] #![no_main] -use aya_ebpf::bindings::xdp_action; use aya_ebpf::macros::map; use aya_ebpf::maps::PerCpuArray; use aya_ebpf::programs::TcContext; -use aya_ebpf::programs::XdpContext; -use aya_log_ebpf as log; #[repr(C)] #[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] @@ -21,113 +18,37 @@ static INGRESS_COUNTER: PerCpuArray = PerCpuArray::::with_max_ #[map(name = "EGRESS_COUNTER")] static EGRESS_COUNTER: PerCpuArray = PerCpuArray::::with_max_entries(1, 0); +// Both directions are counted with TC classifiers only. XDP was tried first +// for ingress before, but attaching an XDP program to a veth clears TSO on +// its peer (`tx-tcp-segmentation: off [fixed]`), so the host had to segment +// every packet sent into the pod, and on `lo` it ran as generic XDP on every +// loopback packet. A classifier sees the same bytes without either cost. +// +// There is no aya-log here: the only failure path is a lookup of index 0 in +// a 1-entry array, which cannot fail, and each loaded object paid a 128 KiB +// AYA_LOGS ring buffer for it. + #[aya_ebpf::macros::classifier] pub fn update_tc_ingress(ctx: TcContext) -> i32 { - match try_update_tc_ingress(&ctx) { - Ok(_) => { - // log::debug!( - // &ctx, - // "TC INGRESS: added packet with {} bytes", - // ctx.data_end() - ctx.data() - // ); - } - Err(msg) => { - log::error!(&ctx, "TC INGRESS: failed to add packet: {}", msg); - } - } - + count(&INGRESS_COUNTER, ctx.len() as u64); aya_ebpf::bindings::TC_ACT_PIPE } -#[inline] -pub fn try_update_tc_ingress(ctx: &TcContext) -> Result<(), &'static str> { - let bytes = ctx.len() as u64; - - let counter = INGRESS_COUNTER - .get_ptr_mut(0) - .ok_or("failed to get pointer to first entry in INGRESS_COUNTER map")?; - - unsafe { - (*counter).packets = (*counter).packets.wrapping_add(1); - (*counter).bytes = (*counter).bytes.wrapping_add(bytes); - } - - Ok(()) -} - -#[aya_ebpf::macros::xdp] -pub fn update_xdp_ingress(ctx: XdpContext) -> u32 { - match try_update_xdp_ingress(&ctx) { - Ok(_) => { - // log::debug!( - // &ctx, - // "XDP INGRESS: added packet with {} bytes", - // ctx.data_end() - ctx.data() - // ); - } - Err(msg) => { - log::error!(&ctx, "XDP INGRESS: failed to add packet: {}", msg); - } - } - - xdp_action::XDP_PASS -} - -#[inline] -fn try_update_xdp_ingress(ctx: &XdpContext) -> Result<(), &'static str> { - // On-wire bytes only — XDP metadata (bpf_xdp_adjust_meta region) is driver/HW - // scratch space, not part of the packet, so omit it to match the TC variant - // which uses ctx.len(). - let bytes = ctx.data_end() as u64 - ctx.data() as u64; - - let counter = INGRESS_COUNTER - .get_ptr_mut(0) - .ok_or("failed to get pointer to first entry in INGRESS_COUNTER map")?; - - unsafe { - (*counter).packets = (*counter).packets.wrapping_add(1); - (*counter).bytes = (*counter).bytes.wrapping_add(bytes); - - // info!(ctx, "XDP INGRESS: Packets: {}, Bytes: {}", (*counter).packets, (*counter).bytes); - } - - Ok(()) -} - #[aya_ebpf::macros::classifier] pub fn update_tc_egress(ctx: TcContext) -> i32 { - match try_update_tc_egress(&ctx) { - Ok(_) => { - // log::debug!( - // &ctx, - // "TC EGRESS: added packet with {} bytes", - // ctx.data_end() - ctx.data() - // ); - } - Err(msg) => { - log::error!(&ctx, "TC EGRESS: failed to add packet: {}", msg); - } - }; - + count(&EGRESS_COUNTER, ctx.len() as u64); aya_ebpf::bindings::TC_ACT_PIPE } -#[inline] -pub fn try_update_tc_egress(ctx: &TcContext) -> Result<(), &'static str> { - let data = ctx.data() as u64; - let data_end = ctx.data_end() as u64; - let bytes = data_end - data; - - let counter = EGRESS_COUNTER - .get_ptr_mut(0) - .ok_or("failed to get pointer to first entry in EGRESS_COUNTER map")?; - - unsafe { - (*counter).packets = (*counter).packets.wrapping_add(1); - (*counter).bytes = (*counter).bytes.wrapping_add(bytes); +#[inline(always)] +fn count(map: &PerCpuArray, bytes: u64) { + if let Some(counter) = map.get_ptr_mut(0) { + // SAFETY: per-CPU map slot; programs on one CPU never run concurrently. + unsafe { + (*counter).packets = (*counter).packets.wrapping_add(1); + (*counter).bytes = (*counter).bytes.wrapping_add(bytes); + } } - - Ok(()) } #[cfg(not(test))] diff --git a/snoopy/Cargo.toml b/snoopy/Cargo.toml index 016dbc3..05d3142 100644 --- a/snoopy/Cargo.toml +++ b/snoopy/Cargo.toml @@ -6,7 +6,6 @@ edition.workspace = true [dependencies] anyhow = { workspace = true } aya = { workspace = true } -aya-log = { workspace = true } clap = { version = "4.5.53", features = ["derive"] } env_logger = { version = "0.11.8", default-features = false } libc = { version = "0.2.177", default-features = false } @@ -15,7 +14,7 @@ pnet = { version = "0.35.0", features = ["serde"] } serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.145" serde_with = "3.16.0" -tokio = { version = "1.48.0", default-features = false, features = ["macros", "rt", "time", "sync", "net"] } +tokio = { version = "1.48.0", default-features = false, features = ["macros", "rt", "time", "sync", "net", "signal"] } [build-dependencies] anyhow = { workspace = true } diff --git a/snoopy/src/main.rs b/snoopy/src/main.rs index cd2ef37..611e0ce 100644 --- a/snoopy/src/main.rs +++ b/snoopy/src/main.rs @@ -1,5 +1,4 @@ use std::collections::HashMap; -use std::ffi::CStr; use std::ffi::CString; use std::io::Write; use std::ops::Add; @@ -14,8 +13,6 @@ use anyhow::anyhow; use aya::Pod; use aya::programs::SchedClassifier; use aya::programs::TcAttachType; -use aya::programs::Xdp; -use aya::programs::XdpMode; use aya::programs::tc::TcError; use clap::Parser; use env_logger::Target; @@ -26,6 +23,8 @@ use serde::Serialize; use serde_with::DisplayFromStr; use serde_with::serde_as; use tokio::io::unix::AsyncFd; +use tokio::signal::unix::SignalKind; +use tokio::signal::unix::signal; // Netlink multicast groups for interface and address change notifications const RTMGRP_LINK: u32 = 1; @@ -51,6 +50,11 @@ struct Arguments { #[arg(long, default_value = "500")] /// Rate at which network metrics are collected from BPF modules and printed to stdout pub metrics_rate: u64, + + #[arg(long = "exclude-interface", default_values_t = vec!["lo".to_string()])] + /// Interface that gets no counters attached (repeatable). Loopback traffic + /// never leaves the pod, and a classifier on `lo` taxes every local packet. + pub exclude_interfaces: Vec, } #[tokio::main(flavor = "current_thread")] @@ -111,20 +115,46 @@ async fn main() -> anyhow::Result<()> { ) .await; + // Exit through the same path for SIGTERM and SIGINT: dropping the eBPF + // objects detaches their programs. Without it the default signal action + // killed the process, and on kernels without tcx (<6.6) the netlink TC + // filters stayed on the pod's interfaces after snoopy was gone. + let mut sigterm = signal(SignalKind::terminate())?; + let mut sigint = signal(SignalKind::interrupt())?; + loop { - // Block until the kernel sends a netlink notification (interface or - // address change), then drain all buffered messages before diffing. - let mut guard = netlink_socket.readable().await?; - guard.clear_ready(); - drain_netlink_messages(netlink_socket.get_ref()); - - handle_updates( - update_network_interfaces(&mut network_interfaces), - &args, - &mut ebpf_tasks, - ) - .await; + tokio::select! { + readable = netlink_socket.readable() => { + // Woken by a netlink notification (interface or address + // change); drain all buffered messages before diffing. + let mut guard = readable?; + guard.clear_ready(); + drain_netlink_messages(netlink_socket.get_ref()); + + handle_updates( + update_network_interfaces(&mut network_interfaces), + &args, + &mut ebpf_tasks, + ) + .await; + } + _ = sigterm.recv() => break, + _ = sigint.recv() => break, + } } + + log::info!( + "shutting down, detaching {} ebpf module(s)", + ebpf_tasks.len() + ); + for (_, (kill_tx, handle)) in ebpf_tasks.drain() { + let _ = kill_tx.send(()); + if handle.await.is_err() { + log::error!("failed to join worker thread"); + } + } + + Ok(()) } async fn handle_updates( @@ -137,6 +167,10 @@ async fn handle_updates( match event { InterfaceUpdate::InterfaceAdded { interface } => { + if args.exclude_interfaces.contains(&interface.name) { + log::debug!("not attaching to excluded interface {}", interface.name); + continue; + } let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); let args = args.clone(); match initialize_ebpf_for_interface(interface.name.clone()).await { @@ -304,7 +338,6 @@ pub enum IngressImplementation { #[default] None, Classifier, - Xdp, } impl FromStr for IngressImplementation { @@ -313,7 +346,6 @@ impl FromStr for IngressImplementation { fn from_str(s: &str) -> Result { match s.to_lowercase().as_str() { "classifier" => Ok(IngressImplementation::Classifier), - "xdp" => Ok(IngressImplementation::Xdp), _ => Err(anyhow::anyhow!("Invalid Ingress Implementation: {s}")), } } @@ -344,11 +376,6 @@ async fn initialize_ebpf_for_interface( let ebpf_program = aya::include_bytes_aligned!(concat!(env!("OUT_DIR"), "/snoopy")); let mut ebpf = aya::Ebpf::load(ebpf_program).with_context(|| "failed to load ebpf program")?; - if let Err(error) = aya_log::EbpfLogger::init_with_logger(&mut ebpf, log::logger()) { - // This can happen if you remove all log statements from your eBPF program. - log::warn!("failed to initialize eBPF logger: {error}"); - } - // aya >= 0.16 identifies interfaces by `&CStr` (or index) instead of `&str`. let iface_c = CString::new(iface.as_str()) .with_context(|| format!("interface name {iface:?} contains a NUL byte"))?; @@ -364,10 +391,44 @@ async fn initialize_ebpf_for_interface( } } - let ingress_impl = attach_ingress_counter(&mut ebpf, &iface_c); - let egress_impl = attach_egress_counter(&mut ebpf, &iface_c); - - Ok((ebpf, ingress_impl, egress_impl)) + // Attach errors used to be dropped with `.is_ok()`, which hid that no + // program had loaded at all for months. Report them: a half-attached + // interface is logged, a fully failed one fails the initialization so the + // operator sees `InterfaceBpfInitializationFailed`. + let ingress = attach_classifier( + &mut ebpf, + "update_tc_ingress", + &iface_c, + TcAttachType::Ingress, + ); + let egress = attach_classifier( + &mut ebpf, + "update_tc_egress", + &iface_c, + TcAttachType::Egress, + ); + match (ingress, egress) { + (Err(ingress_error), Err(egress_error)) => Err(anyhow!( + "ingress: {ingress_error:#}; egress: {egress_error:#}" + )), + (ingress, egress) => { + let ingress_impl = match ingress { + Ok(()) => IngressImplementation::Classifier, + Err(error) => { + log::warn!("failed to attach ingress counter to {iface:?}: {error:#}"); + IngressImplementation::None + } + }; + let egress_impl = match egress { + Ok(()) => EgressImplementation::Classifier, + Err(error) => { + log::warn!("failed to attach egress counter to {iface:?}: {error:#}"); + EgressImplementation::None + } + }; + Ok((ebpf, ingress_impl, egress_impl)) + } + } } async fn attach_to_interface( @@ -412,65 +473,23 @@ async fn attach_to_interface( log::info!("closed ebpf module for interface {iface}"); } -/// Attempt to attach any of the available implementations for counting ingress traffic -/// and returns the chosen implementation. -fn attach_ingress_counter(ebpf: &mut aya::Ebpf, iface: &CStr) -> IngressImplementation { - if attach_ingress_xdp_counter(ebpf, iface).is_ok() { - return IngressImplementation::Xdp; - } - - if attach_ingress_classifier_counter(ebpf, iface).is_ok() { - return IngressImplementation::Classifier; - } - - IngressImplementation::None -} - -/// ingress counter implementation using `XDP` -fn attach_ingress_xdp_counter(ebpf: &mut aya::Ebpf, iface: &CStr) -> anyhow::Result<()> { - let ingress_program: &mut Xdp = ebpf.program_mut("update_xdp_ingress").unwrap().try_into()?; - ingress_program.load()?; - ingress_program - .attach(iface, XdpMode::default()) - .map_err(|err| anyhow!("failed to attach the XDP program with default mode: {err}"))?; - - Ok(()) -} - -/// ingress counter implementation using `Classifier` also known as `Tc` -fn attach_ingress_classifier_counter(ebpf: &mut aya::Ebpf, iface: &CStr) -> anyhow::Result<()> { - let ingress_program: &mut SchedClassifier = ebpf - .program_mut("update_tc_ingress") - .expect("could not find program with name `update_tc_ingress`") - .try_into()?; - ingress_program.load()?; - ingress_program - .attach(iface, TcAttachType::Ingress) - .map_err(|err| anyhow!("failed to attach the TcAttachType::Ingress program: {err}"))?; - - Ok(()) -} - -/// Attempt to attach any of the available implementations for counting egress traffic -/// and returns the chosen implementation. -fn attach_egress_counter(ebpf: &mut aya::Ebpf, iface: &CStr) -> EgressImplementation { - if attach_egress_classifier_counter(ebpf, iface).is_ok() { - return EgressImplementation::Classifier; - } - - EgressImplementation::None -} - -/// egress counter implementation using `Classifier` also known as `Tc` -fn attach_egress_classifier_counter(ebpf: &mut aya::Ebpf, iface: &CStr) -> anyhow::Result<()> { - let egress_program: &mut SchedClassifier = ebpf - .program_mut("update_tc_egress") - .expect("could not find program with name `update_tc_egress`") +/// Loads the named classifier and attaches it to `iface` in `direction`. +fn attach_classifier( + ebpf: &mut aya::Ebpf, + program_name: &str, + iface: &CString, + direction: TcAttachType, +) -> anyhow::Result<()> { + let program: &mut SchedClassifier = ebpf + .program_mut(program_name) + .with_context(|| format!("could not find program with name `{program_name}`"))? .try_into()?; - egress_program.load()?; - egress_program - .attach(iface, TcAttachType::Egress) - .map_err(|err| anyhow!("failed to attach the TcAttachType::Egress program: {err}"))?; + program + .load() + .with_context(|| format!("failed to load `{program_name}`"))?; + program + .attach(iface.as_c_str(), direction) + .with_context(|| format!("failed to attach `{program_name}` as {direction:?}"))?; Ok(()) }