Skip to content

Commit

Permalink
Make map APIs return an option
Browse files Browse the repository at this point in the history
switch map() and map_mut() from returning a
`Result` to an `Option` since it's just getting
a value from a Hashmap, and to stay in line with
the Programs API.

Remove `MapError::MapNotFound`

Signed-off-by: Andrew Stoycos <astoycos@redhat.com>
  • Loading branch information
Andrew Stoycos committed Oct 20, 2022
1 parent 4ddf260 commit f3262e8
Show file tree
Hide file tree
Showing 20 changed files with 31 additions and 58 deletions.
2 changes: 1 addition & 1 deletion aya-log/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl BpfLogger {
logger: T,
) -> Result<BpfLogger, Error> {
let logger = Arc::new(logger);
let mut logs: AsyncPerfEventArray<_> = bpf.take_map("AYA_LOGS")?.try_into()?;
let mut logs: AsyncPerfEventArray<_> = bpf.take_map("AYA_LOGS").unwrap().try_into()?;

for cpu_id in online_cpus().map_err(Error::InvalidOnlineCpu)? {
let mut buf = logs.open(cpu_id, None)?;
Expand Down
36 changes: 8 additions & 28 deletions aya/src/bpf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -743,14 +743,8 @@ impl Bpf {
///
/// For more details and examples on maps and their usage, see the [maps module
/// documentation][crate::maps].
///
/// # Errors
///
/// Returns [`MapError::MapNotFound`] if the map does not exist.
pub fn map(&self, name: &str) -> Result<&Map, MapError> {
self.maps.get(name).ok_or_else(|| MapError::MapNotFound {
name: name.to_owned(),
})
pub fn map(&self, name: &str) -> Option<&Map> {
self.maps.get(name)
}

/// Returns a mutable reference to the map with the given name.
Expand All @@ -760,16 +754,8 @@ impl Bpf {
///
/// For more details and examples on maps and their usage, see the [maps module
/// documentation][crate::maps].
///
/// # Errors
///
/// Returns [`MapError::MapNotFound`] if the map does not exist.
pub fn map_mut(&mut self, name: &str) -> Result<&mut Map, MapError> {
self.maps
.get_mut(name)
.ok_or_else(|| MapError::MapNotFound {
name: name.to_owned(),
})
pub fn map_mut(&mut self, name: &str) -> Option<&mut Map> {
self.maps.get_mut(name)
}

/// Takes ownership of a map with the given name.
Expand All @@ -785,14 +771,8 @@ impl Bpf {
///
/// For more details and examples on maps and their usage, see the [maps module
/// documentation][crate::maps].
///
/// # Errors
///
/// Returns [`MapError::MapNotFound`] if the map does not exist.
pub fn take_map(&mut self, name: &str) -> Result<Map, MapError> {
self.maps.remove(name).ok_or_else(|| MapError::MapNotFound {
name: name.to_owned(),
})
pub fn take_map(&mut self, name: &str) -> Option<Map> {
self.maps.remove(name)
}

/// An iterator over all the maps.
Expand All @@ -808,8 +788,8 @@ impl Bpf {
/// }
/// # Ok::<(), aya::BpfError>(())
/// ```
pub fn maps(&self) -> impl Iterator<Item = (&str, Result<&Map, MapError>)> {
self.maps.iter().map(|(name, map)| (name.as_str(), Ok(map)))
pub fn maps(&self) -> impl Iterator<Item = (&str, &Map)> {
self.maps.iter().map(|(name, map)| (name.as_str(), map))
}

/// Returns a reference to the program with the given name.
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/array/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::Array;
///
/// let mut array = Array::try_from(bpf.map_mut("ARRAY")?)?;
/// let mut array = Array::try_from(bpf.map_mut("ARRAY").unwrap())?;
/// array.set(1, 42, 0)?;
/// assert_eq!(array.get(&1, 0)?, 42);
/// # Ok::<(), aya::BpfError>(())
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/array/per_cpu_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ use crate::{
/// use aya::maps::{PerCpuArray, PerCpuValues};
/// use aya::util::nr_cpus;
///
/// let mut array = PerCpuArray::try_from(bpf.map_mut("ARRAY")?)?;
/// let mut array = PerCpuArray::try_from(bpf.map_mut("ARRAY").unwrap())?;
///
/// // set array[1] = 42 for all cpus
/// let nr_cpus = nr_cpus()?;
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/array/program_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::{
/// use aya::maps::ProgramArray;
/// use aya::programs::CgroupSkb;
///
/// let mut prog_array = ProgramArray::try_from(bpf.take_map("JUMP_TABLE")?)?;
/// let mut prog_array = ProgramArray::try_from(bpf.take_map("JUMP_TABLE").unwrap())?;
/// let prog_0: &CgroupSkb = bpf.program("example_prog_0").unwrap().try_into()?;
/// let prog_0_fd = prog_0.fd().unwrap();
/// let prog_1: &CgroupSkb = bpf.program("example_prog_1").unwrap().try_into()?;
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/bloom_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::bloom_filter::BloomFilter;
///
/// let mut bloom_filter = BloomFilter::try_from(bpf.map_mut("BLOOM_FILTER")?)?;
/// let mut bloom_filter = BloomFilter::try_from(bpf.map_mut("BLOOM_FILTER").unwrap())?;
///
/// bloom_filter.insert(1, 0)?;
///
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/hash_map/hash_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::HashMap;
///
/// let mut redirect_ports = HashMap::try_from(bpf.map_mut("REDIRECT_PORTS")?)?;
/// let mut redirect_ports = HashMap::try_from(bpf.map_mut("REDIRECT_PORTS").unwrap())?;
///
/// // redirect port 80 to 8080
/// redirect_ports.insert(80, 8080, 0);
Expand Down
4 changes: 2 additions & 2 deletions aya/src/maps/hash_map/per_cpu_hash_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use crate::{
/// const CPU_IDS: u8 = 1;
/// const WAKEUPS: u8 = 2;
///
/// let mut hm = PerCpuHashMap::<_, u8, u32>::try_from(bpf.map_mut("PER_CPU_STORAGE")?)?;
/// let mut hm = PerCpuHashMap::<_, u8, u32>::try_from(bpf.map_mut("PER_CPU_STORAGE").unwrap())?;
/// let cpu_ids = unsafe { hm.get(&CPU_IDS, 0)? };
/// let wakeups = unsafe { hm.get(&WAKEUPS, 0)? };
/// for (cpu_id, wakeups) in cpu_ids.iter().zip(wakeups.iter()) {
Expand Down Expand Up @@ -107,7 +107,7 @@ impl<T: AsMut<MapData>, K: Pod, V: Pod> PerCpuHashMap<T, K, V> {
///
/// const RETRIES: u8 = 1;
///
/// let mut hm = PerCpuHashMap::<_, u8, u32>::try_from(bpf.map_mut("PER_CPU_STORAGE")?)?;
/// let mut hm = PerCpuHashMap::<_, u8, u32>::try_from(bpf.map_mut("PER_CPU_STORAGE").unwrap())?;
/// hm.insert(
/// RETRIES,
/// PerCpuValues::try_from(vec![3u32; nr_cpus()?])?,
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/lpm_trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::{
/// use aya::maps::lpm_trie::{LpmTrie, Key};
/// use std::net::Ipv4Addr;
///
/// let mut trie = LpmTrie::try_from(bpf.map_mut("LPM_TRIE")?)?;
/// let mut trie = LpmTrie::try_from(bpf.map_mut("LPM_TRIE").unwrap())?;
/// let ipaddr = Ipv4Addr::new(8, 8, 8, 8);
/// // The following represents a key for the "8.8.8.8/16" subnet.
/// // The first argument - the prefix length - represents how many bytes should be matched against. The second argument is the actual data to be matched.
Expand Down
9 changes: 1 addition & 8 deletions aya/src/maps/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
//! use aya::maps::SockMap;
//! use aya::programs::SkMsg;
//!
//! let intercept_egress = SockMap::try_from(bpf.map_mut("INTERCEPT_EGRESS")?)?;
//! let intercept_egress = SockMap::try_from(bpf.map_mut("INTERCEPT_EGRESS").unwrap())?;
//! let map_fd = intercept_egress.fd()?;
//! let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?;
//! prog.load()?;
Expand Down Expand Up @@ -90,13 +90,6 @@ pub use stack_trace::StackTraceMap;
#[derive(Error, Debug)]
/// Errors occuring from working with Maps
pub enum MapError {
/// Unable to find the map
#[error("map `{name}` not found ")]
MapNotFound {
/// Map name
name: String,
},

/// Invalid map type encontered
#[error("invalid map type {map_type}")]
InvalidMapType {
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/perf/async_perf_event_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ use crate::maps::{
/// use tokio::task; // or async_std::task
///
/// // try to convert the PERF_ARRAY map to an AsyncPerfEventArray
/// let mut perf_array = AsyncPerfEventArray::try_from(bpf.take_map("PERF_ARRAY")?)?;
/// let mut perf_array = AsyncPerfEventArray::try_from(bpf.take_map("PERF_ARRAY").unwrap())?;
///
/// for cpu_id in online_cpus()? {
/// // open a separate perf buffer for each cpu
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/perf/perf_event_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl<T: AsMut<MapData> + AsRef<MapData>> AsRawFd for PerfEventArrayBuffer<T> {
/// use aya::util::online_cpus;
/// use bytes::BytesMut;
///
/// let mut perf_array = PerfEventArray::try_from(bpf.map_mut("EVENTS")?)?;
/// let mut perf_array = PerfEventArray::try_from(bpf.map_mut("EVENTS").unwrap())?;
///
/// // eBPF programs are going to write to the EVENTS perf array, using the id of the CPU they're
/// // running on as the array index.
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::Queue;
///
/// let mut queue = Queue::try_from(bpf.map_mut("ARRAY")?)?;
/// let mut queue = Queue::try_from(bpf.map_mut("ARRAY").unwrap())?;
/// queue.push(42, 0)?;
/// queue.push(43, 0)?;
/// assert_eq!(queue.pop(0)?, 42);
Expand Down
4 changes: 2 additions & 2 deletions aya/src/maps/sock/sock_hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ use crate::{
/// use aya::maps::SockHash;
/// use aya::programs::SkMsg;
///
/// let mut intercept_egress = SockHash::<_, u32>::try_from(bpf.map("INTERCEPT_EGRESS")?)?;
/// let mut intercept_egress = SockHash::<_, u32>::try_from(bpf.map("INTERCEPT_EGRESS").unwrap())?;
/// let map_fd = intercept_egress.fd()?;
///
/// let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?;
/// prog.load()?;
/// prog.attach(map_fd)?;
///
/// let mut client = TcpStream::connect("127.0.0.1:1234")?;
/// let mut intercept_egress = SockHash::try_from(bpf.map_mut("INTERCEPT_EGRESS")?)?;
/// let mut intercept_egress = SockHash::try_from(bpf.map_mut("INTERCEPT_EGRESS").unwrap())?;
///
/// intercept_egress.insert(1234, client.as_raw_fd(), 0)?;
///
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/sock/sock_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::{
/// use aya::maps::SockMap;
/// use aya::programs::SkSkb;
///
/// let intercept_ingress = SockMap::try_from(bpf.map("INTERCEPT_INGRESS")?)?;
/// let intercept_ingress = SockMap::try_from(bpf.map("INTERCEPT_INGRESS").unwrap())?;
/// let map_fd = intercept_ingress.fd()?;
///
/// let prog: &mut SkSkb = bpf.program_mut("intercept_ingress_packet").unwrap().try_into()?;
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::Stack;
///
/// let mut stack = Stack::try_from(bpf.map_mut("STACK")?)?;
/// let mut stack = Stack::try_from(bpf.map_mut("STACK").unwrap())?;
/// stack.push(42, 0)?;
/// stack.push(43, 0)?;
/// assert_eq!(stack.pop(0)?, 43);
Expand Down
2 changes: 1 addition & 1 deletion aya/src/maps/stack_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use crate::{
/// use aya::maps::StackTraceMap;
/// use aya::util::kernel_symbols;
///
/// let mut stack_traces = StackTraceMap::try_from(bpf.map("STACK_TRACES")?)?;
/// let mut stack_traces = StackTraceMap::try_from(bpf.map("STACK_TRACES").unwrap())?;
/// // load kernel symbols from /proc/kallsyms
/// let ksyms = kernel_symbols()?;
///
Expand Down
4 changes: 2 additions & 2 deletions aya/src/programs/sk_msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@ use crate::{
/// use aya::maps::SockHash;
/// use aya::programs::SkMsg;
///
/// let intercept_egress: SockHash<_, u32> = bpf.map("INTERCEPT_EGRESS")?.try_into()?;
/// let intercept_egress: SockHash<_, u32> = bpf.map("INTERCEPT_EGRESS").unwrap().try_into()?;
/// let map_fd = intercept_egress.fd()?;
///
/// let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?;
/// prog.load()?;
/// prog.attach(map_fd)?;
///
/// let mut client = TcpStream::connect("127.0.0.1:1234")?;
/// let mut intercept_egress: SockHash<_, u32> = bpf.map_mut("INTERCEPT_EGRESS")?.try_into()?;
/// let mut intercept_egress: SockHash<_, u32> = bpf.map_mut("INTERCEPT_EGRESS").unwrap().try_into()?;
///
/// intercept_egress.insert(1234, client.as_raw_fd(), 0)?;
///
Expand Down
2 changes: 1 addition & 1 deletion aya/src/programs/sk_skb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub enum SkSkbKind {
/// use aya::maps::SockMap;
/// use aya::programs::SkSkb;
///
/// let intercept_ingress: SockMap<_> = bpf.map("INTERCEPT_INGRESS")?.try_into()?;
/// let intercept_ingress: SockMap<_> = bpf.map("INTERCEPT_INGRESS").unwrap().try_into()?;
/// let map_fd = intercept_ingress.fd()?;
///
/// let prog: &mut SkSkb = bpf.program_mut("intercept_ingress_packet").unwrap().try_into()?;
Expand Down
4 changes: 2 additions & 2 deletions test/integration-test/src/tests/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ fn multiple_btf_maps() -> anyhow::Result<()> {
include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/multimap-btf.bpf.o");
let mut bpf = Bpf::load(bytes)?;

let map_1: Array<_, u64> = bpf.take_map("map_1")?.try_into()?;
let map_2: Array<_, u64> = bpf.take_map("map_2")?.try_into()?;
let map_1: Array<_, u64> = bpf.take_map("map_1").unwrap().try_into()?;
let map_2: Array<_, u64> = bpf.take_map("map_2").unwrap().try_into()?;

let prog: &mut TracePoint = bpf.program_mut("tracepoint").unwrap().try_into().unwrap();
prog.load().unwrap();
Expand Down

0 comments on commit f3262e8

Please sign in to comment.