add get_stat

This commit is contained in:
mii443
2024-10-17 07:35:35 +00:00
parent 3c2dbeaa93
commit af5fa6fcbf
5 changed files with 75 additions and 1 deletions

View File

@ -7,4 +7,5 @@ fn main() {
println!("{:?}", cgroup.read("cgroup.type"));
println!("{:?}", cgroup.get_controllers());
println!("{:?}", cgroup.get_procs());
println!("{:?}", cgroup.get_stat());
}

View File

@ -5,7 +5,7 @@ use std::{
str::FromStr,
};
use super::controller::Controller;
use super::{cgroup_stat::CGroupStat, controller::Controller};
pub struct CGroup {
pub path: PathBuf,
@ -76,4 +76,10 @@ impl CGroup {
Ok(procs)
}
pub fn get_stat(&self) -> Result<CGroupStat, std::io::Error> {
let stat = self.read("cgroup.stat")?;
Ok(CGroupStat::from_str(&stat).unwrap())
}
}

31
src/cgroup/cgroup_stat.rs Normal file
View File

@ -0,0 +1,31 @@
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CGroupStat {
pub nr_descendants: u64,
pub nr_dying_descendants: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseCGroupStatError;
impl FromStr for CGroupStat {
type Err = ParseCGroupStatError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut stat = Self {
nr_descendants: 0,
nr_dying_descendants: 0,
};
s.lines()
.map(|l| l.trim().split(" ").collect())
.for_each(|s: Vec<&str>| match &*s[0] {
"nr_descendants" => stat.nr_descendants = u64::from_str(s[1]).unwrap(),
"nr_dying_descendants" => stat.nr_dying_descendants = u64::from_str(s[1]).unwrap(),
_ => (),
});
Ok(stat)
}
}

35
src/cgroup/controller.rs Normal file
View File

@ -0,0 +1,35 @@
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Controller {
Cpu,
Cpuset,
Memory,
Io,
Hugetlb,
Misc,
Pids,
Rdma,
Unknown,
}
#[derive(Debug, PartialEq, Eq)]
pub struct ParseControllerError;
impl FromStr for Controller {
type Err = ParseControllerError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match &*s {
"cpu" => Ok(Self::Cpu),
"cpuset" => Ok(Self::Cpuset),
"memory" => Ok(Self::Memory),
"io" => Ok(Self::Io),
"hugetlb" => Ok(Self::Hugetlb),
"misc" => Ok(Self::Misc),
"pids" => Ok(Self::Pids),
"rdma" => Ok(Self::Rdma),
_ => Err(ParseControllerError),
}
}
}

View File

@ -1,2 +1,3 @@
pub mod cgroup;
pub mod cgroup_stat;
pub mod controller;