Make map APIs return an option

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>
pull/397/head
Andrew Stoycos 2 years ago
parent 4ddf2600b4
commit f3262e87bd

@ -90,7 +90,7 @@ impl BpfLogger {
logger: T, logger: T,
) -> Result<BpfLogger, Error> { ) -> Result<BpfLogger, Error> {
let logger = Arc::new(logger); 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)? { for cpu_id in online_cpus().map_err(Error::InvalidOnlineCpu)? {
let mut buf = logs.open(cpu_id, None)?; let mut buf = logs.open(cpu_id, None)?;

@ -743,14 +743,8 @@ impl Bpf {
/// ///
/// For more details and examples on maps and their usage, see the [maps module /// For more details and examples on maps and their usage, see the [maps module
/// documentation][crate::maps]. /// documentation][crate::maps].
/// pub fn map(&self, name: &str) -> Option<&Map> {
/// # Errors self.maps.get(name)
///
/// 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(),
})
} }
/// Returns a mutable reference to the map with the given name. /// Returns a mutable reference to the map with the given name.
@ -760,16 +754,8 @@ impl Bpf {
/// ///
/// For more details and examples on maps and their usage, see the [maps module /// For more details and examples on maps and their usage, see the [maps module
/// documentation][crate::maps]. /// documentation][crate::maps].
/// pub fn map_mut(&mut self, name: &str) -> Option<&mut Map> {
/// # Errors self.maps.get_mut(name)
///
/// 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(),
})
} }
/// Takes ownership of a map with the given name. /// Takes ownership of a map with the given name.
@ -785,14 +771,8 @@ impl Bpf {
/// ///
/// For more details and examples on maps and their usage, see the [maps module /// For more details and examples on maps and their usage, see the [maps module
/// documentation][crate::maps]. /// documentation][crate::maps].
/// pub fn take_map(&mut self, name: &str) -> Option<Map> {
/// # Errors self.maps.remove(name)
///
/// 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(),
})
} }
/// An iterator over all the maps. /// An iterator over all the maps.
@ -808,8 +788,8 @@ impl Bpf {
/// } /// }
/// # Ok::<(), aya::BpfError>(()) /// # Ok::<(), aya::BpfError>(())
/// ``` /// ```
pub fn maps(&self) -> impl Iterator<Item = (&str, Result<&Map, MapError>)> { pub fn maps(&self) -> impl Iterator<Item = (&str, &Map)> {
self.maps.iter().map(|(name, map)| (name.as_str(), Ok(map))) self.maps.iter().map(|(name, map)| (name.as_str(), map))
} }
/// Returns a reference to the program with the given name. /// Returns a reference to the program with the given name.

@ -23,7 +23,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?; /// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::Array; /// 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)?; /// array.set(1, 42, 0)?;
/// assert_eq!(array.get(&1, 0)?, 42); /// assert_eq!(array.get(&1, 0)?, 42);
/// # Ok::<(), aya::BpfError>(()) /// # Ok::<(), aya::BpfError>(())

@ -33,7 +33,7 @@ use crate::{
/// use aya::maps::{PerCpuArray, PerCpuValues}; /// use aya::maps::{PerCpuArray, PerCpuValues};
/// use aya::util::nr_cpus; /// 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 /// // set array[1] = 42 for all cpus
/// let nr_cpus = nr_cpus()?; /// let nr_cpus = nr_cpus()?;

@ -27,7 +27,7 @@ use crate::{
/// use aya::maps::ProgramArray; /// use aya::maps::ProgramArray;
/// use aya::programs::CgroupSkb; /// 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: &CgroupSkb = bpf.program("example_prog_0").unwrap().try_into()?;
/// let prog_0_fd = prog_0.fd().unwrap(); /// let prog_0_fd = prog_0.fd().unwrap();
/// let prog_1: &CgroupSkb = bpf.program("example_prog_1").unwrap().try_into()?; /// let prog_1: &CgroupSkb = bpf.program("example_prog_1").unwrap().try_into()?;

@ -19,7 +19,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?; /// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::bloom_filter::BloomFilter; /// 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)?; /// bloom_filter.insert(1, 0)?;
/// ///

@ -21,7 +21,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?; /// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::HashMap; /// 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 port 80 to 8080
/// redirect_ports.insert(80, 8080, 0); /// redirect_ports.insert(80, 8080, 0);

@ -31,7 +31,7 @@ use crate::{
/// const CPU_IDS: u8 = 1; /// const CPU_IDS: u8 = 1;
/// const WAKEUPS: u8 = 2; /// 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 cpu_ids = unsafe { hm.get(&CPU_IDS, 0)? };
/// let wakeups = unsafe { hm.get(&WAKEUPS, 0)? }; /// let wakeups = unsafe { hm.get(&WAKEUPS, 0)? };
/// for (cpu_id, wakeups) in cpu_ids.iter().zip(wakeups.iter()) { /// for (cpu_id, wakeups) in cpu_ids.iter().zip(wakeups.iter()) {
@ -107,7 +107,7 @@ impl<T: AsMut<MapData>, K: Pod, V: Pod> PerCpuHashMap<T, K, V> {
/// ///
/// const RETRIES: u8 = 1; /// 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( /// hm.insert(
/// RETRIES, /// RETRIES,
/// PerCpuValues::try_from(vec![3u32; nr_cpus()?])?, /// PerCpuValues::try_from(vec![3u32; nr_cpus()?])?,

@ -24,7 +24,7 @@ use crate::{
/// use aya::maps::lpm_trie::{LpmTrie, Key}; /// use aya::maps::lpm_trie::{LpmTrie, Key};
/// use std::net::Ipv4Addr; /// 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); /// let ipaddr = Ipv4Addr::new(8, 8, 8, 8);
/// // The following represents a key for the "8.8.8.8/16" subnet. /// // 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. /// // The first argument - the prefix length - represents how many bytes should be matched against. The second argument is the actual data to be matched.

@ -22,7 +22,7 @@
//! use aya::maps::SockMap; //! use aya::maps::SockMap;
//! use aya::programs::SkMsg; //! 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 map_fd = intercept_egress.fd()?;
//! let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?; //! let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?;
//! prog.load()?; //! prog.load()?;
@ -90,13 +90,6 @@ pub use stack_trace::StackTraceMap;
#[derive(Error, Debug)] #[derive(Error, Debug)]
/// Errors occuring from working with Maps /// Errors occuring from working with Maps
pub enum MapError { pub enum MapError {
/// Unable to find the map
#[error("map `{name}` not found ")]
MapNotFound {
/// Map name
name: String,
},
/// Invalid map type encontered /// Invalid map type encontered
#[error("invalid map type {map_type}")] #[error("invalid map type {map_type}")]
InvalidMapType { InvalidMapType {

@ -53,7 +53,7 @@ use crate::maps::{
/// use tokio::task; // or async_std::task /// use tokio::task; // or async_std::task
/// ///
/// // try to convert the PERF_ARRAY map to an AsyncPerfEventArray /// // 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()? { /// for cpu_id in online_cpus()? {
/// // open a separate perf buffer for each cpu /// // open a separate perf buffer for each cpu

@ -110,7 +110,7 @@ impl<T: AsMut<MapData> + AsRef<MapData>> AsRawFd for PerfEventArrayBuffer<T> {
/// use aya::util::online_cpus; /// use aya::util::online_cpus;
/// use bytes::BytesMut; /// 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 /// // 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. /// // running on as the array index.

@ -21,7 +21,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?; /// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::Queue; /// 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(42, 0)?;
/// queue.push(43, 0)?; /// queue.push(43, 0)?;
/// assert_eq!(queue.pop(0)?, 42); /// assert_eq!(queue.pop(0)?, 42);

@ -46,7 +46,7 @@ use crate::{
/// use aya::maps::SockHash; /// use aya::maps::SockHash;
/// use aya::programs::SkMsg; /// 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 map_fd = intercept_egress.fd()?;
/// ///
/// let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?; /// let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?;
@ -54,7 +54,7 @@ use crate::{
/// prog.attach(map_fd)?; /// prog.attach(map_fd)?;
/// ///
/// let mut client = TcpStream::connect("127.0.0.1:1234")?; /// 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)?; /// intercept_egress.insert(1234, client.as_raw_fd(), 0)?;
/// ///

@ -30,7 +30,7 @@ use crate::{
/// use aya::maps::SockMap; /// use aya::maps::SockMap;
/// use aya::programs::SkSkb; /// 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 map_fd = intercept_ingress.fd()?;
/// ///
/// let prog: &mut SkSkb = bpf.program_mut("intercept_ingress_packet").unwrap().try_into()?; /// let prog: &mut SkSkb = bpf.program_mut("intercept_ingress_packet").unwrap().try_into()?;

@ -21,7 +21,7 @@ use crate::{
/// # let mut bpf = aya::Bpf::load(&[])?; /// # let mut bpf = aya::Bpf::load(&[])?;
/// use aya::maps::Stack; /// 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(42, 0)?;
/// stack.push(43, 0)?; /// stack.push(43, 0)?;
/// assert_eq!(stack.pop(0)?, 43); /// assert_eq!(stack.pop(0)?, 43);

@ -35,7 +35,7 @@ use crate::{
/// use aya::maps::StackTraceMap; /// use aya::maps::StackTraceMap;
/// use aya::util::kernel_symbols; /// 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 /// // load kernel symbols from /proc/kallsyms
/// let ksyms = kernel_symbols()?; /// let ksyms = kernel_symbols()?;
/// ///

@ -43,7 +43,7 @@ use crate::{
/// use aya::maps::SockHash; /// use aya::maps::SockHash;
/// use aya::programs::SkMsg; /// 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 map_fd = intercept_egress.fd()?;
/// ///
/// let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?; /// let prog: &mut SkMsg = bpf.program_mut("intercept_egress_packet").unwrap().try_into()?;
@ -51,7 +51,7 @@ use crate::{
/// prog.attach(map_fd)?; /// prog.attach(map_fd)?;
/// ///
/// let mut client = TcpStream::connect("127.0.0.1:1234")?; /// 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)?; /// intercept_egress.insert(1234, client.as_raw_fd(), 0)?;
/// ///

@ -41,7 +41,7 @@ pub enum SkSkbKind {
/// use aya::maps::SockMap; /// use aya::maps::SockMap;
/// use aya::programs::SkSkb; /// 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 map_fd = intercept_ingress.fd()?;
/// ///
/// let prog: &mut SkSkb = bpf.program_mut("intercept_ingress_packet").unwrap().try_into()?; /// let prog: &mut SkSkb = bpf.program_mut("intercept_ingress_packet").unwrap().try_into()?;

@ -36,8 +36,8 @@ fn multiple_btf_maps() -> anyhow::Result<()> {
include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/multimap-btf.bpf.o"); include_bytes_aligned!("../../../../target/bpfel-unknown-none/debug/multimap-btf.bpf.o");
let mut bpf = Bpf::load(bytes)?; let mut bpf = Bpf::load(bytes)?;
let map_1: Array<_, u64> = bpf.take_map("map_1")?.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")?.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(); let prog: &mut TracePoint = bpf.program_mut("tracepoint").unwrap().try_into().unwrap();
prog.load().unwrap(); prog.load().unwrap();

Loading…
Cancel
Save