From eab554135d918c8b7a1e345ffe0fe7bf93d7b653 Mon Sep 17 00:00:00 2001 From: Masato Imai Date: Mon, 21 Oct 2024 02:21:20 +0000 Subject: [PATCH] add cgroup enter to box enter --- src/bin/izoli.rs | 14 ++++++++++---- src/cgroup/cgroup.rs | 8 ++++++++ src/izolibox.rs | 18 +++++++++++++++--- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/src/bin/izoli.rs b/src/bin/izoli.rs index c42f337..142e0e0 100644 --- a/src/bin/izoli.rs +++ b/src/bin/izoli.rs @@ -1,7 +1,10 @@ -use izolilib::{cgroup::cgroup::CGroup, izolibox::IzoliBox}; +use izolilib::{ + cgroup::cgroup::CGroup, + izolibox::{CGroupOption, IzoliBox}, +}; fn main() { - let cgroup = CGroup::new("test").unwrap(); + let cgroup = CGroup::new("izoli").unwrap(); println!("{:?}", cgroup.get_root_path()); println!("{}", cgroup.check_status()); println!("{:?}", cgroup.read("cgroup.type")); @@ -13,12 +16,15 @@ fn main() { println!("{:?}", cgroup.get_max_depth()); 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 .enter(Box::new(|| { println!("Isolated process: {}", std::process::id()); + println!("cgroup: {:?}", CGroup::get_self_cgroup()); 127 })) .unwrap(); diff --git a/src/cgroup/cgroup.rs b/src/cgroup/cgroup.rs index 3f94e1c..91035f4 100644 --- a/src/cgroup/cgroup.rs +++ b/src/cgroup/cgroup.rs @@ -25,6 +25,14 @@ impl CGroup { Ok(cgroup) } + pub fn get_self_cgroup() -> Result { + 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> { let root = self.get_root_path(); fs::create_dir_all(root) diff --git a/src/izolibox.rs b/src/izolibox.rs index b84416d..f624547 100644 --- a/src/izolibox.rs +++ b/src/izolibox.rs @@ -4,13 +4,20 @@ use nix::{ unistd::Pid, }; +use crate::cgroup::cgroup::CGroup; + const STACK_SIZE: usize = 8192; -pub struct IzoliBox {} +pub struct CGroupOption {} + +pub struct IzoliBox { + pub id: usize, + pub cgroup_option: Option, +} impl IzoliBox { - pub fn new() -> Self { - Self {} + pub fn new(id: usize, cgroup_option: Option) -> Self { + Self { id, cgroup_option } } pub fn enter(&self, callback: CloneCb<'_>) -> Result { @@ -20,6 +27,11 @@ impl IzoliBox { | CloneFlags::CLONE_NEWIPC | 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)) } } }