agent: Use anyhow for error handling

Don't use `rustjail::errors` for error handling, since it's not
thread safe and there are better alternatives like `anyhow`.

`anyhow` attaches context to help the person troubleshooting
the error understand where things went wrong, for example:

Current error messages:

```
No such file or directory (os error 2)
```

With `anyhow`:

```
Error: Failed to read config.json
Caused by:
    No such file or directory (os error 2)
```

fixes #641

Signed-off-by: Julio Montes <julio.montes@intel.com>
This commit is contained in:
Julio Montes 2020-08-28 13:47:48 -05:00
parent 33759af548
commit fbb79739c9
8 changed files with 116 additions and 187 deletions

View File

@ -2,7 +2,7 @@
//
// SPDX-License-Identifier: Apache-2.0
//
use rustjail::errors::*;
use anyhow::{anyhow, Result};
use std::env;
use std::fs;
use std::time;
@ -108,7 +108,7 @@ impl agentConfig {
fn get_vsock_port(p: &str) -> Result<i32> {
let fields: Vec<&str> = p.split("=").collect();
if fields.len() != 2 {
return Err(ErrorKind::ErrorCode("invalid port parameter".to_string()).into());
return Err(anyhow!("invalid port parameter"));
}
Ok(fields[1].parse::<i32>()?)
@ -134,7 +134,7 @@ fn logrus_to_slog_level(logrus_level: &str) -> Result<slog::Level> {
"trace" => slog::Level::Trace,
_ => {
return Err(ErrorKind::ErrorCode(String::from("invalid log level")).into());
return Err(anyhow!("invalid log level"));
}
};
@ -145,11 +145,11 @@ fn get_log_level(param: &str) -> Result<slog::Level> {
let fields: Vec<&str> = param.split("=").collect();
if fields.len() != 2 {
return Err(ErrorKind::ErrorCode(String::from("invalid log level parameter")).into());
return Err(anyhow!("invalid log level parameter"));
}
if fields[0] != LOG_LEVEL_OPTION {
Err(ErrorKind::ErrorCode(String::from("invalid log level key name")).into())
Err(anyhow!("invalid log level key name"))
} else {
Ok(logrus_to_slog_level(fields[1])?)
}
@ -159,17 +159,17 @@ fn get_hotplug_timeout(param: &str) -> Result<time::Duration> {
let fields: Vec<&str> = param.split("=").collect();
if fields.len() != 2 {
return Err(ErrorKind::ErrorCode(String::from("invalid hotplug timeout parameter")).into());
return Err(anyhow!("invalid hotplug timeout parameter"));
}
let key = fields[0];
if key != HOTPLUG_TIMOUT_OPTION {
return Err(ErrorKind::ErrorCode(String::from("invalid hotplug timeout key name")).into());
return Err(anyhow!("invalid hotplug timeout key name"));
}
let value = fields[1].parse::<u64>();
if value.is_err() {
return Err(ErrorKind::ErrorCode(String::from("unable to parse hotplug timeout")).into());
return Err(anyhow!("unable to parse hotplug timeout"));
}
Ok(time::Duration::from_secs(value.unwrap()))
@ -179,31 +179,22 @@ fn get_container_pipe_size(param: &str) -> Result<i32> {
let fields: Vec<&str> = param.split("=").collect();
if fields.len() != 2 {
return Err(
ErrorKind::ErrorCode(String::from("invalid container pipe size parameter")).into(),
);
return Err(anyhow!("invalid container pipe size parameter"));
}
let key = fields[0];
if key != CONTAINER_PIPE_SIZE_OPTION {
return Err(
ErrorKind::ErrorCode(String::from("invalid container pipe size key name")).into(),
);
return Err(anyhow!("invalid container pipe size key name"));
}
let res = fields[1].parse::<i32>();
if res.is_err() {
return Err(
ErrorKind::ErrorCode(String::from("unable to parse container pipe size")).into(),
);
return Err(anyhow!("unable to parse container pipe size"));
}
let value = res.unwrap();
if value < 0 {
return Err(ErrorKind::ErrorCode(String::from(
"container pipe size should not be negative",
))
.into());
return Err(anyhow!("container pipe size should not be negative"));
}
Ok(value)
@ -232,7 +223,7 @@ mod tests {
// helper function to make errors less crazy-long
fn make_err(desc: &str) -> Error {
ErrorKind::ErrorCode(desc.to_string()).into()
anyhow!(desc)
}
// Parameters:

View File

@ -15,9 +15,9 @@ use crate::linux_abi::*;
use crate::mount::{DRIVERBLKTYPE, DRIVERMMIOBLKTYPE, DRIVERNVDIMMTYPE, DRIVERSCSITYPE};
use crate::sandbox::Sandbox;
use crate::{AGENT_CONFIG, GLOBAL_DEVICE_WATCHER};
use anyhow::{anyhow, Result};
use oci::{LinuxDeviceCgroup, LinuxResources, Spec};
use protocols::agent::Device;
use rustjail::errors::*;
// Convenience macro to obtain the scope logger
macro_rules! sl {
@ -61,11 +61,10 @@ fn get_pci_device_address(pci_id: &str) -> Result<String> {
let tokens: Vec<&str> = pci_id.split("/").collect();
if tokens.len() != 2 {
return Err(ErrorKind::ErrorCode(format!(
return Err(anyhow!(
"PCI Identifier for device should be of format [bridgeAddr/deviceAddr], got {}",
pci_id
))
.into());
));
}
let bridge_id = tokens[0];
@ -85,11 +84,11 @@ fn get_pci_device_address(pci_id: &str) -> Result<String> {
let bus_num = files_slice.len();
if bus_num != 1 {
return Err(ErrorKind::ErrorCode(format!(
return Err(anyhow!(
"Expected an entry for bus in {}, got {} entries instead",
bridge_bus_path, bus_num
))
.into());
bridge_bus_path,
bus_num
));
}
let bus = files_slice[0].file_name().unwrap().to_str().unwrap();
@ -135,11 +134,11 @@ fn get_device_name(sandbox: &Arc<Mutex<Sandbox>>, dev_addr: &str) -> Result<Stri
Ok(name) => name,
Err(_) => {
GLOBAL_DEVICE_WATCHER.lock().unwrap().remove_entry(dev_addr);
return Err(ErrorKind::ErrorCode(format!(
return Err(anyhow!(
"Timeout reached after {:?} waiting for device {}",
hotplug_timeout, dev_addr
))
.into());
hotplug_timeout,
dev_addr
));
}
};
@ -164,11 +163,10 @@ pub fn get_pci_device_name(sandbox: &Arc<Mutex<Sandbox>>, pci_id: &str) -> Resul
fn scan_scsi_bus(scsi_addr: &str) -> Result<()> {
let tokens: Vec<&str> = scsi_addr.split(":").collect();
if tokens.len() != 2 {
return Err(ErrorKind::Msg(format!(
return Err(anyhow!(
"Unexpected format for SCSI Address: {}, expect SCSIID:LUA",
scsi_addr
))
.into());
));
}
// Scan scsi host passing in the channel, SCSI id and LUN.
@ -203,24 +201,19 @@ fn update_spec_device_list(device: &Device, spec: &mut Spec) -> Result<()> {
// If no container_path is provided, we won't be able to match and
// update the device in the OCI spec device list. This is an error.
if device.container_path == "" {
return Err(ErrorKind::Msg(format!(
return Err(anyhow!(
"container_path cannot empty for device {:?}",
device
))
.into());
));
}
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,
};
if !Path::new(&device.vm_path).exists() {
return Err(ErrorKind::Msg(format!("vm_path:{} doesn't exist", device.vm_path)).into());
return Err(anyhow!("vm_path:{} doesn't exist", device.vm_path));
}
let meta = fs::metadata(&device.vm_path)?;
@ -283,7 +276,7 @@ fn virtiommio_blk_device_handler(
_sandbox: &Arc<Mutex<Sandbox>>,
) -> Result<()> {
if device.vm_path == "" {
return Err(ErrorKind::Msg("Invalid path for virtio mmio blk device".to_string()).into());
return Err(anyhow!("Invalid path for virtio mmio blk device"));
}
update_spec_device_list(device, spec)
@ -325,7 +318,7 @@ fn virtio_nvdimm_device_handler(
_sandbox: &Arc<Mutex<Sandbox>>,
) -> Result<()> {
if device.vm_path == "" {
return Err(ErrorKind::Msg("Invalid path for nvdimm device".to_string()).into());
return Err(anyhow!("Invalid path for nvdimm device"));
}
update_spec_device_list(device, spec)
@ -349,23 +342,19 @@ fn add_device(device: &Device, spec: &mut Spec, sandbox: &Arc<Mutex<Sandbox>>) -
device.id, device.field_type, device.vm_path, device.container_path, device.options);
if device.field_type == "" {
return Err(ErrorKind::Msg(format!("invalid type for device {:?}", device)).into());
return Err(anyhow!("invalid type for device {:?}", device));
}
if device.id == "" && device.vm_path == "" {
return Err(
ErrorKind::Msg(format!("invalid ID and VM path for device {:?}", device)).into(),
);
return Err(anyhow!("invalid ID and VM path for device {:?}", device));
}
if device.container_path == "" {
return Err(
ErrorKind::Msg(format!("invalid container path for device {:?}", device)).into(),
);
return Err(anyhow!("invalid container path for device {:?}", device));
}
match DEVICEHANDLERLIST.get(device.field_type.as_str()) {
None => Err(ErrorKind::Msg(format!("Unknown device type {}", device.field_type)).into()),
None => Err(anyhow!("Unknown device type {}", device.field_type)),
Some(dev_handler) => dev_handler(device, spec, sandbox),
}
}
@ -380,11 +369,7 @@ pub fn update_device_cgroup(spec: &mut Spec) -> Result<()> {
let minor = stat::minor(rdev) as i64;
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,
};

View File

@ -29,13 +29,13 @@ extern crate slog;
extern crate netlink;
use crate::netlink::{RtnlHandle, NETLINK_ROUTE};
use anyhow::{anyhow, Context, Result};
use nix::fcntl::{self, OFlag};
use nix::sys::socket::{self, AddressFamily, SockAddr, SockFlag, SockType};
use nix::sys::wait::{self, WaitStatus};
use nix::unistd;
use nix::unistd::dup;
use prctl::set_child_subreaper;
use rustjail::errors::*;
use signal_hook::{iterator::Signals, SIGCHLD};
use std::collections::HashMap;
use std::env;
@ -208,26 +208,21 @@ fn start_sandbox(logger: &Logger, config: &agentConfig, init_mode: bool) -> Resu
let builder = thread::Builder::new();
let handle = builder
.spawn(move || {
let shells = shells.lock().unwrap();
let result = setup_debug_console(shells.to_vec(), debug_console_vport);
if result.is_err() {
// Report error, but don't fail
warn!(thread_logger, "failed to setup debug console";
let handle = builder.spawn(move || {
let shells = shells.lock().unwrap();
let result = setup_debug_console(shells.to_vec(), debug_console_vport);
if result.is_err() {
// Report error, but don't fail
warn!(thread_logger, "failed to setup debug console";
"error" => format!("{}", result.unwrap_err()));
}
})
.map_err(|e| format!("{:?}", e))?;
}
})?;
shell_handle = Some(handle);
}
// Initialize unique sandbox structure.
let mut s = Sandbox::new(&logger).map_err(|e| {
error!(logger, "Failed to create sandbox with error: {:?}", e);
e
})?;
let mut s = Sandbox::new(&logger).context("Failed to create sandbox")?;
if init_mode {
let mut rtnl = RtnlHandle::new(NETLINK_ROUTE, 0).unwrap();
@ -249,12 +244,12 @@ fn start_sandbox(logger: &Logger, config: &agentConfig, init_mode: bool) -> Resu
let _ = server.start().unwrap();
let _ = rx.recv().map_err(|e| format!("{:?}", e));
let _ = rx.recv()?;
server.shutdown();
if let Some(handle) = shell_handle {
handle.join().map_err(|e| format!("{:?}", e))?;
handle.join().map_err(|e| anyhow!("{:?}", e))?;
}
Ok(())
@ -265,12 +260,8 @@ use nix::sys::wait::WaitPidFlag;
fn setup_signal_handler(logger: &Logger, sandbox: Arc<Mutex<Sandbox>>) -> Result<()> {
let logger = logger.new(o!("subsystem" => "signals"));
set_child_subreaper(true).map_err(|err| {
format!(
"failed to setup agent as a child subreaper, failed with {}",
err
)
})?;
set_child_subreaper(true)
.map_err(|err| anyhow!(err).context("failed to setup agent as a child subreaper"))?;
let signals = Signals::new(&[SIGCHLD])?;
@ -381,7 +372,7 @@ fn sethostname(hostname: &OsStr) -> Result<()> {
unsafe { libc::sethostname(hostname.as_bytes().as_ptr() as *const libc::c_char, size) };
if result != 0 {
Err(ErrorKind::ErrorCode("failed to set hostname".to_string()).into())
Err(anyhow!("failed to set hostname"))
} else {
Ok(())
}
@ -420,9 +411,7 @@ fn setup_debug_console(shells: Vec<String>, port: u32) -> Result<()> {
}
if shell == "" {
return Err(
ErrorKind::ErrorCode("no shell found to launch debug console".to_string()).into(),
);
return Err(anyhow!("no shell found to launch debug console"));
}
let f: RawFd = if port > 0 {
@ -452,7 +441,7 @@ fn setup_debug_console(shells: Vec<String>, port: u32) -> Result<()> {
let mut cmd = match cmd {
Ok(c) => c,
Err(_) => return Err(ErrorKind::ErrorCode("failed to spawn shell".to_string()).into()),
Err(_) => return Err(anyhow!("failed to spawn shell")),
};
cmd.wait()?;

View File

@ -7,8 +7,8 @@ extern crate procfs;
use prometheus::{Encoder, Gauge, GaugeVec, IntCounter, TextEncoder};
use anyhow::Result;
use protocols;
use rustjail::errors::*;
const NAMESPACE_KATA_AGENT: &str = "kata_agent";
const NAMESPACE_KATA_GUEST: &str = "kata_guest";

View File

@ -3,7 +3,6 @@
// SPDX-License-Identifier: Apache-2.0
//
use rustjail::errors::*;
use std::collections::HashMap;
use std::ffi::CString;
use std::fs;
@ -26,6 +25,7 @@ use crate::device::{get_pci_device_name, get_scsi_device_name, online_device};
use crate::linux_abi::*;
use crate::protocols::agent::Storage;
use crate::Sandbox;
use anyhow::{anyhow, Context, Result};
use slog::Logger;
pub const DRIVER9PTYPE: &str = "9p";
@ -191,11 +191,11 @@ impl<'a> BareMount<'a> {
let cstr_fs_type: CString;
if self.source.len() == 0 {
return Err(ErrorKind::ErrorCode("need mount source".to_string()).into());
return Err(anyhow!("need mount source"));
}
if self.destination.len() == 0 {
return Err(ErrorKind::ErrorCode("need mount destination".to_string()).into());
return Err(anyhow!("need mount destination"));
}
cstr_source = CString::new(self.source)?;
@ -205,7 +205,7 @@ impl<'a> BareMount<'a> {
dest = cstr_dest.as_ptr();
if self.fs_type.len() == 0 {
return Err(ErrorKind::ErrorCode("need mount FS type".to_string()).into());
return Err(anyhow!("need mount FS type"));
}
cstr_fs_type = CString::new(self.fs_type)?;
@ -227,13 +227,12 @@ impl<'a> BareMount<'a> {
let rc = unsafe { mount(source, dest, fs_type, self.flags.bits(), options) };
if rc < 0 {
return Err(ErrorKind::ErrorCode(format!(
return Err(anyhow!(
"failed to mount {:?} to {:?}, with error: {}",
self.source,
self.destination,
io::Error::last_os_error()
))
.into());
));
}
Ok(())
}
@ -274,8 +273,10 @@ fn local_storage_handler(
return Ok("".to_string());
}
fs::create_dir_all(&storage.mount_point)
.chain_err(|| format!("failed to create dir all {:?}", &storage.mount_point))?;
fs::create_dir_all(&storage.mount_point).context(format!(
"failed to create dir all {:?}",
&storage.mount_point
))?;
let opts_vec: Vec<String> = storage.options.to_vec();
@ -332,11 +333,11 @@ fn virtio_blk_storage_handler(
// use the virt path provided in Storage Source
if storage.source.starts_with("/dev") {
let metadata = fs::metadata(&storage.source)
.chain_err(|| format!("get metadata on file {:?}", &storage.source))?;
.context(format!("get metadata on file {:?}", &storage.source))?;
let mode = metadata.permissions().mode();
if mode & libc::S_IFBLK == 0 {
return Err(ErrorKind::ErrorCode(format!("Invalid device {}", &storage.source)).into());
return Err(anyhow!("Invalid device {}", &storage.source));
}
} else {
let dev_path = get_pci_device_name(&sandbox, &storage.source)?;
@ -376,7 +377,7 @@ fn mount_storage(logger: &Logger, storage: &Storage) -> Result<()> {
DRIVER9PTYPE | DRIVERVIRTIOFSTYPE => {
let dest_path = Path::new(storage.mount_point.as_str());
if !dest_path.exists() {
fs::create_dir_all(dest_path).chain_err(|| "Create mount destination failed")?;
fs::create_dir_all(dest_path).context("Create mount destination failed")?;
}
}
_ => {
@ -450,11 +451,10 @@ pub fn add_storages(
let handler = match STORAGEHANDLERLIST.get(&handler_name.as_str()) {
None => {
return Err(ErrorKind::ErrorCode(format!(
return Err(anyhow!(
"Failed to find the storage handler {}",
storage.driver.to_owned()
))
.into());
));
}
Some(f) => f,
};
@ -480,7 +480,7 @@ fn mount_to_rootfs(logger: &Logger, m: &INIT_MOUNT) -> Result<()> {
let bare_mount = BareMount::new(m.src, m.dest, m.fstype, flags, options.as_str(), logger);
fs::create_dir_all(Path::new(m.dest)).chain_err(|| "could not create directory")?;
fs::create_dir_all(Path::new(m.dest)).context("could not create directory")?;
if let Err(err) = bare_mount.mount() {
if m.src != "dev" {
@ -514,7 +514,7 @@ pub fn get_mount_fs_type(mount_point: &str) -> Result<String> {
// any error ecountered.
pub fn get_mount_fs_type_from_file(mount_file: &str, mount_point: &str) -> Result<String> {
if mount_point == "" {
return Err(ErrorKind::ErrorCode(format!("Invalid mount point {}", mount_point)).into());
return Err(anyhow!("Invalid mount point {}", mount_point));
}
let file = File::open(mount_file)?;
@ -536,11 +536,10 @@ pub fn get_mount_fs_type_from_file(mount_file: &str, mount_point: &str) -> Resul
}
}
Err(ErrorKind::ErrorCode(format!(
Err(anyhow!(
"failed to find FS type for mount point {}",
mount_point
))
.into())
}
pub fn get_cgroup_mounts(logger: &Logger, cg_path: &str) -> Result<Vec<INIT_MOUNT>> {
@ -635,7 +634,7 @@ pub fn cgroups_mount(logger: &Logger) -> Result<()> {
pub fn remove_mounts(mounts: &Vec<String>) -> Result<()> {
for m in mounts.iter() {
mount::umount(m.as_str()).chain_err(|| format!("failed to umount {:?}", m))?;
mount::umount(m.as_str()).context(format!("failed to umount {:?}", m))?;
}
Ok(())
}
@ -647,21 +646,15 @@ fn ensure_destination_exists(destination: &str, fs_type: &str) -> Result<()> {
if !d.exists() {
let dir = match d.parent() {
Some(d) => d,
None => {
return Err(ErrorKind::ErrorCode(format!(
"mount destination {} doesn't exist",
destination
))
.into())
}
None => return Err(anyhow!("mount destination {} doesn't exist", destination)),
};
if !dir.exists() {
fs::create_dir_all(dir).chain_err(|| format!("create dir all failed on {:?}", dir))?;
fs::create_dir_all(dir).context(format!("create dir all failed on {:?}", dir))?;
}
}
if fs_type != "bind" || d.is_dir() {
fs::create_dir_all(d).chain_err(|| format!("create dir all failed on {:?}", d))?;
fs::create_dir_all(d).context(format!("create dir all failed on {:?}", d))?;
} else {
fs::OpenOptions::new().create(true).open(d)?;
}

View File

@ -3,11 +3,11 @@
// SPDX-License-Identifier: Apache-2.0
//
use anyhow::Result;
use libc;
use nix::errno::Errno;
use nix::fcntl::{self, OFlag};
use nix::sys::stat::Mode;
use rustjail::errors::*;
use std::fs;
pub const RNGDEV: &str = "/dev/random";

View File

@ -7,6 +7,7 @@ use std::path::Path;
use std::sync::{Arc, Mutex};
use ttrpc;
use anyhow::{anyhow, Context, Result};
use oci::{LinuxNamespace, Root, Spec};
use protobuf::{RepeatedField, SingularPtrField};
use protocols::agent::{
@ -21,7 +22,6 @@ use protocols::health::{
use protocols::types::Interface;
use rustjail;
use rustjail::container::{BaseContainer, Container, LinuxContainer};
use rustjail::errors::*;
use rustjail::process::Process;
use rustjail::specconv::CreateOpts;
@ -90,9 +90,7 @@ impl agentService {
Some(spec) => rustjail::grpc_to_oci(spec),
None => {
error!(sl!(), "no oci spec in the create container request!");
return Err(
ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EINVAL)).into(),
);
return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EINVAL)));
}
};
@ -101,7 +99,7 @@ impl agentService {
// re-scan PCI bus
// looking for hidden devices
rescan_pci_bus().chain_err(|| "Could not rescan PCI bus")?;
rescan_pci_bus().context("Could not rescan PCI bus")?;
// Some devices need some extra processing (the ones invoked with
// --device for instance), and that's what this call is doing. It
@ -163,7 +161,7 @@ impl agentService {
tp
} else {
info!(sl!(), "no process configurations!");
return Err(ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EINVAL)).into());
return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EINVAL)));
};
ctr.start(p)?;
@ -184,7 +182,7 @@ impl agentService {
let ctr: &mut LinuxContainer = match s.get_container(cid.as_str()) {
Some(cr) => cr,
None => {
return Err(ErrorKind::Nix(nix::Error::from_errno(Errno::EINVAL)).into());
return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL)));
}
};
@ -203,7 +201,7 @@ impl agentService {
let ctr: &mut LinuxContainer = match sandbox.get_container(cid.as_str()) {
Some(cr) => cr,
None => {
return Err(ErrorKind::Nix(nix::Error::from_errno(Errno::EINVAL)).into());
return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL)));
}
};
@ -252,13 +250,13 @@ impl agentService {
});
if let Err(_) = rx.recv_timeout(Duration::from_secs(req.timeout as u64)) {
return Err(ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::ETIME)).into());
return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::ETIME)));
}
if let Err(_) = handle.join() {
return Err(
ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::UnknownErrno)).into(),
);
return Err(anyhow!(nix::Error::from_errno(
nix::errno::Errno::UnknownErrno
)));
}
let s = self.sandbox.clone();
@ -301,7 +299,7 @@ impl agentService {
let process = if req.process.is_some() {
req.process.as_ref().unwrap()
} else {
return Err(ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EINVAL)).into());
return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EINVAL)));
};
let pipe_size = AGENT_CONFIG.read().unwrap().container_pipe_size;
@ -311,9 +309,7 @@ impl agentService {
let ctr = match sandbox.get_container(cid.as_str()) {
Some(v) => v,
None => {
return Err(
ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EINVAL)).into(),
);
return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EINVAL)));
}
};
@ -396,7 +392,7 @@ impl agentService {
let ctr: &mut LinuxContainer = match sandbox.get_container(cid.as_str()) {
Some(cr) => cr,
None => {
return Err(ErrorKind::Nix(nix::Error::from_errno(Errno::EINVAL)).into());
return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL)));
}
};
@ -472,9 +468,7 @@ impl agentService {
Err(e) => match e {
nix::Error::Sys(nix::errno::Errno::EAGAIN) => l = 0,
_ => {
return Err(
ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EIO)).into(),
);
return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EIO)));
}
},
}
@ -513,7 +507,7 @@ impl agentService {
}
if fd == -1 {
return Err(ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EINVAL)).into());
return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EINVAL)));
}
let vector = read_stream(fd, req.len as usize)?;
@ -1338,7 +1332,7 @@ fn get_memory_info(block_size: bool, hotplug: bool) -> Result<(u64, bool)> {
Ok(v) => {
if v.len() == 0 {
info!(sl!(), "string in empty???");
return Err(ErrorKind::ErrorCode("Invalid block size".to_string()).into());
return Err(anyhow!("Invalid block size"));
}
size = v.trim().parse::<u64>()?;
@ -1346,7 +1340,7 @@ fn get_memory_info(block_size: bool, hotplug: bool) -> Result<(u64, bool)> {
Err(e) => {
info!(sl!(), "memory block size error: {:?}", e.kind());
if e.kind() != std::io::ErrorKind::NotFound {
return Err(ErrorKind::Io(e).into());
return Err(anyhow!(e));
}
}
}
@ -1364,9 +1358,9 @@ fn get_memory_info(block_size: bool, hotplug: bool) -> Result<(u64, bool)> {
match e {
nix::Error::Sys(errno) => match errno {
Errno::ENOENT => plug = false,
_ => return Err(ErrorKind::Nix(e).into()),
_ => return Err(anyhow!(e)),
},
_ => return Err(ErrorKind::Nix(e).into()),
_ => return Err(anyhow!(e)),
}
}
}
@ -1407,15 +1401,15 @@ fn read_stream(fd: RawFd, l: usize) -> Result<Vec<u8>> {
// was closed, instead it would return a 0 reading length, please
// see https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md#errors
if len == 0 {
return Err(ErrorKind::ErrorCode("read meet eof".to_string()).into());
return Err(anyhow!("read meet eof"));
}
}
Err(e) => match e {
nix::Error::Sys(errno) => match errno {
Errno::EAGAIN => v.resize(0, 0),
_ => return Err(ErrorKind::Nix(nix::Error::Sys(errno)).into()),
_ => return Err(anyhow!(nix::Error::Sys(errno))),
},
_ => return Err(ErrorKind::ErrorCode("read error".to_string()).into()),
_ => return Err(anyhow!("read error")),
},
}
@ -1430,15 +1424,13 @@ fn find_process<'a>(
) -> Result<&'a mut Process> {
let ctr = match sandbox.get_container(cid) {
Some(v) => v,
None => return Err(ErrorKind::ErrorCode(String::from("Invalid container id")).into()),
None => return Err(anyhow!("Invalid container id")),
};
if init || eid == "" {
let p = match ctr.processes.get_mut(&ctr.init_process_pid) {
Some(v) => v,
None => {
return Err(ErrorKind::ErrorCode(String::from("cannot find init process!")).into())
}
None => return Err(anyhow!("cannot find init process!")),
};
return Ok(p);
@ -1446,7 +1438,7 @@ fn find_process<'a>(
let p = match ctr.get_process(eid) {
Ok(v) => v,
Err(_) => return Err(ErrorKind::ErrorCode("Invalid exec id".to_string()).into()),
Err(_) => return Err(anyhow!("Invalid exec id")),
};
Ok(p)
@ -1496,11 +1488,7 @@ fn update_container_namespaces(
sandbox_pidns: bool,
) -> 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,
};
@ -1704,7 +1692,7 @@ fn setup_bundle(cid: &str, spec: &mut Spec) -> Result<PathBuf> {
);
let _ = spec.save(config_path.to_str().unwrap());
let olddir = unistd::getcwd().chain_err(|| "cannot getcwd")?;
let olddir = unistd::getcwd().context("cannot getcwd")?;
unistd::chdir(bundle_path.to_str().unwrap())?;
Ok(olddir)
@ -1712,7 +1700,7 @@ fn setup_bundle(cid: &str, spec: &mut Spec) -> Result<PathBuf> {
fn load_kernel_module(module: &protocols::agent::KernelModule) -> Result<()> {
if module.name == "" {
return Err(ErrorKind::ErrorCode("Kernel module name is empty".to_string()).into());
return Err(anyhow!("Kernel module name is empty"));
}
info!(
@ -1744,11 +1732,9 @@ fn load_kernel_module(module: &protocols::agent::KernelModule) -> Result<()> {
"load_kernel_module return code: {} stdout:{} stderr:{}",
code, std_out, std_err
);
return Err(ErrorKind::ErrorCode(msg).into());
}
None => {
return Err(ErrorKind::ErrorCode("Process terminated by signal".to_string()).into())
return Err(anyhow!(msg));
}
None => return Err(anyhow!("Process terminated by signal")),
}
}

View File

@ -9,6 +9,7 @@ use crate::mount::{get_mount_fs_type, remove_mounts, TYPEROOTFS};
use crate::namespace::Namespace;
use crate::namespace::NSTYPEPID;
use crate::network::Network;
use anyhow::{anyhow, Context, Result};
use libc::pid_t;
use netlink::{RtnlHandle, NETLINK_ROUTE};
use oci::{Hook, Hooks};
@ -17,7 +18,6 @@ use regex::Regex;
use rustjail::cgroups;
use rustjail::container::BaseContainer;
use rustjail::container::LinuxContainer;
use rustjail::errors::*;
use rustjail::process::Process;
use slog::Logger;
use std::collections::HashMap;
@ -105,13 +105,7 @@ impl Sandbox {
// acquiring a lock on sandbox.
pub fn unset_sandbox_storage(&mut self, path: &str) -> Result<bool> {
match self.storages.get_mut(path) {
None => {
return Err(ErrorKind::ErrorCode(format!(
"Sandbox storage with path {} not found",
path
))
.into())
}
None => return Err(anyhow!("Sandbox storage with path {} not found", path)),
Some(count) => {
*count -= 1;
if *count < 1 {
@ -131,7 +125,7 @@ impl Sandbox {
pub fn remove_sandbox_storage(&self, path: &str) -> Result<()> {
let mounts = vec![path.to_string()];
remove_mounts(&mounts)?;
fs::remove_dir_all(path).chain_err(|| format!("failed to remove dir {:?}", path))?;
fs::remove_dir_all(path).context(format!("failed to remove dir {:?}", path))?;
Ok(())
}
@ -168,11 +162,7 @@ impl Sandbox {
self.shared_ipcns = match Namespace::new(&self.logger).as_ipc().setup() {
Ok(ns) => ns,
Err(err) => {
return Err(ErrorKind::ErrorCode(format!(
"Failed to setup persistent IPC namespace with error: {}",
err
))
.into())
return Err(anyhow!(err).context("Failed to setup persistent IPC namespace"));
}
};
@ -183,11 +173,7 @@ impl Sandbox {
{
Ok(ns) => ns,
Err(err) => {
return Err(ErrorKind::ErrorCode(format!(
"Failed to setup persistent UTS namespace with error: {}",
err
))
.into())
return Err(anyhow!(err).context("Failed to setup persistent UTS namespace"));
}
};
Ok(true)
@ -206,10 +192,9 @@ impl Sandbox {
if self.sandbox_pidns.is_none() && self.containers.len() == 0 {
let init_pid = c.init_process_pid;
if init_pid == -1 {
return Err(ErrorKind::ErrorCode(String::from(
"Failed to setup pid namespace: init container pid is -1",
))
.into());
return Err(anyhow!(
"Failed to setup pid namespace: init container pid is -1"
));
}
let mut pid_ns = Namespace::new(&self.logger).as_pid();