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

View File

@ -15,9 +15,9 @@ use crate::linux_abi::*;
use crate::mount::{DRIVERBLKTYPE, DRIVERMMIOBLKTYPE, DRIVERNVDIMMTYPE, DRIVERSCSITYPE}; use crate::mount::{DRIVERBLKTYPE, DRIVERMMIOBLKTYPE, DRIVERNVDIMMTYPE, DRIVERSCSITYPE};
use crate::sandbox::Sandbox; use crate::sandbox::Sandbox;
use crate::{AGENT_CONFIG, GLOBAL_DEVICE_WATCHER}; use crate::{AGENT_CONFIG, GLOBAL_DEVICE_WATCHER};
use anyhow::{anyhow, Result};
use oci::{LinuxDeviceCgroup, LinuxResources, Spec}; use oci::{LinuxDeviceCgroup, LinuxResources, Spec};
use protocols::agent::Device; use protocols::agent::Device;
use rustjail::errors::*;
// Convenience macro to obtain the scope logger // Convenience macro to obtain the scope logger
macro_rules! sl { 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(); let tokens: Vec<&str> = pci_id.split("/").collect();
if tokens.len() != 2 { if tokens.len() != 2 {
return Err(ErrorKind::ErrorCode(format!( return Err(anyhow!(
"PCI Identifier for device should be of format [bridgeAddr/deviceAddr], got {}", "PCI Identifier for device should be of format [bridgeAddr/deviceAddr], got {}",
pci_id pci_id
)) ));
.into());
} }
let bridge_id = tokens[0]; 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(); let bus_num = files_slice.len();
if bus_num != 1 { if bus_num != 1 {
return Err(ErrorKind::ErrorCode(format!( return Err(anyhow!(
"Expected an entry for bus in {}, got {} entries instead", "Expected an entry for bus in {}, got {} entries instead",
bridge_bus_path, bus_num bridge_bus_path,
)) bus_num
.into()); ));
} }
let bus = files_slice[0].file_name().unwrap().to_str().unwrap(); 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, Ok(name) => name,
Err(_) => { Err(_) => {
GLOBAL_DEVICE_WATCHER.lock().unwrap().remove_entry(dev_addr); GLOBAL_DEVICE_WATCHER.lock().unwrap().remove_entry(dev_addr);
return Err(ErrorKind::ErrorCode(format!( return Err(anyhow!(
"Timeout reached after {:?} waiting for device {}", "Timeout reached after {:?} waiting for device {}",
hotplug_timeout, dev_addr hotplug_timeout,
)) dev_addr
.into()); ));
} }
}; };
@ -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<()> { fn scan_scsi_bus(scsi_addr: &str) -> Result<()> {
let tokens: Vec<&str> = scsi_addr.split(":").collect(); let tokens: Vec<&str> = scsi_addr.split(":").collect();
if tokens.len() != 2 { if tokens.len() != 2 {
return Err(ErrorKind::Msg(format!( return Err(anyhow!(
"Unexpected format for SCSI Address: {}, expect SCSIID:LUA", "Unexpected format for SCSI Address: {}, expect SCSIID:LUA",
scsi_addr scsi_addr
)) ));
.into());
} }
// Scan scsi host passing in the channel, SCSI id and LUN. // 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 // 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. // update the device in the OCI spec device list. This is an error.
if device.container_path == "" { if device.container_path == "" {
return Err(ErrorKind::Msg(format!( return Err(anyhow!(
"container_path cannot empty for device {:?}", "container_path cannot empty for device {:?}",
device device
)) ));
.into());
} }
let linux = match spec.linux.as_mut() { let linux = match spec.linux.as_mut() {
None => { None => return Err(anyhow!("Spec didn't container linux field")),
return Err(
ErrorKind::ErrorCode("Spec didn't container linux field".to_string()).into(),
)
}
Some(l) => l, Some(l) => l,
}; };
if !Path::new(&device.vm_path).exists() { 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)?; let meta = fs::metadata(&device.vm_path)?;
@ -283,7 +276,7 @@ fn virtiommio_blk_device_handler(
_sandbox: &Arc<Mutex<Sandbox>>, _sandbox: &Arc<Mutex<Sandbox>>,
) -> Result<()> { ) -> Result<()> {
if device.vm_path == "" { 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) update_spec_device_list(device, spec)
@ -325,7 +318,7 @@ fn virtio_nvdimm_device_handler(
_sandbox: &Arc<Mutex<Sandbox>>, _sandbox: &Arc<Mutex<Sandbox>>,
) -> Result<()> { ) -> Result<()> {
if device.vm_path == "" { 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) 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); device.id, device.field_type, device.vm_path, device.container_path, device.options);
if device.field_type == "" { 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 == "" { if device.id == "" && device.vm_path == "" {
return Err( return Err(anyhow!("invalid ID and VM path for device {:?}", device));
ErrorKind::Msg(format!("invalid ID and VM path for device {:?}", device)).into(),
);
} }
if device.container_path == "" { if device.container_path == "" {
return Err( return Err(anyhow!("invalid container path for device {:?}", device));
ErrorKind::Msg(format!("invalid container path for device {:?}", device)).into(),
);
} }
match DEVICEHANDLERLIST.get(device.field_type.as_str()) { 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), 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 minor = stat::minor(rdev) as i64;
let linux = match spec.linux.as_mut() { let linux = match spec.linux.as_mut() {
None => { None => return Err(anyhow!("Spec didn't container linux field")),
return Err(
ErrorKind::ErrorCode("Spec didn't container linux field".to_string()).into(),
)
}
Some(l) => l, Some(l) => l,
}; };

View File

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

View File

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

View File

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

View File

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

View File

@ -7,6 +7,7 @@ use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use ttrpc; use ttrpc;
use anyhow::{anyhow, Context, Result};
use oci::{LinuxNamespace, Root, Spec}; use oci::{LinuxNamespace, Root, Spec};
use protobuf::{RepeatedField, SingularPtrField}; use protobuf::{RepeatedField, SingularPtrField};
use protocols::agent::{ use protocols::agent::{
@ -21,7 +22,6 @@ use protocols::health::{
use protocols::types::Interface; use protocols::types::Interface;
use rustjail; use rustjail;
use rustjail::container::{BaseContainer, Container, LinuxContainer}; use rustjail::container::{BaseContainer, Container, LinuxContainer};
use rustjail::errors::*;
use rustjail::process::Process; use rustjail::process::Process;
use rustjail::specconv::CreateOpts; use rustjail::specconv::CreateOpts;
@ -90,9 +90,7 @@ impl agentService {
Some(spec) => rustjail::grpc_to_oci(spec), Some(spec) => rustjail::grpc_to_oci(spec),
None => { None => {
error!(sl!(), "no oci spec in the create container request!"); error!(sl!(), "no oci spec in the create container request!");
return Err( return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EINVAL)));
ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EINVAL)).into(),
);
} }
}; };
@ -101,7 +99,7 @@ impl agentService {
// re-scan PCI bus // re-scan PCI bus
// looking for hidden devices // 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 // Some devices need some extra processing (the ones invoked with
// --device for instance), and that's what this call is doing. It // --device for instance), and that's what this call is doing. It
@ -163,7 +161,7 @@ impl agentService {
tp tp
} else { } else {
info!(sl!(), "no process configurations!"); 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)?; ctr.start(p)?;
@ -184,7 +182,7 @@ impl agentService {
let ctr: &mut LinuxContainer = match s.get_container(cid.as_str()) { let ctr: &mut LinuxContainer = match s.get_container(cid.as_str()) {
Some(cr) => cr, Some(cr) => cr,
None => { 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()) { let ctr: &mut LinuxContainer = match sandbox.get_container(cid.as_str()) {
Some(cr) => cr, Some(cr) => cr,
None => { 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)) { 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() { if let Err(_) = handle.join() {
return Err( return Err(anyhow!(nix::Error::from_errno(
ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::UnknownErrno)).into(), nix::errno::Errno::UnknownErrno
); )));
} }
let s = self.sandbox.clone(); let s = self.sandbox.clone();
@ -301,7 +299,7 @@ impl agentService {
let process = if req.process.is_some() { let process = if req.process.is_some() {
req.process.as_ref().unwrap() req.process.as_ref().unwrap()
} else { } 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; 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()) { let ctr = match sandbox.get_container(cid.as_str()) {
Some(v) => v, Some(v) => v,
None => { None => {
return Err( return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EINVAL)));
ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EINVAL)).into(),
);
} }
}; };
@ -396,7 +392,7 @@ impl agentService {
let ctr: &mut LinuxContainer = match sandbox.get_container(cid.as_str()) { let ctr: &mut LinuxContainer = match sandbox.get_container(cid.as_str()) {
Some(cr) => cr, Some(cr) => cr,
None => { 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 { Err(e) => match e {
nix::Error::Sys(nix::errno::Errno::EAGAIN) => l = 0, nix::Error::Sys(nix::errno::Errno::EAGAIN) => l = 0,
_ => { _ => {
return Err( return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EIO)));
ErrorKind::Nix(nix::Error::from_errno(nix::errno::Errno::EIO)).into(),
);
} }
}, },
} }
@ -513,7 +507,7 @@ impl agentService {
} }
if fd == -1 { 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)?; 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) => { Ok(v) => {
if v.len() == 0 { if v.len() == 0 {
info!(sl!(), "string in empty???"); 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>()?; size = v.trim().parse::<u64>()?;
@ -1346,7 +1340,7 @@ fn get_memory_info(block_size: bool, hotplug: bool) -> Result<(u64, bool)> {
Err(e) => { Err(e) => {
info!(sl!(), "memory block size error: {:?}", e.kind()); info!(sl!(), "memory block size error: {:?}", e.kind());
if e.kind() != std::io::ErrorKind::NotFound { 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 { match e {
nix::Error::Sys(errno) => match errno { nix::Error::Sys(errno) => match errno {
Errno::ENOENT => plug = false, 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 // 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 // see https://github.com/rust-lang/rfcs/blob/master/text/0517-io-os-reform.md#errors
if len == 0 { if len == 0 {
return Err(ErrorKind::ErrorCode("read meet eof".to_string()).into()); return Err(anyhow!("read meet eof"));
} }
} }
Err(e) => match e { Err(e) => match e {
nix::Error::Sys(errno) => match errno { nix::Error::Sys(errno) => match errno {
Errno::EAGAIN => v.resize(0, 0), 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> { ) -> Result<&'a mut Process> {
let ctr = match sandbox.get_container(cid) { let ctr = match sandbox.get_container(cid) {
Some(v) => v, Some(v) => v,
None => return Err(ErrorKind::ErrorCode(String::from("Invalid container id")).into()), None => return Err(anyhow!("Invalid container id")),
}; };
if init || eid == "" { if init || eid == "" {
let p = match ctr.processes.get_mut(&ctr.init_process_pid) { let p = match ctr.processes.get_mut(&ctr.init_process_pid) {
Some(v) => v, Some(v) => v,
None => { None => return Err(anyhow!("cannot find init process!")),
return Err(ErrorKind::ErrorCode(String::from("cannot find init process!")).into())
}
}; };
return Ok(p); return Ok(p);
@ -1446,7 +1438,7 @@ fn find_process<'a>(
let p = match ctr.get_process(eid) { let p = match ctr.get_process(eid) {
Ok(v) => v, Ok(v) => v,
Err(_) => return Err(ErrorKind::ErrorCode("Invalid exec id".to_string()).into()), Err(_) => return Err(anyhow!("Invalid exec id")),
}; };
Ok(p) Ok(p)
@ -1496,11 +1488,7 @@ fn update_container_namespaces(
sandbox_pidns: bool, sandbox_pidns: bool,
) -> Result<()> { ) -> Result<()> {
let linux = match spec.linux.as_mut() { let linux = match spec.linux.as_mut() {
None => { None => return Err(anyhow!("Spec didn't container linux field")),
return Err(
ErrorKind::ErrorCode("Spec didn't container linux field".to_string()).into(),
)
}
Some(l) => l, 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 _ = 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())?; unistd::chdir(bundle_path.to_str().unwrap())?;
Ok(olddir) 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<()> { fn load_kernel_module(module: &protocols::agent::KernelModule) -> Result<()> {
if module.name == "" { if module.name == "" {
return Err(ErrorKind::ErrorCode("Kernel module name is empty".to_string()).into()); return Err(anyhow!("Kernel module name is empty"));
} }
info!( info!(
@ -1744,11 +1732,9 @@ fn load_kernel_module(module: &protocols::agent::KernelModule) -> Result<()> {
"load_kernel_module return code: {} stdout:{} stderr:{}", "load_kernel_module return code: {} stdout:{} stderr:{}",
code, std_out, std_err code, std_out, std_err
); );
return Err(ErrorKind::ErrorCode(msg).into()); return Err(anyhow!(msg));
}
None => {
return Err(ErrorKind::ErrorCode("Process terminated by signal".to_string()).into())
} }
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::Namespace;
use crate::namespace::NSTYPEPID; use crate::namespace::NSTYPEPID;
use crate::network::Network; use crate::network::Network;
use anyhow::{anyhow, Context, Result};
use libc::pid_t; use libc::pid_t;
use netlink::{RtnlHandle, NETLINK_ROUTE}; use netlink::{RtnlHandle, NETLINK_ROUTE};
use oci::{Hook, Hooks}; use oci::{Hook, Hooks};
@ -17,7 +18,6 @@ use regex::Regex;
use rustjail::cgroups; use rustjail::cgroups;
use rustjail::container::BaseContainer; use rustjail::container::BaseContainer;
use rustjail::container::LinuxContainer; use rustjail::container::LinuxContainer;
use rustjail::errors::*;
use rustjail::process::Process; use rustjail::process::Process;
use slog::Logger; use slog::Logger;
use std::collections::HashMap; use std::collections::HashMap;
@ -105,13 +105,7 @@ impl Sandbox {
// acquiring a lock on sandbox. // acquiring a lock on sandbox.
pub fn unset_sandbox_storage(&mut self, path: &str) -> Result<bool> { pub fn unset_sandbox_storage(&mut self, path: &str) -> Result<bool> {
match self.storages.get_mut(path) { match self.storages.get_mut(path) {
None => { None => return Err(anyhow!("Sandbox storage with path {} not found", path)),
return Err(ErrorKind::ErrorCode(format!(
"Sandbox storage with path {} not found",
path
))
.into())
}
Some(count) => { Some(count) => {
*count -= 1; *count -= 1;
if *count < 1 { if *count < 1 {
@ -131,7 +125,7 @@ impl Sandbox {
pub fn remove_sandbox_storage(&self, path: &str) -> Result<()> { pub fn remove_sandbox_storage(&self, path: &str) -> Result<()> {
let mounts = vec![path.to_string()]; let mounts = vec![path.to_string()];
remove_mounts(&mounts)?; 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(()) Ok(())
} }
@ -168,11 +162,7 @@ impl Sandbox {
self.shared_ipcns = match Namespace::new(&self.logger).as_ipc().setup() { self.shared_ipcns = match Namespace::new(&self.logger).as_ipc().setup() {
Ok(ns) => ns, Ok(ns) => ns,
Err(err) => { Err(err) => {
return Err(ErrorKind::ErrorCode(format!( return Err(anyhow!(err).context("Failed to setup persistent IPC namespace"));
"Failed to setup persistent IPC namespace with error: {}",
err
))
.into())
} }
}; };
@ -183,11 +173,7 @@ impl Sandbox {
{ {
Ok(ns) => ns, Ok(ns) => ns,
Err(err) => { Err(err) => {
return Err(ErrorKind::ErrorCode(format!( return Err(anyhow!(err).context("Failed to setup persistent UTS namespace"));
"Failed to setup persistent UTS namespace with error: {}",
err
))
.into())
} }
}; };
Ok(true) Ok(true)
@ -206,10 +192,9 @@ impl Sandbox {
if self.sandbox_pidns.is_none() && self.containers.len() == 0 { if self.sandbox_pidns.is_none() && self.containers.len() == 0 {
let init_pid = c.init_process_pid; let init_pid = c.init_process_pid;
if init_pid == -1 { if init_pid == -1 {
return Err(ErrorKind::ErrorCode(String::from( return Err(anyhow!(
"Failed to setup pid namespace: init container pid is -1", "Failed to setup pid namespace: init container pid is -1"
)) ));
.into());
} }
let mut pid_ns = Namespace::new(&self.logger).as_pid(); let mut pid_ns = Namespace::new(&self.logger).as_pid();