diff --git a/Cargo.toml b/Cargo.toml index 524e006..6849f81 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ repository = "https://github.com/levex/cgroups-rs" keywords = ["linux", "cgroup", "containers", "isolation"] categories = ["os", "api-bindings", "os::unix-apis"] license = "MIT OR Apache-2.0" -version = "0.1.1-alpha.0" +version = "0.2.1-alpha.0" authors = ["Levente Kurusa ", "Sam Wilson "] edition = "2018" diff --git a/src/blkio.rs b/src/blkio.rs index fa55f64..70773cf 100644 --- a/src/blkio.rs +++ b/src/blkio.rs @@ -6,8 +6,8 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ BlkIoResources, ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem, @@ -279,7 +279,8 @@ impl ControllerInternal for BlkIoController { for dev in &res.weight_device { let _ = self.set_weight_for_device(dev.major, dev.minor, dev.weight as u64); - let _ = self.set_leaf_weight_for_device(dev.major, dev.minor, dev.leaf_weight as u64); + let _ = + self.set_leaf_weight_for_device(dev.major, dev.minor, dev.leaf_weight as u64); } for dev in &res.throttle_read_bps_device { @@ -309,19 +310,7 @@ impl ControllIdentifier for BlkIoController { } } -impl<'a> From<&'a Subsystem> for &'a BlkIoController { - fn from(sub: &'a Subsystem) -> &'a BlkIoController { - unsafe { - match sub { - Subsystem::BlkIo(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::BlkIo, BlkIoController); fn read_string_from(mut file: File) -> Result { let mut string = String::new(); @@ -334,7 +323,10 @@ fn read_string_from(mut file: File) -> Result { fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); match file.read_to_string(&mut string) { - Ok(_) => string.trim().parse().map_err(|e| Error::with_cause(ParseError, e)), + Ok(_) => string + .trim() + .parse() + .map_err(|e| Error::with_cause(ParseError, e)), Err(e) => Err(Error::with_cause(ReadFailed, e)), } } @@ -588,12 +580,7 @@ impl BlkIoController { } /// Same as `set_leaf_weight()`, but settable per each block device. - pub fn set_leaf_weight_for_device( - &self, - major: u64, - minor: u64, - weight: u64, - ) -> Result<()> { + pub fn set_leaf_weight_for_device(&self, major: u64, minor: u64, weight: u64) -> Result<()> { self.open_path("blkio.leaf_weight_device", true) .and_then(|mut file| { file.write_all(format!("{}:{} {}", major, minor, weight).as_ref()) @@ -612,12 +599,7 @@ impl BlkIoController { /// Throttle the bytes per second rate of read operation affecting the block device /// `major:minor` to `bps`. - pub fn throttle_read_bps_for_device( - &self, - major: u64, - minor: u64, - bps: u64, - ) -> Result<()> { + pub fn throttle_read_bps_for_device(&self, major: u64, minor: u64, bps: u64) -> Result<()> { self.open_path("blkio.throttle.read_bps_device", true) .and_then(|mut file| { file.write_all(format!("{}:{} {}", major, minor, bps).to_string().as_ref()) @@ -627,12 +609,7 @@ impl BlkIoController { /// Throttle the I/O operations per second rate of read operation affecting the block device /// `major:minor` to `bps`. - pub fn throttle_read_iops_for_device( - &self, - major: u64, - minor: u64, - iops: u64, - ) -> Result<()> { + pub fn throttle_read_iops_for_device(&self, major: u64, minor: u64, iops: u64) -> Result<()> { self.open_path("blkio.throttle.read_iops_device", true) .and_then(|mut file| { file.write_all(format!("{}:{} {}", major, minor, iops).to_string().as_ref()) @@ -641,12 +618,7 @@ impl BlkIoController { } /// Throttle the bytes per second rate of write operation affecting the block device /// `major:minor` to `bps`. - pub fn throttle_write_bps_for_device( - &self, - major: u64, - minor: u64, - bps: u64, - ) -> Result<()> { + pub fn throttle_write_bps_for_device(&self, major: u64, minor: u64, bps: u64) -> Result<()> { self.open_path("blkio.throttle.write_bps_device", true) .and_then(|mut file| { file.write_all(format!("{}:{} {}", major, minor, bps).to_string().as_ref()) @@ -656,12 +628,7 @@ impl BlkIoController { /// Throttle the I/O operations per second rate of write operation affecting the block device /// `major:minor` to `bps`. - pub fn throttle_write_iops_for_device( - &self, - major: u64, - minor: u64, - iops: u64, - ) -> Result<()> { + pub fn throttle_write_iops_for_device(&self, major: u64, minor: u64, iops: u64) -> Result<()> { self.open_path("blkio.throttle.write_iops_device", true) .and_then(|mut file| { file.write_all(format!("{}:{} {}", major, minor, iops).to_string().as_ref()) @@ -671,20 +638,14 @@ impl BlkIoController { /// Set the weight of the control group's tasks. pub fn set_weight(&self, w: u64) -> Result<()> { - self.open_path("blkio.weight", true) - .and_then(|mut file| { - file.write_all(w.to_string().as_ref()) - .map_err(|e| Error::with_cause(WriteFailed, e)) - }) + self.open_path("blkio.weight", true).and_then(|mut file| { + file.write_all(w.to_string().as_ref()) + .map_err(|e| Error::with_cause(WriteFailed, e)) + }) } /// Same as `set_weight()`, but settable per each block device. - pub fn set_weight_for_device( - &self, - major: u64, - minor: u64, - weight: u64, - ) -> Result<()> { + pub fn set_weight_for_device(&self, major: u64, minor: u64, weight: u64) -> Result<()> { self.open_path("blkio.weight_device", true) .and_then(|mut file| { file.write_all(format!("{}:{} {}", major, minor, weight).as_ref()) @@ -755,10 +716,7 @@ Total 61823067136 #[test] fn test_parse_io_service_total() { let ok = parse_io_service_total(TEST_VALUE.to_string()).unwrap(); - assert_eq!( - ok, - 61823067136 - ); + assert_eq!(ok, 61823067136); } #[test] @@ -806,10 +764,7 @@ Total 61823067136 ] ); let err = parse_io_service(TEST_WRONG_VALUE.to_string()).unwrap_err(); - assert_eq!( - err.kind(), - &ErrorKind::ParseError, - ); + assert_eq!(err.kind(), &ErrorKind::ParseError,); } #[test] diff --git a/src/cgroup.rs b/src/cgroup.rs index 140a4f4..6fd1930 100644 --- a/src/cgroup.rs +++ b/src/cgroup.rs @@ -24,7 +24,7 @@ pub struct Cgroup<'b> { subsystems: Vec, /// The hierarchy. - hier: &'b Hierarchy, + hier: &'b dyn Hierarchy, } impl<'b> Cgroup<'b> { @@ -41,7 +41,7 @@ impl<'b> Cgroup<'b> { /// /// Note that if the handle goes out of scope and is dropped, the control group is _not_ /// destroyed. - pub fn new>(hier: &Hierarchy, path: P) -> Cgroup { + pub fn new>(hier: &dyn Hierarchy, path: P) -> Cgroup { let cg = Cgroup::load(hier, path); cg.create(); cg @@ -54,7 +54,7 @@ impl<'b> Cgroup<'b> { /// /// Note that if the handle goes out of scope and is dropped, the control group is _not_ /// destroyed. - pub fn load>(hier: &Hierarchy, path: P) -> Cgroup { + pub fn load>(hier: &dyn Hierarchy, path: P) -> Cgroup { let path = path.as_ref(); let mut subsystems = hier.subsystems(); if path.as_os_str() != "" { diff --git a/src/cgroup_builder.rs b/src/cgroup_builder.rs index 31999c8..a7bd6fb 100644 --- a/src/cgroup_builder.rs +++ b/src/cgroup_builder.rs @@ -51,11 +51,13 @@ //! .read(6, 1, 10) //! .write(11, 1, 100) //! .done() -//! .build(); +//! .build().unwrap(); //! ``` -use crate::error::*; -use crate::{pid, BlkIoDeviceResource, BlkIoDeviceThrottleResource, Cgroup, DeviceResource, Hierarchy, HugePageResource, NetworkPriority, Resources}; +use crate::{ + error::*, pid, BlkIoDeviceResource, BlkIoDeviceThrottleResource, Cgroup, DeviceResource, + Hierarchy, HugePageResource, NetworkPriority, Resources, +}; macro_rules! gen_setter { ($res:ident, $cont:ident, $func:ident, $name:ident, $ty:ty) => { @@ -65,13 +67,13 @@ macro_rules! gen_setter { self.cgroup.resources.$res.$name = $name; self } - } + }; } /// A control group builder instance pub struct CgroupBuilder<'a> { name: String, - hierarchy: &'a Hierarchy, + hierarchy: &'a dyn Hierarchy, /// Internal, unsupported field: use the associated builders instead. resources: Resources, } @@ -80,7 +82,7 @@ impl<'a> CgroupBuilder<'a> { /// Start building a control group with the supplied hierarchy and name pair. /// /// Note that this does not actually create the control group until `build()` is called. - pub fn new(name: &'a str, hierarchy: &'a Hierarchy) -> CgroupBuilder<'a> { + pub fn new(name: &'a str, hierarchy: &'a dyn Hierarchy) -> CgroupBuilder<'a> { CgroupBuilder { name: name.to_owned(), hierarchy: hierarchy, @@ -90,46 +92,34 @@ impl<'a> CgroupBuilder<'a> { /// Builds the memory resources of the control group. pub fn memory(self) -> MemoryResourceBuilder<'a> { - MemoryResourceBuilder { - cgroup: self, - } + MemoryResourceBuilder { cgroup: self } } /// Builds the pid resources of the control group. pub fn pid(self) -> PidResourceBuilder<'a> { - PidResourceBuilder { - cgroup: self, - } + PidResourceBuilder { cgroup: self } } /// Builds the cpu resources of the control group. pub fn cpu(self) -> CpuResourceBuilder<'a> { - CpuResourceBuilder { - cgroup: self, - } + CpuResourceBuilder { cgroup: self } } /// Builds the devices resources of the control group, disallowing or /// allowing access to certain devices in the system. pub fn devices(self) -> DeviceResourceBuilder<'a> { - DeviceResourceBuilder { - cgroup: self, - } + DeviceResourceBuilder { cgroup: self } } /// Builds the network resources of the control group, setting class id, or /// various priorities on networking interfaces. pub fn network(self) -> NetworkResourceBuilder<'a> { - NetworkResourceBuilder { - cgroup: self, - } + NetworkResourceBuilder { cgroup: self } } /// Builds the hugepage/hugetlb resources available to the control group. pub fn hugepages(self) -> HugepagesResourceBuilder<'a> { - HugepagesResourceBuilder { - cgroup: self, - } + HugepagesResourceBuilder { cgroup: self } } /// Builds the block I/O resources available for the control group. @@ -141,10 +131,10 @@ impl<'a> CgroupBuilder<'a> { } /// Finalize the control group, consuming the builder and creating the control group. - pub fn build(self) -> Cgroup<'a> { + pub fn build(self) -> Result> { let cg = Cgroup::new(self.hierarchy, self.name); - cg.apply(&self.resources); - cg + cg.apply(&self.resources)?; + Ok(cg) } } @@ -154,12 +144,35 @@ pub struct MemoryResourceBuilder<'a> { } impl<'a> MemoryResourceBuilder<'a> { - - gen_setter!(memory, MemController, set_kmem_limit, kernel_memory_limit, u64); + gen_setter!( + memory, + MemController, + set_kmem_limit, + kernel_memory_limit, + u64 + ); gen_setter!(memory, MemController, set_limit, memory_hard_limit, u64); - gen_setter!(memory, MemController, set_soft_limit, memory_soft_limit, u64); - gen_setter!(memory, MemController, set_tcp_limit, kernel_tcp_memory_limit, u64); - gen_setter!(memory, MemController, set_memswap_limit, memory_swap_limit, u64); + gen_setter!( + memory, + MemController, + set_soft_limit, + memory_soft_limit, + u64 + ); + gen_setter!( + memory, + MemController, + set_tcp_limit, + kernel_tcp_memory_limit, + u64 + ); + gen_setter!( + memory, + MemController, + set_memswap_limit, + memory_swap_limit, + u64 + ); gen_setter!(memory, MemController, set_swappiness, swappiness, u64); /// Finish the construction of the memory resources of a control group. @@ -174,8 +187,13 @@ pub struct PidResourceBuilder<'a> { } impl<'a> PidResourceBuilder<'a> { - - gen_setter!(pid, PidController, set_pid_max, maximum_number_of_processes, pid::PidMax); + gen_setter!( + pid, + PidController, + set_pid_max, + maximum_number_of_processes, + pid::PidMax + ); /// Finish the construction of the pid resources of a control group. pub fn done(self) -> CgroupBuilder<'a> { @@ -189,7 +207,6 @@ pub struct CpuResourceBuilder<'a> { } impl<'a> CpuResourceBuilder<'a> { - gen_setter!(cpu, CpuSetController, set_cpus, cpus, String); gen_setter!(cpu, CpuSetController, set_mems, mems, String); gen_setter!(cpu, CpuController, set_shares, shares, u64); @@ -210,22 +227,22 @@ pub struct DeviceResourceBuilder<'a> { } impl<'a> DeviceResourceBuilder<'a> { - /// Restrict (or allow) a device to the tasks inside the control group. - pub fn device(mut self, - major: i64, - minor: i64, - devtype: crate::devices::DeviceType, - allow: bool, - access: Vec) - -> DeviceResourceBuilder<'a> { + pub fn device( + mut self, + major: i64, + minor: i64, + devtype: crate::devices::DeviceType, + allow: bool, + access: Vec, + ) -> DeviceResourceBuilder<'a> { self.cgroup.resources.devices.update_values = true; self.cgroup.resources.devices.devices.push(DeviceResource { major, minor, devtype, allow, - access + access, }); self } @@ -242,18 +259,17 @@ pub struct NetworkResourceBuilder<'a> { } impl<'a> NetworkResourceBuilder<'a> { - gen_setter!(network, NetclsController, set_class, class_id, u64); /// Set the priority of the tasks when operating on a networking device defined by `name` to be /// `priority`. - pub fn priority(mut self, name: String, priority: u64) - -> NetworkResourceBuilder<'a> { + pub fn priority(mut self, name: String, priority: u64) -> NetworkResourceBuilder<'a> { self.cgroup.resources.network.update_values = true; - self.cgroup.resources.network.priorities.push(NetworkPriority { - name, - priority, - }); + self.cgroup + .resources + .network + .priorities + .push(NetworkPriority { name, priority }); self } @@ -269,15 +285,14 @@ pub struct HugepagesResourceBuilder<'a> { } impl<'a> HugepagesResourceBuilder<'a> { - /// Limit the usage of certain hugepages (determined by `size`) to be at most `limit` bytes. - pub fn limit(mut self, size: String, limit: u64) - -> HugepagesResourceBuilder<'a> { + pub fn limit(mut self, size: String, limit: u64) -> HugepagesResourceBuilder<'a> { self.cgroup.resources.hugepages.update_values = true; - self.cgroup.resources.hugepages.limits.push(HugePageResource { - size, - limit, - }); + self.cgroup + .resources + .hugepages + .limits + .push(HugePageResource { size, limit }); self } @@ -294,24 +309,28 @@ pub struct BlkIoResourcesBuilder<'a> { } impl<'a> BlkIoResourcesBuilder<'a> { - gen_setter!(blkio, BlkIoController, set_weight, weight, u16); gen_setter!(blkio, BlkIoController, set_leaf_weight, leaf_weight, u16); /// Set the weight of a certain device. - pub fn weight_device(mut self, - major: u64, - minor: u64, - weight: u16, - leaf_weight: u16) - -> BlkIoResourcesBuilder<'a> { + pub fn weight_device( + mut self, + major: u64, + minor: u64, + weight: u16, + leaf_weight: u16, + ) -> BlkIoResourcesBuilder<'a> { self.cgroup.resources.blkio.update_values = true; - self.cgroup.resources.blkio.weight_device.push(BlkIoDeviceResource { - major, - minor, - weight, - leaf_weight, - }); + self.cgroup + .resources + .blkio + .weight_device + .push(BlkIoDeviceResource { + major, + minor, + weight, + leaf_weight, + }); self } @@ -328,35 +347,41 @@ impl<'a> BlkIoResourcesBuilder<'a> { } /// Limit the read rate of the current metric for a certain device. - pub fn read(mut self, major: u64, minor: u64, rate: u64) - -> BlkIoResourcesBuilder<'a> { + pub fn read(mut self, major: u64, minor: u64, rate: u64) -> BlkIoResourcesBuilder<'a> { self.cgroup.resources.blkio.update_values = true; - let throttle = BlkIoDeviceThrottleResource { - major, - minor, - rate, - }; + let throttle = BlkIoDeviceThrottleResource { major, minor, rate }; if self.throttling_iops { - self.cgroup.resources.blkio.throttle_read_iops_device.push(throttle); + self.cgroup + .resources + .blkio + .throttle_read_iops_device + .push(throttle); } else { - self.cgroup.resources.blkio.throttle_read_bps_device.push(throttle); + self.cgroup + .resources + .blkio + .throttle_read_bps_device + .push(throttle); } self } /// Limit the write rate of the current metric for a certain device. - pub fn write(mut self, major: u64, minor: u64, rate: u64) - -> BlkIoResourcesBuilder<'a> { + pub fn write(mut self, major: u64, minor: u64, rate: u64) -> BlkIoResourcesBuilder<'a> { self.cgroup.resources.blkio.update_values = true; - let throttle = BlkIoDeviceThrottleResource { - major, - minor, - rate, - }; + let throttle = BlkIoDeviceThrottleResource { major, minor, rate }; if self.throttling_iops { - self.cgroup.resources.blkio.throttle_write_iops_device.push(throttle); + self.cgroup + .resources + .blkio + .throttle_write_iops_device + .push(throttle); } else { - self.cgroup.resources.blkio.throttle_write_bps_device.push(throttle); + self.cgroup + .resources + .blkio + .throttle_write_bps_device + .push(throttle); } self } diff --git a/src/cpu.rs b/src/cpu.rs index 3e43ea8..4b6c9a8 100644 --- a/src/cpu.rs +++ b/src/cpu.rs @@ -7,8 +7,8 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ ControllIdentifier, ControllerInternal, Controllers, CpuResources, Resources, Subsystem, @@ -85,24 +85,15 @@ impl ControllIdentifier for CpuController { } } -impl<'a> From<&'a Subsystem> for &'a CpuController { - fn from(sub: &'a Subsystem) -> &'a CpuController { - unsafe { - match sub { - Subsystem::Cpu(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::Cpu, CpuController); fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); match file.read_to_string(&mut string) { - Ok(_) => string.trim().parse().map_err(|e| Error::with_cause(ParseError, e)), + Ok(_) => string + .trim() + .parse() + .map_err(|e| Error::with_cause(ParseError, e)), Err(e) => Err(Error::with_cause(ReadFailed, e)), } } @@ -130,7 +121,8 @@ impl CpuController { Ok(_) => Ok(s), Err(e) => Err(Error::with_cause(ReadFailed, e)), } - }).unwrap_or("".to_string()), + }) + .unwrap_or("".to_string()), } } diff --git a/src/cpuacct.rs b/src/cpuacct.rs index ec3b967..8afb519 100644 --- a/src/cpuacct.rs +++ b/src/cpuacct.rs @@ -6,8 +6,8 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem}; @@ -77,19 +77,7 @@ impl ControllIdentifier for CpuAcctController { } } -impl<'a> From<&'a Subsystem> for &'a CpuAcctController { - fn from(sub: &'a Subsystem) -> &'a CpuAcctController { - unsafe { - match sub { - Subsystem::CpuAcct(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::CpuAcct, CpuAcctController); fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); @@ -162,7 +150,9 @@ impl CpuAcctController { /// Reset the statistics the kernel has gathered about the control group. pub fn reset(&self) -> Result<()> { - self.open_path("cpuacct.usage", true) - .and_then(|mut file| file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e))) + self.open_path("cpuacct.usage", true).and_then(|mut file| { + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) + }) } } diff --git a/src/cpuset.rs b/src/cpuset.rs index b7b679a..fbecd51 100644 --- a/src/cpuset.rs +++ b/src/cpuset.rs @@ -6,8 +6,8 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ ControllIdentifier, ControllerInternal, Controllers, CpuResources, Resources, Subsystem, @@ -112,19 +112,7 @@ impl ControllIdentifier for CpuSetController { } } -impl<'a> From<&'a Subsystem> for &'a CpuSetController { - fn from(sub: &'a Subsystem) -> &'a CpuSetController { - unsafe { - match sub { - Subsystem::CpuSet(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::CpuSet, CpuSetController); fn read_string_from(mut file: File) -> Result { let mut string = String::new(); @@ -137,7 +125,10 @@ fn read_string_from(mut file: File) -> Result { fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); match file.read_to_string(&mut string) { - Ok(_) => string.trim().parse().map_err(|e| Error::with_cause(ParseError, e)), + Ok(_) => string + .trim() + .parse() + .map_err(|e| Error::with_cause(ParseError, e)), Err(e) => Err(Error::with_cause(ReadFailed, e)), } } @@ -285,9 +276,11 @@ impl CpuSetController { self.open_path("cpuset.cpu_exclusive", true) .and_then(|mut file| { if b { - file.write_all(b"1").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"1") + .map_err(|e| Error::with_cause(WriteFailed, e)) } else { - file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) } }) } @@ -298,9 +291,11 @@ impl CpuSetController { self.open_path("cpuset.mem_exclusive", true) .and_then(|mut file| { if b { - file.write_all(b"1").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"1") + .map_err(|e| Error::with_cause(WriteFailed, e)) } else { - file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) } }) } @@ -335,9 +330,11 @@ impl CpuSetController { self.open_path("cpuset.mem_hardwall", true) .and_then(|mut file| { if b { - file.write_all(b"1").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"1") + .map_err(|e| Error::with_cause(WriteFailed, e)) } else { - file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) } }) } @@ -348,9 +345,11 @@ impl CpuSetController { self.open_path("cpuset.sched_load_balance", true) .and_then(|mut file| { if b { - file.write_all(b"1").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"1") + .map_err(|e| Error::with_cause(WriteFailed, e)) } else { - file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) } }) } @@ -372,9 +371,11 @@ impl CpuSetController { self.open_path("cpuset.memory_migrate", true) .and_then(|mut file| { if b { - file.write_all(b"1").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"1") + .map_err(|e| Error::with_cause(WriteFailed, e)) } else { - file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) } }) } @@ -385,9 +386,11 @@ impl CpuSetController { self.open_path("cpuset.memory_spread_page", true) .and_then(|mut file| { if b { - file.write_all(b"1").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"1") + .map_err(|e| Error::with_cause(WriteFailed, e)) } else { - file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) } }) } @@ -398,9 +401,11 @@ impl CpuSetController { self.open_path("cpuset.memory_spread_slab", true) .and_then(|mut file| { if b { - file.write_all(b"1").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"1") + .map_err(|e| Error::with_cause(WriteFailed, e)) } else { - file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) } }) } @@ -417,9 +422,11 @@ impl CpuSetController { self.open_path("cpuset.memory_pressure_enabled", true) .and_then(|mut file| { if b { - file.write_all(b"1").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"1") + .map_err(|e| Error::with_cause(WriteFailed, e)) } else { - file.write_all(b"0").map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(b"0") + .map_err(|e| Error::with_cause(WriteFailed, e)) } }) } diff --git a/src/devices.rs b/src/devices.rs index 90c386d..1bfa661 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -7,8 +7,8 @@ use std::path::PathBuf; use log::*; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ ControllIdentifier, ControllerInternal, Controllers, DeviceResource, DeviceResources, @@ -124,8 +124,7 @@ impl DevicePermissions { return Ok(v); } for e in s.chars() { - let perm = DevicePermissions::from_char(e) - .ok_or_else(|| Error::new(ParseError))?; + let perm = DevicePermissions::from_char(e).ok_or_else(|| Error::new(ParseError))?; v.push(perm); } @@ -171,19 +170,7 @@ impl ControllIdentifier for DevicesController { } } -impl<'a> From<&'a Subsystem> for &'a DevicesController { - fn from(sub: &'a Subsystem) -> &'a DevicesController { - unsafe { - match sub { - Subsystem::Devices(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::Devices, DevicesController); impl DevicesController { /// Constructs a new `DevicesController` with `oroot` serving as the root of the control group. diff --git a/src/error.rs b/src/error.rs index 70eb4ec..4ef2df2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -34,7 +34,7 @@ pub enum ErrorKind { #[derive(Debug)] pub struct Error { kind: ErrorKind, - cause: Option>, + cause: Option>, } impl fmt::Display for Error { @@ -53,7 +53,7 @@ impl fmt::Display for Error { } impl StdError for Error { - fn cause(&self) -> Option<&StdError> { + fn cause(&self) -> Option<&dyn StdError> { match self.cause { Some(ref x) => Some(&**x), None => None, @@ -63,10 +63,7 @@ impl StdError for Error { impl Error { pub(crate) fn new(kind: ErrorKind) -> Self { - Self { - kind, - cause: None, - } + Self { kind, cause: None } } pub(crate) fn with_cause(kind: ErrorKind, cause: E) -> Self diff --git a/src/freezer.rs b/src/freezer.rs index 632ee27..b4e4fd8 100644 --- a/src/freezer.rs +++ b/src/freezer.rs @@ -5,8 +5,8 @@ use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem}; @@ -59,19 +59,7 @@ impl ControllIdentifier for FreezerController { } } -impl<'a> From<&'a Subsystem> for &'a FreezerController { - fn from(sub: &'a Subsystem) -> &'a FreezerController { - unsafe { - match sub { - Subsystem::Freezer(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::Freezer, FreezerController); impl FreezerController { /// Contructs a new `FreezerController` with `oroot` serving as the root of the control group. diff --git a/src/hierarchies.rs b/src/hierarchies.rs index 368251a..3ae9483 100644 --- a/src/hierarchies.rs +++ b/src/hierarchies.rs @@ -125,7 +125,7 @@ fn find_v1_mount() -> Option { let line = _line.unwrap(); let mut fields = line.split_whitespace(); let index = line.find(" - ").unwrap(); - let mut more_fields = line[index + 3..].split_whitespace().collect::>(); + let more_fields = line[index + 3..].split_whitespace().collect::>(); let fstype = more_fields[0]; if fstype == "tmpfs" && more_fields[2].contains("ro") { let cgroups_mount = fields.nth(4).unwrap(); diff --git a/src/hugetlb.rs b/src/hugetlb.rs index 5c3b1b7..319f8bb 100644 --- a/src/hugetlb.rs +++ b/src/hugetlb.rs @@ -6,12 +6,11 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ - ControllIdentifier, ControllerInternal, Controllers, HugePageResources, Resources, - Subsystem, + ControllIdentifier, ControllerInternal, Controllers, HugePageResources, Resources, Subsystem, }; /// A controller that allows controlling the `hugetlb` subsystem of a Cgroup. @@ -60,24 +59,15 @@ impl ControllIdentifier for HugeTlbController { } } -impl<'a> From<&'a Subsystem> for &'a HugeTlbController { - fn from(sub: &'a Subsystem) -> &'a HugeTlbController { - unsafe { - match sub { - Subsystem::HugeTlb(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::HugeTlb, HugeTlbController); fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); match file.read_to_string(&mut string) { - Ok(_) => string.trim().parse().map_err(|e| Error::with_cause(ParseError, e)), + Ok(_) => string + .trim() + .parse() + .map_err(|e| Error::with_cause(ParseError, e)), Err(e) => Err(Error::with_cause(ReadFailed, e)), } } @@ -125,7 +115,8 @@ impl HugeTlbController { self.open_path( &format!("hugetlb.{}.max_usage_in_bytes", hugetlb_size), false, - ).and_then(read_u64_from) + ) + .and_then(read_u64_from) } /// Set the limit (in bytes) of how much memory can be backed by hugepages of a certain size diff --git a/src/lib.rs b/src/lib.rs index e6ed645..af58379 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,8 +4,12 @@ use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; +#[macro_use] +mod macros; + pub mod blkio; pub mod cgroup; +pub mod cgroup_builder; pub mod cpu; pub mod cpuacct; pub mod cpuset; @@ -20,7 +24,6 @@ pub mod net_prio; pub mod perf_event; pub mod pid; pub mod rdma; -pub mod cgroup_builder; use crate::blkio::BlkIoController; use crate::cpu::CpuController; @@ -108,6 +111,7 @@ impl Controllers { } } +#[macro_use] mod sealed { use super::*; @@ -155,7 +159,6 @@ mod sealed { std::path::Path::new(p).exists() } - } } @@ -191,7 +194,10 @@ pub trait Controller { fn tasks(&self) -> Vec; } -impl Controller for T where T: ControllerInternal { +impl Controller for T +where + T: ControllerInternal, +{ fn control_type(&self) -> Controllers { ControllerInternal::control_type(self) } @@ -249,7 +255,8 @@ impl Controller for T where T: ControllerInternal { } } Ok(v.into_iter().map(CgroupPid::from).collect()) - }).unwrap_or(vec![]) + }) + .unwrap_or(vec![]) } } diff --git a/src/macros.rs b/src/macros.rs new file mode 100644 index 0000000..f62ac53 --- /dev/null +++ b/src/macros.rs @@ -0,0 +1,12 @@ +macro_rules! impl_from_subsystem_for_controller { + ($subsystem:path, $controller:ty) => { + impl<'a> From<&'a Subsystem> for &'a $controller { + fn from(sub: &'a Subsystem) -> &'a $controller { + match sub { + $subsystem(c) => c, + sub => panic!("Attempted to get {} from {:?}", std::stringify!($cont), sub), + } + } + } + }; +} diff --git a/src/memory.rs b/src/memory.rs index d7acaf8..0ca8051 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -6,8 +6,8 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ ControllIdentifier, ControllerInternal, Controllers, MemoryResources, Resources, Subsystem, @@ -109,7 +109,8 @@ fn parse_numa_stat(s: String) -> Result { x.split("=").collect::>()[1] .parse::() .unwrap_or(0) - }).collect() + }) + .collect() }, file_pages: file_line .split(|x| x == ' ' || x == '=') @@ -123,7 +124,8 @@ fn parse_numa_stat(s: String) -> Result { x.split("=").collect::>()[1] .parse::() .unwrap_or(0) - }).collect() + }) + .collect() }, anon_pages: anon_line .split(|x| x == ' ' || x == '=') @@ -137,7 +139,8 @@ fn parse_numa_stat(s: String) -> Result { x.split("=").collect::>()[1] .parse::() .unwrap_or(0) - }).collect() + }) + .collect() }, unevictable_pages: unevict_line .split(|x| x == ' ' || x == '=') @@ -151,7 +154,8 @@ fn parse_numa_stat(s: String) -> Result { x.split("=").collect::>()[1] .parse::() .unwrap_or(0) - }).collect() + }) + .collect() }, hierarchical_total_pages: hier_total_line .split(|x| x == ' ' || x == '=') @@ -165,7 +169,8 @@ fn parse_numa_stat(s: String) -> Result { x.split("=").collect::>()[1] .parse::() .unwrap_or(0) - }).collect() + }) + .collect() }, hierarchical_file_pages: hier_file_line .split(|x| x == ' ' || x == '=') @@ -179,7 +184,8 @@ fn parse_numa_stat(s: String) -> Result { x.split("=").collect::>()[1] .parse::() .unwrap_or(0) - }).collect() + }) + .collect() }, hierarchical_anon_pages: hier_anon_line .split(|x| x == ' ' || x == '=') @@ -193,7 +199,8 @@ fn parse_numa_stat(s: String) -> Result { x.split("=").collect::>()[1] .parse::() .unwrap_or(0) - }).collect() + }) + .collect() }, hierarchical_unevictable_pages: hier_unevict_line .split(|x| x == ' ' || x == '=') @@ -207,7 +214,8 @@ fn parse_numa_stat(s: String) -> Result { x.split("=").collect::>()[1] .parse::() .unwrap_or(0) - }).collect() + }) + .collect() }, }) } @@ -564,11 +572,10 @@ impl MemController { /// Reset the fail counter pub fn reset_fail_count(&self) -> Result<()> { - self.open_path("memory.failcnt", true) - .and_then(|mut file| { - file.write_all("0".to_string().as_ref()) - .map_err(|e| Error::with_cause(WriteFailed, e)) - }) + self.open_path("memory.failcnt", true).and_then(|mut file| { + file.write_all("0".to_string().as_ref()) + .map_err(|e| Error::with_cause(WriteFailed, e)) + }) } /// Reset the kernel memory fail counter @@ -665,24 +672,15 @@ impl ControllIdentifier for MemController { } } -impl<'a> From<&'a Subsystem> for &'a MemController { - fn from(sub: &'a Subsystem) -> &'a MemController { - unsafe { - match sub { - Subsystem::Mem(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::Mem, MemController); fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); match file.read_to_string(&mut string) { - Ok(_) => string.trim().parse().map_err(|e| Error::with_cause(ParseError, e)), + Ok(_) => string + .trim() + .parse() + .map_err(|e| Error::with_cause(ParseError, e)), Err(e) => Err(Error::with_cause(ReadFailed, e)), } } diff --git a/src/net_cls.rs b/src/net_cls.rs index c3057f9..4ac1323 100644 --- a/src/net_cls.rs +++ b/src/net_cls.rs @@ -6,12 +6,11 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ - ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, - Subsystem, + ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, Subsystem, }; /// A controller that allows controlling the `net_cls` subsystem of a Cgroup. @@ -59,24 +58,15 @@ impl ControllIdentifier for NetClsController { } } -impl<'a> From<&'a Subsystem> for &'a NetClsController { - fn from(sub: &'a Subsystem) -> &'a NetClsController { - unsafe { - match sub { - Subsystem::NetCls(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::NetCls, NetClsController); fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); match file.read_to_string(&mut string) { - Ok(_) => string.trim().parse().map_err(|e| Error::with_cause(ParseError, e)), + Ok(_) => string + .trim() + .parse() + .map_err(|e| Error::with_cause(ParseError, e)), Err(e) => Err(Error::with_cause(ReadFailed, e)), } } @@ -97,7 +87,8 @@ impl NetClsController { self.open_path("net_cls.classid", true) .and_then(|mut file| { let s = format!("{:#08X}", class); - file.write_all(s.as_ref()).map_err(|e| Error::with_cause(WriteFailed, e)) + file.write_all(s.as_ref()) + .map_err(|e| Error::with_cause(WriteFailed, e)) }) } diff --git a/src/net_prio.rs b/src/net_prio.rs index 6c2ed7b..7cec0fe 100644 --- a/src/net_prio.rs +++ b/src/net_prio.rs @@ -7,12 +7,11 @@ use std::fs::File; use std::io::{BufRead, BufReader, Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ - ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, - Subsystem, + ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, Subsystem, }; /// A controller that allows controlling the `net_prio` subsystem of a Cgroup. @@ -60,24 +59,15 @@ impl ControllIdentifier for NetPrioController { } } -impl<'a> From<&'a Subsystem> for &'a NetPrioController { - fn from(sub: &'a Subsystem) -> &'a NetPrioController { - unsafe { - match sub { - Subsystem::NetPrio(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::NetPrio, NetPrioController); fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); match file.read_to_string(&mut string) { - Ok(_) => string.trim().parse().map_err(|e| Error::with_cause(ParseError, e)), + Ok(_) => string + .trim() + .parse() + .map_err(|e| Error::with_cause(ParseError, e)), Err(e) => Err(Error::with_cause(ReadFailed, e)), } } diff --git a/src/perf_event.rs b/src/perf_event.rs index 4f52b1b..8c9611e 100644 --- a/src/perf_event.rs +++ b/src/perf_event.rs @@ -43,19 +43,7 @@ impl ControllIdentifier for PerfEventController { } } -impl<'a> From<&'a Subsystem> for &'a PerfEventController { - fn from(sub: &'a Subsystem) -> &'a PerfEventController { - unsafe { - match sub { - Subsystem::PerfEvent(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::PerfEvent, PerfEventController); impl PerfEventController { /// Constructs a new `PerfEventController` with `oroot` serving as the root of the control group. diff --git a/src/pid.rs b/src/pid.rs index d7f42d2..8cc2d1f 100644 --- a/src/pid.rs +++ b/src/pid.rs @@ -6,8 +6,8 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ ControllIdentifier, ControllerInternal, Controllers, PidResources, Resources, Subsystem, @@ -82,24 +82,15 @@ impl ControllIdentifier for PidController { } } -impl<'a> From<&'a Subsystem> for &'a PidController { - fn from(sub: &'a Subsystem) -> &'a PidController { - unsafe { - match sub { - Subsystem::Pid(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::Pid, PidController); fn read_u64_from(mut file: File) -> Result { let mut string = String::new(); match file.read_to_string(&mut string) { - Ok(_) => string.trim().parse().map_err(|e| Error::with_cause(ParseError, e)), + Ok(_) => string + .trim() + .parse() + .map_err(|e| Error::with_cause(ParseError, e)), Err(e) => Err(Error::with_cause(ReadFailed, e)), } } @@ -145,14 +136,16 @@ impl PidController { let mut string = String::new(); let res = file.read_to_string(&mut string); match res { - Ok(_) => if string.trim() == "max" { - Ok(PidMax::Max) - } else { - match string.trim().parse() { - Ok(val) => Ok(PidMax::Value(val)), - Err(e) => Err(Error::with_cause(ParseError, e)), + Ok(_) => { + if string.trim() == "max" { + Ok(PidMax::Max) + } else { + match string.trim().parse() { + Ok(val) => Ok(PidMax::Value(val)), + Err(e) => Err(Error::with_cause(ParseError, e)), + } } - }, + } Err(e) => Err(Error::with_cause(ReadFailed, e)), } }) diff --git a/src/rdma.rs b/src/rdma.rs index fb9dcc6..a66bc71 100644 --- a/src/rdma.rs +++ b/src/rdma.rs @@ -6,8 +6,8 @@ use std::fs::File; use std::io::{Read, Write}; use std::path::PathBuf; -use crate::error::*; use crate::error::ErrorKind::*; +use crate::error::*; use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem}; @@ -46,19 +46,7 @@ impl ControllIdentifier for RdmaController { } } -impl<'a> From<&'a Subsystem> for &'a RdmaController { - fn from(sub: &'a Subsystem) -> &'a RdmaController { - unsafe { - match sub { - Subsystem::Rdma(c) => c, - _ => { - assert_eq!(1, 0); - ::std::mem::uninitialized() - } - } - } - } -} +impl_from_subsystem_for_controller!(Subsystem::Rdma, RdmaController); fn read_string_from(mut file: File) -> Result { let mut string = String::new(); diff --git a/tests/builder.rs b/tests/builder.rs index 45c1112..cdd9618 100644 --- a/tests/builder.rs +++ b/tests/builder.rs @@ -1,22 +1,23 @@ //! Some simple tests covering the builder pattern for control groups. -use cgroups::*; +use cgroups::blkio::*; +use cgroups::cgroup_builder::*; use cgroups::cpu::*; use cgroups::devices::*; -use cgroups::pid::*; +use cgroups::hugetlb::*; use cgroups::memory::*; use cgroups::net_cls::*; -use cgroups::hugetlb::*; -use cgroups::blkio::*; -use cgroups::cgroup_builder::*; +use cgroups::pid::*; +use cgroups::*; #[test] pub fn test_cpu_res_build() { let v1 = crate::hierarchies::V1::new(); let cg: Cgroup = CgroupBuilder::new("test_cpu_res_build", &v1) .cpu() - .shares(85) - .done() - .build(); + .shares(85) + .done() + .build() + .unwrap(); { let cpu: &CpuController = cg.controller_of().unwrap(); @@ -32,11 +33,12 @@ pub fn test_memory_res_build() { let v1 = crate::hierarchies::V1::new(); let cg: Cgroup = CgroupBuilder::new("test_memory_res_build", &v1) .memory() - .kernel_memory_limit(128 * 1024 * 1024) - .swappiness(70) - .memory_hard_limit(1024 * 1024 * 1024) - .done() - .build(); + .kernel_memory_limit(128 * 1024 * 1024) + .swappiness(70) + .memory_hard_limit(1024 * 1024 * 1024) + .done() + .build() + .unwrap(); { let c: &MemController = cg.controller_of().unwrap(); @@ -53,9 +55,10 @@ pub fn test_pid_res_build() { let v1 = crate::hierarchies::V1::new(); let cg: Cgroup = CgroupBuilder::new("test_pid_res_build", &v1) .pid() - .maximum_number_of_processes(PidMax::Value(123)) - .done() - .build(); + .maximum_number_of_processes(PidMax::Value(123)) + .done() + .build() + .unwrap(); { let c: &PidController = cg.controller_of().unwrap(); @@ -72,23 +75,24 @@ pub fn test_devices_res_build() { let v1 = crate::hierarchies::V1::new(); let cg: Cgroup = CgroupBuilder::new("test_devices_res_build", &v1) .devices() - .device(1, 6, DeviceType::Char, true, - vec![DevicePermissions::Read]) - .done() - .build(); + .device(1, 6, DeviceType::Char, true, vec![DevicePermissions::Read]) + .done() + .build() + .unwrap(); { let c: &DevicesController = cg.controller_of().unwrap(); assert!(c.allowed_devices().is_ok()); - assert_eq!(c.allowed_devices().unwrap(), vec![ - DeviceResource { - allow: true, - devtype: DeviceType::Char, - major: 1, - minor: 6, - access: vec![DevicePermissions::Read], - } - ]); + assert_eq!( + c.allowed_devices().unwrap(), + vec![DeviceResource { + allow: true, + devtype: DeviceType::Char, + major: 1, + minor: 6, + access: vec![DevicePermissions::Read], + }] + ); } cg.delete(); } @@ -98,9 +102,10 @@ pub fn test_network_res_build() { let v1 = crate::hierarchies::V1::new(); let cg: Cgroup = CgroupBuilder::new("test_network_res_build", &v1) .network() - .class_id(1337) - .done() - .build(); + .class_id(1337) + .done() + .build() + .unwrap(); { let c: &NetClsController = cg.controller_of().unwrap(); @@ -115,14 +120,18 @@ pub fn test_hugepages_res_build() { let v1 = crate::hierarchies::V1::new(); let cg: Cgroup = CgroupBuilder::new("test_hugepages_res_build", &v1) .hugepages() - .limit("2MB".to_string(), 4 * 2 * 1024 * 1024) - .done() - .build(); + .limit("2MB".to_string(), 4 * 2 * 1024 * 1024) + .done() + .build() + .unwrap(); { let c: &HugeTlbController = cg.controller_of().unwrap(); assert!(c.limit_in_bytes(&"2MB".to_string()).is_ok()); - assert_eq!(c.limit_in_bytes(&"2MB".to_string()).unwrap(), 4 * 2 * 1024 * 1024); + assert_eq!( + c.limit_in_bytes(&"2MB".to_string()).unwrap(), + 4 * 2 * 1024 * 1024 + ); } cg.delete(); } @@ -132,9 +141,10 @@ pub fn test_blkio_res_build() { let v1 = crate::hierarchies::V1::new(); let cg: Cgroup = CgroupBuilder::new("test_blkio_res_build", &v1) .blkio() - .weight(100) - .done() - .build(); + .weight(100) + .done() + .build() + .unwrap(); { let c: &BlkIoController = cg.controller_of().unwrap(); diff --git a/tests/cgroup.rs b/tests/cgroup.rs index 8b15d9a..2315dca 100644 --- a/tests/cgroup.rs +++ b/tests/cgroup.rs @@ -8,7 +8,8 @@ fn test_tasks_iterator() { let cg = Cgroup::new(&hier, String::from("test_tasks_iterator")); { // Add a task to the control group. - cg.add_task(CgroupPid::from(pid)); + cg.add_task(CgroupPid::from(pid)) + .expect("Failed to add task to cgroup"); let mut tasks = cg.tasks().into_iter(); // Verify that the task is indeed in the control group assert_eq!(tasks.next(), Some(CgroupPid::from(pid))); diff --git a/tests/devices.rs b/tests/devices.rs index 2fbb305..b936023 100644 --- a/tests/devices.rs +++ b/tests/devices.rs @@ -11,16 +11,18 @@ fn test_devices_parsing() { let devices: &DevicesController = cg.controller_of().unwrap(); // Deny access to all devices first - devices.deny_device( - DeviceType::All, - -1, - -1, - &vec![ - DevicePermissions::Read, - DevicePermissions::Write, - DevicePermissions::MkNod, - ], - ); + devices + .deny_device( + DeviceType::All, + -1, + -1, + &vec![ + DevicePermissions::Read, + DevicePermissions::Write, + DevicePermissions::MkNod, + ], + ) + .expect("Failed to deny device"); // Acquire the list of allowed devices after we denied all let allowed_devices = devices.allowed_devices(); // Verify that there are no devices that we can access. @@ -28,7 +30,9 @@ fn test_devices_parsing() { assert_eq!(allowed_devices.unwrap(), Vec::new()); // Now add mknod access to /dev/null device - devices.allow_device(DeviceType::Char, 1, 3, &vec![DevicePermissions::MkNod]); + devices + .allow_device(DeviceType::Char, 1, 3, &vec![DevicePermissions::MkNod]) + .expect("Failed to allow device"); let allowed_devices = devices.allowed_devices(); assert!(allowed_devices.is_ok()); let allowed_devices = allowed_devices.unwrap(); @@ -45,7 +49,9 @@ fn test_devices_parsing() { ); // Now deny, this device explicitly. - devices.deny_device(DeviceType::Char, 1, 3, &DevicePermissions::all()); + devices + .deny_device(DeviceType::Char, 1, 3, &DevicePermissions::all()) + .expect("Failed to deny device"); // Finally, check that. let allowed_devices = devices.allowed_devices(); // Verify that there are no devices that we can access. diff --git a/tests/pids.rs b/tests/pids.rs index 4c91e54..29b27e0 100644 --- a/tests/pids.rs +++ b/tests/pids.rs @@ -1,22 +1,22 @@ //! Integration tests about the pids subsystem use cgroups::pid::{PidController, PidMax}; +use cgroups::Cgroup; use cgroups::Controller; -use cgroups::{Cgroup, CgroupPid, PidResources, Resources}; use nix::sys::wait::{waitpid, WaitStatus}; -use nix::unistd::{fork, ForkResult, Pid}; +use nix::unistd::{fork, ForkResult}; use libc::pid_t; -use std::thread; - #[test] fn create_and_delete_cgroup() { let hier = cgroups::hierarchies::V1::new(); let cg = Cgroup::new(&hier, String::from("create_and_delete_cgroup")); { let pidcontroller: &PidController = cg.controller_of().unwrap(); - pidcontroller.set_pid_max(PidMax::Value(1337)); + pidcontroller + .set_pid_max(PidMax::Value(1337)) + .expect("Failed to set max pid"); let max = pidcontroller.get_pid_max(); assert!(max.is_ok()); assert_eq!(max.unwrap(), PidMax::Value(1337)); @@ -61,12 +61,13 @@ fn test_pid_events_is_not_zero() { match fork() { Ok(ForkResult::Parent { child, .. }) => { // move the process into the control group - pids.add_task(&(pid_t::from(child) as u64).into()); + pids.add_task(&(pid_t::from(child) as u64).into()).unwrap(); println!("added task to cg: {:?}", child); // Set limit to one - pids.set_pid_max(PidMax::Value(1)); + pids.set_pid_max(PidMax::Value(1)) + .expect("Failed to set max pid"); println!("err = {:?}", pids.get_pid_max()); // wait on the child diff --git a/tests/resources.rs b/tests/resources.rs index c612df1..882afed 100644 --- a/tests/resources.rs +++ b/tests/resources.rs @@ -14,7 +14,7 @@ fn pid_resources() { }, ..Default::default() }; - cg.apply(&res); + cg.apply(&res).expect("Failed to add resources to cgroup"); // verify let pidcontroller: &PidController = cg.controller_of().unwrap();