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
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
"""Manage container definitions (build/create) for dev-isolator.
|
|
2
|
+
|
|
3
|
+
Copyright (C) 2026 Martin Köhler
|
|
4
|
+
|
|
5
|
+
This program comes with ABSOLUTELY NO WARRANTY.
|
|
6
|
+
This is free software, and you are welcome to redistribute it
|
|
7
|
+
under certain conditions; see LICENSE for details.
|
|
8
|
+
SPDX-License-Identifier: GPL-3.0-or-later
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import random
|
|
13
|
+
import re
|
|
14
|
+
import string
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
import podman.errors
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from .utils import dprint, Verbosity
|
|
21
|
+
from .constants import (IMAGE_PREFIX,
|
|
22
|
+
CONTAINER_NAME_SUFFIX_LENGTH,
|
|
23
|
+
BUNDLE_DIR)
|
|
24
|
+
from .container_image import ContainerImage
|
|
25
|
+
from .waitspinner import WaitSpinner
|
|
26
|
+
|
|
27
|
+
def slugify_path(path: str | os.PathLike) -> str:
|
|
28
|
+
"""Return a slug (e.g. ``my-project``) suitable
|
|
29
|
+
for a container name/tag.
|
|
30
|
+
|
|
31
|
+
Replaces every character outside ``[a-zA-Z0-9]`` with ``-``,
|
|
32
|
+
collapses runs of such characters, strips leading/trailing ``-``
|
|
33
|
+
and lowercases the result.
|
|
34
|
+
"""
|
|
35
|
+
text = str(path)
|
|
36
|
+
return re.sub(r"[^a-zA-Z0-9]+", "-", text).strip("-").lower()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ContainerDefintion:
|
|
40
|
+
"""Define, build and run the dev-isolator container for a project.
|
|
41
|
+
|
|
42
|
+
By default the ``Containerfile`` and build context shipped with
|
|
43
|
+
dev-isolator are used; both can be overridden through the
|
|
44
|
+
constructor. The image name and container name are derived from
|
|
45
|
+
the slug of the current working directory (see
|
|
46
|
+
:func:`slugify_path`).
|
|
47
|
+
|
|
48
|
+
When the base image is built (see
|
|
49
|
+
:class:`dev_isolator.base_image.BaseImage`), every
|
|
50
|
+
``addon.<name>.jinja2`` file whose name is enabled in a
|
|
51
|
+
``config.yaml`` file is rendered as a jinja2 template and appended
|
|
52
|
+
to the base image's Containerfile. The addon templates receive the
|
|
53
|
+
same variables as the host user template (see
|
|
54
|
+
:func:`dev_isolator.base_image.render_template`). Only the first
|
|
55
|
+
found ``config.yaml`` is used: the ``.devisolator/config.yaml`` in
|
|
56
|
+
the build context when it exists, otherwise the one bundled with
|
|
57
|
+
dev-isolator. Without any ``config.yaml``, every ``addon.*`` file
|
|
58
|
+
is appended.
|
|
59
|
+
|
|
60
|
+
When a container is run, the environment variables and volume
|
|
61
|
+
mounts declared directly in the active ``config.yaml`` and, in
|
|
62
|
+
addition, those each enabled addon requests through a
|
|
63
|
+
``config.<addon_name>.yaml`` file (see
|
|
64
|
+
:class:`dev_isolator.config.Configuration`) are passed
|
|
65
|
+
to the container when it is created (see
|
|
66
|
+
:meth:`run_container`). Settings from ``config.yaml`` are applied
|
|
67
|
+
first, addon settings override them and the ``/workspace`` mount of
|
|
68
|
+
the current directory always takes precedence.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, context_dir, container_file, config, tag=None):
|
|
72
|
+
"""Set up the container definition.
|
|
73
|
+
|
|
74
|
+
:param container_file: Path to the custom Containerfile to
|
|
75
|
+
build and run.
|
|
76
|
+
:param context_dir: Path to the build context directory; the
|
|
77
|
+
temporary merged Containerfile is written here during the
|
|
78
|
+
build.
|
|
79
|
+
:param config: The project's
|
|
80
|
+
:class:`dev_isolator.config.Configuration` determining
|
|
81
|
+
the enabled addons.
|
|
82
|
+
:param tag: Tag variant of the image to build, so one project
|
|
83
|
+
can have several configurations in parallel. Defaults to
|
|
84
|
+
``"default"``.
|
|
85
|
+
:raises FileNotFoundError: if the resolved Containerfile does
|
|
86
|
+
not exist or the referenced base image has no matching
|
|
87
|
+
base Containerfile.
|
|
88
|
+
:raises RuntimeError: if the Containerfile's ``FROM``
|
|
89
|
+
instruction does not identify a dev-isolator base image or
|
|
90
|
+
a podman build fails (see :class:`ContainerImage`).
|
|
91
|
+
"""
|
|
92
|
+
self.context_dir = Path(context_dir)
|
|
93
|
+
self.container_file = Path(container_file)
|
|
94
|
+
self.config = config
|
|
95
|
+
if tag:
|
|
96
|
+
self.tag = tag
|
|
97
|
+
else:
|
|
98
|
+
self.tag = "default"
|
|
99
|
+
|
|
100
|
+
self.bundled_dir = BUNDLE_DIR
|
|
101
|
+
|
|
102
|
+
dprint(Verbosity.DEBUG, f"Containerfile: {self.container_file}")
|
|
103
|
+
dprint(Verbosity.DEBUG, f"Context dir: {self.context_dir}")
|
|
104
|
+
dprint(Verbosity.DEBUG, f"Bundle dir: {self.bundled_dir}")
|
|
105
|
+
|
|
106
|
+
self.container_file_obj = ContainerImage(self.context_dir,
|
|
107
|
+
self.container_file,
|
|
108
|
+
self.config,
|
|
109
|
+
self.image_name())
|
|
110
|
+
|
|
111
|
+
def build_container(self, keep_container_file=False):
|
|
112
|
+
"""Build the image defined by this container definition.
|
|
113
|
+
|
|
114
|
+
The merged Containerfile is written as a temporary file
|
|
115
|
+
directly into the build context, so podman-py does not copy it
|
|
116
|
+
itself (its copy, ``.containerfile.<random>``, would be left
|
|
117
|
+
behind as an artifact in the build context). The temporary
|
|
118
|
+
file is removed again after the build.
|
|
119
|
+
|
|
120
|
+
If an image with the same tag (see :meth:`image_name`) existed
|
|
121
|
+
before, it is removed after the build - but only when the
|
|
122
|
+
build replaced it, i.e. its image id changed - so no old image
|
|
123
|
+
is left as a dangling artifact in podman.
|
|
124
|
+
|
|
125
|
+
:raises RuntimeError: if the podman build fails or the
|
|
126
|
+
superseded image cannot be removed.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
image = self.container_file_obj.build(
|
|
130
|
+
keep_container_file=keep_container_file)
|
|
131
|
+
return image
|
|
132
|
+
|
|
133
|
+
def run_container(self, interactive_shell: str = "bash",
|
|
134
|
+
command: list[str] | None = None,
|
|
135
|
+
extra_environment: dict[str, str] | None = None) -> int:
|
|
136
|
+
"""Open an interactive terminal/shell inside the container.
|
|
137
|
+
|
|
138
|
+
Builds the image (see :meth:`build_container`), creates a
|
|
139
|
+
container from it, ensures it is running and then attaches the
|
|
140
|
+
local terminal to a command inside the container. The container
|
|
141
|
+
is stopped again after the session ends (unless it is already
|
|
142
|
+
gone).
|
|
143
|
+
|
|
144
|
+
:param interactive_shell: Shell to start inside the container.
|
|
145
|
+
Ignored when ``command`` is given.
|
|
146
|
+
:param command: Optional command to run inside the container
|
|
147
|
+
instead of the interactive shell, for example
|
|
148
|
+
``["opencode", "--port", "4096"]``.
|
|
149
|
+
:returns: The exit code of the session.
|
|
150
|
+
:raises RuntimeError: if the container does not reach the
|
|
151
|
+
``running`` state.
|
|
152
|
+
|
|
153
|
+
The container gets a unique name (see :meth:`container_name`),
|
|
154
|
+
so several containers can run in parallel. The interactive
|
|
155
|
+
session itself is attached via the local
|
|
156
|
+
``podman exec -it`` CLI, because the podman Python bindings
|
|
157
|
+
cannot bridge stdin/TTY to the podman service (their
|
|
158
|
+
``attach``/``attach_socket``/``exec_run(socket=True)`` are not
|
|
159
|
+
implemented).
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
self.build_container()
|
|
163
|
+
|
|
164
|
+
with podman.PodmanClient() as client:
|
|
165
|
+
image = client.images.get(self.image_name())
|
|
166
|
+
|
|
167
|
+
environment: dict[str, str] = {}
|
|
168
|
+
volumes: dict[str, dict] = {}
|
|
169
|
+
|
|
170
|
+
# Settings declared directly in the project's config.yaml.
|
|
171
|
+
config_environment = self.config.config_environment()
|
|
172
|
+
config_volumes = self.config.config_volumes()
|
|
173
|
+
environment |= config_environment
|
|
174
|
+
volumes |= config_volumes
|
|
175
|
+
|
|
176
|
+
# Additional containers.create() arguments declared
|
|
177
|
+
# directly in the project's config.yaml.
|
|
178
|
+
run_arguments = self.config.run_arguments()
|
|
179
|
+
|
|
180
|
+
# Settings requested by the enabled addons.
|
|
181
|
+
addon_environment, addon_volumes = self.config.addon_run_settings()
|
|
182
|
+
environment |= addon_environment
|
|
183
|
+
volumes |= addon_volumes
|
|
184
|
+
|
|
185
|
+
# Add teh extra environment
|
|
186
|
+
if extra_environment:
|
|
187
|
+
environment |= extra_environment
|
|
188
|
+
|
|
189
|
+
# Bind the workspace last, so it always takes precedence.
|
|
190
|
+
volumes[os.getcwd()] = {"bind": "/workspace", "mode": "rw"}
|
|
191
|
+
|
|
192
|
+
dprint(Verbosity.INFO,
|
|
193
|
+
f"Passing environment variables "
|
|
194
|
+
f"{sorted(environment)} to the container")
|
|
195
|
+
dprint(Verbosity.INFO,
|
|
196
|
+
f"Mounting volumes {sorted(volumes)} "
|
|
197
|
+
"into the container")
|
|
198
|
+
|
|
199
|
+
# A unique name lets several containers of the same
|
|
200
|
+
# project run in parallel.
|
|
201
|
+
container_name = self.container_name()
|
|
202
|
+
|
|
203
|
+
with WaitSpinner("Creating the container"):
|
|
204
|
+
container = client.containers.create(
|
|
205
|
+
image,
|
|
206
|
+
name=container_name,
|
|
207
|
+
# The image's entrypoint may exit immediately; keep
|
|
208
|
+
# the container alive so shells can exec into it.
|
|
209
|
+
entrypoint=["sleep", "infinity"],
|
|
210
|
+
environment=environment,
|
|
211
|
+
volumes=volumes,
|
|
212
|
+
detach=True,
|
|
213
|
+
**run_arguments,
|
|
214
|
+
)
|
|
215
|
+
dprint(Verbosity.INFO,
|
|
216
|
+
f"Created container {container_name} "
|
|
217
|
+
f"from {self.image_name()}")
|
|
218
|
+
|
|
219
|
+
container.reload()
|
|
220
|
+
if container.status in ("created", "exited", "stopped"):
|
|
221
|
+
container.start()
|
|
222
|
+
dprint(Verbosity.INFO,
|
|
223
|
+
f"Started container {container_name}")
|
|
224
|
+
# Wait until the container is actually running before
|
|
225
|
+
# attaching, otherwise podman exec may hit it too early.
|
|
226
|
+
for _ in range(100):
|
|
227
|
+
container.reload()
|
|
228
|
+
if container.status == "running":
|
|
229
|
+
break
|
|
230
|
+
time.sleep(0.1)
|
|
231
|
+
else:
|
|
232
|
+
container.kill(9)
|
|
233
|
+
container.remove()
|
|
234
|
+
raise RuntimeError(
|
|
235
|
+
f"Container {container_name} did not reach "
|
|
236
|
+
f"'running' state (status: {container.status})")
|
|
237
|
+
|
|
238
|
+
if command is None:
|
|
239
|
+
exec_argv = [interactive_shell]
|
|
240
|
+
else:
|
|
241
|
+
exec_argv = list(command)
|
|
242
|
+
exec_cmd = [
|
|
243
|
+
"podman", "exec", "-it",
|
|
244
|
+
"--detach-keys", "",
|
|
245
|
+
"-e", f"TERM={os.environ.get('TERM', 'xterm')}",
|
|
246
|
+
container_name,
|
|
247
|
+
*exec_argv,
|
|
248
|
+
]
|
|
249
|
+
session_command = " ".join(exec_argv)
|
|
250
|
+
dprint(Verbosity.INFO,
|
|
251
|
+
f"Opening terminal in {container_name} "
|
|
252
|
+
f"({session_command}; detach with Ctrl-D or 'exit')")
|
|
253
|
+
exit_code = subprocess.call(exec_cmd)
|
|
254
|
+
dprint(Verbosity.INFO,
|
|
255
|
+
f"Session in {container_name} exited "
|
|
256
|
+
f"(exit code: {exit_code})")
|
|
257
|
+
|
|
258
|
+
# Shut the container down after the terminal session ends.
|
|
259
|
+
try:
|
|
260
|
+
container.stop(timeout=0)
|
|
261
|
+
dprint(Verbosity.INFO,
|
|
262
|
+
f"Stopped container {container_name}")
|
|
263
|
+
container.remove()
|
|
264
|
+
dprint(Verbosity.INFO,
|
|
265
|
+
f"Removed container {container_name}")
|
|
266
|
+
except podman.errors.NotFound:
|
|
267
|
+
# Container was removed elsewhere; nothing to shut down.
|
|
268
|
+
dprint(Verbosity.INFO,
|
|
269
|
+
f"Container {container_name} is already gone")
|
|
270
|
+
except podman.errors.APIError as e:
|
|
271
|
+
dprint(Verbosity.INFO,
|
|
272
|
+
f"Warning: could not stop container "
|
|
273
|
+
f"{container_name}: {e}", file=sys.stderr)
|
|
274
|
+
return exit_code
|
|
275
|
+
|
|
276
|
+
def clean_image(self):
|
|
277
|
+
"""Remove the image built for this container definition.
|
|
278
|
+
|
|
279
|
+
Stops (eventually killing) all containers of this container
|
|
280
|
+
definition (by name and by image) and removes them before the
|
|
281
|
+
image is removed; containers are also cleaned when the image
|
|
282
|
+
does not exist anymore.
|
|
283
|
+
|
|
284
|
+
When the global verbosity (see :func:`utils.set_verbosity`)
|
|
285
|
+
is at least ``Verbosity.INFO`` (for example ``--verbose``),
|
|
286
|
+
the removed containers and image are printed to stdout.
|
|
287
|
+
:raises RuntimeError: if podman refuses to remove the image.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
with podman.PodmanClient() as client:
|
|
291
|
+
try:
|
|
292
|
+
image = client.images.get(self.image_name())
|
|
293
|
+
except (podman.errors.NotFound, podman.errors.ImageNotFound):
|
|
294
|
+
dprint(Verbosity.INFO, "Image "
|
|
295
|
+
f"{self.image_name()} not found; nothing to clean")
|
|
296
|
+
image = None
|
|
297
|
+
if image is None:
|
|
298
|
+
self._clean_containers(
|
|
299
|
+
client, [(self.container_name_prefix(), "-")])
|
|
300
|
+
return
|
|
301
|
+
self._clean_images(client, [image],
|
|
302
|
+
[(self.container_name_prefix(), "-")])
|
|
303
|
+
|
|
304
|
+
def clean_local_images(self):
|
|
305
|
+
"""Remove all dev-isolator images of the current project.
|
|
306
|
+
|
|
307
|
+
Stops (eventually killing) all containers derived from any
|
|
308
|
+
dev-isolator image of the current project — matching by name
|
|
309
|
+
or by image — and removes them before the images are removed.
|
|
310
|
+
|
|
311
|
+
When the global verbosity (see :func:`utils.set_verbosity`)
|
|
312
|
+
is at least ``Verbosity.INFO`` (for example ``--verbose``),
|
|
313
|
+
the removed containers and images are printed to stdout.
|
|
314
|
+
:raises RuntimeError: if podman refuses to remove the images.
|
|
315
|
+
"""
|
|
316
|
+
|
|
317
|
+
name_matchers = [(self.project_container_name_prefix(), "--")]
|
|
318
|
+
with podman.PodmanClient() as client:
|
|
319
|
+
images = [image for image in client.images.list()
|
|
320
|
+
if self._is_devisolator_local_image(image)]
|
|
321
|
+
if not images:
|
|
322
|
+
dprint(Verbosity.INFO,
|
|
323
|
+
f"No {IMAGE_PREFIX} images found; nothing to clean")
|
|
324
|
+
self._clean_containers(client, name_matchers)
|
|
325
|
+
return
|
|
326
|
+
self._clean_images(client, images, name_matchers)
|
|
327
|
+
|
|
328
|
+
def clean_all_images(self):
|
|
329
|
+
"""Remove all dev-isolator images.
|
|
330
|
+
|
|
331
|
+
Stops (eventually killing) all containers derived from any
|
|
332
|
+
dev-isolator image — matching by name or by image — and
|
|
333
|
+
removes them before the images are removed.
|
|
334
|
+
|
|
335
|
+
When the global verbosity (see :func:`utils.set_verbosity`)
|
|
336
|
+
is at least ``Verbosity.INFO`` (for example ``--verbose``),
|
|
337
|
+
the removed containers and images are printed to stdout.
|
|
338
|
+
:raises RuntimeError: if podman refuses to remove the images.
|
|
339
|
+
"""
|
|
340
|
+
|
|
341
|
+
name_matchers = [(IMAGE_PREFIX, "-")]
|
|
342
|
+
with podman.PodmanClient() as client:
|
|
343
|
+
images = [image for image in client.images.list()
|
|
344
|
+
if self._is_devisolator_image(image)]
|
|
345
|
+
if not images:
|
|
346
|
+
dprint(Verbosity.INFO,
|
|
347
|
+
f"No {IMAGE_PREFIX} images found; nothing to clean")
|
|
348
|
+
self._clean_containers(client, name_matchers)
|
|
349
|
+
return
|
|
350
|
+
self._clean_images(client, images, name_matchers)
|
|
351
|
+
|
|
352
|
+
@staticmethod
|
|
353
|
+
def _is_devisolator_image(image) -> bool:
|
|
354
|
+
"""Return whether ``image`` is tagged as a dev-isolator image.
|
|
355
|
+
|
|
356
|
+
A image counts as dev-isolator image, when one of its tags
|
|
357
|
+
names the ``IMAGE_PREFIX`` repository (the tag with the
|
|
358
|
+
slug), for example ``dev-isolator:my-project``.
|
|
359
|
+
"""
|
|
360
|
+
return any(
|
|
361
|
+
tag.partition("@")[0].rsplit("/", 1)[-1].rsplit(":", 1)[0]
|
|
362
|
+
== IMAGE_PREFIX
|
|
363
|
+
for tag in image.tags or [])
|
|
364
|
+
|
|
365
|
+
@staticmethod
|
|
366
|
+
def _is_devisolator_local_image(image) -> bool:
|
|
367
|
+
"""Return whether ``image`` is a dev-isolator image of the
|
|
368
|
+
current project.
|
|
369
|
+
|
|
370
|
+
Like :meth:`_is_devisolator_image`, but limited to the current
|
|
371
|
+
working directory: an image counts when one of its tags names
|
|
372
|
+
the ``dev-isolator:<slug>`` repository of the current path,
|
|
373
|
+
for example ``dev-isolator:my-project``
|
|
374
|
+
or ``dev-isolator:my-project--default`` (optionally prefixed by
|
|
375
|
+
a registry). A different project whose
|
|
376
|
+
slug only shares a prefix (e.g. ``my-project-2``) does not
|
|
377
|
+
match.
|
|
378
|
+
"""
|
|
379
|
+
prefix = f"{IMAGE_PREFIX}:{ContainerDefintion.current_path_slug()}"
|
|
380
|
+
return any(
|
|
381
|
+
repo_tag == prefix or repo_tag.startswith(prefix + "--")
|
|
382
|
+
for repo_tag in (
|
|
383
|
+
tag.partition("@")[0].rsplit("/", 1)[-1]
|
|
384
|
+
for tag in image.tags or [])
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
@staticmethod
|
|
388
|
+
def _clean_images(client, images, name_matchers=()):
|
|
389
|
+
"""Stop, kill and remove the containers based on ``images``
|
|
390
|
+
or named after ``name_matchers`` and remove the images
|
|
391
|
+
afterwards.
|
|
392
|
+
|
|
393
|
+
:param client: Connected :class:`podman.PodmanClient`.
|
|
394
|
+
:param images: Images to remove.
|
|
395
|
+
:param name_matchers: ``(base, separator)`` pairs describing
|
|
396
|
+
container name prefixes whose containers are removed
|
|
397
|
+
additionally (for example containers left over from a
|
|
398
|
+
previously built image).
|
|
399
|
+
:raises RuntimeError: if podman refuses to remove an image.
|
|
400
|
+
"""
|
|
401
|
+
image_ids = {image.id for image in images}
|
|
402
|
+
ContainerDefintion._clean_containers(client, name_matchers,
|
|
403
|
+
image_ids)
|
|
404
|
+
|
|
405
|
+
for image in images:
|
|
406
|
+
shown_name = ", ".join(image.tags) if image.tags else image.id
|
|
407
|
+
try:
|
|
408
|
+
client.images.remove(image.id, force=True)
|
|
409
|
+
dprint(Verbosity.INFO, f"Removed image {shown_name}")
|
|
410
|
+
except podman.errors.APIError as e:
|
|
411
|
+
raise RuntimeError(
|
|
412
|
+
f"Failed to remove image {shown_name}: {e}") from e
|
|
413
|
+
|
|
414
|
+
@staticmethod
|
|
415
|
+
def _clean_containers(client, name_matchers, image_ids=frozenset()):
|
|
416
|
+
"""Stop, kill and remove all containers matching the criteria.
|
|
417
|
+
|
|
418
|
+
A container matches when its name equals one of the
|
|
419
|
+
``name_matcher`` bases or starts with a base followed by its
|
|
420
|
+
separator — ``name_matchers`` is a list of
|
|
421
|
+
``(base, separator)`` pairs — or when it was created from one
|
|
422
|
+
of the ``image_ids``.
|
|
423
|
+
|
|
424
|
+
Running containers are stopped (with a grace period); when
|
|
425
|
+
stopping fails, they are killed. Afterwards they are removed.
|
|
426
|
+
|
|
427
|
+
:param client: Connected :class:`podman.PodmanClient`.
|
|
428
|
+
:param name_matchers: ``(base, separator)`` pairs matching
|
|
429
|
+
container names.
|
|
430
|
+
:param image_ids: Ids of images whose containers are removed.
|
|
431
|
+
"""
|
|
432
|
+
image_ids = frozenset(image_ids)
|
|
433
|
+
|
|
434
|
+
def matches(container) -> bool:
|
|
435
|
+
"""Return whether a container is removed by this cleanup:
|
|
436
|
+
by name or by originating from one of ``image_ids``."""
|
|
437
|
+
name = container.name or ""
|
|
438
|
+
if any(name == base or name.startswith(base + separator)
|
|
439
|
+
for base, separator in name_matchers):
|
|
440
|
+
return True
|
|
441
|
+
# The container report keys "ImageID" and "Image" name
|
|
442
|
+
# the image the container was created from.
|
|
443
|
+
container_image_id = container.attrs.get("ImageID") \
|
|
444
|
+
or container.attrs.get("Image")
|
|
445
|
+
return (container_image_id is not None
|
|
446
|
+
and container_image_id in image_ids)
|
|
447
|
+
|
|
448
|
+
for container in client.containers.list(all=True):
|
|
449
|
+
name = container.name or container.id
|
|
450
|
+
if not matches(container):
|
|
451
|
+
continue
|
|
452
|
+
try:
|
|
453
|
+
container.reload()
|
|
454
|
+
if container.status == "running":
|
|
455
|
+
try:
|
|
456
|
+
container.stop(timeout=10)
|
|
457
|
+
dprint(Verbosity.INFO, f"Stopped container {name}")
|
|
458
|
+
except podman.errors.APIError:
|
|
459
|
+
# Fall back to killing the container.
|
|
460
|
+
container.kill()
|
|
461
|
+
dprint(Verbosity.INFO, f"Killed container {name}")
|
|
462
|
+
container.remove()
|
|
463
|
+
dprint(Verbosity.INFO, f"Removed container {name}")
|
|
464
|
+
except podman.errors.NotFound:
|
|
465
|
+
dprint(Verbosity.INFO, f"Container {name} is already gone")
|
|
466
|
+
except podman.errors.APIError as e:
|
|
467
|
+
print(f"Warning: could not remove container "
|
|
468
|
+
f"{name}: {e}", file=sys.stderr)
|
|
469
|
+
|
|
470
|
+
def image_name(self) -> str:
|
|
471
|
+
"""Return the image name
|
|
472
|
+
``dev-isolator:<slug_of_the_current_path>--<tag>``."""
|
|
473
|
+
return f"{IMAGE_PREFIX}:{self.current_path_slug()}--{self.tag}"
|
|
474
|
+
|
|
475
|
+
def project_container_name_prefix(self) -> str:
|
|
476
|
+
"""Return the container name prefix shared by every tag
|
|
477
|
+
variant of the current project
|
|
478
|
+
``dev-isolator-<slug_of_the_current_path>``.
|
|
479
|
+
|
|
480
|
+
Used by ``clean --local`` to find the containers of all tag
|
|
481
|
+
variants of the project (see :meth:`clean_local_images`).
|
|
482
|
+
"""
|
|
483
|
+
return f"{IMAGE_PREFIX}-{self.current_path_slug()}"
|
|
484
|
+
|
|
485
|
+
def container_name_prefix(self) -> str:
|
|
486
|
+
"""Return the container name prefix shared by all containers
|
|
487
|
+
of this container definition
|
|
488
|
+
``dev-isolator-<slug_of_the_current_path>--<tag>``.
|
|
489
|
+
|
|
490
|
+
Podman container names cannot contain ':', so the tag's
|
|
491
|
+
``dev-isolator:slug--tag`` form becomes ``dev-isolator-slug--tag``.
|
|
492
|
+
"""
|
|
493
|
+
return self.image_name().replace(":", "-")
|
|
494
|
+
|
|
495
|
+
def container_name(self) -> str:
|
|
496
|
+
"""Return a unique container name for a new run.
|
|
497
|
+
|
|
498
|
+
The name is the :meth:`container_name_prefix` followed by a
|
|
499
|
+
random suffix of :const:`CONTAINER_NAME_SUFFIX_LENGTH`
|
|
500
|
+
lowercase alphanumeric characters, for example
|
|
501
|
+
``dev-isolator-my-project--default-k3x9q2zf``.
|
|
502
|
+
|
|
503
|
+
The random suffix lets several containers of the same project
|
|
504
|
+
run in parallel without name clashes. Containers matching the
|
|
505
|
+
prefix are removed again by the ``clean`` command (see
|
|
506
|
+
:meth:`clean_image`).
|
|
507
|
+
"""
|
|
508
|
+
alphabet = string.ascii_lowercase + string.digits
|
|
509
|
+
suffix = "".join(random.choices(alphabet,
|
|
510
|
+
k=CONTAINER_NAME_SUFFIX_LENGTH))
|
|
511
|
+
return f"{self.container_name_prefix()}-{suffix}"
|
|
512
|
+
|
|
513
|
+
@staticmethod
|
|
514
|
+
def current_path_slug() -> str:
|
|
515
|
+
"""Return the slug of the current working directory path."""
|
|
516
|
+
return slugify_path(Path.cwd().resolve())
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
FROM ubuntu:26.04
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
#
|
|
5
|
+
# This default Containerfile works on apt, dnf, zypper and pacman
|
|
6
|
+
# based distributions.
|
|
7
|
+
# Consider removing the blocks not matching your desired distribution.
|
|
8
|
+
#
|
|
9
|
+
|
|
10
|
+
# Base packages for Ubuntu/Debian
|
|
11
|
+
RUN if [ -x /usr/bin/apt ]; then \
|
|
12
|
+
apt install --yes build-essential gfortran cmake ninja-build python3-dev python3-pip python3-venv ;\
|
|
13
|
+
fi
|
|
14
|
+
|
|
15
|
+
# Base packages for Fedora/AlmaLinux
|
|
16
|
+
RUN if [ -x /usr/bin/dnf ]; then \
|
|
17
|
+
dnf install -y gcc gcc-gfortran cmake ninja-build python3-devel python3-pip ;\
|
|
18
|
+
fi
|
|
19
|
+
|
|
20
|
+
# Base packages for openSUSE
|
|
21
|
+
RUN if [ -x /usr/bin/zypper ]; then \
|
|
22
|
+
zypper --non-interactive install gcc gcc-fortran cmake ninja make python3 python3-pip ;\
|
|
23
|
+
fi
|
|
24
|
+
|
|
25
|
+
# ArchLinux based
|
|
26
|
+
RUN if [ -x /usr/sbin/pacman ]; then \
|
|
27
|
+
pacman -Sy --noconfirm gcc gcc-fortran cmake ninja make python python-pip ; \
|
|
28
|
+
fi
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
USER root
|
|
2
|
+
RUN if [ -x /usr/bin/apt ]; then \
|
|
3
|
+
apt update && apt install --yes curl ; \
|
|
4
|
+
elif [ -x /usr/bin/dnf ]; then \
|
|
5
|
+
dnf install -y curl ; \
|
|
6
|
+
elif [ -x /usr/sbin/pacman ]; then \
|
|
7
|
+
pacman -Sy --noconfirm curl ; \
|
|
8
|
+
elif [ -x /usr/bin/zypper ]; then \
|
|
9
|
+
zypper --non-interactive install curl ; \
|
|
10
|
+
else \
|
|
11
|
+
exit 1; \
|
|
12
|
+
fi
|
|
13
|
+
USER {{ username }}
|
|
14
|
+
RUN curl -fsSL https://claude.ai/install.sh | bash
|
|
15
|
+
USER root
|
|
16
|
+
ENV PATH="{{ home_dir }}/.local/bin:${PATH}"
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
USER root
|
|
2
|
+
RUN if [ -x /usr/bin/apt ]; then \
|
|
3
|
+
apt update && apt install --yes curl ca-certificates git gnupg jq ; \
|
|
4
|
+
elif [ -x /usr/bin/dnf ]; then \
|
|
5
|
+
dnf install -y curl git jq gnupg; \
|
|
6
|
+
elif [ -x /usr/sbin/pacman ]; then \
|
|
7
|
+
pacman -Sy --noconfirm curl git jq gnupg ; \
|
|
8
|
+
elif [ -x /usr/bin/zypper ]; then \
|
|
9
|
+
zypper --non-interactive install curl ca-certificates git gnupg jq ; \
|
|
10
|
+
else \
|
|
11
|
+
exit 1; \
|
|
12
|
+
fi
|
|
13
|
+
USER {{ username }}
|
|
14
|
+
RUN curl -fsSL https://opencode.ai/v2/install | bash
|
|
15
|
+
USER root
|
|
16
|
+
ENV PATH="{{ home_dir }}/.opencode/bin:${PATH}"
|