agent: replace if let Err with map_err

Fixes #934

Signed-off-by: Tim Zhang <tim@hyper.sh>
This commit is contained in:
Tim Zhang 2020-10-13 14:27:29 +08:00
parent 16a6427ca9
commit 6ffa8283f0
7 changed files with 62 additions and 91 deletions

View File

@ -126,13 +126,12 @@ pub fn drop_privileges(cfd_log: RawFd, caps: &LinuxCapabilities) -> Result<()> {
) )
.map_err(|e| anyhow!(e.to_string()))?; .map_err(|e| anyhow!(e.to_string()))?;
if let Err(_) = caps::set( let _ = caps::set(
None, None,
CapSet::Ambient, CapSet::Ambient,
to_capshashset(cfd_log, caps.ambient.as_ref()), to_capshashset(cfd_log, caps.ambient.as_ref()),
) { )
log_child!(cfd_log, "failed to set ambient capability"); .map_err(|_| log_child!(cfd_log, "failed to set ambient capability"));
}
Ok(()) Ok(())
} }

View File

@ -3,7 +3,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
// //
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, Context, Result};
use dirs; use dirs;
use lazy_static; use lazy_static;
use libc::pid_t; use libc::pid_t;
@ -457,9 +457,8 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
// Ref: https://github.com/opencontainers/runc/commit/50a19c6ff828c58e5dab13830bd3dacde268afe5 // Ref: https://github.com/opencontainers/runc/commit/50a19c6ff828c58e5dab13830bd3dacde268afe5
// //
if !nses.is_empty() { if !nses.is_empty() {
if let Err(e) = prctl::set_dumpable(false) { prctl::set_dumpable(false)
return Err(anyhow!(e).context("set process non-dumpable failed")); .map_err(|e| anyhow!(e).context("set process non-dumpable failed"))?;
};
} }
if userns { if userns {
@ -590,9 +589,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
// NoNewPeiviledges, Drop capabilities // NoNewPeiviledges, Drop capabilities
if oci_process.no_new_privileges { if oci_process.no_new_privileges {
if let Err(_) = prctl::set_no_new_privileges(true) { prctl::set_no_new_privileges(true).map_err(|_| anyhow!("cannot set no new privileges"))?;
return Err(anyhow!("cannot set no new privileges"));
}
} }
if oci_process.capabilities.is_some() { if oci_process.capabilities.is_some() {
@ -1074,14 +1071,12 @@ fn do_exec(args: &[String]) -> ! {
.collect(); .collect();
let a: Vec<&CStr> = sa.iter().map(|s| s.as_c_str()).collect(); let a: Vec<&CStr> = sa.iter().map(|s| s.as_c_str()).collect();
if let Err(e) = unistd::execvp(p.as_c_str(), a.as_slice()) { let _ = unistd::execvp(p.as_c_str(), a.as_slice()).map_err(|e| match e {
match e { nix::Error::Sys(errno) => {
nix::Error::Sys(errno) => { std::process::exit(errno as i32);
std::process::exit(errno as i32);
}
_ => std::process::exit(-2),
} }
} _ => std::process::exit(-2),
});
unreachable!() unreachable!()
} }
@ -1291,9 +1286,9 @@ fn write_mappings(logger: &Logger, path: &str, maps: &[LinuxIDMapping]) -> Resul
fn setid(uid: Uid, gid: Gid) -> Result<()> { fn setid(uid: Uid, gid: Gid) -> Result<()> {
// set uid/gid // set uid/gid
if let Err(e) = prctl::set_keep_capabilities(true) { prctl::set_keep_capabilities(true)
bail!(anyhow!(e).context("set keep capabilities returned")); .map_err(|e| anyhow!(e).context("set keep capabilities returned"))?;
};
{ {
unistd::setresgid(gid, gid, gid)?; unistd::setresgid(gid, gid, gid)?;
} }
@ -1305,9 +1300,9 @@ fn setid(uid: Uid, gid: Gid) -> Result<()> {
capabilities::reset_effective()?; capabilities::reset_effective()?;
} }
if let Err(e) = prctl::set_keep_capabilities(false) { prctl::set_keep_capabilities(false)
bail!(anyhow!(e).context("set keep capabilities returned")); .map_err(|e| anyhow!(e).context("set keep capabilities returned"))?;
};
Ok(()) Ok(())
} }
@ -1325,13 +1320,13 @@ impl LinuxContainer {
// validate oci spec // validate oci spec
validator::validate(&config)?; validator::validate(&config)?;
if let Err(e) = fs::create_dir_all(root.as_str()) { fs::create_dir_all(root.as_str()).map_err(|e| {
if e.kind() == std::io::ErrorKind::AlreadyExists { if e.kind() == std::io::ErrorKind::AlreadyExists {
return Err(e).context(format!("container {} already exists", id.as_str())); return anyhow!(e).context(format!("container {} already exists", id.as_str()));
} }
return Err(e).context(format!("fail to create container directory {}", root)); anyhow!(e).context(format!("fail to create container directory {}", root))
} })?;
unistd::chown( unistd::chown(
root.as_str(), root.as_str(),

View File

@ -512,14 +512,12 @@ fn run_debug_console_shell(logger: &Logger, shell: &str, socket_fd: RawFd) -> Re
let args: Vec<&CStr> = vec![]; let args: Vec<&CStr> = vec![];
// run shell // run shell
if let Err(e) = unistd::execvp(cmd.as_c_str(), args.as_slice()) { let _ = unistd::execvp(cmd.as_c_str(), args.as_slice()).map_err(|e| match e {
match e { nix::Error::Sys(errno) => {
nix::Error::Sys(errno) => { std::process::exit(errno as i32);
std::process::exit(errno as i32);
}
_ => std::process::exit(-2),
} }
} _ => std::process::exit(-2),
});
} }
Ok(ForkResult::Parent { child: child_pid }) => { Ok(ForkResult::Parent { child: child_pid }) => {

View File

@ -251,10 +251,7 @@ fn ephemeral_storage_handler(
return Ok("".to_string()); return Ok("".to_string());
} }
if let Err(err) = fs::create_dir_all(Path::new(&storage.mount_point)) { fs::create_dir_all(Path::new(&storage.mount_point))?;
return Err(err.into());
}
common_storage_handler(logger, storage)?; common_storage_handler(logger, storage)?;
Ok("".to_string()) Ok("".to_string())

View File

@ -131,12 +131,12 @@ impl Namespace {
}; };
let bare_mount = BareMount::new(source, destination, "none", flags, "", &logger); let bare_mount = BareMount::new(source, destination, "none", flags, "", &logger);
if let Err(err) = bare_mount.mount() { bare_mount.mount().map_err(|e| {
return Err(format!( format!(
"Failed to mount {} to {} with err:{:?}", "Failed to mount {} to {} with err:{:?}",
source, destination, err source, destination, e
)); )
} })?;
Ok(()) Ok(())
}); });

View File

@ -258,15 +258,12 @@ impl agentService {
}); });
}); });
if let Err(_) = rx.recv_timeout(Duration::from_secs(req.timeout as u64)) { rx.recv_timeout(Duration::from_secs(req.timeout as u64))
return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::ETIME))); .map_err(|_| anyhow!(nix::Error::from_errno(nix::errno::Errno::ETIME)))?;
}
if let Err(_) = handle.join() { handle
return Err(anyhow!(nix::Error::from_errno( .join()
nix::errno::Errno::UnknownErrno .map_err(|_| anyhow!(nix::Error::from_errno(nix::errno::Errno::UnknownErrno)))?;
)));
}
let s = self.sandbox.clone(); let s = self.sandbox.clone();
let mut sandbox = s.lock().unwrap(); let mut sandbox = s.lock().unwrap();
@ -903,12 +900,12 @@ impl protocols::agent_ttrpc::AgentService for agentService {
}; };
let err = libc::ioctl(fd, TIOCSWINSZ, &win); let err = libc::ioctl(fd, TIOCSWINSZ, &win);
if let Err(e) = Errno::result(err).map(drop) { Errno::result(err).map(drop).map_err(|e| {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status( ttrpc::Error::RpcStatus(ttrpc::get_status(
ttrpc::Code::INTERNAL, ttrpc::Code::INTERNAL,
format!("ioctl error: {:?}", e), format!("ioctl error: {:?}", e),
))); ))
} })?;
} }
Ok(Empty::new()) Ok(Empty::new())
@ -1062,12 +1059,12 @@ impl protocols::agent_ttrpc::AgentService for agentService {
s.running = true; s.running = true;
if !req.guest_hook_path.is_empty() { if !req.guest_hook_path.is_empty() {
if let Err(e) = s.add_hooks(&req.guest_hook_path) { let _ = s.add_hooks(&req.guest_hook_path).map_err(|e| {
error!( error!(
sl!(), sl!(),
"add guest hook {} failed: {:?}", req.guest_hook_path, e "add guest hook {} failed: {:?}", req.guest_hook_path, e
); );
} });
} }
if req.sandbox_id.len() > 0 { if req.sandbox_id.len() > 0 {
@ -1168,12 +1165,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
let s = Arc::clone(&self.sandbox); let s = Arc::clone(&self.sandbox);
let sandbox = s.lock().unwrap(); let sandbox = s.lock().unwrap();
if let Err(e) = sandbox.online_cpu_memory(&req) { sandbox.online_cpu_memory(&req).map_err(|e| {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status( ttrpc::Error::RpcStatus(ttrpc::get_status(ttrpc::Code::INTERNAL, e.to_string()))
ttrpc::Code::INTERNAL, })?;
e.to_string(),
)));
}
Ok(Empty::new()) Ok(Empty::new())
} }
@ -1183,12 +1177,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
_ctx: &ttrpc::TtrpcContext, _ctx: &ttrpc::TtrpcContext,
req: protocols::agent::ReseedRandomDevRequest, req: protocols::agent::ReseedRandomDevRequest,
) -> ttrpc::Result<Empty> { ) -> ttrpc::Result<Empty> {
if let Err(e) = random::reseed_rng(req.data.as_slice()) { random::reseed_rng(req.data.as_slice()).map_err(|e| {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status( ttrpc::Error::RpcStatus(ttrpc::get_status(ttrpc::Code::INTERNAL, e.to_string()))
ttrpc::Code::INTERNAL, })?;
e.to_string(),
)));
}
Ok(Empty::new()) Ok(Empty::new())
} }
@ -1227,12 +1218,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
_ctx: &ttrpc::TtrpcContext, _ctx: &ttrpc::TtrpcContext,
req: protocols::agent::MemHotplugByProbeRequest, req: protocols::agent::MemHotplugByProbeRequest,
) -> ttrpc::Result<Empty> { ) -> ttrpc::Result<Empty> {
if let Err(e) = do_mem_hotplug_by_probe(&req.memHotplugProbeAddr) { do_mem_hotplug_by_probe(&req.memHotplugProbeAddr).map_err(|e| {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status( ttrpc::Error::RpcStatus(ttrpc::get_status(ttrpc::Code::INTERNAL, e.to_string()))
ttrpc::Code::INTERNAL, })?;
e.to_string(),
)));
}
Ok(Empty::new()) Ok(Empty::new())
} }
@ -1242,12 +1230,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
_ctx: &ttrpc::TtrpcContext, _ctx: &ttrpc::TtrpcContext,
req: protocols::agent::SetGuestDateTimeRequest, req: protocols::agent::SetGuestDateTimeRequest,
) -> ttrpc::Result<Empty> { ) -> ttrpc::Result<Empty> {
if let Err(e) = do_set_guest_date_time(req.Sec, req.Usec) { do_set_guest_date_time(req.Sec, req.Usec).map_err(|e| {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status( ttrpc::Error::RpcStatus(ttrpc::get_status(ttrpc::Code::INTERNAL, e.to_string()))
ttrpc::Code::INTERNAL, })?;
e.to_string(),
)));
}
Ok(Empty::new()) Ok(Empty::new())
} }
@ -1257,12 +1242,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
_ctx: &ttrpc::TtrpcContext, _ctx: &ttrpc::TtrpcContext,
req: protocols::agent::CopyFileRequest, req: protocols::agent::CopyFileRequest,
) -> ttrpc::Result<Empty> { ) -> ttrpc::Result<Empty> {
if let Err(e) = do_copy_file(&req) { do_copy_file(&req).map_err(|e| {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status( ttrpc::Error::RpcStatus(ttrpc::get_status(ttrpc::Code::INTERNAL, e.to_string()))
ttrpc::Code::INTERNAL, })?;
e.to_string(),
)));
}
Ok(Empty::new()) Ok(Empty::new())
} }

View File

@ -99,14 +99,14 @@ impl Uevent {
let online_path = format!("{}/{}/online", SYSFS_DIR, &self.devpath); let online_path = format!("{}/{}/online", SYSFS_DIR, &self.devpath);
// It's a memory hot-add event. // It's a memory hot-add event.
if online_path.starts_with(SYSFS_MEMORY_ONLINE_PATH) { if online_path.starts_with(SYSFS_MEMORY_ONLINE_PATH) {
if let Err(e) = online_device(online_path.as_ref()) { let _ = online_device(online_path.as_ref()).map_err(|e| {
error!( error!(
*logger, *logger,
"failed to online device"; "failed to online device";
"device" => &self.devpath, "device" => &self.devpath,
"error" => format!("{}", e), "error" => format!("{}", e),
); )
} });
return; return;
} }
} }