Skip to content

Commit 3edda1a

Browse files
authored
Rollup merge of rust-lang#92697 - the8472:cgroups, r=joshtriplett
Use cgroup quotas for calculating `available_parallelism` Automated tests for this are possible but would require a bunch of assumptions. It requires root + a recent kernel, systemd and maybe docker. And even then it would need a helper binary since the test has to run in a separate process. Limitations * only supports cgroup v2 and assumes it's mounted under `/sys/fs/cgroup` * procfs must be available * the quota gets mixed into `sched_getaffinity`, so if the latter doesn't work then quota information gets ignored too Manually tested via ``` // spawn a new cgroup scope for the current user $ sudo systemd-run -p CPUQuota="300%" --uid=$(id -u) -tdS // quota.rs #![feature(available_parallelism)] fn main() { println!("{:?}", std::thread::available_parallelism()); // prints Ok(3) } ``` strace: ``` sched_getaffinity(3041643, 32, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]) = 32 openat(AT_FDCWD, "/proc/self/cgroup", O_RDONLY|O_CLOEXEC) = 3 statx(0, NULL, AT_STATX_SYNC_AS_STAT, STATX_ALL, NULL) = -1 EFAULT (Bad address) statx(3, "", AT_STATX_SYNC_AS_STAT|AT_EMPTY_PATH, STATX_ALL, {stx_mask=STATX_BASIC_STATS|STATX_MNT_ID, stx_attributes=0, stx_mode=S_IFREG|0444, stx_size=0, ...}) = 0 lseek(3, 0, SEEK_CUR) = 0 read(3, "0::/system.slice/run-u31477.serv"..., 128) = 36 read(3, "", 92) = 0 close(3) = 0 statx(AT_FDCWD, "/sys/fs/cgroup/system.slice/run-u31477.service/cgroup.controllers", AT_STATX_SYNC_AS_STAT, STATX_ALL, {stx_mask=STATX_BASIC_STATS|STATX_MNT_ID, stx_attributes=0, stx_mode=S_IFREG|0444, stx_size=0, ...}) = 0 openat(AT_FDCWD, "/sys/fs/cgroup/system.slice/run-u31477.service/cpu.max", O_RDONLY|O_CLOEXEC) = 3 statx(3, "", AT_STATX_SYNC_AS_STAT|AT_EMPTY_PATH, STATX_ALL, {stx_mask=STATX_BASIC_STATS|STATX_MNT_ID, stx_attributes=0, stx_mode=S_IFREG|0644, stx_size=0, ...}) = 0 lseek(3, 0, SEEK_CUR) = 0 read(3, "300000 100000\n", 20) = 14 read(3, "", 6) = 0 close(3) = 0 openat(AT_FDCWD, "/sys/fs/cgroup/system.slice/cpu.max", O_RDONLY|O_CLOEXEC) = 3 statx(3, "", AT_STATX_SYNC_AS_STAT|AT_EMPTY_PATH, STATX_ALL, {stx_mask=STATX_BASIC_STATS|STATX_MNT_ID, stx_attributes=0, stx_mode=S_IFREG|0644, stx_size=0, ...}) = 0 lseek(3, 0, SEEK_CUR) = 0 read(3, "max 100000\n", 20) = 11 read(3, "", 9) = 0 close(3) = 0 openat(AT_FDCWD, "/sys/fs/cgroup/cpu.max", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) sched_getaffinity(0, 128, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]) = 40 ``` r? `@joshtriplett` cc `@yoshuawuyts` Tracking issue and previous discussion: rust-lang#74479
2 parents 06460fe + e18abbf commit 3edda1a

File tree

2 files changed

+86
-4
lines changed

2 files changed

+86
-4
lines changed

library/std/src/sys/unix/thread.rs

+82-3
Original file line numberDiff line numberDiff line change
@@ -279,10 +279,15 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
279279
))] {
280280
#[cfg(any(target_os = "android", target_os = "linux"))]
281281
{
282+
let quota = cgroup2_quota().max(1);
282283
let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
283-
if unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) } == 0 {
284-
let count = unsafe { libc::CPU_COUNT(&set) };
285-
return Ok(unsafe { NonZeroUsize::new_unchecked(count as usize) });
284+
unsafe {
285+
if libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) == 0 {
286+
let count = libc::CPU_COUNT(&set) as usize;
287+
let count = count.min(quota);
288+
// SAFETY: affinity mask can't be empty and the quota gets clamped to a minimum of 1
289+
return Ok(NonZeroUsize::new_unchecked(count));
290+
}
286291
}
287292
}
288293
match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
@@ -368,6 +373,80 @@ pub fn available_parallelism() -> io::Result<NonZeroUsize> {
368373
}
369374
}
370375

376+
/// Returns cgroup CPU quota in core-equivalents, rounded down, or usize::MAX if the quota cannot
377+
/// be determined or is not set.
378+
#[cfg(any(target_os = "android", target_os = "linux"))]
379+
fn cgroup2_quota() -> usize {
380+
use crate::ffi::OsString;
381+
use crate::fs::{try_exists, File};
382+
use crate::io::Read;
383+
use crate::os::unix::ffi::OsStringExt;
384+
use crate::path::PathBuf;
385+
386+
let mut quota = usize::MAX;
387+
388+
let _: Option<()> = try {
389+
let mut buf = Vec::with_capacity(128);
390+
// find our place in the cgroup hierarchy
391+
File::open("/proc/self/cgroup").ok()?.read_to_end(&mut buf).ok()?;
392+
let cgroup_path = buf
393+
.split(|&c| c == b'\n')
394+
.filter_map(|line| {
395+
let mut fields = line.splitn(3, |&c| c == b':');
396+
// expect cgroupv2 which has an empty 2nd field
397+
if fields.nth(1) != Some(b"") {
398+
return None;
399+
}
400+
let path = fields.last()?;
401+
// skip leading slash
402+
Some(path[1..].to_owned())
403+
})
404+
.next()?;
405+
let cgroup_path = PathBuf::from(OsString::from_vec(cgroup_path));
406+
407+
let mut path = PathBuf::with_capacity(128);
408+
let mut read_buf = String::with_capacity(20);
409+
410+
let cgroup_mount = "/sys/fs/cgroup";
411+
412+
path.push(cgroup_mount);
413+
path.push(&cgroup_path);
414+
415+
path.push("cgroup.controllers");
416+
417+
// skip if we're not looking at cgroup2
418+
if matches!(try_exists(&path), Err(_) | Ok(false)) {
419+
return usize::MAX;
420+
};
421+
422+
path.pop();
423+
424+
while path.starts_with(cgroup_mount) {
425+
path.push("cpu.max");
426+
427+
read_buf.clear();
428+
429+
if File::open(&path).and_then(|mut f| f.read_to_string(&mut read_buf)).is_ok() {
430+
let raw_quota = read_buf.lines().next()?;
431+
let mut raw_quota = raw_quota.split(' ');
432+
let limit = raw_quota.next()?;
433+
let period = raw_quota.next()?;
434+
match (limit.parse::<usize>(), period.parse::<usize>()) {
435+
(Ok(limit), Ok(period)) => {
436+
quota = quota.min(limit / period);
437+
}
438+
_ => {}
439+
}
440+
}
441+
442+
path.pop(); // pop filename
443+
path.pop(); // pop dir
444+
}
445+
};
446+
447+
quota
448+
}
449+
371450
#[cfg(all(
372451
not(target_os = "linux"),
373452
not(target_os = "freebsd"),

library/std/src/thread/mod.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1524,7 +1524,10 @@ fn _assert_sync_and_send() {
15241524
///
15251525
/// On Linux:
15261526
/// - It may overcount the amount of parallelism available when limited by a
1527-
/// process-wide affinity mask, or when affected by cgroup limits.
1527+
/// process-wide affinity mask or cgroup quotas and cgroup2 fs or `sched_getaffinity()` can't be
1528+
/// queried, e.g. due to sandboxing.
1529+
/// - It may undercount the amount of parallelism if the current thread's affinity mask
1530+
/// does not reflect the process' cpuset, e.g. due to pinned threads.
15281531
///
15291532
/// On all targets:
15301533
/// - It may overcount the amount of parallelism available when running in a VM

0 commit comments

Comments
 (0)