mirror of
https://github.com/kata-containers/cgroups-rs.git
synced 2026-08-05 02:13:23 +00:00
Compare commits
104 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b61c07b69 | ||
|
|
45e1f0c274 | ||
|
|
41b5f9c25c | ||
|
|
93a59571e3 | ||
|
|
257012f2bb | ||
|
|
3dd0735324 | ||
|
|
6b338cf997 | ||
|
|
225be2cdbb | ||
|
|
51779d6915 | ||
|
|
5ea28f076c | ||
|
|
aa74f34a91 | ||
|
|
328428ace4 | ||
|
|
c8bb7e1c7e | ||
|
|
25a1340123 | ||
|
|
4203075f19 | ||
|
|
a45ecf0884 | ||
|
|
2f60f213cc | ||
|
|
91146f0ea3 | ||
|
|
e845665b3a | ||
|
|
55034f5b05 | ||
|
|
e2c2618707 | ||
|
|
07878325c3 | ||
|
|
88fb33113d | ||
|
|
1211754b62 | ||
|
|
c9d02afe33 | ||
|
|
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 | ||
|
|
af7a75ce9e | ||
|
|
fb56c817ca | ||
|
|
fdabe52401 | ||
|
|
9ec1010a15 | ||
|
|
610071730d | ||
|
|
0a3e4a828f | ||
|
|
60820bfffb | ||
|
|
2209189244 | ||
|
|
8720aed656 | ||
|
|
16d73e1d59 | ||
|
|
b9ca0a51f1 | ||
|
|
87f05873f0 | ||
|
|
79868d6bfc | ||
|
|
d1d78fe943 | ||
|
|
81d286f31d | ||
|
|
5e538ae286 | ||
|
|
cd5645bb14 | ||
|
|
4a2042068e | ||
|
|
9ac2f5d5ab | ||
|
|
a58cd1d553 | ||
|
|
88a45d4922 | ||
|
|
0c58b5dd84 | ||
|
|
8448548cb3 | ||
|
|
d50245e116 |
1
.clippy.toml
Normal file
1
.clippy.toml
Normal file
@@ -0,0 +1 @@
|
||||
upper-case-acronyms-aggressive = true
|
||||
17
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
17
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal 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.
|
||||
20
.github/ISSUE_TEMPLATE/enhancement-request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/enhancement-request.md
vendored
Normal 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?
|
||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal 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.
|
||||
38
.github/workflows/bvt.yaml
vendored
Normal file
38
.github/workflows/bvt.yaml
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
name: BVT
|
||||
on: [pull_request]
|
||||
env:
|
||||
RUST_VERSION: 1.52
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- 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:
|
||||
name: Clippy 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 clippy
|
||||
- run: make clippy
|
||||
test:
|
||||
name: Run Unit Test
|
||||
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 }}
|
||||
|
||||
31
.travis.yml
31
.travis.yml
@@ -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
|
||||
12
Cargo.toml
12
Cargo.toml
@@ -5,16 +5,22 @@ 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.2"
|
||||
version = "0.3.2"
|
||||
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"
|
||||
nix = { version = "0.25.0", default-features = false, features = ["event", "fs", "process"] }
|
||||
libc = "0.2"
|
||||
procinfo = "0.4.2"
|
||||
serde = { version = "1.0", features = ["derive"], optional = true }
|
||||
thiserror = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
libc = "0.2.76"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
37
Makefile
Normal file
37
Makefile
Normal 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
|
||||
|
||||
375
src/blkio.rs
375
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.
|
||||
@@ -41,7 +43,8 @@ pub struct BlkIoData {
|
||||
pub data: u64,
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Debug)]
|
||||
#[derive(Eq, PartialEq, Debug, Default)]
|
||||
#[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.
|
||||
@@ -56,11 +59,14 @@ pub struct IoService {
|
||||
pub sync: u64,
|
||||
/// How many items were asynchronously transferred.
|
||||
pub r#async: u64,
|
||||
/// How many items were discarded.
|
||||
pub discard: u64,
|
||||
/// Total number of items transferred.
|
||||
pub total: u64,
|
||||
}
|
||||
|
||||
#[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 {
|
||||
@@ -83,44 +89,62 @@ pub struct IoStat {
|
||||
}
|
||||
|
||||
fn parse_io_service(s: String) -> Result<Vec<IoService>> {
|
||||
s.lines()
|
||||
.filter(|x| x.split_whitespace().collect::<Vec<_>>().len() == 3)
|
||||
let mut io_services = Vec::<IoService>::new();
|
||||
let mut io_service = IoService::default();
|
||||
|
||||
let lines = s
|
||||
.lines()
|
||||
.filter(|x| x.split_whitespace().count() == 3)
|
||||
.map(|x| {
|
||||
let mut spl = x.split_whitespace();
|
||||
(spl.nth(0).unwrap(), spl.nth(0).unwrap(), spl.nth(0).unwrap())
|
||||
(
|
||||
spl.next().unwrap(),
|
||||
spl.next().unwrap(),
|
||||
spl.next().unwrap(),
|
||||
)
|
||||
})
|
||||
.map(|(a, b, c)| {
|
||||
let mut spl = a.split(":");
|
||||
(spl.nth(0).unwrap(), spl.nth(0).unwrap(), b, c)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.chunks(5)
|
||||
.map(|x| {
|
||||
match x {
|
||||
[(major, minor, "Read", read_val), (_, _, "Write", write_val),
|
||||
(_, _, "Sync", sync_val), (_, _, "Async", async_val),
|
||||
(_, _, "Total", total_val)] =>
|
||||
Some(IoService {
|
||||
major: major.parse::<i16>().unwrap(),
|
||||
minor: minor.parse::<i16>().unwrap(),
|
||||
read: read_val.parse::<u64>().unwrap(),
|
||||
write: write_val.parse::<u64>().unwrap(),
|
||||
sync: sync_val.parse::<u64>().unwrap(),
|
||||
r#async: async_val.parse::<u64>().unwrap(),
|
||||
total: total_val.parse::<u64>().unwrap(),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.fold(Ok(Vec::new()), |acc, x| {
|
||||
if acc.is_err() || x.is_none() {
|
||||
Err(Error::new(ParseError))
|
||||
} else {
|
||||
let mut acc = acc.unwrap();
|
||||
acc.push(x.unwrap());
|
||||
Ok(acc)
|
||||
}
|
||||
let mut spl = a.split(':');
|
||||
(
|
||||
spl.next().unwrap().parse::<i16>(),
|
||||
spl.next().unwrap().parse::<i16>(),
|
||||
b,
|
||||
c,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for (major_num, minor_num, op, val) in lines.iter() {
|
||||
let major = *major_num.as_ref().map_err(|_| Error::new(ParseError))?;
|
||||
let minor = *minor_num.as_ref().map_err(|_| Error::new(ParseError))?;
|
||||
|
||||
if (major != io_service.major || minor != io_service.minor) && io_service.major != 0 {
|
||||
// new block device
|
||||
io_services.push(io_service);
|
||||
io_service = IoService::default();
|
||||
}
|
||||
|
||||
io_service.major = major;
|
||||
io_service.minor = minor;
|
||||
|
||||
let val = val.parse::<u64>().map_err(|_| Error::new(ParseError))?;
|
||||
|
||||
match *op {
|
||||
"Read" => io_service.read = val,
|
||||
"Write" => io_service.write = val,
|
||||
"Sync" => io_service.sync = val,
|
||||
"Async" => io_service.r#async = val,
|
||||
"Discard" => io_service.discard = val,
|
||||
"Total" => io_service.total = val,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if io_service.major != 0 {
|
||||
io_services.push(io_service);
|
||||
}
|
||||
|
||||
Ok(io_services)
|
||||
}
|
||||
|
||||
fn get_value(s: &str) -> String {
|
||||
@@ -131,15 +155,14 @@ fn get_value(s: &str) -> String {
|
||||
arr[1].to_string()
|
||||
}
|
||||
|
||||
fn parse_io_stat(s: String) -> Result<Vec<IoStat>> {
|
||||
fn parse_io_stat(s: String) -> Vec<IoStat> {
|
||||
// line:
|
||||
// 8:0 rbytes=180224 wbytes=0 rios=3 wios=0 dbytes=0 dios=0
|
||||
let v = s
|
||||
.lines()
|
||||
.filter(|x| x.split_whitespace().collect::<Vec<_>>().len() == 7)
|
||||
s.lines()
|
||||
.filter(|x| x.split_whitespace().count() == 7)
|
||||
.map(|x| {
|
||||
let arr = x.split_whitespace().collect::<Vec<&str>>();
|
||||
let device = arr[0].split(":").collect::<Vec<&str>>();
|
||||
let device = arr[0].split(':').collect::<Vec<&str>>();
|
||||
let (major, minor) = (device[0], device[1]);
|
||||
|
||||
IoStat {
|
||||
@@ -153,14 +176,12 @@ fn parse_io_stat(s: String) -> Result<Vec<IoStat>> {
|
||||
dios: get_value(arr[6]).parse::<u64>().unwrap(),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<IoStat>>();
|
||||
|
||||
Ok(v)
|
||||
.collect::<Vec<IoStat>>()
|
||||
}
|
||||
|
||||
fn parse_io_service_total(s: String) -> Result<u64> {
|
||||
s.lines()
|
||||
.filter(|x| x.split_whitespace().collect::<Vec<_>>().len() == 2)
|
||||
.filter(|x| x.split_whitespace().count() == 2)
|
||||
.fold(Err(Error::new(ParseError)), |_, x| {
|
||||
match x.split_whitespace().collect::<Vec<_>>().as_slice() {
|
||||
["Total", val] => val.parse::<u64>().map_err(|_| Error::new(ParseError)),
|
||||
@@ -197,15 +218,16 @@ fn parse_blkio_data(s: String) -> Result<Vec<BlkIoData>> {
|
||||
});
|
||||
|
||||
if err.is_err() {
|
||||
return Err(Error::new(ParseError));
|
||||
Err(Error::new(ParseError))
|
||||
} else {
|
||||
return Ok(res);
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -241,6 +263,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>,
|
||||
@@ -376,6 +399,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(())
|
||||
}
|
||||
}
|
||||
@@ -407,19 +434,19 @@ impl BlkIoController {
|
||||
Self {
|
||||
base: root.clone(),
|
||||
path: root,
|
||||
v2: v2,
|
||||
v2,
|
||||
}
|
||||
}
|
||||
|
||||
fn blkio_v2(&self) -> BlkIo {
|
||||
let mut blkio: BlkIo = Default::default();
|
||||
blkio.io_stat = self
|
||||
.open_path("io.stat", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_stat)
|
||||
.unwrap_or(Vec::new());
|
||||
|
||||
blkio
|
||||
BlkIo {
|
||||
io_stat: self
|
||||
.open_path("io.stat", false)
|
||||
.and_then(read_string_from)
|
||||
.map(parse_io_stat)
|
||||
.unwrap_or_default(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Gathers statistics about and reports the state of the block devices used by the control
|
||||
@@ -433,222 +460,222 @@ impl BlkIoController {
|
||||
.open_path("blkio.io_merged", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_merged_total: self
|
||||
.open_path("blkio.io_merged", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_merged_recursive: self
|
||||
.open_path("blkio.io_merged_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_merged_recursive_total: self
|
||||
.open_path("blkio.io_merged_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_queued: self
|
||||
.open_path("blkio.io_queued", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_queued_total: self
|
||||
.open_path("blkio.io_queued", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_queued_recursive: self
|
||||
.open_path("blkio.io_queued_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_queued_recursive_total: self
|
||||
.open_path("blkio.io_queued_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_service_bytes: self
|
||||
.open_path("blkio.io_service_bytes", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_service_bytes_total: self
|
||||
.open_path("blkio.io_service_bytes", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_service_bytes_recursive: self
|
||||
.open_path("blkio.io_service_bytes_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_service_bytes_recursive_total: self
|
||||
.open_path("blkio.io_service_bytes_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_serviced: self
|
||||
.open_path("blkio.io_serviced", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_serviced_total: self
|
||||
.open_path("blkio.io_serviced", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_serviced_recursive: self
|
||||
.open_path("blkio.io_serviced_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_serviced_recursive_total: self
|
||||
.open_path("blkio.io_serviced_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_service_time: self
|
||||
.open_path("blkio.io_service_time", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_service_time_total: self
|
||||
.open_path("blkio.io_service_time", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_service_time_recursive: self
|
||||
.open_path("blkio.io_service_time_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_service_time_recursive_total: self
|
||||
.open_path("blkio.io_service_time_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_wait_time: self
|
||||
.open_path("blkio.io_wait_time", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_wait_time_total: self
|
||||
.open_path("blkio.io_wait_time", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_wait_time_recursive: self
|
||||
.open_path("blkio.io_wait_time_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_wait_time_recursive_total: self
|
||||
.open_path("blkio.io_wait_time_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
leaf_weight: self
|
||||
.open_path("blkio.leaf_weight", false)
|
||||
.and_then(|file| read_u64_from(file))
|
||||
.and_then(read_u64_from)
|
||||
.unwrap_or(0u64),
|
||||
leaf_weight_device: self
|
||||
.open_path("blkio.leaf_weight_device", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
sectors: self
|
||||
.open_path("blkio.sectors", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
sectors_recursive: self
|
||||
.open_path("blkio.sectors_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
throttle: BlkIoThrottle {
|
||||
io_service_bytes: self
|
||||
.open_path("blkio.throttle.io_service_bytes", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_service_bytes_total: self
|
||||
.open_path("blkio.throttle.io_service_bytes", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_service_bytes_recursive: self
|
||||
.open_path("blkio.throttle.io_service_bytes_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_service_bytes_recursive_total: self
|
||||
.open_path("blkio.throttle.io_service_bytes_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_serviced: self
|
||||
.open_path("blkio.throttle.io_serviced", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_serviced_total: self
|
||||
.open_path("blkio.throttle.io_serviced", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
io_serviced_recursive: self
|
||||
.open_path("blkio.throttle.io_serviced_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_serviced_recursive_total: self
|
||||
.open_path("blkio.throttle.io_serviced_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_io_service_total)
|
||||
.unwrap_or(0),
|
||||
.unwrap_or_default(),
|
||||
read_bps_device: self
|
||||
.open_path("blkio.throttle.read_bps_device", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
read_iops_device: self
|
||||
.open_path("blkio.throttle.read_iops_device", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
write_bps_device: self
|
||||
.open_path("blkio.throttle.write_bps_device", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
write_iops_device: self
|
||||
.open_path("blkio.throttle.write_iops_device", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
time: self
|
||||
.open_path("blkio.time", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
time_recursive: self
|
||||
.open_path("blkio.time_recursive", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
weight: self
|
||||
.open_path("blkio.weight", false)
|
||||
.and_then(|file| read_u64_from(file))
|
||||
.and_then(read_u64_from)
|
||||
.unwrap_or(0u64),
|
||||
weight_device: self
|
||||
.open_path("blkio.weight_device", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_blkio_data)
|
||||
.unwrap_or(Vec::new()),
|
||||
.unwrap_or_default(),
|
||||
io_stat: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -658,8 +685,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -668,7 +699,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -676,99 +715,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};
|
||||
@@ -780,6 +837,7 @@ mod test {
|
||||
8:32 Write 0
|
||||
8:32 Sync 4280320
|
||||
8:32 Async 0
|
||||
8:32 Discard 1
|
||||
8:32 Total 4280320
|
||||
8:48 Read 5705479168
|
||||
8:48 Write 56096055296
|
||||
@@ -796,28 +854,6 @@ mod test {
|
||||
8:0 Sync 7192576
|
||||
8:0 Async 0
|
||||
8:0 Total 7192576
|
||||
Total 61823067136
|
||||
";
|
||||
|
||||
static TEST_WRONG_VALUE: &str = "\
|
||||
8:32 Read 4280320
|
||||
8:32 Write 0
|
||||
8:32 Async 0
|
||||
8:32 Total 4280320 8:48 Read 5705479168
|
||||
8:48 Write 56096055296
|
||||
8:48 Sync 11213923328
|
||||
8:48 Async 50587611136
|
||||
8:48 Total 61801534464
|
||||
8:16 Read 10059776
|
||||
8:16 Write 0
|
||||
8:16 Sync 10059776
|
||||
8:16 Async 0
|
||||
8:16 Total 10059776
|
||||
8:0 Read 7192576
|
||||
8:0 Write 0
|
||||
8:0 Sync 7192576
|
||||
8:0 Async 0
|
||||
8:0 Total 7192576
|
||||
Total 61823067136
|
||||
";
|
||||
|
||||
@@ -847,6 +883,7 @@ Total 61823067136
|
||||
write: 0,
|
||||
sync: 4280320,
|
||||
r#async: 0,
|
||||
discard: 1,
|
||||
total: 4280320,
|
||||
},
|
||||
IoService {
|
||||
@@ -856,6 +893,7 @@ Total 61823067136
|
||||
write: 56096055296,
|
||||
sync: 11213923328,
|
||||
r#async: 50587611136,
|
||||
discard: 0,
|
||||
total: 61801534464,
|
||||
},
|
||||
IoService {
|
||||
@@ -865,6 +903,7 @@ Total 61823067136
|
||||
write: 0,
|
||||
sync: 10059776,
|
||||
r#async: 0,
|
||||
discard: 0,
|
||||
total: 10059776,
|
||||
},
|
||||
IoService {
|
||||
@@ -874,12 +913,34 @@ Total 61823067136
|
||||
write: 0,
|
||||
sync: 7192576,
|
||||
r#async: 0,
|
||||
discard: 0,
|
||||
total: 7192576,
|
||||
}
|
||||
]
|
||||
);
|
||||
let err = parse_io_service(TEST_WRONG_VALUE.to_string()).unwrap_err();
|
||||
assert_eq!(err.kind(), &ErrorKind::ParseError,);
|
||||
|
||||
let invalid_values = vec![
|
||||
"\
|
||||
8:32 Read 4280320
|
||||
8:32 Write a
|
||||
8:32 Async 1
|
||||
",
|
||||
"\
|
||||
8:32 Read 4280320
|
||||
b:32 Write 1
|
||||
8:32 Async 1
|
||||
",
|
||||
"\
|
||||
8:32 Read 4280320
|
||||
8:32 Write 1
|
||||
8:c Async 1
|
||||
",
|
||||
];
|
||||
|
||||
for value in invalid_values {
|
||||
let err = parse_io_service(value.to_string()).unwrap_err();
|
||||
assert_eq!(err.kind(), &ErrorKind::ParseError,);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
318
src/cgroup.rs
318
src/cgroup.rs
@@ -16,6 +16,11 @@ use std::convert::From;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const CGROUP_MODE_DOMAIN: &str = "domain";
|
||||
pub const CGROUP_MODE_DOMAIN_THREADED: &str = "domain threaded";
|
||||
pub const CGROUP_MODE_DOMAIN_INVALID: &str = "domain invalid";
|
||||
pub const CGROUP_MODE_THREADED: &str = "threaded";
|
||||
|
||||
/// A control group is the central structure to this crate.
|
||||
///
|
||||
///
|
||||
@@ -36,14 +41,18 @@ pub struct Cgroup {
|
||||
/// The hierarchy.
|
||||
hier: Box<dyn Hierarchy>,
|
||||
path: String,
|
||||
|
||||
/// List of controllers specifically enabled in the control group.
|
||||
specified_controllers: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Clone for Cgroup {
|
||||
fn clone(&self) -> Self {
|
||||
Cgroup {
|
||||
subsystems: self.subsystems.clone(),
|
||||
path: self.path.clone(),
|
||||
hier: crate::hierarchies::auto(),
|
||||
path: self.path.clone(),
|
||||
specified_controllers: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,48 +63,67 @@ impl Default for Cgroup {
|
||||
subsystems: Vec::new(),
|
||||
hier: crate::hierarchies::auto(),
|
||||
path: "".to_string(),
|
||||
specified_controllers: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Cgroup {
|
||||
pub fn v2(&self) -> bool {
|
||||
self.hier.v2()
|
||||
}
|
||||
|
||||
/// Create this control group.
|
||||
fn create(&self) {
|
||||
fn create(&self) -> Result<()> {
|
||||
if self.hier.v2() {
|
||||
let _ret = create_v2_cgroup(self.hier.root().clone(), &self.path);
|
||||
create_v2_cgroup(self.hier.root(), &self.path, &self.specified_controllers)
|
||||
} else {
|
||||
for subsystem in &self.subsystems {
|
||||
subsystem.to_controller().create();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn v2(&self) -> bool {
|
||||
self.hier.v2()
|
||||
}
|
||||
|
||||
/// Create a new control group in the hierarchy `hier`, with name `path`.
|
||||
///
|
||||
/// Returns a handle to the control group that can be used to manipulate it.
|
||||
pub fn new<P: AsRef<Path>>(hier: Box<dyn Hierarchy>, path: P) -> Cgroup {
|
||||
pub fn new<P: AsRef<Path>>(hier: Box<dyn Hierarchy>, path: P) -> Result<Cgroup> {
|
||||
let cg = Cgroup::load(hier, path);
|
||||
cg.create();
|
||||
cg
|
||||
cg.create()?;
|
||||
Ok(cg)
|
||||
}
|
||||
|
||||
/// Create a new control group in the hierarchy `hier`, with name `path`.
|
||||
///
|
||||
/// Returns a handle to the control group that can be used to manipulate it.
|
||||
pub fn new_with_specified_controllers<P: AsRef<Path>>(
|
||||
hier: Box<dyn Hierarchy>,
|
||||
path: P,
|
||||
specified_controllers: Option<Vec<String>>,
|
||||
) -> Result<Cgroup> {
|
||||
let cg = if let Some(sc) = specified_controllers {
|
||||
Cgroup::load_with_specified_controllers(hier, path, sc)
|
||||
} else {
|
||||
Cgroup::load(hier, path)
|
||||
};
|
||||
cg.create()?;
|
||||
Ok(cg)
|
||||
}
|
||||
|
||||
/// Create a new control group in the hierarchy `hier`, with name `path` and `relative_paths`
|
||||
///
|
||||
/// Returns a handle to the control group that can be used to manipulate it.
|
||||
///
|
||||
/// Note that this method is only meaningful for cgroup v1, call it is equivalent to call `new` in the v2 mode
|
||||
/// Note that this method is only meaningful for cgroup v1, call it is equivalent to call `new` in the v2 mode.
|
||||
pub fn new_with_relative_paths<P: AsRef<Path>>(
|
||||
hier: Box<dyn Hierarchy>,
|
||||
path: P,
|
||||
relative_paths: HashMap<String, String>,
|
||||
) -> Cgroup {
|
||||
) -> Result<Cgroup> {
|
||||
let cg = Cgroup::load_with_relative_paths(hier, path, relative_paths);
|
||||
cg.create();
|
||||
cg
|
||||
cg.create()?;
|
||||
Ok(cg)
|
||||
}
|
||||
|
||||
/// Create a handle for a control group in the hierarchy `hier`, with name `path`.
|
||||
@@ -112,13 +140,39 @@ impl Cgroup {
|
||||
.collect::<Vec<_>>();
|
||||
}
|
||||
|
||||
let cg = Cgroup {
|
||||
Cgroup {
|
||||
path: path.to_str().unwrap().to_string(),
|
||||
subsystems: subsystems,
|
||||
subsystems,
|
||||
hier,
|
||||
};
|
||||
specified_controllers: None,
|
||||
}
|
||||
}
|
||||
|
||||
cg
|
||||
/// Create a handle for a specified control group in the hierarchy `hier`, with name `path`.
|
||||
///
|
||||
/// Returns a handle to the control group (that possibly does not exist until `create()` has
|
||||
/// been called on the cgroup.
|
||||
pub fn load_with_specified_controllers<P: AsRef<Path>>(
|
||||
hier: Box<dyn Hierarchy>,
|
||||
path: P,
|
||||
specified_controllers: Vec<String>,
|
||||
) -> Cgroup {
|
||||
let path = path.as_ref();
|
||||
let mut subsystems = hier.subsystems();
|
||||
if path.as_os_str() != "" {
|
||||
subsystems = subsystems
|
||||
.into_iter()
|
||||
.filter(|x| specified_controllers.contains(&x.controller_name()))
|
||||
.map(|x| x.enter(path))
|
||||
.collect::<Vec<_>>();
|
||||
}
|
||||
|
||||
Cgroup {
|
||||
path: path.to_str().unwrap().to_string(),
|
||||
subsystems,
|
||||
hier,
|
||||
specified_controllers: Some(specified_controllers),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a handle for a control group in the hierarchy `hier`, with name `path` and `relative_paths`
|
||||
@@ -146,7 +200,7 @@ impl Cgroup {
|
||||
let cn = x.controller_name();
|
||||
if relative_paths.contains_key(&cn) {
|
||||
let rp = relative_paths.get(&cn).unwrap();
|
||||
let valid_path = rp.trim_start_matches("/").to_string();
|
||||
let valid_path = rp.trim_start_matches('/').to_string();
|
||||
let mut p = PathBuf::from(valid_path);
|
||||
p.push(path);
|
||||
x.enter(p.as_ref())
|
||||
@@ -157,13 +211,12 @@ impl Cgroup {
|
||||
.collect::<Vec<_>>();
|
||||
}
|
||||
|
||||
let cg = Cgroup {
|
||||
subsystems: subsystems,
|
||||
Cgroup {
|
||||
subsystems,
|
||||
hier,
|
||||
path: path.to_str().unwrap().to_string(),
|
||||
};
|
||||
|
||||
cg
|
||||
specified_controllers: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The list of subsystems that this control group supports.
|
||||
@@ -179,8 +232,8 @@ impl Cgroup {
|
||||
/// will change.
|
||||
pub fn delete(&self) -> Result<()> {
|
||||
if self.v2() {
|
||||
if self.path != "" {
|
||||
let mut p = self.hier.root().clone();
|
||||
if !self.path.is_empty() {
|
||||
let mut p = self.hier.root();
|
||||
p.push(self.path.clone());
|
||||
return fs::remove_dir(p).map_err(|e| Error::with_cause(RemoveFailed, e));
|
||||
}
|
||||
@@ -222,7 +275,7 @@ impl Cgroup {
|
||||
/// let cpu: &CpuController = control_group.controller_of()
|
||||
/// .expect("No cpu controller attached!");
|
||||
/// ```
|
||||
pub fn controller_of<'a, T>(self: &'a Self) -> Option<&'a T>
|
||||
pub fn controller_of<'a, T>(&'a self) -> Option<&'a T>
|
||||
where
|
||||
&'a T: From<&'a Subsystem>,
|
||||
T: Controller + ControllIdentifier,
|
||||
@@ -237,36 +290,137 @@ impl Cgroup {
|
||||
None
|
||||
}
|
||||
|
||||
/// Removes tasks from the control group by thread group id.
|
||||
///
|
||||
/// Note that this means that the task will be moved back to the root control group in the
|
||||
/// hierarchy and any rules applied to that control group will _still_ apply to the proc.
|
||||
pub fn remove_task_by_tgid(&self, tgid: CgroupPid) -> Result<()> {
|
||||
self.hier.root_control_group().add_task_by_tgid(tgid)
|
||||
}
|
||||
|
||||
/// Removes a task from the control group.
|
||||
///
|
||||
/// Note that this means that the task will be moved back to the root control group in the
|
||||
/// hierarchy and any rules applied to that control group will _still_ apply to the task.
|
||||
pub fn remove_task(&self, pid: CgroupPid) {
|
||||
let _ = self.hier.root_control_group().add_task(pid);
|
||||
pub fn remove_task(&self, tid: CgroupPid) -> Result<()> {
|
||||
self.hier.root_control_group().add_task(tid)
|
||||
}
|
||||
|
||||
/// Moves tasks to the parent control group by thread group id.
|
||||
pub fn move_task_to_parent_by_tgid(&self, tgid: CgroupPid) -> Result<()> {
|
||||
self.hier
|
||||
.parent_control_group(&self.path)
|
||||
.add_task_by_tgid(tgid)
|
||||
}
|
||||
|
||||
/// Moves a task to the parent control group.
|
||||
pub fn move_task_to_parent(&self, tid: CgroupPid) -> Result<()> {
|
||||
self.hier.parent_control_group(&self.path).add_task(tid)
|
||||
}
|
||||
|
||||
/// Return a handle to the parent control group in the hierarchy.
|
||||
pub fn parent_control_group(&self) -> Cgroup {
|
||||
self.hier.parent_control_group(&self.path)
|
||||
}
|
||||
|
||||
/// Kill every process in the control group. Only supported for v2 cgroups and on
|
||||
/// kernels 5.14+. This will fail with InvalidOperation if the 'cgroup.kill' file does
|
||||
/// not exist.
|
||||
pub fn kill(&self) -> Result<()> {
|
||||
if !self.v2() {
|
||||
return Err(Error::new(CgroupVersion));
|
||||
}
|
||||
|
||||
let val = "1";
|
||||
let file_name = "cgroup.kill";
|
||||
let p = self.hier.root().join(self.path.clone()).join(file_name);
|
||||
|
||||
// If cgroup.kill doesn't exist they're not on 5.14+ so lets
|
||||
// surface some error the caller can check against.
|
||||
if !p.exists() {
|
||||
return Err(Error::new(InvalidOperation));
|
||||
}
|
||||
|
||||
fs::write(p, val)
|
||||
.map_err(|e| Error::with_cause(WriteFailed(file_name.to_string(), val.to_string()), e))
|
||||
}
|
||||
|
||||
/// Attach a task to the control group.
|
||||
pub fn add_task(&self, pid: CgroupPid) -> Result<()> {
|
||||
pub fn add_task(&self, tid: CgroupPid) -> Result<()> {
|
||||
if self.v2() {
|
||||
let subsystems = self.subsystems();
|
||||
if subsystems.len() > 0 {
|
||||
if !subsystems.is_empty() {
|
||||
let c = subsystems[0].to_controller();
|
||||
c.add_task(&pid)
|
||||
let cgroup_type = self.get_cgroup_type()?;
|
||||
// In cgroup v2, writing to the cgroup.threads file is only supported in thread mode.
|
||||
if cgroup_type == *CGROUP_MODE_DOMAIN_THREADED
|
||||
|| cgroup_type == *CGROUP_MODE_THREADED
|
||||
{
|
||||
// It is used to move the threads of a process into a cgroup in thread mode.
|
||||
c.add_task(&tid)
|
||||
} else {
|
||||
// When the cgroup type is domain or domain invalid,
|
||||
// cgroup.threads cannot be written.
|
||||
Err(Error::new(CgroupMode))
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
Err(Error::new(SubsystemsEmpty))
|
||||
}
|
||||
} else {
|
||||
self.subsystems()
|
||||
.iter()
|
||||
.try_for_each(|sub| sub.to_controller().add_task(&pid))
|
||||
.try_for_each(|sub| sub.to_controller().add_task(&tid))
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach a task to the control group by thread group id.
|
||||
pub fn add_task_by_tgid(&self, pid: CgroupPid) -> Result<()> {
|
||||
self.subsystems()
|
||||
.iter()
|
||||
.try_for_each(|sub| sub.to_controller().add_task_by_tgid(&pid))
|
||||
/// Attach tasks to the control group by thread group id.
|
||||
pub fn add_task_by_tgid(&self, tgid: CgroupPid) -> Result<()> {
|
||||
if self.v2() {
|
||||
let subsystems = self.subsystems();
|
||||
if !subsystems.is_empty() {
|
||||
let c = subsystems[0].to_controller();
|
||||
// It is used to move a thread of the process to a cgroup,
|
||||
// and other threads of the process will also move together.
|
||||
c.add_task_by_tgid(&tgid)
|
||||
} else {
|
||||
Err(Error::new(SubsystemsEmpty))
|
||||
}
|
||||
} else {
|
||||
self.subsystems()
|
||||
.iter()
|
||||
.try_for_each(|sub| sub.to_controller().add_task_by_tgid(&tgid))
|
||||
}
|
||||
}
|
||||
|
||||
/// set cgroup.type
|
||||
pub fn set_cgroup_type(&self, cgroup_type: &str) -> Result<()> {
|
||||
if self.v2() {
|
||||
let subsystems = self.subsystems();
|
||||
if !subsystems.is_empty() {
|
||||
let c = subsystems[0].to_controller();
|
||||
c.set_cgroup_type(cgroup_type)
|
||||
} else {
|
||||
Err(Error::new(SubsystemsEmpty))
|
||||
}
|
||||
} else {
|
||||
Err(Error::new(CgroupVersion))
|
||||
}
|
||||
}
|
||||
|
||||
/// get cgroup.type
|
||||
pub fn get_cgroup_type(&self) -> Result<String> {
|
||||
if self.v2() {
|
||||
let subsystems = self.subsystems();
|
||||
if !subsystems.is_empty() {
|
||||
let c = subsystems[0].to_controller();
|
||||
let cgroup_type = c.get_cgroup_type()?;
|
||||
Ok(cgroup_type)
|
||||
} else {
|
||||
Err(Error::new(SubsystemsEmpty))
|
||||
}
|
||||
} else {
|
||||
Err(Error::new(CgroupVersion))
|
||||
}
|
||||
}
|
||||
|
||||
/// Set notify_on_release to the control group.
|
||||
@@ -285,13 +439,40 @@ impl Cgroup {
|
||||
.try_for_each(|sub| sub.to_controller().set_release_agent(path))
|
||||
}
|
||||
|
||||
/// Returns an Iterator that can be used to iterate over the procs that are currently in the
|
||||
/// control group.
|
||||
pub fn procs(&self) -> Vec<CgroupPid> {
|
||||
// Collect the procs from all subsystems
|
||||
let mut v = if self.v2() {
|
||||
let subsystems = self.subsystems();
|
||||
if !subsystems.is_empty() {
|
||||
let c = subsystems[0].to_controller();
|
||||
c.procs()
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
} else {
|
||||
self.subsystems()
|
||||
.iter()
|
||||
.map(|x| x.to_controller().procs())
|
||||
.fold(vec![], |mut acc, mut x| {
|
||||
acc.append(&mut x);
|
||||
acc
|
||||
})
|
||||
};
|
||||
|
||||
v.sort();
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
/// Returns an Iterator that can be used to iterate over the tasks that are currently in the
|
||||
/// control group.
|
||||
pub fn tasks(&self) -> Vec<CgroupPid> {
|
||||
// Collect the tasks from all subsystems
|
||||
let mut v = if self.v2() {
|
||||
let subsystems = self.subsystems();
|
||||
if subsystems.len() > 0 {
|
||||
if !subsystems.is_empty() {
|
||||
let c = subsystems[0].to_controller();
|
||||
c.tasks()
|
||||
} else {
|
||||
@@ -313,11 +494,10 @@ impl Cgroup {
|
||||
}
|
||||
}
|
||||
|
||||
pub const UNIFIED_MOUNTPOINT: &'static str = "/sys/fs/cgroup";
|
||||
pub const UNIFIED_MOUNTPOINT: &str = "/sys/fs/cgroup";
|
||||
|
||||
fn enable_controllers(controllers: &Vec<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());
|
||||
@@ -327,31 +507,43 @@ fn enable_controllers(controllers: &Vec<String>, path: &PathBuf) {
|
||||
fn supported_controllers() -> Vec<String> {
|
||||
let p = format!("{}/{}", UNIFIED_MOUNTPOINT, "cgroup.controllers");
|
||||
let ret = fs::read_to_string(p.as_str());
|
||||
ret.unwrap_or(String::new())
|
||||
.split(" ")
|
||||
ret.unwrap_or_default()
|
||||
.split(' ')
|
||||
.map(|x| x.to_string())
|
||||
.collect::<Vec<String>>()
|
||||
}
|
||||
|
||||
fn create_v2_cgroup(root: PathBuf, path: &str) -> Result<()> {
|
||||
fn create_v2_cgroup(
|
||||
root: PathBuf,
|
||||
path: &str,
|
||||
specified_controllers: &Option<Vec<String>>,
|
||||
) -> Result<()> {
|
||||
// controler list ["memory", "cpu"]
|
||||
let controllers = supported_controllers();
|
||||
let controllers = if let Some(s_controllers) = specified_controllers.clone() {
|
||||
if verify_supported_controllers(s_controllers.as_ref()) {
|
||||
s_controllers
|
||||
} else {
|
||||
return Err(Error::new(ErrorKind::SpecifiedControllers));
|
||||
}
|
||||
} else {
|
||||
supported_controllers()
|
||||
};
|
||||
|
||||
let mut fp = root;
|
||||
|
||||
// enable for root
|
||||
enable_controllers(&controllers, &fp);
|
||||
|
||||
// path: "a/b/c"
|
||||
let elements = path.split("/").collect::<Vec<&str>>();
|
||||
let elements = path.split('/').collect::<Vec<&str>>();
|
||||
let last_index = elements.len() - 1;
|
||||
for (i, ele) in elements.iter().enumerate() {
|
||||
// ROOT/a
|
||||
fp.push(ele);
|
||||
// create dir, need not check if is a file or directory
|
||||
if !fp.exists() {
|
||||
match ::std::fs::create_dir(fp.clone()) {
|
||||
Err(e) => return Err(Error::with_cause(ErrorKind::FsError, e)),
|
||||
Ok(_) => {}
|
||||
if let Err(e) = std::fs::create_dir(fp.clone()) {
|
||||
return Err(Error::with_cause(ErrorKind::FsError, e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,10 +556,30 @@ fn create_v2_cgroup(root: PathBuf, path: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn verify_supported_controllers(controllers: &[String]) -> bool {
|
||||
let sc = supported_controllers();
|
||||
for controller in controllers.iter() {
|
||||
if !sc.contains(controller) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -57,11 +57,11 @@
|
||||
//! .read(6, 1, 10)
|
||||
//! .write(11, 1, 100)
|
||||
//! .done()
|
||||
//! .build(h);
|
||||
//! .build(h).unwrap();
|
||||
//! ```
|
||||
|
||||
use crate::{
|
||||
BlkIoDeviceResource, BlkIoDeviceThrottleResource, Cgroup, DeviceResource, Hierarchy,
|
||||
BlkIoDeviceResource, BlkIoDeviceThrottleResource, Cgroup, DeviceResource, Error, Hierarchy,
|
||||
HugePageResource, MaxValue, NetworkPriority, Resources,
|
||||
};
|
||||
|
||||
@@ -80,6 +80,8 @@ pub struct CgroupBuilder {
|
||||
name: String,
|
||||
/// Internal, unsupported field: use the associated builders instead.
|
||||
resources: Resources,
|
||||
/// List of controllers specifically enabled in the control group.
|
||||
specified_controllers: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl CgroupBuilder {
|
||||
@@ -90,6 +92,7 @@ impl CgroupBuilder {
|
||||
CgroupBuilder {
|
||||
name: name.to_owned(),
|
||||
resources: Resources::default(),
|
||||
specified_controllers: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,10 +137,22 @@ impl CgroupBuilder {
|
||||
}
|
||||
|
||||
/// Finalize the control group, consuming the builder and creating the control group.
|
||||
pub fn build(self, hier: Box<dyn Hierarchy>) -> Cgroup {
|
||||
let cg = Cgroup::new(hier, self.name);
|
||||
let _ret = cg.apply(&self.resources);
|
||||
cg
|
||||
pub fn build(self, hier: Box<dyn Hierarchy>) -> Result<Cgroup, Error> {
|
||||
if let Some(controllers) = self.specified_controllers {
|
||||
let cg = Cgroup::new_with_specified_controllers(hier, self.name, Some(controllers))?;
|
||||
cg.apply(&self.resources)?;
|
||||
Ok(cg)
|
||||
} else {
|
||||
let cg = Cgroup::new(hier, self.name)?;
|
||||
cg.apply(&self.resources)?;
|
||||
Ok(cg)
|
||||
}
|
||||
}
|
||||
|
||||
/// Specifically enable some controllers in the control group.
|
||||
pub fn set_specified_controllers(mut self, specified_controllers: Vec<String>) -> Self {
|
||||
self.specified_controllers = Some(specified_controllers);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,10 +255,10 @@ impl DeviceResourceBuilder {
|
||||
access: Vec<crate::devices::DevicePermissions>,
|
||||
) -> DeviceResourceBuilder {
|
||||
self.cgroup.resources.devices.devices.push(DeviceResource {
|
||||
allow,
|
||||
devtype,
|
||||
major,
|
||||
minor,
|
||||
devtype,
|
||||
allow,
|
||||
access,
|
||||
});
|
||||
self
|
||||
|
||||
65
src/cpu.rs
65
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,
|
||||
}
|
||||
@@ -116,7 +117,7 @@ impl CpuController {
|
||||
Self {
|
||||
base: root.clone(),
|
||||
path: root,
|
||||
v2: v2,
|
||||
v2,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,10 +131,10 @@ 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("".to_string()),
|
||||
.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,46 +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: quota,
|
||||
period: 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,
|
||||
@@ -111,35 +112,35 @@ impl CpuAcctController {
|
||||
CpuAcct {
|
||||
stat: self
|
||||
.open_path("cpuacct.stat", false)
|
||||
.and_then(|file| read_string_from(file))
|
||||
.unwrap_or("".to_string()),
|
||||
.and_then(read_string_from)
|
||||
.unwrap_or_default(),
|
||||
usage: self
|
||||
.open_path("cpuacct.usage", false)
|
||||
.and_then(|file| read_u64_from(file))
|
||||
.and_then(read_u64_from)
|
||||
.unwrap_or(0),
|
||||
usage_all: self
|
||||
.open_path("cpuacct.usage_all", false)
|
||||
.and_then(|file| read_string_from(file))
|
||||
.unwrap_or("".to_string()),
|
||||
.and_then(read_string_from)
|
||||
.unwrap_or_default(),
|
||||
usage_percpu: self
|
||||
.open_path("cpuacct.usage_percpu", false)
|
||||
.and_then(|file| read_string_from(file))
|
||||
.unwrap_or("".to_string()),
|
||||
.and_then(read_string_from)
|
||||
.unwrap_or_default(),
|
||||
usage_percpu_sys: self
|
||||
.open_path("cpuacct.usage_percpu_sys", false)
|
||||
.and_then(|file| read_string_from(file))
|
||||
.unwrap_or("".to_string()),
|
||||
.and_then(read_string_from)
|
||||
.unwrap_or_default(),
|
||||
usage_percpu_user: self
|
||||
.open_path("cpuacct.usage_percpu_user", false)
|
||||
.and_then(|file| read_string_from(file))
|
||||
.unwrap_or("".to_string()),
|
||||
.and_then(read_string_from)
|
||||
.unwrap_or_default(),
|
||||
usage_sys: self
|
||||
.open_path("cpuacct.usage_sys", false)
|
||||
.and_then(|file| read_u64_from(file))
|
||||
.and_then(read_u64_from)
|
||||
.unwrap_or(0),
|
||||
usage_user: self
|
||||
.open_path("cpuacct.usage_user", false)
|
||||
.and_then(|file| read_u64_from(file))
|
||||
.and_then(read_u64_from)
|
||||
.unwrap_or(0),
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
191
src/cpuset.rs
191
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,10 +144,15 @@ 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 != "" {
|
||||
if !current_value.is_empty() {
|
||||
return Ok((current_value, v));
|
||||
}
|
||||
v.push(current_path.clone());
|
||||
@@ -167,7 +173,7 @@ fn copy_from_parent(current: &str, file: &str) -> Result<()> {
|
||||
// find not empty cpus/memes from current directory.
|
||||
let (value, parents) = find_no_empty_parent(current, file)?;
|
||||
|
||||
if value == "" || parents.len() == 0 {
|
||||
if value.is_empty() || parents.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,17 +219,17 @@ impl<'a> From<&'a Subsystem> for &'a CpuSetController {
|
||||
fn parse_range(s: String) -> Result<Vec<(u64, u64)>> {
|
||||
let mut fin = Vec::new();
|
||||
|
||||
if s == "".to_string() {
|
||||
if s.is_empty() {
|
||||
return Ok(fin);
|
||||
}
|
||||
|
||||
// first split by commas
|
||||
let comma_split = s.split(",");
|
||||
let comma_split = s.split(',');
|
||||
|
||||
for sp in comma_split {
|
||||
if sp.contains("-") {
|
||||
if sp.contains('-') {
|
||||
// this is a true range
|
||||
let dash_split = sp.split("-").collect::<Vec<_>>();
|
||||
let dash_split = sp.split('-').collect::<Vec<_>>();
|
||||
if dash_split.len() != 2 {
|
||||
return Err(Error::new(ParseError));
|
||||
}
|
||||
@@ -247,7 +258,7 @@ impl CpuSetController {
|
||||
Self {
|
||||
base: root.clone(),
|
||||
path: root,
|
||||
v2: v2,
|
||||
v2,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,7 +268,7 @@ impl CpuSetController {
|
||||
CpuSet {
|
||||
cpu_exclusive: {
|
||||
self.open_path("cpuset.cpu_exclusive", false)
|
||||
.and_then(|file| read_u64_from(file))
|
||||
.and_then(read_u64_from)
|
||||
.map(|x| x == 1)
|
||||
.unwrap_or(false)
|
||||
},
|
||||
@@ -265,19 +276,19 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.cpus", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_range)
|
||||
.unwrap_or(Vec::new())
|
||||
.unwrap_or_default()
|
||||
},
|
||||
effective_cpus: {
|
||||
self.open_path("cpuset.effective_cpus", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_range)
|
||||
.unwrap_or(Vec::new())
|
||||
.unwrap_or_default()
|
||||
},
|
||||
effective_mems: {
|
||||
self.open_path("cpuset.effective_mems", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_range)
|
||||
.unwrap_or(Vec::new())
|
||||
.unwrap_or_default()
|
||||
},
|
||||
mem_exclusive: {
|
||||
self.open_path("cpuset.mem_exclusive", false)
|
||||
@@ -324,7 +335,7 @@ impl CpuSetController {
|
||||
self.open_path("cpuset.mems", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_range)
|
||||
.unwrap_or(Vec::new())
|
||||
.unwrap_or_default()
|
||||
},
|
||||
sched_load_balance: {
|
||||
self.open_path("cpuset.sched_load_balance", false)
|
||||
@@ -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',
|
||||
@@ -102,7 +114,7 @@ impl DevicePermissions {
|
||||
|
||||
/// Checks whether the string is a valid descriptor of DevicePermissions.
|
||||
pub fn is_valid(s: &str) -> bool {
|
||||
if s == "" {
|
||||
if s.is_empty() {
|
||||
return false;
|
||||
}
|
||||
for i in s.chars() {
|
||||
@@ -110,7 +122,7 @@ impl DevicePermissions {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
true
|
||||
}
|
||||
|
||||
/// Returns a Vec will all the permissions that a device can have.
|
||||
@@ -123,9 +135,10 @@ impl DevicePermissions {
|
||||
}
|
||||
|
||||
/// Convert a string into DevicePermissions.
|
||||
#[allow(clippy::should_implement_trait)]
|
||||
pub fn from_str(s: &str) -> Result<Vec<DevicePermissions>> {
|
||||
let mut v = Vec::new();
|
||||
if s == "" {
|
||||
if s.is_empty() {
|
||||
return Ok(v);
|
||||
}
|
||||
for e in s.chars() {
|
||||
@@ -206,7 +219,7 @@ impl DevicesController {
|
||||
devtype: DeviceType,
|
||||
major: i64,
|
||||
minor: i64,
|
||||
perm: &Vec<DevicePermissions>,
|
||||
perm: &[DevicePermissions],
|
||||
) -> Result<()> {
|
||||
let perms = perm
|
||||
.iter()
|
||||
@@ -224,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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -238,7 +252,7 @@ impl DevicesController {
|
||||
devtype: DeviceType,
|
||||
major: i64,
|
||||
minor: i64,
|
||||
perm: &Vec<DevicePermissions>,
|
||||
perm: &[DevicePermissions],
|
||||
) -> Result<()> {
|
||||
let perms = perm
|
||||
.iter()
|
||||
@@ -256,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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -274,13 +289,13 @@ impl DevicesController {
|
||||
error!("allowed_devices: acc: {:?}, ls: {:?}", acc, ls);
|
||||
Err(Error::new(ParseError))
|
||||
} else {
|
||||
let devtype = DeviceType::from_char(ls[0].chars().nth(0));
|
||||
let devtype = DeviceType::from_char(ls[0].chars().next());
|
||||
let mut major = ls[1].parse::<i64>();
|
||||
let mut minor = ls[2].parse::<i64>();
|
||||
if major.is_err() && ls[1] == "*".to_string() {
|
||||
if major.is_err() && ls[1] == "*" {
|
||||
major = Ok(-1);
|
||||
}
|
||||
if minor.is_err() && ls[2] == "*".to_string() {
|
||||
if minor.is_err() && ls[2] == "*" {
|
||||
minor = Ok(-1);
|
||||
}
|
||||
if devtype.is_none() || major.is_err() || minor.is_err() || !DevicePermissions::is_valid(&ls[3]) {
|
||||
@@ -295,14 +310,14 @@ impl DevicesController {
|
||||
devtype: devtype.unwrap(),
|
||||
major: major.unwrap(),
|
||||
minor: minor.unwrap(),
|
||||
access: access,
|
||||
access,
|
||||
});
|
||||
Ok(acc)
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
Err(e) => Err(Error::with_cause(ReadFailed, e)),
|
||||
Err(e) => Err(Error::with_cause(ReadFailed("devices.list".to_string()), e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
53
src/error.rs
53
src/error.rs
@@ -8,40 +8,67 @@ 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,
|
||||
|
||||
/// The specified controller is not in the list of supported controllers.
|
||||
#[error("specified controller is not in the list of supported controllers")]
|
||||
SpecifiedControllers,
|
||||
|
||||
/// Using method in wrong cgroup version.
|
||||
#[error("using method in wrong cgroup version")]
|
||||
CgroupVersion,
|
||||
|
||||
/// Using method in wrong cgroup mode.
|
||||
#[error("using method in wrong cgroup mode.")]
|
||||
CgroupMode,
|
||||
|
||||
/// Subsystems is empty.
|
||||
#[error("subsystems is empty")]
|
||||
SubsystemsEmpty,
|
||||
|
||||
/// An unknown error has occured.
|
||||
#[error("an unknown error")]
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -53,29 +80,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> {
|
||||
fn source(&self) -> Option<&(dyn StdError + 'static)> {
|
||||
#[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 == "" {
|
||||
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) };
|
||||
|
||||
@@ -70,11 +75,8 @@ fn register_memory_event(
|
||||
thread::spawn(move || {
|
||||
loop {
|
||||
let mut buf = [0; 8];
|
||||
match eventfd_file.read(&mut buf) {
|
||||
Err(_err) => {
|
||||
return;
|
||||
}
|
||||
Ok(_) => {}
|
||||
if eventfd_file.read(&mut buf).is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
// When a cgroup is destroyed, an event is sent to 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,
|
||||
@@ -87,50 +88,50 @@ impl FreezerController {
|
||||
Self {
|
||||
base: root.clone(),
|
||||
path: root,
|
||||
v2: v2,
|
||||
v2,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
//! 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::path::PathBuf;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::blkio::BlkIoController;
|
||||
use crate::cpu::CpuController;
|
||||
@@ -31,13 +32,82 @@ use crate::{Controllers, Hierarchy, Subsystem};
|
||||
|
||||
use crate::cgroup::Cgroup;
|
||||
|
||||
/// Process mounts information.
|
||||
///
|
||||
/// See `proc(5)` for format details.
|
||||
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
|
||||
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(_) => break,
|
||||
}
|
||||
}
|
||||
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)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct V1 {
|
||||
mountinfo: Vec<Mountinfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct V2 {
|
||||
root: String,
|
||||
}
|
||||
@@ -100,7 +170,13 @@ impl Hierarchy for V1 {
|
||||
}
|
||||
|
||||
fn root_control_group(&self) -> Cgroup {
|
||||
Cgroup::load(auto(), "".to_string())
|
||||
Cgroup::load(auto(), "")
|
||||
}
|
||||
|
||||
fn parent_control_group(&self, path: &str) -> Cgroup {
|
||||
let path = Path::new(path);
|
||||
let parent_path = path.parent().unwrap().to_string_lossy().to_string();
|
||||
Cgroup::load(auto(), parent_path)
|
||||
}
|
||||
|
||||
fn root(&self) -> PathBuf {
|
||||
@@ -132,7 +208,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 {
|
||||
@@ -171,7 +252,13 @@ impl Hierarchy for V2 {
|
||||
}
|
||||
|
||||
fn root_control_group(&self) -> Cgroup {
|
||||
Cgroup::load(auto(), "".to_string())
|
||||
Cgroup::load(auto(), "")
|
||||
}
|
||||
|
||||
fn parent_control_group(&self, path: &str) -> Cgroup {
|
||||
let path = Path::new(path);
|
||||
let parent_path = path.parent().unwrap().to_string_lossy().to_string();
|
||||
Cgroup::load(auto(), parent_path)
|
||||
}
|
||||
|
||||
fn root(&self) -> PathBuf {
|
||||
@@ -184,7 +271,7 @@ impl V1 {
|
||||
/// can be created.
|
||||
pub fn new() -> V1 {
|
||||
V1 {
|
||||
mountinfo: mountinfo_self().unwrap(),
|
||||
mountinfo: mountinfo_self(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,6 +285,12 @@ impl V1 {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for V1 {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl V2 {
|
||||
/// Finds where control groups are mounted to and returns a hierarchy in which control groups
|
||||
/// can be created.
|
||||
@@ -208,9 +301,18 @@ impl V2 {
|
||||
}
|
||||
}
|
||||
|
||||
pub const UNIFIED_MOUNTPOINT: &'static str = "/sys/fs/cgroup";
|
||||
impl Default for V2 {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
|
||||
pub const UNIFIED_MOUNTPOINT: &str = "/sys/fs/cgroup";
|
||||
|
||||
#[cfg(any(
|
||||
all(target_os = "linux", not(target_env = "musl")),
|
||||
target_os = "android"
|
||||
))]
|
||||
pub fn is_cgroup2_unified_mode() -> bool {
|
||||
use nix::sys::statfs;
|
||||
|
||||
@@ -224,7 +326,7 @@ pub fn is_cgroup2_unified_mode() -> bool {
|
||||
fs_stat.unwrap().filesystem_type() == statfs::CGROUP2_SUPER_MAGIC
|
||||
}
|
||||
|
||||
pub const INIT_CGROUP_PATHS: &'static str = "/proc/1/cgroup";
|
||||
pub const INIT_CGROUP_PATHS: &str = "/proc/1/cgroup";
|
||||
|
||||
#[cfg(all(target_os = "linux", target_env = "musl"))]
|
||||
pub fn is_cgroup2_unified_mode() -> bool {
|
||||
@@ -253,3 +355,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,12 +89,12 @@ 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,
|
||||
sizes: sizes,
|
||||
v2: v2,
|
||||
sizes,
|
||||
v2,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,7 +116,7 @@ impl HugeTlbController {
|
||||
self.open_path(&format!("hugetlb.{}.events", hugetlb_size), false)
|
||||
.and_then(flat_keyed_to_vec)
|
||||
.and_then(|x| {
|
||||
if x.len() == 0 {
|
||||
if x.is_empty() {
|
||||
return Err(Error::from_string(format!(
|
||||
"get empty from hugetlb.{}.events",
|
||||
hugetlb_size
|
||||
@@ -137,8 +138,11 @@ impl HugeTlbController {
|
||||
/// Get the limit (in bytes) of how much memory can be backed by hugepages of a certain size
|
||||
/// (`hugetlb_size`).
|
||||
pub fn limit_in_bytes(&self, hugetlb_size: &str) -> Result<u64> {
|
||||
self.open_path(&format!("hugetlb.{}.limit_in_bytes", hugetlb_size), false)
|
||||
.and_then(read_u64_from)
|
||||
let mut file_name = format!("hugetlb.{}.limit_in_bytes", hugetlb_size);
|
||||
if self.v2 {
|
||||
file_name = format!("hugetlb.{}.max", hugetlb_size);
|
||||
}
|
||||
self.open_path(&file_name, false).and_then(read_u64_from)
|
||||
}
|
||||
|
||||
/// Get the current usage of memory that is backed by hugepages of a certain size
|
||||
@@ -164,43 +168,46 @@ 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)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub const HUGEPAGESIZE_DIR: &'static str = "/sys/kernel/mm/hugepages";
|
||||
pub const HUGEPAGESIZE_DIR: &str = "/sys/kernel/mm/hugepages";
|
||||
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;
|
||||
@@ -264,8 +271,8 @@ fn parse_size(s: &str, m: &HashMap<String, u128>) -> Result<u128> {
|
||||
let caps = re.unwrap().captures(s).unwrap();
|
||||
|
||||
let num = caps.name("num");
|
||||
let size: u128 = if num.is_some() {
|
||||
let n = num.unwrap().as_str().trim().parse::<u128>();
|
||||
let size: u128 = if let Some(num) = num {
|
||||
let n = num.as_str().trim().parse::<u128>();
|
||||
if n.is_err() {
|
||||
return Err(Error::new(InvalidBytesSize));
|
||||
}
|
||||
@@ -275,10 +282,10 @@ fn parse_size(s: &str, m: &HashMap<String, u128>) -> Result<u128> {
|
||||
};
|
||||
|
||||
let q = caps.name("mul");
|
||||
let mul: u128 = if q.is_some() {
|
||||
let t = m.get(q.unwrap().as_str());
|
||||
if t.is_some() {
|
||||
*t.unwrap()
|
||||
let mul: u128 = if let Some(q) = q {
|
||||
let t = m.get(q.as_str());
|
||||
if let Some(t) = t {
|
||||
*t
|
||||
} else {
|
||||
return Err(Error::new(InvalidBytesSize));
|
||||
}
|
||||
@@ -289,7 +296,7 @@ fn parse_size(s: &str, m: &HashMap<String, u128>) -> Result<u128> {
|
||||
Ok(size * mul)
|
||||
}
|
||||
|
||||
fn custom_size(mut size: f64, base: f64, m: &Vec<String>) -> String {
|
||||
fn custom_size(mut size: f64, base: f64, m: &[String]) -> String {
|
||||
let mut i = 0;
|
||||
while size >= base && i < m.len() - 1 {
|
||||
size /= base;
|
||||
|
||||
428
src/lib.rs
428
src/lib.rs
@@ -4,9 +4,11 @@
|
||||
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||
//
|
||||
|
||||
#![allow(clippy::unnecessary_unwrap)]
|
||||
use log::*;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -123,23 +125,23 @@ pub enum Controllers {
|
||||
Systemd,
|
||||
}
|
||||
|
||||
impl Controllers {
|
||||
pub fn to_string(&self) -> String {
|
||||
impl fmt::Display for Controllers {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Controllers::Pids => return "pids".to_string(),
|
||||
Controllers::Mem => return "memory".to_string(),
|
||||
Controllers::CpuSet => return "cpuset".to_string(),
|
||||
Controllers::CpuAcct => return "cpuacct".to_string(),
|
||||
Controllers::Cpu => return "cpu".to_string(),
|
||||
Controllers::Devices => return "devices".to_string(),
|
||||
Controllers::Freezer => return "freezer".to_string(),
|
||||
Controllers::NetCls => return "net_cls".to_string(),
|
||||
Controllers::BlkIo => return "blkio".to_string(),
|
||||
Controllers::PerfEvent => return "perf_event".to_string(),
|
||||
Controllers::NetPrio => return "net_prio".to_string(),
|
||||
Controllers::HugeTlb => return "hugetlb".to_string(),
|
||||
Controllers::Rdma => return "rdma".to_string(),
|
||||
Controllers::Systemd => return "name=systemd".to_string(),
|
||||
Controllers::Pids => write!(f, "pids"),
|
||||
Controllers::Mem => write!(f, "memory"),
|
||||
Controllers::CpuSet => write!(f, "cpuset"),
|
||||
Controllers::CpuAcct => write!(f, "cpuacct"),
|
||||
Controllers::Cpu => write!(f, "cpu"),
|
||||
Controllers::Devices => write!(f, "devices"),
|
||||
Controllers::Freezer => write!(f, "freezer"),
|
||||
Controllers::NetCls => write!(f, "net_cls"),
|
||||
Controllers::BlkIo => write!(f, "blkio"),
|
||||
Controllers::PerfEvent => write!(f, "perf_event"),
|
||||
Controllers::NetPrio => write!(f, "net_prio"),
|
||||
Controllers::HugeTlb => write!(f, "hugetlb"),
|
||||
Controllers::Rdma => write!(f, "rdma"),
|
||||
Controllers::Systemd => write!(f, "name=systemd"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,13 +181,22 @@ mod sealed {
|
||||
|
||||
if w {
|
||||
match File::create(&path) {
|
||||
Err(e) => return Err(Error::with_cause(ErrorKind::WriteFailed, e)),
|
||||
Ok(file) => return Ok(file),
|
||||
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) => return Err(Error::with_cause(ErrorKind::ReadFailed, e)),
|
||||
Ok(file) => return Ok(file),
|
||||
Err(e) => Err(Error::with_cause(
|
||||
ErrorKind::ReadFailed(path.display().to_string()),
|
||||
e,
|
||||
)),
|
||||
Ok(file) => Ok(file),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -196,14 +207,14 @@ 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)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
fn path_exists(&self, p: &str) -> bool {
|
||||
if let Err(_) = self.verify_path() {
|
||||
if self.verify_path().is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -214,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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -224,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)),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -268,9 +280,18 @@ pub trait Controller {
|
||||
/// Attach a task to this controller.
|
||||
fn add_task_by_tgid(&self, pid: &CgroupPid) -> Result<()>;
|
||||
|
||||
/// set cgroup type.
|
||||
fn set_cgroup_type(&self, cgroup_type: &str) -> Result<()>;
|
||||
|
||||
/// get cgroup type.
|
||||
fn get_cgroup_type(&self) -> Result<String>;
|
||||
|
||||
/// Get the list of tasks that this controller has.
|
||||
fn tasks(&self) -> Vec<CgroupPid>;
|
||||
|
||||
/// Get the list of procs that this controller has.
|
||||
fn procs(&self) -> Vec<CgroupPid>;
|
||||
|
||||
fn v2(&self) -> bool;
|
||||
}
|
||||
|
||||
@@ -295,7 +316,7 @@ where
|
||||
/// Create this controller
|
||||
fn create(&self) {
|
||||
self.verify_path()
|
||||
.expect(format!("path should be valid: {:?}", self.path()).as_str());
|
||||
.unwrap_or_else(|_| panic!("path should be valid: {:?}", self.path()));
|
||||
|
||||
match ::std::fs::create_dir_all(self.get_path()) {
|
||||
Ok(_) => self.post_create(),
|
||||
@@ -305,18 +326,32 @@ where
|
||||
|
||||
/// Set notify_on_release
|
||||
fn set_notify_on_release(&self, enable: bool) -> Result<()> {
|
||||
if self.is_v2() {
|
||||
return Err(Error::new(ErrorKind::CgroupVersion));
|
||||
}
|
||||
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<()> {
|
||||
if self.is_v2() {
|
||||
return Err(Error::new(ErrorKind::CgroupVersion));
|
||||
}
|
||||
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?
|
||||
@@ -330,48 +365,131 @@ where
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
fs::remove_dir(self.get_path()).map_err(|e| Error::with_cause(ErrorKind::RemoveFailed, e))
|
||||
// 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.threads";
|
||||
}
|
||||
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))
|
||||
let file_name = "cgroup.procs";
|
||||
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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the list of procs that this controller has.
|
||||
fn procs(&self) -> Vec<CgroupPid> {
|
||||
let file_name = "cgroup.procs";
|
||||
self.open_path(file_name, false)
|
||||
.map(|file| {
|
||||
let bf = BufReader::new(file);
|
||||
let mut v = Vec::new();
|
||||
for line in bf.lines() {
|
||||
match line {
|
||||
Ok(line) => {
|
||||
let n = line.trim().parse().unwrap_or(0u64);
|
||||
v.push(n);
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
v.into_iter().map(CgroupPid::from).collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get the list of tasks that this controller has.
|
||||
fn tasks(&self) -> Vec<CgroupPid> {
|
||||
let mut file = "tasks";
|
||||
let mut file_name = "tasks";
|
||||
if self.is_v2() {
|
||||
file = "cgroup.procs";
|
||||
file_name = "cgroup.threads";
|
||||
}
|
||||
self.open_path(file, false)
|
||||
.and_then(|file| {
|
||||
self.open_path(file_name, false)
|
||||
.map(|file| {
|
||||
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,
|
||||
}
|
||||
}
|
||||
Ok(v.into_iter().map(CgroupPid::from).collect())
|
||||
v.into_iter().map(CgroupPid::from).collect()
|
||||
})
|
||||
.unwrap_or(vec![])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// set cgroup.type
|
||||
fn set_cgroup_type(&self, cgroup_type: &str) -> Result<()> {
|
||||
if !self.is_v2() {
|
||||
return Err(Error::new(ErrorKind::CgroupVersion));
|
||||
}
|
||||
let file_name = "cgroup.type";
|
||||
self.open_path(file_name, true).and_then(|mut file| {
|
||||
file.write_all(cgroup_type.as_bytes()).map_err(|e| {
|
||||
Error::with_cause(
|
||||
ErrorKind::WriteFailed(file_name.to_string(), cgroup_type.to_string()),
|
||||
e,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// get cgroup.type
|
||||
fn get_cgroup_type(&self) -> Result<String> {
|
||||
if !self.is_v2() {
|
||||
return Err(Error::new(ErrorKind::CgroupVersion));
|
||||
}
|
||||
let file_name = "cgroup.type";
|
||||
self.open_path(file_name, false).and_then(|mut file: File| {
|
||||
let mut string = String::new();
|
||||
match file.read_to_string(&mut string) {
|
||||
Ok(_) => Ok(string.trim().to_owned()),
|
||||
Err(e) => Err(Error::with_cause(
|
||||
ErrorKind::ReadFailed(file_name.to_string()),
|
||||
e,
|
||||
)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn v2(&self) -> bool {
|
||||
@@ -379,6 +497,31 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
// remove_dir aims to remove cgroup path. It does so recursively,
|
||||
// by removing any subdirectories (sub-cgroups) first.
|
||||
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(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)?;
|
||||
}
|
||||
}
|
||||
fs::remove_dir(dir).map_err(|e| Error::with_cause(RemoveFailed, e))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub trait ControllIdentifier {
|
||||
fn controller_type() -> Controllers;
|
||||
@@ -396,11 +539,15 @@ pub trait Hierarchy: std::fmt::Debug + Send + Sync {
|
||||
/// Return a handle to the root control group in the hierarchy.
|
||||
fn root_control_group(&self) -> Cgroup;
|
||||
|
||||
/// Return a handle to the parent control group in the hierarchy.
|
||||
fn parent_control_group(&self, path: &str) -> Cgroup;
|
||||
|
||||
fn v2(&self) -> bool;
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
@@ -424,13 +571,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.
|
||||
///
|
||||
@@ -442,6 +591,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
|
||||
@@ -454,9 +604,9 @@ pub struct CpuResources {
|
||||
/// Weight of how much of the total CPU time should this control group get. Note that this is
|
||||
/// hierarchical, so this is weighted against the siblings of this control group.
|
||||
pub shares: Option<u64>,
|
||||
/// In one `period`, how much can the tasks run in nanoseconds.
|
||||
/// In one `period`, how much can the tasks run in microseconds.
|
||||
pub quota: Option<i64>,
|
||||
/// Period of time in nanoseconds.
|
||||
/// Period of time in microseconds.
|
||||
pub period: Option<u64>,
|
||||
/// This is currently a no-operation.
|
||||
pub realtime_runtime: Option<i64>,
|
||||
@@ -466,14 +616,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,
|
||||
@@ -489,6 +640,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>,
|
||||
@@ -496,6 +648,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,
|
||||
@@ -506,6 +659,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.
|
||||
///
|
||||
@@ -517,6 +671,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,
|
||||
@@ -527,6 +682,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>,
|
||||
@@ -534,6 +690,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,
|
||||
@@ -547,6 +704,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,
|
||||
@@ -558,6 +716,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>,
|
||||
@@ -573,10 +732,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,
|
||||
@@ -617,75 +786,61 @@ impl<'a> From<&'a std::process::Child> for CgroupPid {
|
||||
impl Subsystem {
|
||||
fn enter(self, path: &Path) -> Self {
|
||||
match self {
|
||||
Subsystem::Pid(cont) => Subsystem::Pid({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::Pid(mut cont) => Subsystem::Pid({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::Mem(cont) => Subsystem::Mem({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::Mem(mut cont) => Subsystem::Mem({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::CpuSet(cont) => Subsystem::CpuSet({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::CpuSet(mut cont) => Subsystem::CpuSet({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::CpuAcct(cont) => Subsystem::CpuAcct({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::CpuAcct(mut cont) => Subsystem::CpuAcct({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::Cpu(cont) => Subsystem::Cpu({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::Cpu(mut cont) => Subsystem::Cpu({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::Devices(cont) => Subsystem::Devices({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::Devices(mut cont) => Subsystem::Devices({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::Freezer(cont) => Subsystem::Freezer({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::Freezer(mut cont) => Subsystem::Freezer({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::NetCls(cont) => Subsystem::NetCls({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::NetCls(mut cont) => Subsystem::NetCls({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::BlkIo(cont) => Subsystem::BlkIo({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::BlkIo(mut cont) => Subsystem::BlkIo({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::PerfEvent(cont) => Subsystem::PerfEvent({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::PerfEvent(mut cont) => Subsystem::PerfEvent({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::NetPrio(cont) => Subsystem::NetPrio({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::NetPrio(mut cont) => Subsystem::NetPrio({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::HugeTlb(cont) => Subsystem::HugeTlb({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::HugeTlb(mut cont) => Subsystem::HugeTlb({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::Rdma(cont) => Subsystem::Rdma({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::Rdma(mut cont) => Subsystem::Rdma({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
Subsystem::Systemd(cont) => Subsystem::Systemd({
|
||||
let mut c = cont.clone();
|
||||
c.get_path_mut().push(path);
|
||||
c
|
||||
Subsystem::Systemd(mut cont) => Subsystem::Systemd({
|
||||
cont.get_path_mut().push(path);
|
||||
cont
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -716,6 +871,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,
|
||||
@@ -730,22 +886,25 @@ 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,
|
||||
MaxValue::Value(num) => *num,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn to_string(&self) -> String {
|
||||
impl fmt::Display for MaxValue {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
MaxValue::Max => "max".to_string(),
|
||||
MaxValue::Value(num) => num.to_string(),
|
||||
MaxValue::Max => write!(f, "max"),
|
||||
MaxValue::Value(num) => write!(f, "{}", num),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_max_value(s: &String) -> Result<MaxValue> {
|
||||
pub fn parse_max_value(s: &str) -> Result<MaxValue> {
|
||||
if s.trim() == "max" {
|
||||
return Ok(MaxValue::Max);
|
||||
}
|
||||
@@ -761,17 +920,14 @@ pub fn parse_max_value(s: &String) -> 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() {
|
||||
let parts: Vec<&str> = line.split(' ').collect();
|
||||
if parts.len() == 2 {
|
||||
match parts[1].parse::<i64>() {
|
||||
Ok(i) => {
|
||||
v.push((parts[0].to_string(), i));
|
||||
}
|
||||
Err(_) => {}
|
||||
if let Ok(i) = parts[1].parse::<i64>() {
|
||||
v.push((parts[0].to_string(), i));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -784,17 +940,14 @@ 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() {
|
||||
let parts: Vec<&str> = line.split(' ').collect();
|
||||
if parts.len() == 2 {
|
||||
match parts[1].parse::<i64>() {
|
||||
Ok(i) => {
|
||||
h.insert(parts[0].to_string(), i);
|
||||
}
|
||||
Err(_) => {}
|
||||
if let Ok(i) = parts[1].parse::<i64>() {
|
||||
h.insert(parts[0].to_string(), i);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -807,23 +960,20 @@ 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() {
|
||||
let parts: Vec<&str> = line.split(' ').collect();
|
||||
if parts.len() == 0 {
|
||||
if parts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut th = HashMap::new();
|
||||
for item in parts[1..].into_iter() {
|
||||
for item in parts[1..].iter() {
|
||||
let fields: Vec<&str> = item.split('=').collect();
|
||||
if fields.len() == 2 {
|
||||
match fields[1].parse::<i64>() {
|
||||
Ok(i) => {
|
||||
th.insert(fields[0].to_string(), i);
|
||||
}
|
||||
Err(_) => {}
|
||||
if let Ok(i) = fields[1].parse::<i64>() {
|
||||
th.insert(fields[0].to_string(), i);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -844,7 +994,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,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,7 +1005,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,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
422
src/memory.rs
422
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,
|
||||
@@ -56,18 +59,38 @@ pub struct OomControl {
|
||||
pub oom_kill: u64,
|
||||
}
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
fn parse_oom_control(s: String) -> Result<OomControl> {
|
||||
let spl = s.split_whitespace().collect::<Vec<_>>();
|
||||
|
||||
let oom_kill_disable = if spl.len() > 1 {
|
||||
spl[1].parse::<u64>().unwrap() == 1
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
let under_oom = if spl.len() > 3 {
|
||||
spl[3].parse::<u64>().unwrap() == 1
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
let oom_kill = if spl.len() > 5 {
|
||||
spl[5].parse::<u64>().unwrap()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
Ok(OomControl {
|
||||
oom_kill_disable: spl[1].parse::<u64>().unwrap() == 1,
|
||||
under_oom: spl[3].parse::<u64>().unwrap() == 1,
|
||||
oom_kill: spl[5].parse::<u64>().unwrap(),
|
||||
oom_kill_disable,
|
||||
under_oom,
|
||||
oom_kill,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -104,18 +127,19 @@ pub struct NumaStat {
|
||||
pub hierarchical_unevictable_pages_per_node: Vec<u64>,
|
||||
}
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
fn parse_numa_stat(s: String) -> Result<NumaStat> {
|
||||
// Parse the number of nodes
|
||||
let _nodes = (s.split_whitespace().collect::<Vec<_>>().len() - 8) / 8;
|
||||
let _nodes = (s.split_whitespace().count() - 8) / 8;
|
||||
let mut ls = s.lines();
|
||||
let total_line = ls.next().unwrap();
|
||||
let file_line = ls.next().unwrap();
|
||||
let anon_line = ls.next().unwrap();
|
||||
let unevict_line = ls.next().unwrap();
|
||||
let hier_total_line = ls.next().unwrap();
|
||||
let hier_file_line = ls.next().unwrap();
|
||||
let hier_anon_line = ls.next().unwrap();
|
||||
let hier_unevict_line = ls.next().unwrap();
|
||||
let hier_total_line = ls.next().unwrap_or_default();
|
||||
let hier_file_line = ls.next().unwrap_or_default();
|
||||
let hier_anon_line = ls.next().unwrap_or_default();
|
||||
let hier_unevict_line = ls.next().unwrap_or_default();
|
||||
|
||||
Ok(NumaStat {
|
||||
total_pages: total_line
|
||||
@@ -124,10 +148,10 @@ fn parse_numa_stat(s: String) -> Result<NumaStat> {
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0),
|
||||
total_pages_per_node: {
|
||||
let spl = &total_line.split(" ").collect::<Vec<_>>()[1..];
|
||||
let spl = &total_line.split(' ').collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split("=").collect::<Vec<_>>()[1]
|
||||
x.split('=').collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
@@ -139,10 +163,10 @@ fn parse_numa_stat(s: String) -> Result<NumaStat> {
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0),
|
||||
file_pages_per_node: {
|
||||
let spl = &file_line.split(" ").collect::<Vec<_>>()[1..];
|
||||
let spl = &file_line.split(' ').collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split("=").collect::<Vec<_>>()[1]
|
||||
x.split('=').collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
@@ -154,10 +178,10 @@ fn parse_numa_stat(s: String) -> Result<NumaStat> {
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0),
|
||||
anon_pages_per_node: {
|
||||
let spl = &anon_line.split(" ").collect::<Vec<_>>()[1..];
|
||||
let spl = &anon_line.split(' ').collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split("=").collect::<Vec<_>>()[1]
|
||||
x.split('=').collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
@@ -169,79 +193,120 @@ fn parse_numa_stat(s: String) -> Result<NumaStat> {
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0),
|
||||
unevictable_pages_per_node: {
|
||||
let spl = &unevict_line.split(" ").collect::<Vec<_>>()[1..];
|
||||
let spl = &unevict_line.split(' ').collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split("=").collect::<Vec<_>>()[1]
|
||||
x.split('=').collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
},
|
||||
hierarchical_total_pages: hier_total_line
|
||||
.split(|x| x == ' ' || x == '=')
|
||||
.collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0),
|
||||
hierarchical_total_pages: {
|
||||
if !hier_total_line.is_empty() {
|
||||
hier_total_line
|
||||
.split(|x| x == ' ' || x == '=')
|
||||
.collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
},
|
||||
hierarchical_total_pages_per_node: {
|
||||
let spl = &hier_total_line.split(" ").collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split("=").collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
if !hier_total_line.is_empty() {
|
||||
let spl = &hier_total_line.split(' ').collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split('=').collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
hierarchical_file_pages: {
|
||||
if !hier_file_line.is_empty() {
|
||||
hier_file_line
|
||||
.split(|x| x == ' ' || x == '=')
|
||||
.collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
},
|
||||
hierarchical_file_pages: hier_file_line
|
||||
.split(|x| x == ' ' || x == '=')
|
||||
.collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0),
|
||||
hierarchical_file_pages_per_node: {
|
||||
let spl = &hier_file_line.split(" ").collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split("=").collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
if !hier_file_line.is_empty() {
|
||||
let spl = &hier_file_line.split(' ').collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split('=').collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
hierarchical_anon_pages: {
|
||||
if !hier_anon_line.is_empty() {
|
||||
hier_anon_line
|
||||
.split(|x| x == ' ' || x == '=')
|
||||
.collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
},
|
||||
hierarchical_anon_pages: hier_anon_line
|
||||
.split(|x| x == ' ' || x == '=')
|
||||
.collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0),
|
||||
hierarchical_anon_pages_per_node: {
|
||||
let spl = &hier_anon_line.split(" ").collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split("=").collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
if !hier_anon_line.is_empty() {
|
||||
let spl = &hier_anon_line.split(' ').collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split('=').collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
hierarchical_unevictable_pages: {
|
||||
if !hier_unevict_line.is_empty() {
|
||||
hier_unevict_line
|
||||
.split(|x| x == ' ' || x == '=')
|
||||
.collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
},
|
||||
hierarchical_unevictable_pages: hier_unevict_line
|
||||
.split(|x| x == ' ' || x == '=')
|
||||
.collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0),
|
||||
hierarchical_unevictable_pages_per_node: {
|
||||
let spl = &hier_unevict_line.split(" ").collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split("=").collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
if !hier_unevict_line.is_empty() {
|
||||
let spl = &hier_unevict_line.split(' ').collect::<Vec<_>>()[1..];
|
||||
spl.iter()
|
||||
.map(|x| {
|
||||
x.split('=').collect::<Vec<_>>()[1]
|
||||
.parse::<u64>()
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct MemoryStat {
|
||||
pub cache: u64,
|
||||
pub rss: u64,
|
||||
@@ -282,6 +347,7 @@ pub struct MemoryStat {
|
||||
pub raw: HashMap<String, u64>,
|
||||
}
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
fn parse_memory_stat(s: String) -> Result<MemoryStat> {
|
||||
let mut raw = HashMap::new();
|
||||
|
||||
@@ -335,13 +401,14 @@ fn parse_memory_stat(s: String) -> Result<MemoryStat> {
|
||||
total_inactive_file: *raw.get("total_inactive_file").unwrap_or(&0),
|
||||
total_active_file: *raw.get("total_active_file").unwrap_or(&0),
|
||||
total_unevictable: *raw.get("total_unevictable").unwrap_or(&0),
|
||||
raw: raw,
|
||||
raw,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -356,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,
|
||||
@@ -400,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,
|
||||
@@ -418,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,
|
||||
@@ -474,7 +544,7 @@ impl MemController {
|
||||
Self {
|
||||
base: root.clone(),
|
||||
path: root,
|
||||
v2: v2,
|
||||
v2,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -489,11 +559,12 @@ impl MemController {
|
||||
for value in values {
|
||||
let v = value.0;
|
||||
let f = value.1;
|
||||
if v.is_some() {
|
||||
let v = v.unwrap().to_string();
|
||||
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)
|
||||
})
|
||||
})?;
|
||||
}
|
||||
}
|
||||
@@ -531,7 +602,7 @@ impl MemController {
|
||||
.open_path("memory.stat", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_memory_stat)
|
||||
.unwrap_or(MemoryStat::default()),
|
||||
.unwrap_or_default(),
|
||||
swappiness: self
|
||||
.open_path("memory.swap.current", false)
|
||||
.and_then(read_u64_from)
|
||||
@@ -575,12 +646,12 @@ impl MemController {
|
||||
.open_path("memory.numa_stat", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_numa_stat)
|
||||
.unwrap_or(NumaStat::default()),
|
||||
.unwrap_or_default(),
|
||||
oom_control: self
|
||||
.open_path("memory.oom_control", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_oom_control)
|
||||
.unwrap_or(OomControl::default()),
|
||||
.unwrap_or_default(),
|
||||
soft_limit_in_bytes: self
|
||||
.open_path("memory.soft_limit_in_bytes", false)
|
||||
.and_then(read_i64_from)
|
||||
@@ -589,7 +660,7 @@ impl MemController {
|
||||
.open_path("memory.stat", false)
|
||||
.and_then(read_string_from)
|
||||
.and_then(parse_memory_stat)
|
||||
.unwrap_or(MemoryStat::default()),
|
||||
.unwrap_or_default(),
|
||||
swappiness: self
|
||||
.open_path("memory.swappiness", false)
|
||||
.and_then(read_u64_from)
|
||||
@@ -623,7 +694,7 @@ impl MemController {
|
||||
slabinfo: self
|
||||
.open_path("memory.kmem.slabinfo", false)
|
||||
.and_then(read_string_from)
|
||||
.unwrap_or("".to_string()),
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,7 +726,7 @@ impl MemController {
|
||||
fail_cnt: self
|
||||
.open_path("memory.swap.events", false)
|
||||
.and_then(flat_keyed_to_hashmap)
|
||||
.and_then(|x| Ok(*x.get("fail").unwrap_or(&0) as u64))
|
||||
.map(|x| *x.get("fail").unwrap_or(&0) as u64)
|
||||
.unwrap(),
|
||||
limit_in_bytes: self
|
||||
.open_path("memory.swap.max", false)
|
||||
@@ -699,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -713,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -727,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -736,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -745,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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -771,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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -797,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -807,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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -822,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -878,6 +994,7 @@ mod tests {
|
||||
use crate::memory::{
|
||||
parse_memory_stat, parse_numa_stat, parse_oom_control, MemoryStat, NumaStat, OomControl,
|
||||
};
|
||||
|
||||
static GOOD_VALUE: &str = "\
|
||||
total=51189 N0=51189 N1=123
|
||||
file=50175 N0=50175 N1=123
|
||||
@@ -889,7 +1006,24 @@ hierarchical_anon=770402 N0=770402 N1=123
|
||||
hierarchical_unevictable=20 N0=20 N1=123
|
||||
";
|
||||
|
||||
static GOOD_OOMCONTROL_VAL: &str = "\
|
||||
static GOOD_VALUE_NON_HIERARCHICAL: &str = "\
|
||||
total=51189 N0=51189 N1=123
|
||||
file=50175 N0=50175 N1=123
|
||||
anon=1014 N0=1014 N1=123
|
||||
unevictable=0 N0=0 N1=123
|
||||
";
|
||||
|
||||
static GOOD_OOMCONTROL_VAL_1: &str = "\
|
||||
oom_kill_disable 0
|
||||
oom_kill 1337
|
||||
";
|
||||
|
||||
static GOOD_OOMCONTROL_VAL_2: &str = "\
|
||||
oom_kill_disable 0
|
||||
under_oom 1
|
||||
";
|
||||
|
||||
static GOOD_OOMCONTROL_VAL_3: &str = "\
|
||||
oom_kill_disable 0
|
||||
under_oom 1
|
||||
oom_kill 1337
|
||||
@@ -959,11 +1093,61 @@ total_unevictable 81920
|
||||
hierarchical_unevictable_pages_per_node: vec![20, 123],
|
||||
}
|
||||
);
|
||||
let ok = parse_numa_stat(GOOD_VALUE_NON_HIERARCHICAL.to_string()).unwrap();
|
||||
assert_eq!(
|
||||
ok,
|
||||
NumaStat {
|
||||
total_pages: 51189,
|
||||
total_pages_per_node: vec![51189, 123],
|
||||
file_pages: 50175,
|
||||
file_pages_per_node: vec![50175, 123],
|
||||
anon_pages: 1014,
|
||||
anon_pages_per_node: vec![1014, 123],
|
||||
unevictable_pages: 0,
|
||||
unevictable_pages_per_node: vec![0, 123],
|
||||
|
||||
hierarchical_total_pages: 0,
|
||||
hierarchical_total_pages_per_node: vec![],
|
||||
hierarchical_file_pages: 0,
|
||||
hierarchical_file_pages_per_node: vec![],
|
||||
hierarchical_anon_pages: 0,
|
||||
hierarchical_anon_pages_per_node: vec![],
|
||||
hierarchical_unevictable_pages: 0,
|
||||
hierarchical_unevictable_pages_per_node: vec![],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_oom_control() {
|
||||
let ok = parse_oom_control(GOOD_OOMCONTROL_VAL.to_string()).unwrap();
|
||||
let ok = parse_oom_control("".to_string()).unwrap();
|
||||
assert_eq!(
|
||||
ok,
|
||||
OomControl {
|
||||
oom_kill_disable: false,
|
||||
under_oom: false,
|
||||
oom_kill: 0,
|
||||
}
|
||||
);
|
||||
let ok = parse_oom_control(GOOD_OOMCONTROL_VAL_1.to_string()).unwrap();
|
||||
assert_eq!(
|
||||
ok,
|
||||
OomControl {
|
||||
oom_kill_disable: false,
|
||||
under_oom: false,
|
||||
oom_kill: 0,
|
||||
}
|
||||
);
|
||||
let ok = parse_oom_control(GOOD_OOMCONTROL_VAL_2.to_string()).unwrap();
|
||||
assert_eq!(
|
||||
ok,
|
||||
OomControl {
|
||||
oom_kill_disable: false,
|
||||
under_oom: true,
|
||||
oom_kill: 0,
|
||||
}
|
||||
);
|
||||
let ok = parse_oom_control(GOOD_OOMCONTROL_VAL_3.to_string()).unwrap();
|
||||
assert_eq!(
|
||||
ok,
|
||||
OomControl {
|
||||
@@ -1017,7 +1201,7 @@ total_unevictable 81920
|
||||
total_inactive_file: 1272135680,
|
||||
total_active_file: 2338816000,
|
||||
total_unevictable: 81920,
|
||||
raw: raw,
|
||||
raw,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ impl ControllerInternal for NetClsController {
|
||||
|
||||
update_and_test!(self, set_class, res.class_id, get_class);
|
||||
|
||||
return Ok(());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,14 +88,15 @@ 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)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the network class id of the outgoing packets of the control group's tasks.
|
||||
pub fn get_class(&self) -> Result<u64> {
|
||||
self.open_path("net_cls.classid", false)
|
||||
.and_then(|file| read_u64_from(file))
|
||||
.and_then(read_u64_from)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,7 @@ impl NetPrioController {
|
||||
}
|
||||
|
||||
/// A map of priorities for each network interface.
|
||||
#[allow(clippy::iter_nth_zero, clippy::unnecessary_unwrap)]
|
||||
pub fn ifpriomap(&self) -> Result<HashMap<String, u64>> {
|
||||
self.open_path("net_prio.ifpriomap", false)
|
||||
.and_then(|file| {
|
||||
@@ -105,6 +106,7 @@ impl NetPrioController {
|
||||
let mut acc = acc.unwrap();
|
||||
let l = line.unwrap();
|
||||
let mut sp = l.split_whitespace();
|
||||
|
||||
let ifname = sp.nth(0);
|
||||
let ifprio = sp.nth(1);
|
||||
if ifname.is_none() || ifprio.is_none() {
|
||||
@@ -130,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,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
11
src/pid.rs
11
src/pid.rs
@@ -96,7 +96,7 @@ impl PidController {
|
||||
Self {
|
||||
base: root.clone(),
|
||||
path: root,
|
||||
v2: v2,
|
||||
v2,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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: v2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,8 @@ pub fn test_cpu_res_build() {
|
||||
.cpu()
|
||||
.shares(85)
|
||||
.done()
|
||||
.build(h);
|
||||
.build(h)
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
let cpu: &CpuController = cg.controller_of().unwrap();
|
||||
@@ -42,12 +43,14 @@ pub fn test_memory_res_build() {
|
||||
.swappiness(70)
|
||||
.memory_hard_limit(1024 * 1024 * 1024)
|
||||
.done()
|
||||
.build(h);
|
||||
.build(h)
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
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);
|
||||
@@ -63,7 +66,8 @@ pub fn test_pid_res_build() {
|
||||
.pid()
|
||||
.maximum_number_of_processes(MaxValue::Value(123))
|
||||
.done()
|
||||
.build(h);
|
||||
.build(h)
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
let c: &PidController = cg.controller_of().unwrap();
|
||||
@@ -82,7 +86,8 @@ pub fn test_devices_res_build() {
|
||||
.devices()
|
||||
.device(1, 6, DeviceType::Char, true, vec![DevicePermissions::Read])
|
||||
.done()
|
||||
.build(h);
|
||||
.build(h)
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
let c: &DevicesController = cg.controller_of().unwrap();
|
||||
@@ -112,7 +117,8 @@ pub fn test_network_res_build() {
|
||||
.network()
|
||||
.class_id(1337)
|
||||
.done()
|
||||
.build(h);
|
||||
.build(h)
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
let c: &NetClsController = cg.controller_of().unwrap();
|
||||
@@ -133,15 +139,13 @@ pub fn test_hugepages_res_build() {
|
||||
.hugepages()
|
||||
.limit("2MB".to_string(), 4 * 2 * 1024 * 1024)
|
||||
.done()
|
||||
.build(h);
|
||||
.build(h)
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
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();
|
||||
}
|
||||
@@ -154,7 +158,8 @@ pub fn test_blkio_res_build() {
|
||||
.blkio()
|
||||
.weight(100)
|
||||
.done()
|
||||
.build(h);
|
||||
.build(h)
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
let c: &BlkIoController = cg.controller_of().unwrap();
|
||||
|
||||
186
tests/cgroup.rs
186
tests/cgroup.rs
@@ -5,29 +5,60 @@
|
||||
//
|
||||
|
||||
//! Simple unit tests about the control groups system.
|
||||
use cgroups_rs::cgroup::{
|
||||
CGROUP_MODE_DOMAIN, CGROUP_MODE_DOMAIN_INVALID, CGROUP_MODE_DOMAIN_THREADED,
|
||||
CGROUP_MODE_THREADED,
|
||||
};
|
||||
use cgroups_rs::memory::MemController;
|
||||
use cgroups_rs::Controller;
|
||||
use cgroups_rs::{Cgroup, CgroupPid, Subsystem};
|
||||
use std::process::Command;
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn test_tasks_iterator() {
|
||||
fn test_procs_iterator_cgroup() {
|
||||
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"));
|
||||
let cg = Cgroup::new(h, String::from("test_procs_iterator_cgroup")).unwrap();
|
||||
{
|
||||
// Add a task to the control group.
|
||||
cg.add_task_by_tgid(CgroupPid::from(pid)).unwrap();
|
||||
|
||||
let mut procs = cg.procs().into_iter();
|
||||
// Verify that the task is indeed in the xcontrol group
|
||||
assert_eq!(procs.next(), Some(CgroupPid::from(pid)));
|
||||
assert_eq!(procs.next(), None);
|
||||
|
||||
// Now, try removing it.
|
||||
cg.remove_task_by_tgid(CgroupPid::from(pid)).unwrap();
|
||||
procs = cg.procs().into_iter();
|
||||
|
||||
// Verify that it was indeed removed.
|
||||
assert_eq!(procs.next(), None);
|
||||
}
|
||||
cg.delete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tasks_iterator_cgroup_v1() {
|
||||
if cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
|
||||
return;
|
||||
}
|
||||
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_cgroup_v1")).unwrap();
|
||||
{
|
||||
// Add a task to the control group.
|
||||
cg.add_task(CgroupPid::from(pid)).unwrap();
|
||||
|
||||
use std::{thread, time};
|
||||
thread::sleep(time::Duration::from_millis(100));
|
||||
|
||||
let mut tasks = cg.tasks().into_iter();
|
||||
// Verify that the task is indeed in the control group
|
||||
// Verify that the task is indeed in the xcontrol group
|
||||
assert_eq!(tasks.next(), Some(CgroupPid::from(pid)));
|
||||
assert_eq!(tasks.next(), None);
|
||||
|
||||
// Now, try removing it.
|
||||
cg.remove_task(CgroupPid::from(pid));
|
||||
cg.remove_task(CgroupPid::from(pid)).unwrap();
|
||||
tasks = cg.tasks().into_iter();
|
||||
|
||||
// Verify that it was indeed removed.
|
||||
@@ -36,6 +67,143 @@ fn test_tasks_iterator() {
|
||||
cg.delete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tasks_iterator_cgroup_threaded_mode() {
|
||||
if !cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
|
||||
return;
|
||||
}
|
||||
let pid = libc::pid_t::from(nix::unistd::getpid()) as u64;
|
||||
let cg = Cgroup::new(
|
||||
cgroups_rs::hierarchies::auto(),
|
||||
String::from("test_tasks_iterator_cgroup_threaded_mode"),
|
||||
)
|
||||
.unwrap();
|
||||
let cg_threaded_sub1 = Cgroup::new_with_specified_controllers(
|
||||
cgroups_rs::hierarchies::auto(),
|
||||
String::from("test_tasks_iterator_cgroup_threaded_mode/threaded_sub1"),
|
||||
Some(vec![String::from("cpuset"), String::from("cpu")]),
|
||||
)
|
||||
.unwrap();
|
||||
let cg_threaded_sub2 = Cgroup::new_with_specified_controllers(
|
||||
cgroups_rs::hierarchies::auto(),
|
||||
String::from("test_tasks_iterator_cgroup_threaded_mode/threaded_sub2"),
|
||||
Some(vec![String::from("cpuset"), String::from("cpu")]),
|
||||
)
|
||||
.unwrap();
|
||||
{
|
||||
// Verify that cgroup type of the control group is domain mode.
|
||||
assert_eq!(cg.get_cgroup_type().unwrap(), CGROUP_MODE_DOMAIN);
|
||||
|
||||
// Set cgroup type of the sub-control group is thread mode.
|
||||
cg_threaded_sub1
|
||||
.set_cgroup_type(CGROUP_MODE_THREADED)
|
||||
.unwrap();
|
||||
// Verify that cgroup type of the sub-control group is thread mode.
|
||||
assert_eq!(
|
||||
cg_threaded_sub1.get_cgroup_type().unwrap(),
|
||||
CGROUP_MODE_THREADED
|
||||
);
|
||||
// Verify that the cgroup type of the sub-control group that does
|
||||
// not set the cgroup type is domain invalid mode.
|
||||
assert_eq!(
|
||||
cg_threaded_sub2.get_cgroup_type().unwrap(),
|
||||
CGROUP_MODE_DOMAIN_INVALID
|
||||
);
|
||||
// Verify whether the cgroup type of the parent control group of
|
||||
// the control group whose cgroup type is set to thread mode is
|
||||
// domain thread mode.
|
||||
assert_eq!(cg.get_cgroup_type().unwrap(), CGROUP_MODE_DOMAIN_THREADED);
|
||||
|
||||
// Set cgroup type of the sub-control group is thread mode.
|
||||
cg_threaded_sub2
|
||||
.set_cgroup_type(CGROUP_MODE_THREADED)
|
||||
.unwrap();
|
||||
// Verify that cgroup type of the sub-control group is thread mode.
|
||||
assert_eq!(
|
||||
cg_threaded_sub2.get_cgroup_type().unwrap(),
|
||||
CGROUP_MODE_THREADED
|
||||
);
|
||||
|
||||
// Add a proc to the control group.
|
||||
cg.add_task_by_tgid(CgroupPid::from(pid)).unwrap();
|
||||
|
||||
let mut procs = cg.procs().into_iter();
|
||||
// Verify that the task is indeed in the x control group
|
||||
assert_eq!(procs.next(), Some(CgroupPid::from(pid)));
|
||||
assert_eq!(procs.next(), None);
|
||||
|
||||
// Add a task to the sub control group.
|
||||
cg_threaded_sub1.add_task(CgroupPid::from(pid)).unwrap();
|
||||
|
||||
let mut tasks = cg_threaded_sub1.tasks().into_iter();
|
||||
// Verify that the task is indeed in the xcontrol group
|
||||
assert_eq!(tasks.next(), Some(CgroupPid::from(pid)));
|
||||
assert_eq!(tasks.next(), None);
|
||||
|
||||
// Now, try move it to parent.
|
||||
cg_threaded_sub1
|
||||
.move_task_to_parent(CgroupPid::from(pid))
|
||||
.unwrap();
|
||||
tasks = cg_threaded_sub1.tasks().into_iter();
|
||||
|
||||
// Verify that it was indeed removed.
|
||||
assert_eq!(tasks.next(), None);
|
||||
|
||||
// Now, try removing it.
|
||||
cg.remove_task_by_tgid(CgroupPid::from(pid)).unwrap();
|
||||
procs = cg.procs().into_iter();
|
||||
|
||||
// Verify that it was indeed removed.
|
||||
assert_eq!(procs.next(), None);
|
||||
}
|
||||
cg_threaded_sub1.delete().unwrap();
|
||||
cg_threaded_sub2.delete().unwrap();
|
||||
cg.delete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_kill_cgroup() {
|
||||
if !cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
|
||||
return;
|
||||
}
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_kill_cgroup")).unwrap();
|
||||
{
|
||||
// Spawn a proc, don't want to getpid(2) here.
|
||||
let mut child = Command::new("sleep").arg("infinity").spawn().unwrap();
|
||||
cg.add_task_by_tgid(CgroupPid::from(child.id() as u64))
|
||||
.unwrap();
|
||||
|
||||
let cg_procs = cg.procs();
|
||||
assert_eq!(cg_procs.len(), 1_usize);
|
||||
|
||||
// Now kill and wait on the proc.
|
||||
cg.kill().unwrap();
|
||||
|
||||
let mut tries = 0;
|
||||
let status: Option<std::process::ExitStatus> = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
break Some(status);
|
||||
}
|
||||
Ok(None) => {
|
||||
if tries > 3 {
|
||||
break None;
|
||||
}
|
||||
sleep(Duration::from_millis(100));
|
||||
tries += 1;
|
||||
}
|
||||
Err(e) => {
|
||||
child.kill().unwrap();
|
||||
panic!("error attempting to wait: {}", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
assert!(!status.is_none());
|
||||
}
|
||||
cg.delete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cgroup_with_relative_paths() {
|
||||
if cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
|
||||
@@ -48,7 +216,7 @@ fn test_cgroup_with_relative_paths() {
|
||||
let cg = Cgroup::load(h, String::from(cgroup_name));
|
||||
{
|
||||
let subsystems = cg.subsystems();
|
||||
subsystems.into_iter().for_each(|sub| match sub {
|
||||
subsystems.iter().for_each(|sub| match sub {
|
||||
Subsystem::Pid(c) => {
|
||||
let cgroup_path = c.path().to_str().unwrap();
|
||||
let relative_path = "/pids/";
|
||||
@@ -83,7 +251,7 @@ fn test_cgroup_v2() {
|
||||
return;
|
||||
}
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_v2"));
|
||||
let cg = Cgroup::new(h, String::from("test_v2")).unwrap();
|
||||
|
||||
let mem_controller: &MemController = cg.controller_of().unwrap();
|
||||
let (mem, swp, rev) = (4 * 1024 * 1000, 2 * 1024 * 1000, 1024 * 1000);
|
||||
|
||||
@@ -10,7 +10,7 @@ use cgroups_rs::Cgroup;
|
||||
#[test]
|
||||
fn test_cfs_quota_and_periods() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_cfs_quota_and_periods"));
|
||||
let cg = Cgroup::new(h, String::from("test_cfs_quota_and_periods")).unwrap();
|
||||
|
||||
let cpu_controller: &CpuController = cg.controller_of().unwrap();
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::fs;
|
||||
#[test]
|
||||
fn test_cpuset_memory_pressure_root_cg() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_cpuset_memory_pressure_root_cg"));
|
||||
let cg = Cgroup::new(h, String::from("test_cpuset_memory_pressure_root_cg")).unwrap();
|
||||
{
|
||||
let cpuset: &CpuSetController = cg.controller_of().unwrap();
|
||||
|
||||
@@ -27,7 +27,7 @@ fn test_cpuset_memory_pressure_root_cg() {
|
||||
#[test]
|
||||
fn test_cpuset_set_cpus() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_cpuset_set_cpus"));
|
||||
let cg = Cgroup::new(h, String::from("test_cpuset_set_cpus")).unwrap();
|
||||
{
|
||||
let cpuset: &CpuSetController = cg.controller_of().unwrap();
|
||||
|
||||
@@ -36,24 +36,23 @@ 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.len() > 0);
|
||||
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());
|
||||
assert_eq!((0, 0), set.cpus[0]);
|
||||
|
||||
// all cpus in system
|
||||
let cpus =
|
||||
fs::read_to_string("/sys/fs/cgroup/cpuset.cpus.effective").unwrap_or("".to_string());
|
||||
let cpus = fs::read_to_string("/sys/fs/cgroup/cpuset.cpus.effective").unwrap_or_default();
|
||||
let cpus = cpus.trim();
|
||||
if cpus != "" {
|
||||
let r = cpuset.set_cpus(&cpus);
|
||||
assert_eq!(true, r.is_ok());
|
||||
if !cpus.is_empty() {
|
||||
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);
|
||||
@@ -65,7 +64,7 @@ fn test_cpuset_set_cpus() {
|
||||
#[test]
|
||||
fn test_cpuset_set_cpus_add_task() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_cpuset_set_cpus_add_task/sub-dir"));
|
||||
let cg = Cgroup::new(h, String::from("test_cpuset_set_cpus_add_task/sub-dir")).unwrap();
|
||||
|
||||
let cpuset: &CpuSetController = cg.controller_of().unwrap();
|
||||
let set = cpuset.cpuset();
|
||||
@@ -73,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.len() > 0);
|
||||
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 _ = cg.add_task_by_tgid(CgroupPid::from(pid_i));
|
||||
let tasks = cg.tasks();
|
||||
assert_eq!(true, tasks.len() > 0);
|
||||
assert!(!tasks.is_empty());
|
||||
println!("tasks after added: {:?}", tasks);
|
||||
|
||||
// remove task
|
||||
let _ = cg.remove_task(CgroupPid::from(pid_i));
|
||||
cg.remove_task_by_tgid(CgroupPid::from(pid_i)).unwrap();
|
||||
let tasks = cg.tasks();
|
||||
println!("tasks after deleted: {:?}", tasks);
|
||||
assert_eq!(0, tasks.len());
|
||||
|
||||
@@ -17,7 +17,7 @@ fn test_devices_parsing() {
|
||||
}
|
||||
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_devices_parsing"));
|
||||
let cg = Cgroup::new(h, String::from("test_devices_parsing")).unwrap();
|
||||
{
|
||||
let devices: &DevicesController = cg.controller_of().unwrap();
|
||||
|
||||
@@ -27,7 +27,7 @@ fn test_devices_parsing() {
|
||||
DeviceType::All,
|
||||
-1,
|
||||
-1,
|
||||
&vec![
|
||||
&[
|
||||
DevicePermissions::Read,
|
||||
DevicePermissions::Write,
|
||||
DevicePermissions::MkNod,
|
||||
@@ -42,7 +42,7 @@ fn test_devices_parsing() {
|
||||
|
||||
// Now add mknod access to /dev/null device
|
||||
devices
|
||||
.allow_device(DeviceType::Char, 1, 3, &vec![DevicePermissions::MkNod])
|
||||
.allow_device(DeviceType::Char, 1, 3, &[DevicePermissions::MkNod])
|
||||
.unwrap();
|
||||
let allowed_devices = devices.allowed_devices();
|
||||
assert!(allowed_devices.is_ok());
|
||||
|
||||
@@ -17,7 +17,7 @@ fn test_hugetlb_sizes() {
|
||||
}
|
||||
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_hugetlb_sizes"));
|
||||
let cg = Cgroup::new(h, String::from("test_hugetlb_sizes")).unwrap();
|
||||
{
|
||||
let hugetlb_controller: &HugeTlbController = cg.controller_of().unwrap();
|
||||
let _ = hugetlb_controller.get_sizes();
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
@@ -11,28 +11,43 @@ use cgroups_rs::{Cgroup, MaxValue};
|
||||
#[test]
|
||||
fn test_disable_oom_killer() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_disable_oom_killer"));
|
||||
let cg = Cgroup::new(h, String::from("test_disable_oom_killer")).unwrap();
|
||||
{
|
||||
let mem_controller: &MemController = cg.controller_of().unwrap();
|
||||
|
||||
// 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")).unwrap();
|
||||
{
|
||||
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();
|
||||
@@ -40,7 +55,7 @@ fn set_mem_v2() {
|
||||
return;
|
||||
}
|
||||
|
||||
let cg = Cgroup::new(h, String::from("set_mem_v2"));
|
||||
let cg = Cgroup::new(h, String::from("set_mem_v2")).unwrap();
|
||||
{
|
||||
let mem_controller: &MemController = cg.controller_of().unwrap();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -17,7 +17,7 @@ use libc::pid_t;
|
||||
#[test]
|
||||
fn create_and_delete_cgroup() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("create_and_delete_cgroup"));
|
||||
let cg = Cgroup::new(h, String::from("create_and_delete_cgroup")).unwrap();
|
||||
{
|
||||
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
||||
pidcontroller.set_pid_max(MaxValue::Value(1337)).unwrap();
|
||||
@@ -31,7 +31,7 @@ fn create_and_delete_cgroup() {
|
||||
#[test]
|
||||
fn test_pids_current_is_zero() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_pids_current_is_zero"));
|
||||
let cg = Cgroup::new(h, String::from("test_pids_current_is_zero")).unwrap();
|
||||
{
|
||||
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
||||
let current = pidcontroller.get_pid_current();
|
||||
@@ -43,7 +43,7 @@ fn test_pids_current_is_zero() {
|
||||
#[test]
|
||||
fn test_pids_events_is_zero() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_pids_events_is_zero"));
|
||||
let cg = Cgroup::new(h, String::from("test_pids_events_is_zero")).unwrap();
|
||||
{
|
||||
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
||||
let events = pidcontroller.get_pid_events();
|
||||
@@ -56,16 +56,16 @@ fn test_pids_events_is_zero() {
|
||||
#[test]
|
||||
fn test_pid_events_is_not_zero() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("test_pid_events_is_not_zero"));
|
||||
let cg = Cgroup::new(h, String::from("test_pid_events_is_not_zero")).unwrap();
|
||||
{
|
||||
let pids: &PidController = cg.controller_of().unwrap();
|
||||
let before = pids.get_pid_events();
|
||||
let before = before.unwrap();
|
||||
|
||||
match fork() {
|
||||
match unsafe { fork() } {
|
||||
Ok(ForkResult::Parent { child, .. }) => {
|
||||
// move the process into the control group
|
||||
let _ = pids.add_task(&(pid_t::from(child) as u64).into());
|
||||
let _ = pids.add_task_by_tgid(&(pid_t::from(child) as u64).into());
|
||||
|
||||
println!("added task to cg: {:?}", child);
|
||||
|
||||
@@ -89,7 +89,7 @@ fn test_pid_events_is_not_zero() {
|
||||
Ok(ForkResult::Child) => loop {
|
||||
let pids_max = pids.get_pid_max();
|
||||
if pids_max.is_ok() && pids_max.unwrap() == MaxValue::Value(1) {
|
||||
if let Err(_) = fork() {
|
||||
if unsafe { fork() }.is_err() {
|
||||
unsafe { libc::exit(0) };
|
||||
} else {
|
||||
unsafe { libc::exit(1) };
|
||||
|
||||
@@ -11,7 +11,7 @@ use cgroups_rs::{Cgroup, MaxValue, PidResources, Resources};
|
||||
#[test]
|
||||
fn pid_resources() {
|
||||
let h = cgroups_rs::hierarchies::auto();
|
||||
let cg = Cgroup::new(h, String::from("pid_resources"));
|
||||
let cg = Cgroup::new(h, String::from("pid_resources")).unwrap();
|
||||
{
|
||||
let res = Resources {
|
||||
pid: PidResources {
|
||||
@@ -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