diff --git a/src/agent/rustjail/src/cgroups/fs/mod.rs b/src/agent/rustjail/src/cgroups/fs/mod.rs index 3ff1391b78..d339289489 100644 --- a/src/agent/rustjail/src/cgroups/fs/mod.rs +++ b/src/agent/rustjail/src/cgroups/fs/mod.rs @@ -103,21 +103,21 @@ impl CgroupManager for Manager { // set block_io resources if let Some(blkio) = &r.block_io { - set_block_io_resources(&self.cgroup, blkio, res)?; + set_block_io_resources(&self.cgroup, blkio, res); } // set hugepages resources if !r.hugepage_limits.is_empty() { - set_hugepages_resources(&self.cgroup, &r.hugepage_limits, res)?; + set_hugepages_resources(&self.cgroup, &r.hugepage_limits, res); } // set network resources if let Some(network) = &r.network { - set_network_resources(&self.cgroup, network, res)?; + set_network_resources(&self.cgroup, network, res); } // set devices resources - set_devices_resources(&self.cgroup, &r.devices, res)?; + set_devices_resources(&self.cgroup, &r.devices, res); info!(sl!(), "resources after processed {:?}", res); // apply resources @@ -198,7 +198,7 @@ fn set_network_resources( _cg: &cgroups::Cgroup, network: &LinuxNetwork, res: &mut cgroups::Resources, -) -> Result<()> { +) { info!(sl!(), "cgroup manager set network"); // set classid @@ -219,14 +219,13 @@ fn set_network_resources( } res.network.priorities = priorities; - Ok(()) } fn set_devices_resources( _cg: &cgroups::Cgroup, device_resources: &[LinuxDeviceCgroup], res: &mut cgroups::Resources, -) -> Result<()> { +) { info!(sl!(), "cgroup manager set devices"); let mut devices = vec![]; @@ -249,15 +248,13 @@ fn set_devices_resources( } res.devices.devices = devices; - - Ok(()) } fn set_hugepages_resources( _cg: &cgroups::Cgroup, hugepage_limits: &[LinuxHugepageLimit], res: &mut cgroups::Resources, -) -> Result<()> { +) { info!(sl!(), "cgroup manager set hugepage"); let mut limits = vec![]; @@ -269,15 +266,13 @@ fn set_hugepages_resources( limits.push(hr); } res.hugepages.limits = limits; - - Ok(()) } fn set_block_io_resources( _cg: &cgroups::Cgroup, blkio: &LinuxBlockIO, res: &mut cgroups::Resources, -) -> Result<()> { +) { info!(sl!(), "cgroup manager set block io"); res.blkio.weight = blkio.weight; @@ -303,8 +298,6 @@ fn set_block_io_resources( build_blk_io_device_throttle_resource(&blkio.throttle_read_iops_device); res.blkio.throttle_write_iops_device = build_blk_io_device_throttle_resource(&blkio.throttle_write_iops_device); - - Ok(()) } fn set_cpu_resources(cg: &cgroups::Cgroup, cpu: &LinuxCPU) -> Result<()> { @@ -372,7 +365,7 @@ fn set_memory_resources(cg: &cgroups::Cgroup, memory: &LinuxMemory, update: bool } if let Some(swappiness) = memory.swappiness { - if swappiness >= 0 && swappiness <= 100 { + if (0..=100).contains(&swappiness) { mem_controller.set_swappiness(swappiness as u64)?; } else { return Err(anyhow!( @@ -965,7 +958,7 @@ impl Manager { } pub fn update_cpuset_path(&self, guest_cpuset: &str, container_cpuset: &str) -> Result<()> { - if guest_cpuset == "" { + if guest_cpuset.is_empty() { return Ok(()); } info!(sl!(), "update_cpuset_path to: {}", guest_cpuset); diff --git a/src/agent/rustjail/src/cgroups/notifier.rs b/src/agent/rustjail/src/cgroups/notifier.rs index 1b4750a02a..70e503414a 100644 --- a/src/agent/rustjail/src/cgroups/notifier.rs +++ b/src/agent/rustjail/src/cgroups/notifier.rs @@ -132,7 +132,7 @@ async fn register_memory_event_v2( // notify_on_oom returns channel on which you can expect event about OOM, // if process died without OOM this channel will be closed. async fn notify_on_oom(cid: &str, dir: String) -> Result> { - if dir == "" { + if dir.is_empty() { return Err(anyhow!("memory controller missing")); } @@ -141,7 +141,7 @@ async fn notify_on_oom(cid: &str, dir: String) -> Result> { // level is one of "low", "medium", or "critical" async fn notify_memory_pressure(cid: &str, dir: String, level: &str) -> Result> { - if dir == "" { + if dir.is_empty() { return Err(anyhow!("memory controller missing")); } @@ -165,7 +165,7 @@ async fn register_memory_event( let event_control_path = Path::new(&cg_dir).join("cgroup.event_control"); let data; - if arg == "" { + if arg.is_empty() { data = format!("{} {}", eventfd, event_file.as_raw_fd()); } else { data = format!("{} {} {}", eventfd, event_file.as_raw_fd(), arg); diff --git a/src/agent/rustjail/src/container.rs b/src/agent/rustjail/src/container.rs index 07cfbf2ab9..edf99dfa03 100644 --- a/src/agent/rustjail/src/container.rs +++ b/src/agent/rustjail/src/container.rs @@ -695,7 +695,7 @@ fn set_stdio_permissions(uid: libc::uid_t) -> Result<()> { // According to the POSIX specification, -1 is used to indicate that owner and group // are not to be changed. Since uid_t and gid_t are unsigned types, we have to wrap // around to get -1. - let gid = (0 as libc::gid_t).wrapping_sub(1); + let gid = 0u32.wrapping_sub(1); // We only change the uid owner (as it is possible for the mount to // prefer a different gid, and there's no reason for us to change it). @@ -1114,7 +1114,7 @@ fn update_namespaces(logger: &Logger, spec: &mut Spec, init_pid: RawFd) -> Resul TYPETONAME.get(namespace.r#type.as_str()).unwrap() ); - if namespace.path == "" { + if namespace.path.is_empty() { namespace.path = ns_path; } } @@ -1126,7 +1126,7 @@ fn update_namespaces(logger: &Logger, spec: &mut Spec, init_pid: RawFd) -> Resul fn get_pid_namespace(logger: &Logger, linux: &Linux) -> Result> { for ns in &linux.namespaces { if ns.r#type == "pid" { - if ns.path == "" { + if ns.path.is_empty() { return Ok(None); } @@ -1154,7 +1154,7 @@ fn is_userns_enabled(linux: &Linux) -> bool { linux .namespaces .iter() - .any(|ns| ns.r#type == "user" && ns.path == "") + .any(|ns| ns.r#type == "user" && ns.path.is_empty()) } fn get_namespaces(linux: &Linux) -> Vec { diff --git a/src/agent/rustjail/src/validator.rs b/src/agent/rustjail/src/validator.rs index 53e05a45b4..b5fabf9296 100644 --- a/src/agent/rustjail/src/validator.rs +++ b/src/agent/rustjail/src/validator.rs @@ -78,12 +78,8 @@ fn rootfs(root: &str) -> Result<()> { Ok(()) } -fn network(_oci: &Spec) -> Result<()> { - Ok(()) -} - fn hostname(oci: &Spec) -> Result<()> { - if oci.hostname.is_empty() || oci.hostname == "" { + if oci.hostname.is_empty() { return Ok(()); } @@ -301,7 +297,6 @@ pub fn validate(conf: &Config) -> Result<()> { }; rootfs(root).context("rootfs")?; - network(oci).context("network")?; hostname(oci).context("hostname")?; security(oci).context("security")?; usernamespace(oci).context("usernamespace")?; diff --git a/src/agent/src/device.rs b/src/agent/src/device.rs index f69fa5c98f..43c3c72b38 100644 --- a/src/agent/src/device.rs +++ b/src/agent/src/device.rs @@ -203,7 +203,7 @@ fn update_spec_device_list(device: &Device, spec: &mut Spec, devidx: &DevIndex) // If no container_path is provided, we won't be able to match and // update the device in the OCI spec device list. This is an error. - if device.container_path == "" { + if device.container_path.is_empty() { return Err(anyhow!( "container_path cannot empty for device {:?}", device @@ -279,7 +279,7 @@ async fn virtiommio_blk_device_handler( _sandbox: &Arc>, devidx: &DevIndex, ) -> Result<()> { - if device.vm_path == "" { + if device.vm_path.is_empty() { return Err(anyhow!("Invalid path for virtio mmio blk device")); } @@ -298,7 +298,7 @@ async fn virtio_blk_device_handler( // When "Id (PCI path)" is not set, we allow to use the predicted // "VmPath" passed from kata-runtime Note this is a special code // path for cloud-hypervisor when BDF information is not available - if device.id != "" { + if !device.id.is_empty() { let pcipath = pci::Path::from_str(&device.id)?; dev.vm_path = get_pci_device_name(sandbox, &pcipath).await?; } @@ -324,7 +324,7 @@ async fn virtio_nvdimm_device_handler( _sandbox: &Arc>, devidx: &DevIndex, ) -> Result<()> { - if device.vm_path == "" { + if device.vm_path.is_empty() { return Err(anyhow!("Invalid path for nvdimm device")); } @@ -380,15 +380,15 @@ async fn add_device( info!(sl!(), "device-id: {}, device-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.is_empty() { return Err(anyhow!("invalid type for device {:?}", device)); } - if device.id == "" && device.vm_path == "" { + if device.id.is_empty() && device.vm_path.is_empty() { return Err(anyhow!("invalid ID and VM path for device {:?}", device)); } - if device.container_path == "" { + if device.container_path.is_empty() { return Err(anyhow!("invalid container path for device {:?}", device)); } @@ -439,9 +439,10 @@ mod tests { #[test] fn test_update_device_cgroup() { - let mut spec = Spec::default(); - - spec.linux = Some(Linux::default()); + let mut spec = Spec { + linux: Some(Linux::default()), + ..Default::default() + }; update_device_cgroup(&mut spec).unwrap(); diff --git a/src/agent/src/mount.rs b/src/agent/src/mount.rs index 188c2073a6..8b873f1953 100644 --- a/src/agent/src/mount.rs +++ b/src/agent/src/mount.rs @@ -7,7 +7,6 @@ use std::collections::HashMap; use std::ffi::CString; use std::fs; use std::io; -use std::iter::FromIterator; use std::os::unix::fs::PermissionsExt; use std::path::Path; @@ -396,7 +395,7 @@ fn mount_storage(logger: &Logger, storage: &Storage) -> Result<()> { } let options_vec = storage.options.to_vec(); - let options_vec = Vec::from_iter(options_vec.iter().map(String::as_str)); + let options_vec = options_vec.iter().map(String::as_str).collect(); let (flags, options) = parse_mount_flags_and_options(options_vec); info!(logger, "mounting storage"; @@ -538,7 +537,7 @@ pub fn get_mount_fs_type(mount_point: &str) -> Result { // get_mount_fs_type_from_file returns the FS type corresponding to the passed mount point and // any error ecountered. pub fn get_mount_fs_type_from_file(mount_file: &str, mount_point: &str) -> Result { - if mount_point == "" { + if mount_point.is_empty() { return Err(anyhow!("Invalid mount point {}", mount_point)); } @@ -623,7 +622,7 @@ pub fn get_cgroup_mounts( } } - if fields[0] == "" { + if fields[0].is_empty() { continue; } @@ -830,7 +829,7 @@ mod tests { let src_filename: String; let dest_filename: String; - if d.src != "" { + if !d.src.is_empty() { src = dir.path().join(d.src.to_string()); src_filename = src .to_str() @@ -840,7 +839,7 @@ mod tests { src_filename = "".to_owned(); } - if d.dest != "" { + if !d.dest.is_empty() { dest = dir.path().join(d.dest.to_string()); dest_filename = dest .to_str() @@ -852,7 +851,7 @@ mod tests { // Create the mount directories for d in [src_filename.clone(), dest_filename.clone()].iter() { - if d == "" { + if d.is_empty() { continue; } @@ -872,7 +871,7 @@ mod tests { let msg = format!("{}: result: {:?}", msg, result); - if d.error_contains == "" { + if d.error_contains.is_empty() { assert!(result.is_ok(), msg); // Cleanup @@ -990,7 +989,7 @@ mod tests { let msg = format!("{}: result: {:?}", msg, result); - if d.error_contains == "" { + if d.error_contains.is_empty() { assert!(result.is_ok(), msg); continue; } @@ -1098,7 +1097,7 @@ mod tests { // add more details if an assertion fails let msg = format!("{}: result: {:?}", msg, result); - if d.error_contains == "" { + if d.error_contains.is_empty() { let fs_type = result.unwrap(); assert!(d.fs_type == fs_type, msg); @@ -1255,7 +1254,7 @@ mod tests { let result = get_cgroup_mounts(&logger, filename, false); let msg = format!("{}: result: {:?}", msg, result); - if d.error_contains != "" { + if !d.error_contains.is_empty() { assert!(result.is_err(), msg); let error_msg = format!("{}", result.unwrap_err()); diff --git a/src/agent/src/namespace.rs b/src/agent/src/namespace.rs index 6e0d98828f..6ae22e12fa 100644 --- a/src/agent/src/namespace.rs +++ b/src/agent/src/namespace.rs @@ -57,7 +57,7 @@ impl Namespace { pub fn get_uts(mut self, hostname: &str) -> Self { self.ns_type = NamespaceType::UTS; - if hostname != "" { + if !hostname.is_empty() { self.hostname = Some(String::from(hostname)); } self diff --git a/src/agent/src/netlink.rs b/src/agent/src/netlink.rs index fe0db72963..039d83fb40 100644 --- a/src/agent/src/netlink.rs +++ b/src/agent/src/netlink.rs @@ -513,7 +513,7 @@ impl Handle { .as_ref() .map(|to| to.address.as_str()) // Extract address field .and_then(|addr| if addr.is_empty() { None } else { Some(addr) }) // Make sure it's not empty - .ok_or_else(|| nix::Error::Sys(nix::errno::Errno::EINVAL))?; + .ok_or(nix::Error::Sys(nix::errno::Errno::EINVAL))?; let ip = IpAddr::from_str(&ip_address) .map_err(|e| anyhow!("Failed to parse IP {}: {:?}", ip_address, e))?; @@ -611,7 +611,7 @@ fn parse_mac_address(addr: &str) -> Result<[u8; 6]> { let v = u8::from_str_radix( split .next() - .ok_or_else(|| nix::Error::Sys(nix::errno::Errno::EINVAL))?, + .ok_or(nix::Error::Sys(nix::errno::Errno::EINVAL))?, 16, )?; Ok(v) diff --git a/src/agent/src/rpc.rs b/src/agent/src/rpc.rs index 05d7f77bf7..0af61a1f73 100644 --- a/src/agent/src/rpc.rs +++ b/src/agent/src/rpc.rs @@ -324,7 +324,7 @@ impl AgentService { "exec-id" => eid.clone(), ); - if eid == "" { + if eid.is_empty() { init = true; } @@ -1323,7 +1323,7 @@ fn find_process<'a>( .get_container(cid) .ok_or_else(|| anyhow!("Invalid container id"))?; - if init || eid == "" { + if init || eid.is_empty() { return ctr .processes .get_mut(&ctr.init_process_pid) @@ -1391,8 +1391,10 @@ fn update_container_namespaces( } } // update pid namespace - let mut pid_ns = LinuxNamespace::default(); - pid_ns.r#type = NSTYPEPID.to_string(); + let mut pid_ns = LinuxNamespace { + r#type: NSTYPEPID.to_string(), + ..Default::default() + }; // Use shared pid ns if useSandboxPidns has been set in either // the create_sandbox request or create_container request. @@ -1628,7 +1630,7 @@ fn cleanup_process(p: &mut Process) -> Result<()> { } fn load_kernel_module(module: &protocols::agent::KernelModule) -> Result<()> { - if module.name == "" { + if module.name.is_empty() { return Err(anyhow!("Kernel module name is empty")); } @@ -1683,10 +1685,12 @@ mod tests { #[test] fn test_load_kernel_module() { - let mut m = protocols::agent::KernelModule::default(); + let mut m = protocols::agent::KernelModule { + name: "module_not_exists".to_string(), + ..Default::default() + }; // case 1: module not exists - m.name = "module_not_exists".to_string(); let result = load_kernel_module(&m); assert!(result.is_err(), "load module should failed"); diff --git a/src/agent/src/sandbox.rs b/src/agent/src/sandbox.rs index 94b65f1d20..3f512d655d 100644 --- a/src/agent/src/sandbox.rs +++ b/src/agent/src/sandbox.rs @@ -627,13 +627,16 @@ mod tests { } fn create_dummy_opts() -> CreateOpts { - let mut root = Root::default(); - root.path = String::from("/"); + let root = Root { + path: String::from("/"), + ..Default::default() + }; - let linux = Linux::default(); - let mut spec = Spec::default(); - spec.root = Some(root); - spec.linux = Some(linux); + let spec = Spec { + linux: Some(Linux::default()), + root: Some(root), + ..Default::default() + }; CreateOpts { cgroup_name: "".to_string(), diff --git a/src/agent/src/uevent.rs b/src/agent/src/uevent.rs index 83b4c6a877..947442210a 100644 --- a/src/agent/src/uevent.rs +++ b/src/agent/src/uevent.rs @@ -58,7 +58,7 @@ impl Uevent { self.devpath.starts_with(pci_root_bus_path.as_str()) || self.devpath.starts_with(ACPI_DEV_PATH) // NVDIMM/PMEM devices } - && self.devname != "" + && !self.devname.is_empty() } async fn handle_block_add_event(&self, sandbox: &Arc>) {