agent: replace unnecessary match Result with map_err

Replace `match Result` whose Ok hand is useless.

Signed-off-by: Tim Zhang <tim@hyper.sh>
This commit is contained in:
Tim Zhang 2020-10-13 17:54:10 +08:00
parent 7f9e5913e0
commit 7bf4073d8d
5 changed files with 117 additions and 176 deletions

View File

@ -320,14 +320,11 @@ impl Container for LinuxContainer {
pub fn init_child() { pub fn init_child() {
let cwfd = std::env::var(CWFD_FD).unwrap().parse::<i32>().unwrap(); let cwfd = std::env::var(CWFD_FD).unwrap().parse::<i32>().unwrap();
let cfd_log = std::env::var(CLOG_FD).unwrap().parse::<i32>().unwrap(); let cfd_log = std::env::var(CLOG_FD).unwrap().parse::<i32>().unwrap();
match do_init_child(cwfd) {
Ok(_) => (), let _ = do_init_child(cwfd).map_err(|e| {
Err(e) => {
log_child!(cfd_log, "child exit: {:?}", e); log_child!(cfd_log, "child exit: {:?}", e);
let _ = write_sync(cwfd, SYNC_FAILED, format!("{:?}", e).as_str()); let _ = write_sync(cwfd, SYNC_FAILED, format!("{:?}", e).as_str());
return; });
}
}
} }
fn do_init_child(cwfd: RawFd) -> Result<()> { fn do_init_child(cwfd: RawFd) -> Result<()> {
@ -392,9 +389,8 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
to_new.set(*s, true); to_new.set(*s, true);
} }
} else { } else {
let fd = match fcntl::open(ns.path.as_str(), OFlag::O_CLOEXEC, Mode::empty()) { let fd =
Ok(v) => v, fcntl::open(ns.path.as_str(), OFlag::O_CLOEXEC, Mode::empty()).map_err(|e| {
Err(e) => {
log_child!( log_child!(
cfd_log, cfd_log,
"cannot open type: {} path: {}", "cannot open type: {} path: {}",
@ -402,9 +398,8 @@ fn do_init_child(cwfd: RawFd) -> Result<()> {
ns.path.clone() ns.path.clone()
); );
log_child!(cfd_log, "error is : {}", e.as_errno().unwrap().desc()); log_child!(cfd_log, "error is : {}", e.as_errno().unwrap().desc());
return Err(e.into()); e
} })?;
};
if *s != CloneFlags::CLONE_NEWPID { if *s != CloneFlags::CLONE_NEWPID {
to_join.push((*s, fd)); to_join.push((*s, fd));
@ -834,16 +829,14 @@ impl BaseContainer for LinuxContainer {
child_stderr = unsafe { std::process::Stdio::from_raw_fd(stderr) }; child_stderr = unsafe { std::process::Stdio::from_raw_fd(stderr) };
} }
let old_pid_ns = match fcntl::open(PID_NS_PATH, OFlag::O_CLOEXEC, Mode::empty()) { let old_pid_ns =
Ok(v) => v, fcntl::open(PID_NS_PATH, OFlag::O_CLOEXEC, Mode::empty()).map_err(|e| {
Err(e) => {
error!( error!(
logger, logger,
"cannot open pid ns path: {} with error: {:?}", PID_NS_PATH, e "cannot open pid ns path: {} with error: {:?}", PID_NS_PATH, e
); );
return Err(e.into()); e
} })?;
};
//restore the parent's process's pid namespace. //restore the parent's process's pid namespace.
defer!({ defer!({
@ -897,7 +890,7 @@ impl BaseContainer for LinuxContainer {
info!(logger, "child pid: {}", p.pid); info!(logger, "child pid: {}", p.pid);
match join_namespaces( join_namespaces(
&logger, &logger,
&spec, &spec,
&p, &p,
@ -905,16 +898,15 @@ impl BaseContainer for LinuxContainer {
&st, &st,
pwfd, pwfd,
prfd, prfd,
) { )
Ok(_) => (), .map_err(|e| {
Err(e) => {
error!(logger, "create container process error {:?}", e); error!(logger, "create container process error {:?}", e);
// kill the child process. // kill the child process.
let _ = signal::kill(Pid::from_raw(p.pid), Some(Signal::SIGKILL)) let _ = signal::kill(Pid::from_raw(p.pid), Some(Signal::SIGKILL))
.map_err(|e| warn!(logger, "signal::kill joining namespaces {:?}", e)); .map_err(|e| warn!(logger, "signal::kill joining namespaces {:?}", e));
return Err(e);
} e
}; })?;
info!(logger, "entered namespaces!"); info!(logger, "entered namespaces!");
@ -1085,9 +1077,8 @@ fn get_pid_namespace(logger: &Logger, linux: &Linux) -> Result<Option<RawFd>> {
return Ok(None); return Ok(None);
} }
let fd = match fcntl::open(ns.path.as_str(), OFlag::O_CLOEXEC, Mode::empty()) { let fd =
Ok(v) => v, fcntl::open(ns.path.as_str(), OFlag::O_CLOEXEC, Mode::empty()).map_err(|e| {
Err(e) => {
error!( error!(
logger, logger,
"cannot open type: {} path: {}", "cannot open type: {} path: {}",
@ -1095,9 +1086,9 @@ fn get_pid_namespace(logger: &Logger, linux: &Linux) -> Result<Option<RawFd>> {
ns.path.clone() ns.path.clone()
); );
error!(logger, "error is : {}", e.as_errno().unwrap().desc()); error!(logger, "error is : {}", e.as_errno().unwrap().desc());
return Err(e.into());
} e
}; })?;
return Ok(Some(fd)); return Ok(Some(fd));
} }
@ -1245,13 +1236,10 @@ fn write_mappings(logger: &Logger, path: &str, maps: &[LinuxIDMapping]) -> Resul
if !data.is_empty() { if !data.is_empty() {
let fd = fcntl::open(path, OFlag::O_WRONLY, Mode::empty())?; let fd = fcntl::open(path, OFlag::O_WRONLY, Mode::empty())?;
defer!(unistd::close(fd).unwrap()); defer!(unistd::close(fd).unwrap());
match unistd::write(fd, data.as_bytes()) { unistd::write(fd, data.as_bytes()).map_err(|e| {
Ok(_) => {}
Err(e) => {
info!(logger, "cannot write mapping"); info!(logger, "cannot write mapping");
return Err(e.into()); e
} })?;
}
} }
Ok(()) Ok(())
} }

View File

@ -407,8 +407,7 @@ fn mount_cgroups(
if key != base { if key != base {
let src = format!("{}/{}", m.destination.as_str(), key); let src = format!("{}/{}", m.destination.as_str(), key);
match unix::fs::symlink(destination.as_str(), &src[1..]) { unix::fs::symlink(destination.as_str(), &src[1..]).map_err(|e| {
Err(e) => {
log_child!( log_child!(
cfd_log, cfd_log,
"symlink: {} {} err: {}", "symlink: {} {} err: {}",
@ -417,10 +416,8 @@ fn mount_cgroups(
e.to_string() e.to_string()
); );
return Err(e.into()); e
} })?;
Ok(_) => {}
}
} }
} }
@ -689,18 +686,14 @@ fn mount_from(
Path::new(&dest) Path::new(&dest)
}; };
// let _ = fs::create_dir_all(&dir); let _ = fs::create_dir_all(&dir).map_err(|e| {
match fs::create_dir_all(&dir) {
Ok(_) => {}
Err(e) => {
log_child!( log_child!(
cfd_log, cfd_log,
"creat dir {}: {}", "creat dir {}: {}",
dir.to_str().unwrap(), dir.to_str().unwrap(),
e.to_string() e.to_string()
); )
} });
}
// make sure file exists so we can bind over it // make sure file exists so we can bind over it
if src.is_file() { if src.is_file() {
@ -717,31 +710,26 @@ fn mount_from(
} }
}; };
match stat::stat(dest.as_str()) { let _ = stat::stat(dest.as_str()).map_err(|e| {
Ok(_) => {}
Err(e) => {
log_child!( log_child!(
cfd_log, cfd_log,
"dest stat error. {}: {}", "dest stat error. {}: {}",
dest.as_str(), dest.as_str(),
e.as_errno().unwrap().desc() e.as_errno().unwrap().desc()
); )
} });
}
match mount( mount(
Some(src.as_str()), Some(src.as_str()),
dest.as_str(), dest.as_str(),
Some(m.r#type.as_str()), Some(m.r#type.as_str()),
flags, flags,
Some(d.as_str()), Some(d.as_str()),
) { )
Ok(_) => {} .map_err(|e| {
Err(e) => {
log_child!(cfd_log, "mount error: {}", e.as_errno().unwrap().desc()); log_child!(cfd_log, "mount error: {}", e.as_errno().unwrap().desc());
return Err(e.into()); e
} })?;
}
if flags.contains(MsFlags::MS_BIND) if flags.contains(MsFlags::MS_BIND)
&& flags.intersects( && flags.intersects(
@ -753,24 +741,22 @@ fn mount_from(
| MsFlags::MS_SLAVE), | MsFlags::MS_SLAVE),
) )
{ {
match mount( mount(
Some(dest.as_str()), Some(dest.as_str()),
dest.as_str(), dest.as_str(),
None::<&str>, None::<&str>,
flags | MsFlags::MS_REMOUNT, flags | MsFlags::MS_REMOUNT,
None::<&str>, None::<&str>,
) { )
Err(e) => { .map_err(|e| {
log_child!( log_child!(
cfd_log, cfd_log,
"remout {}: {}", "remout {}: {}",
dest.as_str(), dest.as_str(),
e.as_errno().unwrap().desc() e.as_errno().unwrap().desc()
); );
return Err(e.into()); e
} })?;
Ok(_) => {}
}
} }
Ok(()) Ok(())
} }

View File

@ -130,17 +130,14 @@ fn get_device_name(sandbox: &Arc<Mutex<Sandbox>>, dev_addr: &str) -> Result<Stri
info!(sl!(), "Waiting on channel for device notification\n"); info!(sl!(), "Waiting on channel for device notification\n");
let hotplug_timeout = AGENT_CONFIG.read().unwrap().hotplug_timeout; let hotplug_timeout = AGENT_CONFIG.read().unwrap().hotplug_timeout;
let dev_name = match rx.recv_timeout(hotplug_timeout) { let dev_name = rx.recv_timeout(hotplug_timeout).map_err(|_| {
Ok(name) => name,
Err(_) => {
GLOBAL_DEVICE_WATCHER.lock().unwrap().remove_entry(dev_addr); GLOBAL_DEVICE_WATCHER.lock().unwrap().remove_entry(dev_addr);
return Err(anyhow!( anyhow!(
"Timeout reached after {:?} waiting for device {}", "Timeout reached after {:?} waiting for device {}",
hotplug_timeout, hotplug_timeout,
dev_addr dev_addr
)); )
} })?;
};
Ok(format!("{}/{}", SYSTEM_DEV_PATH, &dev_name)) Ok(format!("{}/{}", SYSTEM_DEV_PATH, &dev_name))
} }

View File

@ -588,13 +588,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
_ctx: &ttrpc::TtrpcContext, _ctx: &ttrpc::TtrpcContext,
req: protocols::agent::WaitProcessRequest, req: protocols::agent::WaitProcessRequest,
) -> ttrpc::Result<WaitProcessResponse> { ) -> ttrpc::Result<WaitProcessResponse> {
match self.do_wait_process(req) { self.do_wait_process(req).map_err(|e| {
Err(e) => 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(resp) => Ok(resp),
}
} }
fn list_processes( fn list_processes(
@ -734,13 +730,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
"invalid container id".to_string(), "invalid container id".to_string(),
)))?; )))?;
match ctr.stats() { ctr.stats().map_err(|e| {
Err(e) => 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(resp) => Ok(resp),
}
} }
fn pause_container( fn pause_container(
@ -794,13 +786,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
_ctx: &ttrpc::TtrpcContext, _ctx: &ttrpc::TtrpcContext,
req: protocols::agent::WriteStreamRequest, req: protocols::agent::WriteStreamRequest,
) -> ttrpc::Result<WriteStreamResponse> { ) -> ttrpc::Result<WriteStreamResponse> {
match self.do_write_stream(req) { self.do_write_stream(req).map_err(|e| {
Err(e) => 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(resp) => Ok(resp),
}
} }
fn read_stdout( fn read_stdout(
@ -808,13 +796,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
_ctx: &ttrpc::TtrpcContext, _ctx: &ttrpc::TtrpcContext,
req: protocols::agent::ReadStreamRequest, req: protocols::agent::ReadStreamRequest,
) -> ttrpc::Result<ReadStreamResponse> { ) -> ttrpc::Result<ReadStreamResponse> {
match self.do_read_stream(req, true) { self.do_read_stream(req, true).map_err(|e| {
Err(e) => 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(resp) => Ok(resp),
}
} }
fn read_stderr( fn read_stderr(
@ -822,13 +806,9 @@ impl protocols::agent_ttrpc::AgentService for agentService {
_ctx: &ttrpc::TtrpcContext, _ctx: &ttrpc::TtrpcContext,
req: protocols::agent::ReadStreamRequest, req: protocols::agent::ReadStreamRequest,
) -> ttrpc::Result<ReadStreamResponse> { ) -> ttrpc::Result<ReadStreamResponse> {
match self.do_read_stream(req, false) { self.do_read_stream(req, false).map_err(|e| {
Err(e) => 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(resp) => Ok(resp),
}
} }
fn close_stdin( fn close_stdin(
@ -841,15 +821,12 @@ impl protocols::agent_ttrpc::AgentService for agentService {
let s = Arc::clone(&self.sandbox); let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().unwrap(); let mut sandbox = s.lock().unwrap();
let p = match find_process(&mut sandbox, cid.as_str(), eid.as_str(), false) { let p = find_process(&mut sandbox, cid.as_str(), eid.as_str(), false).map_err(|e| {
Ok(v) => v, ttrpc::Error::RpcStatus(ttrpc::get_status(
Err(e) => {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status(
ttrpc::Code::INVALID_ARGUMENT, ttrpc::Code::INVALID_ARGUMENT,
format!("invalid argument: {:?}", e), format!("invalid argument: {:?}", e),
))); ))
} })?;
};
if p.term_master.is_some() { if p.term_master.is_some() {
let _ = unistd::close(p.term_master.unwrap()); let _ = unistd::close(p.term_master.unwrap());
@ -873,15 +850,12 @@ impl protocols::agent_ttrpc::AgentService for agentService {
let eid = req.exec_id.clone(); let eid = req.exec_id.clone();
let s = Arc::clone(&self.sandbox); let s = Arc::clone(&self.sandbox);
let mut sandbox = s.lock().unwrap(); let mut sandbox = s.lock().unwrap();
let p = match find_process(&mut sandbox, cid.as_str(), eid.as_str(), false) { let p = find_process(&mut sandbox, cid.as_str(), eid.as_str(), false).map_err(|e| {
Ok(v) => v, ttrpc::Error::RpcStatus(ttrpc::get_status(
Err(e) => {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status(
ttrpc::Code::UNAVAILABLE, ttrpc::Code::UNAVAILABLE,
format!("invalid argument: {:?}", e), format!("invalid argument: {:?}", e),
))); ))
} })?;
};
if p.term_master.is_none() { if p.term_master.is_none() {
return Err(ttrpc::Error::RpcStatus(ttrpc::get_status( return Err(ttrpc::Error::RpcStatus(ttrpc::get_status(
@ -1335,13 +1309,10 @@ fn get_memory_info(block_size: bool, hotplug: bool) -> Result<(u64, bool)> {
return Err(anyhow!("Invalid block size")); return Err(anyhow!("Invalid block size"));
} }
size = match u64::from_str_radix(v.trim(), 16) { size = u64::from_str_radix(v.trim(), 16).map_err(|_| {
Ok(h) => h,
Err(_) => {
warn!(sl!(), "failed to parse the str {} to hex", size); warn!(sl!(), "failed to parse the str {} to hex", size);
return Err(anyhow!("Invalid block size")); anyhow!("Invalid block size")
} })?;
};
} }
Err(e) => { Err(e) => {
info!(sl!(), "memory block size error: {:?}", e.kind()); info!(sl!(), "memory block size error: {:?}", e.kind());

View File

@ -316,10 +316,9 @@ impl Sandbox {
thread::spawn(move || { thread::spawn(move || {
for event in rx { for event in rx {
info!(logger, "got an OOM event {:?}", event); info!(logger, "got an OOM event {:?}", event);
match tx.send(container_id.clone()) { let _ = tx
Err(err) => error!(logger, "failed to send message: {:?}", err), .send(container_id.clone())
Ok(_) => {} .map_err(|e| error!(logger, "failed to send message: {:?}", e));
}
} }
}); });
} }