mirror of
https://github.com/kata-containers/cgroups-rs.git
synced 2026-08-05 02:13:23 +00:00
Compare commits
186 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0348f0a95e | ||
|
|
d387c6edc7 | ||
|
|
4d8f704a4b | ||
|
|
860b484a30 | ||
|
|
99da9eeb1f | ||
|
|
ed49cf77e2 | ||
|
|
8f65a0ef89 | ||
|
|
f863f31395 | ||
|
|
91e66f0197 | ||
|
|
3340211c6e | ||
|
|
bd31dc0e7d | ||
|
|
0c908cddf8 | ||
|
|
556dea62b9 | ||
|
|
1a8f9823eb | ||
|
|
dda639f5ab | ||
|
|
476219ab93 | ||
|
|
138c85c4b1 | ||
|
|
92122de48d | ||
|
|
1df6e7a26e | ||
|
|
1bdd52470f | ||
|
|
231d9d599e | ||
|
|
a3bd03c662 | ||
|
|
8932df3fa0 | ||
|
|
fa94a1174f | ||
|
|
b4df6016b3 | ||
|
|
0686400268 | ||
|
|
6986c49e70 | ||
|
|
e0bf36ae23 | ||
|
|
2c68f36488 | ||
|
|
0bc1b9821b | ||
|
|
da75ba25d6 | ||
|
|
01475ad515 | ||
|
|
417badd05f | ||
|
|
1720443d58 | ||
|
|
fb55383273 | ||
|
|
0233c1e046 | ||
|
|
bf5af7b195 | ||
|
|
2e3719dbd5 | ||
|
|
4231f35a44 | ||
|
|
88b7aafd05 | ||
|
|
63750887c2 | ||
|
|
09499e7614 | ||
|
|
bcb7c6cd54 | ||
|
|
2554aa65d0 | ||
|
|
34f935be89 | ||
|
|
5485d8dd46 | ||
|
|
ec4cda1dd9 | ||
|
|
4b5a190ecc | ||
|
|
45b626e0c0 | ||
|
|
0e2430fde1 | ||
|
|
5aa7e6c90e | ||
|
|
5bb27a2692 | ||
|
|
0b2a0405e2 | ||
|
|
c4850ef2ef | ||
|
|
aa207edca8 | ||
|
|
af7a75ce9e | ||
|
|
fb56c817ca | ||
|
|
fdabe52401 | ||
|
|
9ec1010a15 | ||
|
|
610071730d | ||
|
|
0a3e4a828f | ||
|
|
60820bfffb | ||
|
|
2209189244 | ||
|
|
8720aed656 | ||
|
|
16d73e1d59 | ||
|
|
b9ca0a51f1 | ||
|
|
87f05873f0 | ||
|
|
79868d6bfc | ||
|
|
d1d78fe943 | ||
|
|
81d286f31d | ||
|
|
5e538ae286 | ||
|
|
cd5645bb14 | ||
|
|
4a2042068e | ||
|
|
9ac2f5d5ab | ||
|
|
a58cd1d553 | ||
|
|
88a45d4922 | ||
|
|
0c58b5dd84 | ||
|
|
8448548cb3 | ||
|
|
d50245e116 | ||
|
|
bbdfa88596 | ||
|
|
853ed46993 | ||
|
|
15b65c5e5e | ||
|
|
87f8ac7f0d | ||
|
|
225388ff7c | ||
|
|
f0a695cc00 | ||
|
|
50d3c398a0 | ||
|
|
033fa4b857 | ||
|
|
ac4e6eda66 | ||
|
|
35ecd6fd77 | ||
|
|
eb6577e3e0 | ||
|
|
8f6a7e0a31 | ||
|
|
9baa065226 | ||
|
|
e160df0751 | ||
|
|
e1e05d3a1c | ||
|
|
a89f4a062e | ||
|
|
61a0957a65 | ||
|
|
059204589c | ||
|
|
c254fffbe0 | ||
|
|
438d774866 | ||
|
|
42ee1bafbd | ||
|
|
b6bb5ae947 | ||
|
|
d2882b1d85 | ||
|
|
abcb5ed031 | ||
|
|
1f188be405 | ||
|
|
fbd7164c29 | ||
|
|
f34225411e | ||
|
|
cd998f3f9b | ||
|
|
1ac76b69ba | ||
|
|
121f78d8e8 | ||
|
|
0f76570677 | ||
|
|
10650e2b16 | ||
|
|
567cdb43b3 | ||
|
|
0c18b0855e | ||
|
|
ca610bb57e | ||
|
|
af6fc63bed | ||
|
|
6f9e89572e | ||
|
|
42eb32765b | ||
|
|
efb98108fc | ||
|
|
c310b30c52 | ||
|
|
152af17f8f | ||
|
|
d18b3bac2f | ||
|
|
414fa281cc | ||
|
|
f0eac7859a | ||
|
|
db40fe8cd3 | ||
|
|
8717524f2c | ||
|
|
cd7e737149 | ||
|
|
3852d7c180 | ||
|
|
0aaf7dba0b | ||
|
|
42685bbfe9 | ||
|
|
f8d653e987 | ||
|
|
d20e6a5383 | ||
|
|
be617190c7 | ||
|
|
250ada183a | ||
|
|
ff6a0ea82a | ||
|
|
bcbf438823 | ||
|
|
c3912223d0 | ||
|
|
5d51e50bec | ||
|
|
a1bc5868d6 | ||
|
|
86b245076c | ||
|
|
cd2c748a74 | ||
|
|
c623dc3fba | ||
|
|
704db324ae | ||
|
|
9fe6cb58e4 | ||
|
|
c702852fd7 | ||
|
|
9d70467327 | ||
|
|
6b1b26b1fe | ||
|
|
9ce206f6bc | ||
|
|
ed1e8162d5 | ||
|
|
932a6e770f | ||
|
|
01a3c22829 | ||
|
|
b5e0706d6a | ||
|
|
8a2fa92c3a | ||
|
|
dd621eae4e | ||
|
|
751dbc7244 | ||
|
|
3413b7d847 | ||
|
|
3b9d4a8c2a | ||
|
|
e51d781baf | ||
|
|
b4cc91f977 | ||
|
|
f9ffbe2ba4 | ||
|
|
b3738c2c9b | ||
|
|
90ab756be8 | ||
|
|
e85754d943 | ||
|
|
c08e4d3e5d | ||
|
|
c63dad411b | ||
|
|
7826b798bd | ||
|
|
84ae587360 | ||
|
|
adc3323be4 | ||
|
|
ffd4cd70e2 | ||
|
|
ae56cb02b9 | ||
|
|
2149e1c0c4 | ||
|
|
5660656e3a | ||
|
|
af6ed48e39 | ||
|
|
4b67af3eef | ||
|
|
afe1519ed2 | ||
|
|
7fa4527c2a | ||
|
|
d9bc157388 | ||
|
|
9da8998cd4 | ||
|
|
07421b2aff | ||
|
|
196d3e4d45 | ||
|
|
0e350463a1 | ||
|
|
af12452fca | ||
|
|
dbbcb86884 | ||
|
|
1c213caea5 | ||
|
|
be5db6ba50 | ||
|
|
19e2847e15 | ||
|
|
ede7201b73 |
2
.cargo/config
Normal file
2
.cargo/config
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
[target.x86_64-unknown-linux-gnu]
|
||||||
|
runner = 'sudo -E'
|
||||||
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.
|
||||||
21
.github/workflows/PR-wip-checks.yaml
vendored
Normal file
21
.github/workflows/PR-wip-checks.yaml
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
name: Pull request WIP checks
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
- synchronize
|
||||||
|
- reopened
|
||||||
|
- edited
|
||||||
|
- labeled
|
||||||
|
- unlabeled
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
pr_wip_check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: WIP Check
|
||||||
|
steps:
|
||||||
|
- name: WIP Check
|
||||||
|
uses: tim-actions/wip-check@1c2a1ca6c110026b3e2297bb2ef39e1747b5a755
|
||||||
|
with:
|
||||||
|
labels: '["do-not-merge", "wip", "rfc"]'
|
||||||
|
keywords: '["WIP", "wip", "RFC", "rfc", "dnm", "DNM", "do-not-merge"]'
|
||||||
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
|
||||||
|
|
||||||
|
|
||||||
53
.github/workflows/commit-message-check.yaml
vendored
Normal file
53
.github/workflows/commit-message-check.yaml
vendored
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
name: Commit Message Check
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types:
|
||||||
|
- opened
|
||||||
|
- reopened
|
||||||
|
- synchronize
|
||||||
|
|
||||||
|
env:
|
||||||
|
error_msg: |+
|
||||||
|
See the document below for help on formatting commits for the project.
|
||||||
|
|
||||||
|
https://github.com/kata-containers/community/blob/master/CONTRIBUTING.md#patch-forma
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
commit-message-check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Commit Message Check
|
||||||
|
steps:
|
||||||
|
- name: Get PR Commits
|
||||||
|
id: 'get-pr-commits'
|
||||||
|
uses: tim-actions/get-pr-commits@v1.0.0
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: DCO Check
|
||||||
|
uses: tim-actions/dco@2fd0504dc0d27b33f542867c300c60840c6dcb20
|
||||||
|
with:
|
||||||
|
commits: ${{ steps.get-pr-commits.outputs.commits }}
|
||||||
|
|
||||||
|
- name: Commit Body Missing Check
|
||||||
|
if: ${{ success() || failure() }}
|
||||||
|
uses: tim-actions/commit-body-check@v1.0.2
|
||||||
|
with:
|
||||||
|
commits: ${{ steps.get-pr-commits.outputs.commits }}
|
||||||
|
|
||||||
|
- name: Check Subject Line Length
|
||||||
|
if: ${{ success() || failure() }}
|
||||||
|
uses: tim-actions/commit-message-checker-with-regex@v0.3.1
|
||||||
|
with:
|
||||||
|
commits: ${{ steps.get-pr-commits.outputs.commits }}
|
||||||
|
pattern: '^.{0,75}(\n.*)*$'
|
||||||
|
error: 'Subject too long (max 75)'
|
||||||
|
post_error: ${{ env.error_msg }}
|
||||||
|
|
||||||
|
- name: Check Body Line Length
|
||||||
|
if: ${{ success() || failure() }}
|
||||||
|
uses: tim-actions/commit-message-checker-with-regex@v0.3.1
|
||||||
|
with:
|
||||||
|
commits: ${{ steps.get-pr-commits.outputs.commits }}
|
||||||
|
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 }}
|
||||||
11
.travis.yml
11
.travis.yml
@@ -1,11 +0,0 @@
|
|||||||
language: rust
|
|
||||||
rust:
|
|
||||||
- stable
|
|
||||||
- beta
|
|
||||||
- nightly
|
|
||||||
matrix:
|
|
||||||
allow_failures:
|
|
||||||
- rust: nightly
|
|
||||||
fast_finish: true
|
|
||||||
script:
|
|
||||||
- cargo build --verbose --all
|
|
||||||
23
Cargo.toml
23
Cargo.toml
@@ -1,15 +1,26 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "cgroups"
|
name = "cgroups-rs"
|
||||||
description = "Native Rust crate for managing control groups on Linux"
|
description = "Native Rust crate for managing control groups on Linux"
|
||||||
repository = "https://github.com/levex/cgroups-rs"
|
repository = "https://github.com/kata-containers/cgroups-rs"
|
||||||
keywords = ["linux", "cgroup", "containers", "isolation"]
|
keywords = ["linux", "cgroup", "containers", "isolation"]
|
||||||
categories = ["os", "api-bindings", "os::unix-apis"]
|
categories = ["os", "api-bindings", "os::unix-apis"]
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
version = "0.0.2"
|
version = "0.2.11"
|
||||||
authors = ["Levente Kurusa <lkurusa@acm.org>"]
|
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]
|
[dependencies]
|
||||||
|
log = "0.4"
|
||||||
|
regex = "1.1"
|
||||||
|
nix = { version = "0.25.0", default-features = false, features = ["event", "fs", "process"] }
|
||||||
|
libc = "0.2"
|
||||||
|
serde = { version = "1.0", features = ["derive"], optional = true }
|
||||||
|
thiserror = "1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
nix = "0.11.0"
|
libc = "0.2.76"
|
||||||
libc = "0.2.43"
|
|
||||||
|
[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
|
||||||
|
|
||||||
56
README.md
56
README.md
@@ -1,25 +1,47 @@
|
|||||||
# cgroups-rs 
|
# cgroups-rs 
|
||||||
Native Rust library for managing control groups under Linux
|
Native Rust library for managing control groups under Linux
|
||||||
|
|
||||||
# Example
|
Both v1 and v2 of cgroups are supported.
|
||||||
|
|
||||||
## Create a control group, and limit the pid resource
|
# Examples
|
||||||
|
|
||||||
|
## Create a control group using the builder pattern
|
||||||
|
|
||||||
``` rust
|
``` rust
|
||||||
// Acquire a handle for the V1 cgroup hierarchy.
|
|
||||||
let hier = ::hierarchies::V1::new();
|
|
||||||
// Create a control group named "example" in the hierarchy.
|
use cgroups_rs::*;
|
||||||
let cg = Cgroup::new(&hier, String::from("example"), 0);
|
use cgroups_rs::cgroup_builder::*;
|
||||||
{
|
|
||||||
// Get a handle to the pids controller of the control group.
|
// Acquire a handle for the cgroup hierarchy.
|
||||||
let pids: &PidController = cg.controller_of().expect("No pids controller in V1 hierarchy!");
|
let hier = cgroups_rs::hierarchies::auto();
|
||||||
// Set the maximum amount of processes in the cgroup.
|
|
||||||
pids.set_pid_max(PidMax::Value(10));
|
// Use the builder pattern (see the documentation to create the control group)
|
||||||
// Check that this has had the desired effect by reading the value back from the kernel.
|
//
|
||||||
assert_eq!(pids.get_pid_max(), Some(PidMax::Value(10)));
|
// This creates a control group named "example" in the V1 hierarchy.
|
||||||
}
|
let cg: Cgroup = CgroupBuilder::new("example")
|
||||||
// Once done, delete the control group (and its associated controllers).
|
.cpu()
|
||||||
|
.shares(85)
|
||||||
|
.done()
|
||||||
|
.build(hier);
|
||||||
|
|
||||||
|
// Now `cg` is a control group that gets 85% of the CPU time in relative to
|
||||||
|
// other control groups.
|
||||||
|
|
||||||
|
// Get a handle to the CPU controller.
|
||||||
|
let cpus: &cgroups_rs::cpu::CpuController = cg.controller_of().unwrap();
|
||||||
|
cpus.add_task(&CgroupPid::from(1234u64));
|
||||||
|
|
||||||
|
// [...]
|
||||||
|
|
||||||
|
// Finally, clean up and delete the control group.
|
||||||
cg.delete();
|
cg.delete();
|
||||||
|
|
||||||
|
// Note that `Cgroup` does not implement `Drop` and therefore when the
|
||||||
|
// structure is dropped, the Cgroup will stay around. This is because, later
|
||||||
|
// you can then re-create the `Cgroup` using `load()`. We aren't too set on
|
||||||
|
// this behavior, so it might change in the feature. Rest assured, it will be a
|
||||||
|
// major version change.
|
||||||
```
|
```
|
||||||
|
|
||||||
# Disclaimer
|
# Disclaimer
|
||||||
@@ -27,7 +49,7 @@ cg.delete();
|
|||||||
This crate is licensed under:
|
This crate is licensed under:
|
||||||
|
|
||||||
- MIT License (see LICENSE-MIT); or
|
- MIT License (see LICENSE-MIT); or
|
||||||
- Apache 2.0 LIcense (see LICENSE-Apache-2.0),
|
- Apache 2.0 License (see LICENSE-Apache-2.0),
|
||||||
|
|
||||||
at your option.
|
at your option.
|
||||||
|
|
||||||
|
|||||||
1006
src/blkio.rs
1006
src/blkio.rs
File diff suppressed because it is too large
Load Diff
354
src/cgroup.rs
354
src/cgroup.rs
@@ -1,9 +1,20 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module handles cgroup operations. Start here!
|
//! This module handles cgroup operations. Start here!
|
||||||
|
|
||||||
use {CgroupError, CgroupPid, Resources, ControllIdentifier, Controller, Hierarchy, Subsystem};
|
use crate::error::ErrorKind::*;
|
||||||
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::{CgroupPid, ControllIdentifier, Controller, Hierarchy, Resources, Subsystem};
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::convert::From;
|
use std::convert::From;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
/// A control group is the central structure to this crate.
|
/// A control group is the central structure to this crate.
|
||||||
///
|
///
|
||||||
@@ -17,58 +28,142 @@ use std::convert::From;
|
|||||||
/// > specialized behaviour.
|
/// > specialized behaviour.
|
||||||
///
|
///
|
||||||
/// This crate is an attempt at providing a Rust-native way of managing these cgroups.
|
/// This crate is an attempt at providing a Rust-native way of managing these cgroups.
|
||||||
pub struct Cgroup<'b> {
|
#[derive(Debug)]
|
||||||
|
pub struct Cgroup {
|
||||||
/// The list of subsystems that control this cgroup
|
/// The list of subsystems that control this cgroup
|
||||||
subsystems: Vec<Subsystem>,
|
subsystems: Vec<Subsystem>,
|
||||||
|
|
||||||
/// The hierarchy.
|
/// The hierarchy.
|
||||||
hier: &'b Hierarchy,
|
hier: Box<dyn Hierarchy>,
|
||||||
|
path: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'b> Cgroup<'b> {
|
impl Clone for Cgroup {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
/// Create this control group.
|
Cgroup {
|
||||||
fn create(self: &Self) {
|
subsystems: self.subsystems.clone(),
|
||||||
for subsystem in &self.subsystems {
|
path: self.path.clone(),
|
||||||
subsystem.to_controller().create();
|
hier: crate::hierarchies::auto(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Cgroup {
|
||||||
|
fn default() -> Self {
|
||||||
|
Cgroup {
|
||||||
|
subsystems: Vec::new(),
|
||||||
|
hier: crate::hierarchies::auto(),
|
||||||
|
path: "".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Cgroup {
|
||||||
|
/// Create this control group.
|
||||||
|
fn create(&self) {
|
||||||
|
if self.hier.v2() {
|
||||||
|
let _ret = create_v2_cgroup(self.hier.root(), &self.path);
|
||||||
|
} else {
|
||||||
|
for subsystem in &self.subsystems {
|
||||||
|
subsystem.to_controller().create();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn v2(&self) -> bool {
|
||||||
|
self.hier.v2()
|
||||||
|
}
|
||||||
|
|
||||||
/// Create a new control group in the hierarchy `hier`, with name `path`.
|
/// 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.
|
/// 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 {
|
||||||
/// Note that if the handle goes out of scope and is dropped, the control group is _not_
|
|
||||||
/// destroyed.
|
|
||||||
pub fn new(hier: &Hierarchy, path: String) -> Cgroup {
|
|
||||||
let cg = Cgroup::load(hier, path);
|
let cg = Cgroup::load(hier, path);
|
||||||
cg.create();
|
cg.create();
|
||||||
cg
|
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
|
||||||
|
pub fn new_with_relative_paths<P: AsRef<Path>>(
|
||||||
|
hier: Box<dyn Hierarchy>,
|
||||||
|
path: P,
|
||||||
|
relative_paths: HashMap<String, String>,
|
||||||
|
) -> Cgroup {
|
||||||
|
let cg = Cgroup::load_with_relative_paths(hier, path, relative_paths);
|
||||||
|
cg.create();
|
||||||
|
cg
|
||||||
|
}
|
||||||
|
|
||||||
/// Create a handle for a control group in the hierarchy `hier`, with name `path`.
|
/// Create a handle for a control group in the hierarchy `hier`, with name `path`.
|
||||||
///
|
///
|
||||||
/// Returns a handle to the control group (that possibly does not exist until `create()` has
|
/// Returns a handle to the control group (that possibly does not exist until `create()` has
|
||||||
/// been called on the cgroup.
|
/// been called on the cgroup.
|
||||||
///
|
pub fn load<P: AsRef<Path>>(hier: Box<dyn Hierarchy>, path: P) -> Cgroup {
|
||||||
/// Note that if the handle goes out of scope and is dropped, the control group is _not_
|
let path = path.as_ref();
|
||||||
/// destroyed.
|
|
||||||
pub fn load(hier: &Hierarchy, path: String) -> Cgroup {
|
|
||||||
let mut subsystems = hier.subsystems();
|
let mut subsystems = hier.subsystems();
|
||||||
if path != "" {
|
if path.as_os_str() != "" {
|
||||||
subsystems = subsystems.into_iter().map(|x| x.enter(&path)).collect::<Vec<_>>();
|
subsystems = subsystems
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| x.enter(path))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
}
|
}
|
||||||
|
|
||||||
let cg = Cgroup {
|
Cgroup {
|
||||||
subsystems: subsystems,
|
path: path.to_str().unwrap().to_string(),
|
||||||
hier: hier,
|
subsystems,
|
||||||
};
|
hier,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
cg
|
/// Create a handle for a control group in the hierarchy `hier`, with name `path` and `relative_paths`
|
||||||
|
///
|
||||||
|
/// Returns a handle to the control group (that possibly does not exist until `create()` has
|
||||||
|
/// been called on the cgroup.
|
||||||
|
///
|
||||||
|
/// Note that this method is only meaningful for cgroup v1, call it is equivalent to call `load` in the v2 mode
|
||||||
|
pub fn load_with_relative_paths<P: AsRef<Path>>(
|
||||||
|
hier: Box<dyn Hierarchy>,
|
||||||
|
path: P,
|
||||||
|
relative_paths: HashMap<String, String>,
|
||||||
|
) -> Cgroup {
|
||||||
|
// relative_paths only valid for cgroup v1
|
||||||
|
if hier.v2() {
|
||||||
|
return Self::load(hier, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
let path = path.as_ref();
|
||||||
|
let mut subsystems = hier.subsystems();
|
||||||
|
if path.as_os_str() != "" {
|
||||||
|
subsystems = subsystems
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| {
|
||||||
|
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 mut p = PathBuf::from(valid_path);
|
||||||
|
p.push(path);
|
||||||
|
x.enter(p.as_ref())
|
||||||
|
} else {
|
||||||
|
x.enter(path)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
}
|
||||||
|
|
||||||
|
Cgroup {
|
||||||
|
subsystems,
|
||||||
|
hier,
|
||||||
|
path: path.to_str().unwrap().to_string(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The list of subsystems that this control group supports.
|
/// The list of subsystems that this control group supports.
|
||||||
pub fn subsystems(self: &Self) -> &Vec<Subsystem> {
|
pub fn subsystems(&self) -> &Vec<Subsystem> {
|
||||||
&self.subsystems
|
&self.subsystems
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,31 +173,39 @@ impl<'b> Cgroup<'b> {
|
|||||||
/// system call will fail if there are any descendants. Thus, one should check whether it was
|
/// system call will fail if there are any descendants. Thus, one should check whether it was
|
||||||
/// actually removed, and remove the descendants first if not. In the future, this behavior
|
/// actually removed, and remove the descendants first if not. In the future, this behavior
|
||||||
/// will change.
|
/// will change.
|
||||||
pub fn delete(self: Self) {
|
pub fn delete(&self) -> Result<()> {
|
||||||
self.subsystems.into_iter().for_each(|sub| {
|
if self.v2() {
|
||||||
match sub {
|
if !self.path.is_empty() {
|
||||||
Subsystem::Pid(pidc) => pidc.delete(),
|
let mut p = self.hier.root();
|
||||||
Subsystem::Mem(c) => c.delete(),
|
p.push(self.path.clone());
|
||||||
Subsystem::CpuSet(c) => c.delete(),
|
return fs::remove_dir(p).map_err(|e| Error::with_cause(RemoveFailed, e));
|
||||||
Subsystem::CpuAcct(c) => c.delete(),
|
|
||||||
Subsystem::Cpu(c) => c.delete(),
|
|
||||||
Subsystem::Devices(c) => c.delete(),
|
|
||||||
Subsystem::Freezer(c) => c.delete(),
|
|
||||||
Subsystem::NetCls(c) => c.delete(),
|
|
||||||
Subsystem::BlkIo(c) => c.delete(),
|
|
||||||
Subsystem::PerfEvent(c) => c.delete(),
|
|
||||||
Subsystem::NetPrio(c) => c.delete(),
|
|
||||||
Subsystem::HugeTlb(c) => c.delete(),
|
|
||||||
Subsystem::Rdma(c) => c.delete(),
|
|
||||||
}
|
}
|
||||||
});
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
self.subsystems.iter().try_for_each(|sub| match sub {
|
||||||
|
Subsystem::Pid(pidc) => pidc.delete(),
|
||||||
|
Subsystem::Mem(c) => c.delete(),
|
||||||
|
Subsystem::CpuSet(c) => c.delete(),
|
||||||
|
Subsystem::CpuAcct(c) => c.delete(),
|
||||||
|
Subsystem::Cpu(c) => c.delete(),
|
||||||
|
Subsystem::Devices(c) => c.delete(),
|
||||||
|
Subsystem::Freezer(c) => c.delete(),
|
||||||
|
Subsystem::NetCls(c) => c.delete(),
|
||||||
|
Subsystem::BlkIo(c) => c.delete(),
|
||||||
|
Subsystem::PerfEvent(c) => c.delete(),
|
||||||
|
Subsystem::NetPrio(c) => c.delete(),
|
||||||
|
Subsystem::HugeTlb(c) => c.delete(),
|
||||||
|
Subsystem::Rdma(c) => c.delete(),
|
||||||
|
Subsystem::Systemd(c) => c.delete(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply a set of resource limits to the control group.
|
/// Apply a set of resource limits to the control group.
|
||||||
pub fn apply(self: &Self, res: &Resources) {
|
pub fn apply(&self, res: &Resources) -> Result<()> {
|
||||||
for subsystem in &self.subsystems {
|
self.subsystems
|
||||||
subsystem.to_controller().apply(res);
|
.iter()
|
||||||
}
|
.try_fold((), |_, e| e.to_controller().apply(res))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Retrieve a container based on type inference.
|
/// Retrieve a container based on type inference.
|
||||||
@@ -115,16 +218,15 @@ impl<'b> Cgroup<'b> {
|
|||||||
/// let cpu: &CpuController = control_group.controller_of()
|
/// let cpu: &CpuController = control_group.controller_of()
|
||||||
/// .expect("No cpu controller attached!");
|
/// .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>,
|
where
|
||||||
T: Controller + ControllIdentifier,
|
&'a T: From<&'a Subsystem>,
|
||||||
|
T: Controller + ControllIdentifier,
|
||||||
{
|
{
|
||||||
for i in &self.subsystems {
|
for i in &self.subsystems {
|
||||||
if i.to_controller().control_type() == T::controller_type() {
|
if i.to_controller().control_type() == T::controller_type() {
|
||||||
/*
|
// N.B.:
|
||||||
* N.B.:
|
// https://play.rust-lang.org/?gist=978b2846bacebdaa00be62374f4f4334&version=stable&mode=debug&edition=2015
|
||||||
* https://play.rust-lang.org/?gist=978b2846bacebdaa00be62374f4f4334&version=stable&mode=debug&edition=2015
|
|
||||||
*/
|
|
||||||
return Some(i.into());
|
return Some(i.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -135,25 +237,151 @@ impl<'b> Cgroup<'b> {
|
|||||||
///
|
///
|
||||||
/// Note that this means that the task will be moved back to the root control group in the
|
/// 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.
|
/// hierarchy and any rules applied to that control group will _still_ apply to the task.
|
||||||
pub fn remove_task(self: &Self, pid: CgroupPid) {
|
pub fn remove_task(&self, pid: CgroupPid) {
|
||||||
let _ = self.hier.root_control_group().add_task(pid);
|
let _ = self.hier.root_control_group().add_task(pid);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attach a task to the control group.
|
/// Attach a task to the control group.
|
||||||
pub fn add_task(self: &Self, pid: CgroupPid) -> Result<(), CgroupError> {
|
pub fn add_task(&self, pid: CgroupPid) -> Result<()> {
|
||||||
self.subsystems().iter().try_for_each(|sub| sub.to_controller().add_task(&pid))
|
if self.v2() {
|
||||||
|
let subsystems = self.subsystems();
|
||||||
|
if !subsystems.is_empty() {
|
||||||
|
let c = subsystems[0].to_controller();
|
||||||
|
c.add_task(&pid)
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.subsystems()
|
||||||
|
.iter()
|
||||||
|
.try_for_each(|sub| sub.to_controller().add_task(&pid))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set notify_on_release to the control group.
|
||||||
|
pub fn set_notify_on_release(&self, enable: bool) -> Result<()> {
|
||||||
|
self.subsystems()
|
||||||
|
.iter()
|
||||||
|
.try_for_each(|sub| sub.to_controller().set_notify_on_release(enable))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set release_agent
|
||||||
|
pub fn set_release_agent(&self, path: &str) -> Result<()> {
|
||||||
|
self.hier
|
||||||
|
.root_control_group()
|
||||||
|
.subsystems()
|
||||||
|
.iter()
|
||||||
|
.try_for_each(|sub| sub.to_controller().set_release_agent(path))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns an Iterator that can be used to iterate over the tasks that are currently in the
|
/// Returns an Iterator that can be used to iterate over the tasks that are currently in the
|
||||||
/// control group.
|
/// control group.
|
||||||
pub fn tasks(self: &Self) -> Vec<CgroupPid> {
|
pub fn tasks(&self) -> Vec<CgroupPid> {
|
||||||
/* Collect the tasks from all subsystems */
|
// Collect the tasks from all subsystems
|
||||||
let mut v = self.subsystems().iter()
|
let mut v = if self.v2() {
|
||||||
.map(|x| x.to_controller().tasks())
|
let subsystems = self.subsystems();
|
||||||
.fold(vec![], |mut acc, mut x| { acc.append(&mut x); acc });
|
if !subsystems.is_empty() {
|
||||||
|
let c = subsystems[0].to_controller();
|
||||||
|
c.tasks()
|
||||||
|
} else {
|
||||||
|
vec![]
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.subsystems()
|
||||||
|
.iter()
|
||||||
|
.map(|x| x.to_controller().tasks())
|
||||||
|
.fold(vec![], |mut acc, mut x| {
|
||||||
|
acc.append(&mut x);
|
||||||
|
acc
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
v.sort();
|
v.sort();
|
||||||
v.dedup();
|
v.dedup();
|
||||||
v
|
v
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const UNIFIED_MOUNTPOINT: &str = "/sys/fs/cgroup";
|
||||||
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_controllers() -> Vec<String> {
|
||||||
|
let p = format!("{}/{}", UNIFIED_MOUNTPOINT, "cgroup.controllers");
|
||||||
|
let ret = fs::read_to_string(p.as_str());
|
||||||
|
ret.unwrap_or_default()
|
||||||
|
.split(' ')
|
||||||
|
.map(|x| x.to_string())
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_v2_cgroup(root: PathBuf, path: &str) -> Result<()> {
|
||||||
|
// controler list ["memory", "cpu"]
|
||||||
|
let controllers = 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 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() {
|
||||||
|
if let Err(e) = std::fs::create_dir(fp.clone()) {
|
||||||
|
return Err(Error::with_cause(ErrorKind::FsError, e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if i < last_index {
|
||||||
|
// enable controllers for substree
|
||||||
|
enable_controllers(&controllers, &fp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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(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 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let keys: Vec<&str> = fl[1].split(',').collect();
|
||||||
|
for key in &keys {
|
||||||
|
m.insert(key.to_string(), fl[2].to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(m)
|
||||||
}
|
}
|
||||||
|
|||||||
390
src/cgroup_builder.rs
Normal file
390
src/cgroup_builder.rs
Normal file
@@ -0,0 +1,390 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
//! This module allows the user to create a control group using the Builder pattern.
|
||||||
|
//! # Example
|
||||||
|
//!
|
||||||
|
//! The following example demonstrates how the control group builder looks like. The user
|
||||||
|
//! specifies the name of the control group (here: "hello") and the hierarchy it belongs to (here:
|
||||||
|
//! a V1 hierarchy). Next, the user selects a subsystem by calling functions like `memory()`,
|
||||||
|
//! `cpu()` and `devices()`. The user can then add restrictions and details via subsystem-specific
|
||||||
|
//! calls. To finalize a subsystem, the user may call `done()`. Finally, if the control group build
|
||||||
|
//! is done and all requirements/restrictions have been specified, the control group can be created
|
||||||
|
//! by a call to `build()`.
|
||||||
|
//!
|
||||||
|
//! ```rust,no_run
|
||||||
|
//! # use cgroups_rs::*;
|
||||||
|
//! # use cgroups_rs::devices::*;
|
||||||
|
//! # use cgroups_rs::cgroup_builder::*;
|
||||||
|
//! let h = cgroups_rs::hierarchies::auto();
|
||||||
|
//! let cgroup: Cgroup = CgroupBuilder::new("hello")
|
||||||
|
//! .memory()
|
||||||
|
//! .kernel_memory_limit(1024 * 1024)
|
||||||
|
//! .memory_hard_limit(1024 * 1024)
|
||||||
|
//! .done()
|
||||||
|
//! .cpu()
|
||||||
|
//! .shares(100)
|
||||||
|
//! .done()
|
||||||
|
//! .devices()
|
||||||
|
//! .device(1000, 10, DeviceType::Block, true,
|
||||||
|
//! vec![DevicePermissions::Read,
|
||||||
|
//! DevicePermissions::Write,
|
||||||
|
//! DevicePermissions::MkNod])
|
||||||
|
//! .device(6, 1, DeviceType::Char, false, vec![])
|
||||||
|
//! .done()
|
||||||
|
//! .network()
|
||||||
|
//! .class_id(1337)
|
||||||
|
//! .priority("eth0".to_string(), 100)
|
||||||
|
//! .priority("wl0".to_string(), 200)
|
||||||
|
//! .done()
|
||||||
|
//! .hugepages()
|
||||||
|
//! .limit("2M".to_string(), 0)
|
||||||
|
//! .limit("4M".to_string(), 4 * 1024 * 1024 * 100)
|
||||||
|
//! .limit("2G".to_string(), 2 * 1024 * 1024 * 1024)
|
||||||
|
//! .done()
|
||||||
|
//! .blkio()
|
||||||
|
//! .weight(123)
|
||||||
|
//! .leaf_weight(99)
|
||||||
|
//! .weight_device(6, 1, Some(100), Some(55))
|
||||||
|
//! .weight_device(6, 1, Some(100), Some(55))
|
||||||
|
//! .throttle_iops()
|
||||||
|
//! .read(6, 1, 10)
|
||||||
|
//! .write(11, 1, 100)
|
||||||
|
//! .throttle_bps()
|
||||||
|
//! .read(6, 1, 10)
|
||||||
|
//! .write(11, 1, 100)
|
||||||
|
//! .done()
|
||||||
|
//! .build(h);
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
BlkIoDeviceResource, BlkIoDeviceThrottleResource, Cgroup, DeviceResource, Hierarchy,
|
||||||
|
HugePageResource, MaxValue, NetworkPriority, Resources,
|
||||||
|
};
|
||||||
|
|
||||||
|
macro_rules! gen_setter {
|
||||||
|
($res:ident, $cont:ident, $func:ident, $name:ident, $ty:ty) => {
|
||||||
|
/// See the similarly named function in the respective controller.
|
||||||
|
pub fn $name(mut self, $name: $ty) -> Self {
|
||||||
|
self.cgroup.resources.$res.$name = Some($name);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A control group builder instance
|
||||||
|
pub struct CgroupBuilder {
|
||||||
|
name: String,
|
||||||
|
/// Internal, unsupported field: use the associated builders instead.
|
||||||
|
resources: Resources,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CgroupBuilder {
|
||||||
|
/// Start building a control group with the supplied hierarchy and name pair.
|
||||||
|
///
|
||||||
|
/// Note that this does not actually create the control group until `build()` is called.
|
||||||
|
pub fn new(name: &str) -> CgroupBuilder {
|
||||||
|
CgroupBuilder {
|
||||||
|
name: name.to_owned(),
|
||||||
|
resources: Resources::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the memory resources of the control group.
|
||||||
|
pub fn memory(self) -> MemoryResourceBuilder {
|
||||||
|
MemoryResourceBuilder { cgroup: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the pid resources of the control group.
|
||||||
|
pub fn pid(self) -> PidResourceBuilder {
|
||||||
|
PidResourceBuilder { cgroup: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the cpu resources of the control group.
|
||||||
|
pub fn cpu(self) -> CpuResourceBuilder {
|
||||||
|
CpuResourceBuilder { cgroup: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the devices resources of the control group, disallowing or
|
||||||
|
/// allowing access to certain devices in the system.
|
||||||
|
pub fn devices(self) -> DeviceResourceBuilder {
|
||||||
|
DeviceResourceBuilder { cgroup: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the network resources of the control group, setting class id, or
|
||||||
|
/// various priorities on networking interfaces.
|
||||||
|
pub fn network(self) -> NetworkResourceBuilder {
|
||||||
|
NetworkResourceBuilder { cgroup: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the hugepage/hugetlb resources available to the control group.
|
||||||
|
pub fn hugepages(self) -> HugepagesResourceBuilder {
|
||||||
|
HugepagesResourceBuilder { cgroup: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the block I/O resources available for the control group.
|
||||||
|
pub fn blkio(self) -> BlkIoResourcesBuilder {
|
||||||
|
BlkIoResourcesBuilder {
|
||||||
|
cgroup: self,
|
||||||
|
throttling_iops: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A builder that configures the memory controller of a control group.
|
||||||
|
pub struct MemoryResourceBuilder {
|
||||||
|
cgroup: CgroupBuilder,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemoryResourceBuilder {
|
||||||
|
gen_setter!(
|
||||||
|
memory,
|
||||||
|
MemController,
|
||||||
|
set_kmem_limit,
|
||||||
|
kernel_memory_limit,
|
||||||
|
i64
|
||||||
|
);
|
||||||
|
gen_setter!(memory, MemController, set_limit, memory_hard_limit, i64);
|
||||||
|
gen_setter!(
|
||||||
|
memory,
|
||||||
|
MemController,
|
||||||
|
set_soft_limit,
|
||||||
|
memory_soft_limit,
|
||||||
|
i64
|
||||||
|
);
|
||||||
|
gen_setter!(
|
||||||
|
memory,
|
||||||
|
MemController,
|
||||||
|
set_tcp_limit,
|
||||||
|
kernel_tcp_memory_limit,
|
||||||
|
i64
|
||||||
|
);
|
||||||
|
gen_setter!(
|
||||||
|
memory,
|
||||||
|
MemController,
|
||||||
|
set_memswap_limit,
|
||||||
|
memory_swap_limit,
|
||||||
|
i64
|
||||||
|
);
|
||||||
|
gen_setter!(memory, MemController, set_swappiness, swappiness, u64);
|
||||||
|
|
||||||
|
/// Finish the construction of the memory resources of a control group.
|
||||||
|
pub fn done(self) -> CgroupBuilder {
|
||||||
|
self.cgroup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A builder that configures the pid controller of a control group.
|
||||||
|
pub struct PidResourceBuilder {
|
||||||
|
cgroup: CgroupBuilder,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PidResourceBuilder {
|
||||||
|
gen_setter!(
|
||||||
|
pid,
|
||||||
|
PidController,
|
||||||
|
set_pid_max,
|
||||||
|
maximum_number_of_processes,
|
||||||
|
MaxValue
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Finish the construction of the pid resources of a control group.
|
||||||
|
pub fn done(self) -> CgroupBuilder {
|
||||||
|
self.cgroup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A builder that configures the cpuset & cpu controllers of a control group.
|
||||||
|
pub struct CpuResourceBuilder {
|
||||||
|
cgroup: CgroupBuilder,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CpuResourceBuilder {
|
||||||
|
gen_setter!(cpu, CpuSetController, set_cpus, cpus, String);
|
||||||
|
gen_setter!(cpu, CpuSetController, set_mems, mems, String);
|
||||||
|
gen_setter!(cpu, CpuController, set_shares, shares, u64);
|
||||||
|
gen_setter!(cpu, CpuController, set_cfs_quota, quota, i64);
|
||||||
|
gen_setter!(cpu, CpuController, set_cfs_period, period, u64);
|
||||||
|
gen_setter!(cpu, CpuController, set_rt_runtime, realtime_runtime, i64);
|
||||||
|
gen_setter!(cpu, CpuController, set_rt_period, realtime_period, u64);
|
||||||
|
|
||||||
|
/// Finish the construction of the cpu resources of a control group.
|
||||||
|
pub fn done(self) -> CgroupBuilder {
|
||||||
|
self.cgroup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A builder that configures the devices controller of a control group.
|
||||||
|
pub struct DeviceResourceBuilder {
|
||||||
|
cgroup: CgroupBuilder,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceResourceBuilder {
|
||||||
|
/// Restrict (or allow) a device to the tasks inside the control group.
|
||||||
|
pub fn device(
|
||||||
|
mut self,
|
||||||
|
major: i64,
|
||||||
|
minor: i64,
|
||||||
|
devtype: crate::devices::DeviceType,
|
||||||
|
allow: bool,
|
||||||
|
access: Vec<crate::devices::DevicePermissions>,
|
||||||
|
) -> DeviceResourceBuilder {
|
||||||
|
self.cgroup.resources.devices.devices.push(DeviceResource {
|
||||||
|
allow,
|
||||||
|
devtype,
|
||||||
|
major,
|
||||||
|
minor,
|
||||||
|
access,
|
||||||
|
});
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish the construction of the devices resources of a control group.
|
||||||
|
pub fn done(self) -> CgroupBuilder {
|
||||||
|
self.cgroup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A builder that configures the net_cls & net_prio controllers of a control group.
|
||||||
|
pub struct NetworkResourceBuilder {
|
||||||
|
cgroup: CgroupBuilder,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NetworkResourceBuilder {
|
||||||
|
gen_setter!(network, NetclsController, set_class, class_id, u64);
|
||||||
|
|
||||||
|
/// Set the priority of the tasks when operating on a networking device defined by `name` to be
|
||||||
|
/// `priority`.
|
||||||
|
pub fn priority(mut self, name: String, priority: u64) -> NetworkResourceBuilder {
|
||||||
|
self.cgroup
|
||||||
|
.resources
|
||||||
|
.network
|
||||||
|
.priorities
|
||||||
|
.push(NetworkPriority { name, priority });
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish the construction of the network resources of a control group.
|
||||||
|
pub fn done(self) -> CgroupBuilder {
|
||||||
|
self.cgroup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A builder that configures the hugepages controller of a control group.
|
||||||
|
pub struct HugepagesResourceBuilder {
|
||||||
|
cgroup: CgroupBuilder,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HugepagesResourceBuilder {
|
||||||
|
/// Limit the usage of certain hugepages (determined by `size`) to be at most `limit` bytes.
|
||||||
|
pub fn limit(mut self, size: String, limit: u64) -> HugepagesResourceBuilder {
|
||||||
|
self.cgroup
|
||||||
|
.resources
|
||||||
|
.hugepages
|
||||||
|
.limits
|
||||||
|
.push(HugePageResource { size, limit });
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish the construction of the network resources of a control group.
|
||||||
|
pub fn done(self) -> CgroupBuilder {
|
||||||
|
self.cgroup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A builder that configures the blkio controller of a control group.
|
||||||
|
pub struct BlkIoResourcesBuilder {
|
||||||
|
cgroup: CgroupBuilder,
|
||||||
|
throttling_iops: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BlkIoResourcesBuilder {
|
||||||
|
gen_setter!(blkio, BlkIoController, set_weight, weight, u16);
|
||||||
|
gen_setter!(blkio, BlkIoController, set_leaf_weight, leaf_weight, u16);
|
||||||
|
|
||||||
|
/// Set the weight of a certain device.
|
||||||
|
pub fn weight_device(
|
||||||
|
mut self,
|
||||||
|
major: u64,
|
||||||
|
minor: u64,
|
||||||
|
weight: Option<u16>,
|
||||||
|
leaf_weight: Option<u16>,
|
||||||
|
) -> BlkIoResourcesBuilder {
|
||||||
|
self.cgroup
|
||||||
|
.resources
|
||||||
|
.blkio
|
||||||
|
.weight_device
|
||||||
|
.push(BlkIoDeviceResource {
|
||||||
|
major,
|
||||||
|
minor,
|
||||||
|
weight,
|
||||||
|
leaf_weight,
|
||||||
|
});
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start configuring the I/O operations per second metric.
|
||||||
|
pub fn throttle_iops(mut self) -> BlkIoResourcesBuilder {
|
||||||
|
self.throttling_iops = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start configuring the bytes per second metric.
|
||||||
|
pub fn throttle_bps(mut self) -> BlkIoResourcesBuilder {
|
||||||
|
self.throttling_iops = false;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Limit the read rate of the current metric for a certain device.
|
||||||
|
pub fn read(mut self, major: u64, minor: u64, rate: u64) -> BlkIoResourcesBuilder {
|
||||||
|
let throttle = BlkIoDeviceThrottleResource { major, minor, rate };
|
||||||
|
if self.throttling_iops {
|
||||||
|
self.cgroup
|
||||||
|
.resources
|
||||||
|
.blkio
|
||||||
|
.throttle_read_iops_device
|
||||||
|
.push(throttle);
|
||||||
|
} else {
|
||||||
|
self.cgroup
|
||||||
|
.resources
|
||||||
|
.blkio
|
||||||
|
.throttle_read_bps_device
|
||||||
|
.push(throttle);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Limit the write rate of the current metric for a certain device.
|
||||||
|
pub fn write(mut self, major: u64, minor: u64, rate: u64) -> BlkIoResourcesBuilder {
|
||||||
|
let throttle = BlkIoDeviceThrottleResource { major, minor, rate };
|
||||||
|
if self.throttling_iops {
|
||||||
|
self.cgroup
|
||||||
|
.resources
|
||||||
|
.blkio
|
||||||
|
.throttle_write_iops_device
|
||||||
|
.push(throttle);
|
||||||
|
} else {
|
||||||
|
self.cgroup
|
||||||
|
.resources
|
||||||
|
.blkio
|
||||||
|
.throttle_write_bps_device
|
||||||
|
.push(throttle);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish the construction of the blkio resources of a control group.
|
||||||
|
pub fn done(self) -> CgroupBuilder {
|
||||||
|
self.cgroup
|
||||||
|
}
|
||||||
|
}
|
||||||
282
src/cpu.rs
282
src/cpu.rs
@@ -1,12 +1,26 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `cpu` cgroup subsystem.
|
//! This module contains the implementation of the `cpu` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/scheduler/sched-design-CFS.txt](https://www.kernel.org/doc/Documentation/scheduler/sched-design-CFS.txt)
|
//! [Documentation/scheduler/sched-design-CFS.txt](https://www.kernel.org/doc/Documentation/scheduler/sched-design-CFS.txt)
|
||||||
//! paragraph 7 ("GROUP SCHEDULER EXTENSIONS TO CFS").
|
//! paragraph 7 ("GROUP SCHEDULER EXTENSIONS TO CFS").
|
||||||
use std::path::PathBuf;
|
use std::fs::File;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use {CgroupError, CpuResources, Controllers, Controller, Resources, ControllIdentifier, Subsystem};
|
use crate::error::ErrorKind::*;
|
||||||
|
use crate::error::*;
|
||||||
|
use crate::{parse_max_value, read_i64_from, read_u64_from};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
ControllIdentifier, ControllerInternal, Controllers, CpuResources, CustomizedAttribute,
|
||||||
|
MaxValue, Resources, Subsystem,
|
||||||
|
};
|
||||||
|
|
||||||
/// A controller that allows controlling the `cpu` subsystem of a Cgroup.
|
/// A controller that allows controlling the `cpu` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -14,13 +28,15 @@ use {CgroupError, CpuResources, Controllers, Controller, Resources, ControllIden
|
|||||||
/// are using the CPU and creating rules that limit their usage. Note that this crate does not yet
|
/// are using the CPU and creating rules that limit their usage. Note that this crate does not yet
|
||||||
/// support managing realtime tasks.
|
/// support managing realtime tasks.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct CpuController{
|
pub struct CpuController {
|
||||||
base: PathBuf,
|
base: PathBuf,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
v2: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The current state of the control group and its processes.
|
/// The current state of the control group and its processes.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub struct Cpu {
|
pub struct Cpu {
|
||||||
/// Reports CPU time statistics.
|
/// Reports CPU time statistics.
|
||||||
///
|
///
|
||||||
@@ -28,23 +44,49 @@ pub struct Cpu {
|
|||||||
pub stat: String,
|
pub stat: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for CpuController {
|
/// The current state of the control group and its processes.
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::Cpu}
|
#[derive(Debug)]
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
struct CfsQuotaAndPeriod {
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
quota: MaxValue,
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
period: u64,
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, res: &Resources) {
|
impl ControllerInternal for CpuController {
|
||||||
/* get the resources that apply to this controller */
|
fn control_type(&self) -> Controllers {
|
||||||
|
Controllers::Cpu
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_v2(&self) -> bool {
|
||||||
|
self.v2
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(&self, res: &Resources) -> Result<()> {
|
||||||
|
// get the resources that apply to this controller
|
||||||
let res: &CpuResources = &res.cpu;
|
let res: &CpuResources = &res.cpu;
|
||||||
|
|
||||||
if res.update_values {
|
update_and_test!(self, set_shares, res.shares, shares);
|
||||||
/* apply pid_max */
|
update_and_test!(self, set_cfs_period, res.period, cfs_period);
|
||||||
let _ = self.set_shares(res.shares);
|
update_and_test!(self, set_cfs_quota, res.quota, cfs_quota);
|
||||||
let _ = self.set_cfs_period(res.period);
|
|
||||||
let _ = self.set_cfs_quota(res.quota as u64);
|
res.attrs.iter().for_each(|(k, v)| {
|
||||||
/* TODO: rt properties (CONFIG_RT_GROUP_SCHED) are not yet supported */
|
let _ = self.set(k, v);
|
||||||
}
|
});
|
||||||
|
|
||||||
|
// TODO: rt properties (CONFIG_RT_GROUP_SCHED) are not yet supported
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,35 +103,38 @@ impl<'a> From<&'a Subsystem> for &'a CpuController {
|
|||||||
Subsystem::Cpu(c) => c,
|
Subsystem::Cpu(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CpuController {
|
impl CpuController {
|
||||||
/// Contructs a new `CpuController` with `oroot` serving as the root of the control group.
|
/// Contructs a new `CpuController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf, v2: bool) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
|
v2,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns CPU time statistics based on the processes in the control group.
|
/// Returns CPU time statistics based on the processes in the control group.
|
||||||
pub fn cpu(self: &Self) -> Cpu {
|
pub fn cpu(&self) -> Cpu {
|
||||||
Cpu {
|
Cpu {
|
||||||
stat: self.open_path("cpu.stat", false).and_then(|mut file| {
|
stat: self
|
||||||
let mut s = String::new();
|
.open_path("cpu.stat", false)
|
||||||
let res = file.read_to_string(&mut s);
|
.and_then(|mut file| {
|
||||||
match res {
|
let mut s = String::new();
|
||||||
Ok(_) => Ok(s),
|
let res = file.read_to_string(&mut s);
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
match res {
|
||||||
}
|
Ok(_) => Ok(s),
|
||||||
}).unwrap_or("".to_string()),
|
Err(e) => Err(Error::with_cause(ReadFailed("cpu.stat".to_string()), e)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,25 +144,178 @@ impl CpuController {
|
|||||||
/// For example, setting control group `A`'s `shares` to `100`, and control group `B`'s
|
/// For example, setting control group `A`'s `shares` to `100`, and control group `B`'s
|
||||||
/// `shares` to `200` ensures that control group `B` receives twice as much as CPU bandwidth.
|
/// `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)
|
/// (Assuming both `A` and `B` are of the same parent)
|
||||||
pub fn set_shares(self: &Self, shares: u64) -> Result<(), CgroupError> {
|
pub fn set_shares(&self, shares: u64) -> Result<()> {
|
||||||
self.open_path("cpu.shares", true).and_then(|mut file| {
|
let mut file_name = "cpu.shares";
|
||||||
file.write_all(shares.to_string().as_ref()).map_err(CgroupError::WriteError)
|
if self.v2 {
|
||||||
|
file_name = "cpu.weight";
|
||||||
|
}
|
||||||
|
// NOTE: .CpuShares is not used here. Conversion is the caller's responsibility.
|
||||||
|
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)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Retrieve the CPU bandwidth that this control group (relative to other control groups and
|
||||||
|
/// this control group's parent) can use.
|
||||||
|
pub fn shares(&self) -> Result<u64> {
|
||||||
|
let mut file = "cpu.shares";
|
||||||
|
if self.v2 {
|
||||||
|
file = "cpu.weight";
|
||||||
|
}
|
||||||
|
self.open_path(file, false).and_then(read_u64_from)
|
||||||
|
}
|
||||||
|
|
||||||
/// Specify a period (when using the CFS scheduler) of time in microseconds for how often this
|
/// Specify a period (when using the CFS scheduler) of time in microseconds for how often this
|
||||||
/// control group's access to the CPU should be reallocated.
|
/// control group's access to the CPU should be reallocated.
|
||||||
pub fn set_cfs_period(self: &Self, us: u64) -> Result<(), CgroupError> {
|
pub fn set_cfs_period(&self, us: u64) -> Result<()> {
|
||||||
self.open_path("cpu.cfs_period_us", true).and_then(|mut file| {
|
if self.v2 {
|
||||||
file.write_all(us.to_string().as_ref()).map_err(CgroupError::WriteError)
|
return self.set_cfs_quota_and_period(None, Some(us));
|
||||||
})
|
}
|
||||||
|
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("cpu.cfs_period_us".to_string(), us.to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve the period of time of how often this cgroup's access to the CPU should be
|
||||||
|
/// reallocated in microseconds.
|
||||||
|
pub fn cfs_period(&self) -> Result<u64> {
|
||||||
|
if self.v2 {
|
||||||
|
let current_value = self
|
||||||
|
.open_path("cpu.max", false)
|
||||||
|
.and_then(parse_cfs_quota_and_period)?;
|
||||||
|
return Ok(current_value.period);
|
||||||
|
}
|
||||||
|
self.open_path("cpu.cfs_period_us", false)
|
||||||
|
.and_then(read_u64_from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specify a quota (when using the CFS scheduler) of time in microseconds for which all tasks
|
/// Specify a quota (when using the CFS scheduler) of time in microseconds for which all tasks
|
||||||
/// in this control group can run during one period (see: `set_cfs_period()`).
|
/// in this control group can run during one period (see: `set_cfs_period()`).
|
||||||
pub fn set_cfs_quota(self: &Self, us: u64) -> Result<(), CgroupError> {
|
pub fn set_cfs_quota(&self, us: i64) -> Result<()> {
|
||||||
self.open_path("cpu.cfs_quota_us", true).and_then(|mut file| {
|
if self.v2 {
|
||||||
file.write_all(us.to_string().as_ref()).map_err(CgroupError::WriteError)
|
return self.set_cfs_quota_and_period(Some(us), None);
|
||||||
|
}
|
||||||
|
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("cpu.cfs_quota_us".to_string(), us.to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve the quota of time for which all tasks in this cgroup can run during one period, in
|
||||||
|
/// microseconds.
|
||||||
|
pub fn cfs_quota(&self) -> Result<i64> {
|
||||||
|
if self.v2 {
|
||||||
|
let current_value = self
|
||||||
|
.open_path("cpu.max", false)
|
||||||
|
.and_then(parse_cfs_quota_and_period)?;
|
||||||
|
return Ok(current_value.quota.to_i64());
|
||||||
|
}
|
||||||
|
|
||||||
|
self.open_path("cpu.cfs_quota_us", false)
|
||||||
|
.and_then(read_i64_from)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_cfs_quota_and_period(&self, quota: Option<i64>, period: Option<u64>) -> Result<()> {
|
||||||
|
if !self.v2 {
|
||||||
|
if let Some(q) = quota {
|
||||||
|
self.set_cfs_quota(q)?;
|
||||||
|
}
|
||||||
|
if let Some(p) = period {
|
||||||
|
self.set_cfs_period(p)?;
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
|
||||||
|
|
||||||
|
// cpu.max
|
||||||
|
// A read-write two value file which exists on non-root cgroups. The default is “max 100000”.
|
||||||
|
// The maximum bandwidth limit. It’s in the following format:
|
||||||
|
// $MAX $PERIOD
|
||||||
|
// which indicates that the group may consume upto $MAX in each $PERIOD duration.
|
||||||
|
// “max” for $MAX indicates no limit. If only one number is written, $MAX is updated.
|
||||||
|
|
||||||
|
let current_value = self
|
||||||
|
.open_path("cpu.max", false)
|
||||||
|
.and_then(parse_cfs_quota_and_period)?;
|
||||||
|
|
||||||
|
let new_quota = if let Some(q) = quota {
|
||||||
|
if q > 0 {
|
||||||
|
q.to_string()
|
||||||
|
} else {
|
||||||
|
"max".to_string()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
current_value.quota.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
let new_period = if let Some(p) = period {
|
||||||
|
p.to_string()
|
||||||
|
} else {
|
||||||
|
current_value.period.to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
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("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("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("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> {
|
||||||
|
let mut content = String::new();
|
||||||
|
file.read_to_string(&mut content)
|
||||||
|
.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])?;
|
||||||
|
let period = fields[1]
|
||||||
|
.parse::<u64>()
|
||||||
|
.map_err(|e| Error::with_cause(ParseError, e))?;
|
||||||
|
|
||||||
|
Ok(CfsQuotaAndPeriod { quota, period })
|
||||||
}
|
}
|
||||||
|
|||||||
127
src/cpuacct.rs
127
src/cpuacct.rs
@@ -1,12 +1,20 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `cpuacct` cgroup subsystem.
|
//! This module contains the implementation of the `cpuacct` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/cgroup-v1/cpuacct.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/cpuacct.txt)
|
//! [Documentation/cgroup-v1/cpuacct.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/cpuacct.txt)
|
||||||
|
use std::io::Write;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::io::{Read, Write};
|
|
||||||
use std::fs::File;
|
|
||||||
|
|
||||||
use {CgroupError, Controllers, Resources, Subsystem, ControllIdentifier, Controller};
|
use crate::error::ErrorKind::*;
|
||||||
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::{read_string_from, read_u64_from};
|
||||||
|
use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};
|
||||||
|
|
||||||
/// A controller that allows controlling the `cpuacct` subsystem of a Cgroup.
|
/// A controller that allows controlling the `cpuacct` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -19,6 +27,7 @@ pub struct CpuAcctController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Represents the statistics retrieved from the control group.
|
/// Represents the statistics retrieved from the control group.
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub struct CpuAcct {
|
pub struct CpuAcct {
|
||||||
/// Divides the time used by the tasks into `user` time and `system` time.
|
/// Divides the time used by the tasks into `user` time and `system` time.
|
||||||
pub stat: String,
|
pub stat: String,
|
||||||
@@ -49,13 +58,22 @@ pub struct CpuAcct {
|
|||||||
pub usage_user: u64,
|
pub usage_user: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for CpuAcctController {
|
impl ControllerInternal for CpuAcctController {
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::CpuAcct }
|
fn control_type(&self) -> Controllers {
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
Controllers::CpuAcct
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
}
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, _res: &Resources) {
|
fn apply(&self, _res: &Resources) -> Result<()> {
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,39 +90,17 @@ impl<'a> From<&'a Subsystem> for &'a CpuAcctController {
|
|||||||
Subsystem::CpuAcct(c) => c,
|
Subsystem::CpuAcct(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_u64_from(mut file: File) -> Result<u64, CgroupError> {
|
|
||||||
let mut string = String::new();
|
|
||||||
let res = file.read_to_string(&mut string);
|
|
||||||
match res {
|
|
||||||
Ok(_) => match string.trim().parse() {
|
|
||||||
Ok(e) => Ok(e),
|
|
||||||
Err(_) => Err(CgroupError::ParseError),
|
|
||||||
},
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_string_from(mut file: File) -> Result<String, CgroupError> {
|
|
||||||
let mut string = String::new();
|
|
||||||
match file.read_to_string(&mut string) {
|
|
||||||
Ok(_) => Ok(string.trim().to_string()),
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CpuAcctController {
|
impl CpuAcctController {
|
||||||
|
/// Contructs a new `CpuAcctController` with `root` serving as the root of the control group.
|
||||||
/// Contructs a new `CpuAcctController` with `oroot` serving as the root of the control group.
|
pub fn new(root: PathBuf) -> Self {
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
@@ -112,34 +108,49 @@ impl CpuAcctController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Gathers the statistics that are available in the control group into a `CpuAcct` structure.
|
/// Gathers the statistics that are available in the control group into a `CpuAcct` structure.
|
||||||
pub fn cpuacct(self: &Self) -> CpuAcct {
|
pub fn cpuacct(&self) -> CpuAcct {
|
||||||
CpuAcct {
|
CpuAcct {
|
||||||
stat: self.open_path("cpuacct.stat", false)
|
stat: self
|
||||||
.and_then(|file| read_string_from(file)).unwrap_or("".to_string()),
|
.open_path("cpuacct.stat", false)
|
||||||
usage: self.open_path("cpuacct.usage", false)
|
.and_then(read_string_from)
|
||||||
.and_then(|file| read_u64_from(file))
|
.unwrap_or_default(),
|
||||||
.unwrap_or(0),
|
usage: self
|
||||||
usage_all: self.open_path("cpuacct.usage_all", false)
|
.open_path("cpuacct.usage", false)
|
||||||
.and_then(|file| read_string_from(file)).unwrap_or("".to_string()),
|
.and_then(read_u64_from)
|
||||||
usage_percpu: self.open_path("cpuacct.usage_percpu", false)
|
.unwrap_or(0),
|
||||||
.and_then(|file| read_string_from(file)).unwrap_or("".to_string()),
|
usage_all: self
|
||||||
usage_percpu_sys: self.open_path("cpuacct.usage_percpu_sys", false)
|
.open_path("cpuacct.usage_all", false)
|
||||||
.and_then(|file| read_string_from(file)).unwrap_or("".to_string()),
|
.and_then(read_string_from)
|
||||||
usage_percpu_user: self.open_path("cpuacct.usage_percpu_user", false)
|
.unwrap_or_default(),
|
||||||
.and_then(|file| read_string_from(file)).unwrap_or("".to_string()),
|
usage_percpu: self
|
||||||
usage_sys: self.open_path("cpuacct.usage_sys", false)
|
.open_path("cpuacct.usage_percpu", false)
|
||||||
.and_then(|file| read_u64_from(file))
|
.and_then(read_string_from)
|
||||||
.unwrap_or(0),
|
.unwrap_or_default(),
|
||||||
usage_user: self.open_path("cpuacct.usage_user", false)
|
usage_percpu_sys: self
|
||||||
.and_then(|file| read_u64_from(file))
|
.open_path("cpuacct.usage_percpu_sys", false)
|
||||||
.unwrap_or(0),
|
.and_then(read_string_from)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
usage_percpu_user: self
|
||||||
|
.open_path("cpuacct.usage_percpu_user", false)
|
||||||
|
.and_then(read_string_from)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
usage_sys: self
|
||||||
|
.open_path("cpuacct.usage_sys", false)
|
||||||
|
.and_then(read_u64_from)
|
||||||
|
.unwrap_or(0),
|
||||||
|
usage_user: self
|
||||||
|
.open_path("cpuacct.usage_user", false)
|
||||||
|
.and_then(read_u64_from)
|
||||||
|
.unwrap_or(0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reset the statistics the kernel has gathered about the control group.
|
/// Reset the statistics the kernel has gathered about the control group.
|
||||||
pub fn reset(self: &Self) -> Result<(), CgroupError> {
|
pub fn reset(&self) -> Result<()> {
|
||||||
self.open_path("cpuacct.usage", true).and_then(|mut file| {
|
self.open_path("cpuacct.usage", true).and_then(|mut file| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
file.write_all(b"0").map_err(|e| {
|
||||||
|
Error::with_cause(WriteFailed("cpuacct.usage".to_string(), "0".to_string()), e)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
573
src/cpuset.rs
573
src/cpuset.rs
@@ -1,13 +1,25 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `cpuset` cgroup subsystem.
|
//! This module contains the implementation of the `cpuset` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/cgroup-v1/cpusets.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/cpusets.txt)
|
//! [Documentation/cgroup-v1/cpusets.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/cpusets.txt)
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::io::{Read, Write};
|
|
||||||
use std::fs::File;
|
|
||||||
|
|
||||||
use {CgroupError, CpuResources, Resources, Controller, ControllIdentifier, Subsystem, Controllers};
|
use log::*;
|
||||||
use CgroupError::*;
|
use std::io::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use crate::error::ErrorKind::*;
|
||||||
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::{read_string_from, read_u64_from};
|
||||||
|
use crate::{
|
||||||
|
ControllIdentifier, ControllerInternal, Controllers, CpuResources, Resources, Subsystem,
|
||||||
|
};
|
||||||
|
|
||||||
/// A controller that allows controlling the `cpuset` subsystem of a Cgroup.
|
/// A controller that allows controlling the `cpuset` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -17,23 +29,27 @@ use CgroupError::*;
|
|||||||
pub struct CpuSetController {
|
pub struct CpuSetController {
|
||||||
base: PathBuf,
|
base: PathBuf,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
v2: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The current state of the `cpuset` controller for this control group.
|
/// The current state of the `cpuset` controller for this control group.
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub struct CpuSet {
|
pub struct CpuSet {
|
||||||
/// If true, no other control groups can share the CPUs listed in the `cpus` field.
|
/// If true, no other control groups can share the CPUs listed in the `cpus` field.
|
||||||
pub cpu_exclusive: bool,
|
pub cpu_exclusive: bool,
|
||||||
/// The list of CPUs the tasks of the control group can run on. This is a comma-separated list
|
/// The list of CPUs the tasks of the control group can run on.
|
||||||
/// with dashes between numbers representing ranges.
|
///
|
||||||
pub cpus: String,
|
/// This is a vector of `(start, end)` tuples, where each tuple is a range of CPUs where the
|
||||||
|
/// control group is allowed to run on. Both sides of the range are inclusive.
|
||||||
|
pub cpus: Vec<(u64, u64)>,
|
||||||
/// The list of CPUs that the tasks can effectively run on. This removes the list of CPUs that
|
/// The list of CPUs that the tasks can effectively run on. This removes the list of CPUs that
|
||||||
/// the parent (and all of its parents) cannot run on from the `cpus` field of this control
|
/// the parent (and all of its parents) cannot run on from the `cpus` field of this control
|
||||||
/// group.
|
/// group.
|
||||||
pub effective_cpus: String,
|
pub effective_cpus: Vec<(u64, u64)>,
|
||||||
/// The list of memory nodes that the tasks can effectively use. This removes the list of nodes that
|
/// The list of memory nodes that the tasks can effectively use. This removes the list of nodes that
|
||||||
/// the parent (and all of its parents) cannot use from the `mems` field of this control
|
/// the parent (and all of its parents) cannot use from the `mems` field of this control
|
||||||
/// group.
|
/// group.
|
||||||
pub effective_mems: String,
|
pub effective_mems: Vec<(u64, u64)>,
|
||||||
/// If true, no other control groups can share the memory nodes listed in the `mems` field.
|
/// If true, no other control groups can share the memory nodes listed in the `mems` field.
|
||||||
pub mem_exclusive: bool,
|
pub mem_exclusive: bool,
|
||||||
/// If true, the control group is 'hardwalled'. Kernel memory allocations (except for a few
|
/// If true, the control group is 'hardwalled'. Kernel memory allocations (except for a few
|
||||||
@@ -52,9 +68,10 @@ pub struct CpuSet {
|
|||||||
/// If true, kernel slab caches for file I/O are spread across evenly between the nodes
|
/// If true, kernel slab caches for file I/O are spread across evenly between the nodes
|
||||||
/// specified in `mems`.
|
/// specified in `mems`.
|
||||||
pub memory_spread_slab: bool,
|
pub memory_spread_slab: bool,
|
||||||
/// The list of memory nodes the tasks of the control group can use. This is a comma-separated list
|
/// The list of memory nodes the tasks of the control group can use.
|
||||||
/// with dashes between numbers representing ranges.
|
///
|
||||||
pub mems: String,
|
/// The format is the same as the `cpus`, `effective_cpus` and `effective_mems` fields.
|
||||||
|
pub mems: Vec<(u64, u64)>,
|
||||||
/// If true, the kernel will attempt to rebalance the load between the CPUs specified in the
|
/// If true, the kernel will attempt to rebalance the load between the CPUs specified in the
|
||||||
/// `cpus` field of this control group.
|
/// `cpus` field of this control group.
|
||||||
pub sched_load_balance: bool,
|
pub sched_load_balance: bool,
|
||||||
@@ -70,27 +87,113 @@ pub struct CpuSet {
|
|||||||
/// | 5 | Immediately balance the load between CPUs even if the system is NUMA |
|
/// | 5 | Immediately balance the load between CPUs even if the system is NUMA |
|
||||||
/// | 6 | Immediately balance the load between all CPUs |
|
/// | 6 | Immediately balance the load between all CPUs |
|
||||||
pub sched_relax_domain_level: u64,
|
pub sched_relax_domain_level: u64,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for CpuSetController {
|
impl ControllerInternal for CpuSetController {
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::CpuSet }
|
fn control_type(&self) -> Controllers {
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
Controllers::CpuSet
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
}
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, res: &Resources) {
|
fn is_v2(&self) -> bool {
|
||||||
/* get the resources that apply to this controller */
|
self.v2
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(&self, res: &Resources) -> Result<()> {
|
||||||
|
// get the resources that apply to this controller
|
||||||
let res: &CpuResources = &res.cpu;
|
let res: &CpuResources = &res.cpu;
|
||||||
|
|
||||||
if res.update_values {
|
update!(self, set_cpus, res.cpus.as_ref());
|
||||||
/* apply pid_max */
|
update!(self, set_mems, res.mems.as_ref());
|
||||||
let _ = self.set_cpus(&res.cpus);
|
|
||||||
let _ = self.set_mems(&res.mems);
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn post_create(&self) {
|
||||||
|
if self.is_v2() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let current = self.get_path();
|
||||||
|
|
||||||
|
if current != self.get_base() {
|
||||||
|
match copy_from_parent(current.to_str().unwrap(), "cpuset.cpus") {
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(err) => error!("error create_dir for cpuset.cpus {:?}", err),
|
||||||
|
}
|
||||||
|
match copy_from_parent(current.to_str().unwrap(), "cpuset.mems") {
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(err) => error!("error create_dir for cpuset.mems {:?}", err),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn find_no_empty_parent(from: &str, file: &str) -> Result<(String, Vec<PathBuf>)> {
|
||||||
|
let mut current_path = ::std::path::Path::new(from).to_path_buf();
|
||||||
|
let mut v = vec![];
|
||||||
|
|
||||||
|
loop {
|
||||||
|
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(current_path.display().to_string()),
|
||||||
|
e,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !current_value.is_empty() {
|
||||||
|
return Ok((current_value, v));
|
||||||
|
}
|
||||||
|
v.push(current_path.clone());
|
||||||
|
|
||||||
|
let parent = match current_path.parent() {
|
||||||
|
Some(p) => p,
|
||||||
|
None => return Ok(("".to_string(), v)),
|
||||||
|
};
|
||||||
|
|
||||||
|
// next loop, find parent
|
||||||
|
current_path = parent.to_path_buf();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// copy_from_parent copy the cpuset.cpus and cpuset.mems from the parent
|
||||||
|
/// directory to the current directory if the file's contents are 0
|
||||||
|
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.is_empty() || parents.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
for p in parents.iter().rev() {
|
||||||
|
let mut pb = p.clone();
|
||||||
|
pb.push(file);
|
||||||
|
match ::std::fs::write(pb.to_str().unwrap(), value.as_bytes()) {
|
||||||
|
Ok(_) => (),
|
||||||
|
Err(e) => {
|
||||||
|
return Err(Error::with_cause(
|
||||||
|
WriteFailed(pb.display().to_string(), pb.display().to_string()),
|
||||||
|
e,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
impl ControllIdentifier for CpuSetController {
|
impl ControllIdentifier for CpuSetController {
|
||||||
fn controller_type() -> Controllers {
|
fn controller_type() -> Controllers {
|
||||||
Controllers::CpuSet
|
Controllers::CpuSet
|
||||||
@@ -104,94 +207,145 @@ impl<'a> From<&'a Subsystem> for &'a CpuSetController {
|
|||||||
Subsystem::CpuSet(c) => c,
|
Subsystem::CpuSet(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_string_from(mut file: File) -> Result<String, CgroupError> {
|
/// Parse a string like "1,2,4-5,8" into a list of (start, end) tuples.
|
||||||
let mut string = String::new();
|
fn parse_range(s: String) -> Result<Vec<(u64, u64)>> {
|
||||||
match file.read_to_string(&mut string) {
|
let mut fin = Vec::new();
|
||||||
Ok(_) => Ok(string.trim().to_string()),
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_u64_from(mut file: File) -> Result<u64, CgroupError> {
|
if s.is_empty() {
|
||||||
let mut string = String::new();
|
return Ok(fin);
|
||||||
match file.read_to_string(&mut string) {
|
|
||||||
Ok(_) => string.trim().parse().map_err(|_| ParseError),
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// first split by commas
|
||||||
|
let comma_split = s.split(',');
|
||||||
|
|
||||||
|
for sp in comma_split {
|
||||||
|
if sp.contains('-') {
|
||||||
|
// this is a true range
|
||||||
|
let dash_split = sp.split('-').collect::<Vec<_>>();
|
||||||
|
if dash_split.len() != 2 {
|
||||||
|
return Err(Error::new(ParseError));
|
||||||
|
}
|
||||||
|
let first = dash_split[0].parse::<u64>();
|
||||||
|
let second = dash_split[1].parse::<u64>();
|
||||||
|
if first.is_err() || second.is_err() {
|
||||||
|
return Err(Error::new(ParseError));
|
||||||
|
}
|
||||||
|
fin.push((first.unwrap(), second.unwrap()));
|
||||||
|
} else {
|
||||||
|
// this is just a single number
|
||||||
|
let num = sp.parse::<u64>();
|
||||||
|
if num.is_err() {
|
||||||
|
return Err(Error::new(ParseError));
|
||||||
|
}
|
||||||
|
fin.push((num.clone().unwrap(), num.clone().unwrap()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(fin)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CpuSetController {
|
impl CpuSetController {
|
||||||
/// Contructs a new `CpuSetController` with `oroot` serving as the root of the control group.
|
/// Contructs a new `CpuSetController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf, v2: bool) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
|
v2,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the statistics gathered by the kernel for this control group. See the struct for
|
/// Returns the statistics gathered by the kernel for this control group. See the struct for
|
||||||
/// more information on what information this entails.
|
/// more information on what information this entails.
|
||||||
pub fn cpuset(self: &Self) -> CpuSet {
|
pub fn cpuset(&self) -> CpuSet {
|
||||||
CpuSet {
|
CpuSet {
|
||||||
cpu_exclusive: {
|
cpu_exclusive: {
|
||||||
self.open_path("cpuset.cpu_exclusive", false).and_then(|file| {
|
self.open_path("cpuset.cpu_exclusive", false)
|
||||||
read_u64_from(file)
|
.and_then(read_u64_from)
|
||||||
}).map(|x| x == 1).unwrap_or(false)
|
.map(|x| x == 1)
|
||||||
|
.unwrap_or(false)
|
||||||
},
|
},
|
||||||
cpus: {
|
cpus: {
|
||||||
self.open_path("cpuset.cpus", false).and_then(read_string_from).unwrap_or("".to_string())
|
self.open_path("cpuset.cpus", false)
|
||||||
|
.and_then(read_string_from)
|
||||||
|
.and_then(parse_range)
|
||||||
|
.unwrap_or_default()
|
||||||
},
|
},
|
||||||
effective_cpus: {
|
effective_cpus: {
|
||||||
self.open_path("cpuset.effective_cpus", false).and_then(read_string_from).unwrap_or("".to_string())
|
self.open_path("cpuset.effective_cpus", false)
|
||||||
|
.and_then(read_string_from)
|
||||||
|
.and_then(parse_range)
|
||||||
|
.unwrap_or_default()
|
||||||
},
|
},
|
||||||
effective_mems: {
|
effective_mems: {
|
||||||
self.open_path("cpuset.effective_mems", false).and_then(read_string_from).unwrap_or("".to_string())
|
self.open_path("cpuset.effective_mems", false)
|
||||||
|
.and_then(read_string_from)
|
||||||
|
.and_then(parse_range)
|
||||||
|
.unwrap_or_default()
|
||||||
},
|
},
|
||||||
mem_exclusive: {
|
mem_exclusive: {
|
||||||
self.open_path("cpuset.mem_exclusive", false).and_then(read_u64_from)
|
self.open_path("cpuset.mem_exclusive", false)
|
||||||
.map(|x| x == 1).unwrap_or(false)
|
.and_then(read_u64_from)
|
||||||
|
.map(|x| x == 1)
|
||||||
|
.unwrap_or(false)
|
||||||
},
|
},
|
||||||
mem_hardwall: {
|
mem_hardwall: {
|
||||||
self.open_path("cpuset.mem_hardwall", false).and_then(read_u64_from)
|
self.open_path("cpuset.mem_hardwall", false)
|
||||||
.map(|x| x == 1).unwrap_or(false)
|
.and_then(read_u64_from)
|
||||||
|
.map(|x| x == 1)
|
||||||
|
.unwrap_or(false)
|
||||||
},
|
},
|
||||||
memory_migrate: {
|
memory_migrate: {
|
||||||
self.open_path("cpuset.memory_migrate", false).and_then(read_u64_from)
|
self.open_path("cpuset.memory_migrate", false)
|
||||||
.map(|x| x == 1).unwrap_or(false)
|
.and_then(read_u64_from)
|
||||||
|
.map(|x| x == 1)
|
||||||
|
.unwrap_or(false)
|
||||||
},
|
},
|
||||||
memory_pressure: {
|
memory_pressure: {
|
||||||
self.open_path("cpuset.memory_pressure", false).and_then(read_u64_from).unwrap_or(0)
|
self.open_path("cpuset.memory_pressure", false)
|
||||||
|
.and_then(read_u64_from)
|
||||||
|
.unwrap_or(0)
|
||||||
},
|
},
|
||||||
memory_pressure_enabled: {
|
memory_pressure_enabled: {
|
||||||
self.open_path("cpuset.memory_pressure_enabled", false).and_then(read_u64_from)
|
self.open_path("cpuset.memory_pressure_enabled", false)
|
||||||
.map(|x| x == 1).ok()
|
.and_then(read_u64_from)
|
||||||
|
.map(|x| x == 1)
|
||||||
|
.ok()
|
||||||
},
|
},
|
||||||
memory_spread_page: {
|
memory_spread_page: {
|
||||||
self.open_path("cpuset.memory_spread_page", false).and_then(read_u64_from)
|
self.open_path("cpuset.memory_spread_page", false)
|
||||||
.map(|x| x == 1).unwrap_or(false)
|
.and_then(read_u64_from)
|
||||||
|
.map(|x| x == 1)
|
||||||
|
.unwrap_or(false)
|
||||||
},
|
},
|
||||||
memory_spread_slab: {
|
memory_spread_slab: {
|
||||||
self.open_path("cpuset.memory_spread_slab", false).and_then(read_u64_from)
|
self.open_path("cpuset.memory_spread_slab", false)
|
||||||
.map(|x| x == 1).unwrap_or(false)
|
.and_then(read_u64_from)
|
||||||
|
.map(|x| x == 1)
|
||||||
|
.unwrap_or(false)
|
||||||
},
|
},
|
||||||
mems: {
|
mems: {
|
||||||
self.open_path("cpuset.mems", false).and_then(read_string_from).unwrap_or("".to_string())
|
self.open_path("cpuset.mems", false)
|
||||||
|
.and_then(read_string_from)
|
||||||
|
.and_then(parse_range)
|
||||||
|
.unwrap_or_default()
|
||||||
},
|
},
|
||||||
sched_load_balance: {
|
sched_load_balance: {
|
||||||
self.open_path("cpuset.sched_load_balance", false).and_then(read_u64_from)
|
self.open_path("cpuset.sched_load_balance", false)
|
||||||
.map(|x| x == 1).unwrap_or(false)
|
.and_then(read_u64_from)
|
||||||
|
.map(|x| x == 1)
|
||||||
|
.unwrap_or(false)
|
||||||
},
|
},
|
||||||
sched_relax_domain_level: {
|
sched_relax_domain_level: {
|
||||||
self.open_path("cpuset.sched_relax_domain_level", false).and_then(read_u64_from)
|
self.open_path("cpuset.sched_relax_domain_level", false)
|
||||||
|
.and_then(read_u64_from)
|
||||||
.unwrap_or(0)
|
.unwrap_or(0)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -199,44 +353,70 @@ impl CpuSetController {
|
|||||||
|
|
||||||
/// Control whether the CPUs selected via `set_cpus()` should be exclusive to this control
|
/// Control whether the CPUs selected via `set_cpus()` should be exclusive to this control
|
||||||
/// group or not.
|
/// group or not.
|
||||||
pub fn set_cpu_exclusive(self: &Self, b: bool) -> Result<(), CgroupError> {
|
pub fn set_cpu_exclusive(&self, b: bool) -> Result<()> {
|
||||||
self.open_path("cpuset.cpu_exclusive", true).and_then(|mut file| {
|
self.open_path("cpuset.cpu_exclusive", true)
|
||||||
if b {
|
.and_then(|mut file| {
|
||||||
file.write_all(b"1").map_err(CgroupError::WriteError)
|
if b {
|
||||||
} else {
|
file.write_all(b"1").map_err(|e| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
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("cpuset.cpu_exclusive".to_string(), "0".to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Control whether the memory nodes selected via `set_memss()` should be exclusive to this control
|
/// Control whether the memory nodes selected via `set_memss()` should be exclusive to this control
|
||||||
/// group or not.
|
/// group or not.
|
||||||
pub fn set_mem_exclusive(self: &Self, b: bool) -> Result<(), CgroupError> {
|
pub fn set_mem_exclusive(&self, b: bool) -> Result<()> {
|
||||||
self.open_path("cpuset.mem_exclusive", true).and_then(|mut file| {
|
self.open_path("cpuset.mem_exclusive", true)
|
||||||
if b {
|
.and_then(|mut file| {
|
||||||
file.write_all(b"1").map_err(CgroupError::WriteError)
|
if b {
|
||||||
} else {
|
file.write_all(b"1").map_err(|e| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
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("cpuset.mem_exclusive".to_string(), "0".to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the CPUs that the tasks in this control group can run on.
|
/// Set the CPUs that the tasks in this control group can run on.
|
||||||
///
|
///
|
||||||
/// Syntax is a comma separated list of CPUs, with an additional extension that ranges can
|
/// Syntax is a comma separated list of CPUs, with an additional extension that ranges can
|
||||||
/// be represented via dashes.
|
/// be represented via dashes.
|
||||||
pub fn set_cpus(self: &Self, cpus: &String) -> Result<(), CgroupError> {
|
pub fn set_cpus(&self, cpus: &str) -> Result<()> {
|
||||||
self.open_path("cpuset.cpus", true).and_then(|mut file| {
|
self.open_path("cpuset.cpus", true).and_then(|mut file| {
|
||||||
file.write_all(cpus.as_ref()).map_err(CgroupError::WriteError)
|
file.write_all(cpus.as_ref()).map_err(|e| {
|
||||||
|
Error::with_cause(WriteFailed("cpuset.cpus".to_string(), cpus.to_string()), e)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the memory nodes that the tasks in this control group can use.
|
/// Set the memory nodes that the tasks in this control group can use.
|
||||||
///
|
///
|
||||||
/// Syntax is the same as with `set_cpus()`.
|
/// Syntax is the same as with `set_cpus()`.
|
||||||
pub fn set_mems(self: &Self, mems: &String) -> Result<(), CgroupError> {
|
pub fn set_mems(&self, mems: &str) -> Result<()> {
|
||||||
self.open_path("cpuset.mems", true).and_then(|mut file| {
|
self.open_path("cpuset.mems", true).and_then(|mut file| {
|
||||||
file.write_all(mems.as_ref()).map_err(CgroupError::WriteError)
|
file.write_all(mems.as_ref()).map_err(|e| {
|
||||||
|
Error::with_cause(WriteFailed("cpuset.mems".to_string(), mems.to_string()), e)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,86 +425,197 @@ impl CpuSetController {
|
|||||||
///
|
///
|
||||||
/// Note that some kernel allocations, most notably those that are made in interrupt handlers
|
/// Note that some kernel allocations, most notably those that are made in interrupt handlers
|
||||||
/// may disregard this.
|
/// may disregard this.
|
||||||
pub fn set_hardwall(self: &Self, b: bool) -> Result<(), CgroupError> {
|
pub fn set_hardwall(&self, b: bool) -> Result<()> {
|
||||||
self.open_path("cpuset.mem_hardwall", true).and_then(|mut file| {
|
self.open_path("cpuset.mem_hardwall", true)
|
||||||
if b {
|
.and_then(|mut file| {
|
||||||
file.write_all(b"1").map_err(CgroupError::WriteError)
|
if b {
|
||||||
} else {
|
file.write_all(b"1").map_err(|e| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
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("cpuset.mem_hardwall".to_string(), "0".to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Controls whether the kernel should attempt to rebalance the load between the CPUs specified in the
|
/// Controls whether the kernel should attempt to rebalance the load between the CPUs specified in the
|
||||||
/// `cpus` field of this control group.
|
/// `cpus` field of this control group.
|
||||||
pub fn set_load_balancing(self: &Self, b: bool) -> Result<(), CgroupError> {
|
pub fn set_load_balancing(&self, b: bool) -> Result<()> {
|
||||||
self.open_path("cpuset.sched_load_balance", true).and_then(|mut file| {
|
self.open_path("cpuset.sched_load_balance", true)
|
||||||
if b {
|
.and_then(|mut file| {
|
||||||
file.write_all(b"1").map_err(CgroupError::WriteError)
|
if b {
|
||||||
} else {
|
file.write_all(b"1").map_err(|e| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
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("cpuset.sched_load_balance".to_string(), "0".to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Contorl how much effort the kernel should invest in rebalacing the control group.
|
/// Contorl how much effort the kernel should invest in rebalacing the control group.
|
||||||
///
|
///
|
||||||
/// See @CpuSet 's similar field for more information.
|
/// See @CpuSet 's similar field for more information.
|
||||||
pub fn set_rebalance_relax_domain_level(self: &Self, i: i64) -> Result<(), CgroupError> {
|
pub fn set_rebalance_relax_domain_level(&self, i: i64) -> Result<()> {
|
||||||
self.open_path("cpuset.sched_relax_domain_level", true).and_then(|mut file| {
|
self.open_path("cpuset.sched_relax_domain_level", true)
|
||||||
file.write_all(i.to_string().as_ref()).map_err(CgroupError::WriteError)
|
.and_then(|mut file| {
|
||||||
})
|
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,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Control whether when using `set_mems()` the existing memory used by the tasks should be
|
/// Control whether when using `set_mems()` the existing memory used by the tasks should be
|
||||||
/// migrated over to the now-selected nodes.
|
/// migrated over to the now-selected nodes.
|
||||||
pub fn set_memory_migration(self: &Self, b: bool) -> Result<(), CgroupError> {
|
pub fn set_memory_migration(&self, b: bool) -> Result<()> {
|
||||||
self.open_path("cpuset.memory_migrate", true).and_then(|mut file| {
|
self.open_path("cpuset.memory_migrate", true)
|
||||||
if b {
|
.and_then(|mut file| {
|
||||||
file.write_all(b"1").map_err(CgroupError::WriteError)
|
if b {
|
||||||
} else {
|
file.write_all(b"1").map_err(|e| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
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("cpuset.memory_migrate".to_string(), "0".to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Control whether filesystem buffers should be evenly split across the nodes selected via
|
/// Control whether filesystem buffers should be evenly split across the nodes selected via
|
||||||
/// `set_mems()`.
|
/// `set_mems()`.
|
||||||
pub fn set_memory_spread_page(self: &Self, b: bool) -> Result<(), CgroupError> {
|
pub fn set_memory_spread_page(&self, b: bool) -> Result<()> {
|
||||||
self.open_path("cpuset.memory_spread_page", true).and_then(|mut file| {
|
self.open_path("cpuset.memory_spread_page", true)
|
||||||
if b {
|
.and_then(|mut file| {
|
||||||
file.write_all(b"1").map_err(CgroupError::WriteError)
|
if b {
|
||||||
} else {
|
file.write_all(b"1").map_err(|e| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
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("cpuset.memory_spread_page".to_string(), "0".to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Control whether the kernel's slab cache for file I/O should be evenly split across the
|
/// Control whether the kernel's slab cache for file I/O should be evenly split across the
|
||||||
/// nodes selected via `set_mems()`.
|
/// nodes selected via `set_mems()`.
|
||||||
pub fn set_memory_spread_slab(self: &Self, b: bool) -> Result<(), CgroupError> {
|
pub fn set_memory_spread_slab(&self, b: bool) -> Result<()> {
|
||||||
self.open_path("cpuset.memory_spread_slab", true).and_then(|mut file| {
|
self.open_path("cpuset.memory_spread_slab", true)
|
||||||
if b {
|
.and_then(|mut file| {
|
||||||
file.write_all(b"1").map_err(CgroupError::WriteError)
|
if b {
|
||||||
} else {
|
file.write_all(b"1").map_err(|e| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
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("cpuset.memory_spread_slab".to_string(), "0".to_string()),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Control whether the kernel should collect information to calculate memory pressure for
|
/// Control whether the kernel should collect information to calculate memory pressure for
|
||||||
/// control groups.
|
/// control groups.
|
||||||
///
|
///
|
||||||
/// Note: This is a no-operation if the control group referred by `self` is not the root
|
/// Note: This will fail with `InvalidOperation` if the current congrol group is not the root
|
||||||
/// control group.
|
/// control group.
|
||||||
pub fn set_enable_memory_pressure(self: &Self, b: bool) -> Result<(), CgroupError> {
|
pub fn set_enable_memory_pressure(&self, b: bool) -> Result<()> {
|
||||||
/* XXX: this file should only be present in the root cpuset cg */
|
if !self.path_exists("cpuset.memory_pressure_enabled") {
|
||||||
self.open_path("cpuset.memory_pressure_enabled", true).and_then(|mut file| {
|
return Err(Error::new(InvalidOperation));
|
||||||
if b {
|
}
|
||||||
file.write_all(b"1").map_err(CgroupError::WriteError)
|
self.open_path("cpuset.memory_pressure_enabled", true)
|
||||||
} else {
|
.and_then(|mut file| {
|
||||||
file.write_all(b"0").map_err(CgroupError::WriteError)
|
if b {
|
||||||
}
|
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(
|
||||||
|
"cpuset.memory_pressure_enabled".to_string(),
|
||||||
|
"0".to_string(),
|
||||||
|
),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::cpuset;
|
||||||
|
#[test]
|
||||||
|
fn test_parse_range() {
|
||||||
|
let test_cases = vec![
|
||||||
|
"1,2,4-6,9".to_string(),
|
||||||
|
"".to_string(),
|
||||||
|
"1".to_string(),
|
||||||
|
"1-111".to_string(),
|
||||||
|
"1,2,3,4".to_string(),
|
||||||
|
"1-5,6-7,8-9".to_string(),
|
||||||
|
];
|
||||||
|
let expecteds = vec![
|
||||||
|
vec![(1, 1), (2, 2), (4, 6), (9, 9)],
|
||||||
|
vec![],
|
||||||
|
vec![(1, 1)],
|
||||||
|
vec![(1, 111)],
|
||||||
|
vec![(1, 1), (2, 2), (3, 3), (4, 4)],
|
||||||
|
vec![(1, 5), (6, 7), (8, 9)],
|
||||||
|
];
|
||||||
|
|
||||||
|
for (i, case) in test_cases.into_iter().enumerate() {
|
||||||
|
let range = cpuset::parse_range(case.clone());
|
||||||
|
println!("{:?} => {:?}", case, range);
|
||||||
|
assert!(range.is_ok());
|
||||||
|
assert_eq!(range.unwrap(), expecteds[i]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
302
src/devices.rs
302
src/devices.rs
@@ -1,43 +1,182 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `devices` cgroup subsystem.
|
//! This module contains the implementation of the `devices` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/cgroup-v1/devices.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/devices.txt)
|
//! [Documentation/cgroup-v1/devices.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/devices.txt)
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use {CgroupError, DeviceResources, Controllers, Controller, Resources, ControllIdentifier, Subsystem};
|
use log::*;
|
||||||
|
|
||||||
|
use crate::error::ErrorKind::*;
|
||||||
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
ControllIdentifier, ControllerInternal, Controllers, DeviceResource, DeviceResources,
|
||||||
|
Resources, Subsystem,
|
||||||
|
};
|
||||||
|
|
||||||
/// A controller that allows controlling the `devices` subsystem of a Cgroup.
|
/// A controller that allows controlling the `devices` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
/// In essence, using the devices controller, it is possible to allow or disallow sets of devices to
|
/// In essence, using the devices controller, it is possible to allow or disallow sets of devices to
|
||||||
/// be used by the control group's tasks.
|
/// be used by the control group's tasks.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct DevicesController{
|
pub struct DevicesController {
|
||||||
base: PathBuf,
|
base: PathBuf,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for DevicesController {
|
/// An enum holding the different types of devices that can be manipulated using this controller.
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::Devices }
|
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
#[cfg_attr(
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
feature = "serde",
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
derive(serde::Serialize, serde::Deserialize),
|
||||||
|
serde(rename_all = "snake_case")
|
||||||
|
)]
|
||||||
|
pub enum DeviceType {
|
||||||
|
/// The rule applies to all devices.
|
||||||
|
All,
|
||||||
|
/// The rule only applies to character devices.
|
||||||
|
Char,
|
||||||
|
/// The rule only applies to block devices.
|
||||||
|
Block,
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, res: &Resources) {
|
impl Default for DeviceType {
|
||||||
/* get the resources that apply to this controller */
|
fn default() -> Self {
|
||||||
let res: &DeviceResources = &res.devices;
|
DeviceType::All
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if res.update_values {
|
impl DeviceType {
|
||||||
for i in &res.devices {
|
/// Convert a DeviceType into the character that the kernel recognizes.
|
||||||
let wstr = format!("{} {}:{} {}",
|
#[allow(clippy::should_implement_trait, clippy::wrong_self_convention)]
|
||||||
i.devtype, i.major, i.minor, i.access);
|
pub fn to_char(&self) -> char {
|
||||||
if i.allow {
|
match self {
|
||||||
let _ = self.allow_device(&wstr);
|
DeviceType::All => 'a',
|
||||||
} else {
|
DeviceType::Char => 'c',
|
||||||
let _ = self.deny_device(&wstr);
|
DeviceType::Block => 'b',
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert the kenrel's representation into the DeviceType type.
|
||||||
|
pub fn from_char(c: Option<char>) -> Option<DeviceType> {
|
||||||
|
match c {
|
||||||
|
Some('a') => Some(DeviceType::All),
|
||||||
|
Some('c') => Some(DeviceType::Char),
|
||||||
|
Some('b') => Some(DeviceType::Block),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
/// Permission to write to the device.
|
||||||
|
Write,
|
||||||
|
/// Permission to execute the `mknod(2)` system call with the device's major and minor numbers.
|
||||||
|
/// That is, the permission to create a special file that refers to the device node.
|
||||||
|
MkNod,
|
||||||
|
}
|
||||||
|
|
||||||
|
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',
|
||||||
|
DevicePermissions::Write => 'w',
|
||||||
|
DevicePermissions::MkNod => 'm',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert a char to a DevicePermission if there is such a mapping.
|
||||||
|
pub fn from_char(c: char) -> Option<DevicePermissions> {
|
||||||
|
match c {
|
||||||
|
'r' => Some(DevicePermissions::Read),
|
||||||
|
'w' => Some(DevicePermissions::Write),
|
||||||
|
'm' => Some(DevicePermissions::MkNod),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks whether the string is a valid descriptor of DevicePermissions.
|
||||||
|
pub fn is_valid(s: &str) -> bool {
|
||||||
|
if s.is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for i in s.chars() {
|
||||||
|
if i != 'r' && i != 'w' && i != 'm' {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a Vec will all the permissions that a device can have.
|
||||||
|
pub fn all() -> Vec<DevicePermissions> {
|
||||||
|
vec![
|
||||||
|
DevicePermissions::Read,
|
||||||
|
DevicePermissions::Write,
|
||||||
|
DevicePermissions::MkNod,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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.is_empty() {
|
||||||
|
return Ok(v);
|
||||||
|
}
|
||||||
|
for e in s.chars() {
|
||||||
|
let perm = DevicePermissions::from_char(e).ok_or_else(|| Error::new(ParseError))?;
|
||||||
|
v.push(perm);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ControllerInternal for DevicesController {
|
||||||
|
fn control_type(&self) -> Controllers {
|
||||||
|
Controllers::Devices
|
||||||
|
}
|
||||||
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(&self, res: &Resources) -> Result<()> {
|
||||||
|
// get the resources that apply to this controller
|
||||||
|
let res: &DeviceResources = &res.devices;
|
||||||
|
|
||||||
|
for i in &res.devices {
|
||||||
|
if i.allow {
|
||||||
|
let _ = self.allow_device(i.devtype, i.major, i.minor, &i.access);
|
||||||
|
} else {
|
||||||
|
let _ = self.deny_device(i.devtype, i.major, i.minor, &i.access);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,18 +193,17 @@ impl<'a> From<&'a Subsystem> for &'a DevicesController {
|
|||||||
Subsystem::Devices(c) => c,
|
Subsystem::Devices(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DevicesController {
|
impl DevicesController {
|
||||||
/// Constructs a new `DevicesController` with `oroot` serving as the root of the control group.
|
/// Constructs a new `DevicesController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
@@ -74,42 +212,112 @@ impl DevicesController {
|
|||||||
|
|
||||||
/// Allow a (possibly, set of) device(s) to be used by the tasks in the control group.
|
/// Allow a (possibly, set of) device(s) to be used by the tasks in the control group.
|
||||||
///
|
///
|
||||||
/// The format of `dev` is rather simple:
|
/// When `-1` is passed as `major` or `minor`, the kernel interprets that value as "any",
|
||||||
/// `$type $major:$minor $rwm`
|
/// meaning that it will match any device.
|
||||||
/// where `$rwm` is a combination of the characters `r`, `w`, `m`, each standing for read,
|
pub fn allow_device(
|
||||||
/// write, mknod permissions.
|
&self,
|
||||||
///
|
devtype: DeviceType,
|
||||||
/// Note that `dev` can be "regex"-like: both `$major` and `$minor` can be `*` which implies
|
major: i64,
|
||||||
/// that their value does not matter.
|
minor: i64,
|
||||||
pub fn allow_device(self: &Self, dev: &String) -> Result<(), CgroupError> {
|
perm: &[DevicePermissions],
|
||||||
|
) -> Result<()> {
|
||||||
|
let perms = perm
|
||||||
|
.iter()
|
||||||
|
.map(DevicePermissions::to_char)
|
||||||
|
.collect::<String>();
|
||||||
|
let minor = if minor == -1 {
|
||||||
|
"*".to_string()
|
||||||
|
} else {
|
||||||
|
format!("{}", minor)
|
||||||
|
};
|
||||||
|
let major = if major == -1 {
|
||||||
|
"*".to_string()
|
||||||
|
} else {
|
||||||
|
format!("{}", major)
|
||||||
|
};
|
||||||
|
let final_str = format!("{} {}:{} {}", devtype.to_char(), major, minor, perms);
|
||||||
self.open_path("devices.allow", true).and_then(|mut file| {
|
self.open_path("devices.allow", true).and_then(|mut file| {
|
||||||
file.write_all(dev.as_ref()).map_err(CgroupError::WriteError)
|
file.write_all(final_str.as_ref()).map_err(|e| {
|
||||||
|
Error::with_cause(WriteFailed("devices.allow".to_string(), final_str), e)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deny the control group's tasks access to the devices covered by `dev`.
|
/// Deny the control group's tasks access to the devices covered by `dev`.
|
||||||
///
|
///
|
||||||
/// The format of `dev` is rather simple:
|
/// When `-1` is passed as `major` or `minor`, the kernel interprets that value as "any",
|
||||||
/// `$type $major:$minor $rwm`
|
/// meaning that it will match any device.
|
||||||
/// where `$rwm` is a combination of the characters `r`, `w`, `m`, each standing for read,
|
pub fn deny_device(
|
||||||
/// write, mknod permissions.
|
&self,
|
||||||
///
|
devtype: DeviceType,
|
||||||
/// Note that `dev` can be "regex"-like: both `$major` and `$minor` can be `*` which implies
|
major: i64,
|
||||||
/// that their value does not matter.
|
minor: i64,
|
||||||
pub fn deny_device(self: &Self, dev: &String) -> Result<(), CgroupError> {
|
perm: &[DevicePermissions],
|
||||||
|
) -> Result<()> {
|
||||||
|
let perms = perm
|
||||||
|
.iter()
|
||||||
|
.map(DevicePermissions::to_char)
|
||||||
|
.collect::<String>();
|
||||||
|
let minor = if minor == -1 {
|
||||||
|
"*".to_string()
|
||||||
|
} else {
|
||||||
|
format!("{}", minor)
|
||||||
|
};
|
||||||
|
let major = if major == -1 {
|
||||||
|
"*".to_string()
|
||||||
|
} else {
|
||||||
|
format!("{}", major)
|
||||||
|
};
|
||||||
|
let final_str = format!("{} {}:{} {}", devtype.to_char(), major, minor, perms);
|
||||||
self.open_path("devices.deny", true).and_then(|mut file| {
|
self.open_path("devices.deny", true).and_then(|mut file| {
|
||||||
file.write_all(dev.as_ref()).map_err(CgroupError::WriteError)
|
file.write_all(final_str.as_ref()).map_err(|e| {
|
||||||
|
Error::with_cause(WriteFailed("devices.deny".to_string(), final_str), e)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the current list of allowed devices.
|
/// Get the current list of allowed devices.
|
||||||
pub fn allowed_devices(self: &Self) -> Result<String, CgroupError> {
|
pub fn allowed_devices(&self) -> Result<Vec<DeviceResource>> {
|
||||||
self.open_path("devices.list", false).and_then(|mut file| {
|
self.open_path("devices.list", false).and_then(|mut file| {
|
||||||
let mut s = String::new();
|
let mut s = String::new();
|
||||||
let res = file.read_to_string(&mut s);
|
let res = file.read_to_string(&mut s);
|
||||||
match res {
|
match res {
|
||||||
Ok(_) => Ok(s),
|
Ok(_) => {
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
s.lines().fold(Ok(Vec::new()), |acc, line| {
|
||||||
|
let ls = line.to_string().split(|c| c == ' ' || c == ':').map(|x| x.to_string()).collect::<Vec<String>>();
|
||||||
|
if acc.is_err() || ls.len() != 4 {
|
||||||
|
error!("allowed_devices: acc: {:?}, ls: {:?}", acc, ls);
|
||||||
|
Err(Error::new(ParseError))
|
||||||
|
} else {
|
||||||
|
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] == "*" {
|
||||||
|
major = Ok(-1);
|
||||||
|
}
|
||||||
|
if minor.is_err() && ls[2] == "*" {
|
||||||
|
minor = Ok(-1);
|
||||||
|
}
|
||||||
|
if devtype.is_none() || major.is_err() || minor.is_err() || !DevicePermissions::is_valid(&ls[3]) {
|
||||||
|
error!("allowed_devices: acc: {:?}, ls: {:?}, devtype: {:?}, major {:?} minor {:?} ls3 {:?}",
|
||||||
|
acc, ls, devtype, major, minor, &ls[3]);
|
||||||
|
Err(Error::new(ParseError))
|
||||||
|
} else {
|
||||||
|
let access = DevicePermissions::from_str(&ls[3])?;
|
||||||
|
let mut acc = acc.unwrap();
|
||||||
|
acc.push(DeviceResource {
|
||||||
|
allow: true,
|
||||||
|
devtype: devtype.unwrap(),
|
||||||
|
major: major.unwrap(),
|
||||||
|
minor: minor.unwrap(),
|
||||||
|
access,
|
||||||
|
});
|
||||||
|
Ok(acc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
Err(e) => Err(Error::with_cause(ReadFailed("devices.list".to_string()), e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
111
src/error.rs
Normal file
111
src/error.rs
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
use std::error::Error as StdError;
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
/// The different types of errors that can occur while manipulating control groups.
|
||||||
|
#[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.
|
||||||
|
#[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.
|
||||||
|
#[error("unable to read a control group file {0}")]
|
||||||
|
ReadFailed(String),
|
||||||
|
|
||||||
|
/// An error occured while trying to remove a control group.
|
||||||
|
#[error("unable to remove a control group")]
|
||||||
|
RemoveFailed,
|
||||||
|
|
||||||
|
/// An error occured while trying to parse a value from a control group file.
|
||||||
|
///
|
||||||
|
/// In the future, there will be some information attached to this field.
|
||||||
|
#[error("unable to parse control group file")]
|
||||||
|
ParseError,
|
||||||
|
|
||||||
|
/// You tried to do something invalid.
|
||||||
|
///
|
||||||
|
/// This could be because you tried to set a value in a control group that is not a root
|
||||||
|
/// control group. Or, when using unified hierarchy, you tried to add a task in a leaf node.
|
||||||
|
#[error("the requested operation is invalid")]
|
||||||
|
InvalidOperation,
|
||||||
|
|
||||||
|
/// The path of the control group was invalid.
|
||||||
|
///
|
||||||
|
/// This could be caused by trying to escape the control group filesystem via a string of "..".
|
||||||
|
/// This crate checks against this and operations will fail with this error.
|
||||||
|
#[error("the given path is invalid")]
|
||||||
|
InvalidPath,
|
||||||
|
|
||||||
|
#[error("invalid bytes size")]
|
||||||
|
InvalidBytesSize,
|
||||||
|
|
||||||
|
/// An unknown error has occured.
|
||||||
|
#[error("an unknown error")]
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Error {
|
||||||
|
kind: ErrorKind,
|
||||||
|
cause: Option<Box<dyn StdError + Send + Sync>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Error {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
if let Some(cause) = &self.cause {
|
||||||
|
write!(f, "{} caused by: {:?}", &self.kind, cause)
|
||||||
|
} else {
|
||||||
|
write!(f, "{}", &self.kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StdError for Error {
|
||||||
|
fn cause(&self) -> Option<&dyn StdError> {
|
||||||
|
#[allow(clippy::manual_map)]
|
||||||
|
match self.cause {
|
||||||
|
Some(ref x) => Some(&**x),
|
||||||
|
None => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
pub(crate) fn from_string(s: String) -> Self {
|
||||||
|
Self {
|
||||||
|
kind: ErrorKind::Common(s),
|
||||||
|
cause: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub(crate) fn new(kind: ErrorKind) -> Self {
|
||||||
|
Self { kind, cause: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn with_cause<E>(kind: ErrorKind, cause: E) -> Self
|
||||||
|
where
|
||||||
|
E: 'static + Send + Sync + StdError,
|
||||||
|
{
|
||||||
|
Self {
|
||||||
|
kind,
|
||||||
|
cause: Some(Box::new(cause)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kind(&self) -> &ErrorKind {
|
||||||
|
&self.kind
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Result<T> = ::std::result::Result<T, Error>;
|
||||||
92
src/events.rs
Normal file
92
src/events.rs
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
use eventfd::{eventfd, EfdFlags};
|
||||||
|
use nix::sys::eventfd;
|
||||||
|
use std::fs::{self, File};
|
||||||
|
use std::io::Read;
|
||||||
|
use std::os::unix::io::{AsRawFd, FromRawFd};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::mpsc::{self, Receiver};
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
use crate::error::ErrorKind::*;
|
||||||
|
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: &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: &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: &Path, level: &str) -> Result<Receiver<String>> {
|
||||||
|
if level != "low" && level != "medium" && level != "critical" {
|
||||||
|
return Err(Error::from_string(format!(
|
||||||
|
"invalid pressure level {}",
|
||||||
|
level
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
register_memory_event(key, dir, "memory.pressure_level", level)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn register_memory_event(
|
||||||
|
key: &str,
|
||||||
|
cg_dir: &Path,
|
||||||
|
event_name: &str,
|
||||||
|
arg: &str,
|
||||||
|
) -> Result<Receiver<String>> {
|
||||||
|
let path = cg_dir.join(event_name);
|
||||||
|
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("eventfd".to_string()), e))?;
|
||||||
|
|
||||||
|
let event_control_path = cg_dir.join("cgroup.event_control");
|
||||||
|
let data = if arg.is_empty() {
|
||||||
|
format!("{} {}", eventfd, event_file.as_raw_fd())
|
||||||
|
} else {
|
||||||
|
format!("{} {} {}", eventfd, event_file.as_raw_fd(), arg)
|
||||||
|
};
|
||||||
|
|
||||||
|
// write to file and set mode to 0700(FIXME)
|
||||||
|
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) };
|
||||||
|
|
||||||
|
let (sender, receiver) = mpsc::channel();
|
||||||
|
let key = key.to_string();
|
||||||
|
|
||||||
|
thread::spawn(move || {
|
||||||
|
loop {
|
||||||
|
let mut buf = [0; 8];
|
||||||
|
if eventfd_file.read(&mut buf).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// When a cgroup is destroyed, an event is sent to eventfd.
|
||||||
|
// So if the control path is gone, return instead of notifying.
|
||||||
|
if !Path::new(&event_control_path).exists() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sender.send(key.clone()).unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(receiver)
|
||||||
|
}
|
||||||
@@ -1,11 +1,20 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `freezer` cgroup subsystem.
|
//! This module contains the implementation of the `freezer` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/cgroup-v1/freezer-subsystem.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/freezer-subsystem.txt)
|
//! [Documentation/cgroup-v1/freezer-subsystem.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/freezer-subsystem.txt)
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use {CgroupError, Controllers, Controller, Resources, ControllIdentifier, Subsystem};
|
use crate::error::ErrorKind::*;
|
||||||
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};
|
||||||
|
|
||||||
/// A controller that allows controlling the `freezer` subsystem of a Cgroup.
|
/// A controller that allows controlling the `freezer` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -16,12 +25,14 @@ use {CgroupError, Controllers, Controller, Resources, ControllIdentifier, Subsys
|
|||||||
/// Note that if the control group is currently in the `Frozen` or `Freezing` state, then no
|
/// Note that if the control group is currently in the `Frozen` or `Freezing` state, then no
|
||||||
/// processes can be added to it.
|
/// processes can be added to it.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct FreezerController{
|
pub struct FreezerController {
|
||||||
base: PathBuf,
|
base: PathBuf,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
v2: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The current state of the control group
|
/// The current state of the control group
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
pub enum FreezerState {
|
pub enum FreezerState {
|
||||||
/// The processes in the control group are _not_ frozen.
|
/// The processes in the control group are _not_ frozen.
|
||||||
Thawed,
|
Thawed,
|
||||||
@@ -31,13 +42,22 @@ pub enum FreezerState {
|
|||||||
Frozen,
|
Frozen,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for FreezerController {
|
impl ControllerInternal for FreezerController {
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::Freezer }
|
fn control_type(&self) -> Controllers {
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
Controllers::Freezer
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
}
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, _res: &Resources) {
|
fn apply(&self, _res: &Resources) -> Result<()> {
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,51 +74,72 @@ impl<'a> From<&'a Subsystem> for &'a FreezerController {
|
|||||||
Subsystem::Freezer(c) => c,
|
Subsystem::Freezer(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FreezerController {
|
impl FreezerController {
|
||||||
/// Contructs a new `FreezerController` with `oroot` serving as the root of the control group.
|
/// Contructs a new `FreezerController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf, v2: bool) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
|
v2,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Freezes the processes in the control group.
|
/// Freezes the processes in the control group.
|
||||||
pub fn freeze(self: &Self) -> Result<(), CgroupError> {
|
pub fn freeze(&self) -> Result<()> {
|
||||||
self.open_path("freezer.state", true).and_then(|mut file| {
|
let mut file_name = "freezer.state";
|
||||||
file.write_all("FROZEN".to_string().as_ref()).map_err(CgroupError::WriteError)
|
let mut content = "FROZEN".to_string();
|
||||||
|
if self.v2 {
|
||||||
|
file_name = "cgroup.freeze";
|
||||||
|
content = "1".to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
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), e))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Thaws, that is, unfreezes the processes in the control group.
|
/// Thaws, that is, unfreezes the processes in the control group.
|
||||||
pub fn thaw(self: &Self) -> Result<(), CgroupError> {
|
pub fn thaw(&self) -> Result<()> {
|
||||||
self.open_path("freezer.state", true).and_then(|mut file| {
|
let mut file_name = "freezer.state";
|
||||||
file.write_all("THAWED".to_string().as_ref()).map_err(CgroupError::WriteError)
|
let mut content = "THAWED".to_string();
|
||||||
|
if self.v2 {
|
||||||
|
file_name = "cgroup.freeze";
|
||||||
|
content = "0".to_string();
|
||||||
|
}
|
||||||
|
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), e))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Retrieve the state of processes in the control group.
|
/// Retrieve the state of processes in the control group.
|
||||||
pub fn state(self: &Self) -> Result<FreezerState, CgroupError> {
|
pub fn state(&self) -> Result<FreezerState> {
|
||||||
self.open_path("freezer.state", false).and_then(|mut file| {
|
let mut file_name = "freezer.state";
|
||||||
|
if self.v2 {
|
||||||
|
file_name = "cgroup.freeze";
|
||||||
|
}
|
||||||
|
self.open_path(file_name, false).and_then(|mut file| {
|
||||||
let mut s = String::new();
|
let mut s = String::new();
|
||||||
let res = file.read_to_string(&mut s);
|
let res = file.read_to_string(&mut s);
|
||||||
match res {
|
match res {
|
||||||
Ok(_) => match s.as_ref() {
|
Ok(_) => match s.trim() {
|
||||||
"FROZEN" => Ok(FreezerState::Frozen),
|
"FROZEN" => Ok(FreezerState::Frozen),
|
||||||
"THAWED" => Ok(FreezerState::Thawed),
|
"THAWED" => Ok(FreezerState::Thawed),
|
||||||
|
"1" => Ok(FreezerState::Frozen),
|
||||||
|
"0" => Ok(FreezerState::Thawed),
|
||||||
"FREEZING" => Ok(FreezerState::Freezing),
|
"FREEZING" => Ok(FreezerState::Freezing),
|
||||||
_ => Err(CgroupError::ParseError),
|
_ => Err(Error::new(ParseError)),
|
||||||
},
|
},
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
Err(e) => Err(Error::with_cause(ReadFailed(file_name.to_string()), e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,137 +1,378 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module represents the various control group hierarchies the Linux kernel supports.
|
//! This module represents the various control group hierarchies the Linux kernel supports.
|
||||||
//!
|
//!
|
||||||
//! Currently, we only support the cgroupv1 hierarchy, but in the future we will add support for
|
//! Currently, we only support the cgroupv1 hierarchy, but in the future we will add support for
|
||||||
//! the Unified Hierarchy.
|
//! the Unified Hierarchy.
|
||||||
|
|
||||||
use std::io::BufRead;
|
use std::fs;
|
||||||
use std::io::BufReader;
|
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::path::{Path, PathBuf};
|
use std::io::{BufRead, BufReader};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use {Controllers, Hierarchy, Subsystem};
|
use crate::blkio::BlkIoController;
|
||||||
use ::pid::PidController;
|
use crate::cpu::CpuController;
|
||||||
use ::memory::MemController;
|
use crate::cpuacct::CpuAcctController;
|
||||||
use ::cpuset::CpuSetController;
|
use crate::cpuset::CpuSetController;
|
||||||
use ::cpuacct::CpuAcctController;
|
use crate::devices::DevicesController;
|
||||||
use ::cpu::CpuController;
|
use crate::freezer::FreezerController;
|
||||||
use ::freezer::FreezerController;
|
use crate::hugetlb::HugeTlbController;
|
||||||
use ::devices::DevicesController;
|
use crate::memory::MemController;
|
||||||
use ::net_cls::NetClsController;
|
use crate::net_cls::NetClsController;
|
||||||
use ::blkio::BlkIoController;
|
use crate::net_prio::NetPrioController;
|
||||||
use ::perf_event::PerfEventController;
|
use crate::perf_event::PerfEventController;
|
||||||
use ::net_prio::NetPrioController;
|
use crate::pid::PidController;
|
||||||
use ::hugetlb::HugeTlbController;
|
use crate::rdma::RdmaController;
|
||||||
use ::rdma::RdmaController;
|
use crate::systemd::SystemdController;
|
||||||
|
use crate::{Controllers, Hierarchy, Subsystem};
|
||||||
|
|
||||||
use ::cgroup::Cgroup;
|
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".
|
/// The standard, original cgroup implementation. Often referred to as "cgroupv1".
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
pub struct V1 {
|
pub struct V1 {
|
||||||
mount_point: String,
|
mountinfo: Vec<Mountinfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct V2 {
|
||||||
|
root: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Hierarchy for V1 {
|
impl Hierarchy for V1 {
|
||||||
fn subsystems(self: &Self) -> Vec<Subsystem> {
|
fn v2(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subsystems(&self) -> Vec<Subsystem> {
|
||||||
let mut subs = vec![];
|
let mut subs = vec![];
|
||||||
if self.check_support(Controllers::Pids) {
|
|
||||||
subs.push(Subsystem::Pid(PidController::new(self.root())));
|
// The cgroup writeback feature requires cooperation between memcgs and blkcgs
|
||||||
|
// To avoid exceptions, we should add_task for blkcg before memcg(push BlkIo before Mem)
|
||||||
|
// For more Information: https://www.alibabacloud.com/help/doc-detail/155509.htm
|
||||||
|
if let Some(root) = self.get_mount_point(Controllers::BlkIo) {
|
||||||
|
subs.push(Subsystem::BlkIo(BlkIoController::new(root, false)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::Mem) {
|
if let Some(root) = self.get_mount_point(Controllers::Mem) {
|
||||||
subs.push(Subsystem::Mem(MemController::new(self.root())));
|
subs.push(Subsystem::Mem(MemController::new(root, false)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::CpuSet) {
|
if let Some(root) = self.get_mount_point(Controllers::Pids) {
|
||||||
subs.push(Subsystem::CpuSet(CpuSetController::new(self.root())));
|
subs.push(Subsystem::Pid(PidController::new(root, false)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::CpuAcct) {
|
if let Some(root) = self.get_mount_point(Controllers::CpuSet) {
|
||||||
subs.push(Subsystem::CpuAcct(CpuAcctController::new(self.root())));
|
subs.push(Subsystem::CpuSet(CpuSetController::new(root, false)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::Cpu) {
|
if let Some(root) = self.get_mount_point(Controllers::CpuAcct) {
|
||||||
subs.push(Subsystem::Cpu(CpuController::new(self.root())));
|
subs.push(Subsystem::CpuAcct(CpuAcctController::new(root)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::Devices) {
|
if let Some(root) = self.get_mount_point(Controllers::Cpu) {
|
||||||
subs.push(Subsystem::Devices(DevicesController::new(self.root())));
|
subs.push(Subsystem::Cpu(CpuController::new(root, false)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::Freezer) {
|
if let Some(root) = self.get_mount_point(Controllers::Devices) {
|
||||||
subs.push(Subsystem::Freezer(FreezerController::new(self.root())));
|
subs.push(Subsystem::Devices(DevicesController::new(root)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::NetCls) {
|
if let Some(root) = self.get_mount_point(Controllers::Freezer) {
|
||||||
subs.push(Subsystem::NetCls(NetClsController::new(self.root())));
|
subs.push(Subsystem::Freezer(FreezerController::new(root, false)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::BlkIo) {
|
if let Some(root) = self.get_mount_point(Controllers::NetCls) {
|
||||||
subs.push(Subsystem::BlkIo(BlkIoController::new(self.root())));
|
subs.push(Subsystem::NetCls(NetClsController::new(root)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::PerfEvent) {
|
if let Some(root) = self.get_mount_point(Controllers::PerfEvent) {
|
||||||
subs.push(Subsystem::PerfEvent(PerfEventController::new(self.root())));
|
subs.push(Subsystem::PerfEvent(PerfEventController::new(root)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::NetPrio) {
|
if let Some(root) = self.get_mount_point(Controllers::NetPrio) {
|
||||||
subs.push(Subsystem::NetPrio(NetPrioController::new(self.root())));
|
subs.push(Subsystem::NetPrio(NetPrioController::new(root)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::HugeTlb) {
|
if let Some(root) = self.get_mount_point(Controllers::HugeTlb) {
|
||||||
subs.push(Subsystem::HugeTlb(HugeTlbController::new(self.root())));
|
subs.push(Subsystem::HugeTlb(HugeTlbController::new(root, false)));
|
||||||
}
|
}
|
||||||
if self.check_support(Controllers::Rdma) {
|
if let Some(root) = self.get_mount_point(Controllers::Rdma) {
|
||||||
subs.push(Subsystem::Rdma(RdmaController::new(self.root())));
|
subs.push(Subsystem::Rdma(RdmaController::new(root)));
|
||||||
|
}
|
||||||
|
if let Some(root) = self.get_mount_point(Controllers::Systemd) {
|
||||||
|
subs.push(Subsystem::Systemd(SystemdController::new(root, false)));
|
||||||
}
|
}
|
||||||
|
|
||||||
subs
|
subs
|
||||||
}
|
}
|
||||||
|
|
||||||
fn root_control_group(self: &Self) -> Cgroup {
|
fn root_control_group(&self) -> Cgroup {
|
||||||
Cgroup::load(self, "".to_string())
|
Cgroup::load(auto(), "")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_support(self: &Self, sub: Controllers) -> bool {
|
fn root(&self) -> PathBuf {
|
||||||
let root = self.root().read_dir().unwrap();
|
self.mountinfo
|
||||||
for entry in root {
|
.iter()
|
||||||
if let Ok(entry) = entry {
|
.find_map(|m| {
|
||||||
if entry.file_name().into_string().unwrap() == sub.to_string() {
|
if m.fs_type.0 == "cgroup" {
|
||||||
return true;
|
return Some(m.mount_point.parent().unwrap());
|
||||||
}
|
}
|
||||||
|
None
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
.to_path_buf()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Hierarchy for V2 {
|
||||||
|
fn v2(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subsystems(&self) -> Vec<Subsystem> {
|
||||||
|
let p = format!("{}/{}", UNIFIED_MOUNTPOINT, "cgroup.controllers");
|
||||||
|
let ret = fs::read_to_string(p.as_str());
|
||||||
|
if ret.is_err() {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut subs = vec![];
|
||||||
|
|
||||||
|
let controllers = ret.unwrap().trim().to_string();
|
||||||
|
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 {
|
||||||
|
"cpu" => {
|
||||||
|
subs.push(Subsystem::Cpu(CpuController::new(self.root(), true)));
|
||||||
|
}
|
||||||
|
"io" => {
|
||||||
|
subs.push(Subsystem::BlkIo(BlkIoController::new(self.root(), true)));
|
||||||
|
}
|
||||||
|
"cpuset" => {
|
||||||
|
subs.push(Subsystem::CpuSet(CpuSetController::new(self.root(), true)));
|
||||||
|
}
|
||||||
|
"memory" => {
|
||||||
|
subs.push(Subsystem::Mem(MemController::new(self.root(), true)));
|
||||||
|
}
|
||||||
|
"pids" => {
|
||||||
|
subs.push(Subsystem::Pid(PidController::new(self.root(), true)));
|
||||||
|
}
|
||||||
|
"freezer" => {
|
||||||
|
subs.push(Subsystem::Freezer(FreezerController::new(
|
||||||
|
self.root(),
|
||||||
|
true,
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
"hugetlb" => {
|
||||||
|
subs.push(Subsystem::HugeTlb(HugeTlbController::new(
|
||||||
|
self.root(),
|
||||||
|
true,
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
|
||||||
|
subs
|
||||||
}
|
}
|
||||||
|
|
||||||
fn root(self: &Self) -> PathBuf {
|
fn root_control_group(&self) -> Cgroup {
|
||||||
PathBuf::from(self.mount_point.clone())
|
Cgroup::load(auto(), "")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root(&self) -> PathBuf {
|
||||||
|
PathBuf::from(self.root.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl V1 {
|
impl V1 {
|
||||||
/// Finds where control groups are mounted to and returns a hierarchy in which control groups
|
/// Finds where control groups are mounted to and returns a hierarchy in which control groups
|
||||||
/// can be created.
|
/// can be created.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> V1 {
|
||||||
let mount_point = find_v1_mount().unwrap();
|
|
||||||
V1 {
|
V1 {
|
||||||
mount_point: mount_point,
|
mountinfo: mountinfo_self(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mount_point(&self, controller: Controllers) -> Option<PathBuf> {
|
||||||
|
self.mountinfo.iter().find_map(|m| {
|
||||||
|
if m.fs_type.0 == "cgroup" && m.super_opts.contains(&controller.to_string()) {
|
||||||
|
return Some(m.mount_point.clone());
|
||||||
|
}
|
||||||
|
None
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
||||||
|
pub fn new() -> V2 {
|
||||||
|
V2 {
|
||||||
|
root: String::from(UNIFIED_MOUNTPOINT),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_v1_mount() -> Option<String> {
|
impl Default for V2 {
|
||||||
/* Open mountinfo so we can get a parseable mount list */
|
fn default() -> Self {
|
||||||
let mountinfo_path = Path::new("/proc/self/mountinfo");
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* If /proc isn't mounted, or something else happens, then bail out */
|
pub const UNIFIED_MOUNTPOINT: &str = "/sys/fs/cgroup";
|
||||||
if mountinfo_path.exists() == false {
|
|
||||||
return None;
|
#[cfg(any(
|
||||||
|
all(target_os = "linux", not(target_env = "musl")),
|
||||||
|
target_os = "android"
|
||||||
|
))]
|
||||||
|
pub fn is_cgroup2_unified_mode() -> bool {
|
||||||
|
use nix::sys::statfs;
|
||||||
|
|
||||||
|
let path = std::path::Path::new(UNIFIED_MOUNTPOINT);
|
||||||
|
let fs_stat = statfs::statfs(path);
|
||||||
|
if fs_stat.is_err() {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mountinfo_file = File::open(mountinfo_path).unwrap();
|
// FIXME notwork, nix will not compile CGROUP2_SUPER_MAGIC because not(target_env = "musl")
|
||||||
let mountinfo_reader = BufReader::new(&mountinfo_file);
|
fs_stat.unwrap().filesystem_type() == statfs::CGROUP2_SUPER_MAGIC
|
||||||
for _line in mountinfo_reader.lines() {
|
}
|
||||||
let line = _line.unwrap();
|
|
||||||
let mut fields = line.split_whitespace();
|
pub const INIT_CGROUP_PATHS: &str = "/proc/1/cgroup";
|
||||||
let index = line.find(" - ").unwrap();
|
|
||||||
let mut more_fields = line[index + 3..].split_whitespace().collect::<Vec<_>>();
|
#[cfg(all(target_os = "linux", target_env = "musl"))]
|
||||||
let fstype = more_fields[0];
|
pub fn is_cgroup2_unified_mode() -> bool {
|
||||||
if fstype == "tmpfs" && more_fields[2].contains("ro") {
|
let lines = fs::read_to_string(INIT_CGROUP_PATHS);
|
||||||
let cgroups_mount = fields.nth(4).unwrap();
|
if lines.is_err() {
|
||||||
println!("found cgroups at {:?}", cgroups_mount);
|
return false;
|
||||||
return Some(cgroups_mount.to_string());
|
}
|
||||||
|
|
||||||
|
for line in lines.unwrap().lines() {
|
||||||
|
let fields: Vec<&str> = line.split(':').collect();
|
||||||
|
if fields.len() != 3 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if fields[0] != "0" {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn auto() -> Box<dyn Hierarchy> {
|
||||||
|
if is_cgroup2_unified_mode() {
|
||||||
|
Box::new(V2::new())
|
||||||
|
} else {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
269
src/hugetlb.rs
269
src/hugetlb.rs
@@ -1,14 +1,24 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `hugetlb` cgroup subsystem.
|
//! This module contains the implementation of the `hugetlb` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! 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)
|
//! [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;
|
use std::path::PathBuf;
|
||||||
use std::fs::File;
|
|
||||||
use std::io::{Write, Read};
|
|
||||||
|
|
||||||
use {CgroupError, HugePageResources, Controllers, Controller, Resources, ControllIdentifier, Subsystem};
|
use crate::error::ErrorKind::*;
|
||||||
use CgroupError::*;
|
use crate::error::*;
|
||||||
|
use crate::{flat_keyed_to_vec, read_u64_from};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
ControllIdentifier, ControllerInternal, Controllers, HugePageResources, Resources, Subsystem,
|
||||||
|
};
|
||||||
|
|
||||||
/// A controller that allows controlling the `hugetlb` subsystem of a Cgroup.
|
/// A controller that allows controlling the `hugetlb` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -18,23 +28,40 @@ use CgroupError::*;
|
|||||||
pub struct HugeTlbController {
|
pub struct HugeTlbController {
|
||||||
base: PathBuf,
|
base: PathBuf,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
sizes: Vec<String>,
|
||||||
|
v2: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for HugeTlbController {
|
impl ControllerInternal for HugeTlbController {
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::HugeTlb }
|
fn control_type(&self) -> Controllers {
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
Controllers::HugeTlb
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
}
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, res: &Resources) {
|
fn is_v2(&self) -> bool {
|
||||||
/* get the resources that apply to this controller */
|
self.v2
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(&self, res: &Resources) -> Result<()> {
|
||||||
|
// get the resources that apply to this controller
|
||||||
let res: &HugePageResources = &res.hugepages;
|
let res: &HugePageResources = &res.hugepages;
|
||||||
|
|
||||||
if res.update_values {
|
for i in &res.limits {
|
||||||
for i in &res.limits {
|
let _ = self.set_limit_in_bytes(&i.size, i.limit);
|
||||||
let _ = self.set_limit_in_bytes(&i.size, i.limit);
|
if self.limit_in_bytes(&i.size)? != i.limit {
|
||||||
|
return Err(Error::new(Other));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,71 +78,227 @@ impl<'a> From<&'a Subsystem> for &'a HugeTlbController {
|
|||||||
Subsystem::HugeTlb(c) => c,
|
Subsystem::HugeTlb(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_u64_from(mut file: File) -> Result<u64, CgroupError> {
|
|
||||||
let mut string = String::new();
|
|
||||||
match file.read_to_string(&mut string) {
|
|
||||||
Ok(_) => string.trim().parse().map_err(|_| ParseError),
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HugeTlbController {
|
impl HugeTlbController {
|
||||||
/// Constructs a new `HugeTlbController` with `oroot` serving as the root of the control group.
|
/// Constructs a new `HugeTlbController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf, v2: bool) -> Self {
|
||||||
let mut root = oroot;
|
let sizes = get_hugepage_sizes();
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
|
sizes,
|
||||||
|
v2,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the system supports `hugetlb_size` hugepages.
|
/// Whether the system supports `hugetlb_size` hugepages.
|
||||||
pub fn size_supported(self: &Self, _hugetlb_size: String) -> bool {
|
pub fn size_supported(&self, hugetlb_size: &str) -> bool {
|
||||||
/* TODO */
|
for s in &self.sizes {
|
||||||
true
|
if s == hugetlb_size {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_sizes(&self) -> Vec<String> {
|
||||||
|
self.sizes.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failcnt_v2(&self, hugetlb_size: &str) -> Result<u64> {
|
||||||
|
self.open_path(&format!("hugetlb.{}.events", hugetlb_size), false)
|
||||||
|
.and_then(flat_keyed_to_vec)
|
||||||
|
.and_then(|x| {
|
||||||
|
if x.is_empty() {
|
||||||
|
return Err(Error::from_string(format!(
|
||||||
|
"get empty from hugetlb.{}.events",
|
||||||
|
hugetlb_size
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(x[0].1 as u64)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check how many times has the limit of `hugetlb_size` hugepages been hit.
|
/// Check how many times has the limit of `hugetlb_size` hugepages been hit.
|
||||||
pub fn failcnt(self: &Self, hugetlb_size: &String) -> Result<u64, CgroupError> {
|
pub fn failcnt(&self, hugetlb_size: &str) -> Result<u64> {
|
||||||
|
if self.v2 {
|
||||||
|
return self.failcnt_v2(hugetlb_size);
|
||||||
|
}
|
||||||
self.open_path(&format!("hugetlb.{}.failcnt", hugetlb_size), false)
|
self.open_path(&format!("hugetlb.{}.failcnt", hugetlb_size), false)
|
||||||
.and_then(read_u64_from)
|
.and_then(read_u64_from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the limit (in bytes) of how much memory can be backed by hugepages of a certain size
|
/// Get the limit (in bytes) of how much memory can be backed by hugepages of a certain size
|
||||||
/// (`hugetlb_size`).
|
/// (`hugetlb_size`).
|
||||||
pub fn limit_in_bytes(self: &Self, hugetlb_size: &String) -> Result<u64, CgroupError> {
|
pub fn limit_in_bytes(&self, hugetlb_size: &str) -> Result<u64> {
|
||||||
self.open_path(&format!("hugetlb.{}.limit_in_bytes", hugetlb_size), false)
|
self.open_path(&format!("hugetlb.{}.limit_in_bytes", hugetlb_size), false)
|
||||||
.and_then(read_u64_from)
|
.and_then(read_u64_from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the current usage of memory that is backed by hugepages of a certain size
|
/// Get the current usage of memory that is backed by hugepages of a certain size
|
||||||
/// (`hugetlb_size`).
|
/// (`hugetlb_size`).
|
||||||
pub fn usage_in_bytes(self: &Self, hugetlb_size: &String) -> Result<u64, CgroupError> {
|
pub fn usage_in_bytes(&self, hugetlb_size: &str) -> Result<u64> {
|
||||||
self.open_path(&format!("hugetlb.{}.usage_in_bytes", hugetlb_size), false)
|
let mut file = format!("hugetlb.{}.usage_in_bytes", hugetlb_size);
|
||||||
.and_then(read_u64_from)
|
if self.v2 {
|
||||||
|
file = format!("hugetlb.{}.current", hugetlb_size);
|
||||||
|
}
|
||||||
|
self.open_path(&file, false).and_then(read_u64_from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the maximum observed usage of memory that is backed by hugepages of a certain size
|
/// Get the maximum observed usage of memory that is backed by hugepages of a certain size
|
||||||
/// (`hugetlb_size`).
|
/// (`hugetlb_size`).
|
||||||
pub fn max_usage_in_bytes(self: &Self, hugetlb_size: &String) -> Result<u64, CgroupError> {
|
pub fn max_usage_in_bytes(&self, hugetlb_size: &str) -> Result<u64> {
|
||||||
self.open_path(&format!("hugetlb.{}.max_usage_in_bytes", hugetlb_size), false)
|
self.open_path(
|
||||||
.and_then(read_u64_from)
|
&format!("hugetlb.{}.max_usage_in_bytes", hugetlb_size),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.and_then(read_u64_from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the limit (in bytes) of how much memory can be backed by hugepages of a certain size
|
/// Set the limit (in bytes) of how much memory can be backed by hugepages of a certain size
|
||||||
/// (`hugetlb_size`).
|
/// (`hugetlb_size`).
|
||||||
pub fn set_limit_in_bytes(self: &Self, hugetlb_size: &String, limit: u64) -> Result<(), CgroupError> {
|
pub fn set_limit_in_bytes(&self, hugetlb_size: &str, limit: u64) -> Result<()> {
|
||||||
self.open_path(&format!("hugetlb.{}.limit_in_bytes", hugetlb_size), false)
|
let mut file_name = format!("hugetlb.{}.limit_in_bytes", hugetlb_size);
|
||||||
.and_then(|mut file| {
|
if self.v2 {
|
||||||
file.write_all(limit.to_string().as_ref()).map_err(CgroupError::WriteError)
|
file_name = format!("hugetlb.{}.max", hugetlb_size);
|
||||||
|
}
|
||||||
|
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: &str = "/sys/kernel/mm/hugepages";
|
||||||
|
use regex::Regex;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
fn get_hugepage_sizes() -> Vec<String> {
|
||||||
|
let dirs = fs::read_dir(HUGEPAGESIZE_DIR);
|
||||||
|
if dirs.is_err() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
Some(custom_size(size as f64, 1024.0, &dabbrs))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const KB: u128 = 1000;
|
||||||
|
pub const MB: u128 = 1000 * KB;
|
||||||
|
pub const GB: u128 = 1000 * MB;
|
||||||
|
pub const TB: u128 = 1000 * GB;
|
||||||
|
pub const PB: u128 = 1000 * TB;
|
||||||
|
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const KiB: u128 = 1024;
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const MiB: u128 = 1024 * KiB;
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const GiB: u128 = 1024 * MiB;
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const TiB: u128 = 1024 * GiB;
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
pub const PiB: u128 = 1024 * TiB;
|
||||||
|
|
||||||
|
pub fn get_binary_size_map() -> HashMap<String, u128> {
|
||||||
|
let mut m = HashMap::new();
|
||||||
|
m.insert("k".to_string(), KiB);
|
||||||
|
m.insert("m".to_string(), MiB);
|
||||||
|
m.insert("g".to_string(), GiB);
|
||||||
|
m.insert("t".to_string(), TiB);
|
||||||
|
m.insert("p".to_string(), PiB);
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_decimal_size_map() -> HashMap<String, u128> {
|
||||||
|
let mut m = HashMap::new();
|
||||||
|
m.insert("k".to_string(), KB);
|
||||||
|
m.insert("m".to_string(), MB);
|
||||||
|
m.insert("g".to_string(), GB);
|
||||||
|
m.insert("t".to_string(), TB);
|
||||||
|
m.insert("p".to_string(), PB);
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_decimal_abbrs() -> Vec<String> {
|
||||||
|
let m = vec![
|
||||||
|
"B".to_string(),
|
||||||
|
"KB".to_string(),
|
||||||
|
"MB".to_string(),
|
||||||
|
"GB".to_string(),
|
||||||
|
"TB".to_string(),
|
||||||
|
"PB".to_string(),
|
||||||
|
"EB".to_string(),
|
||||||
|
"ZB".to_string(),
|
||||||
|
"YB".to_string(),
|
||||||
|
];
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_size(s: &str, m: &HashMap<String, u128>) -> Result<u128> {
|
||||||
|
let re = Regex::new(r"(?P<num>\d+)(?P<mul>[kKmMgGtTpP]?)[bB]?$");
|
||||||
|
|
||||||
|
if re.is_err() {
|
||||||
|
return Err(Error::new(InvalidBytesSize));
|
||||||
|
}
|
||||||
|
let caps = re.unwrap().captures(s).unwrap();
|
||||||
|
|
||||||
|
let num = caps.name("num");
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
n.unwrap()
|
||||||
|
} else {
|
||||||
|
return Err(Error::new(InvalidBytesSize));
|
||||||
|
};
|
||||||
|
|
||||||
|
let q = caps.name("mul");
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err(Error::new(InvalidBytesSize));
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(size * mul)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn custom_size(mut size: f64, base: f64, m: &[String]) -> String {
|
||||||
|
let mut i = 0;
|
||||||
|
while size >= base && i < m.len() - 1 {
|
||||||
|
size /= base;
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
format!("{}{}", size, m[i].as_str())
|
||||||
|
}
|
||||||
|
|||||||
868
src/lib.rs
868
src/lib.rs
File diff suppressed because it is too large
Load Diff
1146
src/memory.rs
1146
src/memory.rs
File diff suppressed because it is too large
Load Diff
@@ -1,13 +1,22 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `net_cls` cgroup subsystem.
|
//! This module contains the implementation of the `net_cls` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/cgroup-v1/net_cls.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/net_cls.txt)
|
//! [Documentation/cgroup-v1/net_cls.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/net_cls.txt)
|
||||||
|
use std::io::Write;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::io::{Read, Write};
|
|
||||||
use std::fs::File;
|
|
||||||
|
|
||||||
use {CgroupError, NetworkResources, Controllers, Controller, Resources, ControllIdentifier, Subsystem};
|
use crate::error::ErrorKind::*;
|
||||||
use CgroupError::*;
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::read_u64_from;
|
||||||
|
use crate::{
|
||||||
|
ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, Subsystem,
|
||||||
|
};
|
||||||
|
|
||||||
/// A controller that allows controlling the `net_cls` subsystem of a Cgroup.
|
/// A controller that allows controlling the `net_cls` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -20,19 +29,27 @@ pub struct NetClsController {
|
|||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for NetClsController {
|
impl ControllerInternal for NetClsController {
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::NetCls }
|
fn control_type(&self) -> Controllers {
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
Controllers::NetCls
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
}
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, res: &Resources) {
|
fn apply(&self, res: &Resources) -> Result<()> {
|
||||||
/* get the resources that apply to this controller */
|
// get the resources that apply to this controller
|
||||||
let res: &NetworkResources = &res.network;
|
let res: &NetworkResources = &res.network;
|
||||||
|
|
||||||
if res.update_values {
|
update_and_test!(self, set_class, res.class_id, get_class);
|
||||||
let _ = self.set_class(res.class_id);
|
|
||||||
}
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,26 +66,17 @@ impl<'a> From<&'a Subsystem> for &'a NetClsController {
|
|||||||
Subsystem::NetCls(c) => c,
|
Subsystem::NetCls(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_u64_from(mut file: File) -> Result<u64, CgroupError> {
|
|
||||||
let mut string = String::new();
|
|
||||||
match file.read_to_string(&mut string) {
|
|
||||||
Ok(_) => string.trim().parse().map_err(|_| ParseError),
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NetClsController {
|
impl NetClsController {
|
||||||
/// Constructs a new `NetClsController` with `oroot` serving as the root of the control group.
|
/// Constructs a new `NetClsController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
@@ -76,17 +84,19 @@ impl NetClsController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Set the network class id of the outgoing packets of the control group's tasks.
|
/// Set the network class id of the outgoing packets of the control group's tasks.
|
||||||
pub fn set_class(self: &Self, class: u64) -> Result<(), CgroupError> {
|
pub fn set_class(&self, class: u64) -> Result<()> {
|
||||||
self.open_path("net_cls.classid", true).and_then(|mut file| {
|
self.open_path("net_cls.classid", true)
|
||||||
let s = format!("{:#08X}", class);
|
.and_then(|mut file| {
|
||||||
file.write_all(s.as_ref()).map_err(CgroupError::WriteError)
|
let s = format!("{:#08X}", class);
|
||||||
})
|
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.
|
/// Get the network class id of the outgoing packets of the control group's tasks.
|
||||||
pub fn get_class(self: &Self) -> Result<u64, CgroupError> {
|
pub fn get_class(&self) -> Result<u64> {
|
||||||
self.open_path("net_cls.classid", false).and_then(|file| {
|
self.open_path("net_cls.classid", false)
|
||||||
read_u64_from(file)
|
.and_then(read_u64_from)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
136
src/net_prio.rs
136
src/net_prio.rs
@@ -1,14 +1,23 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `net_prio` cgroup subsystem.
|
//! This module contains the implementation of the `net_prio` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/cgroup-v1/net_prio.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/net_prio.txt)
|
//! [Documentation/cgroup-v1/net_prio.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/net_prio.txt)
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::io::{BufReader, BufRead, Write, Read};
|
|
||||||
use std::fs::File;
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::io::{BufRead, BufReader, Write};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use {CgroupError, NetworkResources, Controllers, Controller, Resources, ControllIdentifier, Subsystem};
|
use crate::error::ErrorKind::*;
|
||||||
use CgroupError::*;
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::read_u64_from;
|
||||||
|
use crate::{
|
||||||
|
ControllIdentifier, ControllerInternal, Controllers, NetworkResources, Resources, Subsystem,
|
||||||
|
};
|
||||||
|
|
||||||
/// A controller that allows controlling the `net_prio` subsystem of a Cgroup.
|
/// A controller that allows controlling the `net_prio` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -21,21 +30,29 @@ pub struct NetPrioController {
|
|||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for NetPrioController {
|
impl ControllerInternal for NetPrioController {
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::NetPrio }
|
fn control_type(&self) -> Controllers {
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
Controllers::NetPrio
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
}
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, res: &Resources) {
|
fn apply(&self, res: &Resources) -> Result<()> {
|
||||||
/* get the resources that apply to this controller */
|
// get the resources that apply to this controller
|
||||||
let res: &NetworkResources = &res.network;
|
let res: &NetworkResources = &res.network;
|
||||||
|
|
||||||
if res.update_values {
|
for i in &res.priorities {
|
||||||
for i in &res.priorities {
|
let _ = self.set_if_prio(&i.name, i.priority);
|
||||||
let _ = self.set_if_prio(&i.name, i.priority);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,26 +69,17 @@ impl<'a> From<&'a Subsystem> for &'a NetPrioController {
|
|||||||
Subsystem::NetPrio(c) => c,
|
Subsystem::NetPrio(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_u64_from(mut file: File) -> Result<u64, CgroupError> {
|
|
||||||
let mut string = String::new();
|
|
||||||
match file.read_to_string(&mut string) {
|
|
||||||
Ok(_) => string.trim().parse().map_err(|_| ParseError),
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NetPrioController {
|
impl NetPrioController {
|
||||||
/// Constructs a new `NetPrioController` with `oroot` serving as the root of the control group.
|
/// Constructs a new `NetPrioController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
@@ -79,46 +87,60 @@ impl NetPrioController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Retrieves the current priority of the emitted packets.
|
/// Retrieves the current priority of the emitted packets.
|
||||||
pub fn prio_idx(self: &Self) -> u64 {
|
pub fn prio_idx(&self) -> u64 {
|
||||||
self.open_path("net_prio.prioidx", false)
|
self.open_path("net_prio.prioidx", false)
|
||||||
.and_then(read_u64_from)
|
.and_then(read_u64_from)
|
||||||
.unwrap_or(0)
|
.unwrap_or(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A map of priorities for each network interface.
|
/// A map of priorities for each network interface.
|
||||||
pub fn ifpriomap(self: &Self) -> Result<HashMap<String, u64>, CgroupError> {
|
#[allow(clippy::iter_nth_zero, clippy::unnecessary_unwrap)]
|
||||||
self.open_path("net_prio.ifpriomap", false) .and_then(|file| {
|
pub fn ifpriomap(&self) -> Result<HashMap<String, u64>> {
|
||||||
let bf = BufReader::new(file);
|
self.open_path("net_prio.ifpriomap", false)
|
||||||
bf.lines().fold(Ok(HashMap::new()), |acc, line| {
|
.and_then(|file| {
|
||||||
if acc.is_err() {
|
let bf = BufReader::new(file);
|
||||||
acc
|
bf.lines().fold(Ok(HashMap::new()), |acc, line| {
|
||||||
} else {
|
if acc.is_err() {
|
||||||
let mut acc = acc.unwrap();
|
acc
|
||||||
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() {
|
|
||||||
Err(CgroupError::ParseError)
|
|
||||||
} else {
|
} else {
|
||||||
let ifname = ifname.unwrap();
|
let mut acc = acc.unwrap();
|
||||||
let ifprio = ifprio.unwrap().trim().parse();
|
let l = line.unwrap();
|
||||||
if ifprio.is_err() {
|
let mut sp = l.split_whitespace();
|
||||||
Err(CgroupError::ParseError)
|
|
||||||
|
let ifname = sp.nth(0);
|
||||||
|
let ifprio = sp.nth(1);
|
||||||
|
if ifname.is_none() || ifprio.is_none() {
|
||||||
|
Err(Error::new(ParseError))
|
||||||
} else {
|
} else {
|
||||||
acc.insert(ifname.to_string(), ifprio.unwrap());
|
let ifname = ifname.unwrap();
|
||||||
Ok(acc)
|
let ifprio = ifprio.unwrap().trim().parse();
|
||||||
|
match ifprio {
|
||||||
|
Err(e) => Err(Error::with_cause(ParseError, e)),
|
||||||
|
Ok(_) => {
|
||||||
|
acc.insert(ifname.to_string(), ifprio.unwrap());
|
||||||
|
Ok(acc)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
})
|
})
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the priority of the network traffic on `eif` to be `prio`.
|
/// Set the priority of the network traffic on `eif` to be `prio`.
|
||||||
pub fn set_if_prio(self: &Self, eif: &String, prio: u64) -> Result<(), CgroupError> {
|
pub fn set_if_prio(&self, eif: &str, prio: u64) -> Result<()> {
|
||||||
self.open_path("net_prio.ifpriomap", true).and_then(|mut file| {
|
self.open_path("net_prio.ifpriomap", true)
|
||||||
file.write_all(format!("{} {}", eif, prio).as_ref()).map_err(CgroupError::WriteError)
|
.and_then(|mut file| {
|
||||||
})
|
file.write_all(format!("{} {}", eif, prio).as_ref())
|
||||||
|
.map_err(|e| {
|
||||||
|
Error::with_cause(
|
||||||
|
WriteFailed(
|
||||||
|
"net_prio.ifpriomap".to_string(),
|
||||||
|
format!("{} {}", eif, prio),
|
||||||
|
),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `perf_event` cgroup subsystem.
|
//! This module contains the implementation of the `perf_event` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [tools/perf/Documentation/perf-record.txt](https://raw.githubusercontent.com/torvalds/linux/master/tools/perf/Documentation/perf-record.txt)
|
//! [tools/perf/Documentation/perf-record.txt](https://raw.githubusercontent.com/torvalds/linux/master/tools/perf/Documentation/perf-record.txt)
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use {Controllers, Controller, Resources, ControllIdentifier, Subsystem};
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};
|
||||||
|
|
||||||
/// A controller that allows controlling the `perf_event` subsystem of a Cgroup.
|
/// A controller that allows controlling the `perf_event` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -16,13 +23,22 @@ pub struct PerfEventController {
|
|||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for PerfEventController {
|
impl ControllerInternal for PerfEventController {
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::PerfEvent }
|
fn control_type(&self) -> Controllers {
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
Controllers::PerfEvent
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
}
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, _res: &Resources) {
|
fn apply(&self, _res: &Resources) -> Result<()> {
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,18 +55,17 @@ impl<'a> From<&'a Subsystem> for &'a PerfEventController {
|
|||||||
Subsystem::PerfEvent(c) => c,
|
Subsystem::PerfEvent(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PerfEventController {
|
impl PerfEventController {
|
||||||
/// Constructs a new `PerfEventController` with `oroot` serving as the root of the control group.
|
/// Constructs a new `PerfEventController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
|
|||||||
161
src/pid.rs
161
src/pid.rs
@@ -1,59 +1,72 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `pids` cgroup subsystem.
|
//! This module contains the implementation of the `pids` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/cgroups-v1/pids.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/pids.txt)
|
//! [Documentation/cgroups-v1/pids.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/pids.txt)
|
||||||
|
use std::io::{Read, Write};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::io::{Write, Read};
|
|
||||||
use std::fs::File;
|
|
||||||
|
|
||||||
use {CgroupError, Resources, PidResources, Controller, ControllIdentifier, Subsystem, Controllers};
|
use crate::error::ErrorKind::*;
|
||||||
use CgroupError::*;
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::read_u64_from;
|
||||||
|
use crate::{
|
||||||
|
parse_max_value, ControllIdentifier, ControllerInternal, Controllers, MaxValue, PidResources,
|
||||||
|
Resources, Subsystem,
|
||||||
|
};
|
||||||
|
|
||||||
/// A controller that allows controlling the `pids` subsystem of a Cgroup.
|
/// A controller that allows controlling the `pids` subsystem of a Cgroup.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct PidController {
|
pub struct PidController {
|
||||||
base: PathBuf,
|
base: PathBuf,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
v2: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The values found in the `pids.max` file in a Cgroup's `pids` subsystem.
|
impl ControllerInternal for PidController {
|
||||||
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
|
fn control_type(&self) -> Controllers {
|
||||||
pub enum PidMax {
|
|
||||||
/// This value is returned when the text found `pids.max` is `"max"`.
|
|
||||||
Max,
|
|
||||||
/// When the value in `pids.max` is a numerical value, they are returned via this enum field.
|
|
||||||
Value(i64),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for PidMax {
|
|
||||||
/// By default, (as per the kernel) `pids.max` should contain `"max"`.
|
|
||||||
fn default() -> Self {
|
|
||||||
PidMax::Max
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Controller for PidController {
|
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::Pids }
|
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
|
||||||
|
|
||||||
fn apply(self: &Self, res: &Resources) {
|
|
||||||
/* get the resources that apply to this controller */
|
|
||||||
let pidres: &PidResources = &res.pid;
|
|
||||||
|
|
||||||
if pidres.update_values {
|
|
||||||
/* apply pid_max */
|
|
||||||
let _ = self.set_pid_max(pidres.maximum_number_of_processes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*impl<'a> ControllIdentifier for &'a PidController {
|
|
||||||
fn controller_type() -> Controllers {
|
|
||||||
Controllers::Pids
|
Controllers::Pids
|
||||||
}
|
}
|
||||||
}*/
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_v2(&self) -> bool {
|
||||||
|
self.v2
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(&self, res: &Resources) -> Result<()> {
|
||||||
|
// get the resources that apply to this controller
|
||||||
|
let pidres: &PidResources = &res.pid;
|
||||||
|
|
||||||
|
// apply pid_max
|
||||||
|
update_and_test!(
|
||||||
|
self,
|
||||||
|
set_pid_max,
|
||||||
|
pidres.maximum_number_of_processes,
|
||||||
|
get_pid_max
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// impl<'a> ControllIdentifier for &'a PidController {
|
||||||
|
// fn controller_type() -> Controllers {
|
||||||
|
// Controllers::Pids
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
impl ControllIdentifier for PidController {
|
impl ControllIdentifier for PidController {
|
||||||
fn controller_type() -> Controllers {
|
fn controller_type() -> Controllers {
|
||||||
@@ -68,72 +81,56 @@ impl<'a> From<&'a Subsystem> for &'a PidController {
|
|||||||
Subsystem::Pid(c) => c,
|
Subsystem::Pid(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_u64_from(mut file: File) -> Result<u64, CgroupError> {
|
|
||||||
let mut string = String::new();
|
|
||||||
match file.read_to_string(&mut string) {
|
|
||||||
Ok(_) => string.trim().parse().map_err(|_| ParseError),
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PidController {
|
impl PidController {
|
||||||
/// Constructors a new `PidController` instance, with `oroot` serving as the controller's root
|
/// Constructors a new `PidController` instance, with `root` serving as the controller's root
|
||||||
/// directory.
|
/// directory.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf, v2: bool) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
|
v2,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The number of times `fork` failed because the limit was hit.
|
/// The number of times `fork` failed because the limit was hit.
|
||||||
pub fn get_pid_events(self: &Self) -> Result<u64, CgroupError> {
|
pub fn get_pid_events(&self) -> Result<u64> {
|
||||||
self.open_path("pids.events", false).and_then(|mut file| {
|
self.open_path("pids.events", false).and_then(|mut file| {
|
||||||
let mut string = String::new();
|
let mut string = String::new();
|
||||||
match file.read_to_string(&mut string) {
|
match file.read_to_string(&mut string) {
|
||||||
Ok(_) => {
|
Ok(_) => match string.split_whitespace().nth(1) {
|
||||||
match string.split_whitespace().nth(1) {
|
Some(elem) => match elem.parse() {
|
||||||
Some(elem) => match elem.parse() {
|
Ok(val) => Ok(val),
|
||||||
Ok(val) => Ok(val),
|
Err(e) => Err(Error::with_cause(ParseError, e)),
|
||||||
Err(_) => Err(CgroupError::ParseError),
|
},
|
||||||
},
|
None => Err(Error::new(ParseError)),
|
||||||
None => Err(CgroupError::ParseError),
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
Err(e) => Err(Error::with_cause(ReadFailed("pids.events".to_string()), e)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The number of processes currently.
|
/// The number of processes currently.
|
||||||
pub fn get_pid_current(self: &Self) -> Result<u64, CgroupError> {
|
pub fn get_pid_current(&self) -> Result<u64> {
|
||||||
self.open_path("pids.current", false).and_then(read_u64_from)
|
self.open_path("pids.current", false)
|
||||||
|
.and_then(read_u64_from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The maximum number of processes that can exist at one time in the control group.
|
/// The maximum number of processes that can exist at one time in the control group.
|
||||||
pub fn get_pid_max(self: &Self) -> Result<PidMax, CgroupError> {
|
pub fn get_pid_max(&self) -> Result<MaxValue> {
|
||||||
self.open_path("pids.max", false).and_then(|mut file| {
|
self.open_path("pids.max", false).and_then(|mut file| {
|
||||||
let mut string = String::new();
|
let mut string = String::new();
|
||||||
let res = file.read_to_string(&mut string);
|
let res = file.read_to_string(&mut string);
|
||||||
match res {
|
match res {
|
||||||
Ok(_) => if string.trim() == "max" {
|
Ok(_) => parse_max_value(&string),
|
||||||
Ok(PidMax::Max)
|
Err(e) => Err(Error::with_cause(ReadFailed("pids.max".to_string()), e)),
|
||||||
} else {
|
|
||||||
match string.trim().parse() {
|
|
||||||
Ok(val) => Ok(PidMax::Value(val)),
|
|
||||||
Err(_) => Err(CgroupError::ParseError),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -143,15 +140,15 @@ impl PidController {
|
|||||||
/// Note that if `get_pid_current()` returns a higher number than what you
|
/// Note that if `get_pid_current()` returns a higher number than what you
|
||||||
/// are about to set (`max_pid`), then no processess will be killed. Additonally, attaching
|
/// are about to set (`max_pid`), then no processess will be killed. Additonally, attaching
|
||||||
/// extra processes to a control group disregards the limit.
|
/// extra processes to a control group disregards the limit.
|
||||||
pub fn set_pid_max(self: &Self, max_pid: PidMax) -> Result<(), CgroupError> {
|
pub fn set_pid_max(&self, max_pid: MaxValue) -> Result<()> {
|
||||||
self.open_path("pids.max", true).and_then(|mut file| {
|
self.open_path("pids.max", true).and_then(|mut file| {
|
||||||
let string_to_write = match max_pid {
|
let string_to_write = max_pid.to_string();
|
||||||
PidMax::Max => "max".to_string(),
|
|
||||||
PidMax::Value(num) => num.to_string(),
|
|
||||||
};
|
|
||||||
match file.write_all(string_to_write.as_ref()) {
|
match file.write_all(string_to_write.as_ref()) {
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => Ok(()),
|
||||||
Err(e) => Err(CgroupError::WriteError(e)),
|
Err(e) => Err(Error::with_cause(
|
||||||
|
WriteFailed("pids.max".to_string(), format!("{:?}", max_pid)),
|
||||||
|
e,
|
||||||
|
)),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
62
src/rdma.rs
62
src/rdma.rs
@@ -1,12 +1,20 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! This module contains the implementation of the `rdma` cgroup subsystem.
|
//! This module contains the implementation of the `rdma` cgroup subsystem.
|
||||||
//!
|
//!
|
||||||
//! See the Kernel's documentation for more information about this subsystem, found at:
|
//! See the Kernel's documentation for more information about this subsystem, found at:
|
||||||
//! [Documentation/cgroup-v1/rdma.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/rdma.txt)
|
//! [Documentation/cgroup-v1/rdma.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/rdma.txt)
|
||||||
|
use std::io::Write;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::io::{Write, Read};
|
|
||||||
use std::fs::File;
|
|
||||||
|
|
||||||
use {CgroupError, Controllers, Controller, Resources, ControllIdentifier, Subsystem};
|
use crate::error::ErrorKind::*;
|
||||||
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::read_string_from;
|
||||||
|
use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};
|
||||||
|
|
||||||
/// A controller that allows controlling the `rdma` subsystem of a Cgroup.
|
/// A controller that allows controlling the `rdma` subsystem of a Cgroup.
|
||||||
///
|
///
|
||||||
@@ -18,13 +26,22 @@ pub struct RdmaController {
|
|||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Controller for RdmaController {
|
impl ControllerInternal for RdmaController {
|
||||||
fn control_type(self: &Self) -> Controllers { Controllers::Rdma }
|
fn control_type(&self) -> Controllers {
|
||||||
fn get_path<'a>(self: &'a Self) -> &'a PathBuf { &self.path }
|
Controllers::Rdma
|
||||||
fn get_path_mut<'a>(self: &'a mut Self) -> &'a mut PathBuf { &mut self.path }
|
}
|
||||||
fn get_base<'a>(self: &'a Self) -> &'a PathBuf { &self.base }
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
fn apply(self: &Self, _res: &Resources) {
|
fn apply(&self, _res: &Resources) -> Result<()> {
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,26 +58,17 @@ impl<'a> From<&'a Subsystem> for &'a RdmaController {
|
|||||||
Subsystem::Rdma(c) => c,
|
Subsystem::Rdma(c) => c,
|
||||||
_ => {
|
_ => {
|
||||||
assert_eq!(1, 0);
|
assert_eq!(1, 0);
|
||||||
::std::mem::uninitialized()
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
},
|
v.assume_init()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_string_from(mut file: File) -> Result<String, CgroupError> {
|
|
||||||
let mut string = String::new();
|
|
||||||
match file.read_to_string(&mut string) {
|
|
||||||
Ok(_) => Ok(string.trim().to_string()),
|
|
||||||
Err(e) => Err(CgroupError::ReadError(e)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RdmaController {
|
impl RdmaController {
|
||||||
/// Constructs a new `RdmaController` with `oroot` serving as the root of the control group.
|
/// Constructs a new `RdmaController` with `root` serving as the root of the control group.
|
||||||
pub fn new(oroot: PathBuf) -> Self {
|
pub fn new(root: PathBuf) -> Self {
|
||||||
let mut root = oroot;
|
|
||||||
root.push(Self::controller_type().to_string());
|
|
||||||
Self {
|
Self {
|
||||||
base: root.clone(),
|
base: root.clone(),
|
||||||
path: root,
|
path: root,
|
||||||
@@ -68,15 +76,17 @@ impl RdmaController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the current usage of RDMA/IB specific resources.
|
/// Returns the current usage of RDMA/IB specific resources.
|
||||||
pub fn current(self: &Self) -> Result<String, CgroupError> {
|
pub fn current(&self) -> Result<String> {
|
||||||
self.open_path("rdma.current", false)
|
self.open_path("rdma.current", false)
|
||||||
.and_then(read_string_from)
|
.and_then(read_string_from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a maximum usage for each RDMA/IB resource.
|
/// Set a maximum usage for each RDMA/IB resource.
|
||||||
pub fn set_max(self: &Self, max: &String) -> Result<(), CgroupError> {
|
pub fn set_max(&self, max: &str) -> Result<()> {
|
||||||
self.open_path("rdma.max", true).and_then(|mut file| {
|
self.open_path("rdma.max", true).and_then(|mut file| {
|
||||||
file.write_all(max.as_ref()).map_err(CgroupError::WriteError)
|
file.write_all(max.as_ref()).map_err(|e| {
|
||||||
|
Error::with_cause(WriteFailed("rdma.max".to_string(), max.to_string()), e)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
72
src/systemd.rs
Normal file
72
src/systemd.rs
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
// Copyright (c) 2020 Ant Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
//! This module contains the implementation of the `systemd` cgroup subsystem.
|
||||||
|
//!
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use crate::error::*;
|
||||||
|
|
||||||
|
use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem};
|
||||||
|
|
||||||
|
/// A controller that allows controlling the `systemd` subsystem of a Cgroup.
|
||||||
|
///
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SystemdController {
|
||||||
|
base: PathBuf,
|
||||||
|
path: PathBuf,
|
||||||
|
_v2: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ControllerInternal for SystemdController {
|
||||||
|
fn control_type(&self) -> Controllers {
|
||||||
|
Controllers::Systemd
|
||||||
|
}
|
||||||
|
fn get_path(&self) -> &PathBuf {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
fn get_path_mut(&mut self) -> &mut PathBuf {
|
||||||
|
&mut self.path
|
||||||
|
}
|
||||||
|
fn get_base(&self) -> &PathBuf {
|
||||||
|
&self.base
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(&self, _res: &Resources) -> Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ControllIdentifier for SystemdController {
|
||||||
|
fn controller_type() -> Controllers {
|
||||||
|
Controllers::Systemd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> From<&'a Subsystem> for &'a SystemdController {
|
||||||
|
fn from(sub: &'a Subsystem) -> &'a SystemdController {
|
||||||
|
unsafe {
|
||||||
|
match sub {
|
||||||
|
Subsystem::Systemd(c) => c,
|
||||||
|
_ => {
|
||||||
|
assert_eq!(1, 0);
|
||||||
|
let v = std::mem::MaybeUninit::uninit();
|
||||||
|
v.assume_init()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SystemdController {
|
||||||
|
/// Constructs a new `SystemdController` with `root` serving as the root of the control group.
|
||||||
|
pub fn new(root: PathBuf, v2: bool) -> Self {
|
||||||
|
Self {
|
||||||
|
base: root.clone(),
|
||||||
|
path: root,
|
||||||
|
_v2: v2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
162
tests/builder.rs
Normal file
162
tests/builder.rs
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 And Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
//! Some simple tests covering the builder pattern for control groups.
|
||||||
|
use cgroups_rs::blkio::*;
|
||||||
|
use cgroups_rs::cgroup_builder::*;
|
||||||
|
use cgroups_rs::cpu::*;
|
||||||
|
use cgroups_rs::devices::*;
|
||||||
|
use cgroups_rs::hugetlb::*;
|
||||||
|
use cgroups_rs::memory::*;
|
||||||
|
use cgroups_rs::net_cls::*;
|
||||||
|
use cgroups_rs::pid::*;
|
||||||
|
use cgroups_rs::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
pub fn test_cpu_res_build() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg: Cgroup = CgroupBuilder::new("test_cpu_res_build")
|
||||||
|
.cpu()
|
||||||
|
.shares(85)
|
||||||
|
.done()
|
||||||
|
.build(h);
|
||||||
|
|
||||||
|
{
|
||||||
|
let cpu: &CpuController = cg.controller_of().unwrap();
|
||||||
|
assert!(cpu.shares().is_ok());
|
||||||
|
assert_eq!(cpu.shares().unwrap(), 85);
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
pub fn test_memory_res_build() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg: Cgroup = CgroupBuilder::new("test_memory_res_build")
|
||||||
|
.memory()
|
||||||
|
.kernel_memory_limit(128 * 1024 * 1024)
|
||||||
|
.swappiness(70)
|
||||||
|
.memory_hard_limit(1024 * 1024 * 1024)
|
||||||
|
.done()
|
||||||
|
.build(h);
|
||||||
|
|
||||||
|
{
|
||||||
|
let c: &MemController = cg.controller_of().unwrap();
|
||||||
|
if !c.v2() {
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
pub fn test_pid_res_build() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg: Cgroup = CgroupBuilder::new("test_pid_res_build")
|
||||||
|
.pid()
|
||||||
|
.maximum_number_of_processes(MaxValue::Value(123))
|
||||||
|
.done()
|
||||||
|
.build(h);
|
||||||
|
|
||||||
|
{
|
||||||
|
let c: &PidController = cg.controller_of().unwrap();
|
||||||
|
assert!(c.get_pid_max().is_ok());
|
||||||
|
assert_eq!(c.get_pid_max().unwrap(), MaxValue::Value(123));
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore] // ignore this test for now, not sure why my kernel doesn't like it
|
||||||
|
pub fn test_devices_res_build() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg: Cgroup = CgroupBuilder::new("test_devices_res_build")
|
||||||
|
.devices()
|
||||||
|
.device(1, 6, DeviceType::Char, true, vec![DevicePermissions::Read])
|
||||||
|
.done()
|
||||||
|
.build(h);
|
||||||
|
|
||||||
|
{
|
||||||
|
let c: &DevicesController = cg.controller_of().unwrap();
|
||||||
|
assert!(c.allowed_devices().is_ok());
|
||||||
|
assert_eq!(
|
||||||
|
c.allowed_devices().unwrap(),
|
||||||
|
vec![DeviceResource {
|
||||||
|
allow: true,
|
||||||
|
devtype: DeviceType::Char,
|
||||||
|
major: 1,
|
||||||
|
minor: 6,
|
||||||
|
access: vec![DevicePermissions::Read],
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
pub fn test_network_res_build() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
if h.v2() {
|
||||||
|
// FIXME add cases for v2
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cg: Cgroup = CgroupBuilder::new("test_network_res_build")
|
||||||
|
.network()
|
||||||
|
.class_id(1337)
|
||||||
|
.done()
|
||||||
|
.build(h);
|
||||||
|
|
||||||
|
{
|
||||||
|
let c: &NetClsController = cg.controller_of().unwrap();
|
||||||
|
assert!(c.get_class().is_ok());
|
||||||
|
assert_eq!(c.get_class().unwrap(), 1337);
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
pub fn test_hugepages_res_build() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
if h.v2() {
|
||||||
|
// FIXME add cases for v2
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cg: Cgroup = CgroupBuilder::new("test_hugepages_res_build")
|
||||||
|
.hugepages()
|
||||||
|
.limit("2MB".to_string(), 4 * 2 * 1024 * 1024)
|
||||||
|
.done()
|
||||||
|
.build(h);
|
||||||
|
|
||||||
|
{
|
||||||
|
let c: &HugeTlbController = cg.controller_of().unwrap();
|
||||||
|
assert!(c.limit_in_bytes("2MB").is_ok());
|
||||||
|
assert_eq!(c.limit_in_bytes("2MB").unwrap(), 4 * 2 * 1024 * 1024);
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore] // high version kernel not support `blkio.weight`
|
||||||
|
pub fn test_blkio_res_build() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg: Cgroup = CgroupBuilder::new("test_blkio_res_build")
|
||||||
|
.blkio()
|
||||||
|
.weight(100)
|
||||||
|
.done()
|
||||||
|
.build(h);
|
||||||
|
|
||||||
|
{
|
||||||
|
let c: &BlkIoController = cg.controller_of().unwrap();
|
||||||
|
assert_eq!(c.blkio().weight, 100);
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
@@ -1,18 +1,26 @@
|
|||||||
//! Simple unit tests about the control groups system.
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
extern crate cgroups;
|
// Copyright (c) 2020 And Group
|
||||||
use cgroups::{Cgroup, CgroupPid};
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
extern crate nix;
|
//! Simple unit tests about the control groups system.
|
||||||
extern crate libc;
|
use cgroups_rs::memory::MemController;
|
||||||
|
use cgroups_rs::Controller;
|
||||||
|
use cgroups_rs::{Cgroup, CgroupPid, Subsystem};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_tasks_iterator() {
|
fn test_tasks_iterator() {
|
||||||
let hier = cgroups::hierarchies::V1::new();
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
let pid = libc::pid_t::from(nix::unistd::getpid()) as u64;
|
let pid = libc::pid_t::from(nix::unistd::getpid()) as u64;
|
||||||
let cg = Cgroup::new(&hier, String::from("test_tasks_iterator"));
|
let cg = Cgroup::new(h, String::from("test_tasks_iterator"));
|
||||||
{
|
{
|
||||||
// Add a task to the control group.
|
// Add a task to the control group.
|
||||||
cg.add_task(CgroupPid::from(pid));
|
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();
|
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 control group
|
||||||
assert_eq!(tasks.next(), Some(CgroupPid::from(pid)));
|
assert_eq!(tasks.next(), Some(CgroupPid::from(pid)));
|
||||||
@@ -25,5 +33,73 @@ fn test_tasks_iterator() {
|
|||||||
// Verify that it was indeed removed.
|
// Verify that it was indeed removed.
|
||||||
assert_eq!(tasks.next(), None);
|
assert_eq!(tasks.next(), None);
|
||||||
}
|
}
|
||||||
cg.delete();
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cgroup_with_relative_paths() {
|
||||||
|
if cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cgroup_root = h.root();
|
||||||
|
let cgroup_name = "test_cgroup_with_relative_paths";
|
||||||
|
|
||||||
|
let cg = Cgroup::load(h, String::from(cgroup_name));
|
||||||
|
{
|
||||||
|
let subsystems = cg.subsystems();
|
||||||
|
subsystems.iter().for_each(|sub| match sub {
|
||||||
|
Subsystem::Pid(c) => {
|
||||||
|
let cgroup_path = c.path().to_str().unwrap();
|
||||||
|
let relative_path = "/pids/";
|
||||||
|
// cgroup_path = cgroup_root + relative_path + cgroup_name
|
||||||
|
assert_eq!(
|
||||||
|
cgroup_path,
|
||||||
|
format!(
|
||||||
|
"{}{}{}",
|
||||||
|
cgroup_root.to_str().unwrap(),
|
||||||
|
relative_path,
|
||||||
|
cgroup_name
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Subsystem::Mem(c) => {
|
||||||
|
let cgroup_path = c.path().to_str().unwrap();
|
||||||
|
// cgroup_path = cgroup_root + relative_path + cgroup_name
|
||||||
|
assert_eq!(
|
||||||
|
cgroup_path,
|
||||||
|
format!("{}/memory/{}", cgroup_root.to_str().unwrap(), cgroup_name)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cgroup_v2() {
|
||||||
|
if !cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg = Cgroup::new(h, String::from("test_v2"));
|
||||||
|
|
||||||
|
let mem_controller: &MemController = cg.controller_of().unwrap();
|
||||||
|
let (mem, swp, rev) = (4 * 1024 * 1000, 2 * 1024 * 1000, 1024 * 1000);
|
||||||
|
|
||||||
|
mem_controller.set_limit(mem).unwrap();
|
||||||
|
mem_controller.set_memswap_limit(swp).unwrap();
|
||||||
|
mem_controller.set_soft_limit(rev).unwrap();
|
||||||
|
|
||||||
|
let memory_stat = mem_controller.memory_stat();
|
||||||
|
println!("memory_stat {:?}", memory_stat);
|
||||||
|
assert_eq!(mem, memory_stat.limit_in_bytes);
|
||||||
|
assert_eq!(rev, memory_stat.soft_limit_in_bytes);
|
||||||
|
|
||||||
|
let memswap = mem_controller.memswap();
|
||||||
|
println!("memswap {:?}", memswap);
|
||||||
|
assert_eq!(swp, memswap.limit_in_bytes);
|
||||||
|
|
||||||
|
cg.delete().unwrap();
|
||||||
}
|
}
|
||||||
|
|||||||
61
tests/cpu.rs
Normal file
61
tests/cpu.rs
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
// Copyright (c) 2020 And Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
//! Simple unit tests about the CPU control groups system.
|
||||||
|
use cgroups_rs::cpu::CpuController;
|
||||||
|
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 cpu_controller: &CpuController = cg.controller_of().unwrap();
|
||||||
|
|
||||||
|
let current_quota = cpu_controller.cfs_quota().unwrap();
|
||||||
|
let current_peroid = cpu_controller.cfs_period().unwrap();
|
||||||
|
|
||||||
|
// verify default value
|
||||||
|
// The default is “max 100000”.
|
||||||
|
assert_eq!(-1, current_quota);
|
||||||
|
assert_eq!(100000, current_peroid);
|
||||||
|
|
||||||
|
// case 1 set quota
|
||||||
|
let _ = cpu_controller.set_cfs_quota(2000);
|
||||||
|
|
||||||
|
let current_quota = cpu_controller.cfs_quota().unwrap();
|
||||||
|
let current_peroid = cpu_controller.cfs_period().unwrap();
|
||||||
|
assert_eq!(2000, current_quota);
|
||||||
|
assert_eq!(100000, current_peroid);
|
||||||
|
|
||||||
|
// case 2 set period
|
||||||
|
cpu_controller.set_cfs_period(1000000).unwrap();
|
||||||
|
let current_quota = cpu_controller.cfs_quota().unwrap();
|
||||||
|
let current_peroid = cpu_controller.cfs_period().unwrap();
|
||||||
|
assert_eq!(2000, current_quota);
|
||||||
|
assert_eq!(1000000, current_peroid);
|
||||||
|
|
||||||
|
// case 3 set both quota and period
|
||||||
|
cpu_controller
|
||||||
|
.set_cfs_quota_and_period(Some(5000), Some(100000))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let current_quota = cpu_controller.cfs_quota().unwrap();
|
||||||
|
let current_peroid = cpu_controller.cfs_period().unwrap();
|
||||||
|
assert_eq!(5000, current_quota);
|
||||||
|
assert_eq!(100000, current_peroid);
|
||||||
|
|
||||||
|
// case 4 set both quota and period, set quota to -1
|
||||||
|
cpu_controller
|
||||||
|
.set_cfs_quota_and_period(Some(-1), None)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let current_quota = cpu_controller.cfs_quota().unwrap();
|
||||||
|
let current_peroid = cpu_controller.cfs_period().unwrap();
|
||||||
|
assert_eq!(-1, current_quota);
|
||||||
|
assert_eq!(100000, current_peroid);
|
||||||
|
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
92
tests/cpuset.rs
Normal file
92
tests/cpuset.rs
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 And Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
use cgroups_rs::cpuset::CpuSetController;
|
||||||
|
use cgroups_rs::error::ErrorKind;
|
||||||
|
use cgroups_rs::{Cgroup, CgroupPid};
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cpuset_memory_pressure_root_cg() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg = Cgroup::new(h, String::from("test_cpuset_memory_pressure_root_cg"));
|
||||||
|
{
|
||||||
|
let cpuset: &CpuSetController = cg.controller_of().unwrap();
|
||||||
|
|
||||||
|
// This is not a root control group, so it should fail via InvalidOperation.
|
||||||
|
let res = cpuset.set_enable_memory_pressure(true);
|
||||||
|
assert_eq!(res.unwrap_err().kind(), &ErrorKind::InvalidOperation);
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_cpuset_set_cpus() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg = Cgroup::new(h, String::from("test_cpuset_set_cpus"));
|
||||||
|
{
|
||||||
|
let cpuset: &CpuSetController = cg.controller_of().unwrap();
|
||||||
|
|
||||||
|
let set = cpuset.cpuset();
|
||||||
|
if cg.v2() {
|
||||||
|
assert_eq!(0, set.cpus.len());
|
||||||
|
} else {
|
||||||
|
// for cgroup v1, cpuset is copied from parent.
|
||||||
|
assert!(!set.cpus.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 0
|
||||||
|
let r = cpuset.set_cpus("0");
|
||||||
|
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_default();
|
||||||
|
let cpus = cpus.trim();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 cpuset: &CpuSetController = cg.controller_of().unwrap();
|
||||||
|
let set = cpuset.cpuset();
|
||||||
|
if cg.v2() {
|
||||||
|
assert_eq!(0, set.cpus.len());
|
||||||
|
} else {
|
||||||
|
// for cgroup v1, cpuset is copied from parent.
|
||||||
|
assert!(!set.cpus.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a task to the control group.
|
||||||
|
let pid_i = libc::pid_t::from(nix::unistd::getpid()) as u64;
|
||||||
|
let _ = cg.add_task(CgroupPid::from(pid_i));
|
||||||
|
let tasks = cg.tasks();
|
||||||
|
assert!(!tasks.is_empty());
|
||||||
|
println!("tasks after added: {:?}", tasks);
|
||||||
|
|
||||||
|
// remove task
|
||||||
|
cg.remove_task(CgroupPid::from(pid_i));
|
||||||
|
let tasks = cg.tasks();
|
||||||
|
println!("tasks after deleted: {:?}", tasks);
|
||||||
|
assert_eq!(0, tasks.len());
|
||||||
|
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
73
tests/devices.rs
Normal file
73
tests/devices.rs
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 And Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
//! Integration tests about the devices subsystem
|
||||||
|
|
||||||
|
use cgroups_rs::devices::{DevicePermissions, DeviceType, DevicesController};
|
||||||
|
use cgroups_rs::{Cgroup, DeviceResource};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_devices_parsing() {
|
||||||
|
// now only v2
|
||||||
|
if cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg = Cgroup::new(h, String::from("test_devices_parsing"));
|
||||||
|
{
|
||||||
|
let devices: &DevicesController = cg.controller_of().unwrap();
|
||||||
|
|
||||||
|
// Deny access to all devices first
|
||||||
|
devices
|
||||||
|
.deny_device(
|
||||||
|
DeviceType::All,
|
||||||
|
-1,
|
||||||
|
-1,
|
||||||
|
&[
|
||||||
|
DevicePermissions::Read,
|
||||||
|
DevicePermissions::Write,
|
||||||
|
DevicePermissions::MkNod,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
// Acquire the list of allowed devices after we denied all
|
||||||
|
let allowed_devices = devices.allowed_devices();
|
||||||
|
// Verify that there are no devices that we can access.
|
||||||
|
assert!(allowed_devices.is_ok());
|
||||||
|
assert_eq!(allowed_devices.unwrap(), Vec::new());
|
||||||
|
|
||||||
|
// Now add mknod access to /dev/null device
|
||||||
|
devices
|
||||||
|
.allow_device(DeviceType::Char, 1, 3, &[DevicePermissions::MkNod])
|
||||||
|
.unwrap();
|
||||||
|
let allowed_devices = devices.allowed_devices();
|
||||||
|
assert!(allowed_devices.is_ok());
|
||||||
|
let allowed_devices = allowed_devices.unwrap();
|
||||||
|
assert_eq!(allowed_devices.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
allowed_devices[0],
|
||||||
|
DeviceResource {
|
||||||
|
allow: true,
|
||||||
|
devtype: DeviceType::Char,
|
||||||
|
major: 1,
|
||||||
|
minor: 3,
|
||||||
|
access: vec![DevicePermissions::MkNod],
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Now deny, this device explicitly.
|
||||||
|
devices
|
||||||
|
.deny_device(DeviceType::Char, 1, 3, &DevicePermissions::all())
|
||||||
|
.unwrap();
|
||||||
|
// Finally, check that.
|
||||||
|
let allowed_devices = devices.allowed_devices();
|
||||||
|
// Verify that there are no devices that we can access.
|
||||||
|
assert!(allowed_devices.is_ok());
|
||||||
|
assert_eq!(allowed_devices.unwrap(), Vec::new());
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
44
tests/hugetlb.rs
Normal file
44
tests/hugetlb.rs
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
// Copyright (c) 2020 And Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
//! Integration tests about the hugetlb subsystem
|
||||||
|
use cgroups_rs::error::*;
|
||||||
|
use cgroups_rs::hugetlb::{self, HugeTlbController};
|
||||||
|
use cgroups_rs::Cgroup;
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_hugetlb_sizes() {
|
||||||
|
// now only v2
|
||||||
|
if cgroups_rs::hierarchies::is_cgroup2_unified_mode() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
let cg = Cgroup::new(h, String::from("test_hugetlb_sizes"));
|
||||||
|
{
|
||||||
|
let hugetlb_controller: &HugeTlbController = cg.controller_of().unwrap();
|
||||||
|
let _ = hugetlb_controller.get_sizes();
|
||||||
|
|
||||||
|
// test sizes count
|
||||||
|
let sizes = hugetlb_controller.get_sizes();
|
||||||
|
let sizes_count = fs::read_dir(hugetlb::HUGEPAGESIZE_DIR).unwrap().count();
|
||||||
|
assert_eq!(sizes.len(), sizes_count);
|
||||||
|
|
||||||
|
for size in sizes {
|
||||||
|
let supported = hugetlb_controller.size_supported(&size);
|
||||||
|
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));
|
||||||
|
assert_no_error(hugetlb_controller.max_usage_in_bytes(&size));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_no_error(r: Result<u64>) {
|
||||||
|
assert!(r.is_ok())
|
||||||
|
}
|
||||||
106
tests/memory.rs
Normal file
106
tests/memory.rs
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
// Copyright (c) 2020 And Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
|
//! Integration tests about the hugetlb subsystem
|
||||||
|
use cgroups_rs::memory::{MemController, SetMemory};
|
||||||
|
use cgroups_rs::Controller;
|
||||||
|
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 mem_controller: &MemController = cg.controller_of().unwrap();
|
||||||
|
|
||||||
|
// before disable
|
||||||
|
let m = mem_controller.memory_stat();
|
||||||
|
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!(r.is_ok());
|
||||||
|
|
||||||
|
// after disable
|
||||||
|
let m = mem_controller.memory_stat();
|
||||||
|
assert!(m.oom_control.oom_kill_disable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_kmem_limit_v1() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
if h.v2() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cg = Cgroup::new(h, String::from("set_kmem_limit_v1"));
|
||||||
|
{
|
||||||
|
let mem_controller: &MemController = cg.controller_of().unwrap();
|
||||||
|
mem_controller.set_kmem_limit(1).unwrap();
|
||||||
|
}
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_mem_v2() {
|
||||||
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
|
if !h.v2() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cg = Cgroup::new(h, String::from("set_mem_v2"));
|
||||||
|
{
|
||||||
|
let mem_controller: &MemController = cg.controller_of().unwrap();
|
||||||
|
|
||||||
|
// before disable
|
||||||
|
let m = mem_controller.get_mem().unwrap();
|
||||||
|
// case 1: get default value
|
||||||
|
assert_eq!(m.low, Some(MaxValue::Value(0)));
|
||||||
|
assert_eq!(m.min, Some(MaxValue::Value(0)));
|
||||||
|
assert_eq!(m.high, Some(MaxValue::Max));
|
||||||
|
assert_eq!(m.max, Some(MaxValue::Max));
|
||||||
|
|
||||||
|
// case 2: set parts
|
||||||
|
let m = SetMemory {
|
||||||
|
low: Some(MaxValue::Value(1024 * 1024 * 2)),
|
||||||
|
high: Some(MaxValue::Value(1024 * 1024 * 1024 * 2)),
|
||||||
|
min: Some(MaxValue::Value(1024 * 1024 * 3)),
|
||||||
|
max: None,
|
||||||
|
};
|
||||||
|
let r = mem_controller.set_mem(m);
|
||||||
|
assert!(r.is_ok());
|
||||||
|
|
||||||
|
let m = mem_controller.get_mem().unwrap();
|
||||||
|
// get
|
||||||
|
assert_eq!(m.low, Some(MaxValue::Value(1024 * 1024 * 2)));
|
||||||
|
assert_eq!(m.min, Some(MaxValue::Value(1024 * 1024 * 3)));
|
||||||
|
assert_eq!(m.high, Some(MaxValue::Value(1024 * 1024 * 1024 * 2)));
|
||||||
|
assert_eq!(m.max, Some(MaxValue::Max));
|
||||||
|
|
||||||
|
// case 3: set parts
|
||||||
|
let m = SetMemory {
|
||||||
|
max: Some(MaxValue::Value(1024 * 1024 * 1024 * 2)),
|
||||||
|
min: Some(MaxValue::Value(1024 * 1024 * 4)),
|
||||||
|
high: Some(MaxValue::Max),
|
||||||
|
low: None,
|
||||||
|
};
|
||||||
|
let r = mem_controller.set_mem(m);
|
||||||
|
assert!(r.is_ok());
|
||||||
|
|
||||||
|
let m = mem_controller.get_mem().unwrap();
|
||||||
|
// get
|
||||||
|
assert_eq!(m.low, Some(MaxValue::Value(1024 * 1024 * 2)));
|
||||||
|
assert_eq!(m.min, Some(MaxValue::Value(1024 * 1024 * 4)));
|
||||||
|
assert_eq!(m.max, Some(MaxValue::Value(1024 * 1024 * 1024 * 2)));
|
||||||
|
assert_eq!(m.high, Some(MaxValue::Max));
|
||||||
|
}
|
||||||
|
|
||||||
|
cg.delete().unwrap();
|
||||||
|
}
|
||||||
@@ -1,70 +1,77 @@
|
|||||||
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
|
// Copyright (c) 2020 And Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
//! Integration tests about the pids subsystem
|
//! Integration tests about the pids subsystem
|
||||||
extern crate cgroups;
|
use cgroups_rs::pid::PidController;
|
||||||
use cgroups::{CgroupError, CgroupPid, Cgroup, Resources, PidResources};
|
use cgroups_rs::Controller;
|
||||||
use cgroups::pid::{PidController, PidMax};
|
use cgroups_rs::{Cgroup, MaxValue};
|
||||||
use cgroups::Controller;
|
|
||||||
|
|
||||||
extern crate nix;
|
|
||||||
use nix::unistd::{Pid, fork, ForkResult};
|
|
||||||
use nix::sys::wait::{waitpid, WaitStatus};
|
use nix::sys::wait::{waitpid, WaitStatus};
|
||||||
|
use nix::unistd::{fork, ForkResult};
|
||||||
|
|
||||||
extern crate libc;
|
|
||||||
use libc::pid_t;
|
use libc::pid_t;
|
||||||
|
|
||||||
use std::thread;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn create_and_delete_cgroup() {
|
fn create_and_delete_cgroup() {
|
||||||
let hier = cgroups::hierarchies::V1::new();
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
let cg = Cgroup::new(&hier, String::from("create_and_delete_cgroup"));
|
let cg = Cgroup::new(h, String::from("create_and_delete_cgroup"));
|
||||||
{
|
{
|
||||||
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
||||||
pidcontroller.set_pid_max(PidMax::Value(1337));
|
pidcontroller.set_pid_max(MaxValue::Value(1337)).unwrap();
|
||||||
assert_eq!(pidcontroller.get_pid_max(), Some(PidMax::Value(1337)));
|
let max = pidcontroller.get_pid_max();
|
||||||
|
assert!(max.is_ok());
|
||||||
|
assert_eq!(max.unwrap(), MaxValue::Value(1337));
|
||||||
}
|
}
|
||||||
cg.delete();
|
cg.delete().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_pids_current_is_zero() {
|
fn test_pids_current_is_zero() {
|
||||||
let hier = cgroups::hierarchies::V1::new();
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
let cg = Cgroup::new(&hier, String::from("test_pids_current_is_zero"));
|
let cg = Cgroup::new(h, String::from("test_pids_current_is_zero"));
|
||||||
{
|
{
|
||||||
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
||||||
assert_eq!(pidcontroller.get_pid_current(), 0);
|
let current = pidcontroller.get_pid_current();
|
||||||
|
assert_eq!(current.unwrap(), 0);
|
||||||
}
|
}
|
||||||
cg.delete();
|
cg.delete().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_pids_events_is_zero() {
|
fn test_pids_events_is_zero() {
|
||||||
let hier = cgroups::hierarchies::V1::new();
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
let cg = Cgroup::new(&hier, String::from("test_pids_events_is_zero"));
|
let cg = Cgroup::new(h, String::from("test_pids_events_is_zero"));
|
||||||
{
|
{
|
||||||
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
||||||
assert_eq!(pidcontroller.get_pid_events(), 0);
|
let events = pidcontroller.get_pid_events();
|
||||||
|
assert!(events.is_ok());
|
||||||
|
assert_eq!(events.unwrap(), 0);
|
||||||
}
|
}
|
||||||
cg.delete();
|
cg.delete().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_pid_events_is_not_zero() {
|
fn test_pid_events_is_not_zero() {
|
||||||
let hier = cgroups::hierarchies::V1::new();
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
let cg = Cgroup::new(&hier, String::from("test_pid_events_is_not_zero"));
|
let cg = Cgroup::new(h, String::from("test_pid_events_is_not_zero"));
|
||||||
{
|
{
|
||||||
let pids: &PidController = cg.controller_of().unwrap();
|
let pids: &PidController = cg.controller_of().unwrap();
|
||||||
let before = pids.get_pid_events();
|
let before = pids.get_pid_events();
|
||||||
|
let before = before.unwrap();
|
||||||
|
|
||||||
match fork() {
|
match unsafe { fork() } {
|
||||||
Ok(ForkResult::Parent { child, .. }) => {
|
Ok(ForkResult::Parent { child, .. }) => {
|
||||||
// move the process into the control group
|
// move the process into the control group
|
||||||
pids.add_task(&(pid_t::from(child) as u64).into());
|
let _ = pids.add_task(&(pid_t::from(child) as u64).into());
|
||||||
|
|
||||||
println!("added task to cg: {:?}", child);
|
println!("added task to cg: {:?}", child);
|
||||||
|
|
||||||
// Set limit to one
|
// Set limit to one
|
||||||
pids.set_pid_max(PidMax::Value(1));
|
let _ = pids.set_pid_max(MaxValue::Value(1));
|
||||||
println!("err = {:?}", pids.get_pid_max());
|
println!("current pid.max = {:?}", pids.get_pid_max());
|
||||||
|
|
||||||
// wait on the child
|
// wait on the child
|
||||||
let res = waitpid(child, None);
|
let res = waitpid(child, None);
|
||||||
@@ -75,21 +82,22 @@ fn test_pid_events_is_not_zero() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check pids.events
|
// Check pids.events
|
||||||
assert_eq!(pids.get_pid_events(), before + 1);
|
let events = pids.get_pid_events();
|
||||||
},
|
assert!(events.is_ok());
|
||||||
Ok(ForkResult::Child) => {
|
assert_eq!(events.unwrap(), before + 1);
|
||||||
loop {
|
}
|
||||||
if pids.get_pid_max() == Some(PidMax::Value(1)) {
|
Ok(ForkResult::Child) => loop {
|
||||||
if let Err(_) = fork() {
|
let pids_max = pids.get_pid_max();
|
||||||
unsafe { libc::exit(0) };
|
if pids_max.is_ok() && pids_max.unwrap() == MaxValue::Value(1) {
|
||||||
} else {
|
if unsafe { fork() }.is_err() {
|
||||||
unsafe { libc::exit(1) };
|
unsafe { libc::exit(0) };
|
||||||
}
|
} else {
|
||||||
|
unsafe { libc::exit(1) };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
Err(_) => panic!("failed to fork"),
|
Err(_) => panic!("failed to fork"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
cg.delete();
|
cg.delete().unwrap();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,31 @@
|
|||||||
//! Integration test about setting resources using `apply()`
|
// Copyright (c) 2018 Levente Kurusa
|
||||||
extern crate cgroups;
|
// Copyright (c) 2020 And Group
|
||||||
|
//
|
||||||
|
// SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
//
|
||||||
|
|
||||||
use cgroups::{Cgroup, Resources, PidResources};
|
//! Integration test about setting resources using `apply()`
|
||||||
use cgroups::pid::{PidController, PidMax};
|
use cgroups_rs::pid::PidController;
|
||||||
|
use cgroups_rs::{Cgroup, MaxValue, PidResources, Resources};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn pid_resources() {
|
fn pid_resources() {
|
||||||
let hier = cgroups::hierarchies::V1::new();
|
let h = cgroups_rs::hierarchies::auto();
|
||||||
let cg = Cgroup::new(&hier, String::from("pid_resources"));
|
let cg = Cgroup::new(h, String::from("pid_resources"));
|
||||||
{
|
{
|
||||||
let res = Resources {
|
let res = Resources {
|
||||||
pid: PidResources {
|
pid: PidResources {
|
||||||
update_values: true,
|
maximum_number_of_processes: Some(MaxValue::Value(512)),
|
||||||
maximum_number_of_processes: PidMax::Value(512),
|
|
||||||
},
|
},
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
cg.apply(&res);
|
cg.apply(&res).unwrap();
|
||||||
|
|
||||||
/* verify */
|
// verify
|
||||||
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
let pidcontroller: &PidController = cg.controller_of().unwrap();
|
||||||
assert_eq!(pidcontroller.get_pid_max(), Some(PidMax::Value(512)));
|
let pid_max = pidcontroller.get_pid_max();
|
||||||
|
assert!(pid_max.is_ok());
|
||||||
|
assert_eq!(pid_max.unwrap(), MaxValue::Value(512));
|
||||||
}
|
}
|
||||||
cg.delete();
|
cg.delete().unwrap();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
|
#
|
||||||
|
# Copyright (c) 2018 Levente Kurusa
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
#
|
||||||
|
|
||||||
CONTROL_GROUPS=`cargo test -- --list 2>/dev/null | egrep 'test$' | egrep -v '^src' | cut -d':' -f1`
|
CONTROL_GROUPS=`cargo test -- --list 2>/dev/null | egrep 'test$' | egrep -v '^src' | cut -d':' -f1`
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
|
#
|
||||||
|
# Copyright (c) 2018 Levente Kurusa
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0 or MIT
|
||||||
|
#
|
||||||
|
|
||||||
CONTROL_GROUPS=`cargo test -- --list 2>/dev/null | egrep 'test$' | egrep -v '^src' | cut -d':' -f1`
|
CONTROL_GROUPS=`cargo test -- --list 2>/dev/null | egrep 'test$' | egrep -v '^src' | cut -d':' -f1`
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user