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

localstack / localstack / 19752450189

27 Nov 2025 04:19PM UTC coverage: 86.879% (+0.008%) from 86.871%
19752450189

push

github

web-flow
S3: fix change in behavior in CreateBucketConfiguration (#13427)

3 of 3 new or added lines in 1 file covered. (100.0%)

6 existing lines in 2 files now uncovered.

68878 of 79280 relevant lines covered (86.88%)

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 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
    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: 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:
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
                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)
×
UNCOV
285
        except subprocess.CalledProcessError as e:
×
UNCOV
286
            if not force:
×
287
                self._check_and_raise_no_such_container_error(container_name, error=e)
×
UNCOV
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
    ) -> None:
371
        cmd = self._docker_cmd()
1✔
372
        docker_image = self.registry_resolver_strategy.resolve(docker_image)
1✔
373
        cmd += ["pull", docker_image]
1✔
374
        if platform:
1✔
375
            cmd += ["--platform", platform]
1✔
376
        LOG.debug("Pulling image with cmd: %s", cmd)
1✔
377
        try:
1✔
378
            result = run(cmd)
1✔
379
            # note: we could stream the results, but we'll just process everything at the end for now
380
            if log_handler:
1✔
381
                for line in result.split("\n"):
×
382
                    log_handler(to_str(line))
×
383
        except subprocess.CalledProcessError as e:
×
384
            stdout_str = to_str(e.stdout)
×
385
            if "pull access denied" in stdout_str:
×
386
                raise NoSuchImage(docker_image, stdout=e.stdout, stderr=e.stderr)
×
387
            # note: error message 'access to the resource is denied' raised by Podman client
388
            if "Trying to pull" in stdout_str and "access to the resource is denied" in stdout_str:
×
389
                raise NoSuchImage(docker_image, stdout=e.stdout, stderr=e.stderr)
×
390
            raise ContainerException(
×
391
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
392
            ) from e
393

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

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

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

455
    def get_docker_image_names(
1✔
456
        self, strip_latest=True, include_tags=True, strip_wellknown_repo_prefixes: bool = True
457
    ):
458
        format_string = "{{.Repository}}:{{.Tag}}" if include_tags else "{{.Repository}}"
×
459
        cmd = self._docker_cmd()
×
460
        cmd += ["images", "--format", format_string]
×
461
        try:
×
462
            output = run(cmd)
×
463

464
            image_names = output.splitlines()
×
465
            if strip_wellknown_repo_prefixes:
×
466
                image_names = Util.strip_wellknown_repo_prefixes(image_names)
×
467
            if strip_latest:
×
468
                Util.append_without_latest(image_names)
×
469

470
            return image_names
×
471
        except Exception as e:
×
472
            LOG.info('Unable to list Docker images via "%s": %s', cmd, e)
×
473
            return []
×
474

475
    def get_container_logs(self, container_name_or_id: str, safe=False) -> str:
1✔
476
        cmd = self._docker_cmd()
1✔
477
        cmd += ["logs", container_name_or_id]
1✔
478
        try:
1✔
479
            return run(cmd)
1✔
480
        except subprocess.CalledProcessError as e:
×
481
            if safe:
×
482
                return ""
×
483
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
484
            raise ContainerException(
×
485
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
486
            ) from e
487

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

491
        cmd = self._docker_cmd()
1✔
492
        cmd += ["logs", "--follow", container_name_or_id]
1✔
493

494
        process: subprocess.Popen = run(
1✔
495
            cmd, asynchronous=True, outfile=subprocess.PIPE, stderr=subprocess.STDOUT
496
        )
497

498
        return CancellableProcessStream(process)
1✔
499

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

527
    def inspect_container(self, container_name_or_id: str) -> dict[str, dict | str]:
1✔
528
        try:
1✔
529
            return self._inspect_object(container_name_or_id)
1✔
530
        except NoSuchObject as e:
1✔
531
            raise NoSuchContainer(container_name_or_id=e.object_id)
×
532

533
    def inspect_image(
1✔
534
        self,
535
        image_name: str,
536
        pull: bool = True,
537
        strip_wellknown_repo_prefixes: bool = True,
538
    ) -> dict[str, dict | list | str]:
539
        image_name = self.registry_resolver_strategy.resolve(image_name)
×
540
        try:
×
541
            result = self._inspect_object(image_name)
×
542
            if strip_wellknown_repo_prefixes:
×
543
                if result.get("RepoDigests"):
×
544
                    result["RepoDigests"] = Util.strip_wellknown_repo_prefixes(
×
545
                        result["RepoDigests"]
546
                    )
547
                if result.get("RepoTags"):
×
548
                    result["RepoTags"] = Util.strip_wellknown_repo_prefixes(result["RepoTags"])
×
549
            return result
×
550
        except NoSuchObject as e:
×
551
            if pull:
×
552
                self.pull_image(image_name)
×
553
                return self.inspect_image(image_name, pull=False)
×
554
            raise NoSuchImage(image_name=e.object_id)
×
555

556
    def create_network(self, network_name: str) -> str:
1✔
557
        cmd = self._docker_cmd()
1✔
558
        cmd += ["network", "create", network_name]
1✔
559
        try:
1✔
560
            return run(cmd).strip()
1✔
561
        except subprocess.CalledProcessError as e:
×
562
            raise ContainerException(
×
563
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
564
            ) from e
565

566
    def delete_network(self, network_name: str) -> None:
1✔
567
        cmd = self._docker_cmd()
1✔
568
        cmd += ["network", "rm", network_name]
1✔
569
        try:
1✔
570
            run(cmd)
1✔
571
        except subprocess.CalledProcessError as e:
×
572
            stdout_str = to_str(e.stdout)
×
573
            if re.match(r".*network (.*) not found.*", stdout_str):
×
574
                raise NoSuchNetwork(network_name=network_name)
×
575
            else:
576
                raise ContainerException(
×
577
                    f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
578
                ) from e
579

580
    def inspect_network(self, network_name: str) -> dict[str, dict | str]:
1✔
581
        try:
1✔
582
            return self._inspect_object(network_name)
1✔
583
        except NoSuchObject as e:
1✔
584
            raise NoSuchNetwork(network_name=e.object_id)
1✔
585

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

617
    def disconnect_container_from_network(
1✔
618
        self, network_name: str, container_name_or_id: str
619
    ) -> None:
620
        LOG.debug(
1✔
621
            "Disconnecting container '%s' from network '%s'", container_name_or_id, network_name
622
        )
623
        cmd = self._docker_cmd() + ["network", "disconnect", network_name, container_name_or_id]
1✔
624
        try:
1✔
625
            run(cmd)
1✔
626
        except subprocess.CalledProcessError as e:
×
627
            stdout_str = to_str(e.stdout)
×
628
            if re.match(r".*network (.*) not found.*", stdout_str):
×
629
                raise NoSuchNetwork(network_name=network_name)
×
630
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
631
            raise ContainerException(
×
632
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
633
            ) from e
634

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

655
    def login(self, username: str, password: str, registry: str | None = None) -> None:
1✔
656
        cmd = self._docker_cmd()
×
657
        # TODO specify password via stdin
658
        cmd += ["login", "-u", username, "-p", password]
×
659
        if registry:
×
660
            cmd.append(registry)
×
661
        try:
×
662
            run(cmd)
×
663
        except subprocess.CalledProcessError as e:
×
664
            raise ContainerException(
×
665
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
666
            ) from e
667

668
    @functools.cache
1✔
669
    def has_docker(self) -> bool:
1✔
670
        try:
1✔
671
            # do not use self._docker_cmd here (would result in a loop)
672
            run(shlex.split(config.DOCKER_CMD) + ["ps"])
1✔
673
            return True
1✔
674
        except (subprocess.CalledProcessError, FileNotFoundError):
1✔
675
            return False
1✔
676

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

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

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

742
    def start_container(
1✔
743
        self,
744
        container_name_or_id: str,
745
        stdin=None,
746
        interactive: bool = False,
747
        attach: bool = False,
748
        flags: str | None = None,
749
    ) -> tuple[bytes, bytes]:
750
        cmd = self._docker_cmd() + ["start"]
1✔
751
        if flags:
1✔
752
            cmd.append(flags)
×
753
        if interactive:
1✔
754
            cmd.append("--interactive")
×
755
        if attach:
1✔
756
            cmd.append("--attach")
×
757
        cmd.append(container_name_or_id)
1✔
758
        LOG.debug("Start container with cmd: %s", cmd)
1✔
759
        return self._run_async_cmd(cmd, stdin, container_name_or_id)
1✔
760

761
    def attach_to_container(self, container_name_or_id: str):
1✔
762
        cmd = self._docker_cmd() + ["attach", container_name_or_id]
1✔
763
        LOG.debug("Attaching to container %s", container_name_or_id)
1✔
764
        return self._run_async_cmd(cmd, stdin=None, container_name=container_name_or_id)
1✔
765

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

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

895
        if additional_flags:
1✔
896
            cmd += shlex.split(additional_flags)
1✔
897
        cmd.append(image_name)
1✔
898
        if command:
1✔
899
            cmd += command if isinstance(command, list) else [command]
1✔
900
        return cmd, env_file
1✔
901

902
    @staticmethod
1✔
903
    def _map_to_volume_param(volume: SimpleVolumeBind | BindMount | VolumeDirMount) -> str:
1✔
904
        """
905
        Maps the mount volume, to a parameter for the -v docker cli argument.
906

907
        Examples:
908
        (host_path, container_path) -> host_path:container_path
909
        VolumeBind(host_dir=host_path, container_dir=container_path, read_only=True) -> host_path:container_path:ro
910

911
        :param volume: Either a SimpleVolumeBind, in essence a tuple (host_dir, container_dir), or a VolumeBind object
912
        :return: String which is passable as parameter to the docker cli -v option
913
        """
914
        if isinstance(volume, (BindMount, VolumeDirMount)):
1✔
915
            return volume.to_str()
1✔
916
        else:
917
            return f"{volume[0]}:{volume[1]}"
×
918

919
    def _check_and_raise_no_such_container_error(
1✔
920
        self, container_name_or_id: str, error: subprocess.CalledProcessError
921
    ):
922
        """
923
        Check the given client invocation error and raise a `NoSuchContainer` exception if it
924
        represents a `no such container` exception from Docker or Podman.
925
        """
926
        self._check_output_and_raise_no_such_container_error(
1✔
927
            container_name_or_id, str(error.stdout), error=str(error.stderr)
928
        )
929

930
    def _check_output_and_raise_no_such_container_error(
1✔
931
        self, container_name_or_id: str, output: str, error: str | None = None
932
    ):
933
        """
934
        Check the given client invocation output and raise a `NoSuchContainer` exception if it
935
        represents a `no such container` exception from Docker or Podman.
936
        """
937
        possible_not_found_messages = ("No such container", "no container with name or ID")
1✔
938
        if any(msg.lower() in output.lower() for msg in possible_not_found_messages):
1✔
939
            raise NoSuchContainer(container_name_or_id, stdout=output, stderr=error)
1✔
940

941
    def _transform_container_labels(self, labels: str | dict[str, str]) -> dict[str, str]:
1✔
942
        """
943
        Transforms the container labels returned by the docker command from the key-value pair format to a dict
944
        :param labels: Input string, comma separated key value pairs. Example: key1=value1,key2=value2
945
        :return: Dict representation of the passed values, example: {"key1": "value1", "key2": "value2"}
946
        """
947
        if isinstance(labels, dict):
1✔
948
            return labels
×
949

950
        labels = labels.split(",")
1✔
951
        labels = [label.partition("=") for label in labels]
1✔
952
        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