use std::io::Write;
use std::path::PathBuf;
use crate::fs::error::ErrorKind::*;
use crate::fs::error::*;
use crate::fs::{read_string_from, read_u64_from};
use crate::fs::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};
#[derive(Debug, Clone)]
pub struct CpuAcctController {
base: PathBuf,
path: PathBuf,
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CpuAcct {
pub stat: String,
pub usage: u64,
pub usage_all: String,
pub usage_percpu: String,
pub usage_percpu_sys: String,
pub usage_percpu_user: String,
pub usage_sys: u64,
pub usage_user: u64,
}
impl ControllerInternal for CpuAcctController {
fn control_type(&self) -> Controllers {
Controllers::CpuAcct
}
fn get_path(&self) -> &PathBuf {
&self.path
}
fn get_path_mut(&mut self) -> &mut PathBuf {
&mut self.path
}
fn get_base(&self) -> &PathBuf {
&self.base
}
fn apply(&self, _res: &Resources) -> Result<()> {
Ok(())
}
}
impl ControllIdentifier for CpuAcctController {
fn controller_type() -> Controllers {
Controllers::CpuAcct
}
}
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);
let v = std::mem::MaybeUninit::uninit();
v.assume_init()
}
}
}
}
}
impl CpuAcctController {
pub fn new(point: PathBuf, root: PathBuf) -> Self {
Self {
base: root,
path: point,
}
}
pub fn cpuacct(&self) -> CpuAcct {
CpuAcct {
stat: self
.open_path("cpuacct.stat", false)
.and_then(read_string_from)
.unwrap_or_default(),
usage: self
.open_path("cpuacct.usage", false)
.and_then(read_u64_from)
.unwrap_or(0),
usage_all: self
.open_path("cpuacct.usage_all", false)
.and_then(read_string_from)
.unwrap_or_default(),
usage_percpu: self
.open_path("cpuacct.usage_percpu", false)
.and_then(read_string_from)
.unwrap_or_default(),
usage_percpu_sys: self
.open_path("cpuacct.usage_percpu_sys", false)
.and_then(read_string_from)
.unwrap_or_default(),
usage_percpu_user: self
.open_path("cpuacct.usage_percpu_user", false)
.and_then(read_string_from)
.unwrap_or_default(),
usage_sys: self
.open_path("cpuacct.usage_sys", false)
.and_then(read_u64_from)
.unwrap_or(0),
usage_user: self
.open_path("cpuacct.usage_user", false)
.and_then(read_u64_from)
.unwrap_or(0),
}
}
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("cpuacct.usage".to_string(), "0".to_string()), e)
})
})
}
}