From c192446a595daf144dd6cd428851b9b0e7657fd7 Mon Sep 17 00:00:00 2001 From: Julio Montes Date: Fri, 28 Aug 2020 11:16:34 -0500 Subject: [PATCH] agent/rustjail: Use anyhow for error handling Convert all Errors and Results to `anyhow::Error` and `anyhow::Result` respectively Signed-off-by: Julio Montes --- src/agent/rustjail/src/configs/mod.rs | 1 - src/agent/rustjail/src/container.rs | 80 ++++++++++++--------------- src/agent/rustjail/src/mount.rs | 33 +++++------ src/agent/rustjail/src/sync.rs | 43 ++++++-------- src/agent/rustjail/src/validator.rs | 47 ++++++++-------- 5 files changed, 88 insertions(+), 116 deletions(-) diff --git a/src/agent/rustjail/src/configs/mod.rs b/src/agent/rustjail/src/configs/mod.rs index 2ee991a917..dea1682d26 100644 --- a/src/agent/rustjail/src/configs/mod.rs +++ b/src/agent/rustjail/src/configs/mod.rs @@ -10,7 +10,6 @@ use serde_json; use protocols::oci::State as OCIState; -use crate::errors::*; use std::collections::HashMap; use std::fmt; use std::path::PathBuf; diff --git a/src/agent/rustjail/src/container.rs b/src/agent/rustjail/src/container.rs index ceb8d2c0aa..9b25199e71 100644 --- a/src/agent/rustjail/src/container.rs +++ b/src/agent/rustjail/src/container.rs @@ -14,6 +14,7 @@ use std::os::unix::io::RawFd; use std::path::{Path, PathBuf}; use std::time::SystemTime; // use crate::sync::Cond; +use anyhow::{anyhow, Context, Result}; use libc::pid_t; use oci::{LinuxDevice, LinuxIDMapping}; use std::clone::Clone; @@ -24,7 +25,6 @@ use std::process::{Child, Command}; use crate::cgroups::Manager as CgroupManager; use crate::process::Process; // use crate::intelrdt::Manager as RdtManager; -use crate::errors::*; use crate::log_child; use crate::specconv::CreateOpts; use crate::sync::*; @@ -44,7 +44,6 @@ use nix::sched::{self, CloneFlags}; use nix::sys::signal::{self, Signal}; use nix::sys::stat::{self, Mode}; use nix::unistd::{self, ForkResult, Gid, Pid, Uid}; -use nix::Error; use libc; use protobuf::SingularPtrField; @@ -294,11 +293,10 @@ impl Container for LinuxContainer { fn pause(&mut self) -> Result<()> { let status = self.status(); if status != Status::RUNNING && status != Status::CREATED { - return Err(ErrorKind::ErrorCode(format!( + return Err(anyhow!( "failed to pause container: current status is: {:?}", status - )) - .into()); + )); } if self.cgroup_manager.is_some() { @@ -310,17 +308,13 @@ impl Container for LinuxContainer { self.status.transition(Status::PAUSED); return Ok(()); } - Err(ErrorKind::ErrorCode(String::from("failed to get container's cgroup manager")).into()) + Err(anyhow!("failed to get container's cgroup manager")) } fn resume(&mut self) -> Result<()> { let status = self.status(); if status != Status::PAUSED { - return Err(ErrorKind::ErrorCode(format!( - "container status is: {:?}, not paused", - status - )) - .into()); + return Err(anyhow!("container status is: {:?}, not paused", status)); } if self.cgroup_manager.is_some() { @@ -332,7 +326,7 @@ impl Container for LinuxContainer { self.status.transition(Status::RUNNING); return Ok(()); } - Err(ErrorKind::ErrorCode(String::from("failed to get container's cgroup manager")).into()) + Err(anyhow!("failed to get container's cgroup manager")) } } @@ -383,11 +377,11 @@ fn do_init_child(cwfd: RawFd) -> Result<()> { let p = if spec.process.is_some() { spec.process.as_ref().unwrap() } else { - return Err(ErrorKind::ErrorCode("didn't find process in Spec".to_string()).into()); + return Err(anyhow!("didn't find process in Spec")); }; if spec.linux.is_none() { - return Err(ErrorKind::ErrorCode("no linux config".to_string()).into()); + return Err(anyhow!("no linux config")); } let linux = spec.linux.as_ref().unwrap(); @@ -401,7 +395,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> { for ns in &nses { let s = NAMESPACES.get(&ns.r#type.as_str()); if s.is_none() { - return Err(ErrorKind::ErrorCode("invalid ns type".to_string()).into()); + return Err(anyhow!("invalid ns type")); } let s = s.unwrap(); @@ -569,7 +563,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> { // NoNewPeiviledges, Drop capabilities if oci_process.no_new_privileges { if let Err(_) = prctl::set_no_new_privileges(true) { - return Err(ErrorKind::ErrorCode("cannot set no new privileges".to_string()).into()); + return Err(anyhow!("cannot set no new privileges")); } } @@ -621,9 +615,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> { match find_file(exec_file) { Some(_) => (), None => { - return Err( - ErrorKind::ErrorCode(format!("the file {} is not exist", &args[0])).into(), - ); + return Err(anyhow!("the file {} is not exist", &args[0])); } } } @@ -655,7 +647,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> { do_exec(&args); - Err(ErrorKind::ErrorCode("fail to create container".to_string()).into()) + Err(anyhow!("fail to create container")) } impl BaseContainer for LinuxContainer { @@ -668,7 +660,7 @@ impl BaseContainer for LinuxContainer { } fn state(&self) -> Result { - Err(ErrorKind::ErrorCode(String::from("not suppoerted")).into()) + Err(anyhow!("not suppoerted")) } fn oci_state(&self) -> Result { @@ -708,7 +700,7 @@ impl BaseContainer for LinuxContainer { } } - Err(ErrorKind::ErrorCode(format!("invalid eid {}", eid)).into()) + Err(anyhow!("invalid eid {}", eid)) } fn stats(&self) -> Result { @@ -747,7 +739,7 @@ impl BaseContainer for LinuxContainer { let mut fifofd: RawFd = -1; if p.init { if let Ok(_) = stat::stat(fifo_file.as_str()) { - return Err(ErrorKind::ErrorCode("exec fifo exists".to_string()).into()); + return Err(anyhow!("exec fifo exists")); } unistd::mkfifo(fifo_file.as_str(), Mode::from_bits(0o622).unwrap())?; // defer!(fs::remove_file(&fifo_file)?); @@ -763,18 +755,18 @@ impl BaseContainer for LinuxContainer { fscgroup::init_static(); if self.config.spec.is_none() { - return Err(ErrorKind::ErrorCode("no spec".to_string()).into()); + return Err(anyhow!("no spec")); } let spec = self.config.spec.as_ref().unwrap(); if spec.linux.is_none() { - return Err(ErrorKind::ErrorCode("no linux config".to_string()).into()); + return Err(anyhow!("no linux config")); } let linux = spec.linux.as_ref().unwrap(); let st = self.oci_state()?; - let (pfd_log, cfd_log) = unistd::pipe().chain_err(|| "failed to create pipe")?; + let (pfd_log, cfd_log) = unistd::pipe().context("failed to create pipe")?; fcntl::fcntl(pfd_log, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)); let child_logger = logger.new(o!("action" => "child process log")); @@ -802,8 +794,8 @@ impl BaseContainer for LinuxContainer { }); info!(logger, "exec fifo opened!"); - let (prfd, cwfd) = unistd::pipe().chain_err(|| "failed to create pipe")?; - let (crfd, pwfd) = unistd::pipe().chain_err(|| "failed to create pipe")?; + let (prfd, cwfd) = unistd::pipe().context("failed to create pipe")?; + let (crfd, pwfd) = unistd::pipe().context("failed to create pipe")?; fcntl::fcntl(prfd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)); fcntl::fcntl(pwfd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)); @@ -858,7 +850,7 @@ impl BaseContainer for LinuxContainer { if pidns.is_some() { sched::setns(pidns.unwrap(), CloneFlags::CLONE_NEWPID) - .chain_err(|| "failed to join pidns")?; + .context("failed to join pidns")?; unistd::close(pidns.unwrap())?; } else { sched::unshare(CloneFlags::CLONE_NEWPID)?; @@ -923,7 +915,7 @@ impl BaseContainer for LinuxContainer { // create the pipes for notify process exited let (exit_pipe_r, exit_pipe_w) = unistd::pipe2(OFlag::O_CLOEXEC) - .chain_err(|| "failed to create pipe") + .context("failed to create pipe") .map_err(|e| { signal::kill(Pid::from_raw(child.id() as i32), Some(Signal::SIGKILL)); e @@ -1056,11 +1048,7 @@ fn do_exec(args: &[String]) -> Result<()> { fn update_namespaces(logger: &Logger, spec: &mut Spec, init_pid: RawFd) -> Result<()> { let linux = match spec.linux.as_mut() { - None => { - return Err( - ErrorKind::ErrorCode("Spec didn't container linux field".to_string()).into(), - ) - } + None => return Err(anyhow!("Spec didn't container linux field")), Some(l) => l, }; @@ -1107,7 +1095,7 @@ fn get_pid_namespace(logger: &Logger, linux: &Linux) -> Result> { } } - Err(ErrorKind::ErrorCode("cannot find the pid ns".to_string()).into()) + Err(anyhow!("cannot find the pid ns")) } fn is_userns_enabled(linux: &Linux) -> bool { @@ -1271,7 +1259,7 @@ fn write_mappings(logger: &Logger, path: &str, maps: &[LinuxIDMapping]) -> Resul fn setid(uid: Uid, gid: Gid) -> Result<()> { // set uid/gid if let Err(e) = prctl::set_keep_capabilities(true) { - bail!(format!("set keep capabilities returned {}", e)); + bail!(anyhow!(e).context("set keep capabilities returned")); }; { unistd::setresgid(gid, gid, gid)?; @@ -1285,7 +1273,7 @@ fn setid(uid: Uid, gid: Gid) -> Result<()> { } if let Err(e) = prctl::set_keep_capabilities(false) { - bail!(format!("set keep capabilities returned {}", e)); + bail!(anyhow!(e).context("set keep capabilities returned")); }; Ok(()) } @@ -1306,10 +1294,10 @@ impl LinuxContainer { if let Err(e) = fs::create_dir_all(root.as_str()) { if e.kind() == std::io::ErrorKind::AlreadyExists { - return Err(e).chain_err(|| format!("container {} already exists", id.as_str())); + return Err(e).context(format!("container {} already exists", id.as_str())); } - return Err(e).chain_err(|| format!("fail to create container directory {}", root)); + return Err(e).context(format!("fail to create container directory {}", root)); } unistd::chown( @@ -1317,7 +1305,7 @@ impl LinuxContainer { Some(unistd::getuid()), Some(unistd::getgid()), ) - .chain_err(|| format!("cannot change onwer of container {} root", id))?; + .context(format!("cannot change onwer of container {} root", id))?; if config.spec.is_none() { return Err(nix::Error::Sys(Errno::EINVAL).into()); @@ -1359,7 +1347,7 @@ impl LinuxContainer { } fn load>(_id: T, _base: T) -> Result { - Err(ErrorKind::ErrorCode("not supported".to_string()).into()) + Err(anyhow!("not supported")) } /* fn new_parent_process(&self, p: &Process) -> Result> { @@ -1500,7 +1488,7 @@ fn execute_hook(logger: &Logger, h: &Hook, st: &OCIState) -> Result<()> { let binary = PathBuf::from(h.path.as_str()); let path = binary.canonicalize()?; if !path.exists() { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } let args = h.args.clone(); @@ -1531,11 +1519,11 @@ fn execute_hook(logger: &Logger, h: &Hook, st: &OCIState) -> Result<()> { if status != 0 { if status == -libc::ETIMEDOUT { - return Err(ErrorKind::Nix(Error::from_errno(Errno::ETIMEDOUT)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::ETIMEDOUT))); } else if status == -libc::EPIPE { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EPIPE)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EPIPE))); } else { - return Err(ErrorKind::Nix(Error::from_errno(Errno::UnknownErrno)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::UnknownErrno))); } } diff --git a/src/agent/rustjail/src/mount.rs b/src/agent/rustjail/src/mount.rs index 69f3560b13..ae0e7c5be6 100644 --- a/src/agent/rustjail/src/mount.rs +++ b/src/agent/rustjail/src/mount.rs @@ -3,6 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // +use anyhow::{anyhow, Context, Error, Result}; use libc::uid_t; use nix::errno::Errno; use nix::fcntl::{self, OFlag}; @@ -23,7 +24,6 @@ use std::fs::File; use std::io::{BufRead, BufReader}; use crate::container::DEFAULT_DEVICES; -use crate::errors::*; use crate::sync::write_count; use lazy_static; use std::string::ToString; @@ -139,7 +139,7 @@ pub fn init_rootfs( for m in &spec.mounts { let (mut flags, data) = parse_mount(&m); if !m.destination.starts_with("/") || m.destination.contains("..") { - return Err(ErrorKind::Nix(nix::Error::Sys(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::Sys(Errno::EINVAL))); } if m.r#type == "cgroup" { mount_cgroups(cfd_log, &m, rootfs, flags, &data, cpath, mounts)?; @@ -289,7 +289,7 @@ pub fn pivot_rootfs(path: &P) -> Result<( // Change to the new root so that the pivot_root actually acts on it. unistd::fchdir(newroot)?; - unistd::pivot_root(".", ".").chain_err(|| format!("failed to pivot_root on {:?}", path))?; + unistd::pivot_root(".", ".").context(format!("failed to pivot_root on {:?}", path))?; // Currently our "." is oldroot (according to the current kernel code). // However, purely for safety, we will fchdir(oldroot) since there isn't @@ -311,7 +311,7 @@ pub fn pivot_rootfs(path: &P) -> Result<( )?; // Preform the unmount. MNT_DETACH allows us to unmount /proc/self/cwd. - mount::umount2(".", MntFlags::MNT_DETACH).chain_err(|| "failed to do umount2")?; + mount::umount2(".", MntFlags::MNT_DETACH).context("failed to do umount2")?; // Switch back to our shiny new root. unistd::chdir("/")?; @@ -395,7 +395,7 @@ fn parse_mount_table() -> Result> { infos.push(info); } else { - return Err(ErrorKind::ErrorCode("failed to parse mount info file".to_string()).into()); + return Err(anyhow!("failed to parse mount info file".to_string())); } } @@ -408,20 +408,17 @@ pub fn ms_move_root(rootfs: &str) -> Result { let root_path = Path::new(rootfs); let abs_root_buf = root_path.absolutize()?; - let abs_root = abs_root_buf.to_str().ok_or::( - ErrorKind::ErrorCode(format!("failed to parse {} to absolute path", rootfs)).into(), - )?; + let abs_root = abs_root_buf + .to_str() + .ok_or::(anyhow!("failed to parse {} to absolute path", rootfs))?; for info in mount_infos.iter() { let mount_point = Path::new(&info.mount_point); let abs_mount_buf = mount_point.absolutize()?; - let abs_mount_point = abs_mount_buf.to_str().ok_or::( - ErrorKind::ErrorCode(format!( - "failed to parse {} to absolute path", - info.mount_point - )) - .into(), - )?; + let abs_mount_point = abs_mount_buf.to_str().ok_or::(anyhow!( + "failed to parse {} to absolute path", + info.mount_point + ))?; let abs_mount_point_string = String::from(abs_mount_point); // Umount every syfs and proc file systems, except those under the container rootfs @@ -443,7 +440,7 @@ pub fn ms_move_root(rootfs: &str) -> Result { Ok(_) => (), Err(e) => { if e.ne(&nix::Error::from(Errno::EINVAL)) && e.ne(&nix::Error::from(Errno::EPERM)) { - return Err(ErrorKind::ErrorCode(e.to_string()).into()); + return Err(anyhow!(e)); } // If we have not privileges for umounting (e.g. rootless), then @@ -630,7 +627,7 @@ fn create_devices(devices: &[LinuxDevice], bind: bool) -> Result<()> { for dev in devices { if !dev.path.starts_with("/dev") || dev.path.contains("..") { let msg = format!("{} is not a valid device path", dev.path); - bail!(ErrorKind::ErrorCode(msg)); + bail!(anyhow!(msg)); } op(dev)?; } @@ -661,7 +658,7 @@ lazy_static! { fn mknod_dev(dev: &LinuxDevice) -> Result<()> { let f = match LINUXDEVICETYPE.get(dev.r#type.as_str()) { Some(v) => v, - None => return Err(ErrorKind::ErrorCode("invalid spec".to_string()).into()), + None => return Err(anyhow!("invalid spec".to_string())), }; stat::mknod( diff --git a/src/agent/rustjail/src/sync.rs b/src/agent/rustjail/src/sync.rs index b17277f87b..20bf7b4706 100644 --- a/src/agent/rustjail/src/sync.rs +++ b/src/agent/rustjail/src/sync.rs @@ -3,13 +3,13 @@ // SPDX-License-Identifier: Apache-2.0 // -use crate::errors::*; use nix::errno::Errno; use nix::unistd; -use nix::Error; use std::mem; use std::os::unix::io::RawFd; +use anyhow::{anyhow, Result}; + pub const SYNC_SUCCESS: i32 = 1; pub const SYNC_FAILED: i32 = 2; pub const SYNC_DATA: i32 = 3; @@ -40,7 +40,7 @@ pub fn write_count(fd: RawFd, buf: &[u8], count: usize) -> Result { } Err(e) => { - if e != Error::from_errno(Errno::EINTR) { + if e != nix::Error::from_errno(Errno::EINTR) { return Err(e.into()); } } @@ -64,7 +64,7 @@ fn read_count(fd: RawFd, count: usize) -> Result> { } Err(e) => { - if e != Error::from_errno(Errno::EINTR) { + if e != nix::Error::from_errno(Errno::EINTR) { return Err(e.into()); } } @@ -77,13 +77,12 @@ fn read_count(fd: RawFd, count: usize) -> Result> { pub fn read_sync(fd: RawFd) -> Result> { let buf = read_count(fd, MSG_SIZE)?; if buf.len() != MSG_SIZE { - return Err(ErrorKind::ErrorCode(format!( + return Err(anyhow!( "process: {} failed to receive sync message from peer: got msg length: {}, expected: {}", std::process::id(), buf.len(), MSG_SIZE - )) - .into()); + )); } let buf_array: [u8; MSG_SIZE] = [buf[0], buf[1], buf[2], buf[3]]; let msg: i32 = i32::from_be_bytes(buf_array); @@ -111,19 +110,17 @@ pub fn read_sync(fd: RawFd) -> Result> { } let error_str = match std::str::from_utf8(&error_buf) { - Ok(v) => v, + Ok(v) => String::from(v), Err(e) => { - return Err(ErrorKind::ErrorCode(format!( - "receive error message from child process failed: {:?}", - e - )) - .into()) + return Err( + anyhow!(e).context("receive error message from child process failed") + ); } }; - return Err(ErrorKind::ErrorCode(String::from(error_str)).into()); + return Err(anyhow!(error_str)); } - _ => return Err(ErrorKind::ErrorCode("error in receive sync message".to_string()).into()), + _ => return Err(anyhow!("error in receive sync message")), } } @@ -132,7 +129,7 @@ pub fn write_sync(fd: RawFd, msg_type: i32, data_str: &str) -> Result<()> { let count = write_count(fd, &buf, MSG_SIZE)?; if count != MSG_SIZE { - return Err(ErrorKind::ErrorCode("error in send sync message".to_string()).into()); + return Err(anyhow!("error in send sync message")); } match msg_type { @@ -140,9 +137,7 @@ pub fn write_sync(fd: RawFd, msg_type: i32, data_str: &str) -> Result<()> { Ok(_count) => unistd::close(fd)?, Err(e) => { unistd::close(fd)?; - return Err( - ErrorKind::ErrorCode("error in send message to process".to_string()).into(), - ); + return Err(anyhow!(e).context("error in send message to process")); } }, SYNC_DATA => { @@ -151,10 +146,7 @@ pub fn write_sync(fd: RawFd, msg_type: i32, data_str: &str) -> Result<()> { Ok(_count) => (), Err(e) => { unistd::close(fd)?; - return Err(ErrorKind::ErrorCode( - "error in send message to process".to_string(), - ) - .into()); + return Err(anyhow!(e).context("error in send message to process")); } } @@ -162,10 +154,7 @@ pub fn write_sync(fd: RawFd, msg_type: i32, data_str: &str) -> Result<()> { Ok(_count) => (), Err(e) => { unistd::close(fd)?; - return Err(ErrorKind::ErrorCode( - "error in send message to process".to_string(), - ) - .into()); + return Err(anyhow!(e).context("error in send message to process")); } } } diff --git a/src/agent/rustjail/src/validator.rs b/src/agent/rustjail/src/validator.rs index 3e06398d89..14ffef1bd8 100644 --- a/src/agent/rustjail/src/validator.rs +++ b/src/agent/rustjail/src/validator.rs @@ -4,10 +4,9 @@ // use crate::container::Config; -use crate::errors::*; +use anyhow::{anyhow, Result}; use lazy_static; use nix::errno::Errno; -use nix::Error; use oci::{LinuxIDMapping, LinuxNamespace, Spec}; use protobuf::RepeatedField; use std::collections::HashMap; @@ -30,14 +29,14 @@ fn get_namespace_path(nses: &Vec, key: &str) -> Result { } } - Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()) + Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))) } fn rootfs(root: &str) -> Result<()> { let path = PathBuf::from(root); // not absolute path or not exists if !path.exists() || !path.is_absolute() { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } // symbolic link? ..? @@ -65,7 +64,7 @@ fn rootfs(root: &str) -> Result<()> { let canon = path.canonicalize()?; if cleaned != canon { // There is symbolic in path - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } Ok(()) @@ -81,11 +80,11 @@ fn hostname(oci: &Spec) -> Result<()> { } if oci.linux.is_none() { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } let linux = oci.linux.as_ref().unwrap(); if !contain_namespace(&linux.namespaces, "uts") { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } Ok(()) @@ -98,7 +97,7 @@ fn security(oci: &Spec) -> Result<()> { } if !contain_namespace(&linux.namespaces, "mount") { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } // don't care about selinux at present @@ -113,7 +112,7 @@ fn idmapping(maps: &Vec) -> Result<()> { } } - Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()) + Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))) } fn usernamespace(oci: &Spec) -> Result<()> { @@ -121,7 +120,7 @@ fn usernamespace(oci: &Spec) -> Result<()> { if contain_namespace(&linux.namespaces, "user") { let user_ns = PathBuf::from("/proc/self/ns/user"); if !user_ns.exists() { - return Err(ErrorKind::ErrorCode("user namespace not supported!".to_string()).into()); + return Err(anyhow!("user namespace not supported!")); } // check if idmappings is correct, at least I saw idmaps // with zero size was passed to agent @@ -130,7 +129,7 @@ fn usernamespace(oci: &Spec) -> Result<()> { } else { // no user namespace but idmap if linux.uid_mappings.len() != 0 || linux.gid_mappings.len() != 0 { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } } @@ -142,7 +141,7 @@ fn cgroupnamespace(oci: &Spec) -> Result<()> { if contain_namespace(&linux.namespaces, "cgroup") { let path = PathBuf::from("/proc/self/ns/cgroup"); if !path.exists() { - return Err(ErrorKind::ErrorCode("cgroup unsupported!".to_string()).into()); + return Err(anyhow!("cgroup unsupported!")); } } Ok(()) @@ -176,7 +175,7 @@ fn check_host_ns(path: &str) -> Result<()> { } let real_cpath = cpath.read_link()?; if real_cpath == real_hpath { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } Ok(()) @@ -189,13 +188,13 @@ fn sysctl(oci: &Spec) -> Result<()> { if contain_namespace(&linux.namespaces, "ipc") { continue; } else { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } } if key.starts_with("net.") { if !contain_namespace(&linux.namespaces, "network") { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } let net = get_namespace_path(&linux.namespaces, "network")?; @@ -212,11 +211,11 @@ fn sysctl(oci: &Spec) -> Result<()> { } if key == "kernel.hostname" { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } } - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } Ok(()) } @@ -224,11 +223,11 @@ fn sysctl(oci: &Spec) -> Result<()> { fn rootless_euid_mapping(oci: &Spec) -> Result<()> { let linux = oci.linux.as_ref().unwrap(); if !contain_namespace(&linux.namespaces, "user") { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } if linux.gid_mappings.len() == 0 || linux.gid_mappings.len() == 0 { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } Ok(()) @@ -252,20 +251,20 @@ fn rootless_euid_mount(oci: &Spec) -> Result<()> { let fields: Vec<&str> = opt.split('=').collect(); if fields.len() != 2 { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } let id = fields[1].trim().parse::()?; if opt.starts_with("uid=") { if !has_idmapping(&linux.uid_mappings, id) { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } } if opt.starts_with("gid=") { if !has_idmapping(&linux.gid_mappings, id) { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } } } @@ -285,11 +284,11 @@ pub fn validate(conf: &Config) -> Result<()> { let oci = conf.spec.as_ref().unwrap(); if oci.linux.is_none() { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } if oci.root.is_none() { - return Err(ErrorKind::Nix(Error::from_errno(Errno::EINVAL)).into()); + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } let root = oci.root.as_ref().unwrap().path.as_str();