mirror of
https://github.com/kata-containers/cgroups-rs.git
synced 2026-08-05 02:13:23 +00:00
Compare commits
55 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0348f0a95e | ||
|
|
d387c6edc7 | ||
|
|
4d8f704a4b | ||
|
|
860b484a30 | ||
|
|
99da9eeb1f | ||
|
|
ed49cf77e2 | ||
|
|
8f65a0ef89 | ||
|
|
f863f31395 | ||
|
|
91e66f0197 | ||
|
|
3340211c6e | ||
|
|
bd31dc0e7d | ||
|
|
0c908cddf8 | ||
|
|
556dea62b9 | ||
|
|
1a8f9823eb | ||
|
|
dda639f5ab | ||
|
|
476219ab93 | ||
|
|
138c85c4b1 | ||
|
|
92122de48d | ||
|
|
1df6e7a26e | ||
|
|
1bdd52470f | ||
|
|
231d9d599e | ||
|
|
a3bd03c662 | ||
|
|
8932df3fa0 | ||
|
|
fa94a1174f | ||
|
|
b4df6016b3 | ||
|
|
0686400268 | ||
|
|
6986c49e70 | ||
|
|
e0bf36ae23 | ||
|
|
2c68f36488 | ||
|
|
0bc1b9821b | ||
|
|
da75ba25d6 | ||
|
|
01475ad515 | ||
|
|
417badd05f | ||
|
|
1720443d58 | ||
|
|
fb55383273 | ||
|
|
0233c1e046 | ||
|
|
bf5af7b195 | ||
|
|
2e3719dbd5 | ||
|
|
4231f35a44 | ||
|
|
88b7aafd05 | ||
|
|
63750887c2 | ||
|
|
09499e7614 | ||
|
|
bcb7c6cd54 | ||
|
|
2554aa65d0 | ||
|
|
34f935be89 | ||
|
|
5485d8dd46 | ||
|
|
ec4cda1dd9 | ||
|
|
4b5a190ecc | ||
|
|
45b626e0c0 | ||
|
|
0e2430fde1 | ||
|
|
5aa7e6c90e | ||
|
|
5bb27a2692 | ||
|
|
0b2a0405e2 | ||
|
|
c4850ef2ef | ||
|
|
aa207edca8 |
1
.clippy.toml
Normal file
1
.clippy.toml
Normal file
@@ -0,0 +1 @@
|
||||
upper-case-acronyms-aggressive = true
|
||||
12
.github/workflows/bvt.yaml
vendored
12
.github/workflows/bvt.yaml
vendored
@@ -1,20 +1,22 @@
|
||||
name: BVT
|
||||
on: [pull_request]
|
||||
env:
|
||||
RUST_VERSION: 1.52
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
- name: Build
|
||||
run: make debug
|
||||
- uses: actions/checkout@v2
|
||||
- run: rustup install ${{ env.RUST_VERSION }} && rustup default ${{ env.RUST_VERSION }}
|
||||
- run: make debug
|
||||
|
||||
fmt:
|
||||
name: Format Check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: rustup install ${{ env.RUST_VERSION }} && rustup default ${{ env.RUST_VERSION }}
|
||||
- run: rustup component add rustfmt
|
||||
- run: make fmt
|
||||
clippy:
|
||||
@@ -22,6 +24,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: rustup install ${{ env.RUST_VERSION }} && rustup default ${{ env.RUST_VERSION }}
|
||||
- run: rustup component add clippy
|
||||
- run: make clippy
|
||||
test:
|
||||
@@ -29,6 +32,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- run: rustup install ${{ env.RUST_VERSION }} && rustup default ${{ env.RUST_VERSION }}
|
||||
- run: make test
|
||||
|
||||
|
||||
|
||||
2
.github/workflows/commit-message-check.yaml
vendored
2
.github/workflows/commit-message-check.yaml
vendored
@@ -48,6 +48,6 @@ jobs:
|
||||
uses: tim-actions/commit-message-checker-with-regex@v0.3.1
|
||||
with:
|
||||
commits: ${{ steps.get-pr-commits.outputs.commits }}
|
||||
pattern: '^.+(\n.{0,72})*$|^.+\n\s*[^a-zA-Z\s\n]|^.+\n\S+$'
|
||||
pattern: '^.+(\n([a-zA-Z].{0,149}|[^a-zA-Z\n].*|Signed-off-by:.*|))+$'
|
||||
error: 'Body line too long (max 72)'
|
||||
post_error: ${{ env.error_msg }}
|
||||
|
||||
@@ -5,7 +5,7 @@ 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.4"
|
||||
version = "0.2.11"
|
||||
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"
|
||||
@@ -14,8 +14,13 @@ readme = "README.md"
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
regex = "1.1"
|
||||
nix = "0.20.0"
|
||||
nix = { version = "0.25.0", default-features = false, features = ["event", "fs", "process"] }
|
||||
libc = "0.2"
|
||||
serde = { version = "1.0", features = ["derive"], optional = true }
|
||||
thiserror = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
libc = "0.2.76"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
110
src/blkio.rs
110
src/blkio.rs
@@ -16,7 +16,8 @@ use crate::error::*;
|
||||
|
||||
use crate::{read_string_from, read_u64_from};
|
||||
use crate::{
|
||||
BlkIoResources, ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem,
|
||||
BlkIoResources, ControllIdentifier, ControllerInternal, Controllers, CustomizedAttribute,
|
||||
Resources, Subsystem,
|
||||
};
|
||||
|
||||
/// A controller that allows controlling the `blkio` subsystem of a Cgroup.
|
||||
@@ -31,6 +32,7 @@ pub struct BlkIoController {
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
/// Per-device information
|
||||
pub struct BlkIoData {
|
||||
/// The major number of the device.
|
||||
@@ -42,6 +44,7 @@ pub struct BlkIoData {
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
/// Per-device activity from the control group.
|
||||
pub struct IoService {
|
||||
/// The major number of the device.
|
||||
@@ -61,6 +64,7 @@ pub struct IoService {
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
/// Per-device activity from the control group.
|
||||
/// Only for cgroup v2
|
||||
pub struct IoStat {
|
||||
@@ -203,6 +207,7 @@ fn parse_blkio_data(s: String) -> Result<Vec<BlkIoData>> {
|
||||
/// Current state and statistics about how throttled are the block devices when accessed from the
|
||||
/// controller's control group.
|
||||
#[derive(Default, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct BlkIoThrottle {
|
||||
/// Statistics about the bytes transferred between the block devices by the tasks in this
|
||||
/// control group.
|
||||
@@ -238,6 +243,7 @@ pub struct BlkIoThrottle {
|
||||
|
||||
/// Statistics and state of the block devices.
|
||||
#[derive(Default, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct BlkIo {
|
||||
/// The number of BIOS requests merged into I/O requests by the control group's tasks.
|
||||
pub io_merged: Vec<IoService>,
|
||||
@@ -373,6 +379,10 @@ impl ControllerInternal for BlkIoController {
|
||||
let _ = self.throttle_write_iops_for_device(dev.major, dev.minor, dev.rate);
|
||||
}
|
||||
|
||||
res.attrs.iter().for_each(|(k, v)| {
|
||||
let _ = self.set(k, v);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -655,8 +665,12 @@ impl BlkIoController {
|
||||
pub fn set_leaf_weight(&self, w: u64) -> Result<()> {
|
||||
self.open_path("blkio.leaf_weight", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(w.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(w.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("blkio.leaf_weight".to_string(), w.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -665,7 +679,15 @@ impl BlkIoController {
|
||||
self.open_path("blkio.leaf_weight_device", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(format!("{}:{} {}", major, minor, weight).as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
.map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed(
|
||||
"blkio.leaf_weight_device".to_string(),
|
||||
format!("{}:{} {}", major, minor, weight),
|
||||
),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -673,99 +695,117 @@ impl BlkIoController {
|
||||
pub fn reset_stats(&self) -> Result<()> {
|
||||
self.open_path("blkio.reset_stats", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all("1".to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all("1".to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("blkio.reset_stats".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Throttle the bytes per second rate of read operation affecting the block device
|
||||
/// `major:minor` to `bps`.
|
||||
pub fn throttle_read_bps_for_device(&self, major: u64, minor: u64, bps: u64) -> Result<()> {
|
||||
let mut file = "blkio.throttle.read_bps_device";
|
||||
let mut file_name = "blkio.throttle.read_bps_device";
|
||||
let mut content = format!("{}:{} {}", major, minor, bps);
|
||||
if self.v2 {
|
||||
file = "io.max";
|
||||
file_name = "io.max";
|
||||
content = format!("{}:{} rbps={}", major, minor, bps);
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), content.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Throttle the I/O operations per second rate of read operation affecting the block device
|
||||
/// `major:minor` to `bps`.
|
||||
pub fn throttle_read_iops_for_device(&self, major: u64, minor: u64, iops: u64) -> Result<()> {
|
||||
let mut file = "blkio.throttle.read_iops_device";
|
||||
let mut file_name = "blkio.throttle.read_iops_device";
|
||||
let mut content = format!("{}:{} {}", major, minor, iops);
|
||||
if self.v2 {
|
||||
file = "io.max";
|
||||
file_name = "io.max";
|
||||
content = format!("{}:{} riops={}", major, minor, iops);
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), content.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
/// Throttle the bytes per second rate of write operation affecting the block device
|
||||
/// `major:minor` to `bps`.
|
||||
pub fn throttle_write_bps_for_device(&self, major: u64, minor: u64, bps: u64) -> Result<()> {
|
||||
let mut file = "blkio.throttle.write_bps_device";
|
||||
let mut file_name = "blkio.throttle.write_bps_device";
|
||||
let mut content = format!("{}:{} {}", major, minor, bps);
|
||||
if self.v2 {
|
||||
file = "io.max";
|
||||
file_name = "io.max";
|
||||
content = format!("{}:{} wbps={}", major, minor, bps);
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), content.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Throttle the I/O operations per second rate of write operation affecting the block device
|
||||
/// `major:minor` to `bps`.
|
||||
pub fn throttle_write_iops_for_device(&self, major: u64, minor: u64, iops: u64) -> Result<()> {
|
||||
let mut file = "blkio.throttle.write_iops_device";
|
||||
let mut file_name = "blkio.throttle.write_iops_device";
|
||||
let mut content = format!("{}:{} {}", major, minor, iops);
|
||||
if self.v2 {
|
||||
file = "io.max";
|
||||
file_name = "io.max";
|
||||
content = format!("{}:{} wiops={}", major, minor, iops);
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), content.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Set the weight of the control group's tasks.
|
||||
pub fn set_weight(&self, w: u64) -> Result<()> {
|
||||
// Attation: may not find in high kernel version.
|
||||
let mut file = "blkio.weight";
|
||||
let mut file_name = "blkio.weight";
|
||||
if self.v2 {
|
||||
file = "io.bfq.weight";
|
||||
file_name = "io.bfq.weight";
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(w.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(w.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), w.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Same as `set_weight()`, but settable per each block device.
|
||||
pub fn set_weight_for_device(&self, major: u64, minor: u64, weight: u64) -> Result<()> {
|
||||
let mut file = "blkio.weight_device";
|
||||
let mut file_name = "blkio.weight_device";
|
||||
if self.v2 {
|
||||
// Attation: there is no weight for device in runc
|
||||
// https://github.com/opencontainers/runc/blob/46be7b612e2533c494e6a251111de46d8e286ed5/libcontainer/cgroups/fs2/io.go#L30
|
||||
// may depends on IO schedulers https://wiki.ubuntu.com/Kernel/Reference/IOSchedulers
|
||||
file = "io.bfq.weight";
|
||||
file_name = "io.bfq.weight";
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(format!("{}:{} {}", major, minor, weight).as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
.map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed(
|
||||
file_name.to_string(),
|
||||
format!("{}:{} {}", major, minor, weight),
|
||||
),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomizedAttribute for BlkIoController {}
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::blkio::{parse_blkio_data, BlkIoData};
|
||||
|
||||
@@ -311,9 +311,8 @@ impl Cgroup {
|
||||
|
||||
pub const UNIFIED_MOUNTPOINT: &str = "/sys/fs/cgroup";
|
||||
|
||||
fn enable_controllers(controllers: &[String], path: &PathBuf) {
|
||||
let mut f = path.clone();
|
||||
f.push("cgroup.subtree_control");
|
||||
fn enable_controllers(controllers: &[String], path: &Path) {
|
||||
let f = path.join("cgroup.subtree_control");
|
||||
for c in controllers {
|
||||
let body = format!("+{}", c);
|
||||
let _rest = fs::write(f.as_path(), body.as_bytes());
|
||||
@@ -360,9 +359,19 @@ fn create_v2_cgroup(root: PathBuf, path: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
pub fn get_cgroups_relative_paths() -> Result<HashMap<String, String>> {
|
||||
let path = "/proc/self/cgroup".to_string();
|
||||
get_cgroups_relative_paths_by_path(path)
|
||||
}
|
||||
|
||||
pub fn get_cgroups_relative_paths_by_pid(pid: u32) -> Result<HashMap<String, String>> {
|
||||
let path = format!("/proc/{}/cgroup", pid);
|
||||
get_cgroups_relative_paths_by_path(path)
|
||||
}
|
||||
|
||||
fn get_cgroups_relative_paths_by_path(path: String) -> Result<HashMap<String, String>> {
|
||||
let mut m = HashMap::new();
|
||||
let content =
|
||||
fs::read_to_string("/proc/self/cgroup").map_err(|e| Error::with_cause(ReadFailed, e))?;
|
||||
fs::read_to_string(path.clone()).map_err(|e| Error::with_cause(ReadFailed(path), e))?;
|
||||
for l in content.lines() {
|
||||
let fl: Vec<&str> = l.split(':').collect();
|
||||
if fl.len() != 3 {
|
||||
|
||||
@@ -240,10 +240,10 @@ impl DeviceResourceBuilder {
|
||||
access: Vec<crate::devices::DevicePermissions>,
|
||||
) -> DeviceResourceBuilder {
|
||||
self.cgroup.resources.devices.devices.push(DeviceResource {
|
||||
allow,
|
||||
devtype,
|
||||
major,
|
||||
minor,
|
||||
devtype,
|
||||
allow,
|
||||
access,
|
||||
});
|
||||
self
|
||||
|
||||
58
src/cpu.rs
58
src/cpu.rs
@@ -36,6 +36,7 @@ pub struct CpuController {
|
||||
|
||||
/// The current state of the control group and its processes.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Cpu {
|
||||
/// Reports CPU time statistics.
|
||||
///
|
||||
@@ -45,7 +46,7 @@ pub struct Cpu {
|
||||
|
||||
/// The current state of the control group and its processes.
|
||||
#[derive(Debug)]
|
||||
struct CFSQuotaAndPeriod {
|
||||
struct CfsQuotaAndPeriod {
|
||||
quota: MaxValue,
|
||||
period: u64,
|
||||
}
|
||||
@@ -130,7 +131,7 @@ impl CpuController {
|
||||
let res = file.read_to_string(&mut s);
|
||||
match res {
|
||||
Ok(_) => Ok(s),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed("cpu.stat".to_string()), e)),
|
||||
}
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
@@ -144,14 +145,15 @@ impl CpuController {
|
||||
/// `shares` to `200` ensures that control group `B` receives twice as much as CPU bandwidth.
|
||||
/// (Assuming both `A` and `B` are of the same parent)
|
||||
pub fn set_shares(&self, shares: u64) -> Result<()> {
|
||||
let mut file = "cpu.shares";
|
||||
let mut file_name = "cpu.shares";
|
||||
if self.v2 {
|
||||
file = "cpu.weight";
|
||||
file_name = "cpu.weight";
|
||||
}
|
||||
// NOTE: .CpuShares is not used here. Conversion is the caller's responsibility.
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(shares.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(shares.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), shares.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -173,8 +175,12 @@ impl CpuController {
|
||||
}
|
||||
self.open_path("cpu.cfs_period_us", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(us.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(us.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpu.cfs_period_us".to_string(), us.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -199,8 +205,12 @@ impl CpuController {
|
||||
}
|
||||
self.open_path("cpu.cfs_quota_us", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(us.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(us.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpu.cfs_quota_us".to_string(), us.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -261,43 +271,51 @@ impl CpuController {
|
||||
let line = format!("{} {}", new_quota, new_period);
|
||||
self.open_path("cpu.max", true).and_then(|mut file| {
|
||||
file.write_all(line.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
.map_err(|e| Error::with_cause(WriteFailed("cpu.max".to_string(), line), e))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_rt_runtime(&self, us: i64) -> Result<()> {
|
||||
self.open_path("cpu.rt_runtime_us", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(us.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(us.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpu.rt_runtime_us".to_string(), us.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_rt_period_us(&self, us: u64) -> Result<()> {
|
||||
self.open_path("cpu.rt_period_us", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(us.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(us.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpu.rt_period_us".to_string(), us.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomizedAttribute for CpuController {}
|
||||
|
||||
fn parse_cfs_quota_and_period(mut file: File) -> Result<CFSQuotaAndPeriod> {
|
||||
fn parse_cfs_quota_and_period(mut file: File) -> Result<CfsQuotaAndPeriod> {
|
||||
let mut content = String::new();
|
||||
file.read_to_string(&mut content)
|
||||
.map_err(|e| Error::with_cause(ReadFailed, e))?;
|
||||
.map_err(|e| Error::with_cause(ReadFailed("cpu.max".to_string()), e))?;
|
||||
|
||||
let fields = content.trim().split(' ').collect::<Vec<&str>>();
|
||||
if fields.len() != 2 {
|
||||
return Err(Error::from_string(format!("invaild format: {}", content)));
|
||||
}
|
||||
|
||||
let quota = parse_max_value(&fields[0].to_string())?;
|
||||
let quota = parse_max_value(fields[0])?;
|
||||
let period = fields[1]
|
||||
.parse::<u64>()
|
||||
.map_err(|e| Error::with_cause(ParseError, e))?;
|
||||
|
||||
Ok(CFSQuotaAndPeriod { quota, period })
|
||||
Ok(CfsQuotaAndPeriod { quota, period })
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ pub struct CpuAcctController {
|
||||
}
|
||||
|
||||
/// Represents the statistics retrieved from the control group.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct CpuAcct {
|
||||
/// Divides the time used by the tasks into `user` time and `system` time.
|
||||
pub stat: String,
|
||||
@@ -147,8 +148,9 @@ impl CpuAcctController {
|
||||
/// Reset the statistics the kernel has gathered about the control group.
|
||||
pub fn reset(&self) -> Result<()> {
|
||||
self.open_path("cpuacct.usage", true).and_then(|mut file| {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(WriteFailed("cpuacct.usage".to_string(), "0".to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
167
src/cpuset.rs
167
src/cpuset.rs
@@ -33,6 +33,7 @@ pub struct CpuSetController {
|
||||
}
|
||||
|
||||
/// The current state of the `cpuset` controller for this control group.
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct CpuSet {
|
||||
/// If true, no other control groups can share the CPUs listed in the `cpus` field.
|
||||
pub cpu_exclusive: bool,
|
||||
@@ -143,7 +144,12 @@ fn find_no_empty_parent(from: &str, file: &str) -> Result<(String, Vec<PathBuf>)
|
||||
let current_value =
|
||||
match ::std::fs::read_to_string(current_path.clone().join(file).to_str().unwrap()) {
|
||||
Ok(cpus) => String::from(cpus.trim()),
|
||||
Err(e) => return Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => {
|
||||
return Err(Error::with_cause(
|
||||
ReadFailed(current_path.display().to_string()),
|
||||
e,
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
if !current_value.is_empty() {
|
||||
@@ -176,7 +182,12 @@ fn copy_from_parent(current: &str, file: &str) -> Result<()> {
|
||||
pb.push(file);
|
||||
match ::std::fs::write(pb.to_str().unwrap(), value.as_bytes()) {
|
||||
Ok(_) => (),
|
||||
Err(e) => return Err(Error::with_cause(WriteFailed, e)),
|
||||
Err(e) => {
|
||||
return Err(Error::with_cause(
|
||||
WriteFailed(pb.display().to_string(), pb.display().to_string()),
|
||||
e,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,11 +357,19 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.cpu_exclusive", true)
|
||||
.and_then(|mut file| {
|
||||
if b {
|
||||
file.write_all(b"1")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"1").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.cpu_exclusive".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.cpu_exclusive".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -361,11 +380,19 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.mem_exclusive", true)
|
||||
.and_then(|mut file| {
|
||||
if b {
|
||||
file.write_all(b"1")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"1").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.mem_exclusive".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.mem_exclusive".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -376,8 +403,9 @@ impl CpuSetController {
|
||||
/// be represented via dashes.
|
||||
pub fn set_cpus(&self, cpus: &str) -> Result<()> {
|
||||
self.open_path("cpuset.cpus", true).and_then(|mut file| {
|
||||
file.write_all(cpus.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(cpus.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed("cpuset.cpus".to_string(), cpus.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -386,8 +414,9 @@ impl CpuSetController {
|
||||
/// Syntax is the same as with `set_cpus()`.
|
||||
pub fn set_mems(&self, mems: &str) -> Result<()> {
|
||||
self.open_path("cpuset.mems", true).and_then(|mut file| {
|
||||
file.write_all(mems.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(mems.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed("cpuset.mems".to_string(), mems.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -400,11 +429,19 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.mem_hardwall", true)
|
||||
.and_then(|mut file| {
|
||||
if b {
|
||||
file.write_all(b"1")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"1").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.mem_hardwall".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.mem_hardwall".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -415,11 +452,19 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.sched_load_balance", true)
|
||||
.and_then(|mut file| {
|
||||
if b {
|
||||
file.write_all(b"1")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"1").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.sched_load_balance".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.sched_load_balance".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -430,8 +475,12 @@ impl CpuSetController {
|
||||
pub fn set_rebalance_relax_domain_level(&self, i: i64) -> Result<()> {
|
||||
self.open_path("cpuset.sched_relax_domain_level", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(i.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(i.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.sched_relax_domain_level".to_string(), i.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -441,11 +490,19 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.memory_migrate", true)
|
||||
.and_then(|mut file| {
|
||||
if b {
|
||||
file.write_all(b"1")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"1").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.memory_migrate".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.memory_migrate".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -456,11 +513,19 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.memory_spread_page", true)
|
||||
.and_then(|mut file| {
|
||||
if b {
|
||||
file.write_all(b"1")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"1").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.memory_spread_page".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.memory_spread_page".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -471,11 +536,19 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.memory_spread_slab", true)
|
||||
.and_then(|mut file| {
|
||||
if b {
|
||||
file.write_all(b"1")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"1").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.memory_spread_slab".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("cpuset.memory_spread_slab".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -492,11 +565,25 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.memory_pressure_enabled", true)
|
||||
.and_then(|mut file| {
|
||||
if b {
|
||||
file.write_all(b"1")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"1").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed(
|
||||
"cpuset.memory_pressure_enabled".to_string(),
|
||||
"1".to_string(),
|
||||
),
|
||||
e,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
file.write_all(b"0")
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(b"0").map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed(
|
||||
"cpuset.memory_pressure_enabled".to_string(),
|
||||
"0".to_string(),
|
||||
),
|
||||
e,
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -32,6 +32,11 @@ pub struct DevicesController {
|
||||
|
||||
/// An enum holding the different types of devices that can be manipulated using this controller.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
derive(serde::Serialize, serde::Deserialize),
|
||||
serde(rename_all = "snake_case")
|
||||
)]
|
||||
pub enum DeviceType {
|
||||
/// The rule applies to all devices.
|
||||
All,
|
||||
@@ -49,6 +54,7 @@ impl Default for DeviceType {
|
||||
|
||||
impl DeviceType {
|
||||
/// Convert a DeviceType into the character that the kernel recognizes.
|
||||
#[allow(clippy::should_implement_trait, clippy::wrong_self_convention)]
|
||||
pub fn to_char(&self) -> char {
|
||||
match self {
|
||||
DeviceType::All => 'a',
|
||||
@@ -70,6 +76,11 @@ impl DeviceType {
|
||||
|
||||
/// An enum with the permissions that can be allowed/denied to the control group.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
derive(serde::Serialize, serde::Deserialize),
|
||||
serde(rename_all = "snake_case")
|
||||
)]
|
||||
pub enum DevicePermissions {
|
||||
/// Permission to read from the device.
|
||||
Read,
|
||||
@@ -82,6 +93,7 @@ pub enum DevicePermissions {
|
||||
|
||||
impl DevicePermissions {
|
||||
/// Convert a DevicePermissions into the character that the kernel recognizes.
|
||||
#[allow(clippy::should_implement_trait, clippy::wrong_self_convention)]
|
||||
pub fn to_char(&self) -> char {
|
||||
match self {
|
||||
DevicePermissions::Read => 'r',
|
||||
@@ -225,8 +237,9 @@ impl DevicesController {
|
||||
};
|
||||
let final_str = format!("{} {}:{} {}", devtype.to_char(), major, minor, perms);
|
||||
self.open_path("devices.allow", true).and_then(|mut file| {
|
||||
file.write_all(final_str.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(final_str.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed("devices.allow".to_string(), final_str), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -257,8 +270,9 @@ impl DevicesController {
|
||||
};
|
||||
let final_str = format!("{} {}:{} {}", devtype.to_char(), major, minor, perms);
|
||||
self.open_path("devices.deny", true).and_then(|mut file| {
|
||||
file.write_all(final_str.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(final_str.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed("devices.deny".to_string(), final_str), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -303,7 +317,7 @@ impl DevicesController {
|
||||
}
|
||||
})
|
||||
},
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed("devices.list".to_string()), e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
35
src/error.rs
35
src/error.rs
@@ -8,40 +8,51 @@ use std::error::Error as StdError;
|
||||
use std::fmt;
|
||||
|
||||
/// The different types of errors that can occur while manipulating control groups.
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
#[derive(thiserror::Error, Debug, Eq, PartialEq)]
|
||||
pub enum ErrorKind {
|
||||
#[error("fs error")]
|
||||
FsError,
|
||||
|
||||
#[error("common error: {0}")]
|
||||
Common(String),
|
||||
|
||||
/// An error occured while writing to a control group file.
|
||||
WriteFailed,
|
||||
#[error("unable to write to a control group file {0}, value {1}")]
|
||||
WriteFailed(String, String),
|
||||
|
||||
/// An error occured while trying to read from a control group file.
|
||||
ReadFailed,
|
||||
#[error("unable to read a control group file {0}")]
|
||||
ReadFailed(String),
|
||||
|
||||
/// An error occured while trying to remove a control group.
|
||||
#[error("unable to remove a control group")]
|
||||
RemoveFailed,
|
||||
|
||||
/// An error occured while trying to parse a value from a control group file.
|
||||
///
|
||||
/// In the future, there will be some information attached to this field.
|
||||
#[error("unable to parse control group file")]
|
||||
ParseError,
|
||||
|
||||
/// You tried to do something invalid.
|
||||
///
|
||||
/// This could be because you tried to set a value in a control group that is not a root
|
||||
/// control group. Or, when using unified hierarchy, you tried to add a task in a leaf node.
|
||||
#[error("the requested operation is invalid")]
|
||||
InvalidOperation,
|
||||
|
||||
/// The path of the control group was invalid.
|
||||
///
|
||||
/// This could be caused by trying to escape the control group filesystem via a string of "..".
|
||||
/// This crate checks against this and operations will fail with this error.
|
||||
#[error("the given path is invalid")]
|
||||
InvalidPath,
|
||||
|
||||
#[error("invalid bytes size")]
|
||||
InvalidBytesSize,
|
||||
|
||||
/// An unknown error has occured.
|
||||
#[error("an unknown error")]
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -53,29 +64,17 @@ pub struct Error {
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let msg = match &self.kind {
|
||||
ErrorKind::FsError => "fs error".to_string(),
|
||||
ErrorKind::Common(s) => s.clone(),
|
||||
ErrorKind::WriteFailed => "unable to write to a control group file".to_string(),
|
||||
ErrorKind::ReadFailed => "unable to read a control group file".to_string(),
|
||||
ErrorKind::RemoveFailed => "unable to remove a control group".to_string(),
|
||||
ErrorKind::ParseError => "unable to parse control group file".to_string(),
|
||||
ErrorKind::InvalidOperation => "the requested operation is invalid".to_string(),
|
||||
ErrorKind::InvalidPath => "the given path is invalid".to_string(),
|
||||
ErrorKind::InvalidBytesSize => "invalid bytes size".to_string(),
|
||||
ErrorKind::Other => "an unknown error".to_string(),
|
||||
};
|
||||
|
||||
if let Some(cause) = &self.cause {
|
||||
write!(f, "{} caused by: {:?}", msg, cause)
|
||||
write!(f, "{} caused by: {:?}", &self.kind, cause)
|
||||
} else {
|
||||
write!(f, "{}", msg)
|
||||
write!(f, "{}", &self.kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdError for Error {
|
||||
fn cause(&self) -> Option<&dyn StdError> {
|
||||
#[allow(clippy::manual_map)]
|
||||
match self.cause {
|
||||
Some(ref x) => Some(&**x),
|
||||
None => None,
|
||||
|
||||
@@ -8,7 +8,7 @@ use nix::sys::eventfd;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Read;
|
||||
use std::os::unix::io::{AsRawFd, FromRawFd};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::thread;
|
||||
|
||||
@@ -17,18 +17,18 @@ use crate::error::*;
|
||||
|
||||
// notify_on_oom returns channel on which you can expect event about OOM,
|
||||
// if process died without OOM this channel will be closed.
|
||||
pub fn notify_on_oom_v2(key: &str, dir: &PathBuf) -> Result<Receiver<String>> {
|
||||
pub fn notify_on_oom_v2(key: &str, dir: &Path) -> Result<Receiver<String>> {
|
||||
register_memory_event(key, dir, "memory.oom_control", "")
|
||||
}
|
||||
|
||||
// notify_on_oom returns channel on which you can expect event about OOM,
|
||||
// if process died without OOM this channel will be closed.
|
||||
pub fn notify_on_oom_v1(key: &str, dir: &PathBuf) -> Result<Receiver<String>> {
|
||||
pub fn notify_on_oom_v1(key: &str, dir: &Path) -> Result<Receiver<String>> {
|
||||
register_memory_event(key, dir, "memory.oom_control", "")
|
||||
}
|
||||
|
||||
// level is one of "low", "medium", or "critical"
|
||||
pub fn notify_memory_pressure(key: &str, dir: &PathBuf, level: &str) -> Result<Receiver<String>> {
|
||||
pub fn notify_memory_pressure(key: &str, dir: &Path, level: &str) -> Result<Receiver<String>> {
|
||||
if level != "low" && level != "medium" && level != "critical" {
|
||||
return Err(Error::from_string(format!(
|
||||
"invalid pressure level {}",
|
||||
@@ -41,26 +41,31 @@ pub fn notify_memory_pressure(key: &str, dir: &PathBuf, level: &str) -> Result<R
|
||||
|
||||
fn register_memory_event(
|
||||
key: &str,
|
||||
cg_dir: &PathBuf,
|
||||
cg_dir: &Path,
|
||||
event_name: &str,
|
||||
arg: &str,
|
||||
) -> Result<Receiver<String>> {
|
||||
let path = cg_dir.join(event_name);
|
||||
let event_file = File::open(path).map_err(|e| Error::with_cause(ReadFailed, e))?;
|
||||
let event_file = File::open(path.clone())
|
||||
.map_err(|e| Error::with_cause(ReadFailed(path.display().to_string()), e))?;
|
||||
|
||||
let eventfd =
|
||||
eventfd(0, EfdFlags::EFD_CLOEXEC).map_err(|e| Error::with_cause(ReadFailed, e))?;
|
||||
let eventfd = eventfd(0, EfdFlags::EFD_CLOEXEC)
|
||||
.map_err(|e| Error::with_cause(ReadFailed("eventfd".to_string()), e))?;
|
||||
|
||||
let event_control_path = cg_dir.join("cgroup.event_control");
|
||||
let data;
|
||||
if arg.is_empty() {
|
||||
data = format!("{} {}", eventfd, event_file.as_raw_fd());
|
||||
let data = if arg.is_empty() {
|
||||
format!("{} {}", eventfd, event_file.as_raw_fd())
|
||||
} else {
|
||||
data = format!("{} {} {}", eventfd, event_file.as_raw_fd(), arg);
|
||||
}
|
||||
format!("{} {} {}", eventfd, event_file.as_raw_fd(), arg)
|
||||
};
|
||||
|
||||
// write to file and set mode to 0700(FIXME)
|
||||
fs::write(&event_control_path, data).map_err(|e| Error::with_cause(WriteFailed, e))?;
|
||||
fs::write(&event_control_path, data.clone()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed(event_control_path.display().to_string(), data),
|
||||
e,
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut eventfd_file = unsafe { File::from_raw_fd(eventfd) };
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ pub struct FreezerController {
|
||||
}
|
||||
|
||||
/// The current state of the control group
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum FreezerState {
|
||||
/// The processes in the control group are _not_ frozen.
|
||||
Thawed,
|
||||
@@ -93,44 +94,44 @@ impl FreezerController {
|
||||
|
||||
/// Freezes the processes in the control group.
|
||||
pub fn freeze(&self) -> Result<()> {
|
||||
let mut file = "freezer.state";
|
||||
let mut file_name = "freezer.state";
|
||||
let mut content = "FROZEN".to_string();
|
||||
if self.v2 {
|
||||
file = "cgroup.freeze";
|
||||
file_name = "cgroup.freeze";
|
||||
content = "1".to_string();
|
||||
}
|
||||
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
.map_err(|e| Error::with_cause(WriteFailed(file_name.to_string(), content), e))
|
||||
})
|
||||
}
|
||||
|
||||
/// Thaws, that is, unfreezes the processes in the control group.
|
||||
pub fn thaw(&self) -> Result<()> {
|
||||
let mut file = "freezer.state";
|
||||
let mut file_name = "freezer.state";
|
||||
let mut content = "THAWED".to_string();
|
||||
if self.v2 {
|
||||
file = "cgroup.freeze";
|
||||
file_name = "cgroup.freeze";
|
||||
content = "0".to_string();
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(content.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
.map_err(|e| Error::with_cause(WriteFailed(file_name.to_string(), content), e))
|
||||
})
|
||||
}
|
||||
|
||||
/// Retrieve the state of processes in the control group.
|
||||
pub fn state(&self) -> Result<FreezerState> {
|
||||
let mut file = "freezer.state";
|
||||
let mut file_name = "freezer.state";
|
||||
if self.v2 {
|
||||
file = "cgroup.freeze";
|
||||
file_name = "cgroup.freeze";
|
||||
}
|
||||
self.open_path(file, false).and_then(|mut file| {
|
||||
self.open_path(file_name, false).and_then(|mut file| {
|
||||
let mut s = String::new();
|
||||
let res = file.read_to_string(&mut s);
|
||||
match res {
|
||||
Ok(_) => match s.as_ref() {
|
||||
Ok(_) => match s.trim() {
|
||||
"FROZEN" => Ok(FreezerState::Frozen),
|
||||
"THAWED" => Ok(FreezerState::Thawed),
|
||||
"1" => Ok(FreezerState::Frozen),
|
||||
@@ -138,7 +139,7 @@ impl FreezerController {
|
||||
"FREEZING" => Ok(FreezerState::Freezing),
|
||||
_ => Err(Error::new(ParseError)),
|
||||
},
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed(file_name.to_string()), e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ use crate::cgroup::Cgroup;
|
||||
/// Process mounts information.
|
||||
///
|
||||
/// See `proc(5)` for format details.
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
|
||||
pub struct Mountinfo {
|
||||
/// Mount pathname relative to the process's root.
|
||||
pub mount_point: PathBuf,
|
||||
@@ -87,7 +87,7 @@ fn mountinfo_file(file: &mut File) -> Vec<Mountinfo> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
r
|
||||
@@ -102,12 +102,12 @@ pub fn mountinfo_self() -> Vec<Mountinfo> {
|
||||
}
|
||||
|
||||
/// The standard, original cgroup implementation. Often referred to as "cgroupv1".
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct V1 {
|
||||
mountinfo: Vec<Mountinfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct V2 {
|
||||
root: String,
|
||||
}
|
||||
@@ -170,7 +170,7 @@ impl Hierarchy for V1 {
|
||||
}
|
||||
|
||||
fn root_control_group(&self) -> Cgroup {
|
||||
Cgroup::load(auto(), "".to_string())
|
||||
Cgroup::load(auto(), "")
|
||||
}
|
||||
|
||||
fn root(&self) -> PathBuf {
|
||||
@@ -202,7 +202,12 @@ impl Hierarchy for V2 {
|
||||
let mut subs = vec![];
|
||||
|
||||
let controllers = ret.unwrap().trim().to_string();
|
||||
let controller_list: Vec<&str> = controllers.split(' ').collect();
|
||||
let mut controller_list: Vec<&str> = controllers.split(' ').collect();
|
||||
|
||||
// The freezer functionality is present in V2, but not as a controller,
|
||||
// but apparently as a core functionality. FreezerController supports
|
||||
// that, but we must explicitly fake the controller here.
|
||||
controller_list.push("freezer");
|
||||
|
||||
for s in controller_list {
|
||||
match s {
|
||||
@@ -241,7 +246,7 @@ impl Hierarchy for V2 {
|
||||
}
|
||||
|
||||
fn root_control_group(&self) -> Cgroup {
|
||||
Cgroup::load(auto(), "".to_string())
|
||||
Cgroup::load(auto(), "")
|
||||
}
|
||||
|
||||
fn root(&self) -> PathBuf {
|
||||
@@ -292,7 +297,10 @@ impl Default for V2 {
|
||||
|
||||
pub const UNIFIED_MOUNTPOINT: &str = "/sys/fs/cgroup";
|
||||
|
||||
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
|
||||
#[cfg(any(
|
||||
all(target_os = "linux", not(target_env = "musl")),
|
||||
target_os = "android"
|
||||
))]
|
||||
pub fn is_cgroup2_unified_mode() -> bool {
|
||||
use nix::sys::statfs;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//!
|
||||
//! 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 log::warn;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -88,7 +89,7 @@ impl<'a> From<&'a Subsystem> for &'a HugeTlbController {
|
||||
impl HugeTlbController {
|
||||
/// Constructs a new `HugeTlbController` with `root` serving as the root of the control group.
|
||||
pub fn new(root: PathBuf, v2: bool) -> Self {
|
||||
let sizes = get_hugepage_sizes().unwrap();
|
||||
let sizes = get_hugepage_sizes();
|
||||
Self {
|
||||
base: root.clone(),
|
||||
path: root,
|
||||
@@ -164,13 +165,14 @@ impl HugeTlbController {
|
||||
/// Set the limit (in bytes) of how much memory can be backed by hugepages of a certain size
|
||||
/// (`hugetlb_size`).
|
||||
pub fn set_limit_in_bytes(&self, hugetlb_size: &str, limit: u64) -> Result<()> {
|
||||
let mut file = format!("hugetlb.{}.limit_in_bytes", hugetlb_size);
|
||||
let mut file_name = format!("hugetlb.{}.limit_in_bytes", hugetlb_size);
|
||||
if self.v2 {
|
||||
file = format!("hugetlb.{}.max", hugetlb_size);
|
||||
file_name = format!("hugetlb.{}.max", hugetlb_size);
|
||||
}
|
||||
self.open_path(&file, true).and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(&file_name, true).and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), limit.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -180,27 +182,29 @@ use regex::Regex;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
|
||||
fn get_hugepage_sizes() -> Result<Vec<String>> {
|
||||
let mut m = Vec::new();
|
||||
fn get_hugepage_sizes() -> Vec<String> {
|
||||
let dirs = fs::read_dir(HUGEPAGESIZE_DIR);
|
||||
if dirs.is_err() {
|
||||
return Ok(m);
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
for e in dirs.unwrap() {
|
||||
let entry = e.unwrap();
|
||||
let name = entry.file_name().into_string().unwrap();
|
||||
let parts: Vec<&str> = name.split('-').collect();
|
||||
if parts.len() != 2 {
|
||||
continue;
|
||||
}
|
||||
let bmap = get_binary_size_map();
|
||||
let size = parse_size(parts[1], &bmap)?;
|
||||
let dabbrs = get_decimal_abbrs();
|
||||
m.push(custom_size(size as f64, 1024.0, &dabbrs));
|
||||
}
|
||||
dirs.unwrap()
|
||||
.filter_map(|e| {
|
||||
let entry = e.map_err(|e| warn!("readdir error: {:?}", e)).ok()?;
|
||||
let name = entry.file_name().into_string().unwrap();
|
||||
let parts: Vec<&str> = name.split('-').collect();
|
||||
if parts.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
let bmap = get_binary_size_map();
|
||||
let size = parse_size(parts[1], &bmap)
|
||||
.map_err(|e| warn!("parse_size error: {:?}", e))
|
||||
.ok()?;
|
||||
let dabbrs = get_decimal_abbrs();
|
||||
|
||||
Ok(m)
|
||||
Some(custom_size(size as f64, 1024.0, &dabbrs))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub const KB: u128 = 1000;
|
||||
|
||||
147
src/lib.rs
147
src/lib.rs
@@ -181,12 +181,21 @@ mod sealed {
|
||||
|
||||
if w {
|
||||
match File::create(&path) {
|
||||
Err(e) => Err(Error::with_cause(ErrorKind::WriteFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(
|
||||
ErrorKind::WriteFailed(
|
||||
path.display().to_string(),
|
||||
"[CREATE FILE]".to_string(),
|
||||
),
|
||||
e,
|
||||
)),
|
||||
Ok(file) => Ok(file),
|
||||
}
|
||||
} else {
|
||||
match File::open(&path) {
|
||||
Err(e) => Err(Error::with_cause(ErrorKind::ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(
|
||||
ErrorKind::ReadFailed(path.display().to_string()),
|
||||
e,
|
||||
)),
|
||||
Ok(file) => Ok(file),
|
||||
}
|
||||
}
|
||||
@@ -198,7 +207,7 @@ mod sealed {
|
||||
let res = file.read_to_string(&mut string);
|
||||
match res {
|
||||
Ok(_) => parse_max_value(&string),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed(f.to_string()), e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -216,8 +225,9 @@ mod sealed {
|
||||
pub trait CustomizedAttribute: ControllerInternal {
|
||||
fn set(&self, key: &str, value: &str) -> Result<()> {
|
||||
self.open_path(key, true).and_then(|mut file| {
|
||||
file.write_all(value.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(value.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(key.to_string(), value.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -226,7 +236,7 @@ mod sealed {
|
||||
let mut string = String::new();
|
||||
match file.read_to_string(&mut string) {
|
||||
Ok(_) => Ok(string.trim().to_owned()),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed(key.to_string()), e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -309,16 +319,24 @@ where
|
||||
fn set_notify_on_release(&self, enable: bool) -> Result<()> {
|
||||
self.open_path("notify_on_release", true)
|
||||
.and_then(|mut file| {
|
||||
write!(file, "{}", enable as i32)
|
||||
.map_err(|e| Error::with_cause(ErrorKind::WriteFailed, e))
|
||||
write!(file, "{}", enable as i32).map_err(|e| {
|
||||
Error::with_cause(
|
||||
ErrorKind::WriteFailed("notify_on_release".to_string(), enable.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Set release_agent
|
||||
fn set_release_agent(&self, path: &str) -> Result<()> {
|
||||
self.open_path("release_agent", true).and_then(|mut file| {
|
||||
file.write_all(path.as_bytes())
|
||||
.map_err(|e| Error::with_cause(ErrorKind::WriteFailed, e))
|
||||
file.write_all(path.as_bytes()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
ErrorKind::WriteFailed("release_agent".to_string(), path.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
/// Does this controller already exist?
|
||||
@@ -332,26 +350,50 @@ where
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
remove_dir(self.get_path())
|
||||
// Compatible with runC for remove dir operation
|
||||
// https://github.com/opencontainers/runc/blob/main/libcontainer/cgroups/utils.go#L272
|
||||
//
|
||||
// We trying to remove all paths five times with increasing delay between tries.
|
||||
// If after all there are not removed cgroups - appropriate error will be
|
||||
// returned.
|
||||
let mut delay = std::time::Duration::from_millis(10);
|
||||
let cgroup_path = self.get_path();
|
||||
for _i in 0..4 {
|
||||
if let Ok(()) = remove_dir(cgroup_path) {
|
||||
return Ok(());
|
||||
}
|
||||
std::thread::sleep(delay);
|
||||
delay *= 2;
|
||||
}
|
||||
|
||||
remove_dir(cgroup_path)
|
||||
}
|
||||
|
||||
/// Attach a task to this controller.
|
||||
fn add_task(&self, pid: &CgroupPid) -> Result<()> {
|
||||
let mut file = "tasks";
|
||||
let mut file_name = "tasks";
|
||||
if self.is_v2() {
|
||||
file = "cgroup.procs";
|
||||
file_name = "cgroup.procs";
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(pid.pid.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(ErrorKind::WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(pid.pid.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
ErrorKind::WriteFailed(file_name.to_string(), pid.pid.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Attach a task to this controller by thread group id.
|
||||
fn add_task_by_tgid(&self, pid: &CgroupPid) -> Result<()> {
|
||||
self.open_path("cgroup.procs", true).and_then(|mut file| {
|
||||
file.write_all(pid.pid.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(ErrorKind::WriteFailed, e))
|
||||
file.write_all(pid.pid.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
ErrorKind::WriteFailed("cgroup.procs".to_string(), pid.pid.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -366,9 +408,12 @@ where
|
||||
let bf = BufReader::new(file);
|
||||
let mut v = Vec::new();
|
||||
for line in bf.lines() {
|
||||
if let Ok(line) = line {
|
||||
let n = line.trim().parse().unwrap_or(0u64);
|
||||
v.push(n);
|
||||
match line {
|
||||
Ok(line) => {
|
||||
let n = line.trim().parse().unwrap_or(0u64);
|
||||
v.push(n);
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
v.into_iter().map(CgroupPid::from).collect()
|
||||
@@ -383,15 +428,18 @@ 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<()> {
|
||||
fn remove_dir(dir: &Path) -> Result<()> {
|
||||
// try the fast path first.
|
||||
if fs::remove_dir(dir).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if dir.exists() && 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))?;
|
||||
for entry in fs::read_dir(dir)
|
||||
.map_err(|e| Error::with_cause(ReadFailed(dir.display().to_string()), e))?
|
||||
{
|
||||
let entry =
|
||||
entry.map_err(|e| Error::with_cause(ReadFailed(dir.display().to_string()), e))?;
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
remove_dir(&path)?;
|
||||
@@ -425,6 +473,7 @@ pub trait Hierarchy: std::fmt::Debug + Send + Sync {
|
||||
|
||||
/// Resource limits for the memory subsystem.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct MemoryResources {
|
||||
/// How much memory (in bytes) can the kernel consume.
|
||||
pub kernel_memory_limit: Option<i64>,
|
||||
@@ -448,13 +497,15 @@ pub struct MemoryResources {
|
||||
/// # Usage:
|
||||
/// ```
|
||||
/// let resource = &mut cgroups_rs::Resources::default();
|
||||
/// resource.memory.attrs.insert("memory.numa_balancing", "true".to_string());
|
||||
/// resource.memory.attrs.insert("memory.numa_balancing".to_string(), "true".to_string());
|
||||
/// // apply here
|
||||
pub attrs: std::collections::HashMap<&'static str, String>,
|
||||
/// ```
|
||||
pub attrs: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// Resources limits on the number of processes.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct PidResources {
|
||||
/// The maximum number of processes that can exist in the control group.
|
||||
///
|
||||
@@ -466,6 +517,7 @@ pub struct PidResources {
|
||||
|
||||
/// Resources limits about how the tasks can use the CPU.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct CpuResources {
|
||||
// cpuset
|
||||
/// A comma-separated list of CPU IDs where the task in the control group can run. Dashes
|
||||
@@ -490,14 +542,15 @@ pub struct CpuResources {
|
||||
/// # Usage:
|
||||
/// ```
|
||||
/// let resource = &mut cgroups_rs::Resources::default();
|
||||
/// resource.cpu.attrs.insert("cpu.cfs_init_buffer_us", "10".to_string());
|
||||
/// resource.cpu.attrs.insert("cpu.cfs_init_buffer_us".to_string(), "10".to_string());
|
||||
/// // apply here
|
||||
/// ```
|
||||
pub attrs: std::collections::HashMap<&'static str, String>,
|
||||
pub attrs: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// A device resource that can be allowed or denied access to.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct DeviceResource {
|
||||
/// If true, access to the device is allowed, otherwise it's denied.
|
||||
pub allow: bool,
|
||||
@@ -513,6 +566,7 @@ pub struct DeviceResource {
|
||||
|
||||
/// Limit the usage of devices for the control group's tasks.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct DeviceResources {
|
||||
/// For each device in the list, the limits in the structure are applied.
|
||||
pub devices: Vec<DeviceResource>,
|
||||
@@ -520,6 +574,7 @@ pub struct DeviceResources {
|
||||
|
||||
/// Assigned priority for a network device.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct NetworkPriority {
|
||||
/// The name (as visible in `ifconfig`) of the interface.
|
||||
pub name: String,
|
||||
@@ -530,6 +585,7 @@ pub struct NetworkPriority {
|
||||
/// Collections of limits and tags that can be imposed on packets emitted by the tasks in the
|
||||
/// control group.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct NetworkResources {
|
||||
/// The networking class identifier to attach to the packets.
|
||||
///
|
||||
@@ -541,6 +597,7 @@ pub struct NetworkResources {
|
||||
|
||||
/// A hugepage type and its consumption limit for the control group.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct HugePageResource {
|
||||
/// The size of the hugepage, i.e. `2MB`, `1GB`, etc.
|
||||
pub size: String,
|
||||
@@ -551,6 +608,7 @@ pub struct HugePageResource {
|
||||
|
||||
/// Provides the ability to set consumption limit on each type of hugepages.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct HugePageResources {
|
||||
/// Set a limit of consumption for each hugepages type.
|
||||
pub limits: Vec<HugePageResource>,
|
||||
@@ -558,6 +616,7 @@ pub struct HugePageResources {
|
||||
|
||||
/// Weight for a particular block device.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct BlkIoDeviceResource {
|
||||
/// The major number of the device.
|
||||
pub major: u64,
|
||||
@@ -571,6 +630,7 @@ pub struct BlkIoDeviceResource {
|
||||
|
||||
/// Provides the ability to throttle a device (both byte/sec, and IO op/s)
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct BlkIoDeviceThrottleResource {
|
||||
/// The major number of the device.
|
||||
pub major: u64,
|
||||
@@ -582,6 +642,7 @@ pub struct BlkIoDeviceThrottleResource {
|
||||
|
||||
/// General block I/O resource limits.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct BlkIoResources {
|
||||
/// The weight of the control group against descendant nodes.
|
||||
pub weight: Option<u16>,
|
||||
@@ -597,10 +658,20 @@ pub struct BlkIoResources {
|
||||
pub throttle_write_bps_device: Vec<BlkIoDeviceThrottleResource>,
|
||||
/// Throttled write IO operations per second can be provided for each device.
|
||||
pub throttle_write_iops_device: Vec<BlkIoDeviceThrottleResource>,
|
||||
|
||||
/// Customized key-value attributes
|
||||
/// # Usage:
|
||||
/// ```
|
||||
/// let resource = &mut cgroups_rs::Resources::default();
|
||||
/// resource.blkio.attrs.insert("io.cost.weight".to_string(), "10".to_string());
|
||||
/// // apply here
|
||||
/// ```
|
||||
pub attrs: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// The resource limits and constraints that will be set on the control group.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Resources {
|
||||
/// Memory usage related limits.
|
||||
pub memory: MemoryResources,
|
||||
@@ -726,6 +797,7 @@ impl Subsystem {
|
||||
|
||||
/// The values for `memory.hight` or `pids.max`
|
||||
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum MaxValue {
|
||||
/// This value is returned when the text is `"max"`.
|
||||
Max,
|
||||
@@ -740,6 +812,7 @@ impl Default for MaxValue {
|
||||
}
|
||||
|
||||
impl MaxValue {
|
||||
#[allow(clippy::should_implement_trait, clippy::wrong_self_convention)]
|
||||
fn to_i64(&self) -> i64 {
|
||||
match self {
|
||||
MaxValue::Max => -1,
|
||||
@@ -752,7 +825,7 @@ impl fmt::Display for MaxValue {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
MaxValue::Max => write!(f, "max"),
|
||||
MaxValue::Value(num) => write!(f, "{}", num.to_string()),
|
||||
MaxValue::Value(num) => write!(f, "{}", num),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -773,7 +846,7 @@ pub fn parse_max_value(s: &str) -> Result<MaxValue> {
|
||||
pub fn flat_keyed_to_vec(mut file: File) -> Result<Vec<(String, i64)>> {
|
||||
let mut content = String::new();
|
||||
file.read_to_string(&mut content)
|
||||
.map_err(|e| Error::with_cause(ReadFailed, e))?;
|
||||
.map_err(|e| Error::with_cause(ReadFailed("FIXME: read_string_from".to_string()), e))?;
|
||||
|
||||
let mut v = Vec::new();
|
||||
for line in content.lines() {
|
||||
@@ -793,7 +866,7 @@ pub fn flat_keyed_to_vec(mut file: File) -> Result<Vec<(String, i64)>> {
|
||||
pub fn flat_keyed_to_hashmap(mut file: File) -> Result<HashMap<String, i64>> {
|
||||
let mut content = String::new();
|
||||
file.read_to_string(&mut content)
|
||||
.map_err(|e| Error::with_cause(ReadFailed, e))?;
|
||||
.map_err(|e| Error::with_cause(ReadFailed("FIXME: read_string_from".to_string()), e))?;
|
||||
|
||||
let mut h = HashMap::new();
|
||||
for line in content.lines() {
|
||||
@@ -813,7 +886,7 @@ pub fn flat_keyed_to_hashmap(mut file: File) -> Result<HashMap<String, i64>> {
|
||||
pub fn nested_keyed_to_hashmap(mut file: File) -> Result<HashMap<String, HashMap<String, i64>>> {
|
||||
let mut content = String::new();
|
||||
file.read_to_string(&mut content)
|
||||
.map_err(|e| Error::with_cause(ReadFailed, e))?;
|
||||
.map_err(|e| Error::with_cause(ReadFailed("FIXME: read_string_from".to_string()), e))?;
|
||||
|
||||
let mut h = HashMap::new();
|
||||
for line in content.lines() {
|
||||
@@ -847,7 +920,10 @@ where
|
||||
.trim()
|
||||
.parse::<T>()
|
||||
.map_err(|e| Error::with_cause(ParseError, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(
|
||||
ReadFailed("FIXME: can't get path in fn read_from".to_string()),
|
||||
e,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -855,7 +931,10 @@ 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)),
|
||||
Err(e) => Err(Error::with_cause(
|
||||
ReadFailed("FIXME: can't get path in fn read_string_from".to_string()),
|
||||
e,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
131
src/memory.rs
131
src/memory.rs
@@ -8,6 +8,7 @@
|
||||
//!
|
||||
//! 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 log::warn;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
@@ -38,6 +39,7 @@ pub struct MemController {
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct SetMemory {
|
||||
pub low: Option<MaxValue>,
|
||||
pub high: Option<MaxValue>,
|
||||
@@ -47,6 +49,7 @@ pub struct SetMemory {
|
||||
|
||||
/// Controls statistics and controls about the OOM killer operating in this control group.
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct OomControl {
|
||||
/// If true, the OOM killer has been disabled for the tasks in this control group.
|
||||
pub oom_kill_disable: bool,
|
||||
@@ -87,6 +90,7 @@ fn parse_oom_control(s: String) -> Result<OomControl> {
|
||||
|
||||
/// Contains statistics about the NUMA locality of the control group's tasks.
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct NumaStat {
|
||||
/// Total amount of pages used by the control group.
|
||||
pub total_pages: u64,
|
||||
@@ -302,6 +306,7 @@ fn parse_numa_stat(s: String) -> Result<NumaStat> {
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct MemoryStat {
|
||||
pub cache: u64,
|
||||
pub rss: u64,
|
||||
@@ -403,6 +408,7 @@ fn parse_memory_stat(s: String) -> Result<MemoryStat> {
|
||||
/// Contains statistics about the current usage of memory and swap (together, not seperately) by
|
||||
/// the control group's tasks.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct MemSwap {
|
||||
/// How many times the limit has been hit.
|
||||
pub fail_cnt: u64,
|
||||
@@ -417,6 +423,7 @@ pub struct MemSwap {
|
||||
/// State of and statistics gathered by the kernel about the memory usage of the control group's
|
||||
/// tasks.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Memory {
|
||||
/// How many times the limit has been hit.
|
||||
pub fail_cnt: u64,
|
||||
@@ -461,6 +468,7 @@ pub struct Memory {
|
||||
/// The current state of and gathered statistics about the kernel's memory usage for TCP-related
|
||||
/// data structures.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Tcp {
|
||||
/// How many times the limit has been hit.
|
||||
pub fail_cnt: u64,
|
||||
@@ -479,6 +487,7 @@ pub struct Tcp {
|
||||
/// these tasks if it would think that the limits here would be violated. It's important to note
|
||||
/// that interrupts in particular might not be able to enforce these limits.
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct Kmem {
|
||||
/// How many times the limit has been hit.
|
||||
pub fail_cnt: u64,
|
||||
@@ -553,8 +562,9 @@ impl MemController {
|
||||
if let Some(v) = v {
|
||||
let v = v.to_string();
|
||||
self.open_path(f, true).and_then(|mut file| {
|
||||
file.write_all(v.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(v.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(f.to_string(), format!("{:?}", v)), e)
|
||||
})
|
||||
})?;
|
||||
}
|
||||
}
|
||||
@@ -760,8 +770,12 @@ impl MemController {
|
||||
/// Reset the fail counter
|
||||
pub fn reset_fail_count(&self) -> Result<()> {
|
||||
self.open_path("memory.failcnt", true).and_then(|mut file| {
|
||||
file.write_all("0".to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all("0".to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("memory.failcnt".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -774,8 +788,12 @@ impl MemController {
|
||||
|
||||
self.open_path("memory.kmem.failcnt", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all("0".to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all("0".to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("memory.kmem.failcnt".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -788,8 +806,12 @@ impl MemController {
|
||||
|
||||
self.open_path("memory.kmem.tcp.failcnt", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all("0".to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all("0".to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("memory.kmem.tcp.failcnt".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -797,8 +819,12 @@ impl MemController {
|
||||
pub fn reset_memswap_fail_count(&self) -> Result<()> {
|
||||
self.open_path("memory.memsw.failcnt", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all("0".to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all("0".to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("memory.memsw.failcnt".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -806,20 +832,25 @@ impl MemController {
|
||||
pub fn reset_max_usage(&self) -> Result<()> {
|
||||
self.open_path("memory.max_usage_in_bytes", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all("0".to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all("0".to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("memory.max_usage_in_bytes".to_string(), "0".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Set the memory usage limit of the control group, in bytes.
|
||||
pub fn set_limit(&self, limit: i64) -> Result<()> {
|
||||
let mut file = "memory.limit_in_bytes";
|
||||
let mut file_name = "memory.limit_in_bytes";
|
||||
if self.v2 {
|
||||
file = "memory.max";
|
||||
file_name = "memory.max";
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), limit.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -832,20 +863,31 @@ impl MemController {
|
||||
|
||||
self.open_path("memory.kmem.limit_in_bytes", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
let r = file.write_all(limit.to_string().as_ref());
|
||||
match r {
|
||||
Ok(()) => Ok(()),
|
||||
Err(ref e) if e.raw_os_error() == Some(libc::EOPNOTSUPP) => {
|
||||
warn!("memory.kmem.limit_in_bytes is unsupported by the kernel");
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(Error::with_cause(
|
||||
WriteFailed("memory.kmem.limit_in_bytes".to_string(), limit.to_string()),
|
||||
e,
|
||||
)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Set the memory+swap limit of the control group, in bytes.
|
||||
pub fn set_memswap_limit(&self, limit: i64) -> Result<()> {
|
||||
let mut file = "memory.memsw.limit_in_bytes";
|
||||
let mut file_name = "memory.memsw.limit_in_bytes";
|
||||
if self.v2 {
|
||||
file = "memory.swap.max";
|
||||
file_name = "memory.swap.max";
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), limit.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -858,8 +900,15 @@ impl MemController {
|
||||
|
||||
self.open_path("memory.kmem.tcp.limit_in_bytes", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(limit.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed(
|
||||
"memory.kmem.tcp.limit_in_bytes".to_string(),
|
||||
limit.to_string(),
|
||||
),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -868,13 +917,14 @@ impl MemController {
|
||||
/// This limit is enforced when the system is nearing OOM conditions. Contrast this with the
|
||||
/// hard limit, which is _always_ enforced.
|
||||
pub fn set_soft_limit(&self, limit: i64) -> Result<()> {
|
||||
let mut file = "memory.soft_limit_in_bytes";
|
||||
let mut file_name = "memory.soft_limit_in_bytes";
|
||||
if self.v2 {
|
||||
file = "memory.low"
|
||||
file_name = "memory.low"
|
||||
}
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(limit.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), limit.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -883,22 +933,27 @@ impl MemController {
|
||||
///
|
||||
/// Note that a value of zero does not imply that the process will not be swapped out.
|
||||
pub fn set_swappiness(&self, swp: u64) -> Result<()> {
|
||||
let mut file = "memory.swappiness";
|
||||
let mut file_name = "memory.swappiness";
|
||||
if self.v2 {
|
||||
file = "memory.swap.max"
|
||||
file_name = "memory.swap.max"
|
||||
}
|
||||
|
||||
self.open_path(file, true).and_then(|mut file| {
|
||||
file.write_all(swp.to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(swp.to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed(file_name.to_string(), swp.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn disable_oom_killer(&self) -> Result<()> {
|
||||
self.open_path("memory.oom_control", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all("1".to_string().as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all("1".to_string().as_ref()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed("memory.oom_control".to_string(), "1".to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -88,8 +88,9 @@ impl NetClsController {
|
||||
self.open_path("net_cls.classid", true)
|
||||
.and_then(|mut file| {
|
||||
let s = format!("{:#08X}", class);
|
||||
file.write_all(s.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(s.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed("net_cls.classid".to_string(), s), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -132,7 +132,15 @@ impl NetPrioController {
|
||||
self.open_path("net_prio.ifpriomap", true)
|
||||
.and_then(|mut file| {
|
||||
file.write_all(format!("{} {}", eif, prio).as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
.map_err(|e| {
|
||||
Error::with_cause(
|
||||
WriteFailed(
|
||||
"net_prio.ifpriomap".to_string(),
|
||||
format!("{} {}", eif, prio),
|
||||
),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ impl PidController {
|
||||
},
|
||||
None => Err(Error::new(ParseError)),
|
||||
},
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed("pids.events".to_string()), e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -130,7 +130,7 @@ impl PidController {
|
||||
let res = file.read_to_string(&mut string);
|
||||
match res {
|
||||
Ok(_) => parse_max_value(&string),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed("pids.max".to_string()), e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -145,7 +145,10 @@ impl PidController {
|
||||
let string_to_write = max_pid.to_string();
|
||||
match file.write_all(string_to_write.as_ref()) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(Error::with_cause(WriteFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(
|
||||
WriteFailed("pids.max".to_string(), format!("{:?}", max_pid)),
|
||||
e,
|
||||
)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -84,8 +84,9 @@ impl RdmaController {
|
||||
/// Set a maximum usage for each RDMA/IB resource.
|
||||
pub fn set_max(&self, max: &str) -> Result<()> {
|
||||
self.open_path("rdma.max", true).and_then(|mut file| {
|
||||
file.write_all(max.as_ref())
|
||||
.map_err(|e| Error::with_cause(WriteFailed, e))
|
||||
file.write_all(max.as_ref()).map_err(|e| {
|
||||
Error::with_cause(WriteFailed("rdma.max".to_string(), max.to_string()), e)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subs
|
||||
pub struct SystemdController {
|
||||
base: PathBuf,
|
||||
path: PathBuf,
|
||||
v2: bool,
|
||||
_v2: bool,
|
||||
}
|
||||
|
||||
impl ControllerInternal for SystemdController {
|
||||
@@ -66,7 +66,7 @@ impl SystemdController {
|
||||
Self {
|
||||
base: root.clone(),
|
||||
path: root,
|
||||
v2,
|
||||
_v2: v2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,8 @@ pub fn test_memory_res_build() {
|
||||
{
|
||||
let c: &MemController = cg.controller_of().unwrap();
|
||||
if !c.v2() {
|
||||
assert_eq!(c.kmem_stat().limit_in_bytes, 128 * 1024 * 1024);
|
||||
// Note: we don't tests the value of c.kmem_stat().limit_in_bytes because on Linux
|
||||
// kernel >= 5.16 setting this value is unsupported.
|
||||
assert_eq!(c.memory_stat().swappiness, 70);
|
||||
}
|
||||
assert_eq!(c.memory_stat().limit_in_bytes, 1024 * 1024 * 1024);
|
||||
@@ -137,11 +138,8 @@ pub fn test_hugepages_res_build() {
|
||||
|
||||
{
|
||||
let c: &HugeTlbController = cg.controller_of().unwrap();
|
||||
assert!(c.limit_in_bytes(&"2MB".to_string()).is_ok());
|
||||
assert_eq!(
|
||||
c.limit_in_bytes(&"2MB".to_string()).unwrap(),
|
||||
4 * 2 * 1024 * 1024
|
||||
);
|
||||
assert!(c.limit_in_bytes("2MB").is_ok());
|
||||
assert_eq!(c.limit_in_bytes("2MB").unwrap(), 4 * 2 * 1024 * 1024);
|
||||
}
|
||||
cg.delete().unwrap();
|
||||
}
|
||||
|
||||
@@ -36,12 +36,12 @@ fn test_cpuset_set_cpus() {
|
||||
assert_eq!(0, set.cpus.len());
|
||||
} else {
|
||||
// for cgroup v1, cpuset is copied from parent.
|
||||
assert_eq!(true, !set.cpus.is_empty());
|
||||
assert!(!set.cpus.is_empty());
|
||||
}
|
||||
|
||||
// 0
|
||||
let r = cpuset.set_cpus("0");
|
||||
assert_eq!(true, r.is_ok());
|
||||
assert!(r.is_ok());
|
||||
|
||||
let set = cpuset.cpuset();
|
||||
assert_eq!(1, set.cpus.len());
|
||||
@@ -51,8 +51,8 @@ fn test_cpuset_set_cpus() {
|
||||
let cpus = fs::read_to_string("/sys/fs/cgroup/cpuset.cpus.effective").unwrap_or_default();
|
||||
let cpus = cpus.trim();
|
||||
if !cpus.is_empty() {
|
||||
let r = cpuset.set_cpus(&cpus);
|
||||
assert_eq!(true, r.is_ok());
|
||||
let r = cpuset.set_cpus(cpus);
|
||||
assert!(r.is_ok());
|
||||
let set = cpuset.cpuset();
|
||||
assert_eq!(1, set.cpus.len());
|
||||
assert_eq!(format!("{}-{}", set.cpus[0].0, set.cpus[0].1), cpus);
|
||||
@@ -72,18 +72,18 @@ fn test_cpuset_set_cpus_add_task() {
|
||||
assert_eq!(0, set.cpus.len());
|
||||
} else {
|
||||
// for cgroup v1, cpuset is copied from parent.
|
||||
assert_eq!(true, !set.cpus.is_empty());
|
||||
assert!(!set.cpus.is_empty());
|
||||
}
|
||||
|
||||
// Add a task to the control group.
|
||||
let pid_i = libc::pid_t::from(nix::unistd::getpid()) as u64;
|
||||
let _ = cg.add_task(CgroupPid::from(pid_i));
|
||||
let tasks = cg.tasks();
|
||||
assert_eq!(true, !tasks.is_empty());
|
||||
assert!(!tasks.is_empty());
|
||||
println!("tasks after added: {:?}", tasks);
|
||||
|
||||
// remove task
|
||||
let _ = cg.remove_task(CgroupPid::from(pid_i));
|
||||
cg.remove_task(CgroupPid::from(pid_i));
|
||||
let tasks = cg.tasks();
|
||||
println!("tasks after deleted: {:?}", tasks);
|
||||
assert_eq!(0, tasks.len());
|
||||
|
||||
@@ -29,7 +29,7 @@ fn test_hugetlb_sizes() {
|
||||
|
||||
for size in sizes {
|
||||
let supported = hugetlb_controller.size_supported(&size);
|
||||
assert_eq!(supported, true);
|
||||
assert!(supported);
|
||||
assert_no_error(hugetlb_controller.failcnt(&size));
|
||||
assert_no_error(hugetlb_controller.limit_in_bytes(&size));
|
||||
assert_no_error(hugetlb_controller.usage_in_bytes(&size));
|
||||
@@ -40,5 +40,5 @@ fn test_hugetlb_sizes() {
|
||||
}
|
||||
|
||||
fn assert_no_error(r: Result<u64>) {
|
||||
assert_eq!(!r.is_err(), true)
|
||||
assert!(r.is_ok())
|
||||
}
|
||||
|
||||
@@ -17,22 +17,37 @@ fn test_disable_oom_killer() {
|
||||
|
||||
// before disable
|
||||
let m = mem_controller.memory_stat();
|
||||
assert_eq!(m.oom_control.oom_kill_disable, false);
|
||||
assert!(!m.oom_control.oom_kill_disable);
|
||||
|
||||
// now only v1
|
||||
if !mem_controller.v2() {
|
||||
// disable oom killer
|
||||
let r = mem_controller.disable_oom_killer();
|
||||
assert_eq!(r.is_err(), false);
|
||||
assert!(r.is_ok());
|
||||
|
||||
// after disable
|
||||
let m = mem_controller.memory_stat();
|
||||
assert_eq!(m.oom_control.oom_kill_disable, true);
|
||||
assert!(m.oom_control.oom_kill_disable);
|
||||
}
|
||||
}
|
||||
cg.delete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_kmem_limit_v1() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
if h.v2() {
|
||||
return;
|
||||
}
|
||||
|
||||
let cg = Cgroup::new(h, String::from("set_kmem_limit_v1"));
|
||||
{
|
||||
let mem_controller: &MemController = cg.controller_of().unwrap();
|
||||
mem_controller.set_kmem_limit(1).unwrap();
|
||||
}
|
||||
cg.delete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_mem_v2() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
@@ -60,7 +75,7 @@ fn set_mem_v2() {
|
||||
max: None,
|
||||
};
|
||||
let r = mem_controller.set_mem(m);
|
||||
assert_eq!(true, r.is_ok());
|
||||
assert!(r.is_ok());
|
||||
|
||||
let m = mem_controller.get_mem().unwrap();
|
||||
// get
|
||||
@@ -77,7 +92,7 @@ fn set_mem_v2() {
|
||||
low: None,
|
||||
};
|
||||
let r = mem_controller.set_mem(m);
|
||||
assert_eq!(true, r.is_ok());
|
||||
assert!(r.is_ok());
|
||||
|
||||
let m = mem_controller.get_mem().unwrap();
|
||||
// get
|
||||
|
||||
@@ -24,7 +24,7 @@ fn pid_resources() {
|
||||
// verify
|
||||
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
||||
let pid_max = pidcontroller.get_pid_max();
|
||||
assert_eq!(pid_max.is_ok(), true);
|
||||
assert!(pid_max.is_ok());
|
||||
assert_eq!(pid_max.unwrap(), MaxValue::Value(512));
|
||||
}
|
||||
cg.delete().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user