|
| 1 | +import os |
| 2 | +import pytest |
| 3 | +import sys |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +# In privileged containers, we expect the following |
| 8 | +# cgroupv1 is disabled |
| 9 | +# cgroupv2 is enabled and mounted on /sys/fs/cgroup |
| 10 | +# the user running tests has read and write access to the cgroup subtree |
| 11 | +# memory and cpu controllers are enabled |
| 12 | + |
| 13 | +_MOUNT_FILE_PATH = "/proc/mounts" |
| 14 | +_CGROUP2_PATH = "/sys/fs/cgroup" |
| 15 | +_CTRL_FILE = "cgroup.controllers" |
| 16 | +_EXPECTED_CTRLS = ["memory", "cpu"] |
| 17 | + |
| 18 | + |
| 19 | +# mount file format: |
| 20 | +# cgroup /sys/fs/cgroup cgroup2 rw,nosuid,nodev,noexec,relatime 0 0 |
| 21 | +def test_only_cgroupv2_mounted_rw(): |
| 22 | + found_cgroupv2 = False |
| 23 | + found_cgroupv1 = False |
| 24 | + with open(Path(_MOUNT_FILE_PATH)) as f: |
| 25 | + for line in f: |
| 26 | + c = line.split() |
| 27 | + found_cgroupv2 = found_cgroupv2 or ( |
| 28 | + c[2] == "cgroup2" and c[1] == _CGROUP2_PATH and "rw" in c[3] |
| 29 | + ) |
| 30 | + found_cgroupv1 = found_cgroupv1 or (c[2] == "cgroup") |
| 31 | + assert found_cgroupv2 and not found_cgroupv1 |
| 32 | + |
| 33 | + |
| 34 | +def test_cgroupv2_rw_for_test_user(): |
| 35 | + assert os.access(_CGROUP2_PATH, os.R_OK) and os.access(_CGROUP2_PATH, os.W_OK) |
| 36 | + |
| 37 | + |
| 38 | +def test_cgroupv2_controllers_enabled(): |
| 39 | + with open(os.path.join(_CGROUP2_PATH, _CTRL_FILE)) as f: |
| 40 | + enabled = f.readlines() |
| 41 | + assert len(enabled) == 1 |
| 42 | + enabled_ctrls = enabled[0].split() |
| 43 | + for expected_ctrl in _EXPECTED_CTRLS: |
| 44 | + assert ( |
| 45 | + expected_ctrl in enabled_ctrls |
| 46 | + ), f"Expected {expected_ctrl} to be enabled for cgroups2, but it is not" |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + sys.exit(pytest.main(["-v", __file__])) |
0 commit comments