Compare commits

..

24 Commits

Author SHA1 Message Date
Fupan Li
87f05873f0 Merge pull request #35 from Tim-Zhang/v0.2.3
release: v0.2.3
2021-02-02 11:46:03 +08:00
Tim Zhang
79868d6bfc release: v0.2.3
Bump version from 0.2.2 to 0.2.3

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-02-02 10:24:58 +08:00
Fupan Li
d1d78fe943 Merge pull request #34 from quanweiZhou/get_mountinfo_without_procinfo
cgroup: get the mount info without procinfo
2021-02-01 15:13:59 +08:00
quanweiZhou
81d286f31d cgroup: get the mount info without procinfo
The procinfo library gets all the mount info,
but we don't need all the mount info.

Signed-off-by: quanweiZhou <quanweiZhou@linux.alibaba.com>
2021-02-01 11:26:54 +08:00
Fupan Li
5e538ae286 Merge pull request #33 from lifupan/master
cgroup: fix the issue of remove cgroup
2021-01-25 17:39:38 +08:00
fupan.lfp
cd5645bb14 cgroup: fix the issue of remove cgroup
It should remove the child cgroups recursively
and then remove the parent cgroup, otherwise,
it would remove failed.

Signed-off-by: fupan.lfp <fupan.lfp@antfin.com>
2021-01-25 17:36:49 +08:00
Tim Zhang
4a2042068e Merge pull request #28 from Tim-Zhang/update-cargo-toml
Add field homepage and readme for Cargo.toml
2021-01-25 17:34:43 +08:00
Tim Zhang
9ac2f5d5ab Add field homepage and readme for Cargo.toml
Display readme on the crate's page.

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-01-25 17:32:24 +08:00
Tim Zhang
a58cd1d553 Merge pull request #31 from Tim-Zhang/switch-travis-to-github-action
Migrate the CI from travis-ci to Github Actions
2021-01-25 17:30:37 +08:00
Tim Zhang
88a45d4922 Migrate the CI from travis-ci to Github Actions
Because travis-ci.org will be shutting down.

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-01-25 17:24:45 +08:00
Tim Zhang
0c58b5dd84 Add Makefile
So we can use make to build, check and test

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-01-25 17:20:56 +08:00
Tim Zhang
8448548cb3 Merge pull request #30 from bergwolf/issue-templates
github: add issue templates
2021-01-25 15:33:01 +08:00
Peng Tao
d50245e116 github: add issue templates
cgroups-rs should not use the repository default issue templates.
Let's add a private version to override the default ones.

Fixes: #29
Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2021-01-25 15:01:48 +08:00
Tim Zhang
bbdfa88596 Merge pull request #26 from Tim-Zhang/memory-apply-customized-attrs
Apply customized attributes in MemController.apply
2021-01-25 14:37:34 +08:00
Tim Zhang
853ed46993 release: v0.2.2
Bump version to 0.2.2

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-01-25 12:20:30 +08:00
Tim Zhang
15b65c5e5e Apply customized attributes in MemController.apply
Fixes: #25

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-01-25 12:11:43 +08:00
Tim Zhang
87f8ac7f0d Merge pull request #23 from Tim-Zhang/add-trait-bound-for-hierarchy
Add trait bound for hierarchy
2021-01-07 16:27:15 +08:00
Tim Zhang
225388ff7c release: v0.2.1
Bump version to 0.2.1

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-01-06 22:31:04 +08:00
Tim Zhang
f0a695cc00 Add trait bound Sync for Hierarchy
So that the struct Cgroup could across await

Signed-off-by: Tim Zhang <tim@hyper.sh>
2021-01-06 22:31:04 +08:00
Tim Zhang
50d3c398a0 Merge pull request #22 from Apokleos/master
optimize and refactor: read_to_string and read_i[u]64_from
2021-01-06 22:30:17 +08:00
LiYa'nan
033fa4b857 optimize and refactor: read_to_string and read_i[u]64_from
There's so many Duplicated read_string_from method in different
subsystem's implementation, so as read_u64_from/read_i64_from methods.
(1) Move the read_string_from method into `lib.rs`,
called by each subsystem implementation as needed.
(2) Refactor read_u[i]64_from method with the help Rust Generic f
unction `read_from` and wrapped by read_u64_from or read_i64_from.

fix: #20

Signed-off-by: LiYa'nan <oliverliyn@gmail.com>
2020-12-24 09:25:00 +08:00
Peng Tao
ac4e6eda66 Merge pull request #21 from Tim-Zhang/change-name
Change package name to cgroups-rs
2020-12-21 16:22:06 +08:00
Tim Zhang
35ecd6fd77 Update readme
- Change the travis badge
- Update the description about v2 supporting.

Signed-off-by: Tim Zhang <tim@hyper.sh>
2020-12-21 15:51:34 +08:00
Tim Zhang
eb6577e3e0 Change package name to cgroups-rs
We need a new package name to create a new crate

Signed-off-by: Tim Zhang <tim@hyper.sh>
2020-12-21 15:46:30 +08:00
30 changed files with 373 additions and 273 deletions

17
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,17 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: 'bug, needs-review'
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Enhancement request
about: Suggest an improvement to an existing feature
title: ''
labels: enhancement, needs-review
assignees: ''
---
**Which feature do you think can be improved?**
Specify the feature you think could be made better.
**How can it be improved?**
Describe how specifically you think it could be improved.
**Additional Information**
Anything else to add?

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: 'feature, needs-review'
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

26
.github/workflows/bvt.yaml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: BVT
on: [pull_request]
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Build
run: make debug
fmt:
name: Format Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: rustup component add rustfmt
- run: make fmt
test:
name: Run Unit Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: make test

View File

@@ -1,31 +0,0 @@
# Copyright (c) 2018 Levente Kurusa
# Copyright (c) 2020 Ant Group
#
# SPDX-License-Identifier: Apache-2.0
#
dist: bionic
os: linux
language: rust
cache: cargo
arch:
- amd64
- arm64
install:
- rustup component add rustfmt
script:
- RUSTFLAGS="--deny warnings" cargo build
- if [ "$TRAVIS_CPU_ARCH" == "amd64" ]; then cargo test -- --color always --nocapture ; fi
- cargo fmt -- --check
rust:
- 1.44.1
- nightly
jobs:
allow_failures:
- rust: nightly
fast_finish: true

View File

@@ -1,20 +1,21 @@
[package]
name = "cgroups"
name = "cgroups-rs"
description = "Native Rust crate for managing control groups on Linux"
repository = "https://github.com/levex/cgroups-rs"
repository = "https://github.com/kata-containers/cgroups-rs"
keywords = ["linux", "cgroup", "containers", "isolation"]
categories = ["os", "api-bindings", "os::unix-apis"]
license = "MIT OR Apache-2.0"
version = "0.2.0"
authors = ["Levente Kurusa <lkurusa@acm.org>", "Sam Wilson <tecywiz121@hotmail.com>"]
version = "0.2.3"
authors = ["The Kata Containers community <kata-dev@lists.katacontainers.io>", "Levente Kurusa <lkurusa@acm.org>", "Sam Wilson <tecywiz121@hotmail.com>"]
edition = "2018"
homepage = "https://github.com/kata-containers/cgroups-rs"
readme = "README.md"
[dependencies]
log = "0.4"
regex = "1.1"
nix = "0.18.0"
libc = "0.2"
procinfo = "0.4.2"
[dev-dependencies]
libc = "0.2.76"

37
Makefile Normal file
View File

@@ -0,0 +1,37 @@
all: debug fmt test
#
# Build
#
.PHONY: debug
debug:
RUSTFLAGS="--deny warnings" cargo build
.PHONY: release
release:
cargo build --release
.PHONY: build
build: debug
#
# Tests and linters
#
.PHONY: test
test:
cargo test -- --color always --nocapture
.PHONY: check
check: fmt clippy
.PHONY: fmt
fmt:
cargo fmt --all -- --check
.PHONY: clippy
clippy:
cargo clippy --all-targets --all-features -- -D warnings

View File

@@ -1,8 +1,7 @@
# cgroups-rs ![Build](https://travis-ci.org/levex/cgroups-rs.svg?branch=master)
# cgroups-rs ![Build](https://travis-ci.org/kata-containers/cgroups-rs.svg?branch=master)
Native Rust library for managing control groups under Linux
Right now the crate only support the original, V1 hierarchy, however support
is planned for the Unified hierarchy.
Both v1 and v2 of cgroups are supported.
# Examples
@@ -11,11 +10,11 @@ is planned for the Unified hierarchy.
``` rust
use cgroups::*;
use cgroups::cgroup_builder::*;
use cgroups_rs::*;
use cgroups_rs::cgroup_builder::*;
// Acquire a handle for the cgroup hierarchy.
let hier = cgroups::hierarchies::auto();
let hier = cgroups_rs::hierarchies::auto();
// Use the builder pattern (see the documentation to create the control group)
//
@@ -30,7 +29,7 @@ let hier = cgroups::hierarchies::auto();
// other control groups.
// Get a handle to the CPU controller.
let cpus: &cgroups::cpu::CpuController = cg.controller_of().unwrap();
let cpus: &cgroups_rs::cpu::CpuController = cg.controller_of().unwrap();
cpus.add_task(&CgroupPid::from(1234u64));
// [...]

View File

@@ -8,13 +8,13 @@
//!
//! See the Kernel's documentation for more information about this subsystem, found at:
//! [Documentation/cgroup-v1/blkio-controller.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/blkio-controller.txt)
use std::fs::File;
use std::io::{Read, Write};
use std::io::Write;
use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::{read_string_from, read_u64_from};
use crate::{
BlkIoResources, ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem,
};
@@ -401,25 +401,6 @@ impl<'a> From<&'a Subsystem> for &'a BlkIoController {
}
}
fn read_string_from(mut file: File) -> Result<String> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => Ok(string.trim().to_string()),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
impl BlkIoController {
/// Constructs a new `BlkIoController` with `root` serving as the root of the control group.
pub fn new(root: PathBuf, v2: bool) -> Self {

View File

@@ -16,10 +16,10 @@
//! by a call to `build()`.
//!
//! ```rust,no_run
//! # use cgroups::*;
//! # use cgroups::devices::*;
//! # use cgroups::cgroup_builder::*;
//! let h = cgroups::hierarchies::auto();
//! # use cgroups_rs::*;
//! # use cgroups_rs::devices::*;
//! # use cgroups_rs::cgroup_builder::*;
//! let h = cgroups_rs::hierarchies::auto();
//! let cgroup: Cgroup = CgroupBuilder::new("hello")
//! .memory()
//! .kernel_memory_limit(1024 * 1024)

View File

@@ -15,7 +15,7 @@ use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::{parse_max_value, read_i64_from};
use crate::{parse_max_value, read_i64_from, read_u64_from};
use crate::{
ControllIdentifier, ControllerInternal, Controllers, CpuResources, CustomizedAttribute,
@@ -110,17 +110,6 @@ impl<'a> From<&'a Subsystem> for &'a CpuController {
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
impl CpuController {
/// Contructs a new `CpuController` with `root` serving as the root of the control group.
pub fn new(root: PathBuf, v2: bool) -> Self {

View File

@@ -7,13 +7,13 @@
//!
//! See the Kernel's documentation for more information about this subsystem, found at:
//! [Documentation/cgroup-v1/cpuacct.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/cpuacct.txt)
use std::fs::File;
use std::io::{Read, Write};
use std::io::Write;
use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::{read_string_from, read_u64_from};
use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};
/// A controller that allows controlling the `cpuacct` subsystem of a Cgroup.
@@ -97,26 +97,6 @@ impl<'a> From<&'a Subsystem> for &'a CpuAcctController {
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
let res = file.read_to_string(&mut string);
match res {
Ok(_) => match string.trim().parse() {
Ok(e) => Ok(e),
Err(e) => Err(Error::with_cause(ParseError, e)),
},
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
fn read_string_from(mut file: File) -> Result<String> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => Ok(string.trim().to_string()),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
impl CpuAcctController {
/// Contructs a new `CpuAcctController` with `root` serving as the root of the control group.
pub fn new(root: PathBuf) -> Self {

View File

@@ -10,13 +10,13 @@
//! [Documentation/cgroup-v1/cpusets.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/cpusets.txt)
use log::*;
use std::fs::File;
use std::io::{Read, Write};
use std::io::Write;
use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::{read_string_from, read_u64_from};
use crate::{
ControllIdentifier, ControllerInternal, Controllers, CpuResources, Resources, Subsystem,
};
@@ -204,25 +204,6 @@ impl<'a> From<&'a Subsystem> for &'a CpuSetController {
}
}
fn read_string_from(mut file: File) -> Result<String> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => Ok(string.trim().to_string()),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
/// Parse a string like "1,2,4-5,8" into a list of (start, end) tuples.
fn parse_range(s: String) -> Result<Vec<(u64, u64)>> {
let mut fin = Vec::new();

View File

@@ -9,8 +9,9 @@
//! Currently, we only support the cgroupv1 hierarchy, but in the future we will add support for
//! the Unified Hierarchy.
use procinfo::pid::{mountinfo_self, Mountinfo};
use std::fs;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use crate::blkio::BlkIoController;
@@ -31,6 +32,75 @@ use crate::{Controllers, Hierarchy, Subsystem};
use crate::cgroup::Cgroup;
/// Process mounts information.
///
/// See `proc(5)` for format details.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Mountinfo {
/// Mount pathname relative to the process's root.
pub mount_point: PathBuf,
/// Filesystem type (main type with optional sub-type).
pub fs_type: (String, Option<String>),
/// Superblock options.
pub super_opts: Vec<String>,
}
pub(crate) fn parse_mountinfo_for_line(line: &str) -> Option<Mountinfo> {
let s_values: Vec<_> = line.split(" - ").collect();
if s_values.len() != 2 {
return None;
}
let s0_values: Vec<_> = s_values[0].trim().split(' ').collect();
let s1_values: Vec<_> = s_values[1].trim().split(' ').collect();
if s0_values.len() < 6 || s1_values.len() < 3 {
return None;
}
let mount_point = PathBuf::from(s0_values[4]);
let fs_type_values: Vec<_> = s1_values[0].trim().split('.').collect();
let fs_type = match fs_type_values.len() {
1 => (fs_type_values[0].to_string(), None),
2 => (
fs_type_values[0].to_string(),
Some(fs_type_values[1].to_string()),
),
_ => return None,
};
let super_opts: Vec<String> = s1_values[2].trim().split(',').map(String::from).collect();
Some(Mountinfo {
mount_point,
fs_type,
super_opts,
})
}
/// Parses the provided mountinfo file.
fn mountinfo_file(file: &mut File) -> Vec<Mountinfo> {
let mut r = Vec::new();
for line in BufReader::new(file).lines() {
match line {
Ok(line) => {
if let Some(mi) = parse_mountinfo_for_line(&line) {
if mi.fs_type.0 == "cgroup" {
r.push(mi);
}
}
}
Err(_) => continue,
}
}
r
}
/// Returns mounts information for the current process.
pub fn mountinfo_self() -> Vec<Mountinfo> {
match File::open("/proc/self/mountinfo") {
Ok(mut file) => mountinfo_file(&mut file),
Err(_) => vec![],
}
}
/// The standard, original cgroup implementation. Often referred to as "cgroupv1".
#[derive(Debug)]
pub struct V1 {
@@ -184,7 +254,7 @@ impl V1 {
/// can be created.
pub fn new() -> V1 {
V1 {
mountinfo: mountinfo_self().unwrap(),
mountinfo: mountinfo_self(),
}
}
@@ -253,3 +323,36 @@ pub fn auto() -> Box<dyn Hierarchy> {
Box::new(V1::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_mount() {
let mountinfo = vec![
("29 26 0:26 / /sys/fs/cgroup/cpuset,cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:10 - cgroup cgroup rw,cpuset,cpu,cpuacct",
Mountinfo{mount_point: PathBuf::from("/sys/fs/cgroup/cpuset,cpu,cpuacct"), fs_type: ("cgroup".to_string(), None), super_opts: vec![
"rw".to_string(),
"cpuset".to_string(),
"cpu".to_string(),
"cpuacct".to_string(),
]}),
("121 1731 0:42 / /shm rw,nosuid,nodev,noexec,relatime shared:68 master:66 - tmpfs shm rw,size=65536k",
Mountinfo{mount_point: PathBuf::from("/shm"), fs_type: ("tmpfs".to_string(), None), super_opts: vec![
"rw".to_string(),
"size=65536k".to_string(),
]}),
("121 1731 0:42 / /shm rw,nosuid,nodev,noexec,relatime shared:68 master:66 - tmpfs.123 shm rw,size=65536k",
Mountinfo{mount_point: PathBuf::from("/shm"), fs_type: ("tmpfs".to_string(), Some("123".to_string())), super_opts: vec![
"rw".to_string(),
"size=65536k".to_string(),
]}),
];
for mi in mountinfo {
let info = parse_mountinfo_for_line(mi.0).unwrap();
assert_eq!(info, mi.1)
}
}
}

View File

@@ -8,13 +8,12 @@
//!
//! See the Kernel's documentation for more information about this subsystem, found at:
//! [Documentation/cgroup-v1/hugetlb.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/hugetlb.txt)
use std::fs::File;
use std::io::{Read, Write};
use std::io::Write;
use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::flat_keyed_to_vec;
use crate::{flat_keyed_to_vec, read_u64_from};
use crate::{
ControllIdentifier, ControllerInternal, Controllers, HugePageResources, Resources, Subsystem,
@@ -86,17 +85,6 @@ impl<'a> From<&'a Subsystem> for &'a HugeTlbController {
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
impl HugeTlbController {
/// Constructs a new `HugeTlbController` with `root` serving as the root of the control group.
pub fn new(root: PathBuf, v2: bool) -> Self {

View File

@@ -10,6 +10,7 @@ use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
macro_rules! update_and_test {
($self: ident, $set_func:ident, $value:expr, $get_func:ident) => {
@@ -329,7 +330,7 @@ where
return Ok(());
}
fs::remove_dir(self.get_path()).map_err(|e| Error::with_cause(ErrorKind::RemoveFailed, e))
remove_dir(self.get_path())
}
/// Attach a task to this controller.
@@ -378,6 +379,30 @@ where
}
}
// remove_dir aims to remove cgroup path. It does so recursively,
// by removing any subdirectories (sub-cgroups) first.
fn remove_dir(dir: &PathBuf) -> Result<()> {
// try the fast path first.
if fs::remove_dir(dir).is_ok() {
return Ok(());
}
if dir.exists() {
if dir.is_dir() {
for entry in fs::read_dir(dir).map_err(|e| Error::with_cause(ReadFailed, e))? {
let entry = entry.map_err(|e| Error::with_cause(ReadFailed, e))?;
let path = entry.path();
if path.is_dir() {
remove_dir(&path)?;
}
}
fs::remove_dir(dir).map_err(|e| Error::with_cause(RemoveFailed, e))?;
}
}
Ok(())
}
#[doc(hidden)]
pub trait ControllIdentifier {
fn controller_type() -> Controllers;
@@ -385,7 +410,7 @@ pub trait ControllIdentifier {
/// Control group hierarchy (right now, only V1 is supported, but in the future Unified will be
/// implemented as well).
pub trait Hierarchy: std::fmt::Debug + Send {
pub trait Hierarchy: std::fmt::Debug + Send + Sync {
/// Returns what subsystems are supported by the hierarchy.
fn subsystems(&self) -> Vec<Subsystem>;
@@ -422,7 +447,7 @@ pub struct MemoryResources {
///
/// # Usage:
/// ```
/// let resource = &mut cgroups::Resources::default();
/// let resource = &mut cgroups_rs::Resources::default();
/// resource.memory.attrs.insert("memory.numa_balancing", "true".to_string());
/// // apply here
pub attrs: std::collections::HashMap<&'static str, String>,
@@ -464,7 +489,7 @@ pub struct CpuResources {
/// Customized key-value attributes
/// # Usage:
/// ```
/// let resource = &mut cgroups::Resources::default();
/// let resource = &mut cgroups_rs::Resources::default();
/// resource.cpu.attrs.insert("cpu.cfs_init_buffer_us", "10".to_string());
/// // apply here
/// ```
@@ -832,14 +857,35 @@ pub fn nested_keyed_to_hashmap(mut file: File) -> Result<HashMap<String, HashMap
Ok(h)
}
/// read and parse an i64 data
fn read_i64_from(mut file: File) -> Result<i64> {
fn read_from<T>(mut file: File) -> Result<T>
where
T: FromStr,
<T as FromStr>::Err: 'static + Send + Sync + std::error::Error,
{
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.parse::<T>()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
fn read_string_from(mut file: File) -> Result<String> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => Ok(string.trim().to_string()),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
/// read and parse an u64 data
fn read_u64_from(file: File) -> Result<u64> {
read_from::<u64>(file)
}
/// read and parse an i64 data
fn read_i64_from(file: File) -> Result<i64> {
read_from::<i64>(file)
}

View File

@@ -9,15 +9,14 @@
//! See the Kernel's documentation for more information about this subsystem, found at:
//! [Documentation/cgroup-v1/memory.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt)
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Write};
use std::io::Write;
use std::path::PathBuf;
use std::sync::mpsc::Receiver;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::events;
use crate::read_i64_from;
use crate::{read_i64_from, read_string_from, read_u64_from};
use crate::flat_keyed_to_hashmap;
@@ -461,6 +460,10 @@ impl ControllerInternal for MemController {
update!(self, set_tcp_limit, memres.kernel_tcp_memory_limit);
update!(self, set_swappiness, memres.swappiness);
memres.attrs.iter().for_each(|(k, v)| {
let _ = self.set(k, v);
});
Ok(())
}
}
@@ -870,25 +873,6 @@ impl<'a> From<&'a Subsystem> for &'a MemController {
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
fn read_string_from(mut file: File) -> Result<String> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => Ok(string.trim().to_string()),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
#[cfg(test)]
mod tests {
use crate::memory::{

View File

@@ -7,13 +7,13 @@
//!
//! See the Kernel's documentation for more information about this subsystem, found at:
//! [Documentation/cgroup-v1/net_cls.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/net_cls.txt)
use std::fs::File;
use std::io::{Read, Write};
use std::io::Write;
use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::read_u64_from;
use crate::{
ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, Subsystem,
};
@@ -74,17 +74,6 @@ impl<'a> From<&'a Subsystem> for &'a NetClsController {
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
impl NetClsController {
/// Constructs a new `NetClsController` with `root` serving as the root of the control group.
pub fn new(root: PathBuf) -> Self {

View File

@@ -8,13 +8,13 @@
//! See the Kernel's documentation for more information about this subsystem, found at:
//! [Documentation/cgroup-v1/net_prio.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/net_prio.txt)
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::read_u64_from;
use crate::{
ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, Subsystem,
};
@@ -77,17 +77,6 @@ impl<'a> From<&'a Subsystem> for &'a NetPrioController {
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
impl NetPrioController {
/// Constructs a new `NetPrioController` with `root` serving as the root of the control group.
pub fn new(root: PathBuf) -> Self {

View File

@@ -8,13 +8,13 @@
//!
//! See the Kernel's documentation for more information about this subsystem, found at:
//! [Documentation/cgroups-v1/pids.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/pids.txt)
use std::fs::File;
use std::io::{Read, Write};
use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::read_u64_from;
use crate::{
parse_max_value, ControllIdentifier, ControllerInternal, Controllers, MaxValue, PidResources,
Resources, Subsystem,
@@ -89,17 +89,6 @@ impl<'a> From<&'a Subsystem> for &'a PidController {
}
}
fn read_u64_from(mut file: File) -> Result<u64> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => string
.trim()
.parse()
.map_err(|e| Error::with_cause(ParseError, e)),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
impl PidController {
/// Constructors a new `PidController` instance, with `root` serving as the controller's root
/// directory.

View File

@@ -7,13 +7,13 @@
//!
//! See the Kernel's documentation for more information about this subsystem, found at:
//! [Documentation/cgroup-v1/rdma.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/rdma.txt)
use std::fs::File;
use std::io::{Read, Write};
use std::io::Write;
use std::path::PathBuf;
use crate::error::ErrorKind::*;
use crate::error::*;
use crate::read_string_from;
use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};
/// A controller that allows controlling the `rdma` subsystem of a Cgroup.
@@ -66,14 +66,6 @@ impl<'a> From<&'a Subsystem> for &'a RdmaController {
}
}
fn read_string_from(mut file: File) -> Result<String> {
let mut string = String::new();
match file.read_to_string(&mut string) {
Ok(_) => Ok(string.trim().to_string()),
Err(e) => Err(Error::with_cause(ReadFailed, e)),
}
}
impl RdmaController {
/// Constructs a new `RdmaController` with `root` serving as the root of the control group.
pub fn new(root: PathBuf) -> Self {

View File

@@ -5,19 +5,19 @@
//
//! Some simple tests covering the builder pattern for control groups.
use cgroups::blkio::*;
use cgroups::cgroup_builder::*;
use cgroups::cpu::*;
use cgroups::devices::*;
use cgroups::hugetlb::*;
use cgroups::memory::*;
use cgroups::net_cls::*;
use cgroups::pid::*;
use cgroups::*;
use cgroups_rs::blkio::*;
use cgroups_rs::cgroup_builder::*;
use cgroups_rs::cpu::*;
use cgroups_rs::devices::*;
use cgroups_rs::hugetlb::*;
use cgroups_rs::memory::*;
use cgroups_rs::net_cls::*;
use cgroups_rs::pid::*;
use cgroups_rs::*;
#[test]
pub fn test_cpu_res_build() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg: Cgroup = CgroupBuilder::new("test_cpu_res_build")
.cpu()
.shares(85)
@@ -35,7 +35,7 @@ pub fn test_cpu_res_build() {
#[test]
pub fn test_memory_res_build() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg: Cgroup = CgroupBuilder::new("test_memory_res_build")
.memory()
.kernel_memory_limit(128 * 1024 * 1024)
@@ -58,7 +58,7 @@ pub fn test_memory_res_build() {
#[test]
pub fn test_pid_res_build() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg: Cgroup = CgroupBuilder::new("test_pid_res_build")
.pid()
.maximum_number_of_processes(MaxValue::Value(123))
@@ -77,7 +77,7 @@ pub fn test_pid_res_build() {
#[test]
#[ignore] // ignore this test for now, not sure why my kernel doesn't like it
pub fn test_devices_res_build() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg: Cgroup = CgroupBuilder::new("test_devices_res_build")
.devices()
.device(1, 6, DeviceType::Char, true, vec![DevicePermissions::Read])
@@ -103,7 +103,7 @@ pub fn test_devices_res_build() {
#[test]
pub fn test_network_res_build() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
if h.v2() {
// FIXME add cases for v2
return;
@@ -124,7 +124,7 @@ pub fn test_network_res_build() {
#[test]
pub fn test_hugepages_res_build() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
if h.v2() {
// FIXME add cases for v2
return;
@@ -149,7 +149,7 @@ pub fn test_hugepages_res_build() {
#[test]
#[ignore] // high version kernel not support `blkio.weight`
pub fn test_blkio_res_build() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg: Cgroup = CgroupBuilder::new("test_blkio_res_build")
.blkio()
.weight(100)

View File

@@ -5,13 +5,13 @@
//
//! Simple unit tests about the control groups system.
use cgroups::memory::MemController;
use cgroups::Controller;
use cgroups::{Cgroup, CgroupPid, Subsystem};
use cgroups_rs::memory::MemController;
use cgroups_rs::Controller;
use cgroups_rs::{Cgroup, CgroupPid, Subsystem};
#[test]
fn test_tasks_iterator() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let pid = libc::pid_t::from(nix::unistd::getpid()) as u64;
let cg = Cgroup::new(h, String::from("test_tasks_iterator"));
{
@@ -38,10 +38,10 @@ fn test_tasks_iterator() {
#[test]
fn test_cgroup_with_relative_paths() {
if cgroups::hierarchies::is_cgroup2_unified_mode() {
if cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
return;
}
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cgroup_root = h.root();
let cgroup_name = "test_cgroup_with_relative_paths";
@@ -79,10 +79,10 @@ fn test_cgroup_with_relative_paths() {
#[test]
fn test_cgroup_v2() {
if !cgroups::hierarchies::is_cgroup2_unified_mode() {
if !cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
return;
}
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_v2"));
let mem_controller: &MemController = cg.controller_of().unwrap();

View File

@@ -4,12 +4,12 @@
//
//! Simple unit tests about the CPU control groups system.
use cgroups::cpu::CpuController;
use cgroups::Cgroup;
use cgroups_rs::cpu::CpuController;
use cgroups_rs::Cgroup;
#[test]
fn test_cfs_quota_and_periods() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_cfs_quota_and_periods"));
let cpu_controller: &CpuController = cg.controller_of().unwrap();

View File

@@ -4,15 +4,15 @@
// SPDX-License-Identifier: Apache-2.0 or MIT
//
use cgroups::cpuset::CpuSetController;
use cgroups::error::ErrorKind;
use cgroups::{Cgroup, CgroupPid};
use cgroups_rs::cpuset::CpuSetController;
use cgroups_rs::error::ErrorKind;
use cgroups_rs::{Cgroup, CgroupPid};
use std::fs;
#[test]
fn test_cpuset_memory_pressure_root_cg() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_cpuset_memory_pressure_root_cg"));
{
let cpuset: &CpuSetController = cg.controller_of().unwrap();
@@ -26,7 +26,7 @@ fn test_cpuset_memory_pressure_root_cg() {
#[test]
fn test_cpuset_set_cpus() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_cpuset_set_cpus"));
{
let cpuset: &CpuSetController = cg.controller_of().unwrap();
@@ -64,7 +64,7 @@ fn test_cpuset_set_cpus() {
#[test]
fn test_cpuset_set_cpus_add_task() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_cpuset_set_cpus_add_task/sub-dir"));
let cpuset: &CpuSetController = cg.controller_of().unwrap();

View File

@@ -6,17 +6,17 @@
//! Integration tests about the devices subsystem
use cgroups::devices::{DevicePermissions, DeviceType, DevicesController};
use cgroups::{Cgroup, DeviceResource};
use cgroups_rs::devices::{DevicePermissions, DeviceType, DevicesController};
use cgroups_rs::{Cgroup, DeviceResource};
#[test]
fn test_devices_parsing() {
// now only v2
if cgroups::hierarchies::is_cgroup2_unified_mode() {
if cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
return;
}
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_devices_parsing"));
{
let devices: &DevicesController = cg.controller_of().unwrap();

View File

@@ -4,19 +4,19 @@
//
//! Integration tests about the hugetlb subsystem
use cgroups::error::*;
use cgroups::hugetlb::{self, HugeTlbController};
use cgroups::Cgroup;
use cgroups_rs::error::*;
use cgroups_rs::hugetlb::{self, HugeTlbController};
use cgroups_rs::Cgroup;
use std::fs;
#[test]
fn test_hugetlb_sizes() {
// now only v2
if cgroups::hierarchies::is_cgroup2_unified_mode() {
if cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
return;
}
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_hugetlb_sizes"));
{
let hugetlb_controller: &HugeTlbController = cg.controller_of().unwrap();

View File

@@ -4,13 +4,13 @@
//
//! Integration tests about the hugetlb subsystem
use cgroups::memory::{MemController, SetMemory};
use cgroups::Controller;
use cgroups::{Cgroup, MaxValue};
use cgroups_rs::memory::{MemController, SetMemory};
use cgroups_rs::Controller;
use cgroups_rs::{Cgroup, MaxValue};
#[test]
fn test_disable_oom_killer() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_disable_oom_killer"));
{
let mem_controller: &MemController = cg.controller_of().unwrap();
@@ -35,7 +35,7 @@ fn test_disable_oom_killer() {
#[test]
fn set_mem_v2() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
if !h.v2() {
return;
}

View File

@@ -5,9 +5,9 @@
//
//! Integration tests about the pids subsystem
use cgroups::pid::PidController;
use cgroups::Controller;
use cgroups::{Cgroup, MaxValue};
use cgroups_rs::pid::PidController;
use cgroups_rs::Controller;
use cgroups_rs::{Cgroup, MaxValue};
use nix::sys::wait::{waitpid, WaitStatus};
use nix::unistd::{fork, ForkResult};
@@ -16,7 +16,7 @@ use libc::pid_t;
#[test]
fn create_and_delete_cgroup() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("create_and_delete_cgroup"));
{
let pidcontroller: &PidController = cg.controller_of().unwrap();
@@ -30,7 +30,7 @@ fn create_and_delete_cgroup() {
#[test]
fn test_pids_current_is_zero() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_pids_current_is_zero"));
{
let pidcontroller: &PidController = cg.controller_of().unwrap();
@@ -42,7 +42,7 @@ fn test_pids_current_is_zero() {
#[test]
fn test_pids_events_is_zero() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_pids_events_is_zero"));
{
let pidcontroller: &PidController = cg.controller_of().unwrap();
@@ -55,7 +55,7 @@ fn test_pids_events_is_zero() {
#[test]
fn test_pid_events_is_not_zero() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("test_pid_events_is_not_zero"));
{
let pids: &PidController = cg.controller_of().unwrap();

View File

@@ -5,12 +5,12 @@
//
//! Integration test about setting resources using `apply()`
use cgroups::pid::PidController;
use cgroups::{Cgroup, MaxValue, PidResources, Resources};
use cgroups_rs::pid::PidController;
use cgroups_rs::{Cgroup, MaxValue, PidResources, Resources};
#[test]
fn pid_resources() {
let h = cgroups::hierarchies::auto();
let h = cgroups_rs::hierarchies::auto();
let cg = Cgroup::new(h, String::from("pid_resources"));
{
let res = Resources {