add cgroup enter to box enter

This commit is contained in:
Masato Imai
2024-10-21 02:21:20 +00:00
parent 0d8386dde0
commit eab554135d
3 changed files with 33 additions and 7 deletions

View File

@ -1,7 +1,10 @@
use izolilib::{cgroup::cgroup::CGroup, izolibox::IzoliBox}; use izolilib::{
cgroup::cgroup::CGroup,
izolibox::{CGroupOption, IzoliBox},
};
fn main() { fn main() {
let cgroup = CGroup::new("test").unwrap(); let cgroup = CGroup::new("izoli").unwrap();
println!("{:?}", cgroup.get_root_path()); println!("{:?}", cgroup.get_root_path());
println!("{}", cgroup.check_status()); println!("{}", cgroup.check_status());
println!("{:?}", cgroup.read("cgroup.type")); println!("{:?}", cgroup.read("cgroup.type"));
@ -13,12 +16,15 @@ fn main() {
println!("{:?}", cgroup.get_max_depth()); println!("{:?}", cgroup.get_max_depth());
println!("{:?}", cgroup.get_max_descendants()); println!("{:?}", cgroup.get_max_descendants());
cgroup.enter().unwrap(); cgroup
.add_subtree_control(cgroup.get_controllers().unwrap())
.unwrap();
let izolibox = IzoliBox::new(); let izolibox = IzoliBox::new(1, Some(CGroupOption {}));
let pid = izolibox let pid = izolibox
.enter(Box::new(|| { .enter(Box::new(|| {
println!("Isolated process: {}", std::process::id()); println!("Isolated process: {}", std::process::id());
println!("cgroup: {:?}", CGroup::get_self_cgroup());
127 127
})) }))
.unwrap(); .unwrap();

View File

@ -25,6 +25,14 @@ impl CGroup {
Ok(cgroup) Ok(cgroup)
} }
pub fn get_self_cgroup() -> Result<String, std::io::Error> {
let mut file = std::fs::File::open("/proc/self/cgroup")?;
let mut buf = String::default();
file.read_to_string(&mut buf)?;
Ok(buf.trim().to_string())
}
fn create(&self) -> Result<(), std::io::Error> { fn create(&self) -> Result<(), std::io::Error> {
let root = self.get_root_path(); let root = self.get_root_path();
fs::create_dir_all(root) fs::create_dir_all(root)

View File

@ -4,13 +4,20 @@ use nix::{
unistd::Pid, unistd::Pid,
}; };
use crate::cgroup::cgroup::CGroup;
const STACK_SIZE: usize = 8192; const STACK_SIZE: usize = 8192;
pub struct IzoliBox {} pub struct CGroupOption {}
pub struct IzoliBox {
pub id: usize,
pub cgroup_option: Option<CGroupOption>,
}
impl IzoliBox { impl IzoliBox {
pub fn new() -> Self { pub fn new(id: usize, cgroup_option: Option<CGroupOption>) -> Self {
Self {} Self { id, cgroup_option }
} }
pub fn enter(&self, callback: CloneCb<'_>) -> Result<Pid, nix::errno::Errno> { pub fn enter(&self, callback: CloneCb<'_>) -> Result<Pid, nix::errno::Errno> {
@ -20,6 +27,11 @@ impl IzoliBox {
| CloneFlags::CLONE_NEWIPC | CloneFlags::CLONE_NEWIPC
| CloneFlags::CLONE_NEWPID; | CloneFlags::CLONE_NEWPID;
if let Some(_cgroup_option) = &self.cgroup_option {
let cgroup = CGroup::new(&format!("izoli/box_{}", self.id)).unwrap();
cgroup.enter().unwrap();
}
unsafe { sched::clone(callback, &mut stack, flags, Some(SIGCHLD)) } unsafe { sched::clone(callback, &mut stack, flags, Some(SIGCHLD)) }
} }
} }