groundbox-harbor 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.
@@ -0,0 +1,6 @@
1
+ """Groundbox sandboxes for Harbor: ``harbor run -e groundbox_harbor:GroundboxSandbox``."""
2
+
3
+ from groundbox_harbor.environment import GroundboxOptions, GroundboxSandbox
4
+
5
+ __all__ = ["GroundboxOptions", "GroundboxSandbox"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,291 @@
1
+ """Turn a task's Dockerfile into one Groundbox can build as a template.
2
+
3
+ A Groundbox template is built from the Dockerfile text alone: there is no build
4
+ context, so ``COPY`` and ``ADD`` of local files would fail. When a Dockerfile
5
+ copies local files, the whole ``environment/`` folder is packed into a
6
+ gzipped tar, written into the Dockerfile as base64 in a first build stage
7
+ (``harbor-groundbox-context``, on busybox), and each local ``COPY``/``ADD``
8
+ becomes ``COPY --from=harbor-groundbox-context /ctx/...``. Docker's own COPY
9
+ then decides file versus directory, globs, ``--chown`` and ``--chmod``, so the
10
+ result matches a normal ``docker build`` of the same folder.
11
+
12
+ Groundbox takes a Dockerfile of at most 64 KiB, so this only works for small
13
+ contexts; :class:`ContextTooLargeError` says so when it does not fit.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import base64
19
+ import io
20
+ import json
21
+ import re
22
+ import shlex
23
+ import tarfile
24
+ from dataclasses import dataclass
25
+ from pathlib import Path, PurePosixPath
26
+
27
+ from dockerfile_parse import DockerfileParser
28
+
29
+ CONTEXT_STAGE = "harbor-groundbox-context"
30
+ CONTEXT_STAGE_IMAGE = "busybox:1.36.1"
31
+ CONTEXT_ROOT = "/ctx"
32
+ ADD_EXTRACT_ROOT = "/ctx-add"
33
+ # Groundbox refuses a template Dockerfile longer than this many characters.
34
+ MAX_DOCKERFILE_CHARS = 65536
35
+
36
+ _ARCHIVE_FLAGS = (
37
+ (".tar.gz", "z"),
38
+ (".tgz", "z"),
39
+ (".tar.bz2", "j"),
40
+ (".tbz2", "j"),
41
+ (".tar.xz", "J"),
42
+ (".txz", "J"),
43
+ (".tar", ""),
44
+ )
45
+ _REMOTE_PREFIXES = ("http://", "https://", "git@", "git://", "ssh://")
46
+
47
+
48
+ class ContextTooLargeError(ValueError):
49
+ """The rewritten Dockerfile is over Groundbox's 64 KiB limit."""
50
+
51
+
52
+ @dataclass
53
+ class PreparedDockerfile:
54
+ text: str
55
+ inlined_context: bool
56
+ context_bytes: int = 0
57
+
58
+
59
+ def _split_flags(tokens: list[str]) -> tuple[list[str], list[str]]:
60
+ flags: list[str] = []
61
+ rest = list(tokens)
62
+ while rest and rest[0].startswith("--"):
63
+ flags.append(rest.pop(0))
64
+ return flags, rest
65
+
66
+
67
+ def _parse_copy_value(value: str) -> tuple[list[str], list[str], bool] | None:
68
+ """Flags, paths (sources then destination) and whether the JSON form was used."""
69
+ try:
70
+ tokens = shlex.split(value, posix=True)
71
+ except ValueError:
72
+ tokens = value.split()
73
+ flags, rest = _split_flags(tokens)
74
+ remainder = value.strip()
75
+ # Drop the flags from the raw value to see whether the paths are JSON.
76
+ for flag in flags:
77
+ idx = remainder.find(flag)
78
+ if idx != -1:
79
+ remainder = remainder[idx + len(flag) :].lstrip()
80
+ if remainder.startswith("["):
81
+ try:
82
+ paths = json.loads(remainder)
83
+ except ValueError:
84
+ return None
85
+ if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths):
86
+ return None
87
+ return flags, paths, True
88
+ return flags, rest, False
89
+
90
+
91
+ def _flag_name(flag: str) -> str:
92
+ return flag.split("=", 1)[0]
93
+
94
+
95
+ def _is_local_source(source: str) -> bool:
96
+ return not source.startswith(_REMOTE_PREFIXES)
97
+
98
+
99
+ def _context_path(source: str) -> str:
100
+ """The path inside the context stage for a COPY source."""
101
+ rel = PurePosixPath("/" + source.lstrip("/"))
102
+ # PurePosixPath keeps glob characters and "." as they are.
103
+ text = str(rel)
104
+ if source.rstrip("/") in ("", "."):
105
+ return f"{CONTEXT_ROOT}/."
106
+ return f"{CONTEXT_ROOT}{text}"
107
+
108
+
109
+ def _archive_flag(source: str) -> str | None:
110
+ lower = source.lower()
111
+ for suffix, flag in _ARCHIVE_FLAGS:
112
+ if lower.endswith(suffix):
113
+ return flag
114
+ return None
115
+
116
+
117
+ def _pack_context(environment_dir: Path) -> bytes:
118
+ buffer = io.BytesIO()
119
+ with tarfile.open(fileobj=buffer, mode="w:gz", compresslevel=9) as tar:
120
+ for path in sorted(environment_dir.rglob("*")):
121
+ rel = path.relative_to(environment_dir).as_posix()
122
+ info = tar.gettarinfo(str(path), arcname=rel)
123
+ info.uid = info.gid = 0
124
+ info.uname = info.gname = "root"
125
+ if info.isreg():
126
+ with path.open("rb") as handle:
127
+ tar.addfile(info, handle)
128
+ elif info.isdir() or info.issym():
129
+ tar.addfile(info)
130
+ return buffer.getvalue()
131
+
132
+
133
+ def _render_paths(paths: list[str], as_json: bool) -> str:
134
+ if as_json:
135
+ return json.dumps(paths)
136
+ return " ".join(shlex.quote(p) if re.search(r"\s", p) else p for p in paths)
137
+
138
+
139
+ def prepare_dockerfile(dockerfile_path: Path) -> PreparedDockerfile:
140
+ """Return Dockerfile text Groundbox can build with no build context.
141
+
142
+ Raises :class:`ContextTooLargeError` when the result is over 64 KiB.
143
+ """
144
+ text = dockerfile_path.read_text()
145
+ environment_dir = dockerfile_path.parent
146
+ parser = DockerfileParser(fileobj=io.BytesIO(text.encode()))
147
+ structure = parser.structure
148
+ lines = text.splitlines(keepends=True)
149
+
150
+ replacements: dict[int, tuple[int, str]] = {}
151
+ add_extracts: list[tuple[str, str, str]] = [] # (source, extract dir, tar flag)
152
+ first_from: int | None = None
153
+ needs_context = False
154
+
155
+ for instr in structure:
156
+ name = instr["instruction"]
157
+ if name == "FROM" and first_from is None:
158
+ first_from = instr["startline"]
159
+ if name not in ("COPY", "ADD"):
160
+ continue
161
+ parsed = _parse_copy_value(instr["value"])
162
+ if parsed is None:
163
+ continue
164
+ flags, paths, as_json = parsed
165
+ if len(paths) < 2:
166
+ continue
167
+ from_flags = [f for f in flags if _flag_name(f) == "--from"]
168
+ if from_flags:
169
+ # Stage indexes shift by one once the context stage is added first.
170
+ new_flags = []
171
+ for flag in flags:
172
+ value = flag.split("=", 1)[1] if "=" in flag else ""
173
+ if _flag_name(flag) == "--from" and value.isdigit():
174
+ flag = f"--from={int(value) + 1}"
175
+ new_flags.append(flag)
176
+ if new_flags != flags:
177
+ body = " ".join(new_flags + [_render_paths(paths, as_json)])
178
+ replacements[instr["startline"]] = (
179
+ instr["endline"],
180
+ f"{name} {body}\n",
181
+ )
182
+ continue
183
+ sources, dest = paths[:-1], paths[-1]
184
+ if not all(_is_local_source(s) for s in sources):
185
+ if name == "ADD" and not any(_is_local_source(s) for s in sources):
186
+ continue # ADD from URLs or git needs no context.
187
+ # A mix of remote and local sources: leave it, Docker would too.
188
+ continue
189
+ needs_context = True
190
+ new_sources: list[str] = []
191
+ for source in sources:
192
+ flag = _archive_flag(source) if name == "ADD" else None
193
+ if flag is not None:
194
+ target = f"{ADD_EXTRACT_ROOT}/{len(add_extracts)}"
195
+ add_extracts.append((source, target, flag))
196
+ new_sources.append(f"{target}/.")
197
+ else:
198
+ new_sources.append(_context_path(source))
199
+ kept_flags = [
200
+ f for f in flags if _flag_name(f) in ("--chown", "--chmod", "--link")
201
+ ]
202
+ body = " ".join(
203
+ [f"--from={CONTEXT_STAGE}", *kept_flags]
204
+ + [_render_paths([*new_sources, dest], as_json)]
205
+ )
206
+ replacements[instr["startline"]] = (instr["endline"], f"COPY {body}\n")
207
+
208
+ if not needs_context and not replacements:
209
+ return PreparedDockerfile(text=text, inlined_context=False)
210
+
211
+ out: list[str] = []
212
+ context_size = 0
213
+ i = 0
214
+ while i < len(lines):
215
+ if needs_context and i == first_from:
216
+ archive = _pack_context(environment_dir)
217
+ context_size = len(archive)
218
+ encoded = base64.encodebytes(archive).decode()
219
+ script = [
220
+ "set -e",
221
+ f"mkdir -p {CONTEXT_ROOT}",
222
+ f"base64 -d <<'HARBOR_GROUNDBOX_B64' | tar -xzf - -C {CONTEXT_ROOT}",
223
+ encoded.rstrip("\n"),
224
+ "HARBOR_GROUNDBOX_B64",
225
+ ]
226
+ for source, target, flag in add_extracts:
227
+ archive_path = _context_path(source)
228
+ script.append(
229
+ f"mkdir -p {target} && tar -x{flag}f {shlex.quote(archive_path)} -C {target}"
230
+ )
231
+ out.append(f"FROM {CONTEXT_STAGE_IMAGE} AS {CONTEXT_STAGE}\n")
232
+ out.append("RUN <<'HARBOR_GROUNDBOX_CONTEXT'\n")
233
+ out.append("\n".join(script) + "\n")
234
+ out.append("HARBOR_GROUNDBOX_CONTEXT\n\n")
235
+ if i in replacements:
236
+ end, replacement = replacements[i]
237
+ out.append(replacement)
238
+ i = end + 1
239
+ continue
240
+ out.append(lines[i])
241
+ i += 1
242
+
243
+ result = "".join(out)
244
+ if len(result) > MAX_DOCKERFILE_CHARS:
245
+ raise ContextTooLargeError(
246
+ f"{dockerfile_path} copies local files, and with the environment folder "
247
+ f"written into it ({context_size} bytes compressed) the Dockerfile is "
248
+ f"{len(result)} characters, over Groundbox's {MAX_DOCKERFILE_CHARS}. "
249
+ "Push the image to a registry (for example registry.groundbox.dev with "
250
+ "`groundbox build --push`) and set docker_image in task.toml, or pass "
251
+ "--ek template=<a Groundbox template built from it>."
252
+ )
253
+ return PreparedDockerfile(
254
+ text=result, inlined_context=needs_context, context_bytes=context_size
255
+ )
256
+
257
+
258
+ @dataclass
259
+ class _Stage:
260
+ user: str | None = None
261
+
262
+
263
+ def parse_dockerfile_user(dockerfile_path: Path) -> str | None:
264
+ """The ``USER`` the final stage runs as, or None when it sets none.
265
+
266
+ ``FROM <earlier stage>`` keeps that stage's user, as Docker does. A
267
+ ``user:group`` value gives the user part.
268
+ """
269
+ if not dockerfile_path.exists():
270
+ return None
271
+ parser = DockerfileParser(fileobj=io.BytesIO(dockerfile_path.read_bytes()))
272
+ stages: dict[str, _Stage] = {}
273
+ ordered: list[_Stage] = []
274
+ current: _Stage | None = None
275
+ for instr in parser.structure:
276
+ name = instr["instruction"]
277
+ if name == "FROM":
278
+ parts = instr["value"].split()
279
+ parts = [p for p in parts if not p.startswith("--")]
280
+ base = parts[0] if parts else ""
281
+ parent = stages.get(base.lower())
282
+ if parent is None and base.isdigit() and int(base) < len(ordered):
283
+ parent = ordered[int(base)]
284
+ current = _Stage(user=parent.user if parent else None)
285
+ ordered.append(current)
286
+ if len(parts) >= 3 and parts[1].upper() == "AS":
287
+ stages[parts[2].lower()] = current
288
+ elif name == "USER" and current is not None:
289
+ value = instr["value"].strip()
290
+ current.user = value.split(":", 1)[0] if value else None
291
+ return current.user if current else None