Debian Codegraph @

test/integration/targets/ansible-test-container/runme.py

raw ◀ ▶
1 Debian patch touch this file
•1 #!/usr/bin/env python3
2 """Test suite used to verify ansible-test is able to run its containers on various container hosts."""
3
4 from __future__ import annotations
5
6 import abc
7 import dataclasses
8 import datetime
9 import errno
10 import functools
11 import json
12 import os
13 import pathlib
14 import pwd
15 import secrets
16 import shlex
17 import shutil
18 import signal
19 import subprocess
20 import sys
21 import time
22 import typing as t
23
24 UNPRIVILEGED_USER_NAME = 'ansible-test'
25 CGROUP_ROOT = pathlib.Path('/sys/fs/cgroup')
26 CGROUP_SYSTEMD = CGROUP_ROOT / 'systemd'
27 LOG_PATH = pathlib.Path('/tmp/results')
28
29 # The value of /proc/*/loginuid when it is not set.
30 # It is a reserved UID, which is the maximum 32-bit unsigned integer value.
31 # See: https://access.redhat.com/solutions/25404
32 LOGINUID_NOT_SET = 4294967295
33
34 UID = os.getuid()
35
36 try:
37 LOGINUID = int(pathlib.Path('/proc/self/loginuid').read_text())
38 LOGINUID_MISMATCH = LOGINUID != LOGINUID_NOT_SET and LOGINUID != UID
39 except FileNotFoundError:
40 LOGINUID = None
41 LOGINUID_MISMATCH = False
42
43
44 def main() -> None:
45 """Main program entry point."""
46 display.section('Startup check')
47
48 try:
49 bootstrap_type = pathlib.Path('/etc/ansible-test.bootstrap').read_text().strip()
50 except FileNotFoundError:
51 bootstrap_type = 'undefined'
52
53 display.info(f'Bootstrap type: {bootstrap_type}')
54
55 if bootstrap_type != 'remote':
56 display.warning('Skipping destructive test on system which is not an ansible-test remote provisioned instance.')
57 return
58
59 display.info(f'UID: {UID} / {LOGINUID}')
60
61 if UID != 0:
62 raise Exception('This test must be run as root.')
63
64 if not LOGINUID_MISMATCH:
65 if LOGINUID is None:
66 display.warning('Tests involving loginuid mismatch will be skipped on this host since it does not have audit support.')
67 elif LOGINUID == LOGINUID_NOT_SET:
68 display.warning('Tests involving loginuid mismatch will be skipped on this host since it is not set.')
69 elif LOGINUID == 0:
70 raise Exception('Use sudo, su, etc. as a non-root user to become root before running this test.')
71 else:
72 raise Exception()
73
74 display.section(f'Bootstrapping {os_release}')
75
76 bootstrapper = Bootstrapper.init()
77 bootstrapper.run()
78
79 result_dir = LOG_PATH
80
81 if result_dir.exists():
82 shutil.rmtree(result_dir)
83
84 result_dir.mkdir()
85 result_dir.chmod(0o777)
86
87 scenarios = get_test_scenarios()
88 results = [run_test(scenario) for scenario in scenarios]
89 error_total = 0
90
91 for name in sorted(result_dir.glob('*.log')):
92 lines = name.read_text().strip().splitlines()
93 error_count = len([line for line in lines if line.startswith('FAIL: ')])
94 error_total += error_count
95
96 display.section(f'Log ({error_count=}/{len(lines)}): {name.name}')
97
98 for line in lines:
99 if line.startswith('FAIL: '):
100 display.show(line, display.RED)
101 else:
102 display.show(line)
103
104 error_count = len([result for result in results if result.message])
105 error_total += error_count
106
107 duration = datetime.timedelta(seconds=int(sum(result.duration.total_seconds() for result in results)))
108
109 display.section(f'Test Results ({error_count=}/{len(results)}) [{duration}]')
110
111 for result in results:
112 notes = f' <cleanup: {", ".join(result.cleanup)}>' if result.cleanup else ''
113
114 if result.cgroup_dirs:
115 notes += f' <cgroup_dirs: {len(result.cgroup_dirs)}>'
116
117 notes += f' [{result.duration}]'
118
119 if result.message:
120 display.show(f'FAIL: {result.scenario} {result.message}{notes}', display.RED)
121 elif result.duration.total_seconds() >= 90:
122 display.show(f'SLOW: {result.scenario}{notes}', display.YELLOW)
123 else:
124 display.show(f'PASS: {result.scenario}{notes}')
125
126 if error_total:
127 sys.exit(1)
128
129
130 def get_container_completion_entries() -> dict[str, dict[str, str]]:
131 """Parse and return the ansible-test container completion entries."""
132 completion_lines = pathlib.Path(os.environ['PYTHONPATH'], '../test/lib/ansible_test/_data/completion/docker.txt').read_text().splitlines()
133
134 # TODO: consider including testing for the collection default image
135 entries = {name: value for name, value in (parse_completion_entry(line) for line in completion_lines) if name != 'default'}
136
137 return entries
138
139
140 def get_test_scenarios() -> list[TestScenario]:
141 """Generate and return a list of test scenarios."""
142
143 supported_engines = ('docker', 'podman')
144 available_engines = [engine for engine in supported_engines if shutil.which(engine)]
145
146 if not available_engines:
147 raise ApplicationError(f'No supported container engines found: {", ".join(supported_engines)}')
148
149 entries = get_container_completion_entries()
150
151 unprivileged_user = User.get(UNPRIVILEGED_USER_NAME)
152
153 scenarios: list[TestScenario] = []
154
155 for container_name, settings in entries.items():
156 image = settings['image']
157 cgroup = settings.get('cgroup', 'v1-v2')
158
159 for engine in available_engines:
160 # TODO: figure out how to get tests passing using docker without disabling selinux
161 disable_selinux = os_release.id == 'fedora' and engine == 'docker' and cgroup != 'none'
162 debug_systemd = cgroup != 'none'
163
164 # The AppArmor policy for pasta on Ubuntu 26.04 prevents podman from stopping containers.
165 # Attempting to do so fails with an error like:
166 # rootless netns: kill network process: permission denied
167 # AppArmor denials such as the following show up in dmesg output:
168 # [ 1606.740536] audit: type=1400 audit(1777052086.084:226): apparmor="DENIED" operation="signal" class="signal" profile="pasta" pid=28252
169 # comm="podman" requested_mask="receive" denied_mask="receive" signal=term peer="podman"
170 disable_apparmor_profile_pasta = engine == 'podman' and os_release.id == 'ubuntu' and os_release.version_id == '26.04'
171
172 cgroup_version = get_docker_info(engine).cgroup_version
173
174 user_scenarios = [
175 # TODO: test rootless docker
176 UserScenario(ssh=unprivileged_user),
177 ]
178
179 if engine == 'podman':
180 if os_release.id not in ('ubuntu', 'fedora') \
181 and not (os_release.id == 'rhel' and os_release.version_id.startswith('10.')):
182 # rootfull podman is not supported by all systems
183 # rootfull podman networking stopped working on Fedora 43 hosts when docker is installed
184 # RHEL >= 10 is also excluded due to https://github.com/containers/crun/issues/2059
185 user_scenarios.append(UserScenario(ssh=ROOT_USER))
186
187 # TODO: test podman remote on Alpine and Ubuntu hosts
188 # TODO: combine remote with ssh using different unprivileged users
189 if os_release.id not in ('alpine', 'ubuntu'):
190 user_scenarios.append(UserScenario(remote=unprivileged_user))
191
192 if LOGINUID_MISMATCH and os_release.id not in ('ubuntu', 'fedora') \
193 and not (os_release.id == 'rhel' and os_release.version_id.startswith('10.')):
194 # rootfull podman is not supported by all systems
195 # rootfull podman networking stopped working on Fedora 43 hosts when docker is installed
196 # RHEL >= 10 is also excluded due to https://github.com/containers/crun/issues/2059
197 user_scenarios.append(UserScenario())
198
199 for user_scenario in user_scenarios:
200 expose_cgroup_version: int | None = None # by default the host is assumed to provide sufficient cgroup support for the container and scenario
201
202 if cgroup == 'v1-only' and cgroup_version != 1:
203 expose_cgroup_version = 1 # the container requires cgroup v1 support and the host does not use cgroup v1
204 elif cgroup != 'none' and not have_systemd():
205 # the container requires cgroup support and the host does not use systemd
206 if cgroup_version == 1:
207 expose_cgroup_version = 1 # cgroup v1 mount required
208 elif cgroup_version == 2 and engine == 'podman' and user_scenario.actual != ROOT_USER:
209 # Running a systemd container on a non-systemd host with cgroup v2 fails for rootless podman.
210 # It may be possible to support this scenario, but the necessary configuration to do so is unknown.
211 display.warning(f'Skipping testing of {container_name!r} with rootless podman because the host uses cgroup v2 without systemd.')
212 continue
213
214 scenarios.append(
215 TestScenario(
216 user_scenario=user_scenario,
217 engine=engine,
218 container_name=container_name,
219 image=image,
220 disable_selinux=disable_selinux,
221 expose_cgroup_version=expose_cgroup_version,
222 debug_systemd=debug_systemd,
223 disable_apparmor_profile_pasta=disable_apparmor_profile_pasta,
224 )
225 )
226
227 return scenarios
228
229
230 def run_test(scenario: TestScenario) -> TestResult:
231 """Run a test scenario and return the test results."""
232 display.section(f'Testing {scenario} Started')
233
234 start = time.monotonic()
235
236 integration = ['ansible-test', 'integration', 'split']
237 integration_options = ['--target', f'docker:{scenario.container_name}', '--color', '--truncate', '0', '-v']
238
239 if scenario.debug_systemd:
240 integration_options.append('--dev-systemd-debug')
241
242 target_only_options = ['--dev-probe-cgroups', str(LOG_PATH)]
243
244 entries = get_container_completion_entries()
245
246 # For the split test, Alpine Linux is preferred as the controller. There are two reasons for this:
247 # 1) It doesn't require the cgroup v1 hack, so we can test a target that doesn't need that.
248 # 2) It doesn't require disabling selinux, so we can test a target that doesn't need that.
249 # Unfortunately, this isn't always possible, such as when an Alpine release isn't available with support for controller Python versions.
250 controller_container = [name for name in entries if name.startswith('alpine')][0]
251
252 commands = [
253 # The cgroup probe is only performed for the first test of the target.
254 # There's no need to repeat the probe again for the same target.
255 # The controller will be tested separately as a target.
256 # This ensures that both the probe and no-probe code paths are functional.
257 [*integration, *integration_options, *target_only_options],
258 [*integration, '--controller', f'docker:{controller_container}', *integration_options],
259 ]
260
261 common_env: dict[str, str] = {}
262 test_env: dict[str, str] = {}
263
264 if scenario.engine == 'podman':
265 if scenario.user_scenario.remote:
266 common_env.update(
267 # Podman 4.3.0 has a regression which requires a port for remote connections to work.
268 # See: https://github.com/containers/podman/issues/16509
269 CONTAINER_HOST=f'ssh://{scenario.user_scenario.remote.name}@localhost:22'
270 f'/run/user/{scenario.user_scenario.remote.pwnam.pw_uid}/podman/podman.sock',
271 CONTAINER_SSHKEY=str(pathlib.Path('~/.ssh/id_rsa').expanduser()), # TODO: add support for ssh + remote when the ssh user is not root
272 )
273
274 test_env.update(ANSIBLE_TEST_PREFER_PODMAN='1')
275
276 test_env.update(common_env)
277
278 if scenario.user_scenario.ssh:
279 client_become_cmd = ['ssh', f'{scenario.user_scenario.ssh.name}@localhost']
280 test_commands = [client_become_cmd + [f'cd ~/ansible; {format_env(test_env)}{sys.executable} bin/{shlex.join(command)}'] for command in commands]
281 else:
282 client_become_cmd = ['sh', '-c']
283 test_commands = [client_become_cmd + [f'{format_env(test_env)}{shlex.join(command)}'] for command in commands]
284
285 prime_storage_command = []
286
287 if scenario.engine == 'podman' and scenario.user_scenario.actual.name == UNPRIVILEGED_USER_NAME:
288 # When testing podman we need to make sure that the overlay filesystem is used instead of vfs.
289 # Using the vfs filesystem will result in running out of disk space during the tests.
290 # To change the filesystem used, the existing storage directory must be removed before "priming" the storage database.
291 #
292 # Without this change the following message may be displayed:
293 #
294 # User-selected graph driver "overlay" overwritten by graph driver "vfs" from database - delete libpod local files to resolve
295 #
296 # However, with this change it may be replaced with the following message:
297 #
298 # User-selected graph driver "vfs" overwritten by graph driver "overlay" from database - delete libpod local files to resolve
299
300 actual_become_cmd = ['ssh', f'{scenario.user_scenario.actual.name}@localhost']
301 prime_storage_command = actual_become_cmd + prepare_prime_podman_storage()
302
303 message = ''
304
305 if scenario.expose_cgroup_version == 1:
306 prepare_cgroup_systemd(scenario.user_scenario.actual.name, scenario.engine)
307
308 try:
309 if prime_storage_command:
310 retry_command(lambda: run_command(*prime_storage_command), retry_any_error=True)
311
312 if scenario.disable_selinux:
313 run_command('setenforce', 'permissive')
314
315 if scenario.disable_apparmor_profile_pasta:
316 os.symlink('/etc/apparmor.d/usr.bin.pasta', '/etc/apparmor.d/disable/usr.bin.pasta')
317 run_command('apparmor_parser', '-R', '/etc/apparmor.d/usr.bin.pasta')
318
319 for test_command in test_commands:
320 def run_test_command() -> SubprocessResult:
321 if os_release.id == 'alpine' and scenario.user_scenario.actual.name != 'root':
322 # Make sure rootless networking works on Alpine.
323 # NOTE: The path used below differs slightly from the referenced issue.
324 # See: https://gitlab.alpinelinux.org/alpine/aports/-/issues/16137
325 actual_pwnam = scenario.user_scenario.actual.pwnam
326 root_path = pathlib.Path(f'/tmp/storage-run-{actual_pwnam.pw_uid}')
327 run_path = root_path / 'containers/networks/rootless-netns/run'
328 run_path.mkdir(mode=0o755, parents=True, exist_ok=True)
329
330 while run_path.is_relative_to(root_path):
331 os.chown(run_path, actual_pwnam.pw_uid, actual_pwnam.pw_gid)
332 run_path = run_path.parent
333
334 return run_command(*test_command)
335
336 retry_command(run_test_command)
337 except SubprocessError as ex:
338 message = str(ex)
339 display.error(f'{scenario} {message}')
340 finally:
341 if scenario.disable_apparmor_profile_pasta:
342 os.unlink('/etc/apparmor.d/disable/usr.bin.pasta')
343 run_command('apparmor_parser', '/etc/apparmor.d/usr.bin.pasta')
344
345 if scenario.disable_selinux:
346 run_command('setenforce', 'enforcing')
347
348 if scenario.expose_cgroup_version == 1:
349 dirs = remove_cgroup_systemd()
350 else:
351 dirs = list_group_systemd()
352
353 cleanup_command = [scenario.engine, 'rmi', '-f', scenario.image]
354
355 try:
356 retry_command(lambda: run_command(*client_become_cmd + [f'{format_env(common_env)}{shlex.join(cleanup_command)}']), retry_any_error=True)
357 except SubprocessError as ex:
358 display.error(str(ex))
359
360 cleanup = cleanup_podman() if scenario.engine == 'podman' else tuple()
361
362 finish = time.monotonic()
363 duration = datetime.timedelta(seconds=int(finish - start))
364
365 display.section(f'Testing {scenario} Completed in {duration}')
366
367 return TestResult(
368 scenario=scenario,
369 message=message,
370 cleanup=cleanup,
371 duration=duration,
372 cgroup_dirs=tuple(str(path) for path in dirs),
373 )
374
375
376 def prepare_prime_podman_storage() -> list[str]:
377 """Partially prime podman storage and return a command to complete the remainder."""
378 prime_storage_command = ['rm -rf ~/.local/share/containers; STORAGE_DRIVER=overlay podman pull public.ecr.aws/docker/library/alpine:3.21.2']
379
380 test_containers = pathlib.Path(f'~{UNPRIVILEGED_USER_NAME}/.local/share/containers').expanduser()
381
382 if test_containers.is_dir():
383 # First remove the directory as root, since the user may not have permissions on all the files.
384 # The directory will be removed again after login, before initializing the database.
385 rmtree(test_containers)
386
387 return prime_storage_command
388
389
390 def cleanup_podman() -> tuple[str, ...]:
391 """Cleanup podman processes and files on disk."""
392 cleanup = []
393
394 for remaining in range(3, -1, -1):
395 processes = [(int(item[0]), item[1]) for item in
396 [item.split(maxsplit=1) for item in run_command('ps', '-A', '-o', 'pid,comm', capture=True).stdout.splitlines()]
397 if pathlib.Path(item[1].split()[0]).name in ('catatonit', 'podman', 'conmon')]
398
399 if not processes:
400 break
401
402 for pid, name in processes:
403 display.info(f'Killing "{name}" ({pid}) ...')
404
405 try:
406 os.kill(pid, signal.SIGTERM if remaining > 1 else signal.SIGKILL)
407 except ProcessLookupError:
408 pass
409
410 cleanup.append(name)
411
412 time.sleep(1)
413 else:
414 raise Exception('failed to kill all matching processes')
415
416 uid = pwd.getpwnam(UNPRIVILEGED_USER_NAME).pw_uid
417
418 container_tmp = pathlib.Path(f'/tmp/containers-user-{uid}')
419 podman_tmp = pathlib.Path(f'/tmp/podman-run-{uid}')
420
421 user_config = pathlib.Path(f'~{UNPRIVILEGED_USER_NAME}/.config').expanduser()
422 user_local = pathlib.Path(f'~{UNPRIVILEGED_USER_NAME}/.local').expanduser()
423
424 if container_tmp.is_dir():
425 rmtree(container_tmp)
426
427 if podman_tmp.is_dir():
428 rmtree(podman_tmp)
429
430 if user_config.is_dir():
431 rmtree(user_config)
432
433 if user_local.is_dir():
434 rmtree(user_local)
435
436 return tuple(sorted(set(cleanup)))
437
438
439 def have_systemd() -> bool:
440 """Return True if the host uses systemd."""
441 return pathlib.Path('/run/systemd/system').is_dir()
442
443
444 def prepare_cgroup_systemd(username: str, engine: str) -> None:
445 """Prepare the systemd cgroup."""
446 CGROUP_SYSTEMD.mkdir()
447
448 run_command('mount', 'cgroup', '-t', 'cgroup', str(CGROUP_SYSTEMD), '-o', 'none,name=systemd,xattr', capture=True)
449
450 if engine == 'podman':
451 run_command('chown', '-R', f'{username}:{username}', str(CGROUP_SYSTEMD))
452
453 run_command('find', str(CGROUP_SYSTEMD), '-type', 'd', '-exec', 'ls', '-l', '{}', ';')
454
455
456 def list_group_systemd() -> list[pathlib.Path]:
457 """List the systemd cgroup."""
458 dirs = set()
459
460 for dirpath, dirnames, filenames in os.walk(CGROUP_SYSTEMD, topdown=False):
461 for dirname in dirnames:
462 target_path = pathlib.Path(dirpath, dirname)
463 display.info(f'dir: {target_path}')
464 dirs.add(target_path)
465
466 return sorted(dirs)
467
468
469 def remove_cgroup_systemd() -> list[pathlib.Path]:
470 """Remove the systemd cgroup."""
471 dirs = set()
472
473 for sleep_seconds in range(1, 10):
474 try:
475 for dirpath, dirnames, filenames in os.walk(CGROUP_SYSTEMD, topdown=False):
476 for dirname in dirnames:
477 target_path = pathlib.Path(dirpath, dirname)
478 display.info(f'rmdir: {target_path}')
479 dirs.add(target_path)
480 target_path.rmdir()
481 except OSError as ex:
482 if ex.errno != errno.EBUSY:
483 raise
484
485 error = str(ex)
486 else:
487 break
488
489 display.warning(f'{error} -- sleeping for {sleep_seconds} second(s) before trying again ...') # pylint: disable=used-before-assignment
490
491 time.sleep(sleep_seconds)
492
493 time.sleep(1) # allow time for cgroups to be fully removed before unmounting
494
495 run_command('umount', str(CGROUP_SYSTEMD))
496
497 CGROUP_SYSTEMD.rmdir()
498
499 time.sleep(1) # allow time for cgroup hierarchy to be removed after unmounting
500
501 cgroup = pathlib.Path('/proc/self/cgroup').read_text()
502
503 if 'systemd' in cgroup:
504 raise Exception('systemd hierarchy detected')
505
506 return sorted(dirs)
507
508
509 def rmtree(path: pathlib.Path) -> None:
510 """Wrapper around shutil.rmtree with additional error handling."""
511 for retries in range(10, -1, -1):
512 try:
513 display.info(f'rmtree: {path} ({retries} attempts remaining) ... ')
514 shutil.rmtree(path)
515 except Exception:
516 if not path.exists():
517 display.info(f'rmtree: {path} (not found)')
518 return
519
520 if not path.is_dir():
521 display.info(f'rmtree: {path} (not a directory)')
522 return
523
524 if retries:
525 continue
526
527 raise
528 else:
529 display.info(f'rmtree: {path} (done)')
530 return
531
532
533 def format_env(env: dict[str, str]) -> str:
534 """Format an env dict for injection into a shell command and return the resulting string."""
535 if env:
536 return ' '.join(f'{shlex.quote(key)}={shlex.quote(value)}' for key, value in env.items()) + ' '
537
538 return ''
539
540
541 class DockerInfo:
542 """The results of `docker info` for the container runtime."""
543
544 def __init__(self, data: dict[str, t.Any]) -> None:
545 self.data = data
546
547 @property
548 def cgroup_version(self) -> int:
549 """The cgroup version of the container host."""
550 data = self.data
551 host = data.get('host')
552
553 if host:
554 version = int(host['cgroupVersion'].lstrip('v')) # podman
555 else:
556 version = int(data['CgroupVersion']) # docker
557
558 return version
559
560
561 @functools.lru_cache
562 def get_docker_info(engine: str) -> DockerInfo:
563 """Return info for the current container runtime. The results are cached."""
564 return DockerInfo(json.loads(run_command(engine, 'info', '--format', '{{ json . }}', capture=True).stdout))
565
566
567 @dataclasses.dataclass(frozen=True)
568 class User:
569 name: str
570 pwnam: pwd.struct_passwd
571
572 @classmethod
573 def get(cls, name: str) -> User:
574 return User(
575 name=name,
576 pwnam=pwd.getpwnam(name),
577 )
578
579
580 @dataclasses.dataclass(frozen=True)
581 class UserScenario:
582 ssh: User = None
583 remote: User = None
584
585 @property
586 def actual(self) -> User:
587 return self.remote or self.ssh or ROOT_USER
588
589
590 @dataclasses.dataclass(frozen=True)
591 class TestScenario:
592 user_scenario: UserScenario
593 engine: str
594 container_name: str
595 image: str
596 disable_selinux: bool
597 expose_cgroup_version: int | None
598 debug_systemd: bool
599 disable_apparmor_profile_pasta: bool
600
601 @property
602 def tags(self) -> tuple[str, ...]:
603 tags = []
604
605 if self.user_scenario.ssh:
606 tags.append(f'ssh: {self.user_scenario.ssh.name}')
607
608 if self.user_scenario.remote:
609 tags.append(f'remote: {self.user_scenario.remote.name}')
610
611 if self.disable_selinux:
612 tags.append('selinux: permissive')
613
614 if self.expose_cgroup_version is not None:
615 tags.append(f'cgroup: {self.expose_cgroup_version}')
616
617 if self.disable_apparmor_profile_pasta:
618 tags.append('apparmor(pasta): disabled')
619
620 return tuple(tags)
621
622 @property
623 def tag_label(self) -> str:
624 return ' '.join(f'[{tag}]' for tag in self.tags)
625
626 def __str__(self):
627 return f'[{self.container_name}] ({self.engine}) {self.tag_label}'.strip()
628
629
630 @dataclasses.dataclass(frozen=True)
631 class TestResult:
632 scenario: TestScenario
633 message: str
634 cleanup: tuple[str, ...]
635 duration: datetime.timedelta
636 cgroup_dirs: tuple[str, ...]
637
638
639 def parse_completion_entry(value: str) -> tuple[str, dict[str, str]]:
640 """Parse the given completion entry, returning the entry name and a dictionary of key/value settings."""
641 values = value.split()
642
643 name = values[0]
644 data = {kvp[0]: kvp[1] if len(kvp) > 1 else '' for kvp in [item.split('=', 1) for item in values[1:]]}
645
646 return name, data
647
648
649 @dataclasses.dataclass(frozen=True)
650 class SubprocessResult:
651 """Result from execution of a subprocess."""
652
653 command: list[str]
654 stdout: str
655 stderr: str
656 status: int
657
658
659 class ApplicationError(Exception):
660 """An application error."""
661
662 def __init__(self, message: str) -> None:
663 self.message = message
664
665 super().__init__(message)
666
667
668 class SubprocessError(ApplicationError):
669 """An error from executing a subprocess."""
670
671 def __init__(self, result: SubprocessResult) -> None:
672 self.result = result
673
674 message = f'Command `{shlex.join(result.command)}` exited with status: {result.status}'
675
676 stdout = (result.stdout or '').strip()
677 stderr = (result.stderr or '').strip()
678
679 if stdout:
680 message += f'\n>>> Standard Output\n{stdout}'
681
682 if stderr:
683 message += f'\n>>> Standard Error\n{stderr}'
684
685 super().__init__(message)
686
687
688 class ProgramNotFoundError(ApplicationError):
689 """A required program was not found."""
690
691 def __init__(self, name: str) -> None:
692 self.name = name
693
694 super().__init__(f'Missing program: {name}')
695
696
697 class Display:
698 """Display interface for sending output to the console."""
699
700 CLEAR = '\033[0m'
701 RED = '\033[31m'
702 GREEN = '\033[32m'
703 YELLOW = '\033[33m'
704 BLUE = '\033[34m'
705 PURPLE = '\033[35m'
706 CYAN = '\033[36m'
707
708 def __init__(self) -> None:
709 self.sensitive: set[str] = set()
710
711 def section(self, message: str) -> None:
712 """Print a section message to the console."""
713 self.show(f'==> {message}', color=self.BLUE)
714
715 def subsection(self, message: str) -> None:
716 """Print a subsection message to the console."""
717 self.show(f'--> {message}', color=self.CYAN)
718
719 def fatal(self, message: str) -> None:
720 """Print a fatal message to the console."""
721 self.show(f'FATAL: {message}', color=self.RED)
722
723 def error(self, message: str) -> None:
724 """Print an error message to the console."""
725 self.show(f'ERROR: {message}', color=self.RED)
726
727 def warning(self, message: str) -> None:
728 """Print a warning message to the console."""
729 self.show(f'WARNING: {message}', color=self.PURPLE)
730
731 def info(self, message: str) -> None:
732 """Print an info message to the console."""
733 self.show(f'INFO: {message}', color=self.YELLOW)
734
735 def show(self, message: str, color: str | None = None) -> None:
736 """Print a message to the console."""
737 for item in self.sensitive:
738 message = message.replace(item, '*' * len(item))
739
740 print(f'{color or self.CLEAR}{message}{self.CLEAR}', flush=True)
741
742
743 def run_module(
744 module: str,
745 args: dict[str, t.Any],
746 ) -> SubprocessResult:
747 """Run the specified Ansible module and return the result."""
748 return run_command('ansible', '-m', module, '-v', '-a', json.dumps(args), 'localhost')
749
750
751 def retry_command(func: t.Callable[[], SubprocessResult], attempts: int = 3, retry_any_error: bool = False) -> SubprocessResult:
752 """Run the given command function up to the specified number of attempts when the failure is due to an SSH error."""
753 for attempts_remaining in range(attempts - 1, -1, -1):
754 try:
755 return func()
756 except SubprocessError as ex:
757 if ex.result.command[0] == 'ssh' and ex.result.status == 255 and attempts_remaining:
758 # SSH connections on our Ubuntu 22.04 host sometimes fail for unknown reasons.
759 # This retry should allow the test suite to continue, maintaining CI stability.
760 # TODO: Figure out why local SSH connections sometimes fail during the test run.
761 display.warning('Command failed due to an SSH error. Waiting a few seconds before retrying.')
762 time.sleep(3)
763 continue
764
765 if retry_any_error:
766 display.warning('Command failed. Waiting a few seconds before retrying.')
767 time.sleep(3)
768 continue
769
770 raise
771
772
773 def run_command(
774 *command: str,
775 data: str | None = None,
776 stdin: int | t.IO[bytes] | None = None,
777 env: dict[str, str] | None = None,
778 capture: bool = False,
779 ) -> SubprocessResult:
780 """Run the specified command and return the result."""
781 stdin = subprocess.PIPE if data else stdin or subprocess.DEVNULL
782 stdout = subprocess.PIPE if capture else None
783 stderr = subprocess.PIPE if capture else None
784
785 display.subsection(f'Run command: {shlex.join(command)}')
786
787 try:
788 with subprocess.Popen(args=command, stdin=stdin, stdout=stdout, stderr=stderr, env=env, text=True) as process:
789 process_stdout, process_stderr = process.communicate(data)
790 process_status = process.returncode
791 except FileNotFoundError:
792 raise ProgramNotFoundError(command[0]) from None
793
794 result = SubprocessResult(
795 command=list(command),
796 stdout=process_stdout,
797 stderr=process_stderr,
798 status=process_status,
799 )
800
801 if process.returncode != 0:
802 raise SubprocessError(result)
803
804 return result
805
806
807 class Bootstrapper(metaclass=abc.ABCMeta):
808 """Bootstrapper for remote instances."""
809
810 @classmethod
811 def install_podman(cls) -> bool:
812 """Return True if podman will be installed."""
813 return False
814
815 @classmethod
816 def install_docker(cls) -> bool:
817 """Return True if docker will be installed."""
818 return False
819
820 @classmethod
821 def usable(cls) -> bool:
822 """Return True if the bootstrapper can be used, otherwise False."""
823 return False
824
825 @classmethod
826 def init(cls) -> t.Type[Bootstrapper]:
827 """Return a bootstrapper type appropriate for the current system."""
828 for bootstrapper in cls.__subclasses__():
829 if bootstrapper.usable():
830 return bootstrapper
831
832 display.warning('No supported bootstrapper found.')
833 return Bootstrapper
834
835 @classmethod
836 def run(cls) -> None:
837 """Run the bootstrapper."""
838 cls.configure_root_user()
839 cls.configure_unprivileged_user()
840 cls.configure_source_trees()
841 cls.configure_ssh_keys()
842 cls.configure_podman_remote()
843
844 @classmethod
845 def configure_root_user(cls) -> None:
846 """Configure the root user to run tests."""
847 root_password_status = run_command('passwd', '--status', 'root', capture=True)
848 root_password_set = root_password_status.stdout.split()[1]
849
850 if root_password_set not in ('P', 'PS'):
851 root_password = run_command('openssl', 'passwd', '-5', '-stdin', data=secrets.token_hex(8), capture=True).stdout.strip()
852
853 run_module(
854 'user',
855 dict(
856 user='root',
857 password=root_password,
858 ),
859 )
860
861 @classmethod
862 def configure_unprivileged_user(cls) -> None:
863 """Configure the unprivileged user to run tests."""
864 unprivileged_password = run_command('openssl', 'passwd', '-5', '-stdin', data=secrets.token_hex(8), capture=True).stdout.strip()
865
866 run_module(
867 'user',
868 dict(
869 user=UNPRIVILEGED_USER_NAME,
870 password=unprivileged_password,
871 groups=['docker'] if cls.install_docker() else [],
872 append=True,
873 ),
874 )
875
876 if os_release.id == 'alpine':
877 # Most distros handle this automatically, but not Alpine.
878 # See: https://www.redhat.com/sysadmin/rootless-podman
879 start = 165535
880 end = start + 65535
881 id_range = f'{start}-{end}'
882
883 run_command(
884 'usermod',
885 '--add-subuids',
886 id_range,
887 '--add-subgids',
888 id_range,
889 UNPRIVILEGED_USER_NAME,
890 )
891
892 @classmethod
893 def configure_source_trees(cls):
894 """Configure the source trees needed to run tests for both root and the unprivileged user."""
895 current_ansible = pathlib.Path(os.environ['PYTHONPATH']).parent
896
897 root_ansible = pathlib.Path('~').expanduser() / 'ansible'
898 test_ansible = pathlib.Path(f'~{UNPRIVILEGED_USER_NAME}').expanduser() / 'ansible'
899
900 if current_ansible != root_ansible:
901 display.info(f'copying {current_ansible} -> {root_ansible} ...')
902 rmtree(root_ansible)
903 shutil.copytree(current_ansible, root_ansible)
904 run_command('chown', '-R', 'root:root', str(root_ansible))
905
906 display.info(f'copying {current_ansible} -> {test_ansible} ...')
907 rmtree(test_ansible)
908 shutil.copytree(current_ansible, test_ansible)
909 run_command('chown', '-R', f'{UNPRIVILEGED_USER_NAME}:{UNPRIVILEGED_USER_NAME}', str(test_ansible))
910
911 paths = [pathlib.Path(test_ansible)]
912
913 for root, dir_names, file_names in os.walk(test_ansible):
914 paths.extend(pathlib.Path(root, dir_name) for dir_name in dir_names)
915 paths.extend(pathlib.Path(root, file_name) for file_name in file_names)
916
917 user = pwd.getpwnam(UNPRIVILEGED_USER_NAME)
918 uid = user.pw_uid
919 gid = user.pw_gid
920
921 for path in paths:
922 os.chown(path, uid, gid)
923
924 @classmethod
925 def configure_ssh_keys(cls) -> None:
926 """Configure SSH keys needed to run tests."""
927 user = pwd.getpwnam(UNPRIVILEGED_USER_NAME)
928 uid = user.pw_uid
929 gid = user.pw_gid
930
931 current_rsa_pub = pathlib.Path('~/.ssh/id_rsa.pub').expanduser()
932
933 test_authorized_keys = pathlib.Path(f'~{UNPRIVILEGED_USER_NAME}/.ssh/authorized_keys').expanduser()
934
935 test_authorized_keys.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
936 os.chown(test_authorized_keys.parent, uid, gid)
937
938 shutil.copyfile(current_rsa_pub, test_authorized_keys)
939 os.chown(test_authorized_keys, uid, gid)
940 test_authorized_keys.chmod(mode=0o644)
941
942 @classmethod
943 def configure_podman_remote(cls) -> None:
944 """Configure podman remote support."""
945 # TODO: figure out how to support remote podman without systemd (Alpine)
946 # TODO: figure out how to support remote podman on Ubuntu
947 if os_release.id in ('alpine', 'ubuntu'):
948 return
949
950 # Support podman remote on any host with systemd available.
951 retry_command(lambda: run_command('ssh', f'{UNPRIVILEGED_USER_NAME}@localhost', 'systemctl', '--user', 'enable', '--now', 'podman.socket'))
952 run_command('loginctl', 'enable-linger', UNPRIVILEGED_USER_NAME)
953
954
955 class DnfBootstrapper(Bootstrapper):
956 """Bootstrapper for dnf based systems."""
957
958 @classmethod
959 def install_podman(cls) -> bool:
960 """Return True if podman will be installed."""
961 return True
962
963 @classmethod
964 def install_docker(cls) -> bool:
965 """Return True if docker will be installed."""
966 return os_release.id != 'rhel'
967
968 @classmethod
969 def usable(cls) -> bool:
970 """Return True if the bootstrapper can be used, otherwise False."""
971 return bool(shutil.which('dnf'))
972
973 @classmethod
974 def run(cls) -> None:
975 """Run the bootstrapper."""
976 # NOTE: Install crun to make it available to podman, otherwise installing moby-engine can cause podman to use runc instead.
977 packages = ['podman', 'crun']
978
979 if cls.install_docker():
980 packages.append('moby-engine')
981
982 if cls.install_docker() and os_release.id == 'fedora':
983 packages.append('runc')
984
985 if os_release.id == 'rhel':
986 # As of the release of RHEL 9.1, installing podman on RHEL 9.0 results in a non-fatal error at install time:
987 #
988 # libsemanage.semanage_pipe_data: Child process /usr/libexec/selinux/hll/pp failed with code: 255. (No such file or directory).
989 # container: libsepol.policydb_read: policydb module version 21 does not match my version range 4-20
990 # container: libsepol.sepol_module_package_read: invalid module in module package (at section 0)
991 # container: Failed to read policy package
992 # libsemanage.semanage_direct_commit: Failed to compile hll files into cil files.
993 # (No such file or directory).
994 # /usr/sbin/semodule: Failed!
995 #
996 # Unfortunately this is then fatal when running podman, resulting in no error message and a 127 return code.
997 # The solution is to update the policycoreutils package *before* installing podman.
998 #
999 # NOTE: This work-around can probably be removed once we're testing on RHEL 9.1, as the updated packages should already be installed.
1000 # Unfortunately at this time there is no RHEL 9.1 AMI available (other than the Beta release).
1001
1002 run_command('dnf', 'update', '-y', 'policycoreutils')
1003
1004 run_command('dnf', 'install', '-y', *packages)
1005
1006 if cls.install_docker():
1007 run_command('systemctl', 'start', 'docker')
1008
1009 super().run()
1010
1011
1012 class AptBootstrapper(Bootstrapper):
1013 """Bootstrapper for apt based systems."""
1014
1015 @classmethod
1016 def install_podman(cls) -> bool:
1017 """Return True if podman will be installed."""
1018 return True
1019
1020 @classmethod
1021 def install_docker(cls) -> bool:
1022 """Return True if docker will be installed."""
1023 return True
1024
1025 @classmethod
1026 def usable(cls) -> bool:
1027 """Return True if the bootstrapper can be used, otherwise False."""
1028 return bool(shutil.which('apt-get'))
1029
1030 @classmethod
1031 def run(cls) -> None:
1032 """Run the bootstrapper."""
1033 apt_env = os.environ.copy()
1034 apt_env.update(
1035 DEBIAN_FRONTEND='noninteractive',
1036 )
1037
1038 packages = ['docker.io']
1039
1040 if cls.install_podman():
1041 # NOTE: Install crun to make it available to podman, otherwise installing docker.io can cause podman to use runc instead.
1042 # Using podman rootless requires the `newuidmap` and `slirp4netns` commands.
1043 packages.extend(('podman', 'crun', 'uidmap', 'slirp4netns', 'passt'))
1044
1045 run_command('apt-get', 'install', *packages, '-y', '--no-install-recommends', env=apt_env)
1046
1047 super().run()
1048
1049
1050 class ApkBootstrapper(Bootstrapper):
1051 """Bootstrapper for apk based systems."""
1052
1053 @classmethod
1054 def install_podman(cls) -> bool:
1055 """Return True if podman will be installed."""
1056 return True
1057
1058 @classmethod
1059 def install_docker(cls) -> bool:
1060 """Return True if docker will be installed."""
1061 return True
1062
1063 @classmethod
1064 def usable(cls) -> bool:
1065 """Return True if the bootstrapper can be used, otherwise False."""
1066 return bool(shutil.which('apk'))
1067
1068 @classmethod
1069 def run(cls) -> None:
1070 """Run the bootstrapper."""
1071 # The `openssl` package is used to generate hashed passwords.
1072 # The `crun` package must be explicitly installed since podman won't install it as dep if `runc` is present.
1073 packages = ['docker', 'podman', 'openssl', 'crun']
1074
1075 if os_release.version_id.startswith('3.18.'):
1076 # The 3.19 `crun` package installed below requires `ip6tables`, but depends on the `iptables` package.
1077 # In 3.19, the `iptables` package includes `ip6tables`, but in 3.18 they are separate packages.
1078 # Remove once 3.18 is no longer tested.
1079 packages.append('ip6tables')
1080
1081 run_command('apk', 'add', *packages)
1082
1083 if os_release.version_id.startswith('3.18.'):
1084 # 3.18 only contains `crun` 1.8.4, to get a newer version that resolves the run/shm issue, install `crun` from 3.19.
1085 # Remove once 3.18 is no longer tested.
1086 run_command('apk', 'upgrade', '-U', '--repository=http://dl-cdn.alpinelinux.org/alpine/v3.19/community', 'crun')
1087
1088 run_command('service', 'docker', 'start')
1089 run_command('modprobe', 'tun')
1090
1091 super().run()
1092
1093
1094 @dataclasses.dataclass(frozen=True)
1095 class OsRelease:
1096 """Operating system identification."""
1097
1098 id: str
1099 version_id: str
1100
1101 @staticmethod
1102 def init() -> OsRelease:
1103 """Detect the current OS release and return the result."""
1104 lines = run_command('sh', '-c', '. /etc/os-release && echo $ID && echo $VERSION_ID', capture=True).stdout.splitlines()
1105
1106 result = OsRelease(
1107 id=lines[0],
1108 version_id=lines[1],
1109 )
1110
1111 display.show(f'Detected OS "{result.id}" version "{result.version_id}".')
1112
1113 return result
1114
1115
1116 display = Display()
1117 os_release = OsRelease.init()
1118
1119 ROOT_USER = User.get('root')
1120
1121 if __name__ == '__main__':
1122 main()