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

localstack / localstack / 17144436094

21 Aug 2025 11:28PM UTC coverage: 86.843% (-0.03%) from 86.876%
17144436094

push

github

web-flow
APIGW: internalize DeleteIntegrationResponse (#13046)

40 of 45 new or added lines in 1 file covered. (88.89%)

235 existing lines in 11 files now uncovered.

67068 of 77229 relevant lines covered (86.84%)

0.87 hits per line

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

49.82
/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 typing import Callable, Optional, Union
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
    BindMount,
16
    CancellableStream,
17
    ContainerClient,
18
    ContainerException,
19
    DockerContainerStats,
20
    DockerContainerStatus,
21
    DockerNotAvailable,
22
    DockerPlatform,
23
    LogConfig,
24
    NoSuchContainer,
25
    NoSuchImage,
26
    NoSuchNetwork,
27
    NoSuchObject,
28
    PortMappings,
29
    RegistryConnectionError,
30
    SimpleVolumeBind,
31
    Ulimit,
32
    Util,
33
    VolumeDirMount,
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: Optional[str] = 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:
1✔
191
            self._check_and_raise_no_such_container_error(container_name, error=e)
1✔
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
                "Docker process returned with errorcode %s" % 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
                "Docker process returned with errorcode %s" % 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
                "Docker process returned with errorcode %s" % 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
                "Docker process returned with errorcode %s" % 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
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
266
            ) from e
267

268
    def remove_container(self, container_name: str, force=True, check_existence=False) -> None:
1✔
269
        if check_existence and container_name not in self.get_running_container_names():
1✔
270
            return
×
271
        cmd = self._docker_cmd() + ["rm"]
1✔
272
        if force:
1✔
273
            cmd.append("-f")
1✔
274
        cmd.append(container_name)
1✔
275
        LOG.debug("Removing container with cmd %s", cmd)
1✔
276
        try:
1✔
277
            run(cmd)
1✔
UNCOV
278
        except subprocess.CalledProcessError as e:
×
UNCOV
279
            self._check_and_raise_no_such_container_error(container_name, error=e)
×
UNCOV
280
            raise ContainerException(
×
281
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
282
            ) from e
283

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

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

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

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

386
    def push_image(self, docker_image: str) -> None:
1✔
387
        cmd = self._docker_cmd()
×
388
        cmd += ["push", docker_image]
×
389
        LOG.debug("Pushing image with cmd: %s", cmd)
×
390
        try:
×
391
            run(cmd)
×
392
        except subprocess.CalledProcessError as e:
×
393
            if "is denied" in to_str(e.stdout):
×
394
                raise AccessDenied(docker_image)
×
395
            if "requesting higher privileges than access token allows" in to_str(e.stdout):
×
396
                raise AccessDenied(docker_image)
×
397
            if "access token has insufficient scopes" in to_str(e.stdout):
×
398
                raise AccessDenied(docker_image)
×
399
            if "does not exist" in to_str(e.stdout):
×
400
                raise NoSuchImage(docker_image)
×
401
            if "connection refused" in to_str(e.stdout):
×
402
                raise RegistryConnectionError(e.stdout)
×
403
            # note: error message 'image not known' raised by Podman client
404
            if "image not known" in to_str(e.stdout):
×
405
                raise NoSuchImage(docker_image)
×
406
            raise ContainerException(
×
407
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
408
            ) from e
409

410
    def build_image(
1✔
411
        self,
412
        dockerfile_path: str,
413
        image_name: str,
414
        context_path: str = None,
415
        platform: Optional[DockerPlatform] = None,
416
    ):
417
        cmd = self._docker_cmd()
×
418
        dockerfile_path = Util.resolve_dockerfile_path(dockerfile_path)
×
419
        context_path = context_path or os.path.dirname(dockerfile_path)
×
420
        cmd += ["build", "-t", image_name, "-f", dockerfile_path]
×
421
        if platform:
×
422
            cmd += ["--platform", platform]
×
423
        cmd += [context_path]
×
424
        LOG.debug("Building Docker image: %s", cmd)
×
425
        try:
×
426
            return run(cmd)
×
427
        except subprocess.CalledProcessError as e:
×
428
            raise ContainerException(
×
429
                f"Docker build process returned with error code {e.returncode}", e.stdout, e.stderr
430
            ) from e
431

432
    def tag_image(self, source_ref: str, target_name: str) -> None:
1✔
433
        cmd = self._docker_cmd()
×
434
        cmd += ["tag", source_ref, target_name]
×
435
        LOG.debug("Tagging Docker image %s as %s", source_ref, target_name)
×
436
        try:
×
437
            run(cmd)
×
438
        except subprocess.CalledProcessError as e:
×
439
            # handle different error messages for Docker and podman
440
            error_messages = ["No such image", "image not known"]
×
441
            if any(msg in to_str(e.stdout) for msg in error_messages):
×
442
                raise NoSuchImage(source_ref)
×
443
            raise ContainerException(
×
444
                f"Docker process returned with error code {e.returncode}", e.stdout, e.stderr
445
            ) from e
446

447
    def get_docker_image_names(
1✔
448
        self, strip_latest=True, include_tags=True, strip_wellknown_repo_prefixes: bool = True
449
    ):
450
        format_string = "{{.Repository}}:{{.Tag}}" if include_tags else "{{.Repository}}"
×
451
        cmd = self._docker_cmd()
×
452
        cmd += ["images", "--format", format_string]
×
453
        try:
×
454
            output = run(cmd)
×
455

456
            image_names = output.splitlines()
×
457
            if strip_wellknown_repo_prefixes:
×
458
                image_names = Util.strip_wellknown_repo_prefixes(image_names)
×
459
            if strip_latest:
×
460
                Util.append_without_latest(image_names)
×
461

462
            return image_names
×
463
        except Exception as e:
×
464
            LOG.info('Unable to list Docker images via "%s": %s', cmd, e)
×
465
            return []
×
466

467
    def get_container_logs(self, container_name_or_id: str, safe=False) -> str:
1✔
468
        cmd = self._docker_cmd()
1✔
469
        cmd += ["logs", container_name_or_id]
1✔
470
        try:
1✔
471
            return run(cmd)
1✔
472
        except subprocess.CalledProcessError as e:
×
473
            if safe:
×
474
                return ""
×
475
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
476
            raise ContainerException(
×
477
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
478
            ) from e
479

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

483
        cmd = self._docker_cmd()
1✔
484
        cmd += ["logs", "--follow", container_name_or_id]
1✔
485

486
        process: subprocess.Popen = run(
1✔
487
            cmd, asynchronous=True, outfile=subprocess.PIPE, stderr=subprocess.STDOUT
488
        )
489

490
        return CancellableProcessStream(process)
1✔
491

492
    def _inspect_object(self, object_name_or_id: str) -> dict[str, Union[dict, list, str]]:
1✔
493
        cmd = self._docker_cmd()
1✔
494
        cmd += ["inspect", "--format", "{{json .}}", object_name_or_id]
1✔
495
        try:
1✔
496
            cmd_result = run(cmd, print_error=False)
1✔
497
        except subprocess.CalledProcessError as e:
1✔
498
            # note: case-insensitive comparison, to support Docker and Podman output formats
499
            if "no such object" in to_str(e.stdout).lower():
1✔
500
                raise NoSuchObject(object_name_or_id, stdout=e.stdout, stderr=e.stderr)
1✔
501
            raise ContainerException(
×
502
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
503
            ) from e
504
        object_data = json.loads(cmd_result.strip())
1✔
505
        if isinstance(object_data, list):
1✔
506
            # return first list item, for compatibility with Podman API
507
            if len(object_data) == 1:
×
508
                result = object_data[0]
×
509
                # convert first character to uppercase (e.g., `name` -> `Name`), for Podman/Docker compatibility
510
                result = {first_char_to_upper(k): v for k, v in result.items()}
×
511
                return result
×
512
            LOG.info(
×
513
                "Expected a single object for `inspect` on ID %s, got %s",
514
                object_name_or_id,
515
                len(object_data),
516
            )
517
        return object_data
1✔
518

519
    def inspect_container(self, container_name_or_id: str) -> dict[str, Union[dict, str]]:
1✔
520
        try:
1✔
521
            return self._inspect_object(container_name_or_id)
1✔
522
        except NoSuchObject as e:
1✔
523
            raise NoSuchContainer(container_name_or_id=e.object_id)
×
524

525
    def inspect_image(
1✔
526
        self,
527
        image_name: str,
528
        pull: bool = True,
529
        strip_wellknown_repo_prefixes: bool = True,
530
    ) -> dict[str, Union[dict, list, str]]:
531
        image_name = self.registry_resolver_strategy.resolve(image_name)
×
532
        try:
×
533
            result = self._inspect_object(image_name)
×
534
            if strip_wellknown_repo_prefixes:
×
535
                if result.get("RepoDigests"):
×
536
                    result["RepoDigests"] = Util.strip_wellknown_repo_prefixes(
×
537
                        result["RepoDigests"]
538
                    )
539
                if result.get("RepoTags"):
×
540
                    result["RepoTags"] = Util.strip_wellknown_repo_prefixes(result["RepoTags"])
×
541
            return result
×
542
        except NoSuchObject as e:
×
543
            if pull:
×
544
                self.pull_image(image_name)
×
545
                return self.inspect_image(image_name, pull=False)
×
546
            raise NoSuchImage(image_name=e.object_id)
×
547

548
    def create_network(self, network_name: str) -> str:
1✔
549
        cmd = self._docker_cmd()
1✔
550
        cmd += ["network", "create", network_name]
1✔
551
        try:
1✔
552
            return run(cmd).strip()
1✔
553
        except subprocess.CalledProcessError as e:
×
554
            raise ContainerException(
×
555
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
556
            ) from e
557

558
    def delete_network(self, network_name: str) -> None:
1✔
559
        cmd = self._docker_cmd()
1✔
560
        cmd += ["network", "rm", network_name]
1✔
561
        try:
1✔
562
            run(cmd)
1✔
563
        except subprocess.CalledProcessError as e:
×
564
            stdout_str = to_str(e.stdout)
×
565
            if re.match(r".*network (.*) not found.*", stdout_str):
×
566
                raise NoSuchNetwork(network_name=network_name)
×
567
            else:
568
                raise ContainerException(
×
569
                    "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
570
                ) from e
571

572
    def inspect_network(self, network_name: str) -> dict[str, Union[dict, str]]:
1✔
573
        try:
1✔
574
            return self._inspect_object(network_name)
1✔
575
        except NoSuchObject as e:
1✔
576
            raise NoSuchNetwork(network_name=e.object_id)
1✔
577

578
    def connect_container_to_network(
1✔
579
        self,
580
        network_name: str,
581
        container_name_or_id: str,
582
        aliases: Optional[list] = None,
583
        link_local_ips: list[str] = None,
584
    ) -> None:
585
        LOG.debug(
×
586
            "Connecting container '%s' to network '%s' with aliases '%s'",
587
            container_name_or_id,
588
            network_name,
589
            aliases,
590
        )
591
        cmd = self._docker_cmd()
×
592
        cmd += ["network", "connect"]
×
593
        if aliases:
×
594
            cmd += ["--alias", ",".join(aliases)]
×
595
        if link_local_ips:
×
596
            cmd += ["--link-local-ip", ",".join(link_local_ips)]
×
597
        cmd += [network_name, container_name_or_id]
×
598
        try:
×
599
            run(cmd)
×
600
        except subprocess.CalledProcessError as e:
×
601
            stdout_str = to_str(e.stdout)
×
602
            if re.match(r".*network (.*) not found.*", stdout_str):
×
603
                raise NoSuchNetwork(network_name=network_name)
×
604
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
605
            raise ContainerException(
×
606
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
607
            ) from e
608

609
    def disconnect_container_from_network(
1✔
610
        self, network_name: str, container_name_or_id: str
611
    ) -> None:
612
        LOG.debug(
1✔
613
            "Disconnecting container '%s' from network '%s'", container_name_or_id, network_name
614
        )
615
        cmd = self._docker_cmd() + ["network", "disconnect", network_name, container_name_or_id]
1✔
616
        try:
1✔
617
            run(cmd)
1✔
618
        except subprocess.CalledProcessError as e:
×
619
            stdout_str = to_str(e.stdout)
×
620
            if re.match(r".*network (.*) not found.*", stdout_str):
×
621
                raise NoSuchNetwork(network_name=network_name)
×
622
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
623
            raise ContainerException(
×
624
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
625
            ) from e
626

627
    def get_container_ip(self, container_name_or_id: str) -> str:
1✔
628
        cmd = self._docker_cmd()
1✔
629
        cmd += [
1✔
630
            "inspect",
631
            "--format",
632
            "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}",
633
            container_name_or_id,
634
        ]
635
        try:
1✔
636
            result = run(cmd).strip()
1✔
637
            return result.split(" ")[0] if result else ""
1✔
638
        except subprocess.CalledProcessError as e:
×
639
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
640
            # consider different error messages for Podman
641
            if "no such object" in to_str(e.stdout).lower():
×
642
                raise NoSuchContainer(container_name_or_id, stdout=e.stdout, stderr=e.stderr)
×
643
            raise ContainerException(
×
644
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
645
            ) from e
646

647
    def login(self, username: str, password: str, registry: Optional[str] = None) -> None:
1✔
648
        cmd = self._docker_cmd()
×
649
        # TODO specify password via stdin
650
        cmd += ["login", "-u", username, "-p", password]
×
651
        if registry:
×
652
            cmd.append(registry)
×
653
        try:
×
654
            run(cmd)
×
655
        except subprocess.CalledProcessError as e:
×
656
            raise ContainerException(
×
657
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
658
            ) from e
659

660
    @functools.cache
1✔
661
    def has_docker(self) -> bool:
1✔
662
        try:
1✔
663
            # do not use self._docker_cmd here (would result in a loop)
664
            run(shlex.split(config.DOCKER_CMD) + ["ps"])
1✔
665
            return True
1✔
666
        except (subprocess.CalledProcessError, FileNotFoundError):
1✔
667
            return False
1✔
668

669
    def create_container(self, image_name: str, **kwargs) -> str:
1✔
670
        image_name = self.registry_resolver_strategy.resolve(image_name)
1✔
671
        cmd, env_file = self._build_run_create_cmd("create", image_name, **kwargs)
1✔
672
        LOG.debug("Create container with cmd: %s", cmd)
1✔
673
        try:
1✔
674
            container_id = run(cmd)
1✔
675
            # Note: strip off Docker warning messages like "DNS setting (--dns=127.0.0.1) may fail in containers"
676
            container_id = container_id.strip().split("\n")[-1]
1✔
677
            return container_id.strip()
1✔
678
        except subprocess.CalledProcessError as e:
×
679
            error_messages = ["Unable to find image", "Trying to pull"]
×
680
            if any(msg in to_str(e.stdout) for msg in error_messages):
×
681
                raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr)
×
682
            raise ContainerException(
×
683
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
684
            ) from e
685
        finally:
686
            Util.rm_env_vars_file(env_file)
1✔
687

688
    def run_container(self, image_name: str, stdin=None, **kwargs) -> tuple[bytes, bytes]:
1✔
689
        image_name = self.registry_resolver_strategy.resolve(image_name)
×
690
        cmd, env_file = self._build_run_create_cmd("run", image_name, **kwargs)
×
691
        LOG.debug("Run container with cmd: %s", cmd)
×
692
        try:
×
693
            return self._run_async_cmd(cmd, stdin, kwargs.get("name") or "", image_name)
×
694
        except ContainerException as e:
×
695
            if "Trying to pull" in str(e) and "access to the resource is denied" in str(e):
×
696
                raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr) from e
×
697
            raise
×
698
        finally:
699
            Util.rm_env_vars_file(env_file)
×
700

701
    def exec_in_container(
1✔
702
        self,
703
        container_name_or_id: str,
704
        command: Union[list[str], str],
705
        interactive=False,
706
        detach=False,
707
        env_vars: Optional[dict[str, Optional[str]]] = None,
708
        stdin: Optional[bytes] = None,
709
        user: Optional[str] = None,
710
        workdir: Optional[str] = None,
711
    ) -> tuple[bytes, bytes]:
712
        env_file = None
1✔
713
        cmd = self._docker_cmd()
1✔
714
        cmd.append("exec")
1✔
715
        if interactive:
1✔
716
            cmd.append("--interactive")
×
717
        if detach:
1✔
718
            cmd.append("--detach")
×
719
        if user:
1✔
720
            cmd += ["--user", user]
×
721
        if workdir:
1✔
722
            cmd += ["--workdir", workdir]
×
723
        if env_vars:
1✔
724
            env_flag, env_file = Util.create_env_vars_file_flag(env_vars)
×
725
            cmd += env_flag
×
726
        cmd.append(container_name_or_id)
1✔
727
        cmd += command if isinstance(command, list) else [command]
1✔
728
        LOG.debug("Execute command in container: %s", cmd)
1✔
729
        try:
1✔
730
            return self._run_async_cmd(cmd, stdin, container_name_or_id)
1✔
731
        finally:
732
            Util.rm_env_vars_file(env_file)
1✔
733

734
    def start_container(
1✔
735
        self,
736
        container_name_or_id: str,
737
        stdin=None,
738
        interactive: bool = False,
739
        attach: bool = False,
740
        flags: Optional[str] = None,
741
    ) -> tuple[bytes, bytes]:
742
        cmd = self._docker_cmd() + ["start"]
1✔
743
        if flags:
1✔
744
            cmd.append(flags)
×
745
        if interactive:
1✔
746
            cmd.append("--interactive")
×
747
        if attach:
1✔
748
            cmd.append("--attach")
×
749
        cmd.append(container_name_or_id)
1✔
750
        LOG.debug("Start container with cmd: %s", cmd)
1✔
751
        return self._run_async_cmd(cmd, stdin, container_name_or_id)
1✔
752

753
    def attach_to_container(self, container_name_or_id: str):
1✔
754
        cmd = self._docker_cmd() + ["attach", container_name_or_id]
1✔
755
        LOG.debug("Attaching to container %s", container_name_or_id)
1✔
756
        return self._run_async_cmd(cmd, stdin=None, container_name=container_name_or_id)
1✔
757

758
    def _run_async_cmd(
1✔
759
        self, cmd: list[str], stdin: bytes, container_name: str, image_name=None
760
    ) -> tuple[bytes, bytes]:
761
        kwargs = {
1✔
762
            "inherit_env": True,
763
            "asynchronous": True,
764
            "stderr": subprocess.PIPE,
765
            "outfile": self.default_run_outfile or subprocess.PIPE,
766
        }
767
        if stdin:
1✔
768
            kwargs["stdin"] = True
×
769
        try:
1✔
770
            process = run(cmd, **kwargs)
1✔
771
            stdout, stderr = process.communicate(input=stdin)
1✔
772
            if process.returncode != 0:
1✔
773
                raise subprocess.CalledProcessError(
×
774
                    process.returncode,
775
                    cmd,
776
                    stdout,
777
                    stderr,
778
                )
779
            else:
780
                return stdout, stderr
1✔
781
        except subprocess.CalledProcessError as e:
×
782
            stderr_str = to_str(e.stderr)
×
783
            if "Unable to find image" in stderr_str:
×
784
                raise NoSuchImage(image_name or "", stdout=e.stdout, stderr=e.stderr)
×
785
            # consider different error messages for Docker/Podman
786
            error_messages = ("No such container", "no container with name or ID")
×
787
            if any(msg.lower() in to_str(e.stderr).lower() for msg in error_messages):
×
788
                raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr)
×
789
            raise ContainerException(
×
790
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
791
            ) from e
792

793
    def _build_run_create_cmd(
1✔
794
        self,
795
        action: str,
796
        image_name: str,
797
        *,
798
        name: Optional[str] = None,
799
        entrypoint: Optional[Union[list[str], str]] = None,
800
        remove: bool = False,
801
        interactive: bool = False,
802
        tty: bool = False,
803
        detach: bool = False,
804
        command: Optional[Union[list[str], str]] = None,
805
        volumes: Optional[list[SimpleVolumeBind]] = None,
806
        ports: Optional[PortMappings] = None,
807
        exposed_ports: Optional[list[str]] = None,
808
        env_vars: Optional[dict[str, str]] = None,
809
        user: Optional[str] = None,
810
        cap_add: Optional[list[str]] = None,
811
        cap_drop: Optional[list[str]] = None,
812
        security_opt: Optional[list[str]] = None,
813
        network: Optional[str] = None,
814
        dns: Optional[Union[str, list[str]]] = None,
815
        additional_flags: Optional[str] = None,
816
        workdir: Optional[str] = None,
817
        privileged: Optional[bool] = None,
818
        labels: Optional[dict[str, str]] = None,
819
        platform: Optional[DockerPlatform] = None,
820
        ulimits: Optional[list[Ulimit]] = None,
821
        init: Optional[bool] = None,
822
        log_config: Optional[LogConfig] = None,
823
    ) -> tuple[list[str], str]:
824
        env_file = None
1✔
825
        cmd = self._docker_cmd() + [action]
1✔
826
        if remove:
1✔
827
            cmd.append("--rm")
1✔
828
        if name:
1✔
829
            cmd += ["--name", name]
1✔
830
        if entrypoint is not None:  # empty string entrypoint can be intentional
1✔
831
            if isinstance(entrypoint, str):
1✔
832
                cmd += ["--entrypoint", entrypoint]
1✔
833
            else:
834
                cmd += ["--entrypoint", shlex.join(entrypoint)]
×
835
        if privileged:
1✔
836
            cmd += ["--privileged"]
×
837
        if volumes:
1✔
838
            cmd += [
1✔
839
                param for volume in volumes for param in ["-v", self._map_to_volume_param(volume)]
840
            ]
841
        if interactive:
1✔
842
            cmd.append("--interactive")
×
843
        if tty:
1✔
844
            cmd.append("--tty")
×
845
        if detach:
1✔
846
            cmd.append("--detach")
×
847
        if ports:
1✔
848
            cmd += ports.to_list()
1✔
849
        if exposed_ports:
1✔
850
            cmd += list(itertools.chain.from_iterable(["--expose", port] for port in exposed_ports))
×
851
        if env_vars:
1✔
852
            env_flags, env_file = Util.create_env_vars_file_flag(env_vars)
1✔
853
            cmd += env_flags
1✔
854
        if user:
1✔
855
            cmd += ["--user", user]
×
856
        if cap_add:
1✔
857
            cmd += list(itertools.chain.from_iterable(["--cap-add", cap] for cap in cap_add))
×
858
        if cap_drop:
1✔
859
            cmd += list(itertools.chain.from_iterable(["--cap-drop", cap] for cap in cap_drop))
×
860
        if security_opt:
1✔
861
            cmd += list(
×
862
                itertools.chain.from_iterable(["--security-opt", opt] for opt in security_opt)
863
            )
864
        if network:
1✔
865
            cmd += ["--network", network]
1✔
866
        if dns:
1✔
867
            for dns_server in ensure_list(dns):
×
868
                cmd += ["--dns", dns_server]
×
869
        if workdir:
1✔
870
            cmd += ["--workdir", workdir]
×
871
        if labels:
1✔
872
            for key, value in labels.items():
×
873
                cmd += ["--label", f"{key}={value}"]
×
874
        if platform:
1✔
875
            cmd += ["--platform", platform]
1✔
876
        if ulimits:
1✔
877
            cmd += list(
×
878
                itertools.chain.from_iterable(["--ulimit", str(ulimit)] for ulimit in ulimits)
879
            )
880
        if init:
1✔
881
            cmd += ["--init"]
×
882
        if log_config:
1✔
883
            cmd += ["--log-driver", log_config.type]
×
884
            for key, value in log_config.config.items():
×
885
                cmd += ["--log-opt", f"{key}={value}"]
×
886

887
        if additional_flags:
1✔
888
            cmd += shlex.split(additional_flags)
1✔
889
        cmd.append(image_name)
1✔
890
        if command:
1✔
891
            cmd += command if isinstance(command, list) else [command]
1✔
892
        return cmd, env_file
1✔
893

894
    @staticmethod
1✔
895
    def _map_to_volume_param(volume: Union[SimpleVolumeBind, BindMount, VolumeDirMount]) -> str:
1✔
896
        """
897
        Maps the mount volume, to a parameter for the -v docker cli argument.
898

899
        Examples:
900
        (host_path, container_path) -> host_path:container_path
901
        VolumeBind(host_dir=host_path, container_dir=container_path, read_only=True) -> host_path:container_path:ro
902

903
        :param volume: Either a SimpleVolumeBind, in essence a tuple (host_dir, container_dir), or a VolumeBind object
904
        :return: String which is passable as parameter to the docker cli -v option
905
        """
906
        if isinstance(volume, (BindMount, VolumeDirMount)):
1✔
907
            return volume.to_str()
1✔
908
        else:
909
            return f"{volume[0]}:{volume[1]}"
×
910

911
    def _check_and_raise_no_such_container_error(
1✔
912
        self, container_name_or_id: str, error: subprocess.CalledProcessError
913
    ):
914
        """
915
        Check the given client invocation error and raise a `NoSuchContainer` exception if it
916
        represents a `no such container` exception from Docker or Podman.
917
        """
918

919
        # consider different error messages for Docker/Podman
920
        error_messages = ("No such container", "no container with name or ID")
1✔
921
        process_stdout_lower = to_str(error.stdout).lower()
1✔
922
        if any(msg.lower() in process_stdout_lower for msg in error_messages):
1✔
923
            raise NoSuchContainer(container_name_or_id, stdout=error.stdout, stderr=error.stderr)
1✔
924

925
    def _transform_container_labels(self, labels: Union[str, dict[str, str]]) -> dict[str, str]:
1✔
926
        """
927
        Transforms the container labels returned by the docker command from the key-value pair format to a dict
928
        :param labels: Input string, comma separated key value pairs. Example: key1=value1,key2=value2
929
        :return: Dict representation of the passed values, example: {"key1": "value1", "key2": "value2"}
930
        """
931
        if isinstance(labels, dict):
1✔
932
            return labels
×
933

934
        labels = labels.split(",")
1✔
935
        labels = [label.partition("=") for label in labels]
1✔
936
        return {label[0]: label[2] for label in labels}
1✔
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