hegemony-steps-container 0.46.1__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.
@@ -0,0 +1,35 @@
1
+ # SPDX-FileCopyrightText: 2025-2026 Rexonix s.r.o.
2
+ # SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
3
+ #
4
+ # SPDX-License-Identifier: AGPL-3.0-or-later
5
+
6
+ """Docker container execution step handlers for Hegemony.
7
+
8
+ Container execution on the platform's Docker-in-Docker sandbox, never on the
9
+ worker's own Docker daemon: ``container.run`` runs a container, and
10
+ ``container.build`` builds an image there and pushes it to the platform
11
+ registry. Deliberately its own wheel: the security-sensitive handlers (docker
12
+ socket, privileged mode) — hardened deployments simply don't install it.
13
+
14
+ Registers under the ``hegemony.step_handlers`` entry-point group; the entry
15
+ point name is the claimed handler-id namespace prefix (``container``).
16
+ Handlers reach every platform facility through ``ctx.services``.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from hegemony_step_sdk import BaseHandler, StepHandlerRegistry
22
+
23
+ from .build import BuildImageHandler
24
+ from .run import RunContainerHandler
25
+
26
+ ALL_HANDLERS: tuple[type[BaseHandler], ...] = (RunContainerHandler, BuildImageHandler)
27
+
28
+
29
+ def register(registry: StepHandlerRegistry) -> None:
30
+ """Entry point: register this wheel's handlers with the host registry."""
31
+ for handler_class in ALL_HANDLERS:
32
+ registry.register_handler_type(handler_class)
33
+
34
+
35
+ __all__ = ["ALL_HANDLERS", "register", *sorted(cls.__name__ for cls in ALL_HANDLERS)]
@@ -0,0 +1,326 @@
1
+ # SPDX-FileCopyrightText: 2026 Rexonix s.r.o.
2
+ # SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
3
+ #
4
+ # SPDX-License-Identifier: AGPL-3.0-or-later
5
+
6
+ """The images a Dockerfile builds on, as BuildKit will resolve them.
7
+
8
+ ``container.build`` serves them from the platform registry's cache: BuildKit
9
+ replaces an image reference used in ``FROM``, ``COPY --from`` or
10
+ ``RUN --mount=from=`` with a named build context of the same name
11
+ (``--build-context alpine:3.20=docker-image://<copy>@sha256:...``). Names
12
+ are compared in Docker's familiar form (:func:`familiar_name`), so
13
+ ``alpine``, ``alpine:latest`` and ``docker.io/library/alpine`` are one name,
14
+ and a context whose name is a stage's name replaces that whole stage.
15
+
16
+ What is returned is only what the build of the step's target stage uses and
17
+ the cache can serve as one context for every platform:
18
+
19
+ - the stages the target depends on (``FROM <stage>``, ``COPY --from`` with a
20
+ stage name or index, ``RUN --mount=from=``), the last stage without a
21
+ target: BuildKit builds no other;
22
+ - their ``FROM`` and ``COPY --from`` images, but none whose familiar name is
23
+ a stage's name, and none that one of those stages uses with a
24
+ ``--platform`` other than ``$BUILDPLATFORM`` (a copy holds the one platform
25
+ the sandbox pulled, the build platform; the context would serve it to the
26
+ other platform too);
27
+ - references read from the Dockerfile and the step's build arguments alone. A
28
+ reference that needs a variable the file does not declare before its first
29
+ ``FROM`` (``$TARGETARCH``, say), or an expansion form other than ``$NAME``,
30
+ ``${NAME}``, ``${NAME:-word}`` and ``${NAME:+word}``, is left out.
31
+
32
+ Images a ``RUN --mount=from=`` uses are not served from the cache themselves.
33
+ Everything left out is pulled by BuildKit from its registry, as before.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import re
39
+ from collections.abc import Mapping
40
+ from dataclasses import dataclass, field
41
+
42
+ _NAME_COMPONENT = r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*"
43
+ _HOST_LABEL = r"[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"
44
+ #: An image reference: optional registry host (with a dot, a port or
45
+ #: ``localhost``), a lowercase repository path, an optional tag and an
46
+ #: optional digest.
47
+ _REFERENCE_RE = re.compile(
48
+ rf"^(?:{_HOST_LABEL}(?:\.{_HOST_LABEL})*(?::[0-9]{{1,5}})?/)?"
49
+ rf"{_NAME_COMPONENT}(?:/{_NAME_COMPONENT})*"
50
+ r"(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?"
51
+ r"(?:@sha256:[0-9a-f]{64})?$"
52
+ )
53
+ #: A parser directive at the top of a Dockerfile (``# escape=`` ``).
54
+ _DIRECTIVE_RE = re.compile(r"^#\s*([A-Za-z_]+)\s*=\s*(.*?)\s*$")
55
+ _VARIABLE_RE = re.compile(r"\$(?:\{([^}]*)\}|([A-Za-z_][A-Za-z0-9_]*))")
56
+ _NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
57
+ #: The one ``FROM --platform`` a copy serves: the platform the build runs on.
58
+ _BUILD_PLATFORM_FLAGS = frozenset({"--platform=$buildplatform", "--platform=${buildplatform}"})
59
+ #: Docker Hub's names for itself, which the familiar form drops.
60
+ _DOCKER_HUB_HOSTS = frozenset({"docker.io", "index.docker.io"})
61
+
62
+
63
+ def _escape_character(lines: list[str]) -> str:
64
+ """The Dockerfile's line-continuation character (``\\`` unless a directive says otherwise)."""
65
+ for line in lines:
66
+ match = _DIRECTIVE_RE.match(line.strip())
67
+ if match is None:
68
+ break
69
+ if match.group(1).lower() == "escape" and match.group(2) in ("\\", "`"):
70
+ return match.group(2)
71
+ return "\\"
72
+
73
+
74
+ def _instructions(dockerfile: str) -> list[str]:
75
+ """The Dockerfile's instructions, continuation lines joined, comments dropped."""
76
+ lines = dockerfile.splitlines()
77
+ escape = _escape_character(lines)
78
+ instructions: list[str] = []
79
+ current: list[str] = []
80
+ for raw in lines:
81
+ stripped = raw.strip()
82
+ # A comment line is dropped, inside a continued instruction too.
83
+ if not stripped or stripped.startswith("#"):
84
+ continue
85
+ if stripped.endswith(escape):
86
+ current.append(stripped[: -len(escape)])
87
+ continue
88
+ current.append(stripped)
89
+ instructions.append(" ".join(part.strip() for part in current))
90
+ current = []
91
+ if current:
92
+ instructions.append(" ".join(part.strip() for part in current))
93
+ return instructions
94
+
95
+
96
+ def _split_keyword(instruction: str) -> tuple[str, str]:
97
+ """An instruction's keyword and its arguments, split on any whitespace (tabs too)."""
98
+ parts = instruction.split(None, 1)
99
+ if not parts:
100
+ return "", ""
101
+ return parts[0], parts[1] if len(parts) > 1 else ""
102
+
103
+
104
+ def _expand(value: str, variables: Mapping[str, str | None]) -> str | None:
105
+ """``value`` with its variables expanded, or None when one cannot be."""
106
+ unresolved = False
107
+
108
+ def substitute(match: re.Match[str]) -> str:
109
+ nonlocal unresolved
110
+ braced, bare = match.group(1), match.group(2)
111
+ if bare is not None:
112
+ name, operator, word = bare, "", ""
113
+ else:
114
+ name, operator, word = braced, "", ""
115
+ for candidate in (":-", ":+"):
116
+ if candidate in braced:
117
+ name, _, word = braced.partition(candidate)
118
+ operator = candidate
119
+ break
120
+ if not _NAME_RE.match(name) or name not in variables:
121
+ unresolved = True
122
+ return ""
123
+ current = variables[name] or ""
124
+ if operator:
125
+ # The word may use variables itself (``${FLAVOUR:+-$FLAVOUR}``).
126
+ expanded_word = _expand(word, variables)
127
+ if expanded_word is None:
128
+ unresolved = True
129
+ return ""
130
+ if operator == ":-":
131
+ return current or expanded_word
132
+ return expanded_word if current else ""
133
+ return current
134
+
135
+ expanded = _VARIABLE_RE.sub(substitute, value)
136
+ if unresolved or "$" in expanded:
137
+ return None
138
+ return expanded
139
+
140
+
141
+ def _global_args(arguments: str, build_args: Mapping[str, str]) -> dict[str, str | None]:
142
+ """The variables one ``ARG`` before the first ``FROM`` declares, with their values."""
143
+ declared: dict[str, str | None] = {}
144
+ for token in arguments.split():
145
+ name, separator, default = token.partition("=")
146
+ if not _NAME_RE.match(name):
147
+ continue
148
+ if name in build_args:
149
+ declared[name] = build_args[name]
150
+ else:
151
+ declared[name] = default.strip("\"'") if separator else None
152
+ return declared
153
+
154
+
155
+ def familiar_name(reference: str) -> str:
156
+ """``reference`` as Buildx and BuildKit name a build context or match one.
157
+
158
+ Docker's familiar form: Docker Hub's host and its ``library/`` dropped
159
+ (``docker.io/library/alpine`` is ``alpine``), and a ``:latest`` tag
160
+ dropped unless a digest follows. Two references with the same familiar
161
+ name select the same named context, and a stage whose name equals it is
162
+ replaced by that context entirely.
163
+ """
164
+ name, _, digest = reference.partition("@")
165
+ tag = ""
166
+ slash, colon = name.rfind("/"), name.rfind(":")
167
+ if colon > slash:
168
+ name, tag = name[:colon], name[colon + 1 :]
169
+ first, separator, rest = name.partition("/")
170
+ other_registry = separator and (
171
+ ("." in first or ":" in first or first == "localhost") and first not in _DOCKER_HUB_HOSTS
172
+ )
173
+ if not other_registry:
174
+ if separator and first in _DOCKER_HUB_HOSTS:
175
+ name = rest
176
+ if name.startswith("library/") and name.count("/") == 1:
177
+ name = name[len("library/") :]
178
+ if digest:
179
+ return f"{name}{':' + tag if tag else ''}@{digest}"
180
+ return f"{name}:{tag}" if tag and tag != "latest" else name
181
+
182
+
183
+ @dataclass
184
+ class _Stage:
185
+ """One ``FROM`` and what its instructions take from other stages or images."""
186
+
187
+ index: int
188
+ # The stage's name (``AS name``), lowercased as BuildKit does; "" for none.
189
+ name: str
190
+ # The FROM reference with its variables expanded; None when it cannot be.
191
+ base: str | None
192
+ # Built for another platform than the build's own (``FROM --platform=...``).
193
+ foreign: bool
194
+ # ``COPY --from`` values: a stage name, a stage index or an image.
195
+ copies: list[str] = field(default_factory=list)
196
+ # ``RUN --mount=...,from=`` values: the same, never served from the cache.
197
+ mounts: list[str] = field(default_factory=list)
198
+
199
+
200
+ def _stages(dockerfile: str, build_args: Mapping[str, str]) -> list[_Stage]:
201
+ variables: dict[str, str | None] = {}
202
+ stages: list[_Stage] = []
203
+ for instruction in _instructions(dockerfile):
204
+ keyword, rest = _split_keyword(instruction)
205
+ keyword = keyword.upper()
206
+ words = rest.split()
207
+ flags = []
208
+ for word in words:
209
+ if not word.startswith("--"):
210
+ break
211
+ flags.append(word)
212
+ if keyword == "ARG" and not stages:
213
+ variables.update(_global_args(rest, build_args))
214
+ elif keyword == "FROM":
215
+ names = [word for word in words if not word.startswith("--")]
216
+ alias = names[2].lower() if len(names) >= 3 and names[1].lower() == "as" else ""
217
+ foreign = any(
218
+ flag.lower().startswith("--platform") and flag.lower() not in _BUILD_PLATFORM_FLAGS
219
+ for flag in flags
220
+ )
221
+ base = _expand(names[0], variables) if names else None
222
+ stages.append(_Stage(len(stages), alias, base, foreign))
223
+ elif stages and keyword == "COPY":
224
+ for flag in flags:
225
+ if flag.lower().startswith("--from="):
226
+ stages[-1].copies.append(flag.split("=", 1)[1])
227
+ elif stages and keyword == "RUN":
228
+ for flag in flags:
229
+ if flag.lower().startswith("--mount="):
230
+ for option in flag.split("=", 1)[1].split(","):
231
+ key, _, value = option.partition("=")
232
+ if key.lower() == "from" and value:
233
+ stages[-1].mounts.append(value)
234
+ return stages
235
+
236
+
237
+ def base_image_references(
238
+ dockerfile: str, build_args: Mapping[str, str], target: str = ""
239
+ ) -> list[str]:
240
+ """The image references the build of ``target`` uses, in order and without repeats.
241
+
242
+ ``build_args`` are the step's build arguments: they set the ``ARG``
243
+ variables declared before the first ``FROM``, which is all a ``FROM``
244
+ line may use. ``target`` is the step's target stage; without one the
245
+ last stage is built. Only the stages it depends on count, as BuildKit
246
+ builds only those. An image that any of those stages uses for another
247
+ platform is left out entirely (one named context serves every platform),
248
+ and so is one whose familiar name is a stage's name (the context would
249
+ replace that stage).
250
+ """
251
+ stages = _stages(dockerfile, build_args)
252
+ if not stages:
253
+ return []
254
+ by_name = {stage.name: stage for stage in stages if stage.name}
255
+ if target:
256
+ start = by_name.get(target.strip().lower())
257
+ if start is None:
258
+ return []
259
+ else:
260
+ start = stages[-1]
261
+
262
+ def stage_named(value: str) -> _Stage | None:
263
+ if value.isdigit():
264
+ # isdigit() includes characters int() cannot read (e.g. ²).
265
+ # Strip leading zeroes before bounding conversion so a padded
266
+ # small index remains valid, without Python's integer-size limit.
267
+ if not value.isascii():
268
+ return None
269
+ digits = value.lstrip("0") or "0"
270
+ if len(digits) > len(str(len(stages))):
271
+ return None
272
+ index = int(digits)
273
+ return stages[index] if index < len(stages) else None
274
+ return by_name.get(value.lower())
275
+
276
+ reachable: set[int] = set()
277
+ pending = [start]
278
+ while pending:
279
+ stage = pending.pop()
280
+ if stage.index in reachable:
281
+ continue
282
+ reachable.add(stage.index)
283
+ dependencies: list[_Stage | None] = [stage_named(value) for value in stage.copies]
284
+ dependencies += [stage_named(value) for value in stage.mounts]
285
+ if stage.base is not None and stage.base.lower() in by_name:
286
+ # FROM names only an earlier stage.
287
+ earlier = by_name[stage.base.lower()]
288
+ dependencies.append(earlier if earlier.index < stage.index else None)
289
+ pending.extend(dependency for dependency in dependencies if dependency is not None)
290
+
291
+ def image(value: str | None) -> str | None:
292
+ if not value or "$" in value or value.isdigit() or value.lower() in by_name:
293
+ return None
294
+ if value == "scratch" or not _REFERENCE_RE.match(value):
295
+ return None
296
+ return value
297
+
298
+ wanted: list[str] = []
299
+ other_platform: set[str] = set()
300
+ for stage in stages:
301
+ if stage.index not in reachable:
302
+ continue
303
+ used = [image(stage.base), *(image(value) for value in stage.copies)]
304
+ mounted = [image(value) for value in stage.mounts]
305
+ for reference in used:
306
+ if reference is None:
307
+ continue
308
+ if stage.foreign:
309
+ other_platform.add(familiar_name(reference))
310
+ else:
311
+ wanted.append(reference)
312
+ if stage.foreign:
313
+ other_platform.update(familiar_name(ref) for ref in mounted if ref is not None)
314
+
315
+ found: list[str] = []
316
+ seen: set[str] = set()
317
+ for reference in wanted:
318
+ name = familiar_name(reference)
319
+ if name in other_platform or name in by_name or name in seen:
320
+ continue
321
+ seen.add(name)
322
+ found.append(reference)
323
+ return found
324
+
325
+
326
+ __all__ = ["base_image_references", "familiar_name"]