Skip to content

Commit

Permalink
aya: add helper to return all loaded maps
Browse files Browse the repository at this point in the history
This mirrors the already existing approach to returning all of the
currently loaded programs.
  • Loading branch information
preuss-adam committed Oct 10, 2023
1 parent 9b1c7a9 commit 39c3ca5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
37 changes: 36 additions & 1 deletion aya/src/maps/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ use crate::{
sys::{
bpf_create_map, bpf_get_object, bpf_map_freeze, bpf_map_get_fd_by_id,
bpf_map_get_info_by_fd, bpf_map_get_next_key, bpf_map_update_elem_ptr, bpf_pin_object,
SyscallError,
iter_map_ids, SyscallError,
},
util::{nr_cpus, KernelVersion},
PinningType, Pod,
Expand Down Expand Up @@ -820,6 +820,41 @@ impl<T: Pod> Deref for PerCpuValues<T> {
}
}

/// Returns an iterator over all loaded bpf maps.
///
/// This differs from [`crate::Bpf::maps`] since it will return all maps
/// listed on the host system and not only maps for a specific [`crate::Bpf`] instance.
///
/// # Example
/// ```
/// # use aya::maps::loaded_maps;
///
/// for m in loaded_maps() {
/// match m {
/// Ok(map) => match map.name() {
/// Ok(name) => println!("{}",name),
/// Err(e) => println!("Error querying map name: {:?}", e),
/// }
/// Err(e) => println!("Error iterating maps: {:?}", e),
/// }
/// }
/// ```
///
/// # Errors
///
/// Returns [`MapError::SyscallError`] if any of the syscalls required to either get
/// next map id, get the map fd, or the [`MapData`] fail. In cases where
/// iteration can't be performed, for example the caller does not have the necessary privileges,
/// a single item will be yielded containing the error that occurred.
pub fn loaded_maps() -> impl Iterator<Item = Result<MapData, MapError>> {
iter_map_ids()
.map(|id| {
let id = id?;
bpf_map_get_fd_by_id(id)
})
.map(|fd| MapData::from_fd(fd?))
}

#[cfg(test)]
mod tests {
use std::os::fd::AsRawFd as _;
Expand Down
4 changes: 4 additions & 0 deletions aya/src/sys/bpf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1049,6 +1049,10 @@ pub(crate) fn iter_link_ids() -> impl Iterator<Item = Result<u32, SyscallError>>
iter_obj_ids(bpf_cmd::BPF_LINK_GET_NEXT_ID, "bpf_link_get_next_id")
}

pub(crate) fn iter_map_ids() -> impl Iterator<Item = Result<u32, SyscallError>> {
iter_obj_ids(bpf_cmd::BPF_MAP_GET_NEXT_ID, "bpf_map_get_next_id")
}

pub(crate) fn retry_with_verifier_logs<T>(
max_retries: usize,
f: impl Fn(&mut [u8]) -> SysResult<T>,
Expand Down

0 comments on commit 39c3ca5

Please sign in to comment.