From bf7dec5c4f6fe95a0e5d811da7ecf7b0c8a74917 Mon Sep 17 00:00:00 2001 From: bin liu Date: Fri, 16 Oct 2020 15:46:47 +0800 Subject: [PATCH] agent: clear clippy warnings This commit clears clippy warings for agent package. Signed-off-by: bin liu --- src/agent/src/config.rs | 31 ++++----- src/agent/src/device.rs | 12 ++-- src/agent/src/main.rs | 19 +++--- src/agent/src/metrics.rs | 13 ++-- src/agent/src/mount.rs | 44 ++++++------ src/agent/src/namespace.rs | 27 ++++---- src/agent/src/network.rs | 6 +- src/agent/src/random.rs | 1 - src/agent/src/rpc.rs | 133 ++++++++++++++++++++----------------- src/agent/src/sandbox.rs | 18 ++--- 10 files changed, 150 insertions(+), 154 deletions(-) diff --git a/src/agent/src/config.rs b/src/agent/src/config.rs index b46ab140ac..2c53bde203 100644 --- a/src/agent/src/config.rs +++ b/src/agent/src/config.rs @@ -144,7 +144,7 @@ impl agentConfig { } fn get_vsock_port(p: &str) -> Result { - let fields: Vec<&str> = p.split("=").collect(); + let fields: Vec<&str> = p.split('=').collect(); if fields.len() != 2 { return Err(anyhow!("invalid port parameter")); } @@ -180,7 +180,7 @@ fn logrus_to_slog_level(logrus_level: &str) -> Result { } fn get_log_level(param: &str) -> Result { - let fields: Vec<&str> = param.split("=").collect(); + let fields: Vec<&str> = param.split('=').collect(); if fields.len() != 2 { return Err(anyhow!("invalid log level parameter")); @@ -194,7 +194,7 @@ fn get_log_level(param: &str) -> Result { } fn get_hotplug_timeout(param: &str) -> Result { - let fields: Vec<&str> = param.split("=").collect(); + let fields: Vec<&str> = param.split('=').collect(); if fields.len() != 2 { return Err(anyhow!("invalid hotplug timeout parameter")); @@ -214,7 +214,7 @@ fn get_hotplug_timeout(param: &str) -> Result { } fn get_bool_value(param: &str) -> Result { - let fields: Vec<&str> = param.split("=").collect(); + let fields: Vec<&str> = param.split('=').collect(); if fields.len() != 2 { return Ok(false); @@ -225,18 +225,15 @@ fn get_bool_value(param: &str) -> Result { // first try to parse as bool value v.parse::().or_else(|_err1| { // then try to parse as integer value - v.parse::().or_else(|_err2| Ok(0)).and_then(|v| { - // only `0` returns false, otherwise returns true - Ok(match v { - 0 => false, - _ => true, - }) + v.parse::().or_else(|_err2| Ok(0)).map(|v| match v { + 0 => false, + _ => true, }) }) } fn get_container_pipe_size(param: &str) -> Result { - let fields: Vec<&str> = param.split("=").collect(); + let fields: Vec<&str> = param.split('=').collect(); if fields.len() != 2 { return Err(anyhow!("invalid container pipe size parameter")); @@ -634,10 +631,10 @@ mod tests { let filename = file_path.to_str().expect("failed to create filename"); let mut file = - File::create(filename).expect(&format!("{}: failed to create file", msg)); + File::create(filename).unwrap_or_else(|_| panic!("{}: failed to create file", msg)); file.write_all(d.contents.as_bytes()) - .expect(&format!("{}: failed to write file contents", msg)); + .unwrap_or_else(|_| panic!("{}: failed to write file contents", msg)); let mut config = agentConfig::new(); assert_eq!(config.debug_console, false, "{}", msg); @@ -737,7 +734,7 @@ mod tests { let msg = format!("{}: result: {:?}", msg, result); - assert_result!(d.result, result, format!("{}", msg)); + assert_result!(d.result, result, msg); } } @@ -831,7 +828,7 @@ mod tests { let msg = format!("{}: result: {:?}", msg, result); - assert_result!(d.result, result, format!("{}", msg)); + assert_result!(d.result, result, msg); } } @@ -901,7 +898,7 @@ mod tests { let msg = format!("{}: result: {:?}", msg, result); - assert_result!(d.result, result, format!("{}", msg)); + assert_result!(d.result, result, msg); } } @@ -975,7 +972,7 @@ mod tests { let msg = format!("{}: result: {:?}", msg, result); - assert_result!(d.result, result, format!("{}", msg)); + assert_result!(d.result, result, msg); } } } diff --git a/src/agent/src/device.rs b/src/agent/src/device.rs index 0cd2b1d72c..6a1265d947 100644 --- a/src/agent/src/device.rs +++ b/src/agent/src/device.rs @@ -38,8 +38,8 @@ struct DevIndex(HashMap); // DeviceHandler is the type of callback to be defined to handle every type of device driver. type DeviceHandler = fn(&Device, &mut Spec, &Arc>, &DevIndex) -> Result<()>; -// DeviceHandlerList lists the supported drivers. -#[cfg_attr(rustfmt, rustfmt_skip)] +// DEVICEHANDLERLIST lists the supported drivers. +#[rustfmt::skip] lazy_static! { static ref DEVICEHANDLERLIST: HashMap<&'static str, DeviceHandler> = { let mut m: HashMap<&'static str, DeviceHandler> = HashMap::new(); @@ -65,7 +65,7 @@ pub fn online_device(path: &str) -> Result<()> { // Here, bridgeAddr is the address at which the bridge is attached on the root bus, // while deviceAddr is the address at which the device is attached on the bridge. fn get_pci_device_address(pci_id: &str) -> Result { - let tokens: Vec<&str> = pci_id.split("/").collect(); + let tokens: Vec<&str> = pci_id.split('/').collect(); if tokens.len() != 2 { return Err(anyhow!( @@ -165,7 +165,7 @@ pub fn get_pci_device_name(sandbox: &Arc>, pci_id: &str) -> Resul /// Scan SCSI bus for the given SCSI address(SCSI-Id and LUN) 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 { return Err(anyhow!( "Unexpected format for SCSI Address: {}, expect SCSIID:LUA", @@ -336,11 +336,11 @@ impl DevIndex { fn new(spec: &Spec) -> DevIndex { let mut map = HashMap::new(); - for linux in spec.linux.as_ref() { + if let Some(linux) = spec.linux.as_ref() { for (i, d) in linux.devices.iter().enumerate() { let mut residx = Vec::new(); - for linuxres in linux.resources.as_ref() { + if let Some(linuxres) = linux.resources.as_ref() { for (j, r) in linuxres.devices.iter().enumerate() { if r.r#type == d.r#type && r.major == Some(d.major) diff --git a/src/agent/src/main.rs b/src/agent/src/main.rs index 45c73c1cf1..7ec1f7678e 100644 --- a/src/agent/src/main.rs +++ b/src/agent/src/main.rs @@ -246,8 +246,8 @@ fn start_sandbox(logger: &Logger, config: &agentConfig, init_mode: bool) -> Resu let (tx, rx) = mpsc::channel::(); sandbox.lock().unwrap().sender = Some(tx); - //vsock:///dev/vsock, port - let mut server = rpc::start(sandbox.clone(), config.server_addr.as_str()); + // vsock:///dev/vsock, port + let mut server = rpc::start(sandbox, config.server_addr.as_str()); let _ = server.start().unwrap(); @@ -272,8 +272,6 @@ fn setup_signal_handler(logger: &Logger, sandbox: Arc>) -> Result let signals = Signals::new(&[SIGCHLD])?; - let s = sandbox.clone(); - thread::spawn(move || { 'outer: for sig in signals.forever() { info!(logger, "received signal"; "signal" => sig); @@ -303,13 +301,13 @@ fn setup_signal_handler(logger: &Logger, sandbox: Arc>) -> Result }; let pid = wait_status.pid(); - if pid.is_some() { - let raw_pid = pid.unwrap().as_raw(); + if let Some(pid) = pid { + let raw_pid = pid.as_raw(); let child_pid = format!("{}", raw_pid); let logger = logger.new(o!("child-pid" => child_pid)); - let mut sandbox = s.lock().unwrap(); + let mut sandbox = sandbox.lock().unwrap(); let process = sandbox.find_process(raw_pid); if process.is_none() { info!(logger, "child exited unexpectedly"); @@ -366,7 +364,8 @@ fn init_agent_as_init(logger: &Logger, unified_cgroup_hierarchy: bool) -> Result env::set_var("PATH", "/bin:/sbin/:/usr/bin/:/usr/sbin/"); - let contents = std::fs::read_to_string("/etc/hostname").unwrap_or(String::from("localhost")); + let contents = + std::fs::read_to_string("/etc/hostname").unwrap_or_else(|_| String::from("localhost")); let contents_array: Vec<&str> = contents.split(' ').collect(); let hostname = contents_array[0].trim(); @@ -481,8 +480,8 @@ where // write and return match writer.write_all(&buf[..buf_len]) { - Ok(_) => return Ok(buf_len as u64), - Err(err) => return Err(err), + Ok(_) => Ok(buf_len as u64), + Err(err) => Err(err), } } diff --git a/src/agent/src/metrics.rs b/src/agent/src/metrics.rs index 20809aceb4..35ce4dbba9 100644 --- a/src/agent/src/metrics.rs +++ b/src/agent/src/metrics.rs @@ -8,7 +8,6 @@ extern crate procfs; use prometheus::{Encoder, Gauge, GaugeVec, IntCounter, TextEncoder}; use anyhow::Result; -use protocols; const NAMESPACE_KATA_AGENT: &str = "kata_agent"; const NAMESPACE_KATA_GUEST: &str = "kata_guest"; @@ -85,17 +84,15 @@ pub fn get_metrics(_: &protocols::agent::GetMetricsRequest) -> Result { let encoder = TextEncoder::new(); encoder.encode(&metric_families, &mut buffer).unwrap(); - Ok(String::from_utf8(buffer.clone()).unwrap()) + Ok(String::from_utf8(buffer).unwrap()) } fn update_agent_metrics() { let me = procfs::process::Process::myself(); - match me { - Err(err) => { - error!(sl!(), "failed to create process instance: {:?}", err); - return; - } - Ok(_) => {} + + if let Err(err) = me { + error!(sl!(), "failed to create process instance: {:?}", err); + return; } let me = me.unwrap(); diff --git a/src/agent/src/mount.rs b/src/agent/src/mount.rs index c31afab478..8b98e9046c 100644 --- a/src/agent/src/mount.rs +++ b/src/agent/src/mount.rs @@ -39,7 +39,7 @@ pub const DRIVERLOCALTYPE: &str = "local"; pub const TYPEROOTFS: &str = "rootfs"; -#[cfg_attr(rustfmt, rustfmt_skip)] +#[rustfmt::skip] lazy_static! { pub static ref FLAGS: HashMap<&'static str, (bool, MsFlags)> = { let mut m = HashMap::new(); @@ -88,7 +88,7 @@ pub struct INIT_MOUNT { options: Vec<&'static str>, } -#[cfg_attr(rustfmt, rustfmt_skip)] +#[rustfmt::skip] lazy_static!{ static ref CGROUPS: HashMap<&'static str, &'static str> = { let mut m = HashMap::new(); @@ -109,7 +109,7 @@ lazy_static!{ }; } -#[cfg_attr(rustfmt, rustfmt_skip)] +#[rustfmt::skip] lazy_static! { pub static ref INIT_ROOTFS_MOUNTS: Vec = vec![ INIT_MOUNT{fstype: "proc", src: "proc", dest: "/proc", options: vec!["nosuid", "nodev", "noexec"]}, @@ -126,7 +126,7 @@ lazy_static! { type StorageHandler = fn(&Logger, &Storage, Arc>) -> Result; // STORAGEHANDLERLIST lists the supported drivers. -#[cfg_attr(rustfmt, rustfmt_skip)] +#[rustfmt::skip] lazy_static! { pub static ref STORAGEHANDLERLIST: HashMap<&'static str, StorageHandler> = { let mut m = HashMap::new(); @@ -243,8 +243,7 @@ fn ephemeral_storage_handler( storage: &Storage, sandbox: Arc>, ) -> Result { - let s = sandbox.clone(); - let mut sb = s.lock().unwrap(); + let mut sb = sandbox.lock().unwrap(); let new_storage = sb.set_sandbox_storage(&storage.mount_point); if !new_storage { @@ -262,8 +261,7 @@ fn local_storage_handler( storage: &Storage, sandbox: Arc>, ) -> Result { - let s = sandbox.clone(); - let mut sb = s.lock().unwrap(); + let mut sb = sandbox.lock().unwrap(); let new_storage = sb.set_sandbox_storage(&storage.mount_point); if !new_storage { @@ -279,8 +277,7 @@ fn local_storage_handler( let opts = parse_options(opts_vec); let mode = opts.get("mode"); - if mode.is_some() { - let mode = mode.unwrap(); + if let Some(mode) = mode { let mut permission = fs::metadata(&storage.mount_point)?.permissions(); let o_mode = u32::from_str_radix(mode, 8)?; @@ -414,13 +411,13 @@ fn parse_mount_flags_and_options(options_vec: Vec<&str>) -> (MsFlags, String) { match FLAGS.get(opt) { Some(x) => { let (_, f) = *x; - flags = flags | f; + flags |= f; } None => { if options.len() > 0 { options.push_str(format!(",{}", opt).as_str()); } else { - options.push_str(format!("{}", opt).as_str()); + options.push_str(opt.to_string().as_str()); } } }; @@ -570,10 +567,10 @@ pub fn get_cgroup_mounts( 'outer: for (_, line) in reader.lines().enumerate() { let line = line?; - let fields: Vec<&str> = line.split("\t").collect(); + let fields: Vec<&str> = line.split('\t').collect(); // Ignore comment header - if fields[0].starts_with("#") { + if fields[0].starts_with('#') { continue; } @@ -643,7 +640,7 @@ pub fn cgroups_mount(logger: &Logger, unified_cgroup_hierarchy: bool) -> Result< Ok(()) } -pub fn remove_mounts(mounts: &Vec) -> Result<()> { +pub fn remove_mounts(mounts: &[String]) -> Result<()> { for m in mounts.iter() { mount::umount(m.as_str()).context(format!("failed to umount {:?}", m))?; } @@ -675,7 +672,7 @@ fn ensure_destination_exists(destination: &str, fs_type: &str) -> Result<()> { fn parse_options(option_list: Vec) -> HashMap { let mut options = HashMap::new(); for opt in option_list.iter() { - let fields: Vec<&str> = opt.split("=").collect(); + let fields: Vec<&str> = opt.split('=').collect(); if fields.len() != 2 { continue; } @@ -856,7 +853,7 @@ mod tests { let msg = format!("{}: umount result: {:?}", msg, result); - assert!(ret == 0, format!("{}", msg)); + assert!(ret == 0, msg); }; continue; @@ -914,7 +911,8 @@ mod tests { .expect("failed to create mount destination filename"); for d in [test_dir_filename, mnt_src_filename, mnt_dest_filename].iter() { - std::fs::create_dir_all(d).expect(&format!("failed to create directory {}", d)); + std::fs::create_dir_all(d) + .unwrap_or_else(|_| panic!("failed to create directory {}", d)); } // Create an actual mount @@ -1055,13 +1053,13 @@ mod tests { let filename = file_path .to_str() - .expect(&format!("{}: failed to create filename", msg)); + .unwrap_or_else(|| panic!("{}: failed to create filename", msg)); let mut file = - File::create(filename).expect(&format!("{}: failed to create file", msg)); + File::create(filename).unwrap_or_else(|_| panic!("{}: failed to create file", msg)); file.write_all(d.contents.as_bytes()) - .expect(&format!("{}: failed to write file contents", msg)); + .unwrap_or_else(|_| panic!("{}: failed to write file contents", msg)); let result = get_mount_fs_type_from_file(filename, d.mount_point); @@ -1217,10 +1215,10 @@ mod tests { .expect("failed to create cgroup file filename"); let mut file = - File::create(filename).expect(&format!("{}: failed to create file", msg)); + File::create(filename).unwrap_or_else(|_| panic!("{}: failed to create file", msg)); file.write_all(d.contents.as_bytes()) - .expect(&format!("{}: failed to write file contents", msg)); + .unwrap_or_else(|_| panic!("{}: failed to write file contents", msg)); let result = get_cgroup_mounts(&logger, filename, false); let msg = format!("{}: result: {:?}", msg, result); diff --git a/src/agent/src/namespace.rs b/src/agent/src/namespace.rs index f5c6fa3b0a..3b373b108c 100644 --- a/src/agent/src/namespace.rs +++ b/src/agent/src/namespace.rs @@ -52,12 +52,12 @@ impl Namespace { } } - pub fn as_ipc(mut self) -> Self { + pub fn get_ipc(mut self) -> Self { self.ns_type = NamespaceType::IPC; self } - pub fn as_uts(mut self, hostname: &str) -> Self { + pub fn get_uts(mut self, hostname: &str) -> Self { self.ns_type = NamespaceType::UTS; if hostname != "" { self.hostname = Some(String::from(hostname)); @@ -65,7 +65,7 @@ impl Namespace { self } - pub fn as_pid(mut self) -> Self { + pub fn get_pid(mut self) -> Self { self.ns_type = NamespaceType::PID; self } @@ -81,7 +81,7 @@ impl Namespace { fs::create_dir_all(&self.persistent_ns_dir)?; let ns_path = PathBuf::from(&self.persistent_ns_dir); - let ns_type = self.ns_type.clone(); + let ns_type = self.ns_type; let logger = self.logger.clone(); let new_ns_path = ns_path.join(&ns_type.get()); @@ -97,7 +97,7 @@ impl Namespace { File::open(Path::new(&origin_ns_path))?; // Create a new netns on the current thread. - let cf = ns_type.get_flags().clone(); + let cf = ns_type.get_flags(); unshare(cf)?; @@ -110,12 +110,9 @@ impl Namespace { let mut flags = MsFlags::empty(); - match FLAGS.get("rbind") { - Some(x) => { - let (_, f) = *x; - flags = flags | f; - } - None => (), + if let Some(x) = FLAGS.get("rbind") { + let (_, f) = *x; + flags |= f; }; let bare_mount = BareMount::new(source, destination, "none", flags, "", &logger); @@ -194,23 +191,23 @@ mod tests { let tmpdir = Builder::new().prefix("ipc").tempdir().unwrap(); let ns_ipc = Namespace::new(&logger) - .as_ipc() + .get_ipc() .set_root_dir(tmpdir.path().to_str().unwrap()) .setup(); assert!(ns_ipc.is_ok()); - assert!(remove_mounts(&vec![ns_ipc.unwrap().path]).is_ok()); + assert!(remove_mounts(&[ns_ipc.unwrap().path]).is_ok()); let logger = slog::Logger::root(slog::Discard, o!()); let tmpdir = Builder::new().prefix("ipc").tempdir().unwrap(); let ns_uts = Namespace::new(&logger) - .as_uts("test_hostname") + .get_uts("test_hostname") .set_root_dir(tmpdir.path().to_str().unwrap()) .setup(); assert!(ns_uts.is_ok()); - assert!(remove_mounts(&vec![ns_uts.unwrap().path]).is_ok()); + assert!(remove_mounts(&[ns_uts.unwrap().path]).is_ok()); } #[test] diff --git a/src/agent/src/network.rs b/src/agent/src/network.rs index 1fccf5eeec..829149cdfd 100644 --- a/src/agent/src/network.rs +++ b/src/agent/src/network.rs @@ -117,12 +117,12 @@ mod tests { ]; // write to /run/kata-containers/sandbox/resolv.conf - let mut src_file = - File::create(src_filename).expect(&format!("failed to create file {:?}", src_filename)); + let mut src_file = File::create(src_filename) + .unwrap_or_else(|_| panic!("failed to create file {:?}", src_filename)); let content = dns.join("\n"); src_file .write_all(content.as_bytes()) - .expect(&format!("failed to write file contents")); + .expect("failed to write file contents"); // call do_setup_guest_dns let result = do_setup_guest_dns(logger, dns.clone(), src_filename, dst_filename); diff --git a/src/agent/src/random.rs b/src/agent/src/random.rs index 6d28a49a0c..a5628c2177 100644 --- a/src/agent/src/random.rs +++ b/src/agent/src/random.rs @@ -4,7 +4,6 @@ // use anyhow::Result; -use libc; use nix::errno::Errno; use nix::fcntl::{self, OFlag}; use nix::sys::stat::Mode; diff --git a/src/agent/src/rpc.rs b/src/agent/src/rpc.rs index ee3872d797..60d1af02d0 100644 --- a/src/agent/src/rpc.rs +++ b/src/agent/src/rpc.rs @@ -21,7 +21,6 @@ use protocols::health::{ HealthCheckResponse, HealthCheckResponse_ServingStatus, VersionCheckResponse, }; use protocols::types::Interface; -use rustjail; use rustjail::cgroups::notifier; use rustjail::container::{BaseContainer, Container, LinuxContainer}; use rustjail::process::Process; @@ -47,7 +46,6 @@ use crate::AGENT_CONFIG; use netlink::{RtnlHandle, NETLINK_ROUTE}; use libc::{self, c_ushort, pid_t, winsize, TIOCSWINSZ}; -use serde_json; use std::convert::TryFrom; use std::fs; use std::os::unix::io::RawFd; @@ -152,14 +150,13 @@ impl agentService { let pipe_size = AGENT_CONFIG.read().unwrap().container_pipe_size; let p = if oci.process.is_some() { - let tp = Process::new( + Process::new( &sl!(), &oci.process.as_ref().unwrap(), cid.as_str(), true, pipe_size, - )?; - tp + )? } else { info!(sl!(), "no process configurations!"); return Err(anyhow!(nix::Error::from_errno(nix::errno::Errno::EINVAL))); @@ -175,7 +172,7 @@ impl agentService { } fn do_start_container(&self, req: protocols::agent::StartContainerRequest) -> Result<()> { - let cid = req.container_id.clone(); + let cid = req.container_id; let sandbox = self.sandbox.clone(); let mut s = sandbox.lock().unwrap(); @@ -183,7 +180,7 @@ impl agentService { let ctr = s .get_container(&cid) - .ok_or(anyhow!("Invalid container id"))?; + .ok_or_else(|| anyhow!("Invalid container id"))?; ctr.exec()?; @@ -206,9 +203,7 @@ impl agentService { let mut remove_container_resources = |sandbox: &mut Sandbox| -> Result<()> { // Find the sandbox storage used by this container let mounts = sandbox.container_mounts.get(&cid); - if mounts.is_some() { - let mounts = mounts.unwrap(); - + if let Some(mounts) = mounts { remove_mounts(&mounts)?; for m in mounts.iter() { @@ -232,7 +227,7 @@ impl agentService { let mut sandbox = s.lock().unwrap(); let ctr = sandbox .get_container(&cid) - .ok_or(anyhow!("Invalid container id"))?; + .ok_or_else(|| anyhow!("Invalid container id"))?; ctr.destroy()?; @@ -250,11 +245,11 @@ impl agentService { let mut sandbox = s.lock().unwrap(); let _ctr = sandbox .get_container(&cid2) - .ok_or(anyhow!("Invalid container id")) - .and_then(|ctr| { + .ok_or_else(|| anyhow!("Invalid container id")) + .map(|ctr| { ctr.destroy().unwrap(); tx.send(1).unwrap(); - Ok(ctr) + ctr }); }); @@ -277,7 +272,7 @@ impl agentService { let cid = req.container_id.clone(); let exec_id = req.exec_id.clone(); - info!(sl!(), "cid: {} eid: {}", cid.clone(), exec_id.clone()); + info!(sl!(), "cid: {} eid: {}", cid, exec_id); let s = self.sandbox.clone(); let mut sandbox = s.lock().unwrap(); @@ -294,7 +289,7 @@ impl agentService { let ctr = sandbox .get_container(&cid) - .ok_or(anyhow!("Invalid container id"))?; + .ok_or_else(|| anyhow!("Invalid container id"))?; ctr.run(p)?; @@ -340,7 +335,7 @@ impl agentService { req: protocols::agent::WaitProcessRequest, ) -> Result { let cid = req.container_id.clone(); - let eid = req.exec_id.clone(); + let eid = req.exec_id; let s = self.sandbox.clone(); let mut resp = WaitProcessResponse::new(); let pid: pid_t; @@ -376,7 +371,7 @@ impl agentService { let mut sandbox = s.lock().unwrap(); let ctr = sandbox .get_container(&cid) - .ok_or(anyhow!("Invalid container id"))?; + .ok_or_else(|| anyhow!("Invalid container id"))?; let mut p = match ctr.processes.get_mut(&pid) { Some(p) => p, @@ -584,16 +579,18 @@ impl protocols::agent_ttrpc::AgentService for agentService { ) -> ttrpc::Result { let cid = req.container_id.clone(); let format = req.format.clone(); - let mut args = req.args.clone().into_vec(); + let mut args = req.args.into_vec(); let mut resp = ListProcessesResponse::new(); let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); - let ctr = sandbox.get_container(&cid).ok_or(ttrpc_error( - ttrpc::Code::INVALID_ARGUMENT, - "invalid container id".to_string(), - ))?; + let ctr = sandbox.get_container(&cid).ok_or_else(|| { + ttrpc_error( + ttrpc::Code::INVALID_ARGUMENT, + "invalid container id".to_string(), + ) + })?; let pids = ctr.processes().unwrap(); @@ -670,10 +667,12 @@ impl protocols::agent_ttrpc::AgentService for agentService { let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); - let ctr = sandbox.get_container(&cid).ok_or(ttrpc_error( - ttrpc::Code::INVALID_ARGUMENT, - "invalid container id".to_string(), - ))?; + let ctr = sandbox.get_container(&cid).ok_or_else(|| { + ttrpc_error( + ttrpc::Code::INVALID_ARGUMENT, + "invalid container id".to_string(), + ) + })?; let resp = Empty::new(); @@ -696,14 +695,16 @@ impl protocols::agent_ttrpc::AgentService for agentService { _ctx: &ttrpc::TtrpcContext, req: protocols::agent::StatsContainerRequest, ) -> ttrpc::Result { - let cid = req.container_id.clone(); + let cid = req.container_id; let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); - let ctr = sandbox.get_container(&cid).ok_or(ttrpc_error( - ttrpc::Code::INVALID_ARGUMENT, - "invalid container id".to_string(), - ))?; + let ctr = sandbox.get_container(&cid).ok_or_else(|| { + ttrpc_error( + ttrpc::Code::INVALID_ARGUMENT, + "invalid container id".to_string(), + ) + })?; ctr.stats() .map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string())) @@ -718,10 +719,12 @@ impl protocols::agent_ttrpc::AgentService for agentService { let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); - let ctr = sandbox.get_container(&cid).ok_or(ttrpc_error( - ttrpc::Code::INVALID_ARGUMENT, - "invalid container id".to_string(), - ))?; + let ctr = sandbox.get_container(&cid).ok_or_else(|| { + ttrpc_error( + ttrpc::Code::INVALID_ARGUMENT, + "invalid container id".to_string(), + ) + })?; ctr.pause() .map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string()))?; @@ -738,10 +741,12 @@ impl protocols::agent_ttrpc::AgentService for agentService { let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); - let ctr = sandbox.get_container(&cid).ok_or(ttrpc_error( - ttrpc::Code::INVALID_ARGUMENT, - "invalid container id".to_string(), - ))?; + let ctr = sandbox.get_container(&cid).ok_or_else(|| { + ttrpc_error( + ttrpc::Code::INVALID_ARGUMENT, + "invalid container id".to_string(), + ) + })?; ctr.resume() .map_err(|e| ttrpc_error(ttrpc::Code::INTERNAL, e.to_string()))?; @@ -782,7 +787,7 @@ impl protocols::agent_ttrpc::AgentService for agentService { req: protocols::agent::CloseStdinRequest, ) -> ttrpc::Result { let cid = req.container_id.clone(); - let eid = req.exec_id.clone(); + let eid = req.exec_id; let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); @@ -852,11 +857,11 @@ impl protocols::agent_ttrpc::AgentService for agentService { if req.interface.is_none() { return Err(ttrpc_error( ttrpc::Code::INVALID_ARGUMENT, - format!("empty update interface request"), + "empty update interface request".to_string(), )); } - let interface = req.interface.clone(); + let interface = req.interface; let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); @@ -884,11 +889,11 @@ impl protocols::agent_ttrpc::AgentService for agentService { if req.routes.is_none() { return Err(ttrpc_error( ttrpc::Code::INVALID_ARGUMENT, - format!("empty update routes request"), + "empty update routes request".to_string(), )); } - let rs = req.routes.clone().unwrap().Routes.into_vec(); + let rs = req.routes.unwrap().Routes.into_vec(); let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); @@ -1028,7 +1033,7 @@ impl protocols::agent_ttrpc::AgentService for agentService { Ok(_) => { let sandbox = self.sandbox.clone(); let mut s = sandbox.lock().unwrap(); - let _ = req + let _dns = req .dns .to_vec() .iter() @@ -1065,11 +1070,11 @@ impl protocols::agent_ttrpc::AgentService for agentService { if req.neighbors.is_none() { return Err(ttrpc_error( ttrpc::Code::INVALID_ARGUMENT, - format!("empty add arp neighbours request"), + "empty add arp neighbours request".to_string(), )); } - let neighs = req.neighbors.clone().unwrap().ARPNeighbors.into_vec(); + let neighs = req.neighbors.unwrap().ARPNeighbors.into_vec(); let s = Arc::clone(&self.sandbox); let mut sandbox = s.lock().unwrap(); @@ -1203,7 +1208,7 @@ impl protocols::agent_ttrpc::AgentService for agentService { info!(sl!(), "get_oom_event return {}", &container_id); let mut resp = OOMEvent::new(); resp.container_id = container_id; - return Ok(resp); + Ok(resp) } } } @@ -1340,13 +1345,13 @@ fn find_process<'a>( ) -> Result<&'a mut Process> { let ctr = sandbox .get_container(cid) - .ok_or(anyhow!("Invalid container id"))?; + .ok_or_else(|| anyhow!("Invalid container id"))?; if init || eid == "" { return ctr .processes .get_mut(&ctr.init_process_pid) - .ok_or(anyhow!("cannot find init process!")); + .ok_or_else(|| anyhow!("cannot find init process!")); } ctr.get_process(eid).map_err(|_| anyhow!("Invalid exec id")) @@ -1396,7 +1401,7 @@ fn update_container_namespaces( let linux = spec .linux .as_mut() - .ok_or(anyhow!("Spec didn't container linux field"))?; + .ok_or_else(|| anyhow!("Spec didn't container linux field"))?; let namespaces = linux.namespaces.as_mut_slice(); for namespace in namespaces.iter_mut() { @@ -1464,7 +1469,7 @@ fn is_signal_handled(pid: pid_t, signum: u32) -> bool { } }; if line.starts_with("SigCgt:") { - let mask_vec: Vec<&str> = line.split(":").collect(); + let mask_vec: Vec<&str> = line.split(':').collect(); if mask_vec.len() != 2 { warn!(sl!(), "parse the SigCgt field failed\n"); return false; @@ -1484,7 +1489,7 @@ fn is_signal_handled(pid: pid_t, signum: u32) -> bool { false } -fn do_mem_hotplug_by_probe(addrs: &Vec) -> Result<()> { +fn do_mem_hotplug_by_probe(addrs: &[u64]) -> Result<()> { for addr in addrs.iter() { fs::write(SYSFS_MEMORY_HOTPLUG_PROBE_PATH, format!("{:#X}", *addr))?; } @@ -1497,8 +1502,12 @@ fn do_set_guest_date_time(sec: i64, usec: i64) -> Result<()> { tv_usec: usec, }; - let ret = - unsafe { libc::settimeofday(&tv as *const libc::timeval, 0 as *const libc::timezone) }; + let ret = unsafe { + libc::settimeofday( + &tv as *const libc::timeval, + std::ptr::null::(), + ) + }; Errno::result(ret).map(drop)?; @@ -1514,8 +1523,8 @@ fn do_copy_file(req: &CopyFileRequest) -> Result<()> { let parent = path.parent(); - let dir = if parent.is_some() { - parent.unwrap().to_path_buf() + let dir = if let Some(parent) = parent { + parent.to_path_buf() } else { PathBuf::from("/") }; @@ -1575,8 +1584,8 @@ fn setup_bundle(cid: &str, spec: &mut Spec) -> Result { let spec_root = spec.root.as_ref().unwrap(); let bundle_path = Path::new(CONTAINER_BASE).join(cid); - let config_path = bundle_path.clone().join("config.json"); - let rootfs_path = bundle_path.clone().join("rootfs"); + let config_path = bundle_path.join("config.json"); + let rootfs_path = bundle_path.join("rootfs"); fs::create_dir_all(&rootfs_path)?; BareMount::new( @@ -1640,9 +1649,9 @@ fn load_kernel_module(module: &protocols::agent::KernelModule) -> Result<()> { "load_kernel_module return code: {} stdout:{} stderr:{}", code, std_out, std_err ); - return Err(anyhow!(msg)); + Err(anyhow!(msg)) } - None => return Err(anyhow!("Process terminated by signal")), + None => Err(anyhow!("Process terminated by signal")), } } diff --git a/src/agent/src/sandbox.rs b/src/agent/src/sandbox.rs index ee5ab08f98..9f35af4106 100644 --- a/src/agent/src/sandbox.rs +++ b/src/agent/src/sandbox.rs @@ -112,14 +112,14 @@ impl Sandbox { // acquiring a lock on sandbox. pub fn unset_sandbox_storage(&mut self, path: &str) -> Result { match self.storages.get_mut(path) { - None => return Err(anyhow!("Sandbox storage with path {} not found", path)), + None => Err(anyhow!("Sandbox storage with path {} not found", path)), Some(count) => { *count -= 1; if *count < 1 { self.storages.remove(path); return Ok(true); } - return Ok(false); + Ok(false) } } } @@ -161,13 +161,13 @@ impl Sandbox { pub fn setup_shared_namespaces(&mut self) -> Result { // Set up shared IPC namespace self.shared_ipcns = Namespace::new(&self.logger) - .as_ipc() + .get_ipc() .setup() .context("Failed to setup persistent IPC namespace")?; // // Set up shared UTS namespace self.shared_utsns = Namespace::new(&self.logger) - .as_uts(self.hostname.as_str()) + .get_uts(self.hostname.as_str()) .setup() .context("Failed to setup persistent UTS namespace")?; @@ -192,7 +192,7 @@ impl Sandbox { )); } - let mut pid_ns = Namespace::new(&self.logger).as_pid(); + let mut pid_ns = Namespace::new(&self.logger).get_pid(); pid_ns.path = format!("/proc/{}/ns/pid", init_pid); self.sandbox_pidns = Some(pid_ns); @@ -216,7 +216,7 @@ impl Sandbox { } pub fn destroy(&mut self) -> Result<()> { - for (_, ctr) in &mut self.containers { + for ctr in self.containers.values_mut() { ctr.destroy()?; } Ok(()) @@ -332,7 +332,7 @@ fn online_resources(logger: &Logger, path: &str, pattern: &str, num: i32) -> Res } let c = c.unwrap(); - if c.trim().contains("0") { + if c.trim().contains('0') { let r = fs::write(file.as_str(), "1"); if r.is_err() { continue; @@ -612,8 +612,8 @@ mod tests { let linux = Linux::default(); let mut spec = Spec::default(); - spec.root = Some(root).into(); - spec.linux = Some(linux).into(); + spec.root = Some(root); + spec.linux = Some(linux); CreateOpts { cgroup_name: "".to_string(),