From 4d953dc3246579113e9267de9c8bdd8e731317a7 Mon Sep 17 00:00:00 2001 From: Harvo Jones Date: Thu, 11 Jul 2024 00:22:49 +0000 Subject: [PATCH] Add the ability to detach an eBPF program Our user-space software agent has, until now, relied on catching the `SIGINT` signal (i.e. Ctl+C) for the application to know when to exit. Exiting causes handles in Rust to go out of scope, which invokes `Drop` handlers and unloads eBPF programs and maps from the kernel. However, if any unhandled signal were to cause the application to exit un-gracefully, `Drop` handlers would not be invoked, and eBPF resources would remain loaded in the kernel. The number of loaded programs would build up over time as the application is restarted. Gracefully handling more types of signals is a good approach, but is best effort. If the drop logic were to fail, or an unhandle-able signal were received, resources would be left behind. A robust approach is to perform cleanup on application startup, where previously loaded eBPF programs are identified and unloaded from the kernel. To support that effort, this change adds the a public `detach_program()` function, which wraps the internal `bpf_prog_detach()`. --- aya/src/programs/mod.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/aya/src/programs/mod.rs b/aya/src/programs/mod.rs index 675e36f0..1abf8ad5 100644 --- a/aya/src/programs/mod.rs +++ b/aya/src/programs/mod.rs @@ -122,9 +122,9 @@ use crate::{ }, sys::{ bpf_btf_get_fd_by_id, bpf_get_object, bpf_link_get_fd_by_id, bpf_link_get_info_by_fd, - bpf_load_program, bpf_pin_object, bpf_prog_get_fd_by_id, bpf_prog_get_info_by_fd, - bpf_prog_query, iter_link_ids, iter_prog_ids, retry_with_verifier_logs, - EbpfLoadProgramAttrs, SyscallError, + bpf_load_program, bpf_pin_object, bpf_prog_detach, bpf_prog_get_fd_by_id, + bpf_prog_get_info_by_fd, bpf_prog_query, iter_link_ids, iter_prog_ids, + retry_with_verifier_logs, EbpfLoadProgramAttrs, SyscallError, }, util::{bytes_of_bpf_name, KernelVersion}, VerifierLogLevel, @@ -1151,6 +1151,15 @@ pub fn loaded_programs() -> impl Iterator, + target_fd: BorrowedFd<'_>, + attach_type: bpf_attach_type, +) -> Result<(), ProgramError> { + bpf_prog_detach(prog_fd, target_fd, attach_type).map_err(Into::into) +} + // TODO(https://github.com/aya-rs/aya/issues/645): this API is currently used in tests. Stabilize // and remove doc(hidden). #[doc(hidden)]