diff --git a/src/agent/rustjail/src/capabilities.rs b/src/agent/rustjail/src/capabilities.rs index 91f6ea823c..1370af7e52 100644 --- a/src/agent/rustjail/src/capabilities.rs +++ b/src/agent/rustjail/src/capabilities.rs @@ -6,8 +6,6 @@ // looks like we can use caps to manipulate capabilities // conveniently, use caps to do it directly.. maybe -use lazy_static; - use crate::log_child; use crate::sync::write_count; use anyhow::{anyhow, Result}; diff --git a/src/agent/rustjail/src/cgroups/fs/mod.rs b/src/agent/rustjail/src/cgroups/fs/mod.rs index c7fcee8c89..880a7ece1d 100644 --- a/src/agent/rustjail/src/cgroups/fs/mod.rs +++ b/src/agent/rustjail/src/cgroups/fs/mod.rs @@ -21,7 +21,6 @@ use cgroups::{ use crate::cgroups::Manager as CgroupManager; use crate::container::DEFAULT_DEVICES; use anyhow::{anyhow, Context, Result}; -use lazy_static; use libc::{self, pid_t}; use nix::errno::Errno; use oci::{ @@ -46,18 +45,19 @@ macro_rules! sl { } pub fn load_or_create<'a>(h: Box<&'a dyn cgroups::Hierarchy>, path: &str) -> Cgroup<'a> { - let valid_path = path.trim_start_matches("/").to_string(); + let valid_path = path.trim_start_matches('/').to_string(); let cg = load(h.clone(), &valid_path); - if cg.is_none() { - info!(sl!(), "create new cgroup: {}", &valid_path); - cgroups::Cgroup::new(h, valid_path.as_str()) - } else { - cg.unwrap() + match cg { + Some(cg) => cg, + None => { + info!(sl!(), "create new cgroup: {}", &valid_path); + cgroups::Cgroup::new(h, valid_path.as_str()) + } } } pub fn load<'a>(h: Box<&'a dyn cgroups::Hierarchy>, path: &str) -> Option> { - let valid_path = path.trim_start_matches("/").to_string(); + let valid_path = path.trim_start_matches('/').to_string(); let cg = cgroups::Cgroup::load(h, valid_path.as_str()); let cpu_controller: &CpuController = cg.controller_of().unwrap(); if cpu_controller.exists() { @@ -210,8 +210,8 @@ impl CgroupManager for Manager { let h = cgroups::hierarchies::auto(); let h = Box::new(&*h); let cg = load(h, &self.cpath); - if cg.is_some() { - cg.unwrap().delete(); + if let Some(cg) = cg { + cg.delete(); } Ok(()) } @@ -259,7 +259,7 @@ fn set_network_resources( fn set_devices_resources( _cg: &cgroups::Cgroup, - device_resources: &Vec, + device_resources: &[LinuxDeviceCgroup], res: &mut cgroups::Resources, ) -> Result<()> { info!(sl!(), "cgroup manager set devices"); @@ -291,7 +291,7 @@ fn set_devices_resources( fn set_hugepages_resources( _cg: &cgroups::Cgroup, - hugepage_limits: &Vec, + hugepage_limits: &[LinuxHugepageLimit], res: &mut cgroups::Resources, ) -> Result<()> { info!(sl!(), "cgroup manager set hugepage"); @@ -453,7 +453,7 @@ fn set_pids_resources(cg: &cgroups::Cgroup, pids: &LinuxPids) -> Result<()> { } fn build_blk_io_device_throttle_resource( - input: &Vec, + input: &[oci::LinuxThrottleDevice], ) -> Vec { let mut blk_io_device_throttle_resources = vec![]; for d in input.iter() { @@ -685,7 +685,7 @@ fn get_memory_stats(cg: &cgroups::Cgroup) -> SingularPtrField { // use_hierarchy let value = memory.use_hierarchy; - let use_hierarchy = if value == 1 { true } else { false }; + let use_hierarchy = value == 1; // gte memory datas let usage = SingularPtrField::some(MemoryData { @@ -739,13 +739,12 @@ fn get_pids_stats(cg: &cgroups::Cgroup) -> SingularPtrField { let current = pid_controller.get_pid_current().unwrap_or(0); let max = pid_controller.get_pid_max(); - let limit = if max.is_err() { - 0 - } else { - match max.unwrap() { + let limit = match max { + Err(_) => 0, + Ok(max) => match max { MaxValue::Value(v) => v, MaxValue::Max => 0, - } + }, } as u64; SingularPtrField::some(PidsStats { @@ -788,7 +787,7 @@ https://github.com/opencontainers/runc/blob/a5847db387ae28c0ca4ebe4beee1a76900c8 Total 0 */ -fn get_blkio_stat_blkiodata(blkiodata: &Vec) -> RepeatedField { +fn get_blkio_stat_blkiodata(blkiodata: &[BlkIoData]) -> RepeatedField { let mut m = RepeatedField::new(); if blkiodata.len() == 0 { return m; @@ -810,7 +809,7 @@ fn get_blkio_stat_blkiodata(blkiodata: &Vec) -> RepeatedField) -> RepeatedField { +fn get_blkio_stat_ioservice(services: &[IoService]) -> RepeatedField { let mut m = RepeatedField::new(); if services.len() == 0 { @@ -930,8 +929,8 @@ fn get_hugetlb_stats(cg: &cgroups::Cgroup) -> HashMap { h } -pub const PATHS: &'static str = "/proc/self/cgroup"; -pub const MOUNTS: &'static str = "/proc/self/mountinfo"; +pub const PATHS: &str = "/proc/self/cgroup"; +pub const MOUNTS: &str = "/proc/self/mountinfo"; pub fn get_paths() -> Result> { let mut m = HashMap::new(); @@ -1056,7 +1055,7 @@ impl Manager { if i == 0 { break; } - i = i - 1; + i -= 1; let h = cgroups::hierarchies::auto(); let h = Box::new(&*h); diff --git a/src/agent/rustjail/src/cgroups/notifier.rs b/src/agent/rustjail/src/cgroups/notifier.rs index 10f9cb45f4..cbe03c9806 100644 --- a/src/agent/rustjail/src/cgroups/notifier.rs +++ b/src/agent/rustjail/src/cgroups/notifier.rs @@ -41,7 +41,7 @@ fn get_value_from_cgroup(path: &PathBuf, key: &str) -> Result { ); for line in content.lines() { - let arr: Vec<&str> = line.split(" ").collect(); + let arr: Vec<&str> = line.split(' ').collect(); if arr.len() == 2 && arr[0] == key { let r = arr[1].parse::()?; return Ok(r); diff --git a/src/agent/rustjail/src/container.rs b/src/agent/rustjail/src/container.rs index 7c166fd24c..db4a16bc28 100644 --- a/src/agent/rustjail/src/container.rs +++ b/src/agent/rustjail/src/container.rs @@ -4,12 +4,9 @@ // use anyhow::{anyhow, Context, Result}; -use dirs; -use lazy_static; use libc::pid_t; use oci::{Hook, Linux, LinuxNamespace, LinuxResources, POSIXRlimit, Spec}; use oci::{LinuxDevice, LinuxIDMapping}; -use serde_json; use std::clone::Clone; use std::ffi::{CStr, CString}; use std::fmt; @@ -43,7 +40,6 @@ use nix::sys::signal::{self, Signal}; use nix::sys::stat::{self, Mode}; use nix::unistd::{self, ForkResult, Gid, Pid, Uid}; -use libc; use protobuf::SingularPtrField; use oci::State as OCIState; @@ -54,9 +50,9 @@ use std::os::unix::io::FromRawFd; use slog::{info, o, Logger}; -const STATE_FILENAME: &'static str = "state.json"; -const EXEC_FIFO_FILENAME: &'static str = "exec.fifo"; -const VER_MARKER: &'static str = "1.2.5"; +const STATE_FILENAME: &str = "state.json"; +const EXEC_FIFO_FILENAME: &str = "exec.fifo"; +const VER_MARKER: &str = "1.2.5"; const PID_NS_PATH: &str = "/proc/self/ns/pid"; const INIT: &str = "INIT"; @@ -595,7 +591,7 @@ fn do_init_child(cwfd: RawFd) -> Result<()> { // setup the envs for e in env.iter() { - let v: Vec<&str> = e.splitn(2, "=").collect(); + let v: Vec<&str> = e.splitn(2, '=').collect(); if v.len() != 2 { continue; } @@ -731,7 +727,7 @@ impl BaseContainer for LinuxContainer { info!(logger, "enter container.start!"); let mut fifofd: RawFd = -1; if p.init { - if let Ok(_) = stat::stat(fifo_file.as_str()) { + if stat::stat(fifo_file.as_str()).is_ok() { return Err(anyhow!("exec fifo exists")); } unistd::mkfifo(fifo_file.as_str(), Mode::from_bits(0o622).unwrap())?; @@ -931,7 +927,7 @@ impl BaseContainer for LinuxContainer { .join() .map_err(|e| warn!(logger, "joining log handler {:?}", e)); info!(logger, "create process completed"); - return Ok(()); + Ok(()) } fn run(&mut self, p: Process) -> Result<()> { @@ -1164,11 +1160,9 @@ fn join_namespaces( } // apply cgroups - if p.init { - if res.is_some() { - info!(logger, "apply cgroups!"); - cm.set(res.unwrap(), false)?; - } + if p.init && res.is_some() { + info!(logger, "apply cgroups!"); + cm.set(res.unwrap(), false)?; } if res.is_some() { @@ -1464,7 +1458,7 @@ fn execute_hook(logger: &Logger, h: &Hook, st: &OCIState) -> Result<()> { } } - return Ok(()); + Ok(()) } ForkResult::Child => { @@ -1567,13 +1561,11 @@ fn execute_hook(logger: &Logger, h: &Hook, st: &OCIState) -> Result<()> { error } } + } else if let Ok(s) = rx.recv() { + s } else { - if let Ok(s) = rx.recv() { - s - } else { - let _ = signal::kill(Pid::from_raw(pid), Some(Signal::SIGKILL)); - -libc::EPIPE - } + let _ = signal::kill(Pid::from_raw(pid), Some(Signal::SIGKILL)); + -libc::EPIPE } }; diff --git a/src/agent/rustjail/src/mount.rs b/src/agent/rustjail/src/mount.rs index 1942fcc5b8..dc948a3f88 100644 --- a/src/agent/rustjail/src/mount.rs +++ b/src/agent/rustjail/src/mount.rs @@ -3,7 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 // -use anyhow::{anyhow, bail, Context, Error, Result}; +use anyhow::{anyhow, bail, Context, Result}; use libc::uid_t; use nix::errno::Errno; use nix::fcntl::{self, OFlag}; @@ -22,13 +22,11 @@ use std::os::unix::io::RawFd; use std::path::{Path, PathBuf}; use path_absolutize::*; -use scan_fmt; use std::fs::File; use std::io::{BufRead, BufReader}; use crate::container::DEFAULT_DEVICES; use crate::sync::write_count; -use lazy_static; use std::string::ToString; use crate::log_child; @@ -50,7 +48,7 @@ pub struct Info { vfs_opts: String, } -const MOUNTINFOFORMAT: &'static str = "{d} {d} {d}:{d} {} {} {} {}"; +const MOUNTINFOFORMAT: &str = "{d} {d} {d}:{d} {} {} {} {}"; const PROC_PATH: &str = "/proc"; // since libc didn't defined this const for musl, thus redefined it here. @@ -153,7 +151,7 @@ pub fn init_rootfs( let linux = &spec .linux .as_ref() - .ok_or::(anyhow!("Could not get linux configuration from spec"))?; + .ok_or_else(|| anyhow!("Could not get linux configuration from spec"))?; let mut flags = MsFlags::MS_REC; match PROPAGATION.get(&linux.rootfs_propagation.as_str()) { @@ -164,14 +162,14 @@ pub fn init_rootfs( let root = spec .root .as_ref() - .ok_or(anyhow!("Could not get rootfs path from spec")) + .ok_or_else(|| anyhow!("Could not get rootfs path from spec")) .and_then(|r| { fs::canonicalize(r.path.as_str()).context("Could not canonicalize rootfs path") })?; let rootfs = (*root) .to_str() - .ok_or(anyhow!("Could not convert rootfs path to string"))?; + .ok_or_else(|| anyhow!("Could not convert rootfs path to string"))?; mount(None::<&str>, "/", None::<&str>, flags, None::<&str>)?; @@ -187,7 +185,7 @@ pub fn init_rootfs( for m in &spec.mounts { let (mut flags, data) = parse_mount(&m); - if !m.destination.starts_with("/") || m.destination.contains("..") { + if !m.destination.starts_with('/') || m.destination.contains("..") { return Err(anyhow!( "the mount destination {} is invalid", m.destination @@ -273,9 +271,9 @@ fn check_proc_mount(m: &Mount) -> Result<()> { // only allow a mount on-top of proc if it's source is "proc" unsafe { let mut stats = MaybeUninit::::uninit(); - if let Ok(_) = m - .source + if m.source .with_nix_path(|path| libc::statfs(path.as_ptr(), stats.as_mut_ptr())) + .is_ok() { if stats.assume_init().f_type == PROC_SUPER_MAGIC { return Ok(()); @@ -298,7 +296,7 @@ fn check_proc_mount(m: &Mount) -> Result<()> { ))); } - return Ok(()); + Ok(()) } fn mount_cgroups_v2(cfd_log: RawFd, m: &Mount, rootfs: &str, flags: MsFlags) -> Result<()> { @@ -586,15 +584,14 @@ pub fn ms_move_root(rootfs: &str) -> Result { let abs_root_buf = root_path.absolutize()?; let abs_root = abs_root_buf .to_str() - .ok_or::(anyhow!("failed to parse {} to absolute path", rootfs))?; + .ok_or_else(|| anyhow!("failed to parse {} to absolute path", rootfs))?; for info in mount_infos.iter() { let mount_point = Path::new(&info.mount_point); let abs_mount_buf = mount_point.absolutize()?; - let abs_mount_point = abs_mount_buf.to_str().ok_or::(anyhow!( - "failed to parse {} to absolute path", - info.mount_point - ))?; + let abs_mount_point = abs_mount_buf + .to_str() + .ok_or_else(|| anyhow!("failed to parse {} to absolute path", info.mount_point))?; let abs_mount_point_string = String::from(abs_mount_point); // Umount every syfs and proc file systems, except those under the container rootfs @@ -755,7 +752,7 @@ fn mount_from( Ok(()) } -static SYMLINKS: &'static [(&'static str, &'static str)] = &[ +static SYMLINKS: &[(&str, &str)] = &[ ("/proc/self/fd", "dev/fd"), ("/proc/self/fd/0", "dev/stdin"), ("/proc/self/fd/1", "dev/stdout"), @@ -888,7 +885,7 @@ pub fn finish_rootfs(cfd_log: RawFd, spec: &Spec) -> Result<()> { } fn mask_path(path: &str) -> Result<()> { - if !path.starts_with("/") || path.contains("..") { + if !path.starts_with('/') || path.contains("..") { return Err(nix::Error::Sys(Errno::EINVAL).into()); } @@ -917,7 +914,7 @@ fn mask_path(path: &str) -> Result<()> { } fn readonly_path(path: &str) -> Result<()> { - if !path.starts_with("/") || path.contains("..") { + if !path.starts_with('/') || path.contains("..") { return Err(nix::Error::Sys(Errno::EINVAL).into()); } diff --git a/src/agent/rustjail/src/sync.rs b/src/agent/rustjail/src/sync.rs index 9e98b0ad76..db2929f89f 100644 --- a/src/agent/rustjail/src/sync.rs +++ b/src/agent/rustjail/src/sync.rs @@ -88,14 +88,14 @@ pub fn read_sync(fd: RawFd) -> Result> { let buf_array: [u8; MSG_SIZE] = [buf[0], buf[1], buf[2], buf[3]]; let msg: i32 = i32::from_be_bytes(buf_array); match msg { - SYNC_SUCCESS => return Ok(Vec::new()), + SYNC_SUCCESS => Ok(Vec::new()), SYNC_DATA => { let buf = read_count(fd, MSG_SIZE)?; let buf_array: [u8; MSG_SIZE] = [buf[0], buf[1], buf[2], buf[3]]; let msg_length: i32 = i32::from_be_bytes(buf_array); let data_buf = read_count(fd, msg_length as usize)?; - return Ok(data_buf); + Ok(data_buf) } SYNC_FAILED => { let mut error_buf = vec![]; @@ -119,9 +119,9 @@ pub fn read_sync(fd: RawFd) -> Result> { } }; - return Err(anyhow!(error_str)); + Err(anyhow!(error_str)) } - _ => return Err(anyhow!("error in receive sync message")), + _ => Err(anyhow!("error in receive sync message")), } } diff --git a/src/agent/rustjail/src/validator.rs b/src/agent/rustjail/src/validator.rs index 4e3ce43182..abe0124b96 100644 --- a/src/agent/rustjail/src/validator.rs +++ b/src/agent/rustjail/src/validator.rs @@ -5,13 +5,12 @@ use crate::container::Config; use anyhow::{anyhow, Result}; -use lazy_static; use nix::errno::Errno; use oci::{LinuxIDMapping, LinuxNamespace, Spec}; use std::collections::HashMap; use std::path::{Component, PathBuf}; -fn contain_namespace(nses: &Vec, key: &str) -> bool { +fn contain_namespace(nses: &[LinuxNamespace], key: &str) -> bool { for ns in nses { if ns.r#type.as_str() == key { return true; @@ -21,7 +20,7 @@ fn contain_namespace(nses: &Vec, key: &str) -> bool { false } -fn get_namespace_path(nses: &Vec, key: &str) -> Result { +fn get_namespace_path(nses: &[LinuxNamespace], key: &str) -> Result { for ns in nses { if ns.r#type.as_str() == key { return Ok(ns.path.clone()); @@ -41,10 +40,8 @@ fn rootfs(root: &str) -> Result<()> { // symbolic link? ..? let mut stack: Vec = Vec::new(); for c in path.components() { - if stack.is_empty() { - if c == Component::RootDir || c == Component::ParentDir { - continue; - } + if stack.is_empty() && (c == Component::RootDir || c == Component::ParentDir) { + continue; } if c == Component::ParentDir { @@ -74,7 +71,7 @@ fn network(_oci: &Spec) -> Result<()> { } fn hostname(oci: &Spec) -> Result<()> { - if oci.hostname.is_empty() || oci.hostname == "".to_string() { + if oci.hostname.is_empty() || oci.hostname == "" { return Ok(()); } @@ -104,7 +101,7 @@ fn security(oci: &Spec) -> Result<()> { Ok(()) } -fn idmapping(maps: &Vec) -> Result<()> { +fn idmapping(maps: &[LinuxIDMapping]) -> Result<()> { for map in maps { if map.size > 0 { return Ok(()); @@ -197,7 +194,7 @@ fn sysctl(oci: &Spec) -> Result<()> { } let net = get_namespace_path(&linux.namespaces, "network")?; - if net.is_empty() || net == "".to_string() { + if net.is_empty() || net == "" { continue; } @@ -233,7 +230,7 @@ fn rootless_euid_mapping(oci: &Spec) -> Result<()> { Ok(()) } -fn has_idmapping(maps: &Vec, id: u32) -> bool { +fn has_idmapping(maps: &[LinuxIDMapping], id: u32) -> bool { for map in maps { if id >= map.container_id && id < map.container_id + map.size { return true; @@ -256,16 +253,12 @@ fn rootless_euid_mount(oci: &Spec) -> Result<()> { let id = fields[1].trim().parse::()?; - if opt.starts_with("uid=") { - if !has_idmapping(&linux.uid_mappings, id) { - return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); - } + if opt.starts_with("uid=") && !has_idmapping(&linux.uid_mappings, id) { + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } - if opt.starts_with("gid=") { - if !has_idmapping(&linux.gid_mappings, id) { - return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); - } + if opt.starts_with("gid=") && !has_idmapping(&linux.gid_mappings, id) { + return Err(anyhow!(nix::Error::from_errno(Errno::EINVAL))); } } }