Merge pull request #1701 from dgibson/clippy

Assorted clippy fixes for Rust agent
This commit is contained in:
David Gibson 2021-04-22 20:36:49 +10:00 committed by GitHub
commit e91591fff2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 292 additions and 337 deletions

View File

@ -58,7 +58,7 @@ pub struct Spec {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub windows: Option<Windows<String>>, pub windows: Option<Windows<String>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub vm: Option<VM>, pub vm: Option<Vm>,
} }
impl Spec { impl Spec {
@ -71,7 +71,7 @@ impl Spec {
} }
} }
pub type LinuxRlimit = POSIXRlimit; pub type LinuxRlimit = PosixRlimit;
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct Process { pub struct Process {
@ -93,7 +93,7 @@ pub struct Process {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub capabilities: Option<LinuxCapabilities>, pub capabilities: Option<LinuxCapabilities>,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub rlimits: Vec<POSIXRlimit>, pub rlimits: Vec<PosixRlimit>,
#[serde(default, rename = "noNewPrivileges")] #[serde(default, rename = "noNewPrivileges")]
pub no_new_privileges: bool, pub no_new_privileges: bool,
#[serde( #[serde(
@ -199,9 +199,9 @@ pub struct Hooks {
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct Linux { pub struct Linux {
#[serde(default, rename = "uidMappings", skip_serializing_if = "Vec::is_empty")] #[serde(default, rename = "uidMappings", skip_serializing_if = "Vec::is_empty")]
pub uid_mappings: Vec<LinuxIDMapping>, pub uid_mappings: Vec<LinuxIdMapping>,
#[serde(default, rename = "gidMappings", skip_serializing_if = "Vec::is_empty")] #[serde(default, rename = "gidMappings", skip_serializing_if = "Vec::is_empty")]
pub gid_mappings: Vec<LinuxIDMapping>, pub gid_mappings: Vec<LinuxIdMapping>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")] #[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub sysctl: HashMap<String, String>, pub sysctl: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
@ -261,7 +261,7 @@ pub const UTSNAMESPACE: &str = "uts";
pub const CGROUPNAMESPACE: &str = "cgroup"; pub const CGROUPNAMESPACE: &str = "cgroup";
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct LinuxIDMapping { pub struct LinuxIdMapping {
#[serde(default, rename = "containerID")] #[serde(default, rename = "containerID")]
pub container_id: u32, pub container_id: u32,
#[serde(default, rename = "hostID")] #[serde(default, rename = "hostID")]
@ -271,7 +271,7 @@ pub struct LinuxIDMapping {
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct POSIXRlimit { pub struct PosixRlimit {
#[serde(default)] #[serde(default)]
pub r#type: String, pub r#type: String,
#[serde(default)] #[serde(default)]
@ -297,7 +297,7 @@ pub struct LinuxInterfacePriority {
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct LinuxBlockIODevice { pub struct LinuxBlockIoDevice {
#[serde(default)] #[serde(default)]
pub major: i64, pub major: i64,
#[serde(default)] #[serde(default)]
@ -307,7 +307,7 @@ pub struct LinuxBlockIODevice {
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct LinuxWeightDevice { pub struct LinuxWeightDevice {
#[serde(flatten)] #[serde(flatten)]
pub blk: LinuxBlockIODevice, pub blk: LinuxBlockIoDevice,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub weight: Option<u16>, pub weight: Option<u16>,
#[serde( #[serde(
@ -321,13 +321,13 @@ pub struct LinuxWeightDevice {
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct LinuxThrottleDevice { pub struct LinuxThrottleDevice {
#[serde(flatten)] #[serde(flatten)]
pub blk: LinuxBlockIODevice, pub blk: LinuxBlockIoDevice,
#[serde(default)] #[serde(default)]
pub rate: u64, pub rate: u64,
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct LinuxBlockIO { pub struct LinuxBlockIo {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub weight: Option<u16>, pub weight: Option<u16>,
#[serde( #[serde(
@ -391,7 +391,7 @@ pub struct LinuxMemory {
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct LinuxCPU { pub struct LinuxCpu {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub shares: Option<u64>, pub shares: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
@ -453,11 +453,11 @@ pub struct LinuxResources {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub memory: Option<LinuxMemory>, pub memory: Option<LinuxMemory>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu: Option<LinuxCPU>, pub cpu: Option<LinuxCpu>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub pids: Option<LinuxPids>, pub pids: Option<LinuxPids>,
#[serde(skip_serializing_if = "Option::is_none", rename = "blockIO")] #[serde(skip_serializing_if = "Option::is_none", rename = "blockIO")]
pub block_io: Option<LinuxBlockIO>, pub block_io: Option<LinuxBlockIo>,
#[serde( #[serde(
default, default,
skip_serializing_if = "Vec::is_empty", skip_serializing_if = "Vec::is_empty",
@ -517,7 +517,7 @@ pub struct Solaris {
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub anet: Vec<SolarisAnet>, pub anet: Vec<SolarisAnet>,
#[serde(default, skip_serializing_if = "Option::is_none", rename = "cappedCPU")] #[serde(default, skip_serializing_if = "Option::is_none", rename = "cappedCPU")]
pub capped_cpu: Option<SolarisCappedCPU>, pub capped_cpu: Option<SolarisCappedCpu>,
#[serde( #[serde(
default, default,
skip_serializing_if = "Option::is_none", skip_serializing_if = "Option::is_none",
@ -527,7 +527,7 @@ pub struct Solaris {
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct SolarisCappedCPU { pub struct SolarisCappedCpu {
#[serde(default, skip_serializing_if = "String::is_empty")] #[serde(default, skip_serializing_if = "String::is_empty")]
pub ncpus: String, pub ncpus: String,
} }
@ -605,7 +605,7 @@ pub struct WindowsResources {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub memory: Option<WindowsMemoryResources>, pub memory: Option<WindowsMemoryResources>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub cpu: Option<WindowsCPUResources>, pub cpu: Option<WindowsCpuResources>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub storage: Option<WindowsStorageResources>, pub storage: Option<WindowsStorageResources>,
} }
@ -617,7 +617,7 @@ pub struct WindowsMemoryResources {
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct WindowsCPUResources { pub struct WindowsCpuResources {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub count: Option<u64>, pub count: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
@ -675,14 +675,14 @@ pub struct WindowsHyperV {
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct VM { pub struct Vm {
pub hypervisor: VMHypervisor, pub hypervisor: VmHypervisor,
pub kernel: VMKernel, pub kernel: VmKernel,
pub image: VMImage, pub image: VmImage,
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct VMHypervisor { pub struct VmHypervisor {
#[serde(default)] #[serde(default)]
pub path: String, pub path: String,
#[serde(default, skip_serializing_if = "String::is_empty")] #[serde(default, skip_serializing_if = "String::is_empty")]
@ -690,7 +690,7 @@ pub struct VMHypervisor {
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct VMKernel { pub struct VmKernel {
#[serde(default)] #[serde(default)]
pub path: String, pub path: String,
#[serde(default, skip_serializing_if = "String::is_empty")] #[serde(default, skip_serializing_if = "String::is_empty")]
@ -700,7 +700,7 @@ pub struct VMKernel {
} }
#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct VMImage { pub struct VmImage {
#[serde(default)] #[serde(default)]
pub path: String, pub path: String,
#[serde(default)] #[serde(default)]
@ -801,11 +801,11 @@ pub struct LinuxIntelRdt {
#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq)] #[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum ContainerState { pub enum ContainerState {
CREATING, Creating,
CREATED, Created,
RUNNING, Running,
STOPPED, Stopped,
PAUSED, Paused,
} }
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
@ -846,7 +846,7 @@ mod tests {
let expected = State { let expected = State {
version: "0.2.0".to_string(), version: "0.2.0".to_string(),
id: "oci-container1".to_string(), id: "oci-container1".to_string(),
status: ContainerState::RUNNING, status: ContainerState::Running,
pid: 4422, pid: 4422,
bundle: "/containers/redis".to_string(), bundle: "/containers/redis".to_string(),
annotations: [("myKey".to_string(), "myValue".to_string())] annotations: [("myKey".to_string(), "myValue".to_string())]
@ -1271,12 +1271,12 @@ mod tests {
ambient: vec!["CAP_NET_BIND_SERVICE".to_string()], ambient: vec!["CAP_NET_BIND_SERVICE".to_string()],
}), }),
rlimits: vec![ rlimits: vec![
crate::POSIXRlimit { crate::PosixRlimit {
r#type: "RLIMIT_CORE".to_string(), r#type: "RLIMIT_CORE".to_string(),
hard: 1024, hard: 1024,
soft: 1024, soft: 1024,
}, },
crate::POSIXRlimit { crate::PosixRlimit {
r#type: "RLIMIT_NOFILE".to_string(), r#type: "RLIMIT_NOFILE".to_string(),
hard: 1024, hard: 1024,
soft: 1024, soft: 1024,
@ -1408,12 +1408,12 @@ mod tests {
.cloned() .cloned()
.collect(), .collect(),
linux: Some(crate::Linux { linux: Some(crate::Linux {
uid_mappings: vec![crate::LinuxIDMapping { uid_mappings: vec![crate::LinuxIdMapping {
container_id: 0, container_id: 0,
host_id: 1000, host_id: 1000,
size: 32000, size: 32000,
}], }],
gid_mappings: vec![crate::LinuxIDMapping { gid_mappings: vec![crate::LinuxIdMapping {
container_id: 0, container_id: 0,
host_id: 1000, host_id: 1000,
size: 32000, size: 32000,
@ -1458,7 +1458,7 @@ mod tests {
swappiness: Some(0), swappiness: Some(0),
disable_oom_killer: Some(false), disable_oom_killer: Some(false),
}), }),
cpu: Some(crate::LinuxCPU { cpu: Some(crate::LinuxCpu {
shares: Some(1024), shares: Some(1024),
quota: Some(1000000), quota: Some(1000000),
period: Some(500000), period: Some(500000),
@ -1468,17 +1468,17 @@ mod tests {
mems: "0-7".to_string(), mems: "0-7".to_string(),
}), }),
pids: Some(crate::LinuxPids { limit: 32771 }), pids: Some(crate::LinuxPids { limit: 32771 }),
block_io: Some(crate::LinuxBlockIO { block_io: Some(crate::LinuxBlockIo {
weight: Some(10), weight: Some(10),
leaf_weight: Some(10), leaf_weight: Some(10),
weight_device: vec![ weight_device: vec![
crate::LinuxWeightDevice { crate::LinuxWeightDevice {
blk: crate::LinuxBlockIODevice { major: 8, minor: 0 }, blk: crate::LinuxBlockIoDevice { major: 8, minor: 0 },
weight: Some(500), weight: Some(500),
leaf_weight: Some(300), leaf_weight: Some(300),
}, },
crate::LinuxWeightDevice { crate::LinuxWeightDevice {
blk: crate::LinuxBlockIODevice { blk: crate::LinuxBlockIoDevice {
major: 8, major: 8,
minor: 16, minor: 16,
}, },
@ -1487,13 +1487,13 @@ mod tests {
}, },
], ],
throttle_read_bps_device: vec![crate::LinuxThrottleDevice { throttle_read_bps_device: vec![crate::LinuxThrottleDevice {
blk: crate::LinuxBlockIODevice { major: 8, minor: 0 }, blk: crate::LinuxBlockIoDevice { major: 8, minor: 0 },
rate: 600, rate: 600,
}], }],
throttle_write_bps_device: vec![], throttle_write_bps_device: vec![],
throttle_read_iops_device: vec![], throttle_read_iops_device: vec![],
throttle_write_iops_device: vec![crate::LinuxThrottleDevice { throttle_write_iops_device: vec![crate::LinuxThrottleDevice {
blk: crate::LinuxBlockIODevice { blk: crate::LinuxBlockIoDevice {
major: 8, major: 8,
minor: 16, minor: 16,
}, },

View File

@ -24,7 +24,7 @@ use anyhow::{anyhow, Context, Result};
use libc::{self, pid_t}; use libc::{self, pid_t};
use nix::errno::Errno; use nix::errno::Errno;
use oci::{ use oci::{
LinuxBlockIO, LinuxCPU, LinuxDevice, LinuxDeviceCgroup, LinuxHugepageLimit, LinuxMemory, LinuxBlockIo, LinuxCpu, LinuxDevice, LinuxDeviceCgroup, LinuxHugepageLimit, LinuxMemory,
LinuxNetwork, LinuxPids, LinuxResources, LinuxNetwork, LinuxPids, LinuxResources,
}; };
@ -272,7 +272,7 @@ fn set_hugepages_resources(
fn set_block_io_resources( fn set_block_io_resources(
_cg: &cgroups::Cgroup, _cg: &cgroups::Cgroup,
blkio: &LinuxBlockIO, blkio: &LinuxBlockIo,
res: &mut cgroups::Resources, res: &mut cgroups::Resources,
) { ) {
info!(sl!(), "cgroup manager set block io"); info!(sl!(), "cgroup manager set block io");
@ -302,7 +302,7 @@ fn set_block_io_resources(
build_blk_io_device_throttle_resource(&blkio.throttle_write_iops_device); build_blk_io_device_throttle_resource(&blkio.throttle_write_iops_device);
} }
fn set_cpu_resources(cg: &cgroups::Cgroup, cpu: &LinuxCPU) -> Result<()> { fn set_cpu_resources(cg: &cgroups::Cgroup, cpu: &LinuxCpu) -> Result<()> {
info!(sl!(), "cgroup manager set cpu"); info!(sl!(), "cgroup manager set cpu");
let cpuset_controller: &CpuSetController = cg.controller_of().unwrap(); let cpuset_controller: &CpuSetController = cg.controller_of().unwrap();
@ -489,63 +489,61 @@ lazy_static! {
}; };
pub static ref DEFAULT_ALLOWED_DEVICES: Vec<LinuxDeviceCgroup> = { pub static ref DEFAULT_ALLOWED_DEVICES: Vec<LinuxDeviceCgroup> = {
let mut v = Vec::new(); vec![
// all mknod to all char devices
LinuxDeviceCgroup {
allow: true,
r#type: "c".to_string(),
major: Some(WILDCARD),
minor: Some(WILDCARD),
access: "m".to_string(),
},
// all mknod to all char devices // all mknod to all block devices
v.push(LinuxDeviceCgroup { LinuxDeviceCgroup {
allow: true, allow: true,
r#type: "c".to_string(), r#type: "b".to_string(),
major: Some(WILDCARD), major: Some(WILDCARD),
minor: Some(WILDCARD), minor: Some(WILDCARD),
access: "m".to_string(), access: "m".to_string(),
}); },
// all mknod to all block devices // all read/write/mknod to char device /dev/console
v.push(LinuxDeviceCgroup { LinuxDeviceCgroup {
allow: true, allow: true,
r#type: "b".to_string(), r#type: "c".to_string(),
major: Some(WILDCARD), major: Some(5),
minor: Some(WILDCARD), minor: Some(1),
access: "m".to_string(), access: "rwm".to_string(),
}); },
// all read/write/mknod to char device /dev/console // all read/write/mknod to char device /dev/pts/<N>
v.push(LinuxDeviceCgroup { LinuxDeviceCgroup {
allow: true, allow: true,
r#type: "c".to_string(), r#type: "c".to_string(),
major: Some(5), major: Some(136),
minor: Some(1), minor: Some(WILDCARD),
access: "rwm".to_string(), access: "rwm".to_string(),
}); },
// all read/write/mknod to char device /dev/pts/<N> // all read/write/mknod to char device /dev/ptmx
v.push(LinuxDeviceCgroup { LinuxDeviceCgroup {
allow: true, allow: true,
r#type: "c".to_string(), r#type: "c".to_string(),
major: Some(136), major: Some(5),
minor: Some(WILDCARD), minor: Some(2),
access: "rwm".to_string(), access: "rwm".to_string(),
}); },
// all read/write/mknod to char device /dev/ptmx // all read/write/mknod to char device /dev/net/tun
v.push(LinuxDeviceCgroup { LinuxDeviceCgroup {
allow: true, allow: true,
r#type: "c".to_string(), r#type: "c".to_string(),
major: Some(5), major: Some(10),
minor: Some(2), minor: Some(200),
access: "rwm".to_string(), access: "rwm".to_string(),
}); },
]
// all read/write/mknod to char device /dev/net/tun
v.push(LinuxDeviceCgroup {
allow: true,
r#type: "c".to_string(),
major: Some(10),
minor: Some(200),
access: "rwm".to_string(),
});
v
}; };
} }

View File

@ -8,7 +8,7 @@ use eventfd::{eventfd, EfdFlags};
use nix::sys::eventfd; use nix::sys::eventfd;
use std::fs::{self, File}; use std::fs::{self, File};
use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::io::{AsRawFd, FromRawFd};
use std::path::{Path, PathBuf}; use std::path::Path;
use crate::pipestream::PipeStream; use crate::pipestream::PipeStream;
use futures::StreamExt as _; use futures::StreamExt as _;
@ -35,7 +35,7 @@ pub async fn notify_oom(cid: &str, cg_dir: String) -> Result<Receiver<String>> {
// Flat keyed file format: // Flat keyed file format:
// KEY0 VAL0\n // KEY0 VAL0\n
// KEY1 VAL1\n // KEY1 VAL1\n
fn get_value_from_cgroup(path: &PathBuf, key: &str) -> Result<i64> { fn get_value_from_cgroup(path: &Path, key: &str) -> Result<i64> {
let content = fs::read_to_string(path)?; let content = fs::read_to_string(path)?;
info!( info!(
sl!(), sl!(),

View File

@ -5,7 +5,7 @@
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use libc::pid_t; use libc::pid_t;
use oci::{ContainerState, LinuxDevice, LinuxIDMapping}; use oci::{ContainerState, LinuxDevice, LinuxIdMapping};
use oci::{Hook, Linux, LinuxNamespace, LinuxResources, Spec}; use oci::{Hook, Linux, LinuxNamespace, LinuxResources, Spec};
use std::clone::Clone; use std::clone::Clone;
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
@ -83,8 +83,8 @@ pub struct ContainerStatus {
impl ContainerStatus { impl ContainerStatus {
fn new() -> Self { fn new() -> Self {
ContainerStatus { ContainerStatus {
pre_status: ContainerState::CREATED, pre_status: ContainerState::Created,
cur_status: ContainerState::CREATED, cur_status: ContainerState::Created,
} }
} }
@ -132,62 +132,62 @@ lazy_static! {
}; };
pub static ref DEFAULT_DEVICES: Vec<LinuxDevice> = { pub static ref DEFAULT_DEVICES: Vec<LinuxDevice> = {
let mut v = Vec::new(); vec![
v.push(LinuxDevice { LinuxDevice {
path: "/dev/null".to_string(), path: "/dev/null".to_string(),
r#type: "c".to_string(), r#type: "c".to_string(),
major: 1, major: 1,
minor: 3, minor: 3,
file_mode: Some(0o666), file_mode: Some(0o666),
uid: Some(0xffffffff), uid: Some(0xffffffff),
gid: Some(0xffffffff), gid: Some(0xffffffff),
}); },
v.push(LinuxDevice { LinuxDevice {
path: "/dev/zero".to_string(), path: "/dev/zero".to_string(),
r#type: "c".to_string(), r#type: "c".to_string(),
major: 1, major: 1,
minor: 5, minor: 5,
file_mode: Some(0o666), file_mode: Some(0o666),
uid: Some(0xffffffff), uid: Some(0xffffffff),
gid: Some(0xffffffff), gid: Some(0xffffffff),
}); },
v.push(LinuxDevice { LinuxDevice {
path: "/dev/full".to_string(), path: "/dev/full".to_string(),
r#type: String::from("c"), r#type: String::from("c"),
major: 1, major: 1,
minor: 7, minor: 7,
file_mode: Some(0o666), file_mode: Some(0o666),
uid: Some(0xffffffff), uid: Some(0xffffffff),
gid: Some(0xffffffff), gid: Some(0xffffffff),
}); },
v.push(LinuxDevice { LinuxDevice {
path: "/dev/tty".to_string(), path: "/dev/tty".to_string(),
r#type: "c".to_string(), r#type: "c".to_string(),
major: 5, major: 5,
minor: 0, minor: 0,
file_mode: Some(0o666), file_mode: Some(0o666),
uid: Some(0xffffffff), uid: Some(0xffffffff),
gid: Some(0xffffffff), gid: Some(0xffffffff),
}); },
v.push(LinuxDevice { LinuxDevice {
path: "/dev/urandom".to_string(), path: "/dev/urandom".to_string(),
r#type: "c".to_string(), r#type: "c".to_string(),
major: 1, major: 1,
minor: 9, minor: 9,
file_mode: Some(0o666), file_mode: Some(0o666),
uid: Some(0xffffffff), uid: Some(0xffffffff),
gid: Some(0xffffffff), gid: Some(0xffffffff),
}); },
v.push(LinuxDevice { LinuxDevice {
path: "/dev/random".to_string(), path: "/dev/random".to_string(),
r#type: "c".to_string(), r#type: "c".to_string(),
major: 1, major: 1,
minor: 8, minor: 8,
file_mode: Some(0o666), file_mode: Some(0o666),
uid: Some(0xffffffff), uid: Some(0xffffffff),
gid: Some(0xffffffff), gid: Some(0xffffffff),
}); },
v ]
}; };
} }
@ -255,7 +255,7 @@ pub struct State {
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SyncPC { pub struct SyncPc {
#[serde(default)] #[serde(default)]
pid: pid_t, pid: pid_t,
} }
@ -268,7 +268,7 @@ pub trait Container: BaseContainer {
impl Container for LinuxContainer { impl Container for LinuxContainer {
fn pause(&mut self) -> Result<()> { fn pause(&mut self) -> Result<()> {
let status = self.status(); let status = self.status();
if status != ContainerState::RUNNING && status != ContainerState::CREATED { if status != ContainerState::Running && status != ContainerState::Created {
return Err(anyhow!( return Err(anyhow!(
"failed to pause container: current status is: {:?}", "failed to pause container: current status is: {:?}",
status status
@ -281,7 +281,7 @@ impl Container for LinuxContainer {
.unwrap() .unwrap()
.freeze(FreezerState::Frozen)?; .freeze(FreezerState::Frozen)?;
self.status.transition(ContainerState::PAUSED); self.status.transition(ContainerState::Paused);
return Ok(()); return Ok(());
} }
Err(anyhow!("failed to get container's cgroup manager")) Err(anyhow!("failed to get container's cgroup manager"))
@ -289,7 +289,7 @@ impl Container for LinuxContainer {
fn resume(&mut self) -> Result<()> { fn resume(&mut self) -> Result<()> {
let status = self.status(); let status = self.status();
if status != ContainerState::PAUSED { if status != ContainerState::Paused {
return Err(anyhow!("container status is: {:?}, not paused", status)); return Err(anyhow!("container status is: {:?}, not paused", status));
} }
@ -299,7 +299,7 @@ impl Container for LinuxContainer {
.unwrap() .unwrap()
.freeze(FreezerState::Thawed)?; .freeze(FreezerState::Thawed)?;
self.status.transition(ContainerState::RUNNING); self.status.transition(ContainerState::Running);
return Ok(()); return Ok(());
} }
Err(anyhow!("failed to get container's cgroup manager")) Err(anyhow!("failed to get container's cgroup manager"))
@ -734,7 +734,7 @@ impl BaseContainer for LinuxContainer {
}; };
let status = self.status(); let status = self.status();
let pid = if status != ContainerState::STOPPED { let pid = if status != ContainerState::Stopped {
self.init_process_pid self.init_process_pid
} else { } else {
0 0
@ -984,7 +984,7 @@ impl BaseContainer for LinuxContainer {
if init { if init {
self.exec()?; self.exec()?;
self.status.transition(ContainerState::RUNNING); self.status.transition(ContainerState::Running);
} }
Ok(()) Ok(())
@ -1006,7 +1006,7 @@ impl BaseContainer for LinuxContainer {
} }
} }
self.status.transition(ContainerState::STOPPED); self.status.transition(ContainerState::Stopped);
mount::umount2( mount::umount2(
spec.root.as_ref().unwrap().path.as_str(), spec.root.as_ref().unwrap().path.as_str(),
MntFlags::MNT_DETACH, MntFlags::MNT_DETACH,
@ -1042,7 +1042,7 @@ impl BaseContainer for LinuxContainer {
.unwrap() .unwrap()
.as_secs(); .as_secs();
self.status.transition(ContainerState::RUNNING); self.status.transition(ContainerState::Running);
unistd::close(fd)?; unistd::close(fd)?;
Ok(()) Ok(())
@ -1289,7 +1289,7 @@ async fn join_namespaces(
Ok(()) Ok(())
} }
fn write_mappings(logger: &Logger, path: &str, maps: &[LinuxIDMapping]) -> Result<()> { fn write_mappings(logger: &Logger, path: &str, maps: &[LinuxIdMapping]) -> Result<()> {
let data = maps let data = maps
.iter() .iter()
.filter(|m| m.size != 0) .filter(|m| m.size != 0)
@ -1515,28 +1515,23 @@ async fn execute_hook(logger: &Logger, h: &Hook, st: &OCIState) -> Result<()> {
match child.wait().await { match child.wait().await {
Ok(exit) => { Ok(exit) => {
let code = match exit.code() { let code = exit
Some(c) => c, .code()
None => { .ok_or_else(|| anyhow!("hook exit status has no status code"))?;
return Err(anyhow!("hook exit status has no status code"));
}
};
if code == 0 { if code != 0 {
debug!(logger, "hook {} exit status is 0", &path);
return Ok(());
} else {
error!(logger, "hook {} exit status is {}", &path, code); error!(logger, "hook {} exit status is {}", &path, code);
return Err(anyhow!(nix::Error::from_errno(Errno::UnknownErrno))); return Err(anyhow!(nix::Error::from_errno(Errno::UnknownErrno)));
} }
debug!(logger, "hook {} exit status is 0", &path);
Ok(())
} }
Err(e) => { Err(e) => Err(anyhow!(
return Err(anyhow!( "wait child error: {} {}",
"wait child error: {} {}", e,
e, e.raw_os_error().unwrap()
e.raw_os_error().unwrap() )),
));
}
} }
}); });
@ -1575,7 +1570,7 @@ mod tests {
&OCIState { &OCIState {
version: "1.2.3".to_string(), version: "1.2.3".to_string(),
id: "321".to_string(), id: "321".to_string(),
status: ContainerState::RUNNING, status: ContainerState::Running,
pid: 2, pid: 2,
bundle: "".to_string(), bundle: "".to_string(),
annotations: Default::default(), annotations: Default::default(),
@ -1598,7 +1593,7 @@ mod tests {
&OCIState { &OCIState {
version: "1.2.3".to_string(), version: "1.2.3".to_string(),
id: "321".to_string(), id: "321".to_string(),
status: ContainerState::RUNNING, status: ContainerState::Running,
pid: 2, pid: 2,
bundle: "".to_string(), bundle: "".to_string(),
annotations: Default::default(), annotations: Default::default(),
@ -1617,10 +1612,10 @@ mod tests {
fn test_status_transtition() { fn test_status_transtition() {
let mut status = ContainerStatus::new(); let mut status = ContainerStatus::new();
let status_table: [ContainerState; 4] = [ let status_table: [ContainerState; 4] = [
ContainerState::CREATED, ContainerState::Created,
ContainerState::RUNNING, ContainerState::Running,
ContainerState::PAUSED, ContainerState::Paused,
ContainerState::STOPPED, ContainerState::Stopped,
]; ];
for s in status_table.iter() { for s in status_table.iter() {
@ -1757,7 +1752,7 @@ mod tests {
fn test_linuxcontainer_pause_bad_status() { fn test_linuxcontainer_pause_bad_status() {
let ret = new_linux_container_and_then(|mut c: LinuxContainer| { let ret = new_linux_container_and_then(|mut c: LinuxContainer| {
// Change state to pause, c.pause() should fail // Change state to pause, c.pause() should fail
c.status.transition(ContainerState::PAUSED); c.status.transition(ContainerState::Paused);
c.pause().map_err(|e| anyhow!(e)) c.pause().map_err(|e| anyhow!(e))
}); });
@ -1789,7 +1784,7 @@ mod tests {
fn test_linuxcontainer_resume_bad_status() { fn test_linuxcontainer_resume_bad_status() {
let ret = new_linux_container_and_then(|mut c: LinuxContainer| { let ret = new_linux_container_and_then(|mut c: LinuxContainer| {
// Change state to created, c.resume() should fail // Change state to created, c.resume() should fail
c.status.transition(ContainerState::CREATED); c.status.transition(ContainerState::Created);
c.resume().map_err(|e| anyhow!(e)) c.resume().map_err(|e| anyhow!(e))
}); });
@ -1800,7 +1795,7 @@ mod tests {
#[test] #[test]
fn test_linuxcontainer_resume_cgroupmgr_is_none() { fn test_linuxcontainer_resume_cgroupmgr_is_none() {
let ret = new_linux_container_and_then(|mut c: LinuxContainer| { let ret = new_linux_container_and_then(|mut c: LinuxContainer| {
c.status.transition(ContainerState::PAUSED); c.status.transition(ContainerState::Paused);
c.cgroup_manager = None; c.cgroup_manager = None;
c.resume().map_err(|e| anyhow!(e)) c.resume().map_err(|e| anyhow!(e))
}); });
@ -1813,7 +1808,7 @@ mod tests {
let ret = new_linux_container_and_then(|mut c: LinuxContainer| { let ret = new_linux_container_and_then(|mut c: LinuxContainer| {
c.cgroup_manager = FsManager::new("").ok(); c.cgroup_manager = FsManager::new("").ok();
// Change status to paused, this way we can resume it // Change status to paused, this way we can resume it
c.status.transition(ContainerState::PAUSED); c.status.transition(ContainerState::Paused);
c.resume().map_err(|e| anyhow!(e)) c.resume().map_err(|e| anyhow!(e))
}); });

View File

@ -58,24 +58,16 @@ pub mod validator;
// pub mod user; // pub mod user;
//pub mod intelrdt; //pub mod intelrdt;
// construtc ociSpec from grpcSpec, which is needed for hook
// execution. since hooks read config.json
use oci::{
Box as ociBox, Hooks as ociHooks, Linux as ociLinux, LinuxCapabilities as ociLinuxCapabilities,
Mount as ociMount, POSIXRlimit as ociPOSIXRlimit, Process as ociProcess, Root as ociRoot,
Spec as ociSpec, User as ociUser,
};
use protocols::oci::{
Hooks as grpcHooks, Linux as grpcLinux, Mount as grpcMount, Process as grpcProcess,
Root as grpcRoot, Spec as grpcSpec,
};
use std::collections::HashMap; use std::collections::HashMap;
pub fn process_grpc_to_oci(p: &grpcProcess) -> ociProcess { use protocols::oci as grpc;
// construct ociSpec from grpc::Spec, which is needed for hook
// execution. since hooks read config.json
pub fn process_grpc_to_oci(p: &grpc::Process) -> oci::Process {
let console_size = if p.ConsoleSize.is_some() { let console_size = if p.ConsoleSize.is_some() {
let c = p.ConsoleSize.as_ref().unwrap(); let c = p.ConsoleSize.as_ref().unwrap();
Some(ociBox { Some(oci::Box {
height: c.Height, height: c.Height,
width: c.Width, width: c.Width,
}) })
@ -85,14 +77,14 @@ pub fn process_grpc_to_oci(p: &grpcProcess) -> ociProcess {
let user = if p.User.is_some() { let user = if p.User.is_some() {
let u = p.User.as_ref().unwrap(); let u = p.User.as_ref().unwrap();
ociUser { oci::User {
uid: u.UID, uid: u.UID,
gid: u.GID, gid: u.GID,
additional_gids: u.AdditionalGids.clone(), additional_gids: u.AdditionalGids.clone(),
username: u.Username.clone(), username: u.Username.clone(),
} }
} else { } else {
ociUser { oci::User {
uid: 0, uid: 0,
gid: 0, gid: 0,
additional_gids: vec![], additional_gids: vec![],
@ -103,7 +95,7 @@ pub fn process_grpc_to_oci(p: &grpcProcess) -> ociProcess {
let capabilities = if p.Capabilities.is_some() { let capabilities = if p.Capabilities.is_some() {
let cap = p.Capabilities.as_ref().unwrap(); let cap = p.Capabilities.as_ref().unwrap();
Some(ociLinuxCapabilities { Some(oci::LinuxCapabilities {
bounding: cap.Bounding.clone().into_vec(), bounding: cap.Bounding.clone().into_vec(),
effective: cap.Effective.clone().into_vec(), effective: cap.Effective.clone().into_vec(),
inheritable: cap.Inheritable.clone().into_vec(), inheritable: cap.Inheritable.clone().into_vec(),
@ -117,7 +109,7 @@ pub fn process_grpc_to_oci(p: &grpcProcess) -> ociProcess {
let rlimits = { let rlimits = {
let mut r = Vec::new(); let mut r = Vec::new();
for lm in p.Rlimits.iter() { for lm in p.Rlimits.iter() {
r.push(ociPOSIXRlimit { r.push(oci::PosixRlimit {
r#type: lm.Type.clone(), r#type: lm.Type.clone(),
hard: lm.Hard, hard: lm.Hard,
soft: lm.Soft, soft: lm.Soft,
@ -126,7 +118,7 @@ pub fn process_grpc_to_oci(p: &grpcProcess) -> ociProcess {
r r
}; };
ociProcess { oci::Process {
terminal: p.Terminal, terminal: p.Terminal,
console_size, console_size,
user, user,
@ -142,15 +134,15 @@ pub fn process_grpc_to_oci(p: &grpcProcess) -> ociProcess {
} }
} }
fn root_grpc_to_oci(root: &grpcRoot) -> ociRoot { fn root_grpc_to_oci(root: &grpc::Root) -> oci::Root {
ociRoot { oci::Root {
path: root.Path.clone(), path: root.Path.clone(),
readonly: root.Readonly, readonly: root.Readonly,
} }
} }
fn mount_grpc_to_oci(m: &grpcMount) -> ociMount { fn mount_grpc_to_oci(m: &grpc::Mount) -> oci::Mount {
ociMount { oci::Mount {
destination: m.destination.clone(), destination: m.destination.clone(),
r#type: m.field_type.clone(), r#type: m.field_type.clone(),
source: m.source.clone(), source: m.source.clone(),
@ -158,13 +150,12 @@ fn mount_grpc_to_oci(m: &grpcMount) -> ociMount {
} }
} }
use oci::Hook as ociHook;
use protocols::oci::Hook as grpcHook; use protocols::oci::Hook as grpcHook;
fn hook_grpc_to_oci(h: &[grpcHook]) -> Vec<ociHook> { fn hook_grpc_to_oci(h: &[grpcHook]) -> Vec<oci::Hook> {
let mut r = Vec::new(); let mut r = Vec::new();
for e in h.iter() { for e in h.iter() {
r.push(ociHook { r.push(oci::Hook {
path: e.Path.clone(), path: e.Path.clone(),
args: e.Args.clone().into_vec(), args: e.Args.clone().into_vec(),
env: e.Env.clone().into_vec(), env: e.Env.clone().into_vec(),
@ -174,39 +165,29 @@ fn hook_grpc_to_oci(h: &[grpcHook]) -> Vec<ociHook> {
r r
} }
fn hooks_grpc_to_oci(h: &grpcHooks) -> ociHooks { fn hooks_grpc_to_oci(h: &grpc::Hooks) -> oci::Hooks {
let prestart = hook_grpc_to_oci(h.Prestart.as_ref()); let prestart = hook_grpc_to_oci(h.Prestart.as_ref());
let poststart = hook_grpc_to_oci(h.Poststart.as_ref()); let poststart = hook_grpc_to_oci(h.Poststart.as_ref());
let poststop = hook_grpc_to_oci(h.Poststop.as_ref()); let poststop = hook_grpc_to_oci(h.Poststop.as_ref());
ociHooks { oci::Hooks {
prestart, prestart,
poststart, poststart,
poststop, poststop,
} }
} }
use oci::{ fn idmap_grpc_to_oci(im: &grpc::LinuxIDMapping) -> oci::LinuxIdMapping {
LinuxDevice as ociLinuxDevice, LinuxIDMapping as ociLinuxIDMapping, oci::LinuxIdMapping {
LinuxIntelRdt as ociLinuxIntelRdt, LinuxNamespace as ociLinuxNamespace,
LinuxResources as ociLinuxResources, LinuxSeccomp as ociLinuxSeccomp,
};
use protocols::oci::{
LinuxIDMapping as grpcLinuxIDMapping, LinuxResources as grpcLinuxResources,
LinuxSeccomp as grpcLinuxSeccomp,
};
fn idmap_grpc_to_oci(im: &grpcLinuxIDMapping) -> ociLinuxIDMapping {
ociLinuxIDMapping {
container_id: im.ContainerID, container_id: im.ContainerID,
host_id: im.HostID, host_id: im.HostID,
size: im.Size, size: im.Size,
} }
} }
fn idmaps_grpc_to_oci(ims: &[grpcLinuxIDMapping]) -> Vec<ociLinuxIDMapping> { fn idmaps_grpc_to_oci(ims: &[grpc::LinuxIDMapping]) -> Vec<oci::LinuxIdMapping> {
let mut r = Vec::new(); let mut r = Vec::new();
for im in ims.iter() { for im in ims.iter() {
r.push(idmap_grpc_to_oci(im)); r.push(idmap_grpc_to_oci(im));
@ -214,24 +195,13 @@ fn idmaps_grpc_to_oci(ims: &[grpcLinuxIDMapping]) -> Vec<ociLinuxIDMapping> {
r r
} }
use oci::{ fn throttle_devices_grpc_to_oci(
LinuxBlockIO as ociLinuxBlockIO, LinuxBlockIODevice as ociLinuxBlockIODevice, tds: &[grpc::LinuxThrottleDevice],
LinuxCPU as ociLinuxCPU, LinuxDeviceCgroup as ociLinuxDeviceCgroup, ) -> Vec<oci::LinuxThrottleDevice> {
LinuxHugepageLimit as ociLinuxHugepageLimit,
LinuxInterfacePriority as ociLinuxInterfacePriority, LinuxMemory as ociLinuxMemory,
LinuxNetwork as ociLinuxNetwork, LinuxPids as ociLinuxPids,
LinuxThrottleDevice as ociLinuxThrottleDevice, LinuxWeightDevice as ociLinuxWeightDevice,
};
use protocols::oci::{
LinuxBlockIO as grpcLinuxBlockIO, LinuxThrottleDevice as grpcLinuxThrottleDevice,
LinuxWeightDevice as grpcLinuxWeightDevice,
};
fn throttle_devices_grpc_to_oci(tds: &[grpcLinuxThrottleDevice]) -> Vec<ociLinuxThrottleDevice> {
let mut r = Vec::new(); let mut r = Vec::new();
for td in tds.iter() { for td in tds.iter() {
r.push(ociLinuxThrottleDevice { r.push(oci::LinuxThrottleDevice {
blk: ociLinuxBlockIODevice { blk: oci::LinuxBlockIoDevice {
major: td.Major, major: td.Major,
minor: td.Minor, minor: td.Minor,
}, },
@ -241,11 +211,11 @@ fn throttle_devices_grpc_to_oci(tds: &[grpcLinuxThrottleDevice]) -> Vec<ociLinux
r r
} }
fn weight_devices_grpc_to_oci(wds: &[grpcLinuxWeightDevice]) -> Vec<ociLinuxWeightDevice> { fn weight_devices_grpc_to_oci(wds: &[grpc::LinuxWeightDevice]) -> Vec<oci::LinuxWeightDevice> {
let mut r = Vec::new(); let mut r = Vec::new();
for wd in wds.iter() { for wd in wds.iter() {
r.push(ociLinuxWeightDevice { r.push(oci::LinuxWeightDevice {
blk: ociLinuxBlockIODevice { blk: oci::LinuxBlockIoDevice {
major: wd.Major, major: wd.Major,
minor: wd.Minor, minor: wd.Minor,
}, },
@ -256,7 +226,7 @@ fn weight_devices_grpc_to_oci(wds: &[grpcLinuxWeightDevice]) -> Vec<ociLinuxWeig
r r
} }
fn blockio_grpc_to_oci(blk: &grpcLinuxBlockIO) -> ociLinuxBlockIO { fn blockio_grpc_to_oci(blk: &grpc::LinuxBlockIO) -> oci::LinuxBlockIo {
let weight_device = weight_devices_grpc_to_oci(blk.WeightDevice.as_ref()); let weight_device = weight_devices_grpc_to_oci(blk.WeightDevice.as_ref());
let throttle_read_bps_device = throttle_devices_grpc_to_oci(blk.ThrottleReadBpsDevice.as_ref()); let throttle_read_bps_device = throttle_devices_grpc_to_oci(blk.ThrottleReadBpsDevice.as_ref());
let throttle_write_bps_device = let throttle_write_bps_device =
@ -266,7 +236,7 @@ fn blockio_grpc_to_oci(blk: &grpcLinuxBlockIO) -> ociLinuxBlockIO {
let throttle_write_iops_device = let throttle_write_iops_device =
throttle_devices_grpc_to_oci(blk.ThrottleWriteIOPSDevice.as_ref()); throttle_devices_grpc_to_oci(blk.ThrottleWriteIOPSDevice.as_ref());
ociLinuxBlockIO { oci::LinuxBlockIo {
weight: Some(blk.Weight as u16), weight: Some(blk.Weight as u16),
leaf_weight: Some(blk.LeafWeight as u16), leaf_weight: Some(blk.LeafWeight as u16),
weight_device, weight_device,
@ -277,7 +247,7 @@ fn blockio_grpc_to_oci(blk: &grpcLinuxBlockIO) -> ociLinuxBlockIO {
} }
} }
pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources { pub fn resources_grpc_to_oci(res: &grpc::LinuxResources) -> oci::LinuxResources {
let devices = { let devices = {
let mut d = Vec::new(); let mut d = Vec::new();
for dev in res.Devices.iter() { for dev in res.Devices.iter() {
@ -292,7 +262,7 @@ pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
} else { } else {
Some(dev.Minor) Some(dev.Minor)
}; };
d.push(ociLinuxDeviceCgroup { d.push(oci::LinuxDeviceCgroup {
allow: dev.Allow, allow: dev.Allow,
r#type: dev.Type.clone(), r#type: dev.Type.clone(),
major, major,
@ -305,7 +275,7 @@ pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
let memory = if res.Memory.is_some() { let memory = if res.Memory.is_some() {
let mem = res.Memory.as_ref().unwrap(); let mem = res.Memory.as_ref().unwrap();
Some(ociLinuxMemory { Some(oci::LinuxMemory {
limit: Some(mem.Limit), limit: Some(mem.Limit),
reservation: Some(mem.Reservation), reservation: Some(mem.Reservation),
swap: Some(mem.Swap), swap: Some(mem.Swap),
@ -320,7 +290,7 @@ pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
let cpu = if res.CPU.is_some() { let cpu = if res.CPU.is_some() {
let c = res.CPU.as_ref().unwrap(); let c = res.CPU.as_ref().unwrap();
Some(ociLinuxCPU { Some(oci::LinuxCpu {
shares: Some(c.Shares), shares: Some(c.Shares),
quota: Some(c.Quota), quota: Some(c.Quota),
period: Some(c.Period), period: Some(c.Period),
@ -335,7 +305,7 @@ pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
let pids = if res.Pids.is_some() { let pids = if res.Pids.is_some() {
let p = res.Pids.as_ref().unwrap(); let p = res.Pids.as_ref().unwrap();
Some(ociLinuxPids { limit: p.Limit }) Some(oci::LinuxPids { limit: p.Limit })
} else { } else {
None None
}; };
@ -351,7 +321,7 @@ pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
let hugepage_limits = { let hugepage_limits = {
let mut r = Vec::new(); let mut r = Vec::new();
for hl in res.HugepageLimits.iter() { for hl in res.HugepageLimits.iter() {
r.push(ociLinuxHugepageLimit { r.push(oci::LinuxHugepageLimit {
page_size: hl.Pagesize.clone(), page_size: hl.Pagesize.clone(),
limit: hl.Limit, limit: hl.Limit,
}); });
@ -364,14 +334,14 @@ pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
let priorities = { let priorities = {
let mut r = Vec::new(); let mut r = Vec::new();
for pr in net.Priorities.iter() { for pr in net.Priorities.iter() {
r.push(ociLinuxInterfacePriority { r.push(oci::LinuxInterfacePriority {
name: pr.Name.clone(), name: pr.Name.clone(),
priority: pr.Priority, priority: pr.Priority,
}); });
} }
r r
}; };
Some(ociLinuxNetwork { Some(oci::LinuxNetwork {
class_id: Some(net.ClassID), class_id: Some(net.ClassID),
priorities, priorities,
}) })
@ -379,7 +349,7 @@ pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
None None
}; };
ociLinuxResources { oci::LinuxResources {
devices, devices,
memory, memory,
cpu, cpu,
@ -391,9 +361,7 @@ pub fn resources_grpc_to_oci(res: &grpcLinuxResources) -> ociLinuxResources {
} }
} }
use oci::{LinuxSeccompArg as ociLinuxSeccompArg, LinuxSyscall as ociLinuxSyscall}; fn seccomp_grpc_to_oci(sec: &grpc::LinuxSeccomp) -> oci::LinuxSeccomp {
fn seccomp_grpc_to_oci(sec: &grpcLinuxSeccomp) -> ociLinuxSeccomp {
let syscalls = { let syscalls = {
let mut r = Vec::new(); let mut r = Vec::new();
@ -401,7 +369,7 @@ fn seccomp_grpc_to_oci(sec: &grpcLinuxSeccomp) -> ociLinuxSeccomp {
let mut args = Vec::new(); let mut args = Vec::new();
for arg in sys.Args.iter() { for arg in sys.Args.iter() {
args.push(ociLinuxSeccompArg { args.push(oci::LinuxSeccompArg {
index: arg.Index as u32, index: arg.Index as u32,
value: arg.Value, value: arg.Value,
value_two: arg.ValueTwo, value_two: arg.ValueTwo,
@ -409,7 +377,7 @@ fn seccomp_grpc_to_oci(sec: &grpcLinuxSeccomp) -> ociLinuxSeccomp {
}); });
} }
r.push(ociLinuxSyscall { r.push(oci::LinuxSyscall {
names: sys.Names.clone().into_vec(), names: sys.Names.clone().into_vec(),
action: sys.Action.clone(), action: sys.Action.clone(),
errno_ret: sys.ErrnoRet, errno_ret: sys.ErrnoRet,
@ -419,7 +387,7 @@ fn seccomp_grpc_to_oci(sec: &grpcLinuxSeccomp) -> ociLinuxSeccomp {
r r
}; };
ociLinuxSeccomp { oci::LinuxSeccomp {
default_action: sec.DefaultAction.clone(), default_action: sec.DefaultAction.clone(),
architectures: sec.Architectures.clone().into_vec(), architectures: sec.Architectures.clone().into_vec(),
flags: sec.Flags.clone().into_vec(), flags: sec.Flags.clone().into_vec(),
@ -427,7 +395,7 @@ fn seccomp_grpc_to_oci(sec: &grpcLinuxSeccomp) -> ociLinuxSeccomp {
} }
} }
fn linux_grpc_to_oci(l: &grpcLinux) -> ociLinux { fn linux_grpc_to_oci(l: &grpc::Linux) -> oci::Linux {
let uid_mappings = idmaps_grpc_to_oci(l.UIDMappings.as_ref()); let uid_mappings = idmaps_grpc_to_oci(l.UIDMappings.as_ref());
let gid_mappings = idmaps_grpc_to_oci(l.GIDMappings.as_ref()); let gid_mappings = idmaps_grpc_to_oci(l.GIDMappings.as_ref());
@ -447,7 +415,7 @@ fn linux_grpc_to_oci(l: &grpcLinux) -> ociLinux {
let mut r = Vec::new(); let mut r = Vec::new();
for ns in l.Namespaces.iter() { for ns in l.Namespaces.iter() {
r.push(ociLinuxNamespace { r.push(oci::LinuxNamespace {
r#type: ns.Type.clone(), r#type: ns.Type.clone(),
path: ns.Path.clone(), path: ns.Path.clone(),
}); });
@ -459,7 +427,7 @@ fn linux_grpc_to_oci(l: &grpcLinux) -> ociLinux {
let mut r = Vec::new(); let mut r = Vec::new();
for d in l.Devices.iter() { for d in l.Devices.iter() {
r.push(ociLinuxDevice { r.push(oci::LinuxDevice {
path: d.Path.clone(), path: d.Path.clone(),
r#type: d.Type.clone(), r#type: d.Type.clone(),
major: d.Major, major: d.Major,
@ -475,14 +443,14 @@ fn linux_grpc_to_oci(l: &grpcLinux) -> ociLinux {
let intel_rdt = if l.IntelRdt.is_some() { let intel_rdt = if l.IntelRdt.is_some() {
let rdt = l.IntelRdt.as_ref().unwrap(); let rdt = l.IntelRdt.as_ref().unwrap();
Some(ociLinuxIntelRdt { Some(oci::LinuxIntelRdt {
l3_cache_schema: rdt.L3CacheSchema.clone(), l3_cache_schema: rdt.L3CacheSchema.clone(),
}) })
} else { } else {
None None
}; };
ociLinux { oci::Linux {
uid_mappings, uid_mappings,
gid_mappings, gid_mappings,
sysctl: l.Sysctl.clone(), sysctl: l.Sysctl.clone(),
@ -499,11 +467,11 @@ fn linux_grpc_to_oci(l: &grpcLinux) -> ociLinux {
} }
} }
fn linux_oci_to_grpc(_l: &ociLinux) -> grpcLinux { fn linux_oci_to_grpc(_l: &oci::Linux) -> grpc::Linux {
grpcLinux::default() grpc::Linux::default()
} }
pub fn grpc_to_oci(grpc: &grpcSpec) -> ociSpec { pub fn grpc_to_oci(grpc: &grpc::Spec) -> oci::Spec {
// process // process
let process = if grpc.Process.is_some() { let process = if grpc.Process.is_some() {
Some(process_grpc_to_oci(grpc.Process.as_ref().unwrap())) Some(process_grpc_to_oci(grpc.Process.as_ref().unwrap()))
@ -541,7 +509,7 @@ pub fn grpc_to_oci(grpc: &grpcSpec) -> ociSpec {
None None
}; };
ociSpec { oci::Spec {
version: grpc.Version.clone(), version: grpc.Version.clone(),
process, process,
root, root,

View File

@ -6,7 +6,7 @@
use crate::container::Config; use crate::container::Config;
use anyhow::{anyhow, Context, Error, Result}; use anyhow::{anyhow, Context, Error, Result};
use nix::errno::Errno; use nix::errno::Errno;
use oci::{Linux, LinuxIDMapping, LinuxNamespace, Spec}; use oci::{Linux, LinuxIdMapping, LinuxNamespace, Spec};
use std::collections::HashMap; use std::collections::HashMap;
use std::path::{Component, PathBuf}; use std::path::{Component, PathBuf};
@ -107,7 +107,7 @@ fn security(oci: &Spec) -> Result<()> {
Ok(()) Ok(())
} }
fn idmapping(maps: &[LinuxIDMapping]) -> Result<()> { fn idmapping(maps: &[LinuxIdMapping]) -> Result<()> {
for map in maps { for map in maps {
if map.size > 0 { if map.size > 0 {
return Ok(()); return Ok(());
@ -238,7 +238,7 @@ fn rootless_euid_mapping(oci: &Spec) -> Result<()> {
Ok(()) Ok(())
} }
fn has_idmapping(maps: &[LinuxIDMapping], id: u32) -> bool { fn has_idmapping(maps: &[LinuxIdMapping], id: u32) -> bool {
for map in maps { for map in maps {
if id >= map.container_id && id < map.container_id + map.size { if id >= map.container_id && id < map.container_id + map.size {
return true; return true;
@ -441,7 +441,7 @@ mod tests {
usernamespace(&spec).unwrap(); usernamespace(&spec).unwrap();
let mut linux = Linux::default(); let mut linux = Linux::default();
linux.uid_mappings = vec![LinuxIDMapping { linux.uid_mappings = vec![LinuxIdMapping {
container_id: 0, container_id: 0,
host_id: 1000, host_id: 1000,
size: 0, size: 0,
@ -450,7 +450,7 @@ mod tests {
usernamespace(&spec).unwrap_err(); usernamespace(&spec).unwrap_err();
let mut linux = Linux::default(); let mut linux = Linux::default();
linux.uid_mappings = vec![LinuxIDMapping { linux.uid_mappings = vec![LinuxIdMapping {
container_id: 0, container_id: 0,
host_id: 1000, host_id: 1000,
size: 100, size: 100,
@ -497,12 +497,12 @@ mod tests {
path: "/sys/cgroups/user".to_owned(), path: "/sys/cgroups/user".to_owned(),
}, },
]; ];
linux.uid_mappings = vec![LinuxIDMapping { linux.uid_mappings = vec![LinuxIdMapping {
container_id: 0, container_id: 0,
host_id: 1000, host_id: 1000,
size: 1000, size: 1000,
}]; }];
linux.gid_mappings = vec![LinuxIDMapping { linux.gid_mappings = vec![LinuxIdMapping {
container_id: 0, container_id: 0,
host_id: 1000, host_id: 1000,
size: 1000, size: 1000,

View File

@ -273,12 +273,12 @@ fn get_string_value(param: &str) -> Result<String> {
} }
// We need name (but the value can be blank) // We need name (but the value can be blank)
if fields[0] == "" { if fields[0].is_empty() {
return Err(anyhow!(ERR_INVALID_GET_VALUE_NO_NAME)); return Err(anyhow!(ERR_INVALID_GET_VALUE_NO_NAME));
} }
let value = fields[1..].join("="); let value = fields[1..].join("=");
if value == "" { if value.is_empty() {
return Err(anyhow!(ERR_INVALID_GET_VALUE_NO_VALUE)); return Err(anyhow!(ERR_INVALID_GET_VALUE_NO_VALUE));
} }

View File

@ -96,10 +96,10 @@ struct ScsiBlockMatcher {
} }
impl ScsiBlockMatcher { impl ScsiBlockMatcher {
fn new(scsi_addr: &str) -> Result<ScsiBlockMatcher> { fn new(scsi_addr: &str) -> ScsiBlockMatcher {
let search = format!(r"/0:0:{}/block/", scsi_addr); let search = format!(r"/0:0:{}/block/", scsi_addr);
Ok(ScsiBlockMatcher { search }) ScsiBlockMatcher { search }
} }
} }
@ -113,7 +113,7 @@ pub async fn get_scsi_device_name(
sandbox: &Arc<Mutex<Sandbox>>, sandbox: &Arc<Mutex<Sandbox>>,
scsi_addr: &str, scsi_addr: &str,
) -> Result<String> { ) -> Result<String> {
let matcher = ScsiBlockMatcher::new(scsi_addr)?; let matcher = ScsiBlockMatcher::new(scsi_addr);
scan_scsi_bus(scsi_addr)?; scan_scsi_bus(scsi_addr)?;
let uev = wait_for_uevent(sandbox, matcher).await?; let uev = wait_for_uevent(sandbox, matcher).await?;
@ -126,12 +126,12 @@ struct VirtioBlkPciMatcher {
} }
impl VirtioBlkPciMatcher { impl VirtioBlkPciMatcher {
fn new(relpath: &str) -> Result<VirtioBlkPciMatcher> { fn new(relpath: &str) -> VirtioBlkPciMatcher {
let root_bus = create_pci_root_bus_path(); let root_bus = create_pci_root_bus_path();
let re = format!(r"^{}{}/virtio[0-9]+/block/", root_bus, relpath); let re = format!(r"^{}{}/virtio[0-9]+/block/", root_bus, relpath);
Ok(VirtioBlkPciMatcher { VirtioBlkPciMatcher {
rex: Regex::new(&re).unwrap(), rex: Regex::new(&re).unwrap(),
}) }
} }
} }
@ -147,7 +147,7 @@ pub async fn get_virtio_blk_pci_device_name(
) -> Result<String> { ) -> Result<String> {
let root_bus_sysfs = format!("{}{}", SYSFS_DIR, create_pci_root_bus_path()); let root_bus_sysfs = format!("{}{}", SYSFS_DIR, create_pci_root_bus_path());
let sysfs_rel_path = pcipath_to_sysfs(&root_bus_sysfs, pcipath)?; let sysfs_rel_path = pcipath_to_sysfs(&root_bus_sysfs, pcipath)?;
let matcher = VirtioBlkPciMatcher::new(&sysfs_rel_path)?; let matcher = VirtioBlkPciMatcher::new(&sysfs_rel_path);
rescan_pci_bus()?; rescan_pci_bus()?;
@ -161,10 +161,10 @@ struct PmemBlockMatcher {
} }
impl PmemBlockMatcher { impl PmemBlockMatcher {
fn new(devname: &str) -> Result<PmemBlockMatcher> { fn new(devname: &str) -> PmemBlockMatcher {
let suffix = format!(r"/block/{}", devname); let suffix = format!(r"/block/{}", devname);
Ok(PmemBlockMatcher { suffix }) PmemBlockMatcher { suffix }
} }
} }
@ -188,7 +188,7 @@ pub async fn wait_for_pmem_device(sandbox: &Arc<Mutex<Sandbox>>, devpath: &str)
} }
}; };
let matcher = PmemBlockMatcher::new(devname)?; let matcher = PmemBlockMatcher::new(devname);
let uev = wait_for_uevent(sandbox, matcher).await?; let uev = wait_for_uevent(sandbox, matcher).await?;
if uev.devname != devname { if uev.devname != devname {
return Err(anyhow!( return Err(anyhow!(
@ -822,7 +822,7 @@ mod tests {
sandbox: &Arc<Mutex<Sandbox>>, sandbox: &Arc<Mutex<Sandbox>>,
relpath: &str, relpath: &str,
) -> Result<String> { ) -> Result<String> {
let matcher = VirtioBlkPciMatcher::new(relpath)?; let matcher = VirtioBlkPciMatcher::new(relpath);
let uev = wait_for_uevent(sandbox, matcher).await?; let uev = wait_for_uevent(sandbox, matcher).await?;
@ -875,12 +875,12 @@ mod tests {
uev_a.subsystem = "block".to_string(); uev_a.subsystem = "block".to_string();
uev_a.devname = devname.to_string(); uev_a.devname = devname.to_string();
uev_a.devpath = format!("{}{}/virtio4/block/{}", root_bus, relpath_a, devname); uev_a.devpath = format!("{}{}/virtio4/block/{}", root_bus, relpath_a, devname);
let matcher_a = VirtioBlkPciMatcher::new(&relpath_a).unwrap(); let matcher_a = VirtioBlkPciMatcher::new(&relpath_a);
let mut uev_b = uev_a.clone(); let mut uev_b = uev_a.clone();
let relpath_b = "/0000:00:0a.0/0000:00:0b.0"; let relpath_b = "/0000:00:0a.0/0000:00:0b.0";
uev_b.devpath = format!("{}{}/virtio0/block/{}", root_bus, relpath_b, devname); uev_b.devpath = format!("{}{}/virtio0/block/{}", root_bus, relpath_b, devname);
let matcher_b = VirtioBlkPciMatcher::new(&relpath_b).unwrap(); let matcher_b = VirtioBlkPciMatcher::new(&relpath_b);
assert!(matcher_a.is_match(&uev_a)); assert!(matcher_a.is_match(&uev_a));
assert!(matcher_b.is_match(&uev_b)); assert!(matcher_b.is_match(&uev_b));
@ -902,7 +902,7 @@ mod tests {
"{}/0000:00:00.0/virtio0/host0/target0:0:0/0:0:{}/block/sda", "{}/0000:00:00.0/virtio0/host0/target0:0:0/0:0:{}/block/sda",
root_bus, addr_a root_bus, addr_a
); );
let matcher_a = ScsiBlockMatcher::new(&addr_a).unwrap(); let matcher_a = ScsiBlockMatcher::new(&addr_a);
let mut uev_b = uev_a.clone(); let mut uev_b = uev_a.clone();
let addr_b = "2:0"; let addr_b = "2:0";
@ -910,7 +910,7 @@ mod tests {
"{}/0000:00:00.0/virtio0/host0/target0:0:2/0:0:{}/block/sdb", "{}/0000:00:00.0/virtio0/host0/target0:0:2/0:0:{}/block/sdb",
root_bus, addr_b root_bus, addr_b
); );
let matcher_b = ScsiBlockMatcher::new(&addr_b).unwrap(); let matcher_b = ScsiBlockMatcher::new(&addr_b);
assert!(matcher_a.is_match(&uev_a)); assert!(matcher_a.is_match(&uev_a));
assert!(matcher_b.is_match(&uev_b)); assert!(matcher_b.is_match(&uev_b));

View File

@ -45,18 +45,18 @@ impl Namespace {
logger: logger.clone(), logger: logger.clone(),
path: String::from(""), path: String::from(""),
persistent_ns_dir: String::from(PERSISTENT_NS_DIR), persistent_ns_dir: String::from(PERSISTENT_NS_DIR),
ns_type: NamespaceType::IPC, ns_type: NamespaceType::Ipc,
hostname: None, hostname: None,
} }
} }
pub fn get_ipc(mut self) -> Self { pub fn get_ipc(mut self) -> Self {
self.ns_type = NamespaceType::IPC; self.ns_type = NamespaceType::Ipc;
self self
} }
pub fn get_uts(mut self, hostname: &str) -> Self { pub fn get_uts(mut self, hostname: &str) -> Self {
self.ns_type = NamespaceType::UTS; self.ns_type = NamespaceType::Uts;
if !hostname.is_empty() { if !hostname.is_empty() {
self.hostname = Some(String::from(hostname)); self.hostname = Some(String::from(hostname));
} }
@ -64,7 +64,7 @@ impl Namespace {
} }
pub fn get_pid(mut self) -> Self { pub fn get_pid(mut self) -> Self {
self.ns_type = NamespaceType::PID; self.ns_type = NamespaceType::Pid;
self self
} }
@ -81,7 +81,7 @@ impl Namespace {
let ns_path = PathBuf::from(&self.persistent_ns_dir); let ns_path = PathBuf::from(&self.persistent_ns_dir);
let ns_type = self.ns_type; let ns_type = self.ns_type;
if ns_type == NamespaceType::PID { if ns_type == NamespaceType::Pid {
return Err(anyhow!("Cannot persist namespace of PID type")); return Err(anyhow!("Cannot persist namespace of PID type"));
} }
let logger = self.logger.clone(); let logger = self.logger.clone();
@ -104,7 +104,7 @@ impl Namespace {
unshare(cf)?; unshare(cf)?;
if ns_type == NamespaceType::UTS && hostname.is_some() { if ns_type == NamespaceType::Uts && hostname.is_some() {
nix::unistd::sethostname(hostname.unwrap())?; nix::unistd::sethostname(hostname.unwrap())?;
} }
// Bind mount the new namespace from the current thread onto the mount point to persist it. // Bind mount the new namespace from the current thread onto the mount point to persist it.
@ -147,27 +147,27 @@ impl Namespace {
/// Represents the Namespace type. /// Represents the Namespace type.
#[derive(Clone, Copy, PartialEq)] #[derive(Clone, Copy, PartialEq)]
enum NamespaceType { enum NamespaceType {
IPC, Ipc,
UTS, Uts,
PID, Pid,
} }
impl NamespaceType { impl NamespaceType {
/// Get the string representation of the namespace type. /// Get the string representation of the namespace type.
pub fn get(&self) -> &str { pub fn get(&self) -> &str {
match *self { match *self {
Self::IPC => "ipc", Self::Ipc => "ipc",
Self::UTS => "uts", Self::Uts => "uts",
Self::PID => "pid", Self::Pid => "pid",
} }
} }
/// Get the associate flags with the namespace type. /// Get the associate flags with the namespace type.
pub fn get_flags(&self) -> CloneFlags { pub fn get_flags(&self) -> CloneFlags {
match *self { match *self {
Self::IPC => CloneFlags::CLONE_NEWIPC, Self::Ipc => CloneFlags::CLONE_NEWIPC,
Self::UTS => CloneFlags::CLONE_NEWUTS, Self::Uts => CloneFlags::CLONE_NEWUTS,
Self::PID => CloneFlags::CLONE_NEWPID, Self::Pid => CloneFlags::CLONE_NEWPID,
} }
} }
} }
@ -178,12 +178,6 @@ impl fmt::Debug for NamespaceType {
} }
} }
impl Default for NamespaceType {
fn default() -> Self {
NamespaceType::IPC
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{Namespace, NamespaceType}; use super::{Namespace, NamespaceType};
@ -234,15 +228,15 @@ mod tests {
#[test] #[test]
fn test_namespace_type() { fn test_namespace_type() {
let ipc = NamespaceType::IPC; let ipc = NamespaceType::Ipc;
assert_eq!("ipc", ipc.get()); assert_eq!("ipc", ipc.get());
assert_eq!(CloneFlags::CLONE_NEWIPC, ipc.get_flags()); assert_eq!(CloneFlags::CLONE_NEWIPC, ipc.get_flags());
let uts = NamespaceType::UTS; let uts = NamespaceType::Uts;
assert_eq!("uts", uts.get()); assert_eq!("uts", uts.get());
assert_eq!(CloneFlags::CLONE_NEWUTS, uts.get_flags()); assert_eq!(CloneFlags::CLONE_NEWUTS, uts.get_flags());
let pid = NamespaceType::PID; let pid = NamespaceType::Pid;
assert_eq!("pid", pid.get()); assert_eq!("pid", pid.get());
assert_eq!(CloneFlags::CLONE_NEWPID, pid.get_flags()); assert_eq!(CloneFlags::CLONE_NEWPID, pid.get_flags());
} }

View File

@ -542,12 +542,10 @@ impl Handle {
ntype: NDA_UNSPEC as u8, ntype: NDA_UNSPEC as u8,
}, },
nlas: { nlas: {
let mut nlas = vec![]; let mut nlas = vec![Nla::Destination(match ip {
nlas.push(Nla::Destination(match ip {
IpAddr::V4(v4) => v4.octets().to_vec(), IpAddr::V4(v4) => v4.octets().to_vec(),
IpAddr::V6(v6) => v6.octets().to_vec(), IpAddr::V6(v6) => v6.octets().to_vec(),
})); })];
if !neigh.lladdr.is_empty() { if !neigh.lladdr.is_empty() {
nlas.push(Nla::LinkLocalAddress( nlas.push(Nla::LinkLocalAddress(

View File

@ -245,11 +245,13 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn test_wait_for_uevent() { async fn test_wait_for_uevent() {
let mut uev = crate::uevent::Uevent::default(); let uev = Uevent {
uev.action = crate::linux_abi::U_EVENT_ACTION_ADD.to_string(); action: crate::linux_abi::U_EVENT_ACTION_ADD.to_string(),
uev.subsystem = "test".to_string(); subsystem: "test".to_string(),
uev.devpath = "/test/sysfs/path".to_string(); devpath: "/test/sysfs/path".to_string(),
uev.devname = "testdevname".to_string(); devname: "testdevname".to_string(),
..Default::default()
};
let matcher = AlwaysMatch(); let matcher = AlwaysMatch();