Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Doc/library/os.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6281,7 +6281,7 @@ Miscellaneous System Information

Get the number of logical CPUs usable by the calling thread of the **current
process**. Returns ``None`` if undetermined. It can be less than
:func:`cpu_count` depending on the CPU affinity.
:func:`cpu_count` depending on the CPU affinity and cgroups settings.
Comment thread
itamarst marked this conversation as resolved.
Resolved

The :func:`cpu_count` function can be used to get the number of logical CPUs
in the **system**.
Expand All @@ -6293,6 +6293,9 @@ Miscellaneous System Information

.. versionadded:: 3.13

.. versionchanged:: 3.16
Previously cgroups CPU limits were not used.


.. function:: sysconf(name, /)

Expand Down
129 changes: 128 additions & 1 deletion Lib/os.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@

from _collections_abc import _check_methods

lazy import builtins
lazy import math

GenericAlias = type(list[int])

_names = sys.builtin_module_names
Expand Down Expand Up @@ -1225,6 +1228,124 @@ def add_dll_directory(path):
)


if sys.platform == "linux":
def _unquote_mount_path(path):
"""Decode quoted characters in /etc/fstab, /proc/mounts, and the like.

See https://man7.org/linux/man-pages/man5/fstab.5.html
"""
for quoted, value in [
(r"\040", " "),
(r"\011", "\t"),
(r"\012", "\n"),
(r"\134", "\\"),
]:
path = path.replace(quoted, value)
return path

def _get_cgroup2_mount_point():
if path.exists("/sys/fs/cgroup/cgroup.controllers"):
return "/sys/fs/cgroup"

try:
with builtins.open("/proc/mounts") as fp:
for line in fp:
parts = line.split()
_, mount_dir, mount_type, *_ = parts
if mount_type == "cgroup2":
return _unquote_mount_path(mount_dir)
except OSError:
return None


def _parse_cgroup2_cpu_max(filename):
"""
Returns None if file not found or a parsing error, or a number of cores
if successful.
"""
try:
with builtins.open(filename) as fp:
line = fp.readline()
except OSError:
return None

parts = line.split()
if len(parts) != 2:
return None

if parts[0] == "max":
return cpu_count()

try:
quota = int(parts[0])
period = int(parts[1])
except ValueError:
return None

# Rounds up in order to saturate CPUs if the quota is fractional:
return max(math.ceil(quota / period), 1)
Comment on lines +1285 to +1286

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can avoid floating point numbers and math.ceil() code with:

Suggested change
# Rounds up in order to saturate CPUs if the quota is fractional:
import math
return max(math.ceil(quota / period), 1)
# Rounds up in order to saturate CPUs if the quota is fractional:
count = (quota + (period - 1)) // period
return max(count, 1)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I felt the float version was more readable, but can change if you want.



def _cpu_count_cgroups():
sched = sched_getscheduler(0)
if sched in (SCHED_FIFO, SCHED_RR, SCHED_DEADLINE):
return None

cgroup_subpath = None
try:
fp = builtins.open("/proc/self/cgroup")
except OSError:
return None
with fp:
for line in fp:
# Cgroups v2 format; see cgroups(7) man page, section on
# /proc/pid/cgroups
if line.startswith("0::/"):
cgroup_subpath = line[3:].rstrip("\n")

if cgroup_subpath is None:
return None

cgroup2_mount_point = _get_cgroup2_mount_point()
if cgroup2_mount_point is None:
return None

# Traverse nested controllers, from child to parent, looking for a CPU
# limit:
cpu_quota = None
while True:
cpu_max_filename = path.join(
cgroup2_mount_point,
cgroup_subpath[1:],
"cpu.max"
)
num_cpus = _parse_cgroup2_cpu_max(cpu_max_filename)
if num_cpus is not None:
# Per the docs
# (https://docs.kernel.org/admin-guide/cgroup-v2.html): "When a
# controller is enabled on a nested cgroup, it always restricts
# the resource distribution further. The restrictions set
# closer to the root in the hierarchy can not be overridden
# from further away." So we have to pick the minimum.
if cpu_quota is None:
cpu_quota = num_cpus
cpu_quota = min(num_cpus, cpu_quota)
if cpu_quota == 1:
# Can't get any lower than 1
return 1

# Move on to the parent cgroup, if any:
if cgroup_subpath == "/":
break

cgroup_subpath = path.dirname(cgroup_subpath)

return cpu_quota
else:
def _cpu_count_cgroups():
return None


if _exists('sched_getaffinity') and sys._get_cpu_count_config() < 0:
def process_cpu_count():
"""
Expand All @@ -1233,7 +1354,13 @@ def process_cpu_count():
Return the number of logical CPUs usable by the calling thread of the
Comment thread
itamarst marked this conversation as resolved.
Resolved
current process. Return None if indeterminable.
"""
return len(sched_getaffinity(0))
affinity_count = len(sched_getaffinity(0))
count = _cpu_count_cgroups()
if count is None:
count = cpu_count()
if count is None:
count = affinity_count
return min(affinity_count, count)
else:
# Just an alias to cpu_count() (same docstring)
process_cpu_count = cpu_count
149 changes: 149 additions & 0 deletions Lib/test/test_os/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# portable than they had been thought to be.

import asyncio
import builtins
import codecs
import contextlib
import decimal
Expand All @@ -28,6 +29,7 @@
import time
import types
import unittest
import unittest.mock
import uuid
import warnings
from test import support
Expand Down Expand Up @@ -4682,6 +4684,153 @@ def test_process_cpu_count_affinity(self):
affinity2 = os.process_cpu_count()
self.assertEqual(affinity2, affinity1 - 1)

@unittest.skipUnless(sys.platform == "linux", "Requires Linux")
def test_missing_cgroups_files(self):
original_open = builtins.open
original_exists = os.path.exists

def force_proc_mounts_parsing_exists(path):
if path == "/sys/fs/cgroup/cgroup.controllers":
return False
return original_exists(path)

with unittest.mock.patch(
"os.path.exists",
force_proc_mounts_parsing_exists
):
# /proc/mounts parsing correctly identifies where cgroup sysfs is
# mounted
sysfs_cgroup_path = os._get_cgroup2_mount_point()
if sysfs_cgroup_path is None:
# 99% of the time will be /sys/fs/cgroup, so if we failed to
# find it, that better not exist!
self.assertFalse(original_exists("/sys/fs/cgroup"))
else:
self.assertTrue(
original_exists(
os.path.join(sysfs_cgroup_path, "cgroup.controllers")
)
)

for path_to_fail in [
"/proc/self/cgroup",
"/proc/mounts",
os._get_cgroup2_mount_point()
]:
def might_fail_to_open(path, *args, **kwargs):
if path.startswith(path_to_fail):
raise OSError("disabled for test")
else:
return original_open(path, *args, **kwargs)
with unittest.mock.patch("builtins.open", might_fail_to_open):
self.assertIsNone(os._cpu_count_cgroups())

@unittest.skipUnless(sys.platform == "linux", "Requires Linux")
def test_cpu_count_parse_cpu_max(self):
for cpu_max_contents, expected_n_cpus in [
# max means all cores
("max 100000", os.cpu_count()),
# garbage
("garbage garbage", None),
# too many numbers
("123 123 123", None),
# less than one core means one core
("1000 100000", 1),
# One or more cores, rounding up:
("100000 100000", 1),
("200000 100000", 2),
("230000 100000", 3),
# Divide by quota:
("100000 50000", 2),
]:
with tempfile.NamedTemporaryFile("w") as f:
f.write(cpu_max_contents)
f.flush()
result = os._parse_cgroup2_cpu_max(f.name)
self.assertEqual(result, expected_n_cpus)

@unittest.skipUnless(
sys.platform == "linux" and shutil.which("systemd-run") is not None,
"testing cgroups requires Linux with systemd-run",
)
def test_process_cpu_count_cgroups_end_to_end(self):
"""``os.process_cpu_count()`` respects cgroups v2 limits."""
base_count = os.process_cpu_count()
if base_count is None:
self.skipTest("Could not determine the number of CPUs")
if base_count < 2:
self.skipTest("require at least 2 CPU cores to test")

def get_systemd_args(
num_cpus,
cpu_period_ms=None,
python_code="import os; print(os.process_cpu_count())"
):
result = [
"systemd-run",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like this test. It changes systemd settings, even temporarily.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't really change systemd settings. It creates a new scope: "The main purpose of scope units is grouping worker processes of a system service for organization and for managing resources." per the man page (https://www.freedesktop.org/software/systemd/man/latest/systemd.scope.html).

So this creates a new scope, with specific CPU quota just for those processes, in the scope, by creating a new cgroup.

So this is essentially like doing docker run: it runs a process under a new cgroup. But unlike Docker you don't have have to jump through hoops to access the host filesystem, so it's mechanically simpler.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I meant is that it still creates a transient systemd config. What about systems that aren't on systemd? I believe Alpine doesn't have systemd but alpine docker images are quite used right? (or maybe I misremember).

What I meant is: would it be possible to mock the result of open() instead without invoking systemd at all? And only skip the test when the files don't exist for instance (and also exercise the code paths where the file doesn't exist indeed or raises OSError)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's very useful to have end-to-end tests, when possible, otherwise it's easy to end up in a situation where the mocks/fakes diverge from reality.

But yeah there's the error paths too. And perhaps some CPython devs use non-systemd Linux, too, though CI at least will catch problems.

So maybe an additional set of mock/fake-based tests? And maybe the end-to-end test with systemd can be a bit smaller.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I meant is: would it be possible to mock the result of open() instead without invoking systemd at all?

Hum. If we decide to add tests mocking open(), I would still prefer to also have the systemd-run "integration tests". I already saw major bugs in code tested only by mocks. When you mock everything, you don't test the implementation anymore, but you test the mocks themselves :-D So the two kinds of tests are useful and have different purposes.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added some more tests that talk to the underlying functions directly, and exercise the OSError paths. But I kept (most) of the end-to-end tests too. Let me know if there's more test coverage you want.

"--user",
# Technically only necessary for nested systemd-run, where we
# get the same auto-generat()ed unit name:
f"--unit=python-tests-{os.urandom(16).hex()}",
"--scope",
"--quiet",
"--property",
f"CPUQuota={int(100 * num_cpus)}%",
]
if cpu_period_ms is not None:
result.extend([
"--property",
f"CPUQuotaPeriodSec={cpu_period_ms}ms"
])
result.extend([
"--",
sys.executable,
"-c",
python_code,
])
return result

def run_and_get_int(command_args):
return int(
subprocess.check_output(command_args, encoding="utf-8").strip()
)

# Base setting of number of cores:
result = run_and_get_int(get_systemd_args(1))
self.assertEqual(result, 1)
result = run_and_get_int(get_systemd_args(2))
self.assertEqual(result, 2)

# Changes to the quota's period are taken into account:
result = run_and_get_int(get_systemd_args(1, cpu_period_ms=30))
self.assertEqual(result, 1)

# Result is minimum of sched affinity and quota:
for affinity_cores, cgroups_cores, expected in [
(1, 2, 1),
(2, 1, 1),
(2, 2, 2),
]:
code = f"""\
import os
mask = os.sched_getaffinity(0)
os.sched_setaffinity(0, list(mask)[:{affinity_cores}])
print(os.process_cpu_count())
"""
result = run_and_get_int(
get_systemd_args(cgroups_cores, python_code=code)
)
self.assertEqual(result, expected)

@unittest.skipUnless(
sys.platform == "linux", "Linux-specific functionality",
)
def test_unquote_mount_path(self):
"""``os._unquote_mount_path()`` decodes correctly."""
original_path = "/foo/bar\\\n \t"
encoded_path = r"/foo/bar\134\012\040\011"
self.assertEqual(os._unquote_mount_path(encoded_path), original_path)


# FD inheritance check is only useful for systems with process support.
@support.requires_subprocess()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Add support for cgroups v2 CPU quotas on Linux to :func:`os.process_cpu_count`.
This includes CPU limits set by Docker, Kubernetes, and other tools that rely on
cgroups.
Loading