groundbox-harbor 0.1.0__tar.gz
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.
- groundbox_harbor-0.1.0/.gitignore +6 -0
- groundbox_harbor-0.1.0/PKG-INFO +143 -0
- groundbox_harbor-0.1.0/README.md +121 -0
- groundbox_harbor-0.1.0/pyproject.toml +39 -0
- groundbox_harbor-0.1.0/src/groundbox_harbor/__init__.py +6 -0
- groundbox_harbor-0.1.0/src/groundbox_harbor/_dockerfile.py +291 -0
- groundbox_harbor-0.1.0/src/groundbox_harbor/environment.py +1020 -0
- groundbox_harbor-0.1.0/src/groundbox_harbor/py.typed +0 -0
- groundbox_harbor-0.1.0/tests/__init__.py +0 -0
- groundbox_harbor-0.1.0/tests/conftest.py +193 -0
- groundbox_harbor-0.1.0/tests/test_dockerfile.py +117 -0
- groundbox_harbor-0.1.0/tests/test_environment.py +372 -0
- groundbox_harbor-0.1.0/tests/test_live.py +101 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: groundbox-harbor
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Run Harbor agent evals (Terminal-Bench and more) in Groundbox sandboxes
|
|
5
|
+
Project-URL: Homepage, https://groundbox.dev
|
|
6
|
+
Project-URL: Documentation, https://groundbox.dev/docs
|
|
7
|
+
Project-URL: Source, https://github.com/Ground-box/groundbox-integrations/tree/main/python/harbor
|
|
8
|
+
Author-email: Groundbox <contact@groundbox.dev>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
Keywords: agents,evals,groundbox,harbor,sandbox,terminal-bench
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Requires-Python: >=3.12
|
|
16
|
+
Requires-Dist: dockerfile-parse>=2.0.1
|
|
17
|
+
Requires-Dist: groundbox>=0.4.2
|
|
18
|
+
Requires-Dist: harbor>=0.26.0
|
|
19
|
+
Provides-Extra: test
|
|
20
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# groundbox-harbor
|
|
24
|
+
|
|
25
|
+
Run [Harbor](https://github.com/harbor-framework/harbor) jobs (Terminal-Bench and any other
|
|
26
|
+
Harbor task) in [Groundbox](https://groundbox.dev) sandboxes: each trial gets its own
|
|
27
|
+
Firecracker microVM. This is a Harbor custom environment (`BaseEnvironment`), so it works
|
|
28
|
+
with the `harbor` CLI as it is, with no change to Harbor.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install groundbox-harbor # or: uv tool install harbor --with groundbox-harbor
|
|
34
|
+
export GROUNDBOX_API_KEY=gbx_... # https://app.groundbox.dev/keys
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Install it in the same Python environment as Harbor. It needs Python 3.12 or newer and
|
|
38
|
+
Harbor 0.26 or newer.
|
|
39
|
+
|
|
40
|
+
## Run
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
harbor run -d terminal-bench@2.0 -a terminus-2 -m anthropic/claude-sonnet-4-5 \
|
|
44
|
+
-e groundbox_harbor:GroundboxSandbox -n 8
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The oracle agent needs no model key, which makes it a quick check that everything works:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
harbor run -p examples/tasks/hello-world -a oracle -e groundbox_harbor:GroundboxSandbox
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
In a job config:
|
|
54
|
+
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"environment": {
|
|
58
|
+
"import_path": "groundbox_harbor:GroundboxSandbox",
|
|
59
|
+
"kwargs": { "sandbox_timeout_minutes": 120 }
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Or from Python, with `EnvironmentConfig(import_path="groundbox_harbor:GroundboxSandbox")`.
|
|
65
|
+
|
|
66
|
+
## How a task becomes a sandbox
|
|
67
|
+
|
|
68
|
+
- **`docker_image` in task.toml** (every Terminal-Bench 2.0 task has one): the sandbox starts
|
|
69
|
+
straight from that image. The first sandbox from an image waits a minute or so while
|
|
70
|
+
Groundbox turns it into a disk; later ones start in about a second.
|
|
71
|
+
- **`environment/Dockerfile`** (or `--force-build`): the Dockerfile is built once as a
|
|
72
|
+
Groundbox template named `harbor-<hash>`, and every trial with the same Dockerfile and
|
|
73
|
+
size starts from it. Building is free. `COPY`/`ADD` of local files work: the
|
|
74
|
+
`environment/` folder is written into the Dockerfile as a first build stage (see Limits).
|
|
75
|
+
- **`--ek template=<name>`**: start from a Groundbox template you made yourself, ignoring the
|
|
76
|
+
task's image and Dockerfile.
|
|
77
|
+
|
|
78
|
+
Commands run as the Dockerfile's last `USER` (root when it sets none), in its `WORKDIR`
|
|
79
|
+
(`/` when none), with the image's `ENV`, as `docker exec` would. Harbor's agent and verifier
|
|
80
|
+
users are applied with `su`.
|
|
81
|
+
|
|
82
|
+
## Options
|
|
83
|
+
|
|
84
|
+
Pass them with `--ek name=value` (or `environment.kwargs`):
|
|
85
|
+
|
|
86
|
+
| Option | Default | What it does |
|
|
87
|
+
| --- | --- | --- |
|
|
88
|
+
| `template` | none | Start from this Groundbox template (name, id or `name:version`). |
|
|
89
|
+
| `image_user` | Dockerfile `USER`, else root | User for commands when Harbor names none. |
|
|
90
|
+
| `sandbox_timeout_minutes` | 60 | Sandbox lifetime; renewed while the trial runs, so a sandbox left by a dead Harbor process ends within this long. |
|
|
91
|
+
| `renew_interval_sec` | 600 | How often the lifetime is renewed; 0 turns renewal off. |
|
|
92
|
+
| `flex` | false | Half-price sandboxes that start when a machine has spare room (may queue). |
|
|
93
|
+
| `allow_memory_overcommit` | true | `vm.overcommit_memory=1` at start, as on a Docker host. |
|
|
94
|
+
| `create_retry_sec` | 900 | How long to retry a create Groundbox refuses for a concurrency limit (429). |
|
|
95
|
+
| `evict_templates` | true | At the team's template limit, delete the oldest `harbor-*` template not in use and retry. |
|
|
96
|
+
|
|
97
|
+
Task resources map to the sandbox: `cpus` to vCPUs (whole cores, 1 to 16), `memory_mb` to
|
|
98
|
+
GB (at most 4 GB per vCPU, so more memory raises the vCPU count unless CPU is a hard limit),
|
|
99
|
+
`storage_mb` to the disk size.
|
|
100
|
+
|
|
101
|
+
## What it supports
|
|
102
|
+
|
|
103
|
+
| Harbor feature | Groundbox |
|
|
104
|
+
| --- | --- |
|
|
105
|
+
| exec, cwd, env, user, timeout | yes (long commands run in the background and are polled) |
|
|
106
|
+
| upload/download of files and folders | yes (tar for folders; large files in chunks) |
|
|
107
|
+
| `docker_image` tasks, Dockerfile tasks | yes |
|
|
108
|
+
| `network_mode = "no-network"` | yes (`allow_hosts: []`) |
|
|
109
|
+
| `allowlist` network mode | yes: host names, `*.wildcards`, IPv4 addresses and CIDRs; no IPv6 |
|
|
110
|
+
| switching network policy between phases | yes (egress is changed on the running sandbox) |
|
|
111
|
+
| resource limits | cpus and memory are both reserved and a hard limit |
|
|
112
|
+
| GPUs, TPUs, Windows tasks | no |
|
|
113
|
+
| docker-compose (multi-container) tasks | no |
|
|
114
|
+
| stream mode / SSH, host mounts | no |
|
|
115
|
+
|
|
116
|
+
## Limits
|
|
117
|
+
|
|
118
|
+
- A Dockerfile build has no build context on Groundbox's side, and Groundbox takes a
|
|
119
|
+
Dockerfile of at most 64 KiB. Local `COPY`/`ADD` therefore work when the `environment/`
|
|
120
|
+
folder, gzipped and base64-encoded, fits in that (a few dozen KB). For a bigger context,
|
|
121
|
+
push the image (for example with `groundbox build --push` to `registry.groundbox.dev`) and
|
|
122
|
+
set `docker_image`, or pass `--ek template=...`. `.dockerignore` is not applied.
|
|
123
|
+
- The first build stage on busybox needs Docker Hub; Dockerfiles that set their own
|
|
124
|
+
`# syntax=` older than 1.4 cannot use heredocs.
|
|
125
|
+
- With only `docker_image` (no Dockerfile in `environment/`), the image's own `WORKDIR` and
|
|
126
|
+
`USER` are not known: commands start in `/` as root. Set `workdir` in task.toml or
|
|
127
|
+
`--ek image_user=...` when the image needs them.
|
|
128
|
+
- Images must be `linux/amd64` and public (or in your Groundbox registry).
|
|
129
|
+
- A team keeps 20 templates; `harbor-*` templates past that are evicted oldest first.
|
|
130
|
+
- Each sandbox costs $0.04 per vCPU-hour while it runs. Sandboxes are deleted at the end
|
|
131
|
+
of each trial.
|
|
132
|
+
|
|
133
|
+
## Tests
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
pip install -e '.[test]'
|
|
137
|
+
pytest # unit tests, with a fake Groundbox client
|
|
138
|
+
GROUNDBOX_API_KEY=gbx_... pytest -m live # also starts real sandboxes
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
MIT; see [LICENSE](../../LICENSE) at the root of this repository.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# groundbox-harbor
|
|
2
|
+
|
|
3
|
+
Run [Harbor](https://github.com/harbor-framework/harbor) jobs (Terminal-Bench and any other
|
|
4
|
+
Harbor task) in [Groundbox](https://groundbox.dev) sandboxes: each trial gets its own
|
|
5
|
+
Firecracker microVM. This is a Harbor custom environment (`BaseEnvironment`), so it works
|
|
6
|
+
with the `harbor` CLI as it is, with no change to Harbor.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install groundbox-harbor # or: uv tool install harbor --with groundbox-harbor
|
|
12
|
+
export GROUNDBOX_API_KEY=gbx_... # https://app.groundbox.dev/keys
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Install it in the same Python environment as Harbor. It needs Python 3.12 or newer and
|
|
16
|
+
Harbor 0.26 or newer.
|
|
17
|
+
|
|
18
|
+
## Run
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
harbor run -d terminal-bench@2.0 -a terminus-2 -m anthropic/claude-sonnet-4-5 \
|
|
22
|
+
-e groundbox_harbor:GroundboxSandbox -n 8
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The oracle agent needs no model key, which makes it a quick check that everything works:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
harbor run -p examples/tasks/hello-world -a oracle -e groundbox_harbor:GroundboxSandbox
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
In a job config:
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"environment": {
|
|
36
|
+
"import_path": "groundbox_harbor:GroundboxSandbox",
|
|
37
|
+
"kwargs": { "sandbox_timeout_minutes": 120 }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Or from Python, with `EnvironmentConfig(import_path="groundbox_harbor:GroundboxSandbox")`.
|
|
43
|
+
|
|
44
|
+
## How a task becomes a sandbox
|
|
45
|
+
|
|
46
|
+
- **`docker_image` in task.toml** (every Terminal-Bench 2.0 task has one): the sandbox starts
|
|
47
|
+
straight from that image. The first sandbox from an image waits a minute or so while
|
|
48
|
+
Groundbox turns it into a disk; later ones start in about a second.
|
|
49
|
+
- **`environment/Dockerfile`** (or `--force-build`): the Dockerfile is built once as a
|
|
50
|
+
Groundbox template named `harbor-<hash>`, and every trial with the same Dockerfile and
|
|
51
|
+
size starts from it. Building is free. `COPY`/`ADD` of local files work: the
|
|
52
|
+
`environment/` folder is written into the Dockerfile as a first build stage (see Limits).
|
|
53
|
+
- **`--ek template=<name>`**: start from a Groundbox template you made yourself, ignoring the
|
|
54
|
+
task's image and Dockerfile.
|
|
55
|
+
|
|
56
|
+
Commands run as the Dockerfile's last `USER` (root when it sets none), in its `WORKDIR`
|
|
57
|
+
(`/` when none), with the image's `ENV`, as `docker exec` would. Harbor's agent and verifier
|
|
58
|
+
users are applied with `su`.
|
|
59
|
+
|
|
60
|
+
## Options
|
|
61
|
+
|
|
62
|
+
Pass them with `--ek name=value` (or `environment.kwargs`):
|
|
63
|
+
|
|
64
|
+
| Option | Default | What it does |
|
|
65
|
+
| --- | --- | --- |
|
|
66
|
+
| `template` | none | Start from this Groundbox template (name, id or `name:version`). |
|
|
67
|
+
| `image_user` | Dockerfile `USER`, else root | User for commands when Harbor names none. |
|
|
68
|
+
| `sandbox_timeout_minutes` | 60 | Sandbox lifetime; renewed while the trial runs, so a sandbox left by a dead Harbor process ends within this long. |
|
|
69
|
+
| `renew_interval_sec` | 600 | How often the lifetime is renewed; 0 turns renewal off. |
|
|
70
|
+
| `flex` | false | Half-price sandboxes that start when a machine has spare room (may queue). |
|
|
71
|
+
| `allow_memory_overcommit` | true | `vm.overcommit_memory=1` at start, as on a Docker host. |
|
|
72
|
+
| `create_retry_sec` | 900 | How long to retry a create Groundbox refuses for a concurrency limit (429). |
|
|
73
|
+
| `evict_templates` | true | At the team's template limit, delete the oldest `harbor-*` template not in use and retry. |
|
|
74
|
+
|
|
75
|
+
Task resources map to the sandbox: `cpus` to vCPUs (whole cores, 1 to 16), `memory_mb` to
|
|
76
|
+
GB (at most 4 GB per vCPU, so more memory raises the vCPU count unless CPU is a hard limit),
|
|
77
|
+
`storage_mb` to the disk size.
|
|
78
|
+
|
|
79
|
+
## What it supports
|
|
80
|
+
|
|
81
|
+
| Harbor feature | Groundbox |
|
|
82
|
+
| --- | --- |
|
|
83
|
+
| exec, cwd, env, user, timeout | yes (long commands run in the background and are polled) |
|
|
84
|
+
| upload/download of files and folders | yes (tar for folders; large files in chunks) |
|
|
85
|
+
| `docker_image` tasks, Dockerfile tasks | yes |
|
|
86
|
+
| `network_mode = "no-network"` | yes (`allow_hosts: []`) |
|
|
87
|
+
| `allowlist` network mode | yes: host names, `*.wildcards`, IPv4 addresses and CIDRs; no IPv6 |
|
|
88
|
+
| switching network policy between phases | yes (egress is changed on the running sandbox) |
|
|
89
|
+
| resource limits | cpus and memory are both reserved and a hard limit |
|
|
90
|
+
| GPUs, TPUs, Windows tasks | no |
|
|
91
|
+
| docker-compose (multi-container) tasks | no |
|
|
92
|
+
| stream mode / SSH, host mounts | no |
|
|
93
|
+
|
|
94
|
+
## Limits
|
|
95
|
+
|
|
96
|
+
- A Dockerfile build has no build context on Groundbox's side, and Groundbox takes a
|
|
97
|
+
Dockerfile of at most 64 KiB. Local `COPY`/`ADD` therefore work when the `environment/`
|
|
98
|
+
folder, gzipped and base64-encoded, fits in that (a few dozen KB). For a bigger context,
|
|
99
|
+
push the image (for example with `groundbox build --push` to `registry.groundbox.dev`) and
|
|
100
|
+
set `docker_image`, or pass `--ek template=...`. `.dockerignore` is not applied.
|
|
101
|
+
- The first build stage on busybox needs Docker Hub; Dockerfiles that set their own
|
|
102
|
+
`# syntax=` older than 1.4 cannot use heredocs.
|
|
103
|
+
- With only `docker_image` (no Dockerfile in `environment/`), the image's own `WORKDIR` and
|
|
104
|
+
`USER` are not known: commands start in `/` as root. Set `workdir` in task.toml or
|
|
105
|
+
`--ek image_user=...` when the image needs them.
|
|
106
|
+
- Images must be `linux/amd64` and public (or in your Groundbox registry).
|
|
107
|
+
- A team keeps 20 templates; `harbor-*` templates past that are evicted oldest first.
|
|
108
|
+
- Each sandbox costs $0.04 per vCPU-hour while it runs. Sandboxes are deleted at the end
|
|
109
|
+
of each trial.
|
|
110
|
+
|
|
111
|
+
## Tests
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
pip install -e '.[test]'
|
|
115
|
+
pytest # unit tests, with a fake Groundbox client
|
|
116
|
+
GROUNDBOX_API_KEY=gbx_... pytest -m live # also starts real sandboxes
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## License
|
|
120
|
+
|
|
121
|
+
MIT; see [LICENSE](../../LICENSE) at the root of this repository.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "groundbox-harbor"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Run Harbor agent evals (Terminal-Bench and more) in Groundbox sandboxes"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
requires-python = ">=3.12"
|
|
8
|
+
authors = [{ name = "Groundbox", email = "contact@groundbox.dev" }]
|
|
9
|
+
keywords = ["harbor", "terminal-bench", "groundbox", "sandbox", "agents", "evals"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Programming Language :: Python :: 3.12",
|
|
13
|
+
"Programming Language :: Python :: 3.13",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
]
|
|
16
|
+
dependencies = [
|
|
17
|
+
"harbor>=0.26.0",
|
|
18
|
+
"groundbox>=0.4.2",
|
|
19
|
+
"dockerfile-parse>=2.0.1",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
test = ["pytest>=8"]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://groundbox.dev"
|
|
27
|
+
Documentation = "https://groundbox.dev/docs"
|
|
28
|
+
Source = "https://github.com/Ground-box/groundbox-integrations/tree/main/python/harbor"
|
|
29
|
+
|
|
30
|
+
[build-system]
|
|
31
|
+
requires = ["hatchling>=1.25"]
|
|
32
|
+
build-backend = "hatchling.build"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/groundbox_harbor"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
testpaths = ["tests"]
|
|
39
|
+
markers = ["live: starts real Groundbox sandboxes; needs GROUNDBOX_API_KEY"]
|
|
@@ -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
|