### Get Default Cgroup Setup Source: https://docs.rs/libcgroups/latest/src/libcgroups/common.rs.html Retrieves the cgroup setup for the default cgroup root path (`/sys/fs/cgroup`). This is a convenience function that calls `get_cgroup_setup_with_root`. ```rust pub fn get_cgroup_setup() -> Result { get_cgroup_setup_with_root(Path::new(DEFAULT_CGROUP_ROOT)) } ``` -------------------------------- ### Start Transient Unit with Properties Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/dbus.rs.html Starts a transient systemd unit with specified properties. Useful for creating temporary container units with accounting and dependency settings. ```rust let mut properties: Vec<(&str, Variant)> = Vec::with_capacity(6); properties.push(( "Description", Variant::String(format!("youki container {container_name}")), )); // if we create a slice, the parent is defined via a Wants= // otherwise, we use Slice= if unit_name.ends_with("slice") { properties.push(("Wants", Variant::String(parent.to_owned()))); } else { properties.push(("Slice", Variant::String(parent.to_owned()))); properties.push(("Delegate", Variant::Bool(true))); } properties.push(("MemoryAccounting", Variant::Bool(true))); properties.push(("CPUAccounting", Variant::Bool(true))); properties.push(("IOAccounting", Variant::Bool(true))); properties.push(("TasksAccounting", Variant::Bool(true))); properties.push(("DefaultDependencies", Variant::Bool(false))); properties.push(("PIDs", Variant::ArrayU32(vec![pid]))); tracing::debug!("Starting transient unit: {:?}", properties); let props = properties .into_iter() .map(|(k, v)| Structure::new(k.into(), v)) .collect(); proxy .start_transient_unit(unit_name, "replace", props, vec![]) .map_err(|err| SystemdClientError::FailedTransient { err: Box::new(err), unit_name: unit_name.into(), parent: parent.into(), })?; ``` -------------------------------- ### get_cgroup_setup_with_root Source: https://docs.rs/libcgroups/latest/libcgroups/common/fn.get_cgroup_setup_with_root.html Determines the cgroup setup of the system. Systems typically have one of three setups: Unified (pure cgroup v2), Legacy (pure cgroup v1), or Hybrid (cgroup v1 with an additional, controller-less unified hierarchy). ```APIDOC ## Function get_cgroup_setup_with_root ### Signature ```rust pub fn get_cgroup_setup_with_root( root_path: &Path, ) -> Result ``` ### Parameters * `root_path` (&Path): The path to the cgroup root directory. ### Returns * `Result`: Ok containing the `CgroupSetup` if successful, or an `Err` containing `GetCgroupSetupError` if an error occurred. ``` -------------------------------- ### Memory Cgroup Limits Example Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/memory.rs.html This example demonstrates how to define and assert expected memory cgroup limits, including hierarchical memory and memory swap limits. It's useful for testing cgroup configurations. ```rust let expected = vec![ ("hierarchical_memory_limit".to_owned(), 9223372036854771712), ("hierarchical_memsw_limit".to_owned(), 9223372036854771712), ] .iter() .cloned() .collect(); assert_eq!(actual, expected); } } ``` -------------------------------- ### Start Transient Unit Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/proxy.rs.html Starts a transient systemd unit with specified properties and auxiliary data. ```APIDOC ## POST /unit/transient ### Description Starts a transient systemd unit. ### Method POST ### Endpoint `/unit/transient` ### Parameters #### Request Body - **name** (string) - Required - The name for the transient unit. - **mode** (string) - Required - The mode to start the unit in (e.g., 'replace'). - **properties** (array of Structure) - Required - Properties for the unit. - **aux** (array of Structure>>) - Required - Auxiliary data for the unit. ``` -------------------------------- ### Start Transient Systemd Unit Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/proxy.rs.html Starts a transient systemd unit with specified properties and auxiliary data. Note that the unit might not be fully started immediately after this method returns. ```rust pub fn start_transient_unit( &self, name: &str, mode: &str, properties: Vec>, aux: Vec>>>, ) -> Result { self.method_call( "org.freedesktop.systemd1.Manager", "StartTransientUnit", Some((name, mode, properties, aux)), ) } ``` -------------------------------- ### Hugetlb Limit Configuration Example Source: https://docs.rs/libcgroups/latest/src/libcgroups/v2/hugetlb.rs.html Demonstrates setting and asserting hugetlb limit configurations. Ensure the `HugetlbLimit` struct is correctly defined and populated. ```rust let expected = HugetlbLimit { limit: 1024, fail_count: 5, }; assert_eq!(actual, expected); } } ``` -------------------------------- ### get_cgroup_setup Source: https://docs.rs/libcgroups/latest/libcgroups/common/fn.get_cgroup_setup.html Retrieves the current cgroup setup. Returns a Result containing CgroupSetup on success or GetCgroupSetupError on failure. ```APIDOC ## Function get_cgroup_setup ### Signature ```rust pub fn get_cgroup_setup() -> Result ``` ### Description This function retrieves the current cgroup setup of the system. It returns a `Result` which, on success, contains a `CgroupSetup` enum variant indicating the detected cgroup version and configuration. If an error occurs during the detection process, it returns a `GetCgroupSetupError`. ### Return Value - `Ok(CgroupSetup)`: If the cgroup setup is successfully determined. - `Err(GetCgroupSetupError)`: If an error occurs while trying to determine the cgroup setup. ``` -------------------------------- ### get_cgroup_setup Source: https://docs.rs/libcgroups/latest/src/libcgroups/common.rs.html Determines the current cgroup setup (Unified, Hybrid, or Legacy) on the system using the default cgroup root path. ```APIDOC ## get_cgroup_setup ### Description Determines the current cgroup setup (Unified, Hybrid, or Legacy) on the system using the default cgroup root path. ### Parameters None ### Request Example ```rust let setup = get_cgroup_setup()?; ``` ### Response #### Success Response (Result) - **CgroupSetup**: An enum representing the cgroup setup type: - **Unified**: Cgroup v2 is in use. - **Hybrid**: Both Cgroup v1 and v2 are in use. - **Legacy**: Only Cgroup v1 is in use. #### Error Response (GetCgroupSetupError) - **WrappedIo**: An I/O error occurred. - **NonDefault**: The cgroup root is not the default. - **FailedToDetect**: Failed to detect the cgroup setup. ### Response Example ```rust match get_cgroup_setup() { Ok(CgroupSetup::Unified) => println!("Cgroup v2 detected"), Ok(CgroupSetup::Hybrid) => println!("Hybrid cgroup detected"), Ok(CgroupSetup::Legacy) => println!("Cgroup v1 detected"), Err(e) => eprintln!("Error detecting cgroup setup: {:?}", e), } ``` ``` -------------------------------- ### Detect Cgroup Setup with Specific Root Source: https://docs.rs/libcgroups/latest/src/libcgroups/common.rs.html Determines the cgroup setup (Unified, Hybrid, or Legacy) for a given root path. It checks for the presence of cgroup v1 and v2 filesystem types. ```rust pub fn get_cgroup_setup_with_root(root_path: &Path) -> Result { match statfs(root_path).map_err(std::io::Error::other).wrap_other(root_path) { Ok(stat) if stat.filesystem_type() == CGROUP2_SUPER_MAGIC => { return Ok(CgroupSetup::Unified); } Ok(stat) if stat.filesystem_type() == TMPFS_MAGIC => { let unified = &Path::new(root_path).join("unified"); if Path::new(unified).exists() { let stat = statfs(unified) .map_err(std::io::Error::other) .wrap_other(unified)?; if stat.filesystem_type() == CGROUP2_SUPER_MAGIC { return Ok(CgroupSetup::Hybrid); } } return Ok(CgroupSetup::Legacy); } Ok(_) => Err(GetCgroupSetupError::NonDefault), Err(err) => Err(GetCgroupSetupError::WrappedIo(err)), } } ``` -------------------------------- ### get_cgroup_setup_with_root Source: https://docs.rs/libcgroups/latest/src/libcgroups/common.rs.html Determines the cgroup setup (Unified, Legacy, or Hybrid) of the system based on the provided root path. It inspects the filesystem type to differentiate between cgroup v1 and v2 hierarchies. ```APIDOC ## get_cgroup_setup_with_root ### Description Detects the cgroup setup of the system (Unified, Legacy, or Hybrid) by examining the filesystem type at the given root path. This is crucial for understanding how cgroup resources are managed. ### Unified Cgroup Setup Pure cgroup v2 system. ### Legacy Cgroup Setup Pure cgroup v1 system. ### Hybrid Cgroup Setup A cgroup v1 system with an additional, unused cgroup v2 hierarchy. ### Signature ```rust pub fn get_cgroup_setup_with_root(root_path: &Path) -> Result ``` ### Parameters * `root_path`: A reference to a `Path` representing the root directory of the cgroup filesystem to inspect. ### Returns * `Ok(CgroupSetup)` indicating the detected cgroup setup (Unified, Legacy, or Hybrid). * `Err(GetCgroupSetupError)` if an I/O error occurs, if a non-default cgroup root is encountered and not supported, or if detection fails. ``` -------------------------------- ### Start Transient Unit Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/dbus.rs.html Starts a transient systemd unit with specified properties. This is used to manage container lifecycles and resource allocation. ```APIDOC ## start_transient_unit ### Description Starts a transient systemd unit with specified properties. This is used to manage container lifecycles and resource allocation. ### Method `start_transient_unit` ### Parameters - `unit_name` (string) - The name of the unit to start. - `mode` (string) - The mode for starting the unit (e.g., "replace"). - `properties` (Vec>) - A vector of properties to set for the unit. - `dependencies` (Vec) - A vector of unit names that this unit depends on. ### Return Value - `Result<()>` - Ok(()) on success, or a `SystemdClientError` on failure. ``` -------------------------------- ### Example of Recasting CPU Quota Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/unified.rs.html Demonstrates how to recast a CPU quota value from a generic variant to a specific U64 type for assertion. ```rust assert_eq!(recast!(cpu_quota, Variant)?, Variant::U64(500000)); ``` -------------------------------- ### Apply Freezer Controller Options Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/freezer.rs.html Applies the specified Freezer controller options to a cgroup path. This example demonstrates setting the freezer state and verifying that the state is correctly applied and tasks are added to the cgroup. ```rust let state = FreezerState::Undefined; let controller_opt = ControllerOpt { resources: &linux_resources, freezer_state: Some(state), oom_score_adj: None, disable_oom_killer: false, }; let pid = Pid::from_raw(1002); let old_state_content = std::fs::read_to_string(tmp.path().join(CGROUP_FREEZER_STATE)) .expect("read to string"); Freezer::add_task(pid, tmp.path()).expect("freezer add task"); ::apply(&controller_opt, tmp.path()).expect("freezer apply"); let state_content = std::fs::read_to_string(tmp.path().join(CGROUP_FREEZER_STATE)) .expect("read to string"); assert_eq!(old_state_content, state_content); let pid_content = std::fs::read_to_string(tmp.path().join(CGROUP_PROCS)).expect("read to string"); assert_eq!(pid_content, "1002"); } } } ``` -------------------------------- ### CgroupSetup Enum Definition Source: https://docs.rs/libcgroups/latest/libcgroups/common/enum.CgroupSetup.html Defines the possible configurations for cgroup setup: Hybrid, Legacy, and Unified. ```rust pub enum CgroupSetup { Hybrid, Legacy, Unified, } ``` -------------------------------- ### Create Cgroup Manager with Custom Root Source: https://docs.rs/libcgroups/latest/src/libcgroups/common.rs.html Creates a cgroup manager (v1, v2, or systemd) with a specified root path and configuration. It first detects the cgroup setup and then instantiates the appropriate manager. ```rust pub fn create_cgroup_manager_with_root(root_path: Option<&Path>, config: CgroupConfig) -> Result { let root = match root_path { Some(p) => p, None => Path::new(DEFAULT_CGROUP_ROOT), }; let cgroup_setup = get_cgroup_setup_with_root(root).map_err(|err| match err { GetCgroupSetupError::WrappedIo(err) => CreateCgroupSetupError::WrappedIo(err), GetCgroupSetupError::NonDefault => CreateCgroupSetupError::NonDefault, GetCgroupSetupError::FailedToDetect => CreateCgroupSetupError::FailedToDetect, })?; let cgroup_path = config.cgroup_path.as_path(); match cgroup_setup { CgroupSetup::Legacy | CgroupSetup::Hybrid => { Ok(create_v1_cgroup_manager(cgroup_path)?.any()) } CgroupSetup::Unified => { if cgroup_path.is_absolute() || !config.systemd_cgroup { return Ok(create_v2_cgroup_manager(root, cgroup_path)?.any()); } Ok( create_systemd_cgroup_manager(root, cgroup_path, config.container_name.as_str())? .any(), ) } } } ``` -------------------------------- ### create_cgroup_manager_with_root Source: https://docs.rs/libcgroups/latest/src/libcgroups/common.rs.html Creates a cgroup manager with a specified root path. If the root path is not provided, it defaults to `/sys/fs/cgroup`. This function determines the cgroup setup (legacy, hybrid, or unified) and instantiates the appropriate manager. ```APIDOC ## create_cgroup_manager_with_root ### Description Creates a cgroup manager with a specified root path. If the root path is not provided, it defaults to `/sys/fs/cgroup`. This function determines the cgroup setup (legacy, hybrid, or unified) and instantiates the appropriate manager. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **root_path** (Option<&Path>) - The root path for cgroup management. Defaults to `/sys/fs/cgroup` if None. - **config** (CgroupConfig) - Configuration for the cgroup manager, including `cgroup_path`, `systemd_cgroup`, and `container_name`. ### Request Example ```rust let config = CgroupConfig { cgroup_path: PathBuf::from("/my/cgroup/path"), systemd_cgroup: false, container_name: "my_container".to_string(), }; let manager = create_cgroup_manager_with_root(Some(Path::new("/sys/fs/cgroup")), config)?; ``` ### Response #### Success Response (Result) - **AnyCgroupManager**: An abstract cgroup manager that can be used to interact with the cgroup system. #### Error Response (CreateCgroupSetupError) - **WrappedIo**: An I/O error occurred. - **NonDefault**: The provided cgroup root is not the default. - **FailedToDetect**: Failed to detect the cgroup setup. - **V1**: An error occurred with the v1 cgroup manager. - **V2**: An error occurred with the v2 cgroup manager. - **Systemd**: An error occurred with the systemd cgroup manager. ### Response Example ```rust // On success, manager is of type AnyCgroupManager // On error, an appropriate CreateCgroupSetupError is returned ``` ``` -------------------------------- ### Apply Unified Cgroup Controllers Source: https://docs.rs/libcgroups/latest/src/libcgroups/v2/unified.rs.html Applies specified unified cgroup controllers to a given path. This example demonstrates a scenario where the application is expected to fail, likely due to invalid configuration or unsupported controllers. ```rust let resources = LinuxResourcesBuilder::default() .unified(unified) .build() .unwrap(); let controller_opt = ControllerOpt { resources: &resources, oom_score_adj: None, disable_oom_killer: false, freezer_state: None, }; // act let result = Unified::apply( &controller_opt, tmp.path(), vec![ControllerType::HugeTlb, ControllerType::Cpu], ); // assert assert!(result.is_err()); ``` -------------------------------- ### Build Linux Devices with LinuxDeviceBuilder Source: https://docs.rs/libcgroups/latest/src/libcgroups/common.rs.html Demonstrates how to construct Linux device entries using `LinuxDeviceBuilder`. This is useful for defining specific device nodes within cgroup configurations. ```rust LinuxDeviceBuilder::default() .major(1) .minor(5) .file_mode(0o066u32) .build() .unwrap(), ``` ```rust LinuxDeviceBuilder::default() .path(PathBuf::from("/dev/full")) .typ(LinuxDeviceType::C) .major(1) .minor(7) .file_mode(0o066u32) .build() .unwrap(), ``` ```rust LinuxDeviceBuilder::default() .path(PathBuf::from("/dev/tty")) .typ(LinuxDeviceType::C) .major(5) .minor(0) .file_mode(0o066u32) .build() .unwrap(), ``` ```rust LinuxDeviceBuilder::default() .path(PathBuf::from("/dev/urandom")) .typ(LinuxDeviceType::C) .major(1) .minor(9) .file_mode(0o066u32) .build() .unwrap(), ``` ```rust LinuxDeviceBuilder::default() .path(PathBuf::from("/dev/random")) .typ(LinuxDeviceType::C) .major(1) .minor(8) .file_mode(0o066u32) .build() .unwrap(), ``` -------------------------------- ### Get All PIDs in Cgroup Source: https://docs.rs/libcgroups/latest/libcgroups/common/trait.CgroupManager.html Gets all the PIDs currently inside the cgroup. This method is part of the CgroupManager trait. ```rust fn get_all_pids(&self) -> Result, Self::Error> ``` -------------------------------- ### Get Systemd Version Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/proxy.rs.html Retrieves the systemd version string by calling the 'Get' method on the D-Bus Properties interface. ```rust pub fn version(&self) -> Result { let t = self.method_call::<_, Variant>( "org.freedesktop.DBus.Properties", "Get", Some(("org.freedesktop.systemd1.Manager", "Version")), )?; match t { Variant::String(s) => Ok(s), v => panic!("version expected string variant, got {:?} instead", v), } } ``` -------------------------------- ### Manager::new Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/manager.rs.html Constructs a new Systemd Manager instance. It initializes cgroup paths, client connections, and file system managers based on provided parameters. ```APIDOC ## Manager::new ### Description Constructs a new Systemd Manager instance. It initializes cgroup paths, client connections, and file system managers based on provided parameters. ### Signature ```rust pub fn new( root_path: PathBuf, cgroups_path: PathBuf, container_name: String, use_system: bool, cgroup_wait_timeout_duration: Duration, ) -> Result ``` ### Parameters - `root_path` (PathBuf) - The root directory for cgroup paths. - `cgroups_path` (PathBuf) - The initial cgroup path provided by the user. - `container_name` (String) - The name of the container. - `use_system` (bool) - Flag to indicate whether to use the system or session D-Bus connection. - `cgroup_wait_timeout_duration` (Duration) - The duration to wait for processes to be added to a cgroup. ### Returns - `Result` - Returns a new `Manager` instance on success or a `SystemdManagerError` on failure. ``` -------------------------------- ### new_system Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/dbus.rs.html Creates a new DBus client connected to the system bus. ```APIDOC ## new_system ### Description Creates a new DBus client instance connected to the system bus. ### Method Signature `pub fn new_system() -> Result` ### Returns A `Result` containing a `Self` (DBus client instance) on success, or an error on failure. ``` -------------------------------- ### TestManager CgroupManager Implementation Source: https://docs.rs/libcgroups/latest/libcgroups/test_manager/struct.TestManager.html Implements the CgroupManager trait for TestManager, providing methods to add tasks, apply restrictions, remove the cgroup, get freezer state, retrieve statistics, and get all PIDs. ```rust type Error = Infallible ``` ```rust fn add_task(&self, pid: Pid) -> Result<(), Infallible> ``` ```rust fn apply(&self, _controller_opt: &ControllerOpt<'_>) -> Result<(), Infallible> ``` ```rust fn remove(&self) -> Result<(), Infallible> ``` ```rust fn freeze(&self, _state: FreezerState) -> Result<(), Infallible> ``` ```rust fn stats(&self) -> Result ``` ```rust fn get_all_pids(&self) -> Result, Infallible> ``` -------------------------------- ### Get Systemd Version Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/proxy.rs.html Retrieves the version of the systemd service. ```APIDOC ## GET /version ### Description Retrieves the version of the systemd service. ### Method GET ### Endpoint `/version` ``` -------------------------------- ### Apply Blkio Configuration (Rust) Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/blkio.rs.html Applies Blkio configurations to a cgroup path. This function handles settings for weight, throttle read/write bandwidth, and throttle read/write IOPS, writing them to the appropriate cgroup files. ```rust impl Blkio { fn apply(root_path: &Path, blkio: &LinuxBlockIo) -> Result<(), WrappedIoError> { if let Some(blkio_weight) = blkio.weight() { // be aligned with what runc does // See also: https://github.com/opencontainers/runc/blob/81044ad7c902f3fc153cb8ffadaf4da62855193f/libcontainer/cgroups/fs/blkio.go#L28-L33 if blkio_weight != 0 { let cgroup_file = root_path.join(BLKIO_WEIGHT); if cgroup_file.exists() { common::write_cgroup_file(&cgroup_file, blkio_weight)?; } else { common::write_cgroup_file(root_path.join(BLKIO_BFQ_WEIGHT), blkio_weight)?; } } } if let Some(throttle_read_bps_device) = blkio.throttle_read_bps_device().as_ref() { for trbd in throttle_read_bps_device { common::write_cgroup_file_str( root_path.join(BLKIO_THROTTLE_READ_BPS), &format!("{}:{} {}", trbd.major(), trbd.minor(), trbd.rate()), )?; } } if let Some(throttle_write_bps_device) = blkio.throttle_write_bps_device().as_ref() { for twbd in throttle_write_bps_device { common::write_cgroup_file_str( root_path.join(BLKIO_THROTTLE_WRITE_BPS), &format!("{}:{} {}", twbd.major(), twbd.minor(), twbd.rate()), )?; } } if let Some(throttle_read_iops_device) = blkio.throttle_read_iops_device().as_ref() { for trid in throttle_read_iops_device { common::write_cgroup_file_str( root_path.join(BLKIO_THROTTLE_READ_IOPS), &format!("{}:{} {}", trid.major(), trid.minor(), trid.rate()), )?; } } if let Some(throttle_write_iops_device) = blkio.throttle_write_iops_device().as_ref() { for twid in throttle_write_iops_device { common::write_cgroup_file_str( root_path.join(BLKIO_THROTTLE_WRITE_IOPS), &format!("{}:{} {}", twid.major(), twid.minor(), twid.rate()), )?; } } Ok(()) } } ``` -------------------------------- ### Get Memory Usage Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/memory.rs.html Retrieves the current memory usage of a cgroup. ```APIDOC ## get_memory_usage(cgroup_root: &Path) -> Result ### Description Gets the current memory usage in bytes for the specified cgroup. Returns `u64::MAX` if the value is 'max'. ### Method `Memory::get_memory_usage` ### Parameters - **cgroup_root** (*&Path*) - The root path of the cgroup. ### Returns A `Result` containing the memory usage as a `u64` on success, or a `V1MemoryControllerError` on failure. ### Error Handling - `V1MemoryControllerError::MalformedValue`: If the value in the file cannot be parsed as a u64 or is not 'max'. ``` -------------------------------- ### Add and Manage Tasks in Cgroup Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/manager.rs.html Demonstrates adding multiple processes to a cgroup managed by the systemd manager and verifying their presence. Includes cleanup of the cgroup. ```rust #[test] fn test_task_addition() { let manager = Manager::new( DEFAULT_CGROUP_ROOT.into(), ":youki:test".into(), "youki_test_container".into(), false, PROCESS_IN_CGROUP_TIMEOUT_DURATION, ) .unwrap(); let mut p1 = std::process::Command::new("sleep") .arg("1s") .spawn() .unwrap(); let p1_id = nix::unistd::Pid::from_raw(p1.id() as i32); let mut p2 = std::process::Command::new("sleep") .arg("1s") .spawn() .unwrap(); let p2_id = nix::unistd::Pid::from_raw(p2.id() as i32); manager.add_task(p1_id).unwrap(); manager.add_task(p2_id).unwrap(); let all_pids = manager.get_all_pids().unwrap(); assert!(all_pids.contains(&p1_id)); assert!(all_pids.contains(&p2_id)); let _ = p1.wait(); let _ = p2.wait(); manager.remove().unwrap(); let _ = fs::remove_dir(&manager.full_path); } ``` -------------------------------- ### Get Systemd Version Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/dbus.rs.html Retrieves the version of the systemd instance running on the system. ```APIDOC ## systemd_version ### Description Retrieves the version of the systemd instance running on the system. ### Method `version` ### Return Value - `Result` - The systemd version as a u32 on success, or a `SystemdClientError` on failure. ``` -------------------------------- ### Get Control Group Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/proxy.rs.html Retrieves the control group path for the systemd manager. ```APIDOC ## GET /control-group ### Description Retrieves the control group path for the systemd manager. ### Method GET ### Endpoint `/control-group` ``` -------------------------------- ### Blkio Controller Apply Logic Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/blkio.rs.html Handles the application of Blkio cgroup configuration. It checks if the Blkio controller needs to be managed based on the provided options and then applies the configuration to the specified cgroup root path. ```rust pub struct Blkio {} impl Controller for Blkio { type Error = WrappedIoError; type Resource = LinuxBlockIo; fn apply(controller_opt: &ControllerOpt, cgroup_root: &Path) -> Result<(), Self::Error> { tracing::debug!("Apply blkio cgroup config"); if let Some(blkio) = Self::needs_to_handle(controller_opt) { Self::apply(cgroup_root, blkio)?; } Ok(()) } fn needs_to_handle<'a>(controller_opt: &'a ControllerOpt) -> Option<&'a Self::Resource> { controller_opt.resources.block_io().as_ref() } } ``` -------------------------------- ### Get Unit Information Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/proxy.rs.html Retrieves information about a specific systemd unit by its name. ```APIDOC ## GET /unit/{name} ### Description Retrieves information about a specific systemd unit. ### Method GET ### Endpoint `/unit/{name}` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the unit to retrieve. ``` -------------------------------- ### Test Applying IO Limits Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/io.rs.html Tests the `apply` function by creating a `LinuxBlockIo` configuration with read/write bandwidth and IOPS limits for a device and verifying they are correctly inserted into the properties map. ```rust #[test] fn apply_inserts_structs_for_positive_rates() { let st = stat("/dev/null").expect("stat /dev/null"); let maj = major(st.st_rdev) as i64; let min = minor(st.st_rdev) as i64; // set random bytes let read_bps = 111u64; let write_bps = 222u64; let read_iops = 333u64; let write_iops = 444u64; let blkio = LinuxBlockIoBuilder::default() .throttle_read_bps_device(vec![ LinuxThrottleDeviceBuilder::default() .major(maj) .minor(min) .rate(read_bps) .build() .unwrap(), ]) ``` -------------------------------- ### Hugetlb Controller Needs to Handle Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/hugetlb.rs.html Checks if the controller needs to handle hugetlb configurations based on the provided controller options. ```APIDOC ## needs_to_handle ### Description Checks if the controller needs to handle hugetlb configurations based on the provided controller options. Returns a reference to the hugepage limits if they are present and not empty. ### Method `Controller::needs_to_handle` ### Parameters - `controller_opt`: Options for the controller, including resource limits. ### Returns - `Option<&'a Vec>`: An Option containing a reference to the hugepage limits if they exist and are non-empty, otherwise None. ``` -------------------------------- ### Get Memory Max Usage Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/memory.rs.html Retrieves the maximum memory usage recorded for a cgroup. ```APIDOC ## get_memory_max_usage(cgroup_root: &Path) -> Result ### Description Gets the maximum memory usage in bytes recorded for the specified cgroup. Returns `u64::MAX` if the value is 'max'. ### Method `Memory::get_memory_max_usage` ### Parameters - **cgroup_root** (*&Path*) - The root path of the cgroup. ### Returns A `Result` containing the maximum memory usage as a `u64` on success, or a `V1MemoryControllerError` on failure. ### Error Handling - `V1MemoryControllerError::MalformedValue`: If the value in the file cannot be parsed as a u64 or is not 'max'. ``` -------------------------------- ### Get Stat Data Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/memory.rs.html Parses flat keyed data from the memory statistics file. ```APIDOC ## get_stat_data(cgroup_path: &Path) -> Result, ParseFlatKeyedDataError> ### Description Reads and parses the memory statistics file into a HashMap. ### Method `Memory::get_stat_data` ### Parameters - **cgroup_path** (*&Path*) - The path to the cgroup directory. ### Returns A `Result` containing a `HashMap` of statistics on success or a `ParseFlatKeyedDataError` on failure. ``` -------------------------------- ### Manager::new Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/manager.rs.html Constructs a new cgroup manager. It initializes the manager by discovering available cgroup subsystems relative to the provided cgroup path. ```APIDOC ## Manager::new ### Description Constructs a new cgroup manager with `cgroups_path` being relative to the root of the subsystem. It attempts to find all supported cgroup subsystems and their corresponding paths. ### Signature ```rust pub fn new(cgroup_path: &Path) -> Result ``` ### Parameters * `cgroup_path` (`&Path`): The path within the cgroup filesystem to manage. This path is relative to the mount point of each subsystem. ### Returns * `Result`: Returns a `Manager` instance if successful, otherwise returns a `V1ManagerError`. ### Errors * `V1ManagerError::WrappedIo`: If an I/O error occurs during path resolution. * `V1ManagerError::MountPoint`: If there's an error determining the cgroup mount point. * `V1ManagerError::Proc`: If there's an error reading process information (e.g., from /proc/self/cgroup). * `V1ManagerError::JoinSafely`: If joining path components fails. * `V1ManagerError::SubsystemDoesNotExist`: If a required subsystem path cannot be determined. ``` -------------------------------- ### Manager V2 Get Stats Source: https://docs.rs/libcgroups/latest/src/libcgroups/v2/manager.rs.html Retrieves statistics for various controllers within the cgroup. ```APIDOC ## stats ### Description Retrieves statistics for various controllers within the cgroup. ### Method `stats` ### Returns - `Result` - A `Stats` struct containing statistics if successful, or an error if an issue occurred. ``` -------------------------------- ### Get Control Cgroup Root Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/dbus_native/dbus.rs.html Retrieves the root path for cgroups managed by systemd. ```APIDOC ## control_cgroup_root ### Description Retrieves the root path for cgroups managed by systemd. ### Method `control_group` ### Return Value - `Result` - The cgroup root path as a `PathBuf` on success, or a `SystemdClientError` on failure. ``` -------------------------------- ### get_available_controllers Source: https://docs.rs/libcgroups/latest/libcgroups/v2/util/index.html Reads the `{root_path}/cgroup.controllers` file to get the list of the controllers that are available in this cgroup. ```APIDOC ## Function: get_available_controllers ### Description Reads the `{root_path}/cgroup.controllers` file to get the list of the controllers that are available in this cgroup. ### Signature ```rust fn get_available_controllers(root_path: &str) -> Result, V2UtilError> ``` ### Parameters * `root_path` (*&str*) - The root path of the cgroup filesystem. ### Returns * `Result, V2UtilError>` - A vector of strings representing the available controllers, or a `V2UtilError` if an error occurs. ``` -------------------------------- ### Create a unified cgroup and attach a process Source: https://docs.rs/libcgroups/latest/src/libcgroups/v2/manager.rs.html This function creates a unified cgroup at the manager's `full_path` and attaches a given process ID to it. It first determines available controllers, writes them to the cgroup, and then creates any necessary parent directories before finally writing the process ID to the `cgroup.procs` file. ```rust fn create_unified_cgroup(&self, pid: Pid) -> Result<(), V2ManagerError> { let controllers: Vec = util::get_available_controllers(&self.root_path)? .iter() .map(|c| format!( ``` ```rust +{c}')) .collect(); Self::write_controllers(&self.root_path, &controllers)?; let mut current_path = self.root_path.clone(); let mut components = self .cgroup_path .components() .filter(|c| c.ne(&RootDir)) .peekable(); while let Some(component) = components.next() { current_path = current_path.join(component); if !current_path.exists() { fs::create_dir(¤t_path).wrap_create_dir(¤t_path)?; fs::metadata(¤t_path) .wrap_other(¤t_path)? .permissions() .set_mode(0o755); } // last component cannot have subtree_control enabled due to internal process constraint // if this were set, writing to the cgroups.procs file will fail with Erno 16 (device or resource busy) if components.peek().is_some() { Self::write_controllers(¤t_path, &controllers)?; } } common::write_cgroup_file(self.full_path.join(CGROUP_PROCS), pid)?; Ok(()) } ``` -------------------------------- ### AsRef Implementation Source: https://docs.rs/libcgroups/latest/libcgroups/systemd/controller_type/enum.ControllerType.html Provides a way to get a string slice representation of the ControllerType. ```APIDOC ## Trait Implementations ### impl AsRef for ControllerType #### fn as_ref(&self) -> &str Converts this type into a shared reference of the (usually inferred) input type. ``` -------------------------------- ### Test Mock Device Rules Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/devices.rs.html Tests the `apply_device` function with various mock device rules, including different device types, major/minor numbers, and access permissions. It verifies that both allowed and denied devices are correctly written to their respective files. ```rust #[test] fn test_set_mock_devices() { let tmp = tempfile::tempdir().unwrap(); [ LinuxDeviceCgroupBuilder::default() .allow(true) .typ(LinuxDeviceType::C) .major(10) .access("rwm") .build() .unwrap(), LinuxDeviceCgroupBuilder::default() .allow(true) .typ(LinuxDeviceType::A) .minor(200) .access("rwm") .build() .unwrap(), LinuxDeviceCgroupBuilder::default() .allow(false) .typ(LinuxDeviceType::P) .major(10) .minor(200) .access("m") .build() .unwrap(), LinuxDeviceCgroupBuilder::default() .allow(false) .typ(LinuxDeviceType::U) .access("rw") .build() .unwrap(), ] .iter() .for_each(|d| { set_fixture(tmp.path(), "devices.allow", "").expect("create allowed devices list"); set_fixture(tmp.path(), "devices.deny", "").expect("create denied devices list"); Devices::apply_device(d, tmp.path()).expect("Apply default device"); println!("Device: {}", d); if d.allow() { let allowed_content = read_to_string(tmp.path().join("devices.allow")).expect("read to string"); assert_eq!(allowed_content, d.to_string()); } else { let denied_content = read_to_string(tmp.path().join("devices.deny")).expect("read to string"); assert_eq!(denied_content, d.to_string()); } }); } ``` -------------------------------- ### GetCgroupSetupError Enum Definition Source: https://docs.rs/libcgroups/latest/libcgroups/common/enum.GetCgroupSetupError.html Defines the possible errors that can occur during cgroup setup operations. ```rust pub enum GetCgroupSetupError { WrappedIo(WrappedIoError), NonDefault, FailedToDetect, } ``` -------------------------------- ### add_task Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/manager.rs.html Adds a process to the cgroup managed by this SystemdManager. If the transient unit does not exist, it will be created and started. ```APIDOC ## add_task ### Description Adds a process to the cgroup managed by this SystemdManager. If the transient unit does not exist, it will be created and started. ### Method `add_task(pid: Pid) -> Result<(), Self::Error>` ### Parameters - **pid** (Pid) - The process ID to add to the cgroup. If pid is -1, the operation is a no-op. ### Return Value - `Ok(())` on success. - `Err(Self::Error)` on failure. ``` -------------------------------- ### From for CreateCgroupSetupError Source: https://docs.rs/libcgroups/latest/libcgroups/v2/manager/enum.V2ManagerError.html Enables converting a V2ManagerError into a CreateCgroupSetupError. This is useful when integrating with cgroup setup processes. ```rust impl From for CreateCgroupSetupError { fn from(source: V2ManagerError) -> Self { // ... implementation details ... } } ``` -------------------------------- ### Manager::new Source: https://docs.rs/libcgroups/latest/libcgroups/systemd/manager/struct.Manager.html Constructs a new Manager instance. It requires the root path of cgroups, a specific path for the container's cgroup, the container's name, a flag indicating whether to use systemd, and a timeout duration for cgroup operations. ```APIDOC ## pub fn new( root_path: PathBuf, cgroups_path: PathBuf, container_name: String, use_system: bool, cgroup_wait_timeout_duration: Duration, ) -> Result ``` -------------------------------- ### Manager Constructor Source: https://docs.rs/libcgroups/latest/src/libcgroups/systemd/manager.rs.html Initializes a new Systemd Manager instance. It constructs the cgroup path, determines the unit name, and sets up the D-Bus connection and file system manager based on provided parameters. ```rust pub fn new( root_path: PathBuf, cgroups_path: PathBuf, container_name: String, use_system: bool, cgroup_wait_timeout_duration: Duration, ) -> Result { let mut destructured_path: CgroupsPath = cgroups_path.as_path().try_into()?; ensure_parent_unit(&mut destructured_path, use_system); let client = match use_system { true => DbusConnection::new_system()?, false => DbusConnection::new_session()?, }; let (cgroups_path, delegation_boundary) = Self::construct_cgroups_path(&destructured_path, &client)?; let full_path = root_path.join_safely(&cgroups_path)?; let fs_manager = FsManager::new(root_path.clone(), cgroups_path.clone())?; Ok(Manager { root_path, cgroups_path, full_path, container_name, unit_name: Self::get_unit_name(&destructured_path), destructured_path, client, fs_manager, delegation_boundary, cgroup_wait_timeout_duration, }) } ``` -------------------------------- ### Get Memory Data Source: https://docs.rs/libcgroups/latest/src/libcgroups/v1/memory.rs.html Helper function to retrieve specific memory data fields from a cgroup file. ```APIDOC ## get_memory_data(cgroup_path: &Path, file_prefix: &str) -> Result ### Description Reads and parses memory-related data (usage, max usage, limit, fail count) from cgroup files. ### Method `Memory::get_memory_data` ### Parameters - **cgroup_path** (*&Path*) - The path to the cgroup directory. - **file_prefix** (*&str*) - The prefix for the memory file (e.g., "memory.stat", "memory.usage_in_bytes"). ### Returns A `Result` containing `MemoryData` on success or a `WrappedIoError` on failure. ``` -------------------------------- ### Controller Apply Method Source: https://docs.rs/libcgroups/latest/src/libcgroups/v2/memory.rs.html The main entry point for applying controller options. It checks if memory resources are specified and delegates to the specific apply method for the memory controller. ```rust impl Controller for Memory { type Error = V2MemoryControllerError; fn apply(controller_opt: &ControllerOpt, cgroup_path: &Path) -> Result<(), Self::Error> { if let Some(memory) = &controller_opt.resources.memory() { Self::apply(cgroup_path, memory)?; } Ok(()) } } ``` -------------------------------- ### Manager V2 Get All PIDs Source: https://docs.rs/libcgroups/latest/src/libcgroups/v2/manager.rs.html Retrieves a list of all process IDs (PIDs) currently within the cgroup. ```APIDOC ## get_all_pids ### Description Retrieves a list of all process IDs (PIDs) currently within the cgroup. ### Method `get_all_pids` ### Returns - `Result, Self::Error>` - A vector of `Pid` objects if successful, or an error if an issue occurred. ``` -------------------------------- ### Cgroup Information Retrieval Source: https://docs.rs/libcgroups/latest/libcgroups/all.html Functions for retrieving process IDs within cgroups and cgroup setup information. ```APIDOC ## get_all_pids ### Description Retrieves all process IDs associated with the current cgroup. ### Function Signature `pub fn get_all_pids() -> Result, std::io::Error>` ## get_cgroup_setup ### Description Retrieves the cgroup setup configuration. ### Function Signature `pub fn get_cgroup_setup() -> Result` ## get_cgroup_setup_with_root ### Description Retrieves the cgroup setup configuration for a specified root directory. ### Function Signature `pub fn get_cgroup_setup_with_root(root: &str) -> Result` ``` -------------------------------- ### Unified::apply Source: https://docs.rs/libcgroups/latest/src/libcgroups/v2/unified.rs.html Applies unified cgroup configurations to the specified cgroup path. It takes a `ControllerOpt` which contains the unified resource settings, the cgroup path, and a list of enabled controllers. If unified settings are present in `ControllerOpt`, it delegates the application to `apply_impl`. ```APIDOC ## Unified::apply ### Description Applies unified cgroup configurations to the specified cgroup path. ### Method Signature ```rust pub fn apply( controller_opt: &ControllerOpt, cgroup_path: &Path, controllers: Vec, ) -> Result<(), V2UnifiedError> ``` ### Parameters - `controller_opt` (*ControllerOpt): A reference to `ControllerOpt` containing resource settings, including unified configurations. - `cgroup_path` (*Path): The path to the cgroup directory where configurations will be applied. - `controllers` (Vec): A vector of `ControllerType` specifying which controllers are enabled. ### Returns - `Result<(), V2UnifiedError>`: Ok if the operation is successful, or a `V2UnifiedError` if an error occurs during application. ```