Debian Codegraph @

test/lib/ansible_test/_internal/docker_util.py

raw
1 """Functions for accessing docker via the docker cli."""
2
3 from __future__ import annotations
4
5 import dataclasses
6 import enum
7 import json
8 import os
9 import pathlib
10 import re
11 import socket
12 import time
13 import urllib.parse
14 import typing as t
15
16 from .util import (
17 ApplicationError,
18 common_environment,
19 display,
20 find_executable,
21 SubprocessError,
22 cache,
23 OutputStream,
24 InternalError,
25 format_command_output,
26 )
27
28 from .util_common import (
29 run_command,
30 raw_command,
31 )
32
33 from .config import (
34 CommonConfig,
35 )
36
37 from .thread import (
38 mutex,
39 named_lock,
40 )
41
42 from .cgroup import (
43 CGroupEntry,
44 MountEntry,
45 MountType,
46 )
47
48 DOCKER_COMMANDS = [
49 'docker',
50 'podman',
51 ]
52
53 UTILITY_IMAGE = 'quay.io/ansible/ansible-test-utility-container:3.6.0'
54
55 # Max number of open files in a docker container.
56 # Passed with --ulimit option to the docker run command.
57 MAX_NUM_OPEN_FILES = 10240
58
59 # The value of /proc/*/loginuid when it is not set.
60 # It is a reserved UID, which is the maximum 32-bit unsigned integer value.
61 # See: https://access.redhat.com/solutions/25404
62 LOGINUID_NOT_SET = 4294967295
63
64
65 class DockerInfo:
66 """The results of `docker info` and `docker version` for the container runtime."""
67
68 @classmethod
69 def init(cls, args: CommonConfig) -> DockerInfo:
70 """Initialize and return a DockerInfo instance."""
71 command = require_docker().command
72
73 info_stdout = docker_command(args, ['info', '--format', '{{ json . }}'], capture=True, always=True)[0]
74 info = json.loads(info_stdout)
75
76 if server_errors := info.get('ServerErrors'):
77 # This can occur when a remote docker instance is in use and the instance is not responding, such as when the system is still starting up.
78 # In that case an error such as the following may be returned:
79 # error during connect: Get "http://{hostname}:2375/v1.24/info": dial tcp {ip_address}:2375: connect: no route to host
80 raise ApplicationError('Unable to get container host information: ' + '\n'.join(server_errors))
81
82 version_stdout = docker_command(args, ['version', '--format', '{{ json . }}'], capture=True, always=True)[0]
83 version = json.loads(version_stdout)
84
85 info = DockerInfo(args, command, info, version)
86
87 return info
88
89 def __init__(self, args: CommonConfig, engine: str, info: dict[str, t.Any], version: dict[str, t.Any]) -> None:
90 self.args = args
91 self.engine = engine
92 self.info = info
93 self.version = version
94
95 @property
96 def client(self) -> dict[str, t.Any]:
97 """The client version details."""
98 client = self.version.get('Client')
99
100 if not client:
101 raise ApplicationError('Unable to get container host client information.')
102
103 return client
104
105 @property
106 def server(self) -> dict[str, t.Any]:
107 """The server version details."""
108 server = self.version.get('Server')
109
110 if not server:
111 if self.engine == 'podman':
112 # Some Podman versions always report server version info (verified with 1.8.0 and 1.9.3).
113 # Others do not unless Podman remote is being used.
114 # To provide consistency, use the client version if the server version isn't provided.
115 # See: https://github.com/containers/podman/issues/2671#issuecomment-804382934
116 return self.client
117
118 raise ApplicationError('Unable to get container host server information.')
119
120 return server
121
122 @property
123 def client_version(self) -> str:
124 """The client version."""
125 return self.client['Version']
126
127 @property
128 def server_version(self) -> str:
129 """The server version."""
130 return self.server['Version']
131
132 @property
133 def client_major_minor_version(self) -> tuple[int, int]:
134 """The client major and minor version."""
135 major, minor = self.client_version.split('.')[:2]
136 return int(major), int(minor)
137
138 @property
139 def server_major_minor_version(self) -> tuple[int, int]:
140 """The server major and minor version."""
141 major, minor = self.server_version.split('.')[:2]
142 return int(major), int(minor)
143
144 @property
145 def cgroupns_option_supported(self) -> bool:
146 """Return True if the `--cgroupns` option is supported, otherwise return False."""
147 if self.engine == 'docker':
148 # Docker added support for the `--cgroupns` option in version 20.10.
149 # Both the client and server must support the option to use it.
150 # See: https://docs.docker.com/engine/release-notes/#20100
151 return self.client_major_minor_version >= (20, 10) and self.server_major_minor_version >= (20, 10)
152
153 raise NotImplementedError(self.engine)
154
155 @property
156 def cgroup_version(self) -> int:
157 """The cgroup version of the container host."""
158 info = self.info
159 host = info.get('host')
160
161 # When the container host reports cgroup v1 it is running either cgroup v1 legacy mode or cgroup v2 hybrid mode.
162 # When the container host reports cgroup v2 it is running under cgroup v2 unified mode.
163 # See: https://github.com/containers/podman/blob/8356621249e36ed62fc7f35f12d17db9027ff076/libpod/info_linux.go#L52-L56
164 # See: https://github.com/moby/moby/blob/d082bbcc0557ec667faca81b8b33bec380b75dac/daemon/info_unix.go#L24-L27
165
166 if host:
167 return int(host['cgroupVersion'].lstrip('v')) # podman
168
169 try:
170 return int(info['CgroupVersion']) # docker
171 except KeyError:
172 pass
173
174 # Docker 20.10 (API version 1.41) added support for cgroup v2.
175 # Unfortunately the client or server is too old to report the cgroup version.
176 # If the server is old, we can infer the cgroup version.
177 # Otherwise, we'll need to fall back to detection.
178 # See: https://docs.docker.com/engine/release-notes/#20100
179 # See: https://docs.docker.com/engine/api/version-history/#v141-api-changes
180
181 if self.server_major_minor_version < (20, 10):
182 return 1 # old docker server with only cgroup v1 support
183
184 # Tell the user what versions they have and recommend they upgrade the client.
185 # Downgrading the server should also work, but we won't mention that.
186 message = (
187 f'The Docker client version is {self.client_version}. '
188 f'The Docker server version is {self.server_version}. '
189 'Upgrade your Docker client to version 20.10 or later.'
190 )
191
192 if detect_host_properties(self.args).cgroup_v2:
193 # Unfortunately cgroup v2 was detected on the Docker server.
194 # A newer client is needed to support the `--cgroupns` option for use with cgroup v2.
195 raise ApplicationError(f'Unsupported Docker client and server combination using cgroup v2. {message}')
196
197 display.warning(f'Detected Docker server cgroup v1 using probing. {message}', unique=True)
198
199 return 1 # docker server is using cgroup v1 (or cgroup v2 hybrid)
200
201 @property
202 def docker_desktop_wsl2(self) -> bool:
203 """Return True if Docker Desktop integrated with WSL2 is detected, otherwise False."""
204 info = self.info
205
206 kernel_version = info.get('KernelVersion')
207 operating_system = info.get('OperatingSystem')
208
209 dd_wsl2 = kernel_version and kernel_version.endswith('-WSL2') and operating_system == 'Docker Desktop'
210
211 return dd_wsl2
212
213 @property
214 def description(self) -> str:
215 """Describe the container runtime."""
216 tags = dict(
217 client=self.client_version,
218 server=self.server_version,
219 cgroup=f'v{self.cgroup_version}',
220 )
221
222 labels = [self.engine] + [f'{key}={value}' for key, value in tags.items()]
223
224 if self.docker_desktop_wsl2:
225 labels.append('DD+WSL2')
226
227 return f'Container runtime: {" ".join(labels)}'
228
229
230 @mutex
231 def get_docker_info(args: CommonConfig) -> DockerInfo:
232 """Return info for the current container runtime. The results are cached."""
233 try:
234 return get_docker_info.info # type: ignore[attr-defined]
235 except AttributeError:
236 pass
237
238 info = DockerInfo.init(args)
239
240 display.info(info.description, verbosity=1)
241
242 get_docker_info.info = info # type: ignore[attr-defined]
243
244 return info
245
246
247 class SystemdControlGroupV1Status(enum.Enum):
248 """The state of the cgroup v1 systemd hierarchy on the container host."""
249
250 SUBSYSTEM_MISSING = 'The systemd cgroup subsystem was not found.'
251 FILESYSTEM_NOT_MOUNTED = 'The "/sys/fs/cgroup/systemd" filesystem is not mounted.'
252 MOUNT_TYPE_NOT_CORRECT = 'The "/sys/fs/cgroup/systemd" mount type is not correct.'
253 VALID = 'The "/sys/fs/cgroup/systemd" mount is valid.'
254
255
256 @dataclasses.dataclass(frozen=True)
257 class ContainerHostProperties:
258 """Container host properties detected at run time."""
259
260 audit_code: str
261 max_open_files: int
262 loginuid: t.Optional[int]
263 cgroup_v1: SystemdControlGroupV1Status
264 cgroup_v2: bool
265
266
267 @mutex
268 def detect_host_properties(args: CommonConfig) -> ContainerHostProperties:
269 """
270 Detect and return properties of the container host.
271
272 The information collected is:
273
274 - The errno result from attempting to query the container host's audit status.
275 - The max number of open files supported by the container host to run containers.
276 This value may be capped to the maximum value used by ansible-test.
277 If the value is below the desired limit, a warning is displayed.
278 - The loginuid used by the container host to run containers, or None if the audit subsystem is unavailable.
279 - The cgroup subsystems registered with the Linux kernel.
280 - The mounts visible within a container.
281 - The status of the systemd cgroup v1 hierarchy.
282
283 This information is collected together to reduce the number of container runs to probe the container host.
284 """
285 try:
286 return detect_host_properties.properties # type: ignore[attr-defined]
287 except AttributeError:
288 pass
289
290 single_line_commands = (
291 'audit-status',
292 'cat /proc/sys/fs/nr_open',
293 'ulimit -Hn',
294 '(cat /proc/1/loginuid; echo)',
295 )
296
297 multi_line_commands = (
298 ' && '.join(single_line_commands),
299 'cat /proc/1/cgroup',
300 'cat /proc/1/mountinfo',
301 )
302
303 options = ['--volume', '/sys/fs/cgroup:/probe:ro']
304 cmd = ['sh', '-c', ' && echo "-" && '.join(multi_line_commands)]
305
306 stdout, stderr = run_utility_container(args, 'ansible-test-probe', cmd, options)
307
308 if args.explain:
309 return ContainerHostProperties(
310 audit_code='???',
311 max_open_files=MAX_NUM_OPEN_FILES,
312 loginuid=LOGINUID_NOT_SET,
313 cgroup_v1=SystemdControlGroupV1Status.VALID,
314 cgroup_v2=False,
315 )
316
317 blocks = stdout.split('\n-\n')
318
319 if len(blocks) != len(multi_line_commands):
320 message = f'Unexpected probe output. Expected {len(multi_line_commands)} blocks but found {len(blocks)}.\n'
321 message += format_command_output(stdout, stderr)
322
323 raise InternalError(message.strip())
324
325 values = blocks[0].split('\n')
326
327 audit_parts = values[0].split(' ', 1)
328 audit_status = int(audit_parts[0])
329 audit_code = audit_parts[1]
330
331 system_limit = int(values[1])
332 hard_limit = int(values[2])
333 loginuid = int(values[3]) if values[3] else None
334
335 cgroups = CGroupEntry.loads(blocks[1])
336 mounts = MountEntry.loads(blocks[2])
337
338 if hard_limit < MAX_NUM_OPEN_FILES and hard_limit < system_limit and require_docker().command == 'docker':
339 # Podman will use the highest possible limits, up to its default of 1M.
340 # See: https://github.com/containers/podman/blob/009afb50b308548eb129bc68e654db6c6ad82e7a/pkg/specgen/generate/oci.go#L39-L58
341 # Docker limits are less predictable. They could be the system limit or the user's soft limit.
342 # If Docker is running as root it should be able to use the system limit.
343 # When Docker reports a limit below the preferred value and the system limit, attempt to use the preferred value, up to the system limit.
344 options = ['--ulimit', f'nofile={min(system_limit, MAX_NUM_OPEN_FILES)}']
345 cmd = ['sh', '-c', 'ulimit -Hn']
346
347 try:
348 stdout = run_utility_container(args, 'ansible-test-ulimit', cmd, options)[0]
349 except SubprocessError as ex:
350 display.warning(str(ex))
351 else:
352 hard_limit = int(stdout)
353
354 # Check the audit error code from attempting to query the container host's audit status.
355 #
356 # The following error codes are known to occur:
357 #
358 # EPERM - Operation not permitted
359 # This occurs when the root user runs a container but lacks the AUDIT_WRITE capability.
360 # This will cause patched versions of OpenSSH to disconnect after a login succeeds.
361 # See: https://src.fedoraproject.org/rpms/openssh/blob/f36/f/openssh-7.6p1-audit.patch
362 #
363 # EBADF - Bad file number
364 # This occurs when the host doesn't support the audit system (the open_audit call fails).
365 # This allows SSH logins to succeed despite the failure.
366 # See: https://github.com/Distrotech/libaudit/blob/4fc64f79c2a7f36e3ab7b943ce33ab5b013a7782/lib/netlink.c#L204-L209
367 #
368 # ECONNREFUSED - Connection refused
369 # This occurs when a non-root user runs a container without the AUDIT_WRITE capability.
370 # When sending an audit message, libaudit ignores this error condition.
371 # This allows SSH logins to succeed despite the failure.
372 # See: https://github.com/Distrotech/libaudit/blob/4fc64f79c2a7f36e3ab7b943ce33ab5b013a7782/lib/deprecated.c#L48-L52
373
374 subsystems = set(cgroup.subsystem for cgroup in cgroups)
375 mount_types = {mount.path: mount.type for mount in mounts}
376
377 if 'systemd' not in subsystems:
378 cgroup_v1 = SystemdControlGroupV1Status.SUBSYSTEM_MISSING
379 elif not (mount_type := mount_types.get(pathlib.PurePosixPath('/probe/systemd'))):
380 cgroup_v1 = SystemdControlGroupV1Status.FILESYSTEM_NOT_MOUNTED
381 elif mount_type != MountType.CGROUP_V1:
382 cgroup_v1 = SystemdControlGroupV1Status.MOUNT_TYPE_NOT_CORRECT
383 else:
384 cgroup_v1 = SystemdControlGroupV1Status.VALID
385
386 cgroup_v2 = mount_types.get(pathlib.PurePosixPath('/probe')) == MountType.CGROUP_V2
387
388 display.info(f'Container host audit status: {audit_code} ({audit_status})', verbosity=1)
389 display.info(f'Container host max open files: {hard_limit}', verbosity=1)
390 display.info(f'Container loginuid: {loginuid if loginuid is not None else "unavailable"}'
391 f'{" (not set)" if loginuid == LOGINUID_NOT_SET else ""}', verbosity=1)
392
393 if hard_limit < MAX_NUM_OPEN_FILES:
394 display.warning(f'Unable to set container max open files to {MAX_NUM_OPEN_FILES}. Using container host limit of {hard_limit} instead.')
395 else:
396 hard_limit = MAX_NUM_OPEN_FILES
397
398 properties = ContainerHostProperties(
399 # The errno (audit_status) is intentionally not exposed here, as it can vary across systems and architectures.
400 # Instead, the symbolic name (audit_code) is used, which is resolved inside the container which generated the error.
401 # See: https://man7.org/linux/man-pages/man3/errno.3.html
402 audit_code=audit_code,
403 max_open_files=hard_limit,
404 loginuid=loginuid,
405 cgroup_v1=cgroup_v1,
406 cgroup_v2=cgroup_v2,
407 )
408
409 detect_host_properties.properties = properties # type: ignore[attr-defined]
410
411 return properties
412
413
414 def get_session_container_name(args: CommonConfig, name: str) -> str:
415 """Return the given container name with the current test session name applied to it."""
416 return f'{name}-{args.session_name}'
417
418
419 def run_utility_container(
420 args: CommonConfig,
421 name: str,
422 cmd: list[str],
423 options: list[str],
424 data: t.Optional[str] = None,
425 ) -> tuple[t.Optional[str], t.Optional[str]]:
426 """Run the specified command using the ansible-test utility container, returning stdout and stderr."""
427 name = get_session_container_name(args, name)
428
429 options = options + [
430 '--name', name,
431 '--rm',
432 ] # fmt: skip
433
434 if data:
435 options.append('-i')
436
437 docker_pull(args, UTILITY_IMAGE)
438
439 return docker_run(args, UTILITY_IMAGE, options, cmd, data)
440
441
442 class DockerCommand:
443 """Details about the available docker command."""
444
445 def __init__(self, command: str, executable: str, version: str) -> None:
446 self.command = command
447 self.executable = executable
448 self.version = version
449
450 @staticmethod
451 def detect() -> t.Optional[DockerCommand]:
452 """Detect and return the available docker command, or None."""
453 if os.environ.get('ANSIBLE_TEST_PREFER_PODMAN'):
454 commands = list(reversed(DOCKER_COMMANDS))
455 else:
456 commands = DOCKER_COMMANDS
457
458 for command in commands:
459 executable = find_executable(command, required=False)
460
461 if executable:
462 version = raw_command([command, '-v'], env=docker_environment(), capture=True)[0].strip()
463
464 if command == 'docker' and 'podman' in version:
465 continue # avoid detecting podman as docker
466
467 display.info('Detected "%s" container runtime version: %s' % (command, version), verbosity=1)
468
469 return DockerCommand(command, executable, version)
470
471 return None
472
473
474 def require_docker() -> DockerCommand:
475 """Return the docker command to invoke. Raises an exception if docker is not available."""
476 if command := get_docker_command():
477 return command
478
479 raise ApplicationError(f'No container runtime detected. Supported commands: {", ".join(DOCKER_COMMANDS)}')
480
481
482 @cache
483 def get_docker_command() -> t.Optional[DockerCommand]:
484 """Return the docker command to invoke, or None if docker is not available."""
485 return DockerCommand.detect()
486
487
488 def docker_available() -> bool:
489 """Return True if docker is available, otherwise return False."""
490 return bool(get_docker_command())
491
492
493 @cache
494 def get_docker_host_ip() -> str:
495 """Return the IP of the Docker host."""
496 docker_host_ip = socket.gethostbyname(get_docker_hostname())
497
498 display.info('Detected docker host IP: %s' % docker_host_ip, verbosity=1)
499
500 return docker_host_ip
501
502
503 @cache
504 def get_docker_hostname() -> str:
505 """Return the hostname of the Docker service."""
506 docker_host = os.environ.get('DOCKER_HOST')
507
508 if docker_host and docker_host.startswith(('tcp://', 'ssh://')):
509 try:
510 hostname = urllib.parse.urlparse(docker_host).hostname
511 display.info('Detected Docker host: %s' % hostname, verbosity=1)
512 except ValueError:
513 hostname = 'localhost'
514 display.warning('Could not parse DOCKER_HOST environment variable "%s", falling back to localhost.' % docker_host)
515 else:
516 hostname = 'localhost'
517 display.info('Assuming Docker is available on localhost.', verbosity=1)
518
519 return hostname or 'localhost'
520
521
522 @cache
523 def get_podman_host_ip() -> str:
524 """Return the IP of the Podman host."""
525 podman_host_ip = socket.gethostbyname(get_podman_hostname())
526
527 display.info('Detected Podman host IP: %s' % podman_host_ip, verbosity=1)
528
529 return podman_host_ip
530
531
532 @cache
533 def get_podman_default_hostname() -> t.Optional[str]:
534 """
535 Return the default hostname of the Podman service.
536
537 --format was added in podman 3.3.0, this functionality depends on its availability
538 """
539 hostname: t.Optional[str] = None
540 try:
541 stdout = raw_command(['podman', 'system', 'connection', 'list', '--format=json'], env=docker_environment(), capture=True)[0]
542 except SubprocessError:
543 stdout = '[]'
544
545 try:
546 connections = json.loads(stdout)
547 except json.decoder.JSONDecodeError:
548 return hostname
549
550 for connection in connections:
551 # A trailing indicates the default
552 if connection['Name'][-1] == '*':
553 hostname = connection['URI']
554 break
555
556 return hostname
557
558
559 @cache
560 def get_podman_remote() -> t.Optional[str]:
561 """Return the remote podman hostname, if any, otherwise return None."""
562 # URL value resolution precedence:
563 # - command line value
564 # - environment variable CONTAINER_HOST
565 # - containers.conf
566 # - unix://run/podman/podman.sock
567 hostname = None
568
569 podman_host = os.environ.get('CONTAINER_HOST')
570 if not podman_host:
571 podman_host = get_podman_default_hostname()
572
573 if podman_host and podman_host.startswith('ssh://'):
574 try:
575 hostname = urllib.parse.urlparse(podman_host).hostname
576 except ValueError:
577 display.warning('Could not parse podman URI "%s"' % podman_host)
578 else:
579 display.info('Detected Podman remote: %s' % hostname, verbosity=1)
580 return hostname
581
582
583 @cache
584 def get_podman_hostname() -> str:
585 """Return the hostname of the Podman service."""
586 hostname = get_podman_remote()
587
588 if not hostname:
589 hostname = 'localhost'
590 display.info('Assuming Podman is available on localhost.', verbosity=1)
591
592 return hostname
593
594
595 @cache
596 def get_docker_container_id() -> t.Optional[str]:
597 """Return the current container ID if running in a container, otherwise return None."""
598 mountinfo_path = pathlib.Path('/proc/self/mountinfo')
599 container_id = None
600 engine = None
601
602 if mountinfo_path.is_file():
603 # NOTE: This method of detecting the container engine and container ID relies on implementation details of each container engine.
604 # Although the implementation details have remained unchanged for some time, there is no guarantee they will continue to work.
605 # There have been proposals to create a standard mechanism for this, but none is currently available.
606 # See: https://github.com/opencontainers/runtime-spec/issues/1105
607
608 mounts = MountEntry.loads(mountinfo_path.read_text())
609
610 for mount in mounts:
611 if str(mount.path) == '/etc/hostname':
612 # Podman generates /etc/hostname in the makePlatformBindMounts function.
613 # That function ends up using ContainerRunDirectory to generate a path like: {prefix}/{container_id}/userdata/hostname
614 # NOTE: The {prefix} portion of the path can vary, so should not be relied upon.
615 # See: https://github.com/containers/podman/blob/480c7fbf5361f3bd8c1ed81fe4b9910c5c73b186/libpod/container_internal_linux.go#L660-L664
616 # See: https://github.com/containers/podman/blob/480c7fbf5361f3bd8c1ed81fe4b9910c5c73b186/vendor/github.com/containers/storage/store.go#L3133
617 # This behavior has existed for ~5 years and was present in Podman version 0.2.
618 # See: https://github.com/containers/podman/pull/248
619 if match := re.search('/(?P<id>[0-9a-f]{64})/userdata/hostname$', str(mount.root)):
620 container_id = match.group('id')
621 engine = 'Podman'
622 break
623
624 # Docker generates /etc/hostname in the BuildHostnameFile function.
625 # That function ends up using the containerRoot function to generate a path like: {prefix}/{container_id}/hostname
626 # NOTE: The {prefix} portion of the path can vary, so should not be relied upon.
627 # See: https://github.com/moby/moby/blob/cd8a090e6755bee0bdd54ac8a894b15881787097/container/container_unix.go#L58
628 # See: https://github.com/moby/moby/blob/92e954a2f05998dc05773b6c64bbe23b188cb3a0/daemon/container.go#L86
629 # This behavior has existed for at least ~7 years and was present in Docker version 1.0.1.
630 # See: https://github.com/moby/moby/blob/v1.0.1/daemon/container.go#L351
631 # See: https://github.com/moby/moby/blob/v1.0.1/daemon/daemon.go#L133
632 if match := re.search('/(?P<id>[0-9a-f]{64})/hostname$', str(mount.root)):
633 container_id = match.group('id')
634 engine = 'Docker'
635 break
636
637 if container_id:
638 display.info(f'Detected execution in {engine} container ID: {container_id}', verbosity=1)
639
640 return container_id
641
642
643 def docker_pull(args: CommonConfig, image: str) -> None:
644 """
645 Pull the specified image if it is not available.
646 Images without a tag or digest will not be pulled.
647 Retries up to 10 times if the pull fails.
648 A warning will be shown for any image with volumes defined.
649 Images will be pulled only once.
650 Concurrent pulls for the same image will block until the first completes.
651 """
652 with named_lock(f'docker_pull:{image}') as first:
653 if first:
654 __docker_pull(args, image)
655
656
657 def __docker_pull(args: CommonConfig, image: str) -> None:
658 """Internal implementation for docker_pull. Do not call directly."""
659 if '@' not in image and ':' not in image:
660 display.info('Skipping pull of image without tag or digest: %s' % image, verbosity=2)
661 docker_image_inspect(args, image)
662 elif docker_image_inspect(args, image, always=True):
663 display.info('Skipping pull of existing image: %s' % image, verbosity=2)
664 else:
665 for _iteration in range(1, 10):
666 try:
667 docker_command(args, ['pull', image], capture=False)
668
669 if docker_image_inspect(args, image) or args.explain:
670 break
671
672 display.warning(f'Image "{image}" not found after pull completed. Waiting a few seconds before trying again.')
673 except SubprocessError:
674 display.warning(f'Failed to pull container image "{image}". Waiting a few seconds before trying again.')
675 time.sleep(3)
676 else:
677 raise ApplicationError(f'Failed to pull container image "{image}".')
678
679
680 def docker_cp_to(args: CommonConfig, container_id: str, src: str, dst: str) -> None:
681 """Copy a file to the specified container."""
682 docker_command(args, ['cp', src, '%s:%s' % (container_id, dst)], capture=True)
683
684
685 def docker_cp_from(args: CommonConfig, container_id: str, src: str, dst: str) -> None:
686 """Copy a file from the specified container."""
687 docker_command(args, ['cp', '%s:%s' % (container_id, src), dst], capture=True)
688
689
690 def docker_create(
691 args: CommonConfig,
692 image: str,
693 options: list[str],
694 cmd: list[str] = None,
695 ) -> tuple[t.Optional[str], t.Optional[str]]:
696 """Create a container using the given docker image."""
697 return docker_command(args, ['create'] + options + [image] + cmd, capture=True)
698
699
700 def docker_run(
701 args: CommonConfig,
702 image: str,
703 options: list[str],
704 cmd: list[str] = None,
705 data: t.Optional[str] = None,
706 ) -> tuple[t.Optional[str], t.Optional[str]]:
707 """Run a container using the given docker image."""
708 return docker_command(args, ['run'] + options + [image] + cmd, data=data, capture=True)
709
710
711 def docker_start(
712 args: CommonConfig,
713 container_id: str,
714 options: list[str],
715 ) -> tuple[t.Optional[str], t.Optional[str]]:
716 """Start a container by name or ID."""
717 return docker_command(args, ['start'] + options + [container_id], capture=True)
718
719
720 def docker_rm(args: CommonConfig, container_id: str) -> None:
721 """Remove the specified container."""
722 try:
723 # Stop the container with SIGKILL immediately, then remove the container.
724 # Docker supports `--timeout` for stop. The `--time` option was deprecated in v28.0.
725 # Podman supports `--time` for stop. The `--timeout` option was deprecated in 1.9.0.
726 # Both Docker and Podman support the `-t` option for stop.
727 docker_command(args, ['stop', '-t', '0', container_id], capture=True)
728 docker_command(args, ['rm', '-v', container_id], capture=True)
729 except SubprocessError as ex:
730 # Both Podman and Docker report an error if the container does not exist.
731 # The error messages contain the same "no such container" string, differing only in capitalization.
732 if 'no such container' not in ex.stderr.lower():
733 raise ex
734
735
736 class DockerError(Exception):
737 """General Docker error."""
738
739
740 class ContainerNotFoundError(DockerError):
741 """The container identified by `identifier` was not found."""
742
743 def __init__(self, identifier: str) -> None:
744 super().__init__('The container "%s" was not found.' % identifier)
745
746 self.identifier = identifier
747
748
749 class DockerInspect:
750 """The results of `docker inspect` for a single container."""
751
752 def __init__(self, args: CommonConfig, inspection: dict[str, t.Any]) -> None:
753 self.args = args
754 self.inspection = inspection
755
756 # primary properties
757
758 @property
759 def id(self) -> str:
760 """Return the ID of the container."""
761 return self.inspection['Id']
762
763 @property
764 def network_settings(self) -> dict[str, t.Any]:
765 """Return a dictionary of the container network settings."""
766 return self.inspection['NetworkSettings']
767
768 @property
769 def state(self) -> dict[str, t.Any]:
770 """Return a dictionary of the container state."""
771 return self.inspection['State']
772
773 @property
774 def config(self) -> dict[str, t.Any]:
775 """Return a dictionary of the container configuration."""
776 return self.inspection['Config']
777
778 # nested properties
779
780 @property
781 def ports(self) -> dict[str, list[dict[str, str]]]:
782 """Return a dictionary of ports the container has published."""
783 return self.network_settings['Ports']
784
785 @property
786 def networks(self) -> t.Optional[dict[str, dict[str, t.Any]]]:
787 """Return a dictionary of the networks the container is attached to, or None if running under podman, which does not support networks."""
788 return self.network_settings.get('Networks')
789
790 @property
791 def running(self) -> bool:
792 """Return True if the container is running, otherwise False."""
793 return self.state['Running']
794
795 @property
796 def pid(self) -> int:
797 """Return the PID of the init process."""
798 if self.args.explain:
799 return 0
800
801 return self.state['Pid']
802
803 @property
804 def env(self) -> list[str]:
805 """Return a list of the environment variables used to create the container."""
806 return self.config['Env']
807
808 @property
809 def image(self) -> str:
810 """Return the image used to create the container."""
811 return self.config['Image']
812
813 # functions
814
815 def env_dict(self) -> dict[str, str]:
816 """Return a dictionary of the environment variables used to create the container."""
817 return dict((item[0], item[1]) for item in [e.split('=', 1) for e in self.env])
818
819 def get_tcp_port(self, port: int) -> t.Optional[list[dict[str, str]]]:
820 """Return a list of the endpoints published by the container for the specified TCP port, or None if it is not published."""
821 return self.ports.get('%d/tcp' % port)
822
823 def get_network_names(self) -> t.Optional[list[str]]:
824 """Return a list of the network names the container is attached to."""
825 if self.networks is None:
826 return None
827
828 return sorted(self.networks)
829
830 def get_network_name(self) -> str:
831 """Return the network name the container is attached to. Raises an exception if no network, or more than one, is attached."""
832 networks = self.get_network_names()
833
834 if not networks:
835 raise ApplicationError('No network found for Docker container: %s.' % self.id)
836
837 if len(networks) > 1:
838 raise ApplicationError('Found multiple networks for Docker container %s instead of only one: %s' % (self.id, ', '.join(networks)))
839
840 return networks[0]
841
842
843 def docker_inspect(args: CommonConfig, identifier: str, always: bool = False) -> DockerInspect:
844 """
845 Return the results of `docker container inspect` for the specified container.
846 Raises a ContainerNotFoundError if the container was not found.
847 """
848 try:
849 stdout = docker_command(args, ['container', 'inspect', identifier], capture=True, always=always)[0]
850 except SubprocessError as ex:
851 stdout = ex.stdout
852
853 if args.explain and not always:
854 items = []
855 else:
856 items = json.loads(stdout)
857
858 if len(items) == 1:
859 return DockerInspect(args, items[0])
860
861 raise ContainerNotFoundError(identifier)
862
863
864 def docker_network_disconnect(args: CommonConfig, container_id: str, network: str) -> None:
865 """Disconnect the specified docker container from the given network."""
866 docker_command(args, ['network', 'disconnect', network, container_id], capture=True)
867
868
869 class DockerImageInspect:
870 """The results of `docker image inspect` for a single image."""
871
872 def __init__(self, args: CommonConfig, inspection: dict[str, t.Any]) -> None:
873 self.args = args
874 self.inspection = inspection
875
876 # primary properties
877
878 @property
879 def config(self) -> dict[str, t.Any]:
880 """Return a dictionary of the image config."""
881 return self.inspection['Config']
882
883 # nested properties
884
885 @property
886 def volumes(self) -> dict[str, t.Any]:
887 """Return a dictionary of the image volumes."""
888 return self.config.get('Volumes') or {}
889
890 @property
891 def cmd(self) -> list[str]:
892 """The command to run when the container starts."""
893 return self.config['Cmd']
894
895
896 @mutex
897 def docker_image_inspect(args: CommonConfig, image: str, always: bool = False) -> t.Optional[DockerImageInspect]:
898 """
899 Return the results of `docker image inspect` for the specified image or None if the image does not exist.
900 """
901 inspect_cache: dict[str, DockerImageInspect]
902
903 try:
904 inspect_cache = docker_image_inspect.cache # type: ignore[attr-defined]
905 except AttributeError:
906 inspect_cache = docker_image_inspect.cache = {} # type: ignore[attr-defined]
907
908 if inspect_result := inspect_cache.get(image):
909 return inspect_result
910
911 try:
912 stdout = docker_command(args, ['image', 'inspect', image], capture=True, always=always)[0]
913 except SubprocessError:
914 stdout = '[]'
915
916 if args.explain and not always:
917 items = []
918 else:
919 items = json.loads(stdout)
920
921 if len(items) > 1:
922 raise ApplicationError(f'Inspection of image "{image}" resulted in {len(items)} items:\n{json.dumps(items, indent=4)}')
923
924 if len(items) == 1:
925 inspect_result = DockerImageInspect(args, items[0])
926 inspect_cache[image] = inspect_result
927 return inspect_result
928
929 return None
930
931
932 class DockerNetworkInspect:
933 """The results of `docker network inspect` for a single network."""
934
935 def __init__(self, args: CommonConfig, inspection: dict[str, t.Any]) -> None:
936 self.args = args
937 self.inspection = inspection
938
939
940 def docker_network_inspect(args: CommonConfig, network: str, always: bool = False) -> t.Optional[DockerNetworkInspect]:
941 """
942 Return the results of `docker network inspect` for the specified network or None if the network does not exist.
943 """
944 try:
945 stdout = docker_command(args, ['network', 'inspect', network], capture=True, always=always)[0]
946 except SubprocessError:
947 stdout = '[]'
948
949 if args.explain and not always:
950 items = []
951 else:
952 items = json.loads(stdout)
953
954 if len(items) == 1:
955 return DockerNetworkInspect(args, items[0])
956
957 return None
958
959
960 def docker_logs(args: CommonConfig, container_id: str) -> None:
961 """Display logs for the specified container. If an error occurs, it is displayed rather than raising an exception."""
962 try:
963 docker_command(args, ['logs', container_id], capture=False)
964 except SubprocessError as ex:
965 display.error(str(ex))
966
967
968 def docker_exec(
969 args: CommonConfig,
970 container_id: str,
971 cmd: list[str],
972 capture: bool,
973 options: t.Optional[list[str]] = None,
974 stdin: t.Optional[t.IO[bytes]] = None,
975 stdout: t.Optional[t.IO[bytes]] = None,
976 interactive: bool = False,
977 output_stream: t.Optional[OutputStream] = None,
978 data: t.Optional[str] = None,
979 ) -> tuple[t.Optional[str], t.Optional[str]]:
980 """Execute the given command in the specified container."""
981 if not options:
982 options = []
983
984 if data or stdin or stdout:
985 options.append('-i')
986
987 return docker_command(
988 args,
989 ['exec'] + options + [container_id] + cmd,
990 capture=capture,
991 stdin=stdin,
992 stdout=stdout,
993 interactive=interactive,
994 output_stream=output_stream,
995 data=data,
996 )
997
998
999 def docker_command(
1000 args: CommonConfig,
1001 cmd: list[str],
1002 capture: bool,
1003 stdin: t.Optional[t.IO[bytes]] = None,
1004 stdout: t.Optional[t.IO[bytes]] = None,
1005 interactive: bool = False,
1006 output_stream: t.Optional[OutputStream] = None,
1007 always: bool = False,
1008 data: t.Optional[str] = None,
1009 ) -> tuple[t.Optional[str], t.Optional[str]]:
1010 """Run the specified docker command."""
1011 env = docker_environment()
1012 command = [require_docker().command]
1013
1014 if command[0] == 'podman' and get_podman_remote():
1015 command.append('--remote')
1016
1017 return run_command(
1018 args,
1019 command + cmd,
1020 env=env,
1021 capture=capture,
1022 stdin=stdin,
1023 stdout=stdout,
1024 interactive=interactive,
1025 always=always,
1026 output_stream=output_stream,
1027 data=data,
1028 )
1029
1030
1031 def docker_environment() -> dict[str, str]:
1032 """Return a dictionary of docker related environment variables found in the current environment."""
1033 env = common_environment()
1034
1035 var_names = {
1036 'XDG_RUNTIME_DIR', # podman
1037 }
1038
1039 var_prefixes = {
1040 'CONTAINER_', # podman remote
1041 'DOCKER_', # docker
1042 }
1043
1044 env.update({name: value for name, value in os.environ.items() if name in var_names or any(name.startswith(prefix) for prefix in var_prefixes)})
1045
1046 return env