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

localstack / localstack / 20571191684

29 Dec 2025 10:56AM UTC coverage: 84.082%. First build
20571191684

Pull #13569

github

web-flow
Merge 3e3c76e15 into 225bb3465
Pull Request #13569: Allow authenticated pull of docker images

18 of 26 new or added lines in 4 files covered. (69.23%)

67170 of 79886 relevant lines covered (84.08%)

0.84 hits per line

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

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

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

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

40

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

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

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

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

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

60

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

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

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

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

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

89

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

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

99
    default_run_outfile: str | None = None
1✔
100

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

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

120
        return json.loads(cmd_result)
1✔
121

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

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

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

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

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

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

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

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

184
    def stop_container(self, container_name: str, timeout: int = 10) -> None:
1✔
185
        cmd = self._docker_cmd()
1✔
186
        cmd += ["stop", "--time", str(timeout), container_name]
1✔
187
        LOG.debug("Stopping container with cmd %s", cmd)
1✔
188
        try:
1✔
189
            run(cmd)
1✔
190
        except subprocess.CalledProcessError as e:
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)
×
285
        except subprocess.CalledProcessError as e:
×
286
            if not force:
×
287
                self._check_and_raise_no_such_container_error(container_name, error=e)
×
288
            raise ContainerException(
×
289
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
290
            ) from e
291

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

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

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

365
    def pull_image(
1✔
366
        self,
367
        docker_image: str,
368
        platform: DockerPlatform | None = None,
369
        log_handler: Callable[[str], None] | None = None,
370
        auth_config: dict[str, str] | None = None,
371
    ) -> None:
NEW
372
        if auth_config:
×
NEW
373
            LOG.warning(
×
374
                "Using global docker login for authentication in docker_cmd_client. "
375
                "This may lead to unexpected behaviors with concurrent requests to different registries. "
376
                "Consider stop using LEGACY_DOCKER_CLIENT for thread-safe authentication."
377
            )
378
            # Extract registry from the image name
NEW
379
            registry = get_registry_from_image_name(docker_image)
×
NEW
380
            self.login(
×
381
                username=auth_config.get("username", ""),
382
                password=auth_config.get("password", ""),
383
                registry=registry,
384
            )
385
        cmd = self._docker_cmd()
×
386
        docker_image = self.registry_resolver_strategy.resolve(docker_image)
×
387
        cmd += ["pull", docker_image]
×
388
        if platform:
×
389
            cmd += ["--platform", platform]
×
390
        LOG.debug("Pulling image with cmd: %s", cmd)
×
391
        try:
×
392
            result = run(cmd)
×
393
            # note: we could stream the results, but we'll just process everything at the end for now
394
            if log_handler:
×
395
                for line in result.split("\n"):
×
396
                    log_handler(to_str(line))
×
397
        except subprocess.CalledProcessError as e:
×
398
            stdout_str = to_str(e.stdout)
×
399
            if "pull access denied" in stdout_str:
×
400
                raise NoSuchImage(docker_image, stdout=e.stdout, stderr=e.stderr)
×
401
            # note: error message 'access to the resource is denied' raised by Podman client
402
            if "Trying to pull" in stdout_str and "access to the resource is denied" in stdout_str:
×
403
                raise NoSuchImage(docker_image, stdout=e.stdout, stderr=e.stderr)
×
404
            raise ContainerException(
×
405
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
406
            ) from e
407

408
    def push_image(self, docker_image: str) -> None:
1✔
409
        cmd = self._docker_cmd()
×
410
        cmd += ["push", docker_image]
×
411
        LOG.debug("Pushing image with cmd: %s", cmd)
×
412
        try:
×
413
            run(cmd)
×
414
        except subprocess.CalledProcessError as e:
×
415
            if "is denied" in to_str(e.stdout):
×
416
                raise AccessDenied(docker_image)
×
417
            if "requesting higher privileges than access token allows" in to_str(e.stdout):
×
418
                raise AccessDenied(docker_image)
×
419
            if "access token has insufficient scopes" in to_str(e.stdout):
×
420
                raise AccessDenied(docker_image)
×
421
            if "does not exist" in to_str(e.stdout):
×
422
                raise NoSuchImage(docker_image)
×
423
            if "connection refused" in to_str(e.stdout):
×
424
                raise RegistryConnectionError(e.stdout)
×
425
            # note: error message 'image not known' raised by Podman client
426
            if "image not known" in to_str(e.stdout):
×
427
                raise NoSuchImage(docker_image)
×
428
            raise ContainerException(
×
429
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
430
            ) from e
431

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

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

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

478
            image_names = output.splitlines()
×
479
            if strip_wellknown_repo_prefixes:
×
480
                image_names = Util.strip_wellknown_repo_prefixes(image_names)
×
481
            if strip_latest:
×
482
                Util.append_without_latest(image_names)
×
483

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

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

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

505
        cmd = self._docker_cmd()
1✔
506
        cmd += ["logs", "--follow", container_name_or_id]
1✔
507

508
        process: subprocess.Popen = run(
1✔
509
            cmd, asynchronous=True, outfile=subprocess.PIPE, stderr=subprocess.STDOUT
510
        )
511

512
        return CancellableProcessStream(process)
1✔
513

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

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

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

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

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

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

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

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

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

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

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

691
    def create_container(self, image_name: str, **kwargs) -> str:
1✔
692
        # Extract auth_config if provided
693
        auth_config = kwargs.pop("auth_config", None)
1✔
694
        if auth_config:
1✔
NEW
695
            LOG.warning(
×
696
                "Using global docker login for authentication in docker_cmd_client. "
697
                "This may lead to unexpected behaviors with concurrent requests to different registries. "
698
                "Consider using docker_sdk_client for thread-safe authentication."
699
            )
NEW
700
            registry = get_registry_from_image_name(image_name)
×
NEW
701
            self.login(
×
702
                username=auth_config.get("username", ""),
703
                password=auth_config.get("password", ""),
704
                registry=registry,
705
            )
706
        image_name = self.registry_resolver_strategy.resolve(image_name)
1✔
707
        cmd, env_file = self._build_run_create_cmd("create", image_name, **kwargs)
1✔
708
        LOG.debug("Create container with cmd: %s", cmd)
1✔
709
        try:
1✔
710
            container_id = run(cmd)
1✔
711
            # Note: strip off Docker warning messages like "DNS setting (--dns=127.0.0.1) may fail in containers"
712
            container_id = container_id.strip().split("\n")[-1]
1✔
713
            return container_id.strip()
1✔
714
        except subprocess.CalledProcessError as e:
×
715
            error_messages = ["Unable to find image", "Trying to pull"]
×
716
            if any(msg in to_str(e.stdout) for msg in error_messages):
×
717
                raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr)
×
718
            raise ContainerException(
×
719
                f"Docker process returned with errorcode {e.returncode}", e.stdout, e.stderr
720
            ) from e
721
        finally:
722
            Util.rm_env_vars_file(env_file)
1✔
723

724
    def run_container(self, image_name: str, stdin=None, **kwargs) -> tuple[bytes, bytes]:
1✔
725
        image_name = self.registry_resolver_strategy.resolve(image_name)
×
726
        cmd, env_file = self._build_run_create_cmd("run", image_name, **kwargs)
×
727
        LOG.debug("Run container with cmd: %s", cmd)
×
728
        try:
×
729
            return self._run_async_cmd(cmd, stdin, kwargs.get("name") or "", image_name)
×
730
        except ContainerException as e:
×
731
            if "Trying to pull" in str(e) and "access to the resource is denied" in str(e):
×
732
                raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr) from e
×
733
            raise
×
734
        finally:
735
            Util.rm_env_vars_file(env_file)
×
736

737
    def exec_in_container(
1✔
738
        self,
739
        container_name_or_id: str,
740
        command: list[str] | str,
741
        interactive=False,
742
        detach=False,
743
        env_vars: dict[str, str | None] | None = None,
744
        stdin: bytes | None = None,
745
        user: str | None = None,
746
        workdir: str | None = None,
747
    ) -> tuple[bytes, bytes]:
748
        env_file = None
1✔
749
        cmd = self._docker_cmd()
1✔
750
        cmd.append("exec")
1✔
751
        if interactive:
1✔
752
            cmd.append("--interactive")
×
753
        if detach:
1✔
754
            cmd.append("--detach")
×
755
        if user:
1✔
756
            cmd += ["--user", user]
×
757
        if workdir:
1✔
758
            cmd += ["--workdir", workdir]
×
759
        if env_vars:
1✔
760
            env_flag, env_file = Util.create_env_vars_file_flag(env_vars)
×
761
            cmd += env_flag
×
762
        cmd.append(container_name_or_id)
1✔
763
        cmd += command if isinstance(command, list) else [command]
1✔
764
        LOG.debug("Execute command in container: %s", cmd)
1✔
765
        try:
1✔
766
            return self._run_async_cmd(cmd, stdin, container_name_or_id)
1✔
767
        finally:
768
            Util.rm_env_vars_file(env_file)
1✔
769

770
    def start_container(
1✔
771
        self,
772
        container_name_or_id: str,
773
        stdin=None,
774
        interactive: bool = False,
775
        attach: bool = False,
776
        flags: str | None = None,
777
    ) -> tuple[bytes, bytes]:
778
        cmd = self._docker_cmd() + ["start"]
1✔
779
        if flags:
1✔
780
            cmd.append(flags)
×
781
        if interactive:
1✔
782
            cmd.append("--interactive")
×
783
        if attach:
1✔
784
            cmd.append("--attach")
×
785
        cmd.append(container_name_or_id)
1✔
786
        LOG.debug("Start container with cmd: %s", cmd)
1✔
787
        return self._run_async_cmd(cmd, stdin, container_name_or_id)
1✔
788

789
    def attach_to_container(self, container_name_or_id: str):
1✔
790
        cmd = self._docker_cmd() + ["attach", container_name_or_id]
1✔
791
        LOG.debug("Attaching to container %s", container_name_or_id)
1✔
792
        return self._run_async_cmd(cmd, stdin=None, container_name=container_name_or_id)
1✔
793

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

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

929
        if additional_flags:
1✔
930
            cmd += shlex.split(additional_flags)
1✔
931
        cmd.append(image_name)
1✔
932
        if command:
1✔
933
            cmd += command if isinstance(command, list) else [command]
1✔
934
        return cmd, env_file
1✔
935

936
    @staticmethod
1✔
937
    def _map_to_volume_param(volume: VolumeMappingSpecification) -> str:
1✔
938
        """
939
        Maps the mount volume, to a parameter for the -v docker cli argument.
940

941
        Examples:
942
        (host_path, container_path) -> host_path:container_path
943
        VolumeBind(host_dir=host_path, container_dir=container_path, read_only=True) -> host_path:container_path:ro
944

945
        :param volume: Either a SimpleVolumeBind, in essence a tuple (host_dir, container_dir), or a VolumeBind object
946
        :return: String which is passable as parameter to the docker cli -v option
947
        """
948
        # TODO: move this logic to the VolumeMappingSpecification type
949
        if isinstance(volume, Mount):
1✔
950
            return volume.to_str()
1✔
951
        else:
952
            return f"{volume[0]}:{volume[1]}"
×
953

954
    def _check_and_raise_no_such_container_error(
1✔
955
        self, container_name_or_id: str, error: subprocess.CalledProcessError
956
    ):
957
        """
958
        Check the given client invocation error and raise a `NoSuchContainer` exception if it
959
        represents a `no such container` exception from Docker or Podman.
960
        """
961
        self._check_output_and_raise_no_such_container_error(
1✔
962
            container_name_or_id, str(error.stdout), error=str(error.stderr)
963
        )
964

965
    def _check_output_and_raise_no_such_container_error(
1✔
966
        self, container_name_or_id: str, output: str, error: str | None = None
967
    ):
968
        """
969
        Check the given client invocation output and raise a `NoSuchContainer` exception if it
970
        represents a `no such container` exception from Docker or Podman.
971
        """
972
        possible_not_found_messages = ("No such container", "no container with name or ID")
1✔
973
        if any(msg.lower() in output.lower() for msg in possible_not_found_messages):
1✔
974
            raise NoSuchContainer(container_name_or_id, stdout=output, stderr=error)
1✔
975

976
    def _transform_container_labels(self, labels: str | dict[str, str]) -> dict[str, str]:
1✔
977
        """
978
        Transforms the container labels returned by the docker command from the key-value pair format to a dict
979
        :param labels: Input string, comma separated key value pairs. Example: key1=value1,key2=value2
980
        :return: Dict representation of the passed values, example: {"key1": "value1", "key2": "value2"}
981
        """
982
        if isinstance(labels, dict):
1✔
983
            return labels
×
984

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

© 2025 Coveralls, Inc