| 1 |
"""Diagnostic utilities to probe container cgroup behavior during development and testing (both manual and integration).""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import dataclasses |
| 6 |
import enum |
| 7 |
import json |
| 8 |
import os |
| 9 |
import pathlib |
| 10 |
import pwd |
| 11 |
import typing as t |
| 12 |
|
| 13 |
from ..io import ( |
| 14 |
read_text_file, |
| 15 |
write_text_file, |
| 16 |
) |
| 17 |
|
| 18 |
from ..util import ( |
| 19 |
display, |
| 20 |
ANSIBLE_TEST_TARGET_ROOT, |
| 21 |
) |
| 22 |
|
| 23 |
from ..config import ( |
| 24 |
EnvironmentConfig, |
| 25 |
) |
| 26 |
|
| 27 |
from ..docker_util import ( |
| 28 |
LOGINUID_NOT_SET, |
| 29 |
docker_exec, |
| 30 |
get_docker_info, |
| 31 |
get_podman_remote, |
| 32 |
require_docker, |
| 33 |
) |
| 34 |
|
| 35 |
from ..host_configs import ( |
| 36 |
DockerConfig, |
| 37 |
) |
| 38 |
|
| 39 |
from ..cgroup import ( |
| 40 |
CGroupEntry, |
| 41 |
CGroupPath, |
| 42 |
MountEntry, |
| 43 |
MountType, |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
class CGroupState(enum.Enum): |
| 48 |
"""The expected state of a cgroup related mount point.""" |
| 49 |
|
| 50 |
HOST = enum.auto() |
| 51 |
PRIVATE = enum.auto() |
| 52 |
SHADOWED = enum.auto() |
| 53 |
|
| 54 |
|
| 55 |
@dataclasses.dataclass(frozen=True) |
| 56 |
class CGroupMount: |
| 57 |
"""Details on a cgroup mount point that is expected to be present in the container.""" |
| 58 |
|
| 59 |
path: str |
| 60 |
type: t.Optional[str] |
| 61 |
writable: t.Optional[bool] |
| 62 |
state: t.Optional[CGroupState] |
| 63 |
|
| 64 |
def __post_init__(self): |
| 65 |
assert pathlib.PurePosixPath(self.path).is_relative_to(CGroupPath.ROOT) |
| 66 |
|
| 67 |
if self.type is None: |
| 68 |
assert self.state is None |
| 69 |
elif self.type == MountType.TMPFS: |
| 70 |
assert self.writable is True |
| 71 |
assert self.state is None |
| 72 |
else: |
| 73 |
assert self.type in (MountType.CGROUP_V1, MountType.CGROUP_V2) |
| 74 |
assert self.state is not None |
| 75 |
|
| 76 |
|
| 77 |
def check_container_cgroup_status(args: EnvironmentConfig, config: DockerConfig, container_name: str, expected_mounts: tuple[CGroupMount, ...]) -> None: |
| 78 |
"""Check the running container to examine the state of the cgroup hierarchies.""" |
| 79 |
cmd = ['sh', '-c', 'cat /proc/1/cgroup && echo && cat /proc/1/mountinfo'] |
| 80 |
|
| 81 |
stdout = docker_exec(args, container_name, cmd, capture=True)[0] |
| 82 |
cgroups_stdout, mounts_stdout = stdout.split('\n\n') |
| 83 |
|
| 84 |
cgroups = CGroupEntry.loads(cgroups_stdout) |
| 85 |
mounts = MountEntry.loads(mounts_stdout) |
| 86 |
|
| 87 |
mounts = tuple(mount for mount in mounts if mount.path.is_relative_to(CGroupPath.ROOT)) |
| 88 |
|
| 89 |
mount_cgroups: dict[MountEntry, CGroupEntry] = {} |
| 90 |
probe_paths: dict[pathlib.PurePosixPath, t.Optional[str]] = {} |
| 91 |
|
| 92 |
for cgroup in cgroups: |
| 93 |
if cgroup.subsystem: |
| 94 |
mount = ([mount for mount in mounts if |
| 95 |
mount.type == MountType.CGROUP_V1 and |
| 96 |
mount.path.is_relative_to(cgroup.root_path) and |
| 97 |
cgroup.full_path.is_relative_to(mount.path) |
| 98 |
] or [None])[-1] |
| 99 |
else: |
| 100 |
mount = ([mount for mount in mounts if |
| 101 |
mount.type == MountType.CGROUP_V2 and |
| 102 |
mount.path == cgroup.root_path |
| 103 |
] or [None])[-1] |
| 104 |
|
| 105 |
if mount: |
| 106 |
mount_cgroups[mount] = cgroup |
| 107 |
|
| 108 |
for mount in mounts: |
| 109 |
probe_paths[mount.path] = None |
| 110 |
|
| 111 |
if (cgroup := mount_cgroups.get(mount)) and cgroup.full_path != mount.path: # child of mount.path |
| 112 |
probe_paths[cgroup.full_path] = None |
| 113 |
|
| 114 |
probe_script = read_text_file(os.path.join(ANSIBLE_TEST_TARGET_ROOT, 'setup', 'probe_cgroups.py')) |
| 115 |
probe_command = [config.python.path, '-', f'{container_name}-probe'] + [str(path) for path in probe_paths] |
| 116 |
probe_results = json.loads(docker_exec(args, container_name, probe_command, capture=True, data=probe_script)[0]) |
| 117 |
|
| 118 |
for path in probe_paths: |
| 119 |
probe_paths[path] = probe_results[str(path)] |
| 120 |
|
| 121 |
remaining_mounts: dict[pathlib.PurePosixPath, MountEntry] = {mount.path: mount for mount in mounts} |
| 122 |
results: dict[pathlib.PurePosixPath, tuple[bool, str]] = {} |
| 123 |
|
| 124 |
for expected_mount in expected_mounts: |
| 125 |
expected_path = pathlib.PurePosixPath(expected_mount.path) |
| 126 |
|
| 127 |
if not (actual_mount := remaining_mounts.pop(expected_path, None)): |
| 128 |
results[expected_path] = (False, 'not mounted') |
| 129 |
continue |
| 130 |
|
| 131 |
actual_mount_write_error = probe_paths[actual_mount.path] |
| 132 |
actual_mount_errors = [] |
| 133 |
|
| 134 |
if cgroup := mount_cgroups.get(actual_mount): |
| 135 |
if expected_mount.state == CGroupState.SHADOWED: |
| 136 |
actual_mount_errors.append('unexpected cgroup association') |
| 137 |
|
| 138 |
if cgroup.root_path == cgroup.full_path and expected_mount.state == CGroupState.HOST: |
| 139 |
results[cgroup.root_path.joinpath('???')] = (False, 'missing cgroup') |
| 140 |
|
| 141 |
if cgroup.full_path == actual_mount.path: |
| 142 |
if cgroup.root_path != cgroup.full_path and expected_mount.state == CGroupState.PRIVATE: |
| 143 |
actual_mount_errors.append('unexpected mount') |
| 144 |
else: |
| 145 |
cgroup_write_error = probe_paths[cgroup.full_path] |
| 146 |
cgroup_errors = [] |
| 147 |
|
| 148 |
if expected_mount.state == CGroupState.SHADOWED: |
| 149 |
cgroup_errors.append('unexpected cgroup association') |
| 150 |
|
| 151 |
if cgroup.root_path != cgroup.full_path and expected_mount.state == CGroupState.PRIVATE: |
| 152 |
cgroup_errors.append('unexpected cgroup') |
| 153 |
|
| 154 |
if cgroup_write_error: |
| 155 |
cgroup_errors.append(cgroup_write_error) |
| 156 |
|
| 157 |
if cgroup_errors: |
| 158 |
results[cgroup.full_path] = (False, f'directory errors: {", ".join(cgroup_errors)}') |
| 159 |
else: |
| 160 |
results[cgroup.full_path] = (True, 'directory (writable)') |
| 161 |
elif expected_mount.state not in (None, CGroupState.SHADOWED): |
| 162 |
actual_mount_errors.append('missing cgroup association') |
| 163 |
|
| 164 |
if actual_mount.type != expected_mount.type and expected_mount.type is not None: |
| 165 |
actual_mount_errors.append(f'type not {expected_mount.type}') |
| 166 |
|
| 167 |
if bool(actual_mount_write_error) == expected_mount.writable: |
| 168 |
actual_mount_errors.append(f'{actual_mount_write_error or "writable"}') |
| 169 |
|
| 170 |
if actual_mount_errors: |
| 171 |
results[actual_mount.path] = (False, f'{actual_mount.type} errors: {", ".join(actual_mount_errors)}') |
| 172 |
else: |
| 173 |
results[actual_mount.path] = (True, f'{actual_mount.type} ({actual_mount_write_error or "writable"})') |
| 174 |
|
| 175 |
for remaining_mount in remaining_mounts.values(): |
| 176 |
remaining_mount_write_error = probe_paths[remaining_mount.path] |
| 177 |
|
| 178 |
results[remaining_mount.path] = (False, f'unexpected {remaining_mount.type} mount ({remaining_mount_write_error or "writable"})') |
| 179 |
|
| 180 |
identity = get_identity(args, config, container_name) |
| 181 |
messages: list[tuple[pathlib.PurePosixPath, bool, str]] = [(path, result[0], result[1]) for path, result in sorted(results.items())] |
| 182 |
message = '\n'.join(f'{"PASS" if result else "FAIL"}: {path} -> {message}' for path, result, message in messages) |
| 183 |
|
| 184 |
display.info(f'>>> Container: {identity}\n{message.rstrip()}') |
| 185 |
|
| 186 |
if args.dev_probe_cgroups: |
| 187 |
write_text_file(os.path.join(args.dev_probe_cgroups, f'{identity}.log'), message) |
| 188 |
|
| 189 |
|
| 190 |
def get_identity(args: EnvironmentConfig, config: DockerConfig, container_name: str) -> str: |
| 191 |
"""Generate and return an identity string to use when logging test results.""" |
| 192 |
engine = require_docker().command |
| 193 |
|
| 194 |
try: |
| 195 |
loginuid = int(read_text_file('/proc/self/loginuid')) |
| 196 |
except FileNotFoundError: |
| 197 |
loginuid = LOGINUID_NOT_SET |
| 198 |
|
| 199 |
user = pwd.getpwuid(os.getuid()).pw_name |
| 200 |
login_user = user if loginuid == LOGINUID_NOT_SET else pwd.getpwuid(loginuid).pw_name |
| 201 |
remote = engine == 'podman' and get_podman_remote() |
| 202 |
|
| 203 |
tags = ( |
| 204 |
config.name, |
| 205 |
engine, |
| 206 |
f'cgroup={config.cgroup.value}@{get_docker_info(args).cgroup_version}', |
| 207 |
f'remote={remote}', |
| 208 |
f'user={user}', |
| 209 |
f'loginuid={login_user}', |
| 210 |
container_name, |
| 211 |
) |
| 212 |
|
| 213 |
return '|'.join(tags) |