• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

localstack / localstack / 22209548116

19 Feb 2026 02:08PM UTC coverage: 86.964% (-0.04%) from 87.003%
22209548116

push

github

web-flow
Logs: fix snapshot region from tests (#13792)

69755 of 80211 relevant lines covered (86.96%)

0.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

47.89
/localstack-core/localstack/utils/container_utils/docker_cmd_client.py
1
import functools
1✔
2
import itertools
1✔
3
import json
1✔
4
import logging
1✔
5
import os
1✔
6
import re
1✔
7
import shlex
1✔
8
import subprocess
1✔
9
from collections.abc import Callable
1✔
10

11
from localstack import config
1✔
12
from localstack.utils.collections import ensure_list
1✔
13
from localstack.utils.container_utils.container_client import (
1✔
14
    AccessDenied,
15
    CancellableStream,
16
    ContainerClient,
17
    ContainerException,
18
    DockerContainerStats,
19
    DockerContainerStatus,
20
    DockerNotAvailable,
21
    DockerPlatform,
22
    LogConfig,
23
    Mount,
24
    NoSuchContainer,
25
    NoSuchImage,
26
    NoSuchNetwork,
27
    NoSuchObject,
28
    PortMappings,
29
    RegistryConnectionError,
30
    Ulimit,
31
    Util,
32
    VolumeMappingSpecification,
33
    get_registry_from_image_name,
34
)
35
from localstack.utils.run import run
1✔
36
from localstack.utils.strings import first_char_to_upper, to_str
1✔
37

38
LOG = logging.getLogger(__name__)
1✔
39

40

41
class CancellableProcessStream(CancellableStream):
1✔
42
    process: subprocess.Popen
1✔
43

44
    def __init__(self, process: subprocess.Popen) -> None:
1✔
45
        super().__init__()
1✔
46
        self.process = process
1✔
47

48
    def __iter__(self):
1✔
49
        return self
1✔
50

51
    def __next__(self):
1✔
52
        line = self.process.stdout.readline()
1✔
53
        if not line:
1✔
54
            raise StopIteration
1✔
55
        return line
1✔
56

57
    def close(self):
1✔
58
        return self.process.terminate()
1✔
59

60

61
def parse_size_string(size_str: str) -> int:
1✔
62
    """Parse human-readable size strings from Docker CLI into bytes"""
63
    size_str = size_str.strip().replace(" ", "").upper()
×
64
    if size_str == "0B":
×
65
        return 0
×
66

67
    # Match value and unit using regex
68
    match = re.match(r"^([\d.]+)([A-Za-z]+)$", size_str)
×
69
    if not match:
×
70
        return 0
×
71

72
    value = float(match.group(1))
×
73
    unit = match.group(2)
×
74

75
    unit_factors = {
×
76
        "B": 1,
77
        "KB": 10**3,
78
        "MB": 10**6,
79
        "GB": 10**9,
80
        "TB": 10**12,
81
        "KIB": 2**10,
82
        "MIB": 2**20,
83
        "GIB": 2**30,
84
        "TIB": 2**40,
85
    }
86

87
    return int(value * unit_factors.get(unit, 1))
×
88

89

90
class CmdDockerClient(ContainerClient):
1✔
91
    """
92
    Class for managing Docker (or Podman) containers using the command line executable.
93

94
    The client also supports targeting Podman engines, as Podman is almost a drop-in replacement
95
    for Docker these days. The majority of compatibility switches in this class is to handle slightly
96
    different response payloads or error messages returned by the `docker` vs `podman` commands.
97
    """
98

99
    default_run_outfile: str | None = None
1✔
100

101
    def _docker_cmd(self) -> list[str]:
1✔
102
        """
103
        Get the configured, tested Docker CMD.
104
        :return: string to be used for running Docker commands
105
        :raises: DockerNotAvailable exception if the Docker command or the socker is not available
106
        """
107
        if not self.has_docker():
1✔
108
            raise DockerNotAvailable()
1✔
109
        return shlex.split(config.DOCKER_CMD)
1✔
110

111
    def get_system_info(self) -> dict:
1✔
112
        cmd = [
1✔
113
            *self._docker_cmd(),
114
            "info",
115
            "--format",
116
            "{{json .}}",
117
        ]
118
        cmd_result = run(cmd)
1✔
119

120
        return json.loads(cmd_result)
1✔
121

122
    def get_container_status(self, container_name: str) -> DockerContainerStatus:
1✔
123
        cmd = self._docker_cmd()
1✔
124
        cmd += [
1✔
125
            "ps",
126
            "-a",
127
            "--filter",
128
            f"name={container_name}",
129
            "--format",
130
            "{{ .Status }} - {{ .Names }}",
131
        ]
132
        cmd_result = run(cmd)
1✔
133

134
        # filter empty / invalid lines from docker ps output
135
        cmd_result = next((line for line in cmd_result.splitlines() if container_name in line), "")
1✔
136
        container_status = cmd_result.strip().lower()
1✔
137
        if len(container_status) == 0:
1✔
138
            return DockerContainerStatus.NON_EXISTENT
1✔
139
        elif "(paused)" in container_status:
1✔
140
            return DockerContainerStatus.PAUSED
×
141
        elif container_status.startswith("up "):
1✔
142
            return DockerContainerStatus.UP
1✔
143
        else:
144
            return DockerContainerStatus.DOWN
1✔
145

146
    def get_container_stats(self, container_name: str) -> DockerContainerStats:
1✔
147
        cmd = self._docker_cmd()
×
148
        cmd += ["stats", "--no-stream", "--format", "{{json .}}", container_name]
×
149
        cmd_result = run(cmd)
×
150
        raw_stats = json.loads(cmd_result)
×
151

152
        # BlockIO (read, write)
153
        block_io_parts = raw_stats["BlockIO"].split("/")
×
154
        block_read = parse_size_string(block_io_parts[0])
×
155
        block_write = parse_size_string(block_io_parts[1])
×
156

157
        # CPU percentage
158
        cpu_percentage = float(raw_stats["CPUPerc"].strip("%"))
×
159

160
        # Memory (usage, limit)
161
        mem_parts = raw_stats["MemUsage"].split("/")
×
162
        mem_used = parse_size_string(mem_parts[0])
×
163
        mem_limit = parse_size_string(mem_parts[1])
×
164
        mem_percentage = float(raw_stats["MemPerc"].strip("%"))
×
165

166
        # Network (rx, tx)
167
        net_parts = raw_stats["NetIO"].split("/")
×
168
        net_rx = parse_size_string(net_parts[0])
×
169
        net_tx = parse_size_string(net_parts[1])
×
170

171
        return DockerContainerStats(
×
172
            Container=raw_stats["ID"],
173
            ID=raw_stats["ID"],
174
            Name=raw_stats["Name"],
175
            BlockIO=(block_read, block_write),
176
            CPUPerc=round(cpu_percentage, 2),
177
            MemPerc=round(mem_percentage, 2),
178
            MemUsage=(mem_used, mem_limit),
179
            NetIO=(net_rx, net_tx),
180
            PIDs=int(raw_stats["PIDs"]),
181
            SDKStats=None,
182
        )
183

184
    def stop_container(self, container_name: str, timeout: int = 10) -> None:
1✔
185
        cmd = self._docker_cmd()
1✔
186
        cmd += ["stop", "--time", str(timeout), container_name]
1✔
187
        LOG.debug("Stopping container with cmd %s", cmd)
1✔
188
        try:
1✔
189
            run(cmd)
1✔
190
        except subprocess.CalledProcessError as e:
×
191
            self._check_and_raise_no_such_container_error(container_name, error=e)
×
192
            raise ContainerException(
×
193
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
194
            ) from e
195

196
    def restart_container(self, container_name: str, timeout: int = 10) -> None:
1✔
197
        cmd = self._docker_cmd()
×
198
        cmd += ["restart", "--time", str(timeout), container_name]
×
199
        LOG.debug("Restarting container with cmd %s", cmd)
×
200
        try:
×
201
            run(cmd)
×
202
        except subprocess.CalledProcessError as e:
×
203
            self._check_and_raise_no_such_container_error(container_name, error=e)
×
204
            raise ContainerException(
×
205
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
206
            ) from e
207

208
    def pause_container(self, container_name: str) -> None:
1✔
209
        cmd = self._docker_cmd()
×
210
        cmd += ["pause", container_name]
×
211
        LOG.debug("Pausing container with cmd %s", cmd)
×
212
        try:
×
213
            run(cmd)
×
214
        except subprocess.CalledProcessError as e:
×
215
            self._check_and_raise_no_such_container_error(container_name, error=e)
×
216
            raise ContainerException(
×
217
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
218
            ) from e
219

220
    def unpause_container(self, container_name: str) -> None:
1✔
221
        cmd = self._docker_cmd()
×
222
        cmd += ["unpause", container_name]
×
223
        LOG.debug("Unpausing container with cmd %s", cmd)
×
224
        try:
×
225
            run(cmd)
×
226
        except subprocess.CalledProcessError as e:
×
227
            self._check_and_raise_no_such_container_error(container_name, error=e)
×
228
            raise ContainerException(
×
229
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
230
            ) from e
231

232
    def remove_image(self, image: str, force: bool = True) -> None:
1✔
233
        cmd = self._docker_cmd()
×
234
        cmd += ["rmi", image]
×
235
        if force:
×
236
            cmd += ["--force"]
×
237
        LOG.debug("Removing image %s %s", image, "(forced)" if force else "")
×
238
        try:
×
239
            run(cmd)
×
240
        except subprocess.CalledProcessError as e:
×
241
            # handle different error messages for Docker and podman
242
            error_messages = ["No such image", "image not known"]
×
243
            if any(msg in to_str(e.stdout) for msg in error_messages):
×
244
                raise NoSuchImage(image, stdout=e.stdout, stderr=e.stderr)
×
245
            raise ContainerException(
×
246
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
247
            ) from e
248

249
    def commit(
1✔
250
        self,
251
        container_name_or_id: str,
252
        image_name: str,
253
        image_tag: str,
254
    ):
255
        cmd = self._docker_cmd()
×
256
        cmd += ["commit", container_name_or_id, f"{image_name}:{image_tag}"]
×
257
        LOG.debug(
×
258
            "Creating image from container %s as %s:%s", container_name_or_id, image_name, image_tag
259
        )
260
        try:
×
261
            run(cmd)
×
262
        except subprocess.CalledProcessError as e:
×
263
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
264
            raise ContainerException(
×
265
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
266
            ) from e
267

268
    def remove_container(
1✔
269
        self, container_name: str, force=True, check_existence=False, volumes=False
270
    ) -> None:
271
        if check_existence and container_name not in self.get_all_container_names():
1✔
272
            return
×
273
        cmd = self._docker_cmd() + ["rm"]
1✔
274
        if force:
1✔
275
            cmd.append("-f")
1✔
276
        if volumes:
1✔
277
            cmd.append("--volumes")
×
278
        cmd.append(container_name)
1✔
279
        LOG.debug("Removing container with cmd %s", cmd)
1✔
280
        try:
1✔
281
            output = run(cmd)
1✔
282
            # When the container does not exist, the output could have the error message without any exception
283
            if isinstance(output, str) and not force:
1✔
284
                self._check_output_and_raise_no_such_container_error(container_name, output=output)
×
285
        except subprocess.CalledProcessError as e:
×
286
            if not force:
×
287
                self._check_and_raise_no_such_container_error(container_name, error=e)
×
288
            raise ContainerException(
×
289
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
290
            ) from e
291

292
    def list_containers(self, filter: list[str] | str | None = None, all=True) -> list[dict]:
1✔
293
        filter = [filter] if isinstance(filter, str) else filter
1✔
294
        cmd = self._docker_cmd()
1✔
295
        cmd.append("ps")
1✔
296
        if all:
1✔
297
            cmd.append("-a")
1✔
298
        options = []
1✔
299
        if filter:
1✔
300
            options += [y for filter_item in filter for y in ["--filter", filter_item]]
×
301
        cmd += options
1✔
302
        cmd.append("--format")
1✔
303
        cmd.append("{{json . }}")
1✔
304
        try:
1✔
305
            cmd_result = run(cmd).strip()
1✔
306
        except subprocess.CalledProcessError as e:
×
307
            raise ContainerException(
×
308
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
309
            ) from e
310
        container_list = []
1✔
311
        if cmd_result:
1✔
312
            if cmd_result[0] == "[":
1✔
313
                container_list = json.loads(cmd_result)
×
314
            else:
315
                container_list = [json.loads(line) for line in cmd_result.splitlines()]
1✔
316
        result = []
1✔
317
        for container in container_list:
1✔
318
            labels = self._transform_container_labels(container["Labels"])
1✔
319
            result.append(
1✔
320
                {
321
                    # support both, Docker and podman API response formats (`ID` vs `Id`)
322
                    "id": container.get("ID") or container["Id"],
323
                    "image": container["Image"],
324
                    # Docker returns a single string for `Names`, whereas podman returns a list of names
325
                    "name": ensure_list(container["Names"])[0],
326
                    "status": container["State"],
327
                    "labels": labels,
328
                }
329
            )
330
        return result
1✔
331

332
    def copy_into_container(
1✔
333
        self, container_name: str, local_path: str, container_path: str
334
    ) -> None:
335
        cmd = self._docker_cmd()
1✔
336
        cmd += ["cp", local_path, f"{container_name}:{container_path}"]
1✔
337
        LOG.debug("Copying into container with cmd: %s", cmd)
1✔
338
        try:
1✔
339
            run(cmd)
1✔
340
        except subprocess.CalledProcessError as e:
×
341
            self._check_and_raise_no_such_container_error(container_name, error=e)
×
342
            if "does not exist" in to_str(e.stdout):
×
343
                raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr)
×
344
            raise ContainerException(
×
345
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
346
            ) from e
347

348
    def copy_from_container(
1✔
349
        self, container_name: str, local_path: str, container_path: str
350
    ) -> None:
351
        cmd = self._docker_cmd()
×
352
        cmd += ["cp", f"{container_name}:{container_path}", local_path]
×
353
        LOG.debug("Copying from container with cmd: %s", cmd)
×
354
        try:
×
355
            run(cmd)
×
356
        except subprocess.CalledProcessError as e:
×
357
            self._check_and_raise_no_such_container_error(container_name, error=e)
×
358
            # additional check to support Podman CLI output
359
            if re.match(".*container .+ does not exist", to_str(e.stdout)):
×
360
                raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr)
×
361
            raise ContainerException(
×
362
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
363
            ) from e
364

365
    def pull_image(
1✔
366
        self,
367
        docker_image: str,
368
        platform: DockerPlatform | None = None,
369
        log_handler: Callable[[str], None] | None = None,
370
        auth_config: dict[str, str] | None = None,
371
    ) -> None:
372
        self._login_if_needed(auth_config, docker_image)
1✔
373
        cmd = self._docker_cmd()
1✔
374
        docker_image = self.registry_resolver_strategy.resolve(docker_image)
1✔
375
        cmd += ["pull", docker_image]
1✔
376
        if platform:
1✔
377
            cmd += ["--platform", platform]
1✔
378
        LOG.debug("Pulling image with cmd: %s", cmd)
1✔
379
        try:
1✔
380
            result = run(cmd)
1✔
381
            # note: we could stream the results, but we'll just process everything at the end for now
382
            if log_handler:
1✔
383
                for line in result.split("\n"):
×
384
                    log_handler(to_str(line))
×
385
        except subprocess.CalledProcessError as e:
×
386
            stdout_str = to_str(e.stdout)
×
387
            if "pull access denied" in stdout_str:
×
388
                raise NoSuchImage(docker_image, stdout=e.stdout, stderr=e.stderr)
×
389
            # note: error message 'access to the resource is denied' raised by Podman client
390
            if "Trying to pull" in stdout_str and "access to the resource is denied" in stdout_str:
×
391
                raise NoSuchImage(docker_image, stdout=e.stdout, stderr=e.stderr)
×
392
            raise ContainerException(
×
393
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
394
            ) from e
395

396
    def push_image(self, docker_image: str, auth_config: dict[str, str] | None = None) -> None:
1✔
397
        self._login_if_needed(auth_config, docker_image)
×
398
        cmd = self._docker_cmd()
×
399
        cmd += ["push", docker_image]
×
400
        LOG.debug("Pushing image with cmd: %s", cmd)
×
401
        try:
×
402
            run(cmd)
×
403
        except subprocess.CalledProcessError as e:
×
404
            if "is denied" in to_str(e.stdout):
×
405
                raise AccessDenied(docker_image)
×
406
            if "requesting higher privileges than access token allows" in to_str(e.stdout):
×
407
                raise AccessDenied(docker_image)
×
408
            if "access token has insufficient scopes" in to_str(e.stdout):
×
409
                raise AccessDenied(docker_image)
×
410
            if "authorization failed: no basic auth credentials" in to_str(e.stdout):
×
411
                raise AccessDenied(docker_image)
×
412
            if "failed to authorize: failed to fetch oauth token" in to_str(e.stdout):
×
413
                raise AccessDenied(docker_image)
×
414
            if "insufficient_scope: authorization failed" in to_str(e.stdout):
×
415
                raise AccessDenied(docker_image)
×
416
            if "does not exist" in to_str(e.stdout):
×
417
                raise NoSuchImage(docker_image)
×
418
            if "connection refused" in to_str(e.stdout):
×
419
                raise RegistryConnectionError(e.stdout)
×
420
            if "failed to do request:" in to_str(e.stdout):
×
421
                raise RegistryConnectionError(e.stdout)
×
422
            # note: error message 'image not known' raised by Podman client
423
            if "image not known" in to_str(e.stdout):
×
424
                raise NoSuchImage(docker_image)
×
425
            raise ContainerException(
×
426
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
427
            ) from e
428

429
    def build_image(
1✔
430
        self,
431
        dockerfile_path: str,
432
        image_name: str,
433
        context_path: str = None,
434
        platform: DockerPlatform | None = None,
435
    ):
436
        cmd = self._docker_cmd()
×
437
        dockerfile_path = Util.resolve_dockerfile_path(dockerfile_path)
×
438
        context_path = context_path or os.path.dirname(dockerfile_path)
×
439
        cmd += ["build", "-t", image_name, "-f", dockerfile_path]
×
440
        if platform:
×
441
            cmd += ["--platform", platform]
×
442
        cmd += [context_path]
×
443
        LOG.debug("Building Docker image: %s", cmd)
×
444
        try:
×
445
            return run(cmd)
×
446
        except subprocess.CalledProcessError as e:
×
447
            raise ContainerException(
×
448
                f"Docker build process returned with error code {e.returncode}", e.stdout, e.stderr
449
            ) from e
450

451
    def tag_image(self, source_ref: str, target_name: str) -> None:
1✔
452
        cmd = self._docker_cmd()
×
453
        cmd += ["tag", source_ref, target_name]
×
454
        LOG.debug("Tagging Docker image %s as %s", source_ref, target_name)
×
455
        try:
×
456
            run(cmd)
×
457
        except subprocess.CalledProcessError as e:
×
458
            # handle different error messages for Docker and podman
459
            error_messages = ["No such image", "image not known"]
×
460
            if any(msg in to_str(e.stdout) for msg in error_messages):
×
461
                raise NoSuchImage(source_ref)
×
462
            raise ContainerException(
×
463
                f"Docker process returned with error code {e.returncode}", e.stdout, e.stderr
464
            ) from e
465

466
    def get_docker_image_names(
1✔
467
        self, strip_latest=True, include_tags=True, strip_wellknown_repo_prefixes: bool = True
468
    ):
469
        format_string = "{{.Repository}}:{{.Tag}}" if include_tags else "{{.Repository}}"
×
470
        cmd = self._docker_cmd()
×
471
        cmd += ["images", "--format", format_string]
×
472
        try:
×
473
            output = run(cmd)
×
474

475
            image_names = output.splitlines()
×
476
            if strip_wellknown_repo_prefixes:
×
477
                image_names = Util.strip_wellknown_repo_prefixes(image_names)
×
478
            if strip_latest:
×
479
                Util.append_without_latest(image_names)
×
480

481
            return image_names
×
482
        except Exception as e:
×
483
            LOG.info('Unable to list Docker images via "%s": %s', cmd, e)
×
484
            return []
×
485

486
    def get_container_logs(self, container_name_or_id: str, safe=False) -> str:
1✔
487
        cmd = self._docker_cmd()
1✔
488
        cmd += ["logs", container_name_or_id]
1✔
489
        try:
1✔
490
            return run(cmd)
1✔
491
        except subprocess.CalledProcessError as e:
×
492
            if safe:
×
493
                return ""
×
494
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
495
            raise ContainerException(
×
496
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
497
            ) from e
498

499
    def stream_container_logs(self, container_name_or_id: str) -> CancellableStream:
1✔
500
        self.inspect_container(container_name_or_id)  # guard to check whether container is there
1✔
501

502
        cmd = self._docker_cmd()
1✔
503
        cmd += ["logs", "--follow", container_name_or_id]
1✔
504

505
        process: subprocess.Popen = run(
1✔
506
            cmd, asynchronous=True, outfile=subprocess.PIPE, stderr=subprocess.STDOUT
507
        )
508

509
        return CancellableProcessStream(process)
1✔
510

511
    def _inspect_object(self, object_name_or_id: str) -> dict[str, dict | list | str]:
1✔
512
        cmd = self._docker_cmd()
1✔
513
        cmd += ["inspect", "--format", "{{json .}}", object_name_or_id]
1✔
514
        try:
1✔
515
            cmd_result = run(cmd, print_error=False)
1✔
516
        except subprocess.CalledProcessError as e:
1✔
517
            # note: case-insensitive comparison, to support Docker and Podman output formats
518
            if "no such object" in to_str(e.stdout).lower():
1✔
519
                raise NoSuchObject(object_name_or_id, stdout=e.stdout, stderr=e.stderr)
1✔
520
            raise ContainerException(
×
521
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
522
            ) from e
523
        object_data = json.loads(cmd_result.strip())
1✔
524
        if isinstance(object_data, list):
1✔
525
            # return first list item, for compatibility with Podman API
526
            if len(object_data) == 1:
×
527
                result = object_data[0]
×
528
                # convert first character to uppercase (e.g., `name` -> `Name`), for Podman/Docker compatibility
529
                result = {first_char_to_upper(k): v for k, v in result.items()}
×
530
                return result
×
531
            LOG.info(
×
532
                "Expected a single object for `inspect` on ID %s, got %s",
533
                object_name_or_id,
534
                len(object_data),
535
            )
536
        return object_data
1✔
537

538
    def inspect_container(self, container_name_or_id: str) -> dict[str, dict | str]:
1✔
539
        try:
1✔
540
            return self._inspect_object(container_name_or_id)
1✔
541
        except NoSuchObject as e:
×
542
            raise NoSuchContainer(container_name_or_id=e.object_id)
×
543

544
    def inspect_image(
1✔
545
        self,
546
        image_name: str,
547
        pull: bool = True,
548
        strip_wellknown_repo_prefixes: bool = True,
549
    ) -> dict[str, dict | list | str]:
550
        image_name = self.registry_resolver_strategy.resolve(image_name)
×
551
        try:
×
552
            result = self._inspect_object(image_name)
×
553
            if strip_wellknown_repo_prefixes:
×
554
                if result.get("RepoDigests"):
×
555
                    result["RepoDigests"] = Util.strip_wellknown_repo_prefixes(
×
556
                        result["RepoDigests"]
557
                    )
558
                if result.get("RepoTags"):
×
559
                    result["RepoTags"] = Util.strip_wellknown_repo_prefixes(result["RepoTags"])
×
560
            return result
×
561
        except NoSuchObject as e:
×
562
            if pull:
×
563
                self.pull_image(image_name)
×
564
                return self.inspect_image(image_name, pull=False)
×
565
            raise NoSuchImage(image_name=e.object_id)
×
566

567
    def create_network(self, network_name: str) -> str:
1✔
568
        cmd = self._docker_cmd()
1✔
569
        cmd += ["network", "create", network_name]
1✔
570
        try:
1✔
571
            return run(cmd).strip()
1✔
572
        except subprocess.CalledProcessError as e:
×
573
            raise ContainerException(
×
574
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
575
            ) from e
576

577
    def delete_network(self, network_name: str) -> None:
1✔
578
        cmd = self._docker_cmd()
1✔
579
        cmd += ["network", "rm", network_name]
1✔
580
        try:
1✔
581
            run(cmd)
1✔
582
        except subprocess.CalledProcessError as e:
×
583
            stdout_str = to_str(e.stdout)
×
584
            if re.match(r".*network (.*) not found.*", stdout_str):
×
585
                raise NoSuchNetwork(network_name=network_name)
×
586
            else:
587
                raise ContainerException(
×
588
                    f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
589
                ) from e
590

591
    def inspect_network(self, network_name: str) -> dict[str, dict | str]:
1✔
592
        try:
1✔
593
            return self._inspect_object(network_name)
1✔
594
        except NoSuchObject as e:
1✔
595
            raise NoSuchNetwork(network_name=e.object_id)
1✔
596

597
    def connect_container_to_network(
1✔
598
        self,
599
        network_name: str,
600
        container_name_or_id: str,
601
        aliases: list | None = None,
602
        link_local_ips: list[str] = None,
603
    ) -> None:
604
        LOG.debug(
×
605
            "Connecting container '%s' to network '%s' with aliases '%s'",
606
            container_name_or_id,
607
            network_name,
608
            aliases,
609
        )
610
        cmd = self._docker_cmd()
×
611
        cmd += ["network", "connect"]
×
612
        if aliases:
×
613
            cmd += ["--alias", ",".join(aliases)]
×
614
        if link_local_ips:
×
615
            cmd += ["--link-local-ip", ",".join(link_local_ips)]
×
616
        cmd += [network_name, container_name_or_id]
×
617
        try:
×
618
            run(cmd)
×
619
        except subprocess.CalledProcessError as e:
×
620
            stdout_str = to_str(e.stdout)
×
621
            if re.match(r".*network (.*) not found.*", stdout_str):
×
622
                raise NoSuchNetwork(network_name=network_name)
×
623
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
624
            raise ContainerException(
×
625
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
626
            ) from e
627

628
    def disconnect_container_from_network(
1✔
629
        self, network_name: str, container_name_or_id: str
630
    ) -> None:
631
        LOG.debug(
1✔
632
            "Disconnecting container '%s' from network '%s'", container_name_or_id, network_name
633
        )
634
        cmd = self._docker_cmd() + ["network", "disconnect", network_name, container_name_or_id]
1✔
635
        try:
1✔
636
            run(cmd)
1✔
637
        except subprocess.CalledProcessError as e:
×
638
            stdout_str = to_str(e.stdout)
×
639
            if re.match(r".*network (.*) not found.*", stdout_str):
×
640
                raise NoSuchNetwork(network_name=network_name)
×
641
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
642
            raise ContainerException(
×
643
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
644
            ) from e
645

646
    def get_container_ip(self, container_name_or_id: str) -> str:
1✔
647
        cmd = self._docker_cmd()
1✔
648
        cmd += [
1✔
649
            "inspect",
650
            "--format",
651
            "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}",
652
            container_name_or_id,
653
        ]
654
        try:
1✔
655
            result = run(cmd).strip()
1✔
656
            return result.split(" ")[0] if result else ""
1✔
657
        except subprocess.CalledProcessError as e:
×
658
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
659
            # consider different error messages for Podman
660
            if "no such object" in to_str(e.stdout).lower():
×
661
                raise NoSuchContainer(container_name_or_id, stdout=e.stdout, stderr=e.stderr)
×
662
            raise ContainerException(
×
663
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
664
            ) from e
665

666
    def login(self, username: str, password: str, registry: str | None = None) -> None:
1✔
667
        cmd = self._docker_cmd()
×
668
        # TODO specify password via stdin
669
        cmd += ["login", "-u", username, "-p", password]
×
670
        if registry:
×
671
            cmd.append(registry)
×
672
        try:
×
673
            run(cmd)
×
674
        except subprocess.CalledProcessError as e:
×
675
            raise ContainerException(
×
676
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
677
            ) from e
678

679
    @functools.cache
1✔
680
    def has_docker(self) -> bool:
1✔
681
        try:
1✔
682
            # do not use self._docker_cmd here (would result in a loop)
683
            run(shlex.split(config.DOCKER_CMD) + ["ps"])
1✔
684
            return True
1✔
685
        except (subprocess.CalledProcessError, FileNotFoundError):
1✔
686
            return False
1✔
687

688
    def create_container(self, image_name: str, **kwargs) -> str:
1✔
689
        # Extract auth_config if provided
690
        auth_config = kwargs.pop("auth_config", None)
1✔
691
        self._login_if_needed(auth_config, image_name)
1✔
692
        image_name = self.registry_resolver_strategy.resolve(image_name)
1✔
693
        cmd, env_file = self._build_run_create_cmd("create", image_name, **kwargs)
1✔
694
        LOG.debug("Create container with cmd: %s", cmd)
1✔
695
        try:
1✔
696
            container_id = run(cmd)
1✔
697
            # Note: strip off Docker warning messages like "DNS setting (--dns=127.0.0.1) may fail in containers"
698
            container_id = container_id.strip().split("\n")[-1]
1✔
699
            return container_id.strip()
1✔
700
        except subprocess.CalledProcessError as e:
×
701
            error_messages = ["Unable to find image", "Trying to pull"]
×
702
            if any(msg in to_str(e.stdout) for msg in error_messages):
×
703
                raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr)
×
704
            raise ContainerException(
×
705
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
706
            ) from e
707
        finally:
708
            Util.rm_env_vars_file(env_file)
1✔
709

710
    def run_container(self, image_name: str, stdin=None, **kwargs) -> tuple[bytes, bytes]:
1✔
711
        auth_config = kwargs.pop("auth_config", None)
×
712
        self._login_if_needed(auth_config, image_name)
×
713
        image_name = self.registry_resolver_strategy.resolve(image_name)
×
714
        cmd, env_file = self._build_run_create_cmd("run", image_name, **kwargs)
×
715
        LOG.debug("Run container with cmd: %s", cmd)
×
716
        try:
×
717
            return self._run_async_cmd(cmd, stdin, kwargs.get("name") or "", image_name)
×
718
        except ContainerException as e:
×
719
            if "Trying to pull" in str(e) and "access to the resource is denied" in str(e):
×
720
                raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr) from e
×
721
            raise
×
722
        finally:
723
            Util.rm_env_vars_file(env_file)
×
724

725
    def exec_in_container(
1✔
726
        self,
727
        container_name_or_id: str,
728
        command: list[str] | str,
729
        interactive=False,
730
        detach=False,
731
        env_vars: dict[str, str | None] | None = None,
732
        stdin: bytes | None = None,
733
        user: str | None = None,
734
        workdir: str | None = None,
735
    ) -> tuple[bytes, bytes]:
736
        env_file = None
1✔
737
        cmd = self._docker_cmd()
1✔
738
        cmd.append("exec")
1✔
739
        if interactive:
1✔
740
            cmd.append("--interactive")
×
741
        if detach:
1✔
742
            cmd.append("--detach")
×
743
        if user:
1✔
744
            cmd += ["--user", user]
×
745
        if workdir:
1✔
746
            cmd += ["--workdir", workdir]
×
747
        if env_vars:
1✔
748
            env_flag, env_file = Util.create_env_vars_file_flag(env_vars)
×
749
            cmd += env_flag
×
750
        cmd.append(container_name_or_id)
1✔
751
        cmd += command if isinstance(command, list) else [command]
1✔
752
        LOG.debug("Execute command in container: %s", cmd)
1✔
753
        try:
1✔
754
            return self._run_async_cmd(cmd, stdin, container_name_or_id)
1✔
755
        finally:
756
            Util.rm_env_vars_file(env_file)
1✔
757

758
    def start_container(
1✔
759
        self,
760
        container_name_or_id: str,
761
        stdin=None,
762
        interactive: bool = False,
763
        attach: bool = False,
764
        flags: str | None = None,
765
    ) -> tuple[bytes, bytes]:
766
        cmd = self._docker_cmd() + ["start"]
1✔
767
        if flags:
1✔
768
            cmd.append(flags)
×
769
        if interactive:
1✔
770
            cmd.append("--interactive")
×
771
        if attach:
1✔
772
            cmd.append("--attach")
×
773
        cmd.append(container_name_or_id)
1✔
774
        LOG.debug("Start container with cmd: %s", cmd)
1✔
775
        return self._run_async_cmd(cmd, stdin, container_name_or_id)
1✔
776

777
    def attach_to_container(self, container_name_or_id: str):
1✔
778
        cmd = self._docker_cmd() + ["attach", container_name_or_id]
1✔
779
        LOG.debug("Attaching to container %s", container_name_or_id)
1✔
780
        return self._run_async_cmd(cmd, stdin=None, container_name=container_name_or_id)
1✔
781

782
    def _run_async_cmd(
1✔
783
        self, cmd: list[str], stdin: bytes, container_name: str, image_name=None
784
    ) -> tuple[bytes, bytes]:
785
        kwargs = {
1✔
786
            "inherit_env": True,
787
            "asynchronous": True,
788
            "stderr": subprocess.PIPE,
789
            "outfile": self.default_run_outfile or subprocess.PIPE,
790
        }
791
        if stdin:
1✔
792
            kwargs["stdin"] = True
×
793
        try:
1✔
794
            process = run(cmd, **kwargs)
1✔
795
            stdout, stderr = process.communicate(input=stdin)
1✔
796
            if process.returncode != 0:
1✔
797
                raise subprocess.CalledProcessError(
×
798
                    process.returncode,
799
                    cmd,
800
                    stdout,
801
                    stderr,
802
                )
803
            else:
804
                return stdout, stderr
1✔
805
        except subprocess.CalledProcessError as e:
×
806
            stderr_str = to_str(e.stderr)
×
807
            if "Unable to find image" in stderr_str:
×
808
                raise NoSuchImage(image_name or "", stdout=e.stdout, stderr=e.stderr)
×
809
            # consider different error messages for Docker/Podman
810
            error_messages = ("No such container", "no container with name or ID")
×
811
            if any(msg.lower() in to_str(e.stderr).lower() for msg in error_messages):
×
812
                raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr)
×
813
            raise ContainerException(
×
814
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
815
            ) from e
816

817
    def _build_run_create_cmd(
1✔
818
        self,
819
        action: str,
820
        image_name: str,
821
        *,
822
        name: str | None = None,
823
        entrypoint: list[str] | str | None = None,
824
        remove: bool = False,
825
        interactive: bool = False,
826
        tty: bool = False,
827
        detach: bool = False,
828
        command: list[str] | str | None = None,
829
        volumes: list[VolumeMappingSpecification] | None = None,
830
        ports: PortMappings | None = None,
831
        exposed_ports: list[str] | None = None,
832
        env_vars: dict[str, str] | None = None,
833
        user: str | None = None,
834
        cap_add: list[str] | None = None,
835
        cap_drop: list[str] | None = None,
836
        security_opt: list[str] | None = None,
837
        network: str | None = None,
838
        dns: str | list[str] | None = None,
839
        additional_flags: str | None = None,
840
        workdir: str | None = None,
841
        privileged: bool | None = None,
842
        labels: dict[str, str] | None = None,
843
        platform: DockerPlatform | None = None,
844
        ulimits: list[Ulimit] | None = None,
845
        init: bool | None = None,
846
        log_config: LogConfig | None = None,
847
        cpu_shares: int | None = None,
848
        mem_limit: int | str | None = None,
849
    ) -> tuple[list[str], str]:
850
        env_file = None
1✔
851
        cmd = self._docker_cmd() + [action]
1✔
852
        if remove:
1✔
853
            cmd.append("--rm")
1✔
854
        if name:
1✔
855
            cmd += ["--name", name]
1✔
856
        if entrypoint is not None:  # empty string entrypoint can be intentional
1✔
857
            if isinstance(entrypoint, str):
1✔
858
                cmd += ["--entrypoint", entrypoint]
1✔
859
            else:
860
                cmd += ["--entrypoint", shlex.join(entrypoint)]
×
861
        if privileged:
1✔
862
            cmd += ["--privileged"]
×
863
        if volumes:
1✔
864
            cmd += [
1✔
865
                param for volume in volumes for param in ["-v", self._map_to_volume_param(volume)]
866
            ]
867
        if interactive:
1✔
868
            cmd.append("--interactive")
×
869
        if tty:
1✔
870
            cmd.append("--tty")
×
871
        if detach:
1✔
872
            cmd.append("--detach")
×
873
        if ports:
1✔
874
            cmd += ports.to_list()
1✔
875
        if exposed_ports:
1✔
876
            cmd += list(itertools.chain.from_iterable(["--expose", port] for port in exposed_ports))
×
877
        if env_vars:
1✔
878
            env_flags, env_file = Util.create_env_vars_file_flag(env_vars)
1✔
879
            cmd += env_flags
1✔
880
        if user:
1✔
881
            cmd += ["--user", user]
×
882
        if cap_add:
1✔
883
            cmd += list(itertools.chain.from_iterable(["--cap-add", cap] for cap in cap_add))
×
884
        if cap_drop:
1✔
885
            cmd += list(itertools.chain.from_iterable(["--cap-drop", cap] for cap in cap_drop))
×
886
        if security_opt:
1✔
887
            cmd += list(
×
888
                itertools.chain.from_iterable(["--security-opt", opt] for opt in security_opt)
889
            )
890
        if network:
1✔
891
            cmd += ["--network", network]
1✔
892
        if dns:
1✔
893
            for dns_server in ensure_list(dns):
×
894
                cmd += ["--dns", dns_server]
×
895
        if workdir:
1✔
896
            cmd += ["--workdir", workdir]
×
897
        if labels:
1✔
898
            for key, value in labels.items():
×
899
                cmd += ["--label", f"{key}={value}"]
×
900
        if platform:
1✔
901
            cmd += ["--platform", platform]
1✔
902
        if ulimits:
1✔
903
            cmd += list(
×
904
                itertools.chain.from_iterable(["--ulimit", str(ulimit)] for ulimit in ulimits)
905
            )
906
        if init:
1✔
907
            cmd += ["--init"]
×
908
        if log_config:
1✔
909
            cmd += ["--log-driver", log_config.type]
×
910
            for key, value in log_config.config.items():
×
911
                cmd += ["--log-opt", f"{key}={value}"]
×
912
        if cpu_shares:
1✔
913
            cmd += ["--cpu-shares", str(cpu_shares)]
×
914
        if mem_limit:
1✔
915
            cmd += ["--memory", str(mem_limit)]
×
916

917
        if additional_flags:
1✔
918
            cmd += shlex.split(additional_flags)
1✔
919
        cmd.append(image_name)
1✔
920
        if command:
1✔
921
            cmd += command if isinstance(command, list) else [command]
1✔
922
        return cmd, env_file
1✔
923

924
    @staticmethod
1✔
925
    def _map_to_volume_param(volume: VolumeMappingSpecification) -> str:
1✔
926
        """
927
        Maps the mount volume, to a parameter for the -v docker cli argument.
928

929
        Examples:
930
        (host_path, container_path) -> host_path:container_path
931
        VolumeBind(host_dir=host_path, container_dir=container_path, read_only=True) -> host_path:container_path:ro
932

933
        :param volume: Either a SimpleVolumeBind, in essence a tuple (host_dir, container_dir), or a VolumeBind object
934
        :return: String which is passable as parameter to the docker cli -v option
935
        """
936
        # TODO: move this logic to the VolumeMappingSpecification type
937
        if isinstance(volume, Mount):
1✔
938
            return volume.to_str()
1✔
939
        else:
940
            return f"{volume[0]}:{volume[1]}"
×
941

942
    def _check_and_raise_no_such_container_error(
1✔
943
        self, container_name_or_id: str, error: subprocess.CalledProcessError
944
    ):
945
        """
946
        Check the given client invocation error and raise a `NoSuchContainer` exception if it
947
        represents a `no such container` exception from Docker or Podman.
948
        """
949
        self._check_output_and_raise_no_such_container_error(
×
950
            container_name_or_id, str(error.stdout), error=str(error.stderr)
951
        )
952

953
    def _check_output_and_raise_no_such_container_error(
1✔
954
        self, container_name_or_id: str, output: str, error: str | None = None
955
    ):
956
        """
957
        Check the given client invocation output and raise a `NoSuchContainer` exception if it
958
        represents a `no such container` exception from Docker or Podman.
959
        """
960
        possible_not_found_messages = ("No such container", "no container with name or ID")
×
961
        if any(msg.lower() in output.lower() for msg in possible_not_found_messages):
×
962
            raise NoSuchContainer(container_name_or_id, stdout=output, stderr=error)
×
963

964
    def _transform_container_labels(self, labels: str | dict[str, str]) -> dict[str, str]:
1✔
965
        """
966
        Transforms the container labels returned by the docker command from the key-value pair format to a dict
967
        :param labels: Input string, comma separated key value pairs. Example: key1=value1,key2=value2
968
        :return: Dict representation of the passed values, example: {"key1": "value1", "key2": "value2"}
969
        """
970
        if isinstance(labels, dict):
1✔
971
            return labels
×
972

973
        labels = labels.split(",")
1✔
974
        labels = [label.partition("=") for label in labels]
1✔
975
        return {label[0]: label[2] for label in labels}
1✔
976

977
    def _login_if_needed(self, auth_config: dict[str, str] | None, image_name) -> None:
1✔
978
        if auth_config:
1✔
979
            LOG.warning(
×
980
                "Using global docker login for authentication in docker_cmd_client. "
981
                "This may lead to unexpected behaviors with concurrent requests to different registries. "
982
                "Consider stop using LEGACY_DOCKER_CLIENT for thread-safe authentication."
983
            )
984
            registry = get_registry_from_image_name(image_name)
×
985
            self.login(
×
986
                username=auth_config.get("username", ""),
987
                password=auth_config.get("password", ""),
988
                registry=registry,
989
            )
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc