diff --git a/Doc/library/os.rst b/Doc/library/os.rst index fff27b48ae989c..f09d6ef31e3d1f 100644 --- a/Doc/library/os.rst +++ b/Doc/library/os.rst @@ -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. The :func:`cpu_count` function can be used to get the number of logical CPUs in the **system**. @@ -6293,6 +6293,9 @@ Miscellaneous System Information .. versionadded:: 3.13 + .. versionchanged:: 3.16 + Previously cgroups CPU limits were not used. + .. function:: sysconf(name, /) diff --git a/Lib/os.py b/Lib/os.py index f999150150ccba..cad7fdd9985c3c 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -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 @@ -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) + + + 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(): """ @@ -1233,7 +1354,13 @@ def process_cpu_count(): Return the number of logical CPUs usable by the calling thread of the 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 diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index 8b6b7deb65b88b..85b3fd6ddc65ae 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -3,6 +3,7 @@ # portable than they had been thought to be. import asyncio +import builtins import codecs import contextlib import decimal @@ -28,6 +29,7 @@ import time import types import unittest +import unittest.mock import uuid import warnings from test import support @@ -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", + "--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() diff --git a/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst new file mode 100644 index 00000000000000..0c9d10ff2b3790 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-23-17-03-23.gh-issue-149452.zKhaUP.rst @@ -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.