Repository navigation
Expand file tree
/
Copy pathdev
More file actions
executable file
·287 lines (248 loc) · 14 KB
/
Copy pathdev
File metadata and controls
executable file
·287 lines (248 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-or-later
# ABOUTME: `./dev`: runs a command, or a shell, in the development image (D235 §3), building the
# ABOUTME: image first when it is missing or its inputs changed. The host needs only git and Docker.
"""Run a command in the development container.
./dev a shell in the container, in the directory you are in
./dev make check the gate, the same way CI and every other machine run it
./dev make dev the app, on http://127.0.0.1:5173 (the server on :8432)
./dev --stop remove this repository's container (the volumes stay)
./dev --gate <cmd> run cmd in the gate's container: the same image and caches, apart from
the dev loop's, so a gate never replaces it (scripts/run_gate.py uses it)
./dev --image-tag print the image's tag, which a CI cache keys the built image by
The image is built from deploy/Containerfile's dev stage and tagged with a hash of every file it is built
from and of your uid and gid, so a changed pin builds a new one and an unchanged tree reuses it.
One container per clone runs in the background, and every `./dev` runs its command in it: a dev
loop in one terminal and `./dev make check` in another share it and do not fight over ports. The
container is replaced when the image or anything below changes.
- The repository is mounted at its own path, so paths read the same inside and out.
- You are yourself inside: the image's user has your uid and gid.
- Go's module and build caches, npm's cache and Playwright's browsers live in named volumes
(VOLUMES), never on the host.
- ORPHEUM_DEV_MEDIA, when set, is a media directory mounted read-only at its own path, and the dev
loop gives the node it as a root, so a new library can choose it.
- ORPHEUM_FFMPEG_LOCAL, when set, is a local build of FFmpeg mounted read-only at its own path and
named to the command, which uses it in place of the pin (scripts/fetch_ffmpeg.py).
- /dev/dri is passed through when the host has it, for Quick Sync.
- The dev loop's ports are published on ORPHEUM_DEV_PUBLISH (default 127.0.0.1; 0.0.0.0 opens
them to the LAN, as `make dev-lan` does outside a container).
- ORPHEUM_DEV_ALLOWED_HOSTS, the names Vite answers to besides IP addresses (`devnas.example`), is
passed to the command, so the LAN reaches the dev loop by name.
- ORPHEUM_DEV_ENGINE picks the container engine; otherwise docker, then podman.
- ORPHEUM_DEV_CACHE_DIR, when set, keeps the caches in a directory of the host, one subdirectory
each, in place of the named volumes: CI saves and restores it between runs.
"""
from __future__ import annotations
import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent
CONTAINERFILE = "deploy/Containerfile"
# Every file the image is built from, at its repository path. The image tag hashes them; the
# build context holds only them, so a large .dev/ or node_modules is never sent to the engine.
BUILD_INPUTS = (
CONTAINERFILE,
"go.mod",
"scripts/fetch_ffmpeg.py",
"scripts/fetch_mkvtoolnix.py",
"scripts/fetch_tools.py",
"web/package-lock.json",
)
IMAGE = "orpheum-dev"
# The image's user's home (deploy/Containerfile, the dev stage).
HOME = "/home/dev"
VOLUMES = {
"orpheum-dev-go": f"{HOME}/go", # Go's module cache (GOPATH)
"orpheum-dev-cache": f"{HOME}/.cache", # Go's build cache, golangci-lint's, Playwright's browsers
"orpheum-dev-npm": f"{HOME}/.npm", # npm's cache
}
# Names a directory of the host to keep the caches in, one subdirectory per volume, in place of the
# named volumes: what CI saves between runs (the jobs rebuild's step 4a′).
CACHE_DIR_ENV = "ORPHEUM_DEV_CACHE_DIR"
# The dev loop's ports: the server's (deploy/dev/core.dev.toml's listen) and Vite's (scripts/dev.py).
SERVER_PORT = 8432
VITE_PORT = 5173
# Inside the container the loop listens on every interface, or a published port reaches nothing;
# what the host exposes is decided by ORPHEUM_DEV_PUBLISH. DEV_LISTEN is the Makefile's knob.
CONTAINER_LISTEN = f"0.0.0.0:{SERVER_PORT}"
DEFAULT_PUBLISH = "127.0.0.1"
ENGINES = ("docker", "podman")
# udev's database on the host, which says which disks are a ZFS pool's (D240 §5).
UDEV_DATABASE = Path("/run/udev")
# Labels: one marks every image and container this script made, one records a container's
# configuration so a changed one is replaced.
LABEL = "orpheum.dev"
CONFIG_LABEL = "orpheum.dev.config"
# The caller's environment variables a command inside sees too.
FORWARDED_ENV = ("TERM", "ORPHEUM_DEV_ALLOWED_HOSTS")
FORWARDED_ENV_PREFIXES = ("ORPHEUM_TEST_", "ORPHEUM_GATE_")
# Set by the Stop hook: a gate it runs never builds the image, which can take minutes past its limit.
NO_BUILD_ENV = "ORPHEUM_DEV_NO_BUILD"
# The exit when NO_BUILD_ENV forbids building a missing image.
NEEDS_BUILD = 3
def image_tag(root: Path, uid: int, gid: int) -> str:
"""The image's name and tag: a hash of every build input, and of the uid and gid baked in."""
digest = hashlib.sha256(f"uid={uid} gid={gid}\n".encode())
for rel in BUILD_INPUTS:
digest.update(rel.encode() + b"\0")
digest.update((root / rel).read_bytes() + b"\0")
return f"{IMAGE}:{digest.hexdigest()[:16]}"
def container_name(root: Path, gate: bool = False) -> str:
"""One container per clone, named for the clone's path; the gate's is another, beside it."""
return f"{IMAGE}-{'gate-' if gate else ''}{hashlib.sha256(str(root).encode()).hexdigest()[:12]}"
def find_engine(env: dict[str, str], which=shutil.which) -> str | None:
"""ORPHEUM_DEV_ENGINE if set, else the first of docker and podman on PATH."""
wanted = env.get("ORPHEUM_DEV_ENGINE")
for name in (wanted,) if wanted else ENGINES:
if which(name):
return name
return None
def dri_groups(dri: Path) -> list[int]:
"""The groups owning the GPU's device nodes, which the user needs to open them."""
return sorted({entry.stat().st_gid for entry in dri.iterdir()}) if dri.is_dir() else []
def build_args(engine: str, tag: str, context: Path, uid: int, gid: int) -> list[str]:
return [engine, "build", "--file", str(context / CONTAINERFILE), "--target", "dev", "--tag", tag,
"--label", f"{LABEL}=1", "--build-arg", f"DEV_UID={uid}", "--build-arg", f"DEV_GID={gid}",
str(context)]
def run_args(engine: str, tag: str, root: Path, env: dict[str, str], dri: Path, gitconfig: Path,
udev: Path | None = None, gate: bool = False) -> list[str]:
"""`<engine> run` for the background container, without the name and config labels. udev is the
host's udev database, mounted read-only when there is one. The gate's container (gate) publishes
no port and takes none of the dev loop's media or FFmpeg settings, so neither ever replaces the
other by changing its configuration: a gate run through the dev loop's container without the dev
loop's exact environment replaced it, and staging with it (process review F1, 2026-10-26)."""
publish = env.get("ORPHEUM_DEV_PUBLISH", DEFAULT_PUBLISH)
if gate:
env = {key: value for key, value in env.items() if key not in ("ORPHEUM_DEV_MEDIA", "ORPHEUM_FFMPEG_LOCAL")}
args = [engine, "run", "--detach", "--init", "--label", f"{LABEL}=1",
"--mount", f"type=bind,src={root},dst={root}",
"--env", f"DEV_LISTEN={CONTAINER_LISTEN}",
# tc shapes the container's own loopback for make test-acceptance (D252 §1).
"--cap-add", "NET_ADMIN"]
if engine == "podman":
args.append("--userns=keep-id") # rootless podman: map the host user to the same uid inside
cache_dir = env.get(CACHE_DIR_ENV)
for volume, path in VOLUMES.items():
if cache_dir:
args += ["--mount", f"type=bind,src={Path(cache_dir).resolve() / volume},dst={path}"]
else:
args += ["--mount", f"type=volume,src={volume},dst={path}"]
for port in () if gate else (SERVER_PORT, VITE_PORT):
args += ["--publish", f"{publish}:{port}:{port}"]
media = env.get("ORPHEUM_DEV_MEDIA")
if media:
media_path = Path(media).resolve()
args += ["--mount", f"type=bind,src={media_path},dst={media_path},readonly",
"--env", f"ORPHEUM_DEV_MEDIA={media_path}"]
local_ffmpeg = env.get("ORPHEUM_FFMPEG_LOCAL")
if local_ffmpeg:
local_path = Path(local_ffmpeg).resolve()
args += ["--mount", f"type=bind,src={local_path},dst={local_path},readonly",
"--env", f"ORPHEUM_FFMPEG_LOCAL={local_path}"]
if udev is not None and udev.is_dir(): # so the node can follow a ZFS pool to its disks (D240 §5)
args += ["--mount", f"type=bind,src={udev},dst={udev},readonly"]
if dri.is_dir():
args += ["--device", str(dri)]
for group in dri_groups(dri):
args += ["--group-add", str(group)]
if gitconfig.is_file(): # so a commit made inside is made as you
args += ["--mount", f"type=bind,src={gitconfig},dst={HOME}/.gitconfig,readonly"]
return args + [tag, "sleep", "infinity"]
def config_hash(args: list[str]) -> str:
return hashlib.sha256("\0".join(args).encode()).hexdigest()[:16]
def exec_args(engine: str, name: str, root: Path, cwd: Path, command: list[str], env: dict[str, str],
tty: bool) -> list[str]:
"""`<engine> exec` running command in the container, in cwd when it is inside the clone."""
workdir = cwd if cwd == root or root in cwd.parents else root
args = [engine, "exec", "--interactive", "--workdir", str(workdir)]
if tty:
args.append("--tty")
for key in sorted(env):
if key in FORWARDED_ENV or key.startswith(FORWARDED_ENV_PREFIXES):
args += ["--env", key]
return args + [name] + (command or ["bash"])
def quiet(args: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(args, capture_output=True, text=True, check=False)
class ImageNeeded(Exception):
"""The image is missing and NO_BUILD_ENV forbids building it here."""
def ensure_image(engine: str, root: Path, uid: int, gid: int, may_build: bool = True) -> str:
tag = image_tag(root, uid, gid)
if quiet([engine, "image", "inspect", tag]).returncode == 0:
return tag
if not may_build:
raise ImageNeeded(tag)
print(f"dev: building {tag} from {CONTAINERFILE} (first run, or a pin changed)", file=sys.stderr)
with tempfile.TemporaryDirectory(prefix="orpheum-dev-") as tmp:
context = Path(tmp)
for rel in BUILD_INPUTS:
(context / rel).parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(root / rel, context / rel)
subprocess.run(build_args(engine, tag, context, uid, gid), check=True)
return tag
def ensure_container(engine: str, name: str, args: list[str]) -> None:
config = config_hash(args)
state = quiet([engine, "inspect", "--format", f'{{{{index .Config.Labels "{CONFIG_LABEL}"}}}} {{{{.State.Running}}}}',
name])
if state.returncode == 0:
if state.stdout.split() == [config, "true"]:
return
print(f"dev: replacing {name}: its image or configuration changed, or it had stopped", file=sys.stderr)
quiet([engine, "rm", "--force", name])
started = [*args[:2], "--name", name, "--label", f"{CONFIG_LABEL}={config}", *args[2:]]
subprocess.run(started, check=True, stdout=subprocess.DEVNULL)
subprocess.run(loopback_args(args[0], name), check=True, stdout=subprocess.DEVNULL)
# A real link's packet size on the container's loopback, which the browser tier and the
# acceptance cross: at its own 64 KB, a TCP packet of the film held a voice packet behind it for a
# tenth of a second on the acceptance's 5 Mbit/s link, which no real link does (D262 §1). Set as
# root once the container starts: iproute2's ip drops a file capability when the developer runs it.
LOOPBACK_MTU = 1500
def loopback_args(engine: str, name: str) -> list[str]:
"""Sets the container's loopback to LOOPBACK_MTU, and the size the kernel batches packets to."""
return [engine, "exec", "--user", "0", name, "ip", "link", "set", "dev", "lo",
"mtu", str(LOOPBACK_MTU), "gso_max_size", str(LOOPBACK_MTU)]
def main(argv: list[str]) -> int:
env = dict(os.environ)
engine = find_engine(env)
if engine is None:
print("dev: no container engine found. Install Docker (https://docs.docker.com/engine/install/)"
" or Podman, or name one in ORPHEUM_DEV_ENGINE.", file=sys.stderr)
return 127
uid, gid = os.getuid(), os.getgid()
if uid == 0:
print("dev: run it as your own user, not root: the container's user takes your uid.", file=sys.stderr)
return 2
gate = argv[:1] == ["--gate"]
if gate:
argv = argv[1:]
name = container_name(ROOT, gate)
if argv == ["--stop"]:
return quiet([engine, "rm", "--force", name]).returncode
if argv == ["--image-tag"]:
print(image_tag(ROOT, uid, gid))
return 0
cache_dir = env.get(CACHE_DIR_ENV)
if cache_dir:
for volume in VOLUMES:
(Path(cache_dir) / volume).mkdir(parents=True, exist_ok=True)
try:
tag = ensure_image(engine, ROOT, uid, gid, may_build=env.get(NO_BUILD_ENV) != "1")
ensure_container(engine, name, run_args(engine, tag, ROOT, env, Path("/dev/dri"),
Path.home() / ".gitconfig", UDEV_DATABASE, gate))
except ImageNeeded as needed:
print(f"dev: the development image {needed} needs building (a pin changed); run `./dev true` once, "
"outside the hook, then try again", file=sys.stderr)
return NEEDS_BUILD
except subprocess.CalledProcessError as failed:
print(f"dev: {' '.join(failed.cmd[:2])} failed (exit {failed.returncode}); its output is above",
file=sys.stderr)
return failed.returncode
tty = sys.stdin.isatty() and sys.stdout.isatty()
command = exec_args(engine, name, ROOT, Path.cwd().resolve(), argv, env, tty)
os.execvp(command[0], command)
return 0 # not reached: execvp replaces this process
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))