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

localstack / localstack / a2d64f5c-fd99-46a4-81e3-cf1df888ed04

18 Apr 2025 08:38AM UTC coverage: 86.281% (+0.002%) from 86.279%
a2d64f5c-fd99-46a4-81e3-cf1df888ed04

push

circleci

web-flow
apply fix for podman container labels dict (#12526)

Co-authored-by: Tjeerd Ritsma <tjeerd@playgroundtech.io>

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

6 existing lines in 1 file now uncovered.

63892 of 74051 relevant lines covered (86.28%)

0.86 hits per line

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

38.6
/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 Dict, List, Optional, Tuple, 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__()
×
46
        self.process = process
×
47

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

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

57
    def close(self):
1✔
58
        return self.process.terminate()
×
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✔
278
        except subprocess.CalledProcessError as e:
×
279
            self._check_and_raise_no_such_container_error(container_name, error=e)
×
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(self, docker_image: str, platform: Optional[DockerPlatform] = None) -> None:
1✔
358
        cmd = self._docker_cmd()
1✔
359
        cmd += ["pull", docker_image]
1✔
360
        if platform:
1✔
361
            cmd += ["--platform", platform]
1✔
362
        LOG.debug("Pulling image with cmd: %s", cmd)
1✔
363
        try:
1✔
364
            run(cmd)
1✔
365
        except subprocess.CalledProcessError as e:
×
366
            stdout_str = to_str(e.stdout)
×
367
            if "pull access denied" in stdout_str:
×
368
                raise NoSuchImage(docker_image, stdout=e.stdout, stderr=e.stderr)
×
369
            # note: error message 'access to the resource is denied' raised by Podman client
370
            if "Trying to pull" in stdout_str and "access to the resource is denied" in stdout_str:
×
371
                raise NoSuchImage(docker_image, stdout=e.stdout, stderr=e.stderr)
×
372
            raise ContainerException(
×
373
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
374
            ) from e
375

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

400
    def build_image(
1✔
401
        self,
402
        dockerfile_path: str,
403
        image_name: str,
404
        context_path: str = None,
405
        platform: Optional[DockerPlatform] = None,
406
    ):
407
        cmd = self._docker_cmd()
×
408
        dockerfile_path = Util.resolve_dockerfile_path(dockerfile_path)
×
409
        context_path = context_path or os.path.dirname(dockerfile_path)
×
410
        cmd += ["build", "-t", image_name, "-f", dockerfile_path]
×
411
        if platform:
×
412
            cmd += ["--platform", platform]
×
413
        cmd += [context_path]
×
414
        LOG.debug("Building Docker image: %s", cmd)
×
415
        try:
×
416
            return run(cmd)
×
417
        except subprocess.CalledProcessError as e:
×
418
            raise ContainerException(
×
419
                f"Docker build process returned with error code {e.returncode}", e.stdout, e.stderr
420
            ) from e
421

422
    def tag_image(self, source_ref: str, target_name: str) -> None:
1✔
423
        cmd = self._docker_cmd()
×
424
        cmd += ["tag", source_ref, target_name]
×
425
        LOG.debug("Tagging Docker image %s as %s", source_ref, target_name)
×
426
        try:
×
427
            run(cmd)
×
428
        except subprocess.CalledProcessError as e:
×
429
            # handle different error messages for Docker and podman
430
            error_messages = ["No such image", "image not known"]
×
431
            if any(msg in to_str(e.stdout) for msg in error_messages):
×
432
                raise NoSuchImage(source_ref)
×
433
            raise ContainerException(
×
434
                f"Docker process returned with error code {e.returncode}", e.stdout, e.stderr
435
            ) from e
436

437
    def get_docker_image_names(
1✔
438
        self, strip_latest=True, include_tags=True, strip_wellknown_repo_prefixes: bool = True
439
    ):
440
        format_string = "{{.Repository}}:{{.Tag}}" if include_tags else "{{.Repository}}"
×
441
        cmd = self._docker_cmd()
×
442
        cmd += ["images", "--format", format_string]
×
443
        try:
×
444
            output = run(cmd)
×
445

446
            image_names = output.splitlines()
×
447
            if strip_wellknown_repo_prefixes:
×
448
                image_names = Util.strip_wellknown_repo_prefixes(image_names)
×
449
            if strip_latest:
×
450
                Util.append_without_latest(image_names)
×
451

452
            return image_names
×
453
        except Exception as e:
×
454
            LOG.info('Unable to list Docker images via "%s": %s', cmd, e)
×
455
            return []
×
456

457
    def get_container_logs(self, container_name_or_id: str, safe=False) -> str:
1✔
458
        cmd = self._docker_cmd()
×
459
        cmd += ["logs", container_name_or_id]
×
460
        try:
×
461
            return run(cmd)
×
462
        except subprocess.CalledProcessError as e:
×
463
            if safe:
×
464
                return ""
×
465
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
466
            raise ContainerException(
×
467
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
468
            ) from e
469

470
    def stream_container_logs(self, container_name_or_id: str) -> CancellableStream:
1✔
471
        self.inspect_container(container_name_or_id)  # guard to check whether container is there
×
472

473
        cmd = self._docker_cmd()
×
474
        cmd += ["logs", "--follow", container_name_or_id]
×
475

476
        process: subprocess.Popen = run(
×
477
            cmd, asynchronous=True, outfile=subprocess.PIPE, stderr=subprocess.STDOUT
478
        )
479

480
        return CancellableProcessStream(process)
×
481

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

509
    def inspect_container(self, container_name_or_id: str) -> Dict[str, Union[Dict, str]]:
1✔
510
        try:
1✔
511
            return self._inspect_object(container_name_or_id)
1✔
512
        except NoSuchObject as e:
×
513
            raise NoSuchContainer(container_name_or_id=e.object_id)
×
514

515
    def inspect_image(
1✔
516
        self,
517
        image_name: str,
518
        pull: bool = True,
519
        strip_wellknown_repo_prefixes: bool = True,
520
    ) -> Dict[str, Union[dict, list, str]]:
521
        try:
×
522
            result = self._inspect_object(image_name)
×
523
            if strip_wellknown_repo_prefixes:
×
524
                if result.get("RepoDigests"):
×
525
                    result["RepoDigests"] = Util.strip_wellknown_repo_prefixes(
×
526
                        result["RepoDigests"]
527
                    )
528
                if result.get("RepoTags"):
×
529
                    result["RepoTags"] = Util.strip_wellknown_repo_prefixes(result["RepoTags"])
×
530
            return result
×
531
        except NoSuchObject as e:
×
532
            if pull:
×
533
                self.pull_image(image_name)
×
534
                return self.inspect_image(image_name, pull=False)
×
535
            raise NoSuchImage(image_name=e.object_id)
×
536

537
    def create_network(self, network_name: str) -> str:
1✔
538
        cmd = self._docker_cmd()
×
539
        cmd += ["network", "create", network_name]
×
540
        try:
×
541
            return run(cmd).strip()
×
542
        except subprocess.CalledProcessError as e:
×
543
            raise ContainerException(
×
544
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
545
            ) from e
546

547
    def delete_network(self, network_name: str) -> None:
1✔
548
        cmd = self._docker_cmd()
×
549
        cmd += ["network", "rm", network_name]
×
550
        try:
×
551
            run(cmd)
×
552
        except subprocess.CalledProcessError as e:
×
553
            stdout_str = to_str(e.stdout)
×
554
            if re.match(r".*network (.*) not found.*", stdout_str):
×
555
                raise NoSuchNetwork(network_name=network_name)
×
556
            else:
557
                raise ContainerException(
×
558
                    "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
559
                ) from e
560

561
    def inspect_network(self, network_name: str) -> Dict[str, Union[Dict, str]]:
1✔
562
        try:
1✔
563
            return self._inspect_object(network_name)
1✔
564
        except NoSuchObject as e:
×
565
            raise NoSuchNetwork(network_name=e.object_id)
×
566

567
    def connect_container_to_network(
1✔
568
        self,
569
        network_name: str,
570
        container_name_or_id: str,
571
        aliases: Optional[List] = None,
572
        link_local_ips: List[str] = None,
573
    ) -> None:
574
        LOG.debug(
×
575
            "Connecting container '%s' to network '%s' with aliases '%s'",
576
            container_name_or_id,
577
            network_name,
578
            aliases,
579
        )
580
        cmd = self._docker_cmd()
×
581
        cmd += ["network", "connect"]
×
582
        if aliases:
×
583
            cmd += ["--alias", ",".join(aliases)]
×
584
        if link_local_ips:
×
585
            cmd += ["--link-local-ip", ",".join(link_local_ips)]
×
586
        cmd += [network_name, container_name_or_id]
×
587
        try:
×
588
            run(cmd)
×
589
        except subprocess.CalledProcessError as e:
×
590
            stdout_str = to_str(e.stdout)
×
591
            if re.match(r".*network (.*) not found.*", stdout_str):
×
592
                raise NoSuchNetwork(network_name=network_name)
×
593
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
594
            raise ContainerException(
×
595
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
596
            ) from e
597

598
    def disconnect_container_from_network(
1✔
599
        self, network_name: str, container_name_or_id: str
600
    ) -> None:
601
        LOG.debug(
×
602
            "Disconnecting container '%s' from network '%s'", container_name_or_id, network_name
603
        )
604
        cmd = self._docker_cmd() + ["network", "disconnect", network_name, container_name_or_id]
×
605
        try:
×
606
            run(cmd)
×
607
        except subprocess.CalledProcessError as e:
×
608
            stdout_str = to_str(e.stdout)
×
609
            if re.match(r".*network (.*) not found.*", stdout_str):
×
610
                raise NoSuchNetwork(network_name=network_name)
×
611
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
612
            raise ContainerException(
×
613
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
614
            ) from e
615

616
    def get_container_ip(self, container_name_or_id: str) -> str:
1✔
617
        cmd = self._docker_cmd()
×
618
        cmd += [
×
619
            "inspect",
620
            "--format",
621
            "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}",
622
            container_name_or_id,
623
        ]
624
        try:
×
625
            result = run(cmd).strip()
×
626
            return result.split(" ")[0] if result else ""
×
627
        except subprocess.CalledProcessError as e:
×
628
            self._check_and_raise_no_such_container_error(container_name_or_id, error=e)
×
629
            # consider different error messages for Podman
630
            if "no such object" in to_str(e.stdout).lower():
×
631
                raise NoSuchContainer(container_name_or_id, stdout=e.stdout, stderr=e.stderr)
×
632
            raise ContainerException(
×
633
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
634
            ) from e
635

636
    def login(self, username: str, password: str, registry: Optional[str] = None) -> None:
1✔
637
        cmd = self._docker_cmd()
×
638
        # TODO specify password via stdin
639
        cmd += ["login", "-u", username, "-p", password]
×
640
        if registry:
×
641
            cmd.append(registry)
×
642
        try:
×
643
            run(cmd)
×
644
        except subprocess.CalledProcessError as e:
×
645
            raise ContainerException(
×
646
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
647
            ) from e
648

649
    @functools.lru_cache(maxsize=None)
1✔
650
    def has_docker(self) -> bool:
1✔
651
        try:
1✔
652
            # do not use self._docker_cmd here (would result in a loop)
653
            run(shlex.split(config.DOCKER_CMD) + ["ps"])
1✔
654
            return True
1✔
655
        except (subprocess.CalledProcessError, FileNotFoundError):
1✔
656
            return False
1✔
657

658
    def create_container(self, image_name: str, **kwargs) -> str:
1✔
659
        cmd, env_file = self._build_run_create_cmd("create", image_name, **kwargs)
1✔
660
        LOG.debug("Create container with cmd: %s", cmd)
1✔
661
        try:
1✔
662
            container_id = run(cmd)
1✔
663
            # Note: strip off Docker warning messages like "DNS setting (--dns=127.0.0.1) may fail in containers"
664
            container_id = container_id.strip().split("\n")[-1]
1✔
665
            return container_id.strip()
1✔
666
        except subprocess.CalledProcessError as e:
×
667
            error_messages = ["Unable to find image", "Trying to pull"]
×
668
            if any(msg in to_str(e.stdout) for msg in error_messages):
×
669
                raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr)
×
670
            raise ContainerException(
×
671
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
672
            ) from e
673
        finally:
674
            Util.rm_env_vars_file(env_file)
1✔
675

676
    def run_container(self, image_name: str, stdin=None, **kwargs) -> Tuple[bytes, bytes]:
1✔
677
        cmd, env_file = self._build_run_create_cmd("run", image_name, **kwargs)
×
678
        LOG.debug("Run container with cmd: %s", cmd)
×
679
        try:
×
680
            return self._run_async_cmd(cmd, stdin, kwargs.get("name") or "", image_name)
×
681
        except ContainerException as e:
×
682
            if "Trying to pull" in str(e) and "access to the resource is denied" in str(e):
×
683
                raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr) from e
×
684
            raise
×
685
        finally:
686
            Util.rm_env_vars_file(env_file)
×
687

688
    def exec_in_container(
1✔
689
        self,
690
        container_name_or_id: str,
691
        command: Union[List[str], str],
692
        interactive=False,
693
        detach=False,
694
        env_vars: Optional[Dict[str, Optional[str]]] = None,
695
        stdin: Optional[bytes] = None,
696
        user: Optional[str] = None,
697
        workdir: Optional[str] = None,
698
    ) -> Tuple[bytes, bytes]:
699
        env_file = None
×
700
        cmd = self._docker_cmd()
×
701
        cmd.append("exec")
×
702
        if interactive:
×
703
            cmd.append("--interactive")
×
704
        if detach:
×
705
            cmd.append("--detach")
×
706
        if user:
×
707
            cmd += ["--user", user]
×
708
        if workdir:
×
709
            cmd += ["--workdir", workdir]
×
710
        if env_vars:
×
711
            env_flag, env_file = Util.create_env_vars_file_flag(env_vars)
×
712
            cmd += env_flag
×
713
        cmd.append(container_name_or_id)
×
714
        cmd += command if isinstance(command, List) else [command]
×
715
        LOG.debug("Execute command in container: %s", cmd)
×
716
        try:
×
717
            return self._run_async_cmd(cmd, stdin, container_name_or_id)
×
718
        finally:
719
            Util.rm_env_vars_file(env_file)
×
720

721
    def start_container(
1✔
722
        self,
723
        container_name_or_id: str,
724
        stdin=None,
725
        interactive: bool = False,
726
        attach: bool = False,
727
        flags: Optional[str] = None,
728
    ) -> Tuple[bytes, bytes]:
729
        cmd = self._docker_cmd() + ["start"]
1✔
730
        if flags:
1✔
731
            cmd.append(flags)
×
732
        if interactive:
1✔
733
            cmd.append("--interactive")
×
734
        if attach:
1✔
735
            cmd.append("--attach")
×
736
        cmd.append(container_name_or_id)
1✔
737
        LOG.debug("Start container with cmd: %s", cmd)
1✔
738
        return self._run_async_cmd(cmd, stdin, container_name_or_id)
1✔
739

740
    def attach_to_container(self, container_name_or_id: str):
1✔
741
        cmd = self._docker_cmd() + ["attach", container_name_or_id]
×
742
        LOG.debug("Attaching to container %s", container_name_or_id)
×
743
        return self._run_async_cmd(cmd, stdin=None, container_name=container_name_or_id)
×
744

745
    def _run_async_cmd(
1✔
746
        self, cmd: List[str], stdin: bytes, container_name: str, image_name=None
747
    ) -> Tuple[bytes, bytes]:
748
        kwargs = {
1✔
749
            "inherit_env": True,
750
            "asynchronous": True,
751
            "stderr": subprocess.PIPE,
752
            "outfile": self.default_run_outfile or subprocess.PIPE,
753
        }
754
        if stdin:
1✔
755
            kwargs["stdin"] = True
×
756
        try:
1✔
757
            process = run(cmd, **kwargs)
1✔
758
            stdout, stderr = process.communicate(input=stdin)
1✔
759
            if process.returncode != 0:
1✔
760
                raise subprocess.CalledProcessError(
×
761
                    process.returncode,
762
                    cmd,
763
                    stdout,
764
                    stderr,
765
                )
766
            else:
767
                return stdout, stderr
1✔
768
        except subprocess.CalledProcessError as e:
×
769
            stderr_str = to_str(e.stderr)
×
770
            if "Unable to find image" in stderr_str:
×
771
                raise NoSuchImage(image_name or "", stdout=e.stdout, stderr=e.stderr)
×
772
            # consider different error messages for Docker/Podman
773
            error_messages = ("No such container", "no container with name or ID")
×
774
            if any(msg.lower() in to_str(e.stderr).lower() for msg in error_messages):
×
775
                raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr)
×
776
            raise ContainerException(
×
777
                "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr
778
            ) from e
779

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

874
        if additional_flags:
1✔
875
            cmd += shlex.split(additional_flags)
×
876
        cmd.append(image_name)
1✔
877
        if command:
1✔
878
            cmd += command if isinstance(command, List) else [command]
×
879
        return cmd, env_file
1✔
880

881
    @staticmethod
1✔
882
    def _map_to_volume_param(volume: Union[SimpleVolumeBind, BindMount, VolumeDirMount]) -> str:
1✔
883
        """
884
        Maps the mount volume, to a parameter for the -v docker cli argument.
885

886
        Examples:
887
        (host_path, container_path) -> host_path:container_path
888
        VolumeBind(host_dir=host_path, container_dir=container_path, read_only=True) -> host_path:container_path:ro
889

890
        :param volume: Either a SimpleVolumeBind, in essence a tuple (host_dir, container_dir), or a VolumeBind object
891
        :return: String which is passable as parameter to the docker cli -v option
892
        """
893
        if isinstance(volume, (BindMount, VolumeDirMount)):
×
894
            return volume.to_str()
×
895
        else:
896
            return f"{volume[0]}:{volume[1]}"
×
897

898
    def _check_and_raise_no_such_container_error(
1✔
899
        self, container_name_or_id: str, error: subprocess.CalledProcessError
900
    ):
901
        """
902
        Check the given client invocation error and raise a `NoSuchContainer` exception if it
903
        represents a `no such container` exception from Docker or Podman.
904
        """
905

906
        # consider different error messages for Docker/Podman
907
        error_messages = ("No such container", "no container with name or ID")
1✔
908
        process_stdout_lower = to_str(error.stdout).lower()
1✔
909
        if any(msg.lower() in process_stdout_lower for msg in error_messages):
1✔
910
            raise NoSuchContainer(container_name_or_id, stdout=error.stdout, stderr=error.stderr)
1✔
911

912
    def _transform_container_labels(self, labels: Union[str, Dict[str, str]]) -> Dict[str, str]:
1✔
913
        """
914
        Transforms the container labels returned by the docker command from the key-value pair format to a dict
915
        :param labels: Input string, comma separated key value pairs. Example: key1=value1,key2=value2
916
        :return: Dict representation of the passed values, example: {"key1": "value1", "key2": "value2"}
917
        """
918
        if isinstance(labels, Dict):
1✔
NEW
919
            return labels
×
920

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