dev-isolator 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dev_isolator/__init__.py +13 -0
- dev_isolator/__main__.py +15 -0
- dev_isolator/base_image.py +429 -0
- dev_isolator/config.py +650 -0
- dev_isolator/constants.py +58 -0
- dev_isolator/container_image.py +302 -0
- dev_isolator/container_manager.py +516 -0
- dev_isolator/data/Containerfile +32 -0
- dev_isolator/data/addons/addon.claude.jinja2 +16 -0
- dev_isolator/data/addons/addon.opencode.jinja2 +16 -0
- dev_isolator/data/addons/config.claude.yaml +292 -0
- dev_isolator/data/addons/config.opencode.py +4 -0
- dev_isolator/data/addons/config.opencode.yaml +8 -0
- dev_isolator/data/base/Containerfile.almalinux-10 +5 -0
- dev_isolator/data/base/Containerfile.almalinux-9 +5 -0
- dev_isolator/data/base/Containerfile.archlinux +6 -0
- dev_isolator/data/base/Containerfile.debian-13 +6 -0
- dev_isolator/data/base/Containerfile.fedora-43 +5 -0
- dev_isolator/data/base/Containerfile.fedora-44 +5 -0
- dev_isolator/data/base/Containerfile.fedora-45 +5 -0
- dev_isolator/data/base/Containerfile.fedora-rawhide +6 -0
- dev_isolator/data/base/Containerfile.opensuse-leap +4 -0
- dev_isolator/data/base/Containerfile.opensuse-tumbleweed +5 -0
- dev_isolator/data/base/Containerfile.ubuntu-22.04 +6 -0
- dev_isolator/data/base/Containerfile.ubuntu-24.04 +7 -0
- dev_isolator/data/base/Containerfile.ubuntu-26.04 +8 -0
- dev_isolator/data/config.yaml +136 -0
- dev_isolator/data/setup/add_user.containerfile.jinja2 +36 -0
- dev_isolator/main.py +931 -0
- dev_isolator/podman_utils.py +116 -0
- dev_isolator/utils.py +86 -0
- dev_isolator/waitspinner.py +115 -0
- dev_isolator-0.1.0.dist-info/METADATA +131 -0
- dev_isolator-0.1.0.dist-info/RECORD +38 -0
- dev_isolator-0.1.0.dist-info/WHEEL +5 -0
- dev_isolator-0.1.0.dist-info/entry_points.txt +3 -0
- dev_isolator-0.1.0.dist-info/licenses/LICENSE +674 -0
- dev_isolator-0.1.0.dist-info/top_level.txt +1 -0
dev_isolator/config.py
ADDED
|
@@ -0,0 +1,650 @@
|
|
|
1
|
+
"""Read and parse the addon configuration files of dev-isolator.
|
|
2
|
+
|
|
3
|
+
This module is only about the configuration files themselves:
|
|
4
|
+
which addons are enabled (``config.yaml``), the environment
|
|
5
|
+
variables and volumes requested in ``config.yaml`` and by an addon
|
|
6
|
+
(``config.<addon_name>.yaml``), and the syntax of volume specs.
|
|
7
|
+
|
|
8
|
+
Locating the files inside a build context is done by
|
|
9
|
+
:class:`dev_isolator.container_manager.ContainerDefintion`.
|
|
10
|
+
|
|
11
|
+
Copyright (C) 2026 Martin Köhler
|
|
12
|
+
|
|
13
|
+
This program comes with ABSOLUTELY NO WARRANTY.
|
|
14
|
+
This is free software, and you are welcome to redistribute it
|
|
15
|
+
under certain conditions; see LICENSE for details.
|
|
16
|
+
SPDX-License-Identifier: GPL-3.0-or-later
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from .constants import (ADDON_FILE_PREFIX, ADDON_FILE_SUFFIX,
|
|
23
|
+
ADDON_CONFIG_FILE_PREFIX, ADDON_CONFIG_FILE_SUFFIX,
|
|
24
|
+
CONFIG_VERSION)
|
|
25
|
+
import yaml
|
|
26
|
+
import importlib.util
|
|
27
|
+
|
|
28
|
+
from .utils import Verbosity, dprint
|
|
29
|
+
|
|
30
|
+
ENV_REFERENCE_PATTERN = re.compile(r"ENV\[(\w+)\]")
|
|
31
|
+
# Sentinel marking a not-yet-computed cached value.
|
|
32
|
+
_UNSET = object()
|
|
33
|
+
|
|
34
|
+
#: Keyword arguments of the podman bindings' ``containers.create()``
|
|
35
|
+
#: (see https://podman-py.readthedocs.io/en/latest/
|
|
36
|
+
#: podman.domain.containers_create.html) that may be set via the
|
|
37
|
+
#: ``run_arguments`` key of ``config.yaml``. The most common ones:
|
|
38
|
+
SUPPORTED_RUN_ARGUMENTS = frozenset({
|
|
39
|
+
"auto_remove", # Remove the container when its process exits.
|
|
40
|
+
"cap_add", # Add kernel capabilities,
|
|
41
|
+
# e.g. ["SYS_ADMIN", "MKNOD"].
|
|
42
|
+
"cap_drop", # Drop kernel capabilities.
|
|
43
|
+
"cpu_shares", # CPU shares (relative weight).
|
|
44
|
+
"cpuset_cpus", # CPUs in which to allow execution ("0-3", "0,1").
|
|
45
|
+
"devices", # Expose host devices,
|
|
46
|
+
# e.g. ["/dev/sda:/dev/xvda:rwm"].
|
|
47
|
+
"dns", # Custom DNS servers, e.g. ["8.8.8.8"].
|
|
48
|
+
"dns_search", # DNS search domains.
|
|
49
|
+
"extra_hosts", # Additional hostnames, mapping hostname to IP.
|
|
50
|
+
"group_add", # Additional groups the container process runs as.
|
|
51
|
+
"hostname", # Optional hostname for the container.
|
|
52
|
+
"init", # Run an init that forwards
|
|
53
|
+
# signals and reaps processes.
|
|
54
|
+
"ipc_mode", # IPC mode for the container.
|
|
55
|
+
"labels", # Name-value labels, e.g. {"label1": "value1"}.
|
|
56
|
+
"mem_limit", # Memory limit, e.g. 1073741824 or "1g".
|
|
57
|
+
"mem_reservation", # Memory soft limit.
|
|
58
|
+
"memswap_limit", # Maximum memory + swap the container may consume.
|
|
59
|
+
"nano_cpus", # CPU quota in units of 1e-9 CPUs
|
|
60
|
+
# (e.g. 2000000000 = 2 CPUs).
|
|
61
|
+
"network_mode", # One of "bridge", "none", "host",
|
|
62
|
+
# "container:<name|id>".
|
|
63
|
+
"pid_mode", # "host" to use the host PID namespace.
|
|
64
|
+
"ports", # Ports to bind, e.g. {"2222/tcp": 3333}.
|
|
65
|
+
"privileged", # Give extended privileges to the container.
|
|
66
|
+
"publish_all_ports", # Publish all exposed ports to the host.
|
|
67
|
+
"read_only", # Mount the container's root filesystem read only.
|
|
68
|
+
"restart_policy", # Restart on exit,
|
|
69
|
+
# e.g. {"Name": "on-failure","MaximumRetryCount": 5}.
|
|
70
|
+
"security_opt", # MLS/SELinux label customization,
|
|
71
|
+
# e.g. ["label=disable"].
|
|
72
|
+
"shm_size", # Size of /dev/shm, e.g. "1G".
|
|
73
|
+
"stdin_open", # Keep STDIN open even if not attached.
|
|
74
|
+
"stop_signal", # Signal used to stop the container, e.g. "SIGINT".
|
|
75
|
+
"sysctls", # Kernel parameters to set,
|
|
76
|
+
# e.g. {"net.ipv4.ip_forward": "1"}.
|
|
77
|
+
"tty", # Allocate a pseudo-TTY.
|
|
78
|
+
"user", # Username or UID to run commands as inside
|
|
79
|
+
# the container.
|
|
80
|
+
"userns_mode", # Usermode for the network, default
|
|
81
|
+
"working_dir", # Working directory inside the container.
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
#: Keyword arguments of ``containers.create()`` that dev-isolator
|
|
85
|
+
#: controls itself; they cannot be overridden via ``run_arguments``.
|
|
86
|
+
RESERVED_RUN_ARGUMENTS = frozenset({
|
|
87
|
+
"image", "command", "name", "entrypoint",
|
|
88
|
+
"environment", "volumes", "detach",
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def addon_name(path: Path) -> str:
|
|
93
|
+
"""Return the name of an addon file (``addon.<name>.jinja2``).
|
|
94
|
+
|
|
95
|
+
:param path: Path to an addon file; the addon name is the part
|
|
96
|
+
after ``addon.``, with the ``.jinja2`` template suffix
|
|
97
|
+
removed, e.g. ``opencode`` for ``addon.opencode.jinja2``.
|
|
98
|
+
:returns: The addon name.
|
|
99
|
+
"""
|
|
100
|
+
return path.name.removeprefix(ADDON_FILE_PREFIX).removesuffix(
|
|
101
|
+
ADDON_FILE_SUFFIX)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_environment_and_volumes(config_file: Path) -> dict:
|
|
105
|
+
"""Return the ``environment`` and ``volumes`` entries of a config
|
|
106
|
+
file (the main ``config.yaml`` or an addon
|
|
107
|
+
``config.<addon_name>.yaml``).
|
|
108
|
+
|
|
109
|
+
The file is expected to have the shape::
|
|
110
|
+
|
|
111
|
+
environment:
|
|
112
|
+
- VAR1
|
|
113
|
+
- VAR2
|
|
114
|
+
- VAR3=value3
|
|
115
|
+
volumes:
|
|
116
|
+
- path:/path/in/container
|
|
117
|
+
- path:/path/in/container:ro
|
|
118
|
+
|
|
119
|
+
Missing (or empty) sections are returned as empty lists.
|
|
120
|
+
|
|
121
|
+
:param config_file: Path to the config file.
|
|
122
|
+
:returns: A dict with the keys ``environment`` and ``volumes``,
|
|
123
|
+
each holding a list of strings.
|
|
124
|
+
:raises RuntimeError: if the file is not valid YAML, does not
|
|
125
|
+
contain a mapping, or one of the sections is not a list of
|
|
126
|
+
strings.
|
|
127
|
+
"""
|
|
128
|
+
try:
|
|
129
|
+
data = yaml.safe_load(config_file.read_text(encoding="utf-8"))
|
|
130
|
+
except yaml.YAMLError as e:
|
|
131
|
+
raise RuntimeError(
|
|
132
|
+
f"Invalid config file {config_file}: {e}") from e
|
|
133
|
+
if data is None:
|
|
134
|
+
data = {}
|
|
135
|
+
if not isinstance(data, dict):
|
|
136
|
+
raise RuntimeError(
|
|
137
|
+
f"Invalid config file {config_file}: "
|
|
138
|
+
"expected a mapping with 'environment' and/or 'volumes' keys")
|
|
139
|
+
|
|
140
|
+
config = {"environment": [], "volumes": []}
|
|
141
|
+
for key in config:
|
|
142
|
+
entries = data.get(key)
|
|
143
|
+
if entries is None:
|
|
144
|
+
continue
|
|
145
|
+
if not isinstance(entries, list) \
|
|
146
|
+
or not all(isinstance(entry, str) for entry in entries):
|
|
147
|
+
raise RuntimeError(
|
|
148
|
+
f"Invalid addon config file {config_file}: "
|
|
149
|
+
f"'{key}' must be a list of strings")
|
|
150
|
+
config[key] = entries
|
|
151
|
+
return config
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def resolve_env_references(spec: str) -> str | None:
|
|
155
|
+
"""Replace ``ENV[NAME]`` references in a volume spec part with the
|
|
156
|
+
value of the environment variable ``NAME``.
|
|
157
|
+
|
|
158
|
+
:param spec: The volume spec part; every ``ENV[NAME]`` occurrence
|
|
159
|
+
(with ``NAME`` an identifier) is replaced in place.
|
|
160
|
+
:returns: The spec with all references resolved, or ``None``
|
|
161
|
+
when a referenced environment variable is not set (i.e.
|
|
162
|
+
could not be replaced).
|
|
163
|
+
"""
|
|
164
|
+
# An unset variable turns a None replacement into an empty
|
|
165
|
+
# string, so unresolvable references must be detected before
|
|
166
|
+
# replacing them.
|
|
167
|
+
names = ENV_REFERENCE_PATTERN.findall(spec)
|
|
168
|
+
if any(os.environ.get(name) is None for name in names):
|
|
169
|
+
return None
|
|
170
|
+
return ENV_REFERENCE_PATTERN.sub(
|
|
171
|
+
lambda match: os.environ[match.group(1)], spec)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def parse_volume_spec(spec: str) -> tuple[str, str, str]:
|
|
175
|
+
"""Split a volume spec ``host:container[:mode]`` into its parts.
|
|
176
|
+
|
|
177
|
+
:returns: The tuple ``(host_path, container_path, mode)``; the
|
|
178
|
+
mode defaults to ``rw`` when the spec has no third part.
|
|
179
|
+
:raises RuntimeError: if the spec does not have a host and a
|
|
180
|
+
container path part.
|
|
181
|
+
"""
|
|
182
|
+
parts = spec.split(":")
|
|
183
|
+
if len(parts) == 2:
|
|
184
|
+
host, container_path, mode = *parts, "rw"
|
|
185
|
+
elif len(parts) == 3:
|
|
186
|
+
host, container_path, mode = parts
|
|
187
|
+
else:
|
|
188
|
+
raise RuntimeError(
|
|
189
|
+
f"Invalid volume spec '{spec}': expected "
|
|
190
|
+
"'host_path:container_path[:mode]'")
|
|
191
|
+
if not host or not container_path:
|
|
192
|
+
raise RuntimeError(
|
|
193
|
+
f"Invalid volume spec '{spec}': "
|
|
194
|
+
"host and container path must be non-empty")
|
|
195
|
+
return host, container_path, mode
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class Configuration:
|
|
199
|
+
"""Locate and read the configuration files controlling the addons.
|
|
200
|
+
|
|
201
|
+
All configuration management lives here: the active ``config.yaml``
|
|
202
|
+
(the ``config_file`` given to the constructor), the ``addon.*``
|
|
203
|
+
files to append to the Containerfile (see :meth:`list_addon_files`),
|
|
204
|
+
the per-addon ``config.<addon_name>.yaml`` files with the environment
|
|
205
|
+
variables and volumes of every addon (see
|
|
206
|
+
:meth:`addon_run_settings`) and the environment variables and
|
|
207
|
+
volumes declared directly in the ``config.yaml`` (see
|
|
208
|
+
:meth:`config_environment` and :meth:`config_volumes`).
|
|
209
|
+
|
|
210
|
+
The ``.devisolator`` directory inside the build context takes
|
|
211
|
+
precedence over the directory bundled with dev-isolator: the
|
|
212
|
+
first configuration file found is used and the bundled list is
|
|
213
|
+
ignored entirely.
|
|
214
|
+
|
|
215
|
+
Computed results are cached for the lifetime of the instance, so
|
|
216
|
+
repeated calls (e.g. during a build) evaluate each configuration
|
|
217
|
+
file only once.
|
|
218
|
+
"""
|
|
219
|
+
|
|
220
|
+
def __init__(self, config_file,
|
|
221
|
+
addon_search_paths):
|
|
222
|
+
"""Set up the configuration for a build context.
|
|
223
|
+
|
|
224
|
+
:param config_file: Path to the active ``config.yaml`` file
|
|
225
|
+
determining the enabled addons.
|
|
226
|
+
:param addon_search_paths: List of directories searched for
|
|
227
|
+
``addon.*`` files and ``config.<addon_name>.yaml`` files,
|
|
228
|
+
in precedence order (the first existing file wins).
|
|
229
|
+
"""
|
|
230
|
+
self.config_file = config_file
|
|
231
|
+
self.addon_search_paths = addon_search_paths
|
|
232
|
+
self._enabled_addons = _UNSET
|
|
233
|
+
self._addon_files = _UNSET
|
|
234
|
+
|
|
235
|
+
try:
|
|
236
|
+
self.yaml_data = (yaml.safe_load(
|
|
237
|
+
config_file.read_text(encoding="utf-8")))
|
|
238
|
+
except yaml.YAMLError as e:
|
|
239
|
+
raise RuntimeError(
|
|
240
|
+
f"Invalid config file {config_file}: {e}") from e
|
|
241
|
+
if self.yaml_data is None:
|
|
242
|
+
self.yaml_data = {}
|
|
243
|
+
if not isinstance(self.yaml_data, dict):
|
|
244
|
+
raise RuntimeError(f"Invalid config file {config_file}: "
|
|
245
|
+
"expected a mapping with an 'addons' key")
|
|
246
|
+
|
|
247
|
+
version = self.yaml_data.get("version")
|
|
248
|
+
# YAML parses an unquoted "0.1" as a float, so compare the
|
|
249
|
+
# string form to accept both "0.1" and 0.1 in the config.
|
|
250
|
+
if version is None or str(version) != CONFIG_VERSION:
|
|
251
|
+
raise RuntimeError(
|
|
252
|
+
f"Unsupported config file version in {config_file}: "
|
|
253
|
+
f"expected {CONFIG_VERSION}, got {version!r}. "
|
|
254
|
+
"Please update the 'version' key of your config.yaml.")
|
|
255
|
+
|
|
256
|
+
def enabled_addons(self) -> set[str]:
|
|
257
|
+
"""Return the names of the enabled addons.
|
|
258
|
+
|
|
259
|
+
Reads the ``addons`` key of the ``config.yaml`` file given to
|
|
260
|
+
the constructor (the active config file).
|
|
261
|
+
|
|
262
|
+
The result is computed once and cached for the lifetime of
|
|
263
|
+
this instance, so repeated calls (e.g. from
|
|
264
|
+
:meth:`list_addon_files` during a build) do not print the addon
|
|
265
|
+
managing messages again.
|
|
266
|
+
|
|
267
|
+
:returns: The set of enabled addon names, or an empty set when
|
|
268
|
+
the ``addons`` key is missing (no addons enabled).
|
|
269
|
+
:raises RuntimeError: if the ``config.yaml`` file is invalid.
|
|
270
|
+
"""
|
|
271
|
+
if self._enabled_addons is _UNSET:
|
|
272
|
+
enabled = self.yaml_data.get("addons", None)
|
|
273
|
+
if enabled is None:
|
|
274
|
+
return set()
|
|
275
|
+
if not isinstance(enabled, list):
|
|
276
|
+
raise RuntimeError(f"Invalid config file {self.config_file}: "
|
|
277
|
+
"'addons' must be a list of addon names")
|
|
278
|
+
enabled = set({str(name) for name in enabled})
|
|
279
|
+
|
|
280
|
+
dprint(Verbosity.INFO,
|
|
281
|
+
f"Addons enabled in {self.config_file}: "
|
|
282
|
+
f"{sorted(enabled)}")
|
|
283
|
+
self._enabled_addons = enabled
|
|
284
|
+
return self._enabled_addons
|
|
285
|
+
|
|
286
|
+
def list_addon_files(self):
|
|
287
|
+
"""Return all ``addon.*`` files appended to the Containerfile.
|
|
288
|
+
|
|
289
|
+
The addons bundled with dev-isolator come first, followed by
|
|
290
|
+
any ``addon.*`` files in the ``.devisolator`` directory
|
|
291
|
+
inside the build context (sorted by file name). Duplicates
|
|
292
|
+
are removed, so when the build context *is* the bundled
|
|
293
|
+
directory, every file is only returned once.
|
|
294
|
+
|
|
295
|
+
Only addons whose name (the part after ``addon.`` with the
|
|
296
|
+
``.jinja2`` suffix removed, e.g. ``opencode`` for
|
|
297
|
+
``addon.opencode.jinja2``) is enabled via
|
|
298
|
+
:meth:`enabled_addons` are returned; addons whose name is not
|
|
299
|
+
in the enabled set are skipped with a message.
|
|
300
|
+
|
|
301
|
+
Like :meth:`enabled_addons`, the result is computed once and
|
|
302
|
+
cached for the lifetime of this instance, so the addon
|
|
303
|
+
managing messages are only printed once per build.
|
|
304
|
+
|
|
305
|
+
:returns: List of resolved (absolute) paths to the addon files.
|
|
306
|
+
"""
|
|
307
|
+
if self._addon_files is _UNSET:
|
|
308
|
+
enabled = self.enabled_addons()
|
|
309
|
+
|
|
310
|
+
addons = []
|
|
311
|
+
seen = set()
|
|
312
|
+
for directory in self.addon_search_paths:
|
|
313
|
+
if not directory.is_dir():
|
|
314
|
+
continue
|
|
315
|
+
for addon in sorted(directory.glob("addon.*")):
|
|
316
|
+
if not addon.is_file():
|
|
317
|
+
continue
|
|
318
|
+
name = addon_name(addon)
|
|
319
|
+
if name not in enabled:
|
|
320
|
+
dprint(Verbosity.INFO,
|
|
321
|
+
f"Skipping disabled addon: {addon.name}")
|
|
322
|
+
continue
|
|
323
|
+
resolved = addon.resolve()
|
|
324
|
+
if resolved not in seen:
|
|
325
|
+
seen.add(resolved)
|
|
326
|
+
addons.append(resolved)
|
|
327
|
+
self._addon_files = addons
|
|
328
|
+
return list(self._addon_files)
|
|
329
|
+
|
|
330
|
+
def addon_config_file(self, addon_name: str) -> Path | None:
|
|
331
|
+
"""Return the config file (``config.<addon_name>.yaml``) of
|
|
332
|
+
an addon.
|
|
333
|
+
|
|
334
|
+
The ``.devisolator/config.<addon_name>.yaml`` in the build
|
|
335
|
+
context is used when it exists; otherwise the bundled
|
|
336
|
+
``config.<addon_name>.yaml`` is used. As with the addon file
|
|
337
|
+
lookup, the first found file wins (the search paths are in
|
|
338
|
+
precedence order).
|
|
339
|
+
|
|
340
|
+
:param addon_name: Name of the addon (the part after
|
|
341
|
+
``addon.`` in the addon file name, with the ``.jinja2``
|
|
342
|
+
suffix removed).
|
|
343
|
+
:returns: The resolved (absolute) path of the addon's config
|
|
344
|
+
file, or ``None`` when neither exists.
|
|
345
|
+
"""
|
|
346
|
+
file_name = (f"{ADDON_CONFIG_FILE_PREFIX}{addon_name}"
|
|
347
|
+
f"{ADDON_CONFIG_FILE_SUFFIX}")
|
|
348
|
+
for directory in self.addon_search_paths:
|
|
349
|
+
candidate = directory / file_name
|
|
350
|
+
dprint(Verbosity.TRACE, f"Try addon config file {candidate}")
|
|
351
|
+
resolved = candidate.resolve()
|
|
352
|
+
if resolved.is_file():
|
|
353
|
+
return resolved
|
|
354
|
+
return None
|
|
355
|
+
|
|
356
|
+
def addon_config_script(self, addon_name: str) -> tuple[dict[str, str],
|
|
357
|
+
dict[str, dict]]:
|
|
358
|
+
environment: dict[str, str] = {}
|
|
359
|
+
volumes: dict[str, str] = {}
|
|
360
|
+
file_name = (f"{ADDON_CONFIG_FILE_PREFIX}{addon_name}"
|
|
361
|
+
f".py")
|
|
362
|
+
for directory in self.addon_search_paths:
|
|
363
|
+
candidate = directory / file_name
|
|
364
|
+
dprint(Verbosity.TRACE, f"Try addon script file {candidate}")
|
|
365
|
+
resolved = candidate.resolve()
|
|
366
|
+
if resolved.is_file():
|
|
367
|
+
break
|
|
368
|
+
if not resolved:
|
|
369
|
+
return environment, volumes
|
|
370
|
+
if not resolved.is_file():
|
|
371
|
+
return environment, volumes
|
|
372
|
+
|
|
373
|
+
spec = importlib.util.spec_from_file_location(f"{addon_name}",
|
|
374
|
+
resolved)
|
|
375
|
+
|
|
376
|
+
module = importlib.util.module_from_spec(spec)
|
|
377
|
+
spec.loader.exec_module(module)
|
|
378
|
+
|
|
379
|
+
environment_func = getattr(module, "environment", None)
|
|
380
|
+
if environment_func:
|
|
381
|
+
environment = environment_func()
|
|
382
|
+
volumes_func = getattr(module, "volumes", None)
|
|
383
|
+
if volumes_func:
|
|
384
|
+
volumes = volumes()
|
|
385
|
+
|
|
386
|
+
return environment, volumes
|
|
387
|
+
|
|
388
|
+
def addon_run_settings(self) -> tuple[dict[str, str], dict[str, dict]]:
|
|
389
|
+
"""Return the environment variables and volume mounts
|
|
390
|
+
requested by the enabled addons' config files.
|
|
391
|
+
|
|
392
|
+
Every enabled addon with a ``config.<addon_name>.yaml`` file
|
|
393
|
+
(see :meth:`addon_config_file`) contributes its entries:
|
|
394
|
+
|
|
395
|
+
- ``environment`` entries are either ``NAME``, which is
|
|
396
|
+
taken from the host environment (variables that are not
|
|
397
|
+
set on the host are skipped with a message), or
|
|
398
|
+
``NAME=value``, where ``value`` is used as-is.
|
|
399
|
+
- ``volumes`` holds ``host:container[:mode]`` specs;
|
|
400
|
+
``ENV[VAR]`` references are resolved (a spec referencing an
|
|
401
|
+
unset variable is skipped), then ``~`` and ``${VAR}`` in
|
|
402
|
+
the host path are expanded.
|
|
403
|
+
|
|
404
|
+
:returns: The tuple ``(environment, volumes)`` where
|
|
405
|
+
``environment`` maps variable names to their values
|
|
406
|
+
and ``volumes`` maps expanded host paths to
|
|
407
|
+
``{"bind": container_path, "mode": mode}`` dicts, in the
|
|
408
|
+
shape expected by the podman bindings'
|
|
409
|
+
``containers.create()``.
|
|
410
|
+
:raises RuntimeError: if an addon config file is invalid.
|
|
411
|
+
"""
|
|
412
|
+
environment: dict[str, str] = {}
|
|
413
|
+
volumes: dict[str, dict] = {}
|
|
414
|
+
for addon in self.list_addon_files():
|
|
415
|
+
name = addon_name(addon)
|
|
416
|
+
config_file = self.addon_config_file(name)
|
|
417
|
+
if not config_file:
|
|
418
|
+
continue
|
|
419
|
+
dprint(Verbosity.INFO,
|
|
420
|
+
f"Addon config for {name}: {config_file}")
|
|
421
|
+
try:
|
|
422
|
+
data = yaml.safe_load(config_file.read_text(encoding="utf-8"))
|
|
423
|
+
except Exception as e:
|
|
424
|
+
raise RuntimeError(f"Failed to load addon config {config_file}"
|
|
425
|
+
": {e}") from e
|
|
426
|
+
|
|
427
|
+
script_environment, script_volumes = self.addon_config_script(name)
|
|
428
|
+
if script_environment:
|
|
429
|
+
environment |= script_environment
|
|
430
|
+
if script_volumes:
|
|
431
|
+
volumes |= script_volumes
|
|
432
|
+
|
|
433
|
+
addon_environment = self._get_environment(data)
|
|
434
|
+
addon_volumes = self._get_volumes(data)
|
|
435
|
+
|
|
436
|
+
environment |= addon_environment
|
|
437
|
+
volumes |= addon_volumes
|
|
438
|
+
dprint(Verbosity.TRACE, f"Environment: {str(environment)}")
|
|
439
|
+
dprint(Verbosity.TRACE, f"Volumes: {str(volumes)}")
|
|
440
|
+
|
|
441
|
+
return environment, volumes
|
|
442
|
+
|
|
443
|
+
def config_environment(self) -> dict[str, str]:
|
|
444
|
+
"""Return the environment variables declared in the active
|
|
445
|
+
``config.yaml``.
|
|
446
|
+
|
|
447
|
+
The ``environment`` entries are either ``NAME`` (taken from
|
|
448
|
+
the host) or ``NAME=value`` (used as given); both are
|
|
449
|
+
processed exactly like those of an addon config file
|
|
450
|
+
(see :meth:`_get_environment`).
|
|
451
|
+
|
|
452
|
+
:returns: A dict mapping variable names to their values (the
|
|
453
|
+
environment part only), or ``{}`` when none are declared.
|
|
454
|
+
:raises RuntimeError: if the ``config.yaml`` is invalid.
|
|
455
|
+
"""
|
|
456
|
+
return self._get_environment(self.yaml_data)
|
|
457
|
+
|
|
458
|
+
def config_volumes(self) -> dict[str, dict]:
|
|
459
|
+
"""Return the volume mounts declared in the active
|
|
460
|
+
``config.yaml``.
|
|
461
|
+
|
|
462
|
+
The ``volumes`` entries are ``host:container[:mode]`` specs;
|
|
463
|
+
they are processed exactly like those of an addon config file
|
|
464
|
+
(see :meth:`_get_volumes`).
|
|
465
|
+
|
|
466
|
+
:returns: A dict mapping expanded host paths to
|
|
467
|
+
``{"bind": container_path, "mode": mode}`` dicts (the
|
|
468
|
+
volumes part only), or ``{}`` when none are declared.
|
|
469
|
+
:raises RuntimeError: if the ``config.yaml`` is invalid.
|
|
470
|
+
"""
|
|
471
|
+
return self._get_volumes(self.yaml_data)
|
|
472
|
+
|
|
473
|
+
def run_arguments(self) -> dict:
|
|
474
|
+
"""Return the additional container creation arguments declared
|
|
475
|
+
in the active ``config.yaml``.
|
|
476
|
+
|
|
477
|
+
The ``run_arguments`` key is a mapping of keyword argument
|
|
478
|
+
names of the podman bindings' ``containers.create()`` (see
|
|
479
|
+
https://podman-py.readthedocs.io/en/latest/
|
|
480
|
+
podman.domain.containers_create.html) to their values; only
|
|
481
|
+
the most common arguments are supported (see
|
|
482
|
+
:data:`SUPPORTED_RUN_ARGUMENTS`).
|
|
483
|
+
|
|
484
|
+
:returns: A dict mapping ``containers.create()`` keyword
|
|
485
|
+
argument names to their values, or ``{}`` when none are
|
|
486
|
+
declared.
|
|
487
|
+
:raises RuntimeError: if the ``config.yaml`` is invalid or
|
|
488
|
+
contains an unsupported or reserved argument.
|
|
489
|
+
"""
|
|
490
|
+
arguments = self.yaml_data.get("run_arguments", None)
|
|
491
|
+
if arguments is None:
|
|
492
|
+
return {}
|
|
493
|
+
if not isinstance(arguments, dict):
|
|
494
|
+
raise RuntimeError(f"Invalid config file {self.config_file}: "
|
|
495
|
+
"'run_arguments' must be a mapping of "
|
|
496
|
+
"containers.create() arguments to values")
|
|
497
|
+
for key, value in arguments.items():
|
|
498
|
+
if not isinstance(key, str):
|
|
499
|
+
raise RuntimeError(
|
|
500
|
+
f"Invalid config file {self.config_file}: "
|
|
501
|
+
f"'run_arguments' key '{key}' must be a string")
|
|
502
|
+
if key in RESERVED_RUN_ARGUMENTS:
|
|
503
|
+
raise RuntimeError(
|
|
504
|
+
f"Invalid config file {self.config_file}: "
|
|
505
|
+
f"'run_arguments' key '{key}' is managed by "
|
|
506
|
+
"dev-isolator and cannot be overridden")
|
|
507
|
+
if key not in SUPPORTED_RUN_ARGUMENTS:
|
|
508
|
+
raise RuntimeError(
|
|
509
|
+
f"Invalid config file {self.config_file}: "
|
|
510
|
+
f"'run_arguments' key '{key}' is not supported "
|
|
511
|
+
"(see SUPPORTED_RUN_ARGUMENTS in "
|
|
512
|
+
"dev_isolator/config.py)")
|
|
513
|
+
dprint(Verbosity.TRACE, f"Run argument {key}: {value}")
|
|
514
|
+
|
|
515
|
+
if "userns_mode" not in arguments:
|
|
516
|
+
arguments["userns_mode"] = "keep-id"
|
|
517
|
+
if "network_mode" not in arguments:
|
|
518
|
+
arguments["network_mode"] = "bridge"
|
|
519
|
+
return dict(arguments)
|
|
520
|
+
|
|
521
|
+
def config_targets(self) -> dict[str, str | list[str]]:
|
|
522
|
+
"""Return the predefined target commands declared in the
|
|
523
|
+
active ``config.yaml``.
|
|
524
|
+
|
|
525
|
+
The ``targets`` key is a mapping of target names to commands;
|
|
526
|
+
a command is a jinja2 template string (rendered as a whole
|
|
527
|
+
command line) or a list of jinja2 template strings (every
|
|
528
|
+
entry one line of a script, executed line by line). The extra
|
|
529
|
+
arguments given on the command line
|
|
530
|
+
(``dev-isolator target <name> [args...]``) are available in
|
|
531
|
+
the templates as ``args`` (the list of the extra arguments)
|
|
532
|
+
and ``all_args`` (all extra arguments joined with spaces); the
|
|
533
|
+
``optional`` filter marks an argument that may be omitted (see
|
|
534
|
+
the ``target`` subcommand in :mod:`dev_isolator.main`).
|
|
535
|
+
|
|
536
|
+
:returns: A dict mapping target names to their command
|
|
537
|
+
templates (a template string or a list of template
|
|
538
|
+
strings), or ``{}`` when no targets are declared.
|
|
539
|
+
:raises RuntimeError: if the ``targets`` key is not a mapping
|
|
540
|
+
of non-empty string names to string or string-list
|
|
541
|
+
commands.
|
|
542
|
+
"""
|
|
543
|
+
targets = self.yaml_data.get("targets", None)
|
|
544
|
+
if targets is None:
|
|
545
|
+
return {}
|
|
546
|
+
if not isinstance(targets, dict):
|
|
547
|
+
raise RuntimeError(f"Invalid config file {self.config_file}: "
|
|
548
|
+
"'targets' must be a mapping of target "
|
|
549
|
+
"names to commands")
|
|
550
|
+
result: dict[str, str | list[str]] = {}
|
|
551
|
+
for name, command in targets.items():
|
|
552
|
+
if not isinstance(name, str) or not name:
|
|
553
|
+
raise RuntimeError(
|
|
554
|
+
f"Invalid config file {self.config_file}: "
|
|
555
|
+
f"'targets' key {name!r} must be a non-empty string")
|
|
556
|
+
if isinstance(command, str):
|
|
557
|
+
result[name] = command
|
|
558
|
+
elif (isinstance(command, list)
|
|
559
|
+
and all(isinstance(entry, str) for entry in command)):
|
|
560
|
+
result[name] = list(command)
|
|
561
|
+
else:
|
|
562
|
+
raise RuntimeError(
|
|
563
|
+
f"Invalid config file {self.config_file}: "
|
|
564
|
+
f"'targets' entry '{name}' must be a command string "
|
|
565
|
+
"or a list of command strings")
|
|
566
|
+
return result
|
|
567
|
+
|
|
568
|
+
def build_get_local_context(self):
|
|
569
|
+
build = self.yaml_data.get("build", {})
|
|
570
|
+
|
|
571
|
+
return bool(build.get("local_context", False))
|
|
572
|
+
|
|
573
|
+
def build_get_nocache(self):
|
|
574
|
+
build = self.yaml_data.get("build", {})
|
|
575
|
+
return bool(build.get("nocache", False))
|
|
576
|
+
|
|
577
|
+
#
|
|
578
|
+
# Internal Routines
|
|
579
|
+
#
|
|
580
|
+
def _get_volumes(self, config: dict) -> dict[str, dict]:
|
|
581
|
+
"""Turn the ``volumes`` entries of a config mapping into the
|
|
582
|
+
podman volume-mount dict.
|
|
583
|
+
|
|
584
|
+
The ``volumes`` entries are ``host:container[:mode]`` specs;
|
|
585
|
+
``ENV[VAR]`` references are resolved (a spec referencing an unset
|
|
586
|
+
variable is skipped) and then ``~`` and ``${VAR}`` in the host path
|
|
587
|
+
are expanded. The same processing is used for both the main
|
|
588
|
+
``config.yaml`` and an addon ``config.<addon_name>.yaml``.
|
|
589
|
+
|
|
590
|
+
:param config: A config mapping holding a ``volumes`` key (a list
|
|
591
|
+
of ``host:container[:mode]`` specs).
|
|
592
|
+
:returns: A dict mapping expanded host paths to
|
|
593
|
+
``{"bind": container_path, "mode": mode}`` dicts, in the shape
|
|
594
|
+
expected by the podman bindings' ``containers.create()``.
|
|
595
|
+
"""
|
|
596
|
+
volumes: dict[str, dict] = {}
|
|
597
|
+
|
|
598
|
+
volume_entries = config.get("volumes", [])
|
|
599
|
+
for spec in volume_entries:
|
|
600
|
+
host, container_path, mode = parse_volume_spec(spec)
|
|
601
|
+
host = resolve_env_references(host)
|
|
602
|
+
container_path = resolve_env_references(container_path)
|
|
603
|
+
mode = resolve_env_references(mode)
|
|
604
|
+
if host is None or container_path is None or mode is None:
|
|
605
|
+
dprint(Verbosity.TRACE, f"Skipping {spec} due to missing "
|
|
606
|
+
"environment variables.")
|
|
607
|
+
continue
|
|
608
|
+
host = os.path.expanduser(os.path.expandvars(host))
|
|
609
|
+
container_path = os.path.expanduser(
|
|
610
|
+
os.path.expandvars(container_path))
|
|
611
|
+
host_path = Path(host)
|
|
612
|
+
if host_path.exists():
|
|
613
|
+
volumes[host] = {"bind": container_path, "mode": mode}
|
|
614
|
+
else:
|
|
615
|
+
dprint(Verbosity.DEBUG, f"Skipping non exitsing volume {host}")
|
|
616
|
+
return volumes
|
|
617
|
+
|
|
618
|
+
def _get_environment(self, config: dict) -> dict[str, str]:
|
|
619
|
+
"""Turn the ``environment`` entries of a config mapping into the
|
|
620
|
+
podman environment dict.
|
|
621
|
+
|
|
622
|
+
The ``environment`` entries are either ``NAME``, which is taken
|
|
623
|
+
from the host environment (variables that are not set on the host
|
|
624
|
+
are skipped with a message), or ``NAME=value``, where ``value`` is
|
|
625
|
+
used as-is. The same processing is used for both the main
|
|
626
|
+
``config.yaml`` and an addon ``config.<addon_name>.yaml``.
|
|
627
|
+
|
|
628
|
+
:param config: A config mapping holding an ``environment`` key (a
|
|
629
|
+
list of ``NAME`` or ``NAME=value`` entries).
|
|
630
|
+
:returns: A dict mapping variable names to their values.
|
|
631
|
+
"""
|
|
632
|
+
environment: dict[str, str] = {}
|
|
633
|
+
|
|
634
|
+
environment_entries = config.get("environment", [])
|
|
635
|
+
for entry in environment_entries:
|
|
636
|
+
name, sep, value = entry.partition("=")
|
|
637
|
+
if name and not sep:
|
|
638
|
+
# Only a name: copy the variable from the host environment.
|
|
639
|
+
value = os.environ.get(name)
|
|
640
|
+
if value is None:
|
|
641
|
+
dprint(Verbosity.TRACE,
|
|
642
|
+
f"Environment variable {name} is not set; skipping")
|
|
643
|
+
continue
|
|
644
|
+
elif not name:
|
|
645
|
+
dprint(Verbosity.TRACE,
|
|
646
|
+
f"Invalid environment entry '{entry}'; skipping")
|
|
647
|
+
continue
|
|
648
|
+
environment[name] = value
|
|
649
|
+
|
|
650
|
+
return environment
|