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

localstack / localstack / c98f6ef0-0f32-4bad-99a7-eb2ba1217c55

28 Jan 2025 03:05PM UTC coverage: 86.895% (-0.006%) from 86.901%
c98f6ef0-0f32-4bad-99a7-eb2ba1217c55

push

circleci

web-flow
S3: implement new data integrity for MultipartUpload (#12183)

175 of 186 new or added lines in 4 files covered. (94.09%)

376 existing lines in 8 files now uncovered.

61354 of 70607 relevant lines covered (86.9%)

0.87 hits per line

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

90.53
/localstack-core/localstack/utils/container_utils/container_client.py
1
import dataclasses
1✔
2
import io
1✔
3
import ipaddress
1✔
4
import logging
1✔
5
import os
1✔
6
import re
1✔
7
import shlex
1✔
8
import sys
1✔
9
import tarfile
1✔
10
import tempfile
1✔
11
from abc import ABCMeta, abstractmethod
1✔
12
from enum import Enum, unique
1✔
13
from pathlib import Path
1✔
14
from typing import (
1✔
15
    Dict,
16
    List,
17
    Literal,
18
    NamedTuple,
19
    Optional,
20
    Protocol,
21
    Tuple,
22
    TypedDict,
23
    Union,
24
    get_args,
25
)
26

27
import dotenv
1✔
28

29
from localstack import config
1✔
30
from localstack.utils.collections import HashableList, ensure_list
1✔
31
from localstack.utils.files import TMP_FILES, chmod_r, rm_rf, save_file
1✔
32
from localstack.utils.no_exit_argument_parser import NoExitArgumentParser
1✔
33
from localstack.utils.strings import short_uid
1✔
34

35
LOG = logging.getLogger(__name__)
1✔
36

37
# list of well-known image repo prefixes that should be stripped off to canonicalize image names
38
WELL_KNOWN_IMAGE_REPO_PREFIXES = ("localhost/", "docker.io/library/")
1✔
39

40

41
@unique
1✔
42
class DockerContainerStatus(Enum):
1✔
43
    DOWN = -1
1✔
44
    NON_EXISTENT = 0
1✔
45
    UP = 1
1✔
46
    PAUSED = 2
1✔
47

48

49
class DockerContainerStats(TypedDict):
1✔
50
    """Container usage statistics"""
51

52
    Container: str
1✔
53
    ID: str
1✔
54
    Name: str
1✔
55
    BlockIO: tuple[int, int]
1✔
56
    CPUPerc: float
1✔
57
    MemPerc: float
1✔
58
    MemUsage: tuple[int, int]
1✔
59
    NetIO: tuple[int, int]
1✔
60
    PIDs: int
1✔
61
    SDKStats: Optional[dict]
1✔
62

63

64
class ContainerException(Exception):
1✔
65
    def __init__(self, message=None, stdout=None, stderr=None) -> None:
1✔
66
        self.message = message or "Error during the communication with the docker daemon"
1✔
67
        self.stdout = stdout
1✔
68
        self.stderr = stderr
1✔
69

70

71
class NoSuchObject(ContainerException):
1✔
72
    def __init__(self, object_id: str, message=None, stdout=None, stderr=None) -> None:
1✔
UNCOV
73
        message = message or f"Docker object {object_id} not found"
×
UNCOV
74
        super().__init__(message, stdout, stderr)
×
UNCOV
75
        self.object_id = object_id
×
76

77

78
class NoSuchContainer(ContainerException):
1✔
79
    def __init__(self, container_name_or_id: str, message=None, stdout=None, stderr=None) -> None:
1✔
80
        message = message or f"Docker container {container_name_or_id} not found"
1✔
81
        super().__init__(message, stdout, stderr)
1✔
82
        self.container_name_or_id = container_name_or_id
1✔
83

84

85
class NoSuchImage(ContainerException):
1✔
86
    def __init__(self, image_name: str, message=None, stdout=None, stderr=None) -> None:
1✔
87
        message = message or f"Docker image {image_name} not found"
1✔
88
        super().__init__(message, stdout, stderr)
1✔
89
        self.image_name = image_name
1✔
90

91

92
class NoSuchNetwork(ContainerException):
1✔
93
    def __init__(self, network_name: str, message=None, stdout=None, stderr=None) -> None:
1✔
94
        message = message or f"Docker network {network_name} not found"
1✔
95
        super().__init__(message, stdout, stderr)
1✔
96
        self.network_name = network_name
1✔
97

98

99
class RegistryConnectionError(ContainerException):
1✔
100
    def __init__(self, details: str, message=None, stdout=None, stderr=None) -> None:
1✔
101
        message = message or f"Connection error: {details}"
1✔
102
        super().__init__(message, stdout, stderr)
1✔
103
        self.details = details
1✔
104

105

106
class DockerNotAvailable(ContainerException):
1✔
107
    def __init__(self, message=None, stdout=None, stderr=None) -> None:
1✔
108
        message = message or "Docker not available"
1✔
109
        super().__init__(message, stdout, stderr)
1✔
110

111

112
class AccessDenied(ContainerException):
1✔
113
    def __init__(self, object_name: str, message=None, stdout=None, stderr=None) -> None:
1✔
114
        message = message or f"Access denied to {object_name}"
1✔
115
        super().__init__(message, stdout, stderr)
1✔
116
        self.object_name = object_name
1✔
117

118

119
class CancellableStream(Protocol):
1✔
120
    """Describes a generator that can be closed. Borrowed from ``docker.types.daemon``."""
121

122
    def __iter__(self):
1✔
123
        raise NotImplementedError
124

125
    def __next__(self):
1✔
126
        raise NotImplementedError
127

128
    def close(self):
1✔
129
        raise NotImplementedError
130

131

132
class DockerPlatform(str):
1✔
133
    """Platform in the format ``os[/arch[/variant]]``"""
134

135
    linux_amd64 = "linux/amd64"
1✔
136
    linux_arm64 = "linux/arm64"
1✔
137

138

139
@dataclasses.dataclass
1✔
140
class Ulimit:
1✔
141
    """The ``ulimit`` settings for the container.
142
    See https://www.tutorialspoint.com/setting-ulimit-values-on-docker-containers
143
    """
144

145
    name: str
1✔
146
    soft_limit: int
1✔
147
    hard_limit: Optional[int] = None
1✔
148

149
    def __repr__(self):
150
        """Format: <type>=<soft limit>[:<hard limit>]"""
151
        ulimit_string = f"{self.name}={self.soft_limit}"
152
        if self.hard_limit:
153
            ulimit_string += f":{self.hard_limit}"
154
        return ulimit_string
155

156

157
# defines the type for port mappings (source->target port range)
158
PortRange = Union[List, HashableList]
1✔
159
# defines the protocol for a port range ("tcp" or "udp")
160
PortProtocol = str
1✔
161

162

163
def isinstance_union(obj, class_or_tuple):
1✔
164
    # that's some dirty hack
165
    if sys.version_info < (3, 10):
1✔
UNCOV
166
        return isinstance(obj, get_args(PortRange))
×
167
    else:
168
        return isinstance(obj, class_or_tuple)
1✔
169

170

171
class PortMappings:
1✔
172
    """Maps source to target port ranges for Docker port mappings."""
173

174
    # bind host to be used for defining port mappings
175
    bind_host: str
1✔
176
    # maps `from` port range to `to` port range for port mappings
177
    mappings: Dict[Tuple[PortRange, PortProtocol], List]
1✔
178

179
    def __init__(self, bind_host: str = None):
1✔
180
        self.bind_host = bind_host if bind_host else ""
1✔
181
        self.mappings = {}
1✔
182

183
    def add(
1✔
184
        self,
185
        port: Union[int, PortRange],
186
        mapped: Union[int, PortRange] = None,
187
        protocol: PortProtocol = "tcp",
188
    ):
189
        mapped = mapped or port
1✔
190
        if isinstance_union(port, PortRange):
1✔
191
            for i in range(port[1] - port[0] + 1):
1✔
192
                if isinstance_union(mapped, PortRange):
1✔
193
                    self.add(port[0] + i, mapped[0] + i, protocol)
1✔
194
                else:
195
                    self.add(port[0] + i, mapped, protocol)
1✔
196
            return
1✔
197
        if port is None or int(port) < 0:
1✔
UNCOV
198
            raise Exception(f"Unable to add mapping for invalid port: {port}")
×
199
        if self.contains(port, protocol):
1✔
200
            return
1✔
201
        bisected_host_port = None
1✔
202
        for (from_range, from_protocol), to_range in self.mappings.items():
1✔
203
            if not from_protocol == protocol:
1✔
204
                continue
1✔
205
            if not self.in_expanded_range(port, from_range):
1✔
206
                continue
1✔
207
            if not self.in_expanded_range(mapped, to_range):
1✔
208
                continue
1✔
209
            from_range_len = from_range[1] - from_range[0]
1✔
210
            to_range_len = to_range[1] - to_range[0]
1✔
211
            is_uniform = from_range_len == to_range_len
1✔
212
            if is_uniform:
1✔
213
                self.expand_range(port, from_range, protocol=protocol, remap=True)
1✔
214
                self.expand_range(mapped, to_range, protocol=protocol)
1✔
215
            else:
216
                if not self.in_range(mapped, to_range):
1✔
217
                    continue
1✔
218
                # extending a 1 to 1 mapping to be many to 1
219
                elif from_range_len == 1:
1✔
220
                    self.expand_range(port, from_range, protocol=protocol, remap=True)
1✔
221
                # splitting a uniform mapping
222
                else:
223
                    bisected_port_index = mapped - to_range[0]
1✔
224
                    bisected_host_port = from_range[0] + bisected_port_index
1✔
225
                    self.bisect_range(mapped, to_range, protocol=protocol)
1✔
226
                    self.bisect_range(bisected_host_port, from_range, protocol=protocol, remap=True)
1✔
227
                    break
1✔
228
            return
1✔
229
        if bisected_host_port is None:
1✔
230
            port_range = [port, port]
1✔
231
        elif bisected_host_port < port:
1✔
232
            port_range = [bisected_host_port, port]
1✔
233
        else:
UNCOV
234
            port_range = [port, bisected_host_port]
×
235
        protocol = str(protocol or "tcp").lower()
1✔
236
        self.mappings[(HashableList(port_range), protocol)] = [mapped, mapped]
1✔
237

238
    def to_str(self) -> str:
1✔
239
        bind_address = f"{self.bind_host}:" if self.bind_host else ""
1✔
240

241
        def entry(k, v):
1✔
242
            from_range, protocol = k
1✔
243
            to_range = v
1✔
244
            # use /<protocol> suffix if the protocol is not"tcp"
245
            protocol_suffix = f"/{protocol}" if protocol != "tcp" else ""
1✔
246
            if from_range[0] == from_range[1] and to_range[0] == to_range[1]:
1✔
247
                return f"-p {bind_address}{from_range[0]}:{to_range[0]}{protocol_suffix}"
1✔
248
            if from_range[0] != from_range[1] and to_range[0] == to_range[1]:
1✔
249
                return f"-p {bind_address}{from_range[0]}-{from_range[1]}:{to_range[0]}{protocol_suffix}"
1✔
250
            return f"-p {bind_address}{from_range[0]}-{from_range[1]}:{to_range[0]}-{to_range[1]}{protocol_suffix}"
1✔
251

252
        return " ".join([entry(k, v) for k, v in self.mappings.items()])
1✔
253

254
    def to_list(self) -> List[str]:  # TODO test
1✔
255
        bind_address = f"{self.bind_host}:" if self.bind_host else ""
1✔
256

257
        def entry(k, v):
1✔
258
            from_range, protocol = k
1✔
259
            to_range = v
1✔
260
            protocol_suffix = f"/{protocol}" if protocol != "tcp" else ""
1✔
261
            if from_range[0] == from_range[1] and to_range[0] == to_range[1]:
1✔
262
                return ["-p", f"{bind_address}{from_range[0]}:{to_range[0]}{protocol_suffix}"]
1✔
263
            return [
1✔
264
                "-p",
265
                f"{bind_address}{from_range[0]}-{from_range[1]}:{to_range[0]}-{to_range[1]}{protocol_suffix}",
266
            ]
267

268
        return [item for k, v in self.mappings.items() for item in entry(k, v)]
1✔
269

270
    def to_dict(self) -> Dict[str, Union[Tuple[str, Union[int, List[int]]], int]]:
1✔
271
        bind_address = self.bind_host or ""
1✔
272

273
        def bind_port(bind_address, host_port):
1✔
274
            if host_port == 0:
1✔
275
                return None
1✔
276
            elif bind_address:
1✔
277
                return (bind_address, host_port)
1✔
278
            else:
279
                return host_port
1✔
280

281
        def entry(k, v):
1✔
282
            from_range, protocol = k
1✔
283
            to_range = v
1✔
284
            protocol_suffix = f"/{protocol}"
1✔
285
            if from_range[0] != from_range[1] and to_range[0] == to_range[1]:
1✔
286
                container_port = to_range[0]
1✔
287
                host_ports = list(range(from_range[0], from_range[1] + 1))
1✔
288
                return [
1✔
289
                    (
290
                        f"{container_port}{protocol_suffix}",
291
                        (bind_address, host_ports) if bind_address else host_ports,
292
                    )
293
                ]
294
            return [
1✔
295
                (
296
                    f"{container_port}{protocol_suffix}",
297
                    bind_port(bind_address, host_port),
298
                )
299
                for container_port, host_port in zip(
300
                    range(to_range[0], to_range[1] + 1), range(from_range[0], from_range[1] + 1)
301
                )
302
            ]
303

304
        items = [item for k, v in self.mappings.items() for item in entry(k, v)]
1✔
305
        return dict(items)
1✔
306

307
    def contains(self, port: int, protocol: PortProtocol = "tcp") -> bool:
1✔
308
        for from_range_w_protocol, to_range in self.mappings.items():
1✔
309
            from_protocol = from_range_w_protocol[1]
1✔
310
            if from_protocol == protocol:
1✔
311
                from_range = from_range_w_protocol[0]
1✔
312
                if self.in_range(port, from_range):
1✔
313
                    return True
1✔
314

315
    def in_range(self, port: int, range: PortRange) -> bool:
1✔
316
        return port >= range[0] and port <= range[1]
1✔
317

318
    def in_expanded_range(self, port: int, range: PortRange):
1✔
319
        return port >= range[0] - 1 and port <= range[1] + 1
1✔
320

321
    def expand_range(
1✔
322
        self, port: int, range: PortRange, protocol: PortProtocol = "tcp", remap: bool = False
323
    ):
324
        """
325
        Expand the given port range by the given port. If remap==True, put the updated range into self.mappings
326
        """
327
        if self.in_range(port, range):
1✔
328
            return
1✔
329
        new_range = list(range) if remap else range
1✔
330
        if port == range[0] - 1:
1✔
UNCOV
331
            new_range[0] = port
×
332
        elif port == range[1] + 1:
1✔
333
            new_range[1] = port
1✔
334
        else:
UNCOV
335
            raise Exception(f"Unable to add port {port} to existing range {range}")
×
336
        if remap:
1✔
337
            self._remap_range(range, new_range, protocol=protocol)
1✔
338

339
    def bisect_range(
1✔
340
        self, port: int, range: PortRange, protocol: PortProtocol = "tcp", remap: bool = False
341
    ):
342
        """
343
        Bisect a port range, at the provided port. This is needed in some cases when adding a
344
        non-uniform host to port mapping adjacent to an existing port range.
345
        If remap==True, put the updated range into self.mappings
346
        """
347
        if not self.in_range(port, range):
1✔
UNCOV
348
            return
×
349
        new_range = list(range) if remap else range
1✔
350
        if port == range[0]:
1✔
UNCOV
351
            new_range[0] = port + 1
×
352
        else:
353
            new_range[1] = port - 1
1✔
354
        if remap:
1✔
355
            self._remap_range(range, new_range, protocol)
1✔
356

357
    def _remap_range(self, old_key: PortRange, new_key: PortRange, protocol: PortProtocol):
1✔
358
        self.mappings[(HashableList(new_key), protocol)] = self.mappings.pop(
1✔
359
            (HashableList(old_key), protocol)
360
        )
361

362
    def __repr__(self):
363
        return f"<PortMappings: {self.to_dict()}>"
364

365

366
SimpleVolumeBind = Tuple[str, str]
1✔
367
"""Type alias for a simple version of VolumeBind"""
1✔
368

369

370
@dataclasses.dataclass
1✔
371
class VolumeBind:
1✔
372
    """Represents a --volume argument run/create command. When using VolumeBind to bind-mount a file or directory
373
    that does not yet exist on the Docker host, -v creates the endpoint for you. It is always created as a directory.
374
    """
375

376
    host_dir: str
1✔
377
    container_dir: str
1✔
378
    read_only: bool = False
1✔
379

380
    def to_str(self) -> str:
1✔
UNCOV
381
        args = []
×
382

UNCOV
383
        if self.host_dir:
×
UNCOV
384
            args.append(self.host_dir)
×
385

UNCOV
386
        if not self.container_dir:
×
UNCOV
387
            raise ValueError("no container dir specified")
×
388

UNCOV
389
        args.append(self.container_dir)
×
390

UNCOV
391
        if self.read_only:
×
UNCOV
392
            args.append("ro")
×
393

UNCOV
394
        return ":".join(args)
×
395

396
    @classmethod
1✔
397
    def parse(cls, param: str) -> "VolumeBind":
1✔
398
        parts = param.split(":")
1✔
399
        if 1 > len(parts) > 3:
1✔
UNCOV
400
            raise ValueError(f"Cannot parse volume bind {param}")
×
401

402
        volume = cls(parts[0], parts[1])
1✔
403
        if len(parts) == 3:
1✔
404
            if "ro" in parts[2].split(","):
1✔
405
                volume.read_only = True
1✔
406
        return volume
1✔
407

408

409
class VolumeMappings:
1✔
410
    mappings: List[Union[SimpleVolumeBind, VolumeBind]]
1✔
411

412
    def __init__(self, mappings: List[Union[SimpleVolumeBind, VolumeBind]] = None):
1✔
413
        self.mappings = mappings if mappings is not None else []
1✔
414

415
    def add(self, mapping: Union[SimpleVolumeBind, VolumeBind]):
1✔
416
        self.append(mapping)
1✔
417

418
    def append(
1✔
419
        self,
420
        mapping: Union[
421
            SimpleVolumeBind,
422
            VolumeBind,
423
        ],
424
    ):
425
        self.mappings.append(mapping)
1✔
426

427
    def find_target_mapping(
1✔
428
        self, container_dir: str
429
    ) -> Optional[Union[SimpleVolumeBind, VolumeBind]]:
430
        """
431
        Looks through the volumes and returns the one where the container dir matches ``container_dir``.
432
        Returns None if there is no volume mapping to the given container directory.
433

434
        :param container_dir: the target of the volume mapping, i.e., the path in the container
435
        :return: the volume mapping or None
436
        """
UNCOV
437
        for volume in self.mappings:
×
UNCOV
438
            target_dir = volume[1] if isinstance(volume, tuple) else volume.container_dir
×
UNCOV
439
            if container_dir == target_dir:
×
UNCOV
440
                return volume
×
UNCOV
441
        return None
×
442

443
    def __iter__(self):
1✔
444
        return self.mappings.__iter__()
1✔
445

446
    def __repr__(self):
447
        return self.mappings.__repr__()
448

449

450
VolumeType = Literal["bind", "volume"]
1✔
451

452

453
class VolumeInfo(NamedTuple):
1✔
454
    """Container volume information."""
455

456
    type: VolumeType
1✔
457
    source: str
1✔
458
    destination: str
1✔
459
    mode: str
1✔
460
    rw: bool
1✔
461
    propagation: str
1✔
462
    name: Optional[str] = None
1✔
463
    driver: Optional[str] = None
1✔
464

465

466
@dataclasses.dataclass
1✔
467
class LogConfig:
1✔
468
    type: Literal["json-file", "syslog", "journald", "gelf", "fluentd", "none", "awslogs", "splunk"]
1✔
469
    config: Dict[str, str] = dataclasses.field(default_factory=dict)
1✔
470

471

472
@dataclasses.dataclass
1✔
473
class ContainerConfiguration:
1✔
474
    image_name: str
1✔
475
    name: Optional[str] = None
1✔
476
    volumes: VolumeMappings = dataclasses.field(default_factory=VolumeMappings)
1✔
477
    ports: PortMappings = dataclasses.field(default_factory=PortMappings)
1✔
478
    exposed_ports: List[str] = dataclasses.field(default_factory=list)
1✔
479
    entrypoint: Optional[Union[List[str], str]] = None
1✔
480
    additional_flags: Optional[str] = None
1✔
481
    command: Optional[List[str]] = None
1✔
482
    env_vars: Dict[str, str] = dataclasses.field(default_factory=dict)
1✔
483

484
    privileged: bool = False
1✔
485
    remove: bool = False
1✔
486
    interactive: bool = False
1✔
487
    tty: bool = False
1✔
488
    detach: bool = False
1✔
489

490
    stdin: Optional[str] = None
1✔
491
    user: Optional[str] = None
1✔
492
    cap_add: Optional[List[str]] = None
1✔
493
    cap_drop: Optional[List[str]] = None
1✔
494
    security_opt: Optional[List[str]] = None
1✔
495
    network: Optional[str] = None
1✔
496
    dns: Optional[str] = None
1✔
497
    workdir: Optional[str] = None
1✔
498
    platform: Optional[str] = None
1✔
499
    ulimits: Optional[List[Ulimit]] = None
1✔
500
    labels: Optional[Dict[str, str]] = None
1✔
501
    init: Optional[bool] = None
1✔
502
    log_config: Optional[LogConfig] = None
1✔
503

504

505
class ContainerConfigurator(Protocol):
1✔
506
    """Protocol for functional configurators. A ContainerConfigurator modifies, when called,
507
    a ContainerConfiguration in place."""
508

509
    def __call__(self, configuration: ContainerConfiguration):
1✔
510
        """
511
        Modify the given container configuration.
512

513
        :param configuration: the configuration to modify
514
        """
UNCOV
515
        ...
×
516

517

518
@dataclasses.dataclass
1✔
519
class DockerRunFlags:
1✔
520
    """Class to capture Docker run/create flags for a container.
521
    run: https://docs.docker.com/engine/reference/commandline/run/
522
    create: https://docs.docker.com/engine/reference/commandline/create/
523
    """
524

525
    env_vars: Optional[Dict[str, str]]
1✔
526
    extra_hosts: Optional[Dict[str, str]]
1✔
527
    labels: Optional[Dict[str, str]]
1✔
528
    volumes: Optional[List[SimpleVolumeBind]]
1✔
529
    network: Optional[str]
1✔
530
    platform: Optional[DockerPlatform]
1✔
531
    privileged: Optional[bool]
1✔
532
    ports: Optional[PortMappings]
1✔
533
    ulimits: Optional[List[Ulimit]]
1✔
534
    user: Optional[str]
1✔
535
    dns: Optional[List[str]]
1✔
536

537

538
# TODO: remove Docker/Podman compatibility switches (in particular strip_wellknown_repo_prefixes=...)
539
#  from the container client base interface and introduce derived Podman client implementations instead!
540
class ContainerClient(metaclass=ABCMeta):
1✔
541
    @abstractmethod
1✔
542
    def get_system_info(self) -> dict:
1✔
543
        """Returns the docker system-wide information as dictionary (``docker info``)."""
544

545
    def get_system_id(self) -> str:
1✔
546
        """Returns the unique and stable ID of the docker daemon."""
547
        return self.get_system_info()["ID"]
1✔
548

549
    @abstractmethod
1✔
550
    def get_container_status(self, container_name: str) -> DockerContainerStatus:
1✔
551
        """Returns the status of the container with the given name"""
UNCOV
552
        pass
×
553

554
    def get_container_stats(self, container_name: str) -> DockerContainerStats:
1✔
555
        """Returns the usage statistics of the container with the given name"""
UNCOV
556
        pass
×
557

558
    def get_networks(self, container_name: str) -> List[str]:
1✔
559
        LOG.debug("Getting networks for container: %s", container_name)
1✔
560
        container_attrs = self.inspect_container(container_name_or_id=container_name)
1✔
561
        return list(container_attrs["NetworkSettings"].get("Networks", {}).keys())
1✔
562

563
    def get_container_ipv4_for_network(
1✔
564
        self, container_name_or_id: str, container_network: str
565
    ) -> str:
566
        """
567
        Returns the IPv4 address for the container on the interface connected to the given network
568
        :param container_name_or_id: Container to inspect
569
        :param container_network: Network the IP address will belong to
570
        :return: IP address of the given container on the interface connected to the given network
571
        """
572
        LOG.debug(
1✔
573
            "Getting ipv4 address for container %s in network %s.",
574
            container_name_or_id,
575
            container_network,
576
        )
577
        # we always need the ID for this
578
        container_id = self.get_container_id(container_name=container_name_or_id)
1✔
579
        network_attrs = self.inspect_network(container_network)
1✔
580
        containers = network_attrs.get("Containers") or {}
1✔
581
        if container_id not in containers:
1✔
582
            LOG.debug("Network attributes: %s", network_attrs)
1✔
583
            try:
1✔
584
                inspection = self.inspect_container(container_name_or_id=container_name_or_id)
1✔
585
                LOG.debug("Container %s Attributes: %s", container_name_or_id, inspection)
1✔
586
                logs = self.get_container_logs(container_name_or_id=container_name_or_id)
1✔
587
                LOG.debug("Container %s Logs: %s", container_name_or_id, logs)
1✔
UNCOV
588
            except ContainerException as e:
×
UNCOV
589
                LOG.debug("Cannot inspect container %s: %s", container_name_or_id, e)
×
590
            raise ContainerException(
1✔
591
                "Container %s is not connected to target network %s",
592
                container_name_or_id,
593
                container_network,
594
            )
595
        try:
1✔
596
            ip = str(ipaddress.IPv4Interface(containers[container_id]["IPv4Address"]).ip)
1✔
UNCOV
597
        except Exception as e:
×
UNCOV
598
            raise ContainerException(
×
599
                f"Unable to detect IP address for container {container_name_or_id} in network {container_network}: {e}"
600
            )
601
        return ip
1✔
602

603
    @abstractmethod
1✔
604
    def stop_container(self, container_name: str, timeout: int = 10):
1✔
605
        """Stops container with given name
606
        :param container_name: Container identifier (name or id) of the container to be stopped
607
        :param timeout: Timeout after which SIGKILL is sent to the container.
608
        """
609

610
    @abstractmethod
1✔
611
    def restart_container(self, container_name: str, timeout: int = 10):
1✔
612
        """Restarts a container with the given name.
613
        :param container_name: Container identifier
614
        :param timeout: Seconds to wait for stop before killing the container
615
        """
616

617
    @abstractmethod
1✔
618
    def pause_container(self, container_name: str):
1✔
619
        """Pauses a container with the given name."""
620

621
    @abstractmethod
1✔
622
    def unpause_container(self, container_name: str):
1✔
623
        """Unpauses a container with the given name."""
624

625
    @abstractmethod
1✔
626
    def remove_container(self, container_name: str, force=True, check_existence=False) -> None:
1✔
627
        """Removes container with given name"""
628

629
    @abstractmethod
1✔
630
    def remove_image(self, image: str, force: bool = True) -> None:
1✔
631
        """Removes an image with given name
632

633
        :param image: Image name and tag
634
        :param force: Force removal
635
        """
636

637
    @abstractmethod
1✔
638
    def list_containers(self, filter: Union[List[str], str, None] = None, all=True) -> List[dict]:
1✔
639
        """List all containers matching the given filters
640

641
        :return: A list of dicts with keys id, image, name, labels, status
642
        """
643

644
    def get_running_container_names(self) -> List[str]:
1✔
645
        """Returns a list of the names of all running containers"""
646
        result = self.list_containers(all=False)
1✔
647
        result = [container["name"] for container in result]
1✔
648
        return result
1✔
649

650
    def is_container_running(self, container_name: str) -> bool:
1✔
651
        """Checks whether a container with a given name is currently running"""
652
        return container_name in self.get_running_container_names()
1✔
653

654
    def create_file_in_container(
1✔
655
        self,
656
        container_name,
657
        file_contents: bytes,
658
        container_path: str,
659
        chmod_mode: Optional[int] = None,
660
    ) -> None:
661
        """
662
        Create a file in container with the provided content. Provide the 'chmod_mode' argument if you want the file to have specific permissions.
663
        """
664
        with tempfile.NamedTemporaryFile() as tmp:
1✔
665
            tmp.write(file_contents)
1✔
666
            tmp.flush()
1✔
667
            if chmod_mode is not None:
1✔
UNCOV
668
                chmod_r(tmp.name, chmod_mode)
×
669
            self.copy_into_container(
1✔
670
                container_name=container_name,
671
                local_path=tmp.name,
672
                container_path=container_path,
673
            )
674

675
    @abstractmethod
1✔
676
    def copy_into_container(
1✔
677
        self, container_name: str, local_path: str, container_path: str
678
    ) -> None:
679
        """Copy contents of the given local path into the container"""
680

681
    @abstractmethod
1✔
682
    def copy_from_container(
1✔
683
        self, container_name: str, local_path: str, container_path: str
684
    ) -> None:
685
        """Copy contents of the given container to the host"""
686

687
    @abstractmethod
1✔
688
    def pull_image(self, docker_image: str, platform: Optional[DockerPlatform] = None) -> None:
1✔
689
        """Pulls an image with a given name from a Docker registry"""
690

691
    @abstractmethod
1✔
692
    def push_image(self, docker_image: str) -> None:
1✔
693
        """Pushes an image with a given name to a Docker registry"""
694

695
    @abstractmethod
1✔
696
    def build_image(
1✔
697
        self,
698
        dockerfile_path: str,
699
        image_name: str,
700
        context_path: str = None,
701
        platform: Optional[DockerPlatform] = None,
702
    ) -> None:
703
        """Builds an image from the given Dockerfile
704

705
        :param dockerfile_path: Path to Dockerfile, or a directory that contains a Dockerfile
706
        :param image_name: Name of the image to be built
707
        :param context_path: Path for build context (defaults to dirname of Dockerfile)
708
        :param platform: Target platform for build (defaults to platform of Docker host)
709
        """
710

711
    @abstractmethod
1✔
712
    def tag_image(self, source_ref: str, target_name: str) -> None:
1✔
713
        """Tags an image with a new name
714

715
        :param source_ref: Name or ID of the image to be tagged
716
        :param target_name: New name (tag) of the tagged image
717
        """
718

719
    @abstractmethod
1✔
720
    def get_docker_image_names(
1✔
721
        self,
722
        strip_latest: bool = True,
723
        include_tags: bool = True,
724
        strip_wellknown_repo_prefixes: bool = True,
725
    ) -> List[str]:
726
        """
727
        Get all names of docker images available to the container engine
728
        :param strip_latest: return images both with and without :latest tag
729
        :param include_tags: include tags of the images in the names
730
        :param strip_wellknown_repo_prefixes: whether to strip off well-known repo prefixes like
731
               "localhost/" or "docker.io/library/" which are added by the Podman API, but not by Docker
732
        :return: List of image names
733
        """
734

735
    @abstractmethod
1✔
736
    def get_container_logs(self, container_name_or_id: str, safe: bool = False) -> str:
1✔
737
        """Get all logs of a given container"""
738

739
    @abstractmethod
1✔
740
    def stream_container_logs(self, container_name_or_id: str) -> CancellableStream:
1✔
741
        """Returns a blocking generator you can iterate over to retrieve log output as it happens."""
742

743
    @abstractmethod
1✔
744
    def inspect_container(self, container_name_or_id: str) -> Dict[str, Union[Dict, str]]:
1✔
745
        """Get detailed attributes of a container.
746

747
        :return: Dict containing docker attributes as returned by the daemon
748
        """
749

750
    def inspect_container_volumes(self, container_name_or_id) -> List[VolumeInfo]:
1✔
751
        """Return information about the volumes mounted into the given container.
752

753
        :param container_name_or_id: the container name or id
754
        :return: a list of volumes
755
        """
756
        volumes = []
1✔
757
        for doc in self.inspect_container(container_name_or_id)["Mounts"]:
1✔
758
            volumes.append(VolumeInfo(**{k.lower(): v for k, v in doc.items()}))
1✔
759

760
        return volumes
1✔
761

762
    @abstractmethod
1✔
763
    def inspect_image(
1✔
764
        self, image_name: str, pull: bool = True, strip_wellknown_repo_prefixes: bool = True
765
    ) -> Dict[str, Union[dict, list, str]]:
766
        """Get detailed attributes of an image.
767

768
        :param image_name: Image name to inspect
769
        :param pull: Whether to pull image if not existent
770
        :param strip_wellknown_repo_prefixes: whether to strip off well-known repo prefixes like
771
               "localhost/" or "docker.io/library/" which are added by the Podman API, but not by Docker
772
        :return: Dict containing docker attributes as returned by the daemon
773
        """
774

775
    @abstractmethod
1✔
776
    def create_network(self, network_name: str) -> str:
1✔
777
        """
778
        Creates a network with the given name
779
        :param network_name: Name of the network
780
        :return Network ID
781
        """
782

783
    @abstractmethod
1✔
784
    def delete_network(self, network_name: str) -> None:
1✔
785
        """
786
        Delete a network with the given name
787
        :param network_name: Name of the network
788
        """
789

790
    @abstractmethod
1✔
791
    def inspect_network(self, network_name: str) -> Dict[str, Union[Dict, str]]:
1✔
792
        """Get detailed attributes of an network.
793

794
        :return: Dict containing docker attributes as returned by the daemon
795
        """
796

797
    @abstractmethod
1✔
798
    def connect_container_to_network(
1✔
799
        self,
800
        network_name: str,
801
        container_name_or_id: str,
802
        aliases: Optional[List] = None,
803
        link_local_ips: List[str] = None,
804
    ) -> None:
805
        """
806
        Connects a container to a given network
807
        :param network_name: Network to connect the container to
808
        :param container_name_or_id: Container to connect to the network
809
        :param aliases: List of dns names the container should be available under in the network
810
        :param link_local_ips: List of link-local (IPv4 or IPv6) addresses
811
        """
812

813
    @abstractmethod
1✔
814
    def disconnect_container_from_network(
1✔
815
        self, network_name: str, container_name_or_id: str
816
    ) -> None:
817
        """
818
        Disconnects a container from a given network
819
        :param network_name: Network to disconnect the container from
820
        :param container_name_or_id: Container to disconnect from the network
821
        """
822

823
    def get_container_name(self, container_id: str) -> str:
1✔
824
        """Get the name of a container by a given identifier"""
825
        return self.inspect_container(container_id)["Name"].lstrip("/")
1✔
826

827
    def get_container_id(self, container_name: str) -> str:
1✔
828
        """Get the id of a container by a given name"""
829
        return self.inspect_container(container_name)["Id"]
1✔
830

831
    @abstractmethod
1✔
832
    def get_container_ip(self, container_name_or_id: str) -> str:
1✔
833
        """Get the IP address of a given container
834

835
        If container has multiple networks, it will return the IP of the first
836
        """
837

838
    def get_image_cmd(self, docker_image: str, pull: bool = True) -> List[str]:
1✔
839
        """Get the command for the given image
840
        :param docker_image: Docker image to inspect
841
        :param pull: Whether to pull if image is not present
842
        :return: Image command in its array form
843
        """
844
        cmd_list = self.inspect_image(docker_image, pull)["Config"]["Cmd"] or []
1✔
845
        return cmd_list
1✔
846

847
    def get_image_entrypoint(self, docker_image: str, pull: bool = True) -> str:
1✔
848
        """Get the entry point for the given image
849
        :param docker_image: Docker image to inspect
850
        :param pull: Whether to pull if image is not present
851
        :return: Image entrypoint
852
        """
853
        LOG.debug("Getting the entrypoint for image: %s", docker_image)
1✔
854
        entrypoint_list = self.inspect_image(docker_image, pull)["Config"].get("Entrypoint") or []
1✔
855
        return shlex.join(entrypoint_list)
1✔
856

857
    @abstractmethod
1✔
858
    def has_docker(self) -> bool:
1✔
859
        """Check if system has docker available"""
860

861
    @abstractmethod
1✔
862
    def commit(
1✔
863
        self,
864
        container_name_or_id: str,
865
        image_name: str,
866
        image_tag: str,
867
    ):
868
        """Create an image from a running container.
869

870
        :param container_name_or_id: Source container
871
        :param image_name: Destination image name
872
        :param image_tag: Destination image tag
873
        """
874

875
    def create_container_from_config(self, container_config: ContainerConfiguration) -> str:
1✔
876
        """
877
        Similar to create_container, but allows passing the whole ContainerConfiguration
878
        :param container_config: ContainerConfiguration how to start the container
879
        :return: Container ID
880
        """
881
        return self.create_container(
1✔
882
            image_name=container_config.image_name,
883
            name=container_config.name,
884
            entrypoint=container_config.entrypoint,
885
            remove=container_config.remove,
886
            interactive=container_config.interactive,
887
            tty=container_config.tty,
888
            command=container_config.command,
889
            volumes=container_config.volumes,
890
            ports=container_config.ports,
891
            exposed_ports=container_config.exposed_ports,
892
            env_vars=container_config.env_vars,
893
            user=container_config.user,
894
            cap_add=container_config.cap_add,
895
            cap_drop=container_config.cap_drop,
896
            security_opt=container_config.security_opt,
897
            network=container_config.network,
898
            dns=container_config.dns,
899
            additional_flags=container_config.additional_flags,
900
            workdir=container_config.workdir,
901
            privileged=container_config.privileged,
902
            platform=container_config.platform,
903
            labels=container_config.labels,
904
            ulimits=container_config.ulimits,
905
            init=container_config.init,
906
            log_config=container_config.log_config,
907
        )
908

909
    @abstractmethod
1✔
910
    def create_container(
1✔
911
        self,
912
        image_name: str,
913
        *,
914
        name: Optional[str] = None,
915
        entrypoint: Optional[Union[List[str], str]] = None,
916
        remove: bool = False,
917
        interactive: bool = False,
918
        tty: bool = False,
919
        detach: bool = False,
920
        command: Optional[Union[List[str], str]] = None,
921
        volumes: Optional[Union[VolumeMappings, List[SimpleVolumeBind]]] = None,
922
        ports: Optional[PortMappings] = None,
923
        exposed_ports: Optional[List[str]] = None,
924
        env_vars: Optional[Dict[str, str]] = None,
925
        user: Optional[str] = None,
926
        cap_add: Optional[List[str]] = None,
927
        cap_drop: Optional[List[str]] = None,
928
        security_opt: Optional[List[str]] = None,
929
        network: Optional[str] = None,
930
        dns: Optional[Union[str, List[str]]] = None,
931
        additional_flags: Optional[str] = None,
932
        workdir: Optional[str] = None,
933
        privileged: Optional[bool] = None,
934
        labels: Optional[Dict[str, str]] = None,
935
        platform: Optional[DockerPlatform] = None,
936
        ulimits: Optional[List[Ulimit]] = None,
937
        init: Optional[bool] = None,
938
        log_config: Optional[LogConfig] = None,
939
    ) -> str:
940
        """Creates a container with the given image
941

942
        :return: Container ID
943
        """
944

945
    @abstractmethod
1✔
946
    def run_container(
1✔
947
        self,
948
        image_name: str,
949
        stdin: bytes = None,
950
        *,
951
        name: Optional[str] = None,
952
        entrypoint: Optional[str] = None,
953
        remove: bool = False,
954
        interactive: bool = False,
955
        tty: bool = False,
956
        detach: bool = False,
957
        command: Optional[Union[List[str], str]] = None,
958
        volumes: Optional[Union[VolumeMappings, List[SimpleVolumeBind]]] = None,
959
        ports: Optional[PortMappings] = None,
960
        exposed_ports: Optional[List[str]] = None,
961
        env_vars: Optional[Dict[str, str]] = None,
962
        user: Optional[str] = None,
963
        cap_add: Optional[List[str]] = None,
964
        cap_drop: Optional[List[str]] = None,
965
        security_opt: Optional[List[str]] = None,
966
        network: Optional[str] = None,
967
        dns: Optional[str] = None,
968
        additional_flags: Optional[str] = None,
969
        workdir: Optional[str] = None,
970
        labels: Optional[Dict[str, str]] = None,
971
        platform: Optional[DockerPlatform] = None,
972
        privileged: Optional[bool] = None,
973
        ulimits: Optional[List[Ulimit]] = None,
974
        init: Optional[bool] = None,
975
        log_config: Optional[LogConfig] = None,
976
    ) -> Tuple[bytes, bytes]:
977
        """Creates and runs a given docker container
978

979
        :return: A tuple (stdout, stderr)
980
        """
981

982
    def run_container_from_config(
1✔
983
        self, container_config: ContainerConfiguration
984
    ) -> Tuple[bytes, bytes]:
985
        """Like ``run_container`` but uses the parameters from the configuration."""
986

UNCOV
987
        return self.run_container(
×
988
            image_name=container_config.image_name,
989
            stdin=container_config.stdin,
990
            name=container_config.name,
991
            entrypoint=container_config.entrypoint,
992
            remove=container_config.remove,
993
            interactive=container_config.interactive,
994
            tty=container_config.tty,
995
            detach=container_config.detach,
996
            command=container_config.command,
997
            volumes=container_config.volumes,
998
            ports=container_config.ports,
999
            exposed_ports=container_config.exposed_ports,
1000
            env_vars=container_config.env_vars,
1001
            user=container_config.user,
1002
            cap_add=container_config.cap_add,
1003
            cap_drop=container_config.cap_drop,
1004
            security_opt=container_config.security_opt,
1005
            network=container_config.network,
1006
            dns=container_config.dns,
1007
            additional_flags=container_config.additional_flags,
1008
            workdir=container_config.workdir,
1009
            platform=container_config.platform,
1010
            privileged=container_config.privileged,
1011
            ulimits=container_config.ulimits,
1012
            init=container_config.init,
1013
            log_config=container_config.log_config,
1014
        )
1015

1016
    @abstractmethod
1✔
1017
    def exec_in_container(
1✔
1018
        self,
1019
        container_name_or_id: str,
1020
        command: Union[List[str], str],
1021
        interactive: bool = False,
1022
        detach: bool = False,
1023
        env_vars: Optional[Dict[str, Optional[str]]] = None,
1024
        stdin: Optional[bytes] = None,
1025
        user: Optional[str] = None,
1026
        workdir: Optional[str] = None,
1027
    ) -> Tuple[bytes, bytes]:
1028
        """Execute a given command in a container
1029

1030
        :return: A tuple (stdout, stderr)
1031
        """
1032

1033
    @abstractmethod
1✔
1034
    def start_container(
1✔
1035
        self,
1036
        container_name_or_id: str,
1037
        stdin: bytes = None,
1038
        interactive: bool = False,
1039
        attach: bool = False,
1040
        flags: Optional[str] = None,
1041
    ) -> Tuple[bytes, bytes]:
1042
        """Start a given, already created container
1043

1044
        :return: A tuple (stdout, stderr) if attach or interactive is set, otherwise a tuple (b"container_name_or_id", b"")
1045
        """
1046

1047
    @abstractmethod
1✔
1048
    def attach_to_container(self, container_name_or_id: str):
1✔
1049
        """
1050
        Attach local standard input, output, and error streams to a running container
1051
        """
1052

1053
    @abstractmethod
1✔
1054
    def login(self, username: str, password: str, registry: Optional[str] = None) -> None:
1✔
1055
        """
1056
        Login into an OCI registry
1057

1058
        :param username: Username for the registry
1059
        :param password: Password / token for the registry
1060
        :param registry: Registry url
1061
        """
1062

1063

1064
class Util:
1✔
1065
    MAX_ENV_ARGS_LENGTH = 20000
1✔
1066

1067
    @staticmethod
1✔
1068
    def format_env_vars(key: str, value: Optional[str]):
1✔
1069
        if value is None:
1✔
UNCOV
1070
            return key
×
1071
        return f"{key}={value}"
1✔
1072

1073
    @classmethod
1✔
1074
    def create_env_vars_file_flag(cls, env_vars: Dict) -> Tuple[List[str], Optional[str]]:
1✔
1075
        if not env_vars:
1✔
UNCOV
1076
            return [], None
×
1077
        result = []
1✔
1078
        env_vars = dict(env_vars)
1✔
1079
        env_file = None
1✔
1080
        if len(str(env_vars)) > cls.MAX_ENV_ARGS_LENGTH:
1✔
1081
            # default ARG_MAX=131072 in Docker - let's create an env var file if the string becomes too long...
UNCOV
1082
            env_file = cls.mountable_tmp_file()
×
UNCOV
1083
            env_content = ""
×
UNCOV
1084
            for name, value in dict(env_vars).items():
×
UNCOV
1085
                if len(value) > cls.MAX_ENV_ARGS_LENGTH:
×
1086
                    # each line in the env file has a max size as well (error "bufio.Scanner: token too long")
UNCOV
1087
                    continue
×
UNCOV
1088
                env_vars.pop(name)
×
UNCOV
1089
                value = value.replace("\n", "\\")
×
UNCOV
1090
                env_content += f"{cls.format_env_vars(name, value)}\n"
×
UNCOV
1091
            save_file(env_file, env_content)
×
UNCOV
1092
            result += ["--env-file", env_file]
×
1093

1094
        env_vars_res = [
1✔
1095
            item for k, v in env_vars.items() for item in ["-e", cls.format_env_vars(k, v)]
1096
        ]
1097
        result += env_vars_res
1✔
1098
        return result, env_file
1✔
1099

1100
    @staticmethod
1✔
1101
    def rm_env_vars_file(env_vars_file) -> None:
1✔
1102
        if env_vars_file:
1✔
UNCOV
1103
            return rm_rf(env_vars_file)
×
1104

1105
    @staticmethod
1✔
1106
    def mountable_tmp_file():
1✔
UNCOV
1107
        f = os.path.join(config.dirs.mounted_tmp, short_uid())
×
UNCOV
1108
        TMP_FILES.append(f)
×
UNCOV
1109
        return f
×
1110

1111
    @staticmethod
1✔
1112
    def append_without_latest(image_names: List[str]):
1✔
1113
        suffix = ":latest"
1✔
1114
        for image in list(image_names):
1✔
1115
            if image.endswith(suffix):
1✔
1116
                image_names.append(image[: -len(suffix)])
1✔
1117

1118
    @staticmethod
1✔
1119
    def strip_wellknown_repo_prefixes(image_names: List[str]) -> List[str]:
1✔
1120
        """
1121
        Remove well-known repo prefixes like `localhost/` or `docker.io/library/` from the list of given
1122
        image names. This is mostly to ensure compatibility of our Docker client with Podman API responses.
1123
        :return: a copy of the list of image names, with well-known repo prefixes removed
1124
        """
1125
        result = []
1✔
1126
        for image in image_names:
1✔
1127
            for prefix in WELL_KNOWN_IMAGE_REPO_PREFIXES:
1✔
1128
                if image.startswith(prefix):
1✔
UNCOV
1129
                    image = image.removeprefix(prefix)
×
1130
                    # strip only one of the matching prefixes (avoid multi-stripping)
UNCOV
1131
                    break
×
1132
            result.append(image)
1✔
1133
        return result
1✔
1134

1135
    @staticmethod
1✔
1136
    def tar_path(path: str, target_path: str, is_dir: bool):
1✔
1137
        f = tempfile.NamedTemporaryFile()
1✔
1138
        with tarfile.open(mode="w", fileobj=f) as t:
1✔
1139
            abs_path = os.path.abspath(path)
1✔
1140
            arcname = (
1✔
1141
                os.path.basename(path)
1142
                if is_dir
1143
                else (os.path.basename(target_path) or os.path.basename(path))
1144
            )
1145
            t.add(abs_path, arcname=arcname)
1✔
1146

1147
        f.seek(0)
1✔
1148
        return f
1✔
1149

1150
    @staticmethod
1✔
1151
    def untar_to_path(tardata, target_path):
1✔
1152
        target_path = Path(target_path)
1✔
1153
        with tarfile.open(mode="r", fileobj=io.BytesIO(b"".join(b for b in tardata))) as t:
1✔
1154
            if target_path.is_dir():
1✔
1155
                t.extractall(path=target_path)
1✔
1156
            else:
1157
                member = t.next()
1✔
1158
                if member:
1✔
1159
                    member.name = target_path.name
1✔
1160
                    t.extract(member, target_path.parent)
1✔
1161
                else:
UNCOV
1162
                    LOG.debug("File to copy empty, ignoring...")
×
1163

1164
    @staticmethod
1✔
1165
    def _read_docker_cli_env_file(env_file: str) -> Dict[str, str]:
1✔
1166
        """
1167
        Read an environment file in docker CLI format, specified here:
1168
        https://docs.docker.com/reference/cli/docker/container/run/#env
1169
        :param env_file: Path to the environment file
1170
        :return: Read environment variables
1171
        """
1172
        env_vars = {}
1✔
1173
        try:
1✔
1174
            with open(env_file, mode="rt") as f:
1✔
1175
                env_file_lines = f.readlines()
1✔
UNCOV
1176
        except FileNotFoundError as e:
×
UNCOV
1177
            LOG.error(
×
1178
                "Specified env file '%s' not found. Please make sure the file is properly mounted into the LocalStack container. Error: %s",
1179
                env_file,
1180
                e,
1181
            )
UNCOV
1182
            raise
×
UNCOV
1183
        except OSError as e:
×
UNCOV
1184
            LOG.error(
×
1185
                "Could not read env file '%s'. Please make sure the LocalStack container has the permissions to read it. Error: %s",
1186
                env_file,
1187
                e,
1188
            )
UNCOV
1189
            raise
×
1190
        for idx, line in enumerate(env_file_lines):
1✔
1191
            line = line.strip()
1✔
1192
            if not line or line.startswith("#"):
1✔
1193
                # skip comments or empty lines
1194
                continue
1✔
1195
            lhs, separator, rhs = line.partition("=")
1✔
1196
            if rhs or separator:
1✔
1197
                env_vars[lhs] = rhs
1✔
1198
            else:
1199
                # No "=" in the line, only the name => lookup in local env
1200
                if env_value := os.environ.get(lhs):
1✔
1201
                    env_vars[lhs] = env_value
1✔
1202
        return env_vars
1✔
1203

1204
    @staticmethod
1✔
1205
    def parse_additional_flags(
1✔
1206
        additional_flags: str,
1207
        env_vars: Optional[Dict[str, str]] = None,
1208
        labels: Optional[Dict[str, str]] = None,
1209
        volumes: Optional[List[SimpleVolumeBind]] = None,
1210
        network: Optional[str] = None,
1211
        platform: Optional[DockerPlatform] = None,
1212
        ports: Optional[PortMappings] = None,
1213
        privileged: Optional[bool] = None,
1214
        user: Optional[str] = None,
1215
        ulimits: Optional[List[Ulimit]] = None,
1216
        dns: Optional[Union[str, List[str]]] = None,
1217
    ) -> DockerRunFlags:
1218
        """Parses additional CLI-formatted Docker flags, which could overwrite provided defaults.
1219
        :param additional_flags: String which contains the flag definitions inspired by the Docker CLI reference:
1220
                                 https://docs.docker.com/engine/reference/commandline/run/
1221
        :param env_vars: Dict with env vars. Will be modified in place.
1222
        :param labels: Dict with labels. Will be modified in place.
1223
        :param volumes: List of mount tuples (host_path, container_path). Will be modified in place.
1224
        :param network: Existing network name (optional). Warning will be printed if network is overwritten in flags.
1225
        :param platform: Platform to execute container. Warning will be printed if platform is overwritten in flags.
1226
        :param ports: PortMapping object. Will be modified in place.
1227
        :param privileged: Run the container in privileged mode. Warning will be printed if overwritten in flags.
1228
        :param ulimits: ulimit options in the format <type>=<soft limit>[:<hard limit>]
1229
        :param user: User to run first process. Warning will be printed if user is overwritten in flags.
1230
        :param dns: List of DNS servers to configure the container with.
1231
        :return: A DockerRunFlags object that will return new objects if respective parameters were None and
1232
                additional flags contained a flag for that object or the same which are passed otherwise.
1233
        """
1234
        # Argparse refactoring opportunity: custom argparse actions can be used to modularize parsing (e.g., key=value)
1235
        # https://docs.python.org/3/library/argparse.html#action
1236

1237
        # Configure parser
1238
        parser = NoExitArgumentParser(description="Docker run flags parser")
1✔
1239
        parser.add_argument(
1✔
1240
            "--add-host",
1241
            help="Add a custom host-to-IP mapping (host:ip)",
1242
            dest="add_hosts",
1243
            action="append",
1244
        )
1245
        parser.add_argument(
1✔
1246
            "--env", "-e", help="Set environment variables", dest="envs", action="append"
1247
        )
1248
        parser.add_argument(
1✔
1249
            "--env-file",
1250
            help="Set environment variables via a file",
1251
            dest="env_files",
1252
            action="append",
1253
        )
1254
        parser.add_argument(
1✔
1255
            "--compose-env-file",
1256
            help="Set environment variables via a file, with a docker-compose supported feature set.",
1257
            dest="compose_env_files",
1258
            action="append",
1259
        )
1260
        parser.add_argument(
1✔
1261
            "--label", "-l", help="Add container meta data", dest="labels", action="append"
1262
        )
1263
        parser.add_argument("--network", help="Connect a container to a network")
1✔
1264
        parser.add_argument(
1✔
1265
            "--platform",
1266
            type=DockerPlatform,
1267
            help="Docker platform (e.g., linux/amd64 or linux/arm64)",
1268
        )
1269
        parser.add_argument(
1✔
1270
            "--privileged",
1271
            help="Give extended privileges to this container",
1272
            action="store_true",
1273
        )
1274
        parser.add_argument(
1✔
1275
            "--publish",
1276
            "-p",
1277
            help="Publish container port(s) to the host",
1278
            dest="publish_ports",
1279
            action="append",
1280
        )
1281
        parser.add_argument(
1✔
1282
            "--ulimit", help="Container ulimit settings", dest="ulimits", action="append"
1283
        )
1284
        parser.add_argument("--user", "-u", help="Username or UID to execute first process")
1✔
1285
        parser.add_argument(
1✔
1286
            "--volume", "-v", help="Bind mount a volume", dest="volumes", action="append"
1287
        )
1288
        parser.add_argument("--dns", help="Set custom DNS servers", dest="dns", action="append")
1✔
1289

1290
        # Parse
1291
        flags = shlex.split(additional_flags)
1✔
1292
        args = parser.parse_args(flags)
1✔
1293

1294
        # Post-process parsed flags
1295
        extra_hosts = None
1✔
1296
        if args.add_hosts:
1✔
1297
            for add_host in args.add_hosts:
1✔
1298
                extra_hosts = extra_hosts if extra_hosts is not None else {}
1✔
1299
                hosts_split = add_host.split(":")
1✔
1300
                extra_hosts[hosts_split[0]] = hosts_split[1]
1✔
1301

1302
        # set env file values before env values, as the latter override the earlier
1303
        if args.env_files:
1✔
1304
            env_vars = env_vars if env_vars is not None else {}
1✔
1305
            for env_file in args.env_files:
1✔
1306
                env_vars.update(Util._read_docker_cli_env_file(env_file))
1✔
1307

1308
        if args.compose_env_files:
1✔
1309
            env_vars = env_vars if env_vars is not None else {}
1✔
1310
            for env_file in args.compose_env_files:
1✔
1311
                env_vars.update(dotenv.dotenv_values(env_file))
1✔
1312

1313
        if args.envs:
1✔
1314
            env_vars = env_vars if env_vars is not None else {}
1✔
1315
            for env in args.envs:
1✔
1316
                lhs, _, rhs = env.partition("=")
1✔
1317
                env_vars[lhs] = rhs
1✔
1318

1319
        if args.labels:
1✔
1320
            labels = labels if labels is not None else {}
1✔
1321
            for label in args.labels:
1✔
1322
                key, _, value = label.partition("=")
1✔
1323
                # Only consider non-empty labels
1324
                if key:
1✔
1325
                    labels[key] = value
1✔
1326

1327
        if args.network:
1✔
1328
            LOG.warning(
1✔
1329
                "Overwriting Docker container network '%s' with new value '%s'",
1330
                network,
1331
                args.network,
1332
            )
1333
            network = args.network
1✔
1334

1335
        if args.platform:
1✔
1336
            LOG.warning(
1✔
1337
                "Overwriting Docker platform '%s' with new value '%s'",
1338
                platform,
1339
                args.platform,
1340
            )
1341
            platform = args.platform
1✔
1342

1343
        if args.privileged:
1✔
1344
            LOG.warning(
1✔
1345
                "Overwriting Docker container privileged flag %s with new value %s",
1346
                privileged,
1347
                args.privileged,
1348
            )
1349
            privileged = args.privileged
1✔
1350

1351
        if args.publish_ports:
1✔
1352
            for port_mapping in args.publish_ports:
1✔
1353
                port_split = port_mapping.split(":")
1✔
1354
                protocol = "tcp"
1✔
1355
                if len(port_split) == 2:
1✔
1356
                    host_port, container_port = port_split
1✔
1357
                elif len(port_split) == 3:
1✔
1358
                    LOG.warning(
1✔
1359
                        "Host part of port mappings are ignored currently in additional flags"
1360
                    )
1361
                    _, host_port, container_port = port_split
1✔
1362
                else:
1363
                    raise ValueError(f"Invalid port string provided: {port_mapping}")
1✔
1364
                host_port_split = host_port.split("-")
1✔
1365
                if len(host_port_split) == 2:
1✔
1366
                    host_port = [int(host_port_split[0]), int(host_port_split[1])]
1✔
1367
                elif len(host_port_split) == 1:
1✔
1368
                    host_port = int(host_port)
1✔
1369
                else:
UNCOV
1370
                    raise ValueError(f"Invalid port string provided: {port_mapping}")
×
1371
                if "/" in container_port:
1✔
1372
                    container_port, protocol = container_port.split("/")
1✔
1373
                ports = ports if ports is not None else PortMappings()
1✔
1374
                ports.add(host_port, int(container_port), protocol)
1✔
1375

1376
        if args.ulimits:
1✔
1377
            ulimits = ulimits if ulimits is not None else []
1✔
1378
            ulimits_dict = {ul.name: ul for ul in ulimits}
1✔
1379
            for ulimit in args.ulimits:
1✔
1380
                name, _, rhs = ulimit.partition("=")
1✔
1381
                soft, _, hard = rhs.partition(":")
1✔
1382
                hard_limit = int(hard) if hard else int(soft)
1✔
1383
                new_ulimit = Ulimit(name=name, soft_limit=int(soft), hard_limit=hard_limit)
1✔
1384
                if ulimits_dict.get(name):
1✔
1385
                    LOG.warning("Overwriting Docker ulimit %s", new_ulimit)
1✔
1386
                ulimits_dict[name] = new_ulimit
1✔
1387
            ulimits = list(ulimits_dict.values())
1✔
1388

1389
        if args.user:
1✔
1390
            LOG.warning(
1✔
1391
                "Overwriting Docker user '%s' with new value '%s'",
1392
                user,
1393
                args.user,
1394
            )
1395
            user = args.user
1✔
1396

1397
        if args.volumes:
1✔
1398
            volumes = volumes if volumes is not None else []
1✔
1399
            for volume in args.volumes:
1✔
1400
                match = re.match(
1✔
1401
                    r"(?P<host>[\w\s\\\/:\-.]+?):(?P<container>[\w\s\/\-.]+)(?::(?P<arg>ro|rw|z|Z))?",
1402
                    volume,
1403
                )
1404
                if not match:
1✔
UNCOV
1405
                    LOG.warning("Unable to parse volume mount Docker flags: %s", volume)
×
UNCOV
1406
                    continue
×
1407
                host_path = match.group("host")
1✔
1408
                container_path = match.group("container")
1✔
1409
                rw_args = match.group("arg")
1✔
1410
                if rw_args:
1✔
1411
                    LOG.info("Volume options like :ro or :rw are currently ignored.")
1✔
1412
                volumes.append((host_path, container_path))
1✔
1413

1414
        dns = ensure_list(dns or [])
1✔
1415
        if args.dns:
1✔
1416
            LOG.info(
1✔
1417
                "Extending Docker container DNS servers %s with additional values %s", dns, args.dns
1418
            )
1419
            dns.extend(args.dns)
1✔
1420

1421
        return DockerRunFlags(
1✔
1422
            env_vars=env_vars,
1423
            extra_hosts=extra_hosts,
1424
            labels=labels,
1425
            volumes=volumes,
1426
            ports=ports,
1427
            network=network,
1428
            platform=platform,
1429
            privileged=privileged,
1430
            ulimits=ulimits,
1431
            user=user,
1432
            dns=dns,
1433
        )
1434

1435
    @staticmethod
1✔
1436
    def convert_mount_list_to_dict(
1✔
1437
        volumes: Union[List[SimpleVolumeBind], VolumeMappings],
1438
    ) -> Dict[str, Dict[str, str]]:
1439
        """Converts a List of (host_path, container_path) tuples to a Dict suitable as volume argument for docker sdk"""
1440

1441
        def _map_to_dict(paths: SimpleVolumeBind | VolumeBind):
1✔
1442
            if isinstance(paths, VolumeBind):
1✔
1443
                return str(paths.host_dir), {
1✔
1444
                    "bind": paths.container_dir,
1445
                    "mode": "ro" if paths.read_only else "rw",
1446
                }
1447
            else:
UNCOV
1448
                return str(paths[0]), {"bind": paths[1], "mode": "rw"}
×
1449

1450
        return dict(
1✔
1451
            map(
1452
                _map_to_dict,
1453
                volumes,
1454
            )
1455
        )
1456

1457
    @staticmethod
1✔
1458
    def resolve_dockerfile_path(dockerfile_path: str) -> str:
1✔
1459
        """If the given path is a directory that contains a Dockerfile, then return the file path to it."""
1460
        rel_path = os.path.join(dockerfile_path, "Dockerfile")
1✔
1461
        if os.path.isdir(dockerfile_path) and os.path.exists(rel_path):
1✔
1462
            return rel_path
1✔
1463
        return dockerfile_path
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc