@0perator/operator 0.1.349 → 0.1.350
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.
- package/dist/cli.js +7 -2
- package/dist/config/toolchain.js +151 -0
- package/dist/enterprise/cli.js +48 -1
- package/dist/gateway-cli.js +46 -4
- package/dist/models/bench.js +12 -7
- package/dist/models/switch.js +82 -29
- package/dist/toolchain/manifest.json +222 -0
- package/dist/toolchain/toolchain.py +2723 -0
- package/dist/toolchain-cli.js +26 -0
- package/dist/tools/computer.js +8 -0
- package/dist/tools/contract.js +9 -0
- package/dist/tools/git-pr.js +1 -0
- package/dist/tools/monitoring-tools.js +3 -0
- package/dist/tools/registry.js +34 -0
- package/dist/tools/wave-tools.js +4 -0
- package/dist/tools/wave2-tools.js +7 -0
- package/package.json +2 -2
|
@@ -0,0 +1,2723 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Operator toolchain: reviewed, verified llama.cpp builds in an Operator-owned store, one pointer per consumer.
|
|
3
|
+
|
|
4
|
+
toolchain install [PKG[@previous] ...] [--activate C,... | --no-activate] [--offline --cache DIR] [--witness]
|
|
5
|
+
toolchain activate GEN --consumer C[,C...] --reason TEXT [--force-flags]
|
|
6
|
+
toolchain rollback --consumer C[,C...] --reason TEXT [--to GEN]
|
|
7
|
+
toolchain which BIN --consumer C [--resolve]
|
|
8
|
+
toolchain verify [--deep] [--probe] [--quiet]
|
|
9
|
+
toolchain status
|
|
10
|
+
toolchain gc [--keep 3] [--apply]
|
|
11
|
+
toolchain migrate --from-hermes [--dry-run | --undo] (JL2: ~/.operator/tools is a link into ~/.hermes/tools)
|
|
12
|
+
toolchain migrate --replace-tools-dir [--undo] (JL1: ~/.operator/tools is an unused real directory)
|
|
13
|
+
toolchain smoke --bin PATH [--gguf PATH] [--metal] [--via-launchd LABEL] [--ready-timeout SECONDS]
|
|
14
|
+
toolchain gate (--url URL --suite quick|aurora | --input FILE) (--baseline OUT | --compare FILE)
|
|
15
|
+
toolchain manifest check [FILE]
|
|
16
|
+
|
|
17
|
+
The root is --root, else $OPERATOR_TOOLCHAIN_HOME, else $OPERATOR_HOME/toolchain (~/.operator/toolchain):
|
|
18
|
+
.lock, .lock.owner flock for every mutation; a box with .lock is managed
|
|
19
|
+
bin/, manifest.applied.json the CLI and manifest this box last applied
|
|
20
|
+
cas/sha256/<hex> verified archives and fixtures
|
|
21
|
+
store/<entry>-<sha12>/ sealed entries (dirs 0555, files a-w) holding .toolchain-entry.json
|
|
22
|
+
generations/<N>/ immutable symlink farms with Hermes-schema facts.json and generation.json
|
|
23
|
+
consumers/<c> -> ../generations/<N>, the only mutable pointers (aurora, portal, arena)
|
|
24
|
+
history.jsonl, state.json, baselines/, .trash/
|
|
25
|
+
Exit codes: 0 ok, 1 error, 2 drift (verify), 78 unresolved or refused (EX_CONFIG, which supervise-gateway.sh parks on).
|
|
26
|
+
One stdlib file for /usr/bin/python3 -I (3.9.6 on both boxes): -I drops the script dir from sys.path.
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import argparse, contextlib, datetime as dt, fcntl, hashlib, http.client, json, os, pathlib, platform, plistlib, pwd, re, shutil, signal, socket, stat, struct, subprocess, sys, tarfile, tempfile, time, urllib.error, urllib.parse, urllib.request, zipfile
|
|
31
|
+
|
|
32
|
+
HERE = pathlib.Path(__file__).resolve().parent
|
|
33
|
+
SCHEMA = "operator.toolchain/1"
|
|
34
|
+
GEN_SCHEMA = "operator.toolchain.generation/1"
|
|
35
|
+
FACTS_SCHEMA = 1
|
|
36
|
+
CONSUMERS = ("aurora", "portal", "arena")
|
|
37
|
+
MANIFEST_CONSUMERS = CONSUMERS + ("agent",) # 'agent' is reserved for v2: rows may name it, nothing activates it
|
|
38
|
+
EX_OK, EX_ERROR, EX_DRIFT, EX_REFUSED = 0, 1, 2, 78
|
|
39
|
+
ENTRY_META = ".toolchain-entry.json"
|
|
40
|
+
UA = "operator-toolchain/1 (+urllib)"
|
|
41
|
+
LOOPBACK = ("127.0.0.1", "localhost", "::1")
|
|
42
|
+
HEX64 = re.compile(r"[0-9a-f]{64}")
|
|
43
|
+
FORMATS = ("tar.gz", "tgz", "tar.xz", "zip")
|
|
44
|
+
ROLES = ("payload", "checksums", "signature", "certificate")
|
|
45
|
+
CODESIGN_KINDS = ("adhoc", "developer-id", "unsigned-bundle", "none")
|
|
46
|
+
FLIP_ACTIONS = ("activate", "rollback", "migrate")
|
|
47
|
+
MIGRATE_PACKAGE = "llamacpp-metal"
|
|
48
|
+
TARGET_ARCH = {"darwin-arm64": "arm64", "darwin-x64": "x86_64"}
|
|
49
|
+
# Flags operator-runtime/gateway/server.cjs passes besides the preset keys (temp becomes --temperature).
|
|
50
|
+
GATEWAY_FLAGS = ("--host", "--port", "--model", "--alias", "--jinja", "--metrics", "--slots", "--no-webui")
|
|
51
|
+
# portal/src/agent/serving-defaults.ts LLAMA_SERVER_DEFAULTS: added to every portal recipe that lacks them.
|
|
52
|
+
PORTAL_DEFAULT_FLAGS = ("--cache-ram", "--cache-type-k", "--cache-type-v")
|
|
53
|
+
SHIM = """#!/bin/sh
|
|
54
|
+
# Runs the toolchain CLI with the system interpreter, isolated from PYTHON* and the caller's cwd.
|
|
55
|
+
here="$(cd "$(dirname "$0")" && pwd)"
|
|
56
|
+
[ -f "$here/toolchain.py" ] || here="$(dirname "$here")"
|
|
57
|
+
exec /usr/bin/python3 -I "$here/toolchain.py" "$@"
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ToolchainError(Exception):
|
|
62
|
+
code = EX_ERROR
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Refused(ToolchainError):
|
|
66
|
+
code = EX_REFUSED
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Mismatch(Refused):
|
|
70
|
+
"""Bytes that do not match their pin: never retried, never kept."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def now() -> str:
|
|
74
|
+
return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def utc_today() -> dt.date:
|
|
78
|
+
return dt.datetime.now(dt.timezone.utc).date()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def parse_date(s) -> dt.date:
|
|
82
|
+
return dt.date.fromisoformat(str(s)[:10])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def parse_ts(s) -> dt.datetime:
|
|
86
|
+
t = dt.datetime.fromisoformat(str(s).replace("Z", "+00:00"))
|
|
87
|
+
return t if t.tzinfo else t.replace(tzinfo=dt.timezone.utc)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def say(msg: str) -> None:
|
|
91
|
+
print(msg, file=sys.stderr, flush=True)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def first_line(text: str) -> str:
|
|
95
|
+
for line in (text or "").splitlines():
|
|
96
|
+
if line.strip():
|
|
97
|
+
return line.strip()[:240]
|
|
98
|
+
return ""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def run(cmd, timeout: float = 60, **kw) -> subprocess.CompletedProcess:
|
|
102
|
+
argv = [os.fspath(c) if isinstance(c, os.PathLike) else str(c) for c in cmd]
|
|
103
|
+
return subprocess.run(argv, capture_output=True, text=True, errors="replace", timeout=timeout, **kw)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ── paths and guards ────────────────────────────────────────────────────────
|
|
107
|
+
|
|
108
|
+
def real_home() -> pathlib.Path:
|
|
109
|
+
return pathlib.Path(pwd.getpwuid(os.getuid()).pw_dir)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def env_home() -> pathlib.Path:
|
|
113
|
+
return pathlib.Path(os.environ.get("HOME") or real_home())
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def operator_home() -> pathlib.Path:
|
|
117
|
+
return pathlib.Path(os.path.abspath(os.environ.get("OPERATOR_HOME") or env_home() / ".operator"))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def kode_home() -> pathlib.Path:
|
|
121
|
+
return pathlib.Path(os.path.abspath(os.environ.get("KODE_HOME") or env_home() / ".axe" / "operator"))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def portal_home() -> pathlib.Path:
|
|
125
|
+
return pathlib.Path(os.path.abspath(os.environ.get("PORTAL_HOME") or env_home() / ".axe" / "portal"))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def default_root() -> pathlib.Path:
|
|
129
|
+
return pathlib.Path(os.path.abspath(os.environ.get("OPERATOR_TOOLCHAIN_HOME") or operator_home() / "toolchain"))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_mode() -> bool:
|
|
133
|
+
return os.environ.get("OPERATOR_TOOLCHAIN_TEST") == "1"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def within(path, base) -> bool:
|
|
137
|
+
path, base = os.fspath(path), os.fspath(base).rstrip(os.sep)
|
|
138
|
+
return path == base or path.startswith(base + os.sep)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def hermes_dirs() -> list:
|
|
142
|
+
return sorted({os.path.realpath(h / ".hermes") for h in (real_home(), env_home())})
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def live_dirs() -> list:
|
|
146
|
+
"""The real box's state, which a test run may never write: its runtime, KODE_HOME, portal and launchd homes."""
|
|
147
|
+
h = real_home()
|
|
148
|
+
return [os.path.realpath(h / p) for p in (".operator", ".axe/operator", ".axe/portal", "Library/LaunchAgents")]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def guard_write(path) -> None:
|
|
152
|
+
"""Every write path is checked against ~/.hermes, and in test mode against the live homes. The last component is not
|
|
153
|
+
resolved: replacing ~/.operator/tools (a link into ~/.hermes) writes ~/.operator, not Hermes's tree."""
|
|
154
|
+
p = os.path.abspath(os.fspath(path))
|
|
155
|
+
full = os.path.join(os.path.realpath(os.path.dirname(p)), os.path.basename(p))
|
|
156
|
+
for h in hermes_dirs():
|
|
157
|
+
if within(full, h):
|
|
158
|
+
raise Refused(f"refusing to write under {h}: {p}")
|
|
159
|
+
if test_mode():
|
|
160
|
+
for h in live_dirs():
|
|
161
|
+
if within(full, h):
|
|
162
|
+
raise Refused(f"refusing to write live state in test mode: {p}")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def resolve_root(arg) -> pathlib.Path:
|
|
166
|
+
root = pathlib.Path(os.path.abspath(os.path.expanduser(arg))) if arg else default_root()
|
|
167
|
+
real = os.path.realpath(root)
|
|
168
|
+
for h in hermes_dirs():
|
|
169
|
+
if within(real, h):
|
|
170
|
+
raise Refused(f"refusing root {root}: it resolves under {h}")
|
|
171
|
+
if test_mode():
|
|
172
|
+
for h in live_dirs():
|
|
173
|
+
if within(real, h):
|
|
174
|
+
raise Refused(f"refusing root {root} in test mode: it resolves under {h}")
|
|
175
|
+
return root
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ── durable files ───────────────────────────────────────────────────────────
|
|
179
|
+
|
|
180
|
+
def sha256_file(path) -> str:
|
|
181
|
+
h = hashlib.sha256()
|
|
182
|
+
with open(path, "rb") as f:
|
|
183
|
+
for block in iter(lambda: f.read(1 << 20), b""):
|
|
184
|
+
h.update(block)
|
|
185
|
+
return h.hexdigest()
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def fsync_path(path) -> None:
|
|
189
|
+
fd = os.open(path, os.O_RDONLY)
|
|
190
|
+
try:
|
|
191
|
+
os.fsync(fd)
|
|
192
|
+
finally:
|
|
193
|
+
os.close(fd)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def full_fsync(path) -> None:
|
|
197
|
+
"""fsync on macOS stops at the drive's cache; F_FULLFSYNC flushes it. Called once per commit."""
|
|
198
|
+
fd = os.open(path, os.O_RDONLY)
|
|
199
|
+
try:
|
|
200
|
+
fcntl.fcntl(fd, getattr(fcntl, "F_FULLFSYNC", 51))
|
|
201
|
+
except OSError:
|
|
202
|
+
os.fsync(fd)
|
|
203
|
+
finally:
|
|
204
|
+
os.close(fd)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def durable_write(path, data: bytes, mode: int = 0o644) -> None:
|
|
208
|
+
path = pathlib.Path(path)
|
|
209
|
+
guard_write(path)
|
|
210
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
211
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
|
|
212
|
+
try:
|
|
213
|
+
with os.fdopen(fd, "wb") as f:
|
|
214
|
+
f.write(data)
|
|
215
|
+
f.flush()
|
|
216
|
+
os.fchmod(f.fileno(), mode)
|
|
217
|
+
os.fsync(f.fileno())
|
|
218
|
+
os.replace(tmp, path)
|
|
219
|
+
fsync_path(path.parent)
|
|
220
|
+
finally:
|
|
221
|
+
if os.path.lexists(tmp):
|
|
222
|
+
os.unlink(tmp)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def canonical(obj) -> bytes:
|
|
226
|
+
"""pm's state-file bytes: sorted keys, indent 2, trailing newline."""
|
|
227
|
+
return (json.dumps(obj, indent=2, sort_keys=True) + "\n").encode()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def read_json(path, default=None):
|
|
231
|
+
try:
|
|
232
|
+
return json.loads(pathlib.Path(path).read_text())
|
|
233
|
+
except (OSError, ValueError):
|
|
234
|
+
return default
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def force_rmtree(path, root=None) -> None:
|
|
238
|
+
"""rmtree that first makes sealed dirs writable; with `root`, refuses anything outside it."""
|
|
239
|
+
path = pathlib.Path(path)
|
|
240
|
+
if not os.path.lexists(path):
|
|
241
|
+
return
|
|
242
|
+
guard_write(path)
|
|
243
|
+
if root is not None and not within(os.path.join(os.path.realpath(path.parent), path.name), os.path.realpath(root)):
|
|
244
|
+
raise Refused(f"refusing to delete outside {root}: {path}")
|
|
245
|
+
if path.is_symlink() or not path.is_dir():
|
|
246
|
+
path.unlink()
|
|
247
|
+
return
|
|
248
|
+
for d, _, _ in os.walk(path):
|
|
249
|
+
os.chmod(d, 0o755)
|
|
250
|
+
shutil.rmtree(path)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def fsync_tree(top) -> None:
|
|
254
|
+
for d, dirs, files in os.walk(top):
|
|
255
|
+
for name in files:
|
|
256
|
+
p = os.path.join(d, name)
|
|
257
|
+
if not os.path.islink(p):
|
|
258
|
+
fsync_path(p)
|
|
259
|
+
fsync_path(d)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def seal(top) -> None:
|
|
263
|
+
"""Files lose every write bit and dirs become 0555, bottom-up. The top dir stays writable: macOS needs write on a
|
|
264
|
+
directory to rename it into another parent, so the caller seals it after the rename."""
|
|
265
|
+
for d, dirs, files in os.walk(top, topdown=False):
|
|
266
|
+
for name in files:
|
|
267
|
+
p = os.path.join(d, name)
|
|
268
|
+
st = os.lstat(p)
|
|
269
|
+
if stat.S_ISREG(st.st_mode):
|
|
270
|
+
os.chmod(p, stat.S_IMODE(st.st_mode) & ~0o222)
|
|
271
|
+
if os.path.realpath(d) != os.path.realpath(top):
|
|
272
|
+
os.chmod(d, 0o555)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def fault(point: str) -> None:
|
|
276
|
+
if test_mode() and os.environ.get("TOOLCHAIN_FAULT_AT") == point:
|
|
277
|
+
sys.stdout.flush()
|
|
278
|
+
sys.stderr.flush()
|
|
279
|
+
os._exit(137)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
# ── lock ────────────────────────────────────────────────────────────────────
|
|
283
|
+
|
|
284
|
+
def lock_is_current(fd: int, lock: pathlib.Path) -> bool:
|
|
285
|
+
try:
|
|
286
|
+
held, named = os.fstat(fd), os.stat(lock)
|
|
287
|
+
except FileNotFoundError:
|
|
288
|
+
return False
|
|
289
|
+
return (held.st_dev, held.st_ino) == (named.st_dev, named.st_ino)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def ever_activated(root: pathlib.Path) -> bool:
|
|
293
|
+
return bool(consumer_names(root)) or any(r.get("action") in FLIP_ACTIONS for r in read_history(root))
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@contextlib.contextmanager
|
|
297
|
+
def mutation(root: pathlib.Path):
|
|
298
|
+
"""The .lock file is also the managed marker: gateways and accessors that find it fail closed (78) instead of using
|
|
299
|
+
their legacy chain. So a mutation that fails right after creating it, before any consumer was ever activated, takes it
|
|
300
|
+
away again, under the flock; a waiter that locked the removed file sees that and locks the new one."""
|
|
301
|
+
lock = root / ".lock"
|
|
302
|
+
guard_write(lock)
|
|
303
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
304
|
+
started, told = time.monotonic(), False
|
|
305
|
+
while True:
|
|
306
|
+
created = not os.path.lexists(lock)
|
|
307
|
+
fd = os.open(lock, os.O_CREAT | os.O_RDWR, 0o644)
|
|
308
|
+
while True:
|
|
309
|
+
try:
|
|
310
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
311
|
+
break
|
|
312
|
+
except BlockingIOError:
|
|
313
|
+
if not told and time.monotonic() - started > 2:
|
|
314
|
+
owner = read_json(root / ".lock.owner") or {}
|
|
315
|
+
say(f"waiting for pid {owner.get('pid', '?')}: toolchain {' '.join(owner.get('argv') or [])}")
|
|
316
|
+
told = True
|
|
317
|
+
time.sleep(0.05)
|
|
318
|
+
if lock_is_current(fd, lock):
|
|
319
|
+
break
|
|
320
|
+
os.close(fd)
|
|
321
|
+
try:
|
|
322
|
+
durable_write(root / ".lock.owner", canonical({"pid": os.getpid(), "argv": sys.argv[1:], "ts": now()}))
|
|
323
|
+
sweep(root)
|
|
324
|
+
yield
|
|
325
|
+
except BaseException:
|
|
326
|
+
if created and not ever_activated(root):
|
|
327
|
+
with contextlib.suppress(OSError):
|
|
328
|
+
lock.unlink()
|
|
329
|
+
raise
|
|
330
|
+
finally:
|
|
331
|
+
with contextlib.suppress(OSError):
|
|
332
|
+
(root / ".lock.owner").unlink()
|
|
333
|
+
os.close(fd)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def sweep(root: pathlib.Path) -> None:
|
|
337
|
+
"""Leftovers of a killed run. Safe to remove: the caller holds the lock."""
|
|
338
|
+
for parent, pattern in (("store", ".staging-*"), ("generations", ".tmp-*"), (".trash", "*"), ("cas/partials", "*")):
|
|
339
|
+
for p in (root / parent).glob(pattern):
|
|
340
|
+
force_rmtree(p, root)
|
|
341
|
+
for p in (root / "consumers").glob(".*.tmp"):
|
|
342
|
+
guard_write(p)
|
|
343
|
+
p.unlink()
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def history(root: pathlib.Path, action: str, **fields) -> None:
|
|
347
|
+
rec = {"ts": now(), "user": pwd.getpwuid(os.getuid()).pw_name, "host": socket.gethostname(), "argv": sys.argv[1:],
|
|
348
|
+
"action": action, "consumer": None, "from": None, "to": None, "manifest_serial": None, "reason": None,
|
|
349
|
+
"result": "ok", **fields}
|
|
350
|
+
path = root / "history.jsonl"
|
|
351
|
+
guard_write(path)
|
|
352
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
|
|
353
|
+
try:
|
|
354
|
+
os.write(fd, (json.dumps(rec, sort_keys=True) + "\n").encode())
|
|
355
|
+
os.fsync(fd)
|
|
356
|
+
finally:
|
|
357
|
+
os.close(fd)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def read_history(root: pathlib.Path) -> list:
|
|
361
|
+
out = []
|
|
362
|
+
try:
|
|
363
|
+
lines = (root / "history.jsonl").read_text().splitlines()
|
|
364
|
+
except OSError:
|
|
365
|
+
return out
|
|
366
|
+
for line in lines:
|
|
367
|
+
with contextlib.suppress(ValueError):
|
|
368
|
+
rec = json.loads(line)
|
|
369
|
+
if isinstance(rec, dict):
|
|
370
|
+
out.append(rec)
|
|
371
|
+
return out
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
# ── manifest ────────────────────────────────────────────────────────────────
|
|
375
|
+
|
|
376
|
+
def manifest_file(arg) -> pathlib.Path:
|
|
377
|
+
if arg:
|
|
378
|
+
return pathlib.Path(arg)
|
|
379
|
+
if os.environ.get("OPERATOR_TOOLCHAIN_MANIFEST"):
|
|
380
|
+
return pathlib.Path(os.environ["OPERATOR_TOOLCHAIN_MANIFEST"])
|
|
381
|
+
for p in (HERE / "manifest.json", HERE.parent / "manifest.applied.json"):
|
|
382
|
+
if p.is_file():
|
|
383
|
+
return p
|
|
384
|
+
raise ToolchainError("no manifest found: pass --manifest FILE")
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def load_manifest(path: pathlib.Path) -> dict:
|
|
388
|
+
try:
|
|
389
|
+
data = json.loads(path.read_text())
|
|
390
|
+
except (OSError, ValueError) as e:
|
|
391
|
+
raise ToolchainError(f"cannot read manifest {path}: {e}")
|
|
392
|
+
if not isinstance(data, dict) or data.get("schema") != SCHEMA:
|
|
393
|
+
raise ToolchainError(f"{path}: schema is not {SCHEMA}")
|
|
394
|
+
return data
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def row_for(manifest: dict, spec: str) -> tuple:
|
|
398
|
+
"""(name, 'current'|'previous', row). A previous row inherits every field it does not set from its package."""
|
|
399
|
+
name, _, which = spec.partition("@")
|
|
400
|
+
pkg = (manifest.get("packages") or {}).get(name)
|
|
401
|
+
if not isinstance(pkg, dict):
|
|
402
|
+
raise Refused(f"unknown package {name!r}")
|
|
403
|
+
base = {k: v for k, v in pkg.items() if k != "previous"}
|
|
404
|
+
if which == "":
|
|
405
|
+
return name, "current", base
|
|
406
|
+
if which != "previous":
|
|
407
|
+
raise Refused(f"unknown row {spec!r}: use NAME or NAME@previous")
|
|
408
|
+
if not isinstance(pkg.get("previous"), dict):
|
|
409
|
+
raise Refused(f"{name} has no previous row")
|
|
410
|
+
return name, "previous", {**base, **pkg["previous"]}
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def manifest_rows(manifest: dict) -> list:
|
|
414
|
+
out = []
|
|
415
|
+
for name, pkg in sorted((manifest.get("packages") or {}).items()):
|
|
416
|
+
out.append(row_for(manifest, name))
|
|
417
|
+
if isinstance(pkg.get("previous"), dict):
|
|
418
|
+
out.append(row_for(manifest, f"{name}@previous"))
|
|
419
|
+
return out
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def box_target() -> str:
|
|
423
|
+
arch = {"arm64": "arm64", "aarch64": "arm64", "x86_64": "x64", "amd64": "x64"}.get(platform.machine().lower(), platform.machine())
|
|
424
|
+
return f"{'darwin' if sys.platform == 'darwin' else sys.platform}-{arch}"
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def box_name() -> str:
|
|
428
|
+
return (os.environ.get("OPERATOR_BOX") or socket.gethostname().split(".")[0]).lower()
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def artifacts_for(row: dict, target: str) -> list:
|
|
432
|
+
arts = row.get("artifacts") or {}
|
|
433
|
+
found = arts.get(target, arts.get("any"))
|
|
434
|
+
if found is None:
|
|
435
|
+
return []
|
|
436
|
+
return [dict(a) for a in (found if isinstance(found, list) else [found])]
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def role(art: dict) -> str:
|
|
440
|
+
return art.get("role", "payload")
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def store_name(row: dict, target: str) -> str:
|
|
444
|
+
payloads = [a for a in artifacts_for(row, target) if role(a) == "payload"]
|
|
445
|
+
if not payloads:
|
|
446
|
+
raise Refused(f"{row.get('entry')}: no payload artifact for {target}")
|
|
447
|
+
return f"{row['entry']}-{payloads[0]['sha256'][:12]}"
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def row_matching(manifest: dict, pkg: dict) -> tuple:
|
|
451
|
+
"""The manifest row a generation's package was realized from, or (None, None)."""
|
|
452
|
+
for name, which, row in manifest_rows(manifest):
|
|
453
|
+
if (row.get("entry"), str(row.get("version")), row.get("tree")) != (pkg.get("entry"), str(pkg.get("version")), pkg.get("tree")):
|
|
454
|
+
continue
|
|
455
|
+
with contextlib.suppress(ToolchainError, KeyError):
|
|
456
|
+
if store_name(row, pkg.get("target") or box_target()) == pkg.get("store_entry"):
|
|
457
|
+
return which, row
|
|
458
|
+
return None, None
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
# ── fetch ───────────────────────────────────────────────────────────────────
|
|
462
|
+
|
|
463
|
+
def host_allowed(host: str, hosts) -> bool:
|
|
464
|
+
host = (host or "").lower()
|
|
465
|
+
for h in hosts or ():
|
|
466
|
+
h = str(h).lower()
|
|
467
|
+
if host == h or (h.startswith("*.") and host.endswith(h[1:])):
|
|
468
|
+
return True
|
|
469
|
+
return False
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def check_url(url: str, hosts) -> None:
|
|
473
|
+
u = urllib.parse.urlsplit(url)
|
|
474
|
+
host = u.hostname or ""
|
|
475
|
+
if u.scheme != "https" and not (u.scheme == "http" and test_mode() and host in LOOPBACK):
|
|
476
|
+
raise Refused(f"refusing non-https url: {url}")
|
|
477
|
+
if u.username is not None or u.password is not None:
|
|
478
|
+
raise Refused(f"refusing url with userinfo: {url}")
|
|
479
|
+
if not host_allowed(host, hosts):
|
|
480
|
+
raise Refused(f"refusing off-list host {host!r}: {url}")
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
class _CheckedRedirects(urllib.request.HTTPRedirectHandler):
|
|
484
|
+
"""Every redirect hop must be https and on the manifest's host list."""
|
|
485
|
+
|
|
486
|
+
def __init__(self, hosts):
|
|
487
|
+
super().__init__()
|
|
488
|
+
self.hosts = hosts
|
|
489
|
+
|
|
490
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
491
|
+
check_url(newurl, self.hosts)
|
|
492
|
+
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def retry_delay() -> float:
|
|
496
|
+
return float(os.environ.get("OPERATOR_TOOLCHAIN_RETRY_DELAY", "2")) if test_mode() else 2.0
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def download(url: str, sha: str, size, hosts, dest: pathlib.Path) -> None:
|
|
500
|
+
check_url(url, hosts)
|
|
501
|
+
handlers = [_CheckedRedirects(hosts)] + ([urllib.request.ProxyHandler({})] if test_mode() else [])
|
|
502
|
+
opener = urllib.request.build_opener(*handlers)
|
|
503
|
+
last = ""
|
|
504
|
+
for attempt in range(4):
|
|
505
|
+
wait = min(30.0, retry_delay() * 2 ** attempt)
|
|
506
|
+
try:
|
|
507
|
+
_download_once(opener, url, sha, size, hosts, dest)
|
|
508
|
+
return
|
|
509
|
+
except urllib.error.HTTPError as e:
|
|
510
|
+
if e.code not in (408, 429) and e.code < 500:
|
|
511
|
+
raise ToolchainError(f"fetch {url}: HTTP {e.code}")
|
|
512
|
+
after = (e.headers or {}).get("Retry-After") or ""
|
|
513
|
+
if after.isdigit():
|
|
514
|
+
wait = min(30.0, float(after))
|
|
515
|
+
last = f"HTTP {e.code}"
|
|
516
|
+
except (urllib.error.URLError, http.client.HTTPException, OSError) as e:
|
|
517
|
+
last = str(getattr(e, "reason", "") or e) or type(e).__name__
|
|
518
|
+
if attempt < 3:
|
|
519
|
+
say(f"fetch {url}: {last}; retrying in {wait:.0f}s")
|
|
520
|
+
time.sleep(wait)
|
|
521
|
+
raise ToolchainError(f"fetch {url} failed after 4 attempts: {last}")
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _download_once(opener, url: str, sha: str, size, hosts, dest: pathlib.Path) -> None:
|
|
525
|
+
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
|
526
|
+
h, n = hashlib.sha256(), 0
|
|
527
|
+
with opener.open(req, timeout=60) as r:
|
|
528
|
+
check_url(r.geturl(), hosts)
|
|
529
|
+
declared = r.headers.get("Content-Length")
|
|
530
|
+
with open(dest, "wb") as f:
|
|
531
|
+
for block in iter(lambda: r.read(1 << 20), b""):
|
|
532
|
+
n += len(block)
|
|
533
|
+
if size is not None and n > size:
|
|
534
|
+
raise Mismatch(f"{url}: body is longer than the pinned {size} bytes")
|
|
535
|
+
h.update(block)
|
|
536
|
+
f.write(block)
|
|
537
|
+
f.flush()
|
|
538
|
+
os.fsync(f.fileno())
|
|
539
|
+
# http.client's read(amt) returns short at EOF instead of raising, so a cut transfer would read as tampering.
|
|
540
|
+
if declared and declared.isdigit() and n < int(declared):
|
|
541
|
+
raise http.client.IncompleteRead(b"", int(declared) - n)
|
|
542
|
+
if size is not None and n != size:
|
|
543
|
+
raise Mismatch(f"{url}: got {n} bytes, the manifest pins {size}")
|
|
544
|
+
if h.hexdigest() != sha:
|
|
545
|
+
raise Mismatch(f"{url}: sha256 {h.hexdigest()} does not match the pin {sha}")
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def blob_ok(path: pathlib.Path, sha: str, size) -> bool:
|
|
549
|
+
try:
|
|
550
|
+
return (size is None or path.stat().st_size == size) and sha256_file(path) == sha
|
|
551
|
+
except OSError:
|
|
552
|
+
return False
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def copy_blob(src: pathlib.Path, dest: pathlib.Path, sha: str) -> None:
|
|
556
|
+
guard_write(dest)
|
|
557
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
558
|
+
tmp = dest.with_name(f".{sha}.{os.getpid()}.tmp")
|
|
559
|
+
shutil.copyfile(src, tmp)
|
|
560
|
+
fsync_path(tmp)
|
|
561
|
+
os.replace(tmp, dest)
|
|
562
|
+
fsync_path(dest.parent)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def obtain(art: dict, cas: pathlib.Path, hosts, *, cache=None, offline=False, also_read=()) -> tuple:
|
|
566
|
+
"""(path, source) of a verified artifact: our CAS, then --cache, then upstream. Bytes that fail the pin are dropped."""
|
|
567
|
+
sha, size = art["sha256"], art.get("size")
|
|
568
|
+
blob = cas / "sha256" / sha
|
|
569
|
+
for p in [blob] + [pathlib.Path(d) / "sha256" / sha for d in also_read]:
|
|
570
|
+
if p.is_file():
|
|
571
|
+
if blob_ok(p, sha, size):
|
|
572
|
+
if p != blob:
|
|
573
|
+
copy_blob(p, blob, sha)
|
|
574
|
+
return blob, "cas"
|
|
575
|
+
if p == blob:
|
|
576
|
+
say(f"cas {sha[:12]}: bytes do not match the pin, refetching")
|
|
577
|
+
guard_write(blob)
|
|
578
|
+
blob.unlink()
|
|
579
|
+
if cache:
|
|
580
|
+
base = pathlib.Path(cache)
|
|
581
|
+
for p in (base / "sha256" / sha, base / sha, base / pathlib.PurePosixPath(urllib.parse.urlsplit(art["url"]).path).name):
|
|
582
|
+
if p.is_file() and blob_ok(p, sha, size):
|
|
583
|
+
copy_blob(p, blob, sha)
|
|
584
|
+
return blob, "cache"
|
|
585
|
+
if offline:
|
|
586
|
+
raise ToolchainError(f"offline: {sha} ({art['url']}) is in neither the CAS nor --cache")
|
|
587
|
+
part = cas / "partials" / f"{sha}.part"
|
|
588
|
+
guard_write(part)
|
|
589
|
+
part.parent.mkdir(parents=True, exist_ok=True)
|
|
590
|
+
blob.parent.mkdir(parents=True, exist_ok=True)
|
|
591
|
+
try:
|
|
592
|
+
download(art["url"], sha, size, hosts, part)
|
|
593
|
+
os.replace(part, blob)
|
|
594
|
+
fsync_path(blob.parent)
|
|
595
|
+
finally:
|
|
596
|
+
if part.exists():
|
|
597
|
+
part.unlink()
|
|
598
|
+
return blob, "upstream"
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
# gh reports a failed request as Go's url.Error (`Get "https://...": <cause>`), which separates "could not ask GitHub"
|
|
602
|
+
# (seatbelt-blocked trustd, no network, no login) from an attestation that was fetched and failed to verify.
|
|
603
|
+
GH_UNAVAILABLE = re.compile(r'(?:Get|Post|Head) "https?://[^"]+": |dial tcp|no such host|connection refused|connection reset|'
|
|
604
|
+
r"i/o timeout|context deadline exceeded|network is unreachable|HTTP 5\d\d|gh auth login|not logged in|"
|
|
605
|
+
r"rate limit|no valid Sigstore verifiers could be initialized", re.I)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def attest(path: pathlib.Path, att: dict) -> str:
|
|
609
|
+
"""'verified', or 'unavailable: ...' when gh or the network is missing (warned and recorded). A bad attestation raises."""
|
|
610
|
+
gh = os.environ.get("OPERATOR_TOOLCHAIN_GH", "" if test_mode() else (shutil.which("gh") or ""))
|
|
611
|
+
if not gh or not os.access(gh, os.X_OK):
|
|
612
|
+
return "unavailable: gh not found"
|
|
613
|
+
cmd = [gh, "attestation", "verify", str(path), "--repo", att["repo"], "--signer-workflow", att["signer_workflow"],
|
|
614
|
+
"--source-digest", att["source_digest"], "--deny-self-hosted-runners"]
|
|
615
|
+
try:
|
|
616
|
+
r = run(cmd, timeout=180)
|
|
617
|
+
except subprocess.TimeoutExpired:
|
|
618
|
+
return "unavailable: gh attestation verify timed out"
|
|
619
|
+
if r.returncode == 0:
|
|
620
|
+
return "verified"
|
|
621
|
+
out = (r.stderr + "\n" + r.stdout).strip()
|
|
622
|
+
if GH_UNAVAILABLE.search(out):
|
|
623
|
+
return f"unavailable: {first_line(out)}"
|
|
624
|
+
raise Refused(f"attestation failed for {path.name} (signer {att['signer_workflow']}): {first_line(out)}")
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def check_checksums(arts: list, files: dict) -> None:
|
|
628
|
+
for a in arts:
|
|
629
|
+
if role(a) != "checksums":
|
|
630
|
+
continue
|
|
631
|
+
listed = set(re.findall(r"\b[0-9a-f]{64}\b", files[a["sha256"]].read_text(errors="replace").lower()))
|
|
632
|
+
for p in arts:
|
|
633
|
+
if role(p) == "payload" and p["sha256"] not in listed:
|
|
634
|
+
raise Refused(f"{a['url']} does not list the payload sha256 {p['sha256']}")
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
# ── extraction ──────────────────────────────────────────────────────────────
|
|
638
|
+
|
|
639
|
+
def member_path(name: str):
|
|
640
|
+
"""The normalized relative path of an archive member, or None for the archive root."""
|
|
641
|
+
if name.startswith("/"):
|
|
642
|
+
raise Refused(f"archive member has an absolute path: {name}")
|
|
643
|
+
parts = [p for p in name.split("/") if p not in ("", ".")]
|
|
644
|
+
if ".." in parts:
|
|
645
|
+
raise Refused(f"archive member escapes the entry: {name}")
|
|
646
|
+
return "/".join(parts) or None
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def check_link(rel: str, target: str) -> None:
|
|
650
|
+
if target.startswith("/"):
|
|
651
|
+
raise Refused(f"absolute symlink in archive: {rel} -> {target}")
|
|
652
|
+
resolved = os.path.normpath(os.path.join(os.path.dirname(rel), target))
|
|
653
|
+
if resolved == ".." or resolved.startswith("../"):
|
|
654
|
+
raise Refused(f"symlink escapes the entry: {rel} -> {target}")
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def place(dest: pathlib.Path, rel: str) -> pathlib.Path:
|
|
658
|
+
"""Creates the parents of rel as real directories; a member never lands through a symlink."""
|
|
659
|
+
cur = dest
|
|
660
|
+
for part in rel.split("/")[:-1]:
|
|
661
|
+
cur = cur / part
|
|
662
|
+
if os.path.islink(cur):
|
|
663
|
+
raise Refused(f"archive member {rel} runs through the symlink {part}")
|
|
664
|
+
if not cur.exists():
|
|
665
|
+
cur.mkdir(mode=0o755)
|
|
666
|
+
elif not cur.is_dir():
|
|
667
|
+
raise Refused(f"archive member {rel} runs through the file {part}")
|
|
668
|
+
out = dest / rel
|
|
669
|
+
if os.path.lexists(out) and not (out.is_dir() and not out.is_symlink()):
|
|
670
|
+
raise Refused(f"archive member {rel} would overwrite an earlier one")
|
|
671
|
+
return out
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def ensure_space(dest: pathlib.Path, need: int) -> None:
|
|
675
|
+
free = shutil.disk_usage(dest).free
|
|
676
|
+
if free < need + (256 << 20):
|
|
677
|
+
raise Refused(f"not enough free space in {dest}: need {need >> 20} MB + 256 MB headroom, have {free >> 20} MB")
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def extract_tar(archive: pathlib.Path, dest: pathlib.Path, fmt: str) -> None:
|
|
681
|
+
"""Our own member filter: /usr/bin/python3 3.9 has no tarfile.data_filter."""
|
|
682
|
+
with tarfile.open(archive, "r:xz" if fmt == "tar.xz" else "r:gz") as tf:
|
|
683
|
+
members, kinds, total = tf.getmembers(), {}, 0
|
|
684
|
+
for m in members:
|
|
685
|
+
rel = member_path(m.name)
|
|
686
|
+
if rel is None:
|
|
687
|
+
continue
|
|
688
|
+
if rel in kinds:
|
|
689
|
+
raise Refused(f"duplicate archive member: {rel}")
|
|
690
|
+
if m.issym():
|
|
691
|
+
check_link(rel, m.linkname)
|
|
692
|
+
elif m.islnk():
|
|
693
|
+
if kinds.get(member_path(m.linkname)) != "f":
|
|
694
|
+
raise Refused(f"hard link {rel} -> {m.linkname} has no earlier regular file to point at")
|
|
695
|
+
elif not (m.isfile() or m.isdir()):
|
|
696
|
+
raise Refused(f"archive member is not a file, directory or link: {rel}")
|
|
697
|
+
kinds[rel] = "d" if m.isdir() else "l" if m.issym() else "f"
|
|
698
|
+
total += m.size if m.isfile() else 0
|
|
699
|
+
ensure_space(dest, total)
|
|
700
|
+
for m in members:
|
|
701
|
+
rel = member_path(m.name)
|
|
702
|
+
if rel is None:
|
|
703
|
+
continue
|
|
704
|
+
out = place(dest, rel)
|
|
705
|
+
if m.isdir():
|
|
706
|
+
out.mkdir(mode=0o755, exist_ok=True)
|
|
707
|
+
elif m.issym():
|
|
708
|
+
os.symlink(m.linkname, out)
|
|
709
|
+
elif m.islnk():
|
|
710
|
+
os.link(dest / member_path(m.linkname), out)
|
|
711
|
+
else:
|
|
712
|
+
src = tf.extractfile(m)
|
|
713
|
+
with open(out, "xb") as f:
|
|
714
|
+
shutil.copyfileobj(src, f, 1 << 20)
|
|
715
|
+
os.chmod(out, 0o755 if m.mode & 0o111 else 0o644)
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def extract_zip(archive: pathlib.Path, dest: pathlib.Path) -> None:
|
|
719
|
+
"""Members are validated with zipfile, then ditto extracts: zipfile drops symlinks, which CfT's bundle needs."""
|
|
720
|
+
with zipfile.ZipFile(archive) as zf:
|
|
721
|
+
seen, total = set(), 0
|
|
722
|
+
for info in zf.infolist():
|
|
723
|
+
rel = member_path(info.filename)
|
|
724
|
+
if rel is None or rel.split("/")[0] == "__MACOSX":
|
|
725
|
+
continue
|
|
726
|
+
if rel in seen:
|
|
727
|
+
raise Refused(f"duplicate archive member: {rel}")
|
|
728
|
+
kind = stat.S_IFMT(info.external_attr >> 16)
|
|
729
|
+
if kind == stat.S_IFLNK:
|
|
730
|
+
check_link(rel, zf.read(info).decode("utf-8", "replace"))
|
|
731
|
+
elif kind not in (0, stat.S_IFREG, stat.S_IFDIR):
|
|
732
|
+
raise Refused(f"archive member is not a file, directory or link: {rel}")
|
|
733
|
+
seen.add(rel)
|
|
734
|
+
total += info.file_size
|
|
735
|
+
ensure_space(dest, total)
|
|
736
|
+
r = run(["/usr/bin/ditto", "-x", "-k", "--noqtn", archive, dest], timeout=600)
|
|
737
|
+
if r.returncode:
|
|
738
|
+
raise ToolchainError(f"ditto -x -k {archive.name}: {first_line(r.stderr)}")
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def check_extracted(top: pathlib.Path) -> None:
|
|
742
|
+
"""After extraction: only files, dirs and links that resolve inside the entry, whatever order the archive used."""
|
|
743
|
+
real_top = os.path.realpath(top)
|
|
744
|
+
for d, dirs, files in os.walk(top):
|
|
745
|
+
for name in dirs + files:
|
|
746
|
+
p = os.path.join(d, name)
|
|
747
|
+
st = os.lstat(p)
|
|
748
|
+
if stat.S_ISLNK(st.st_mode):
|
|
749
|
+
rel = os.path.relpath(p, top)
|
|
750
|
+
if os.path.isabs(os.readlink(p)) or not within(os.path.realpath(p), real_top):
|
|
751
|
+
raise Refused(f"symlink escapes the entry: {rel} -> {os.readlink(p)}")
|
|
752
|
+
elif not (stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)):
|
|
753
|
+
raise Refused(f"not a file, directory or link: {os.path.relpath(p, top)}")
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def extract(archive: pathlib.Path, dest: pathlib.Path, layout: dict) -> None:
|
|
757
|
+
fmt = layout.get("format")
|
|
758
|
+
if fmt == "zip":
|
|
759
|
+
extract_zip(archive, dest)
|
|
760
|
+
elif fmt in ("tar.gz", "tgz", "tar.xz"):
|
|
761
|
+
extract_tar(archive, dest, fmt)
|
|
762
|
+
else:
|
|
763
|
+
raise Refused(f"unsupported archive format {fmt!r}")
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def apply_layout(raw: pathlib.Path, layout: dict) -> pathlib.Path:
|
|
767
|
+
if int(layout.get("strip", 0)) == 0:
|
|
768
|
+
return raw
|
|
769
|
+
tops = sorted(os.listdir(raw))
|
|
770
|
+
if len(tops) != 1 or os.path.islink(raw / tops[0]) or not (raw / tops[0]).is_dir():
|
|
771
|
+
raise Refused(f"strip 1 needs one top-level directory; the archive has {tops[:6]}")
|
|
772
|
+
if layout.get("root") and tops[0] != layout["root"]:
|
|
773
|
+
raise Refused(f"archive root is {tops[0]!r}, the manifest says {layout['root']!r}")
|
|
774
|
+
return raw / tops[0]
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
# ── identity: trees, digests, Mach-O, codesign, probe ───────────────────────
|
|
778
|
+
|
|
779
|
+
def entry_items(top) -> list:
|
|
780
|
+
"""(relpath, path, lstat) of everything under an entry, sorted, without .DS_Store, __pycache__ or our metadata."""
|
|
781
|
+
out = []
|
|
782
|
+
|
|
783
|
+
def walk(d, prefix):
|
|
784
|
+
with os.scandir(d) as it:
|
|
785
|
+
for e in it:
|
|
786
|
+
if e.name == ".DS_Store" or (not prefix and e.name == ENTRY_META):
|
|
787
|
+
continue
|
|
788
|
+
st = e.stat(follow_symlinks=False)
|
|
789
|
+
if stat.S_ISDIR(st.st_mode) and e.name == "__pycache__":
|
|
790
|
+
continue
|
|
791
|
+
out.append((prefix + e.name, e.path, st))
|
|
792
|
+
if stat.S_ISDIR(st.st_mode):
|
|
793
|
+
walk(e.path, prefix + e.name + "/")
|
|
794
|
+
|
|
795
|
+
walk(top, "")
|
|
796
|
+
out.sort(key=lambda item: item[0])
|
|
797
|
+
return out
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def canonical_tree(top) -> str:
|
|
801
|
+
"""sha256 of the sorted JSON list [relpath, f|l|d, size, sha256, exec, link target]: length-framed and exec-aware."""
|
|
802
|
+
rows = []
|
|
803
|
+
for rel, path, st in entry_items(top):
|
|
804
|
+
if stat.S_ISLNK(st.st_mode):
|
|
805
|
+
rows.append([rel, "l", 0, "", False, os.readlink(path)])
|
|
806
|
+
elif stat.S_ISDIR(st.st_mode):
|
|
807
|
+
rows.append([rel, "d", 0, "", False, ""])
|
|
808
|
+
else:
|
|
809
|
+
rows.append([rel, "f", st.st_size, sha256_file(path), bool(st.st_mode & 0o111), ""])
|
|
810
|
+
return "sha256:" + hashlib.sha256(json.dumps(rows, separators=(",", ":")).encode()).hexdigest()
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
def pm_digest(top) -> str:
|
|
814
|
+
"""Hermes pm's tree_digest, reimplemented: sha256 over `relpath\\0content` in relpath order, a symlink contributing its
|
|
815
|
+
link text, real __pycache__ dirs skipped, no modes or mtimes. Our own ENTRY_META is not package bytes."""
|
|
816
|
+
items = []
|
|
817
|
+
|
|
818
|
+
def walk(d, prefix):
|
|
819
|
+
with os.scandir(d) as it:
|
|
820
|
+
for e in it:
|
|
821
|
+
if not prefix and e.name == ENTRY_META:
|
|
822
|
+
continue
|
|
823
|
+
if e.is_symlink():
|
|
824
|
+
items.append((prefix + e.name, e.path, True))
|
|
825
|
+
elif e.is_dir():
|
|
826
|
+
if e.name != "__pycache__":
|
|
827
|
+
walk(e.path, prefix + e.name + "/")
|
|
828
|
+
else:
|
|
829
|
+
items.append((prefix + e.name, e.path, False))
|
|
830
|
+
|
|
831
|
+
walk(top, "")
|
|
832
|
+
items.sort(key=lambda item: item[0])
|
|
833
|
+
h = hashlib.sha256()
|
|
834
|
+
for rel, path, link in items:
|
|
835
|
+
h.update(rel.encode("utf-8") + b"\0")
|
|
836
|
+
if link:
|
|
837
|
+
h.update(os.readlink(path).encode("utf-8"))
|
|
838
|
+
else:
|
|
839
|
+
with open(path, "rb") as f:
|
|
840
|
+
for block in iter(lambda: f.read(1 << 20), b""):
|
|
841
|
+
h.update(block)
|
|
842
|
+
return h.hexdigest()
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def pm_listing(top) -> dict:
|
|
846
|
+
"""relpath -> sha256 or link text, over exactly what pm_digest hashes: the paths behind a digest mismatch."""
|
|
847
|
+
out = {}
|
|
848
|
+
for d, dirs, files in os.walk(top):
|
|
849
|
+
rel_d = os.path.relpath(d, top)
|
|
850
|
+
for name in list(dirs):
|
|
851
|
+
p = os.path.join(d, name)
|
|
852
|
+
if os.path.islink(p):
|
|
853
|
+
out[os.path.normpath(os.path.join(rel_d, name))] = "-> " + os.readlink(p)
|
|
854
|
+
dirs[:] = [n for n in dirs if n != "__pycache__" and not os.path.islink(os.path.join(d, n))]
|
|
855
|
+
for name in files:
|
|
856
|
+
p, rel = os.path.join(d, name), os.path.normpath(os.path.join(rel_d, name))
|
|
857
|
+
if rel == ENTRY_META:
|
|
858
|
+
continue
|
|
859
|
+
out[rel] = "-> " + os.readlink(p) if os.path.islink(p) else sha256_file(p)
|
|
860
|
+
return out
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
def digest_diff(ours, theirs) -> list:
|
|
864
|
+
a, b = pm_listing(ours), pm_listing(theirs) if os.path.isdir(theirs) else {}
|
|
865
|
+
return sorted(k for k in set(a) | set(b) if a.get(k) != b.get(k))
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
CPU_NAMES = {0x0100000C: "arm64", 0x01000007: "x86_64", 0x00000007: "i386", 0x0000000C: "arm"}
|
|
869
|
+
LC_DYLIBS = (0xC, 0xD, 0x20, 0x80000018, 0x8000001F, 0x80000023)
|
|
870
|
+
LC_RPATH = 0x8000001C
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def macho(path) -> dict | None:
|
|
874
|
+
"""Arches, dylib install names and rpaths of a Mach-O file (thin or fat), read directly: no Xcode tools needed."""
|
|
875
|
+
try:
|
|
876
|
+
f = open(path, "rb")
|
|
877
|
+
except OSError:
|
|
878
|
+
return None
|
|
879
|
+
with f:
|
|
880
|
+
head = f.read(8)
|
|
881
|
+
if len(head) < 8:
|
|
882
|
+
return None
|
|
883
|
+
(be,) = struct.unpack(">I", head[:4])
|
|
884
|
+
slices = [0]
|
|
885
|
+
if be in (0xCAFEBABE, 0xCAFEBABF):
|
|
886
|
+
(n,) = struct.unpack(">I", head[4:8])
|
|
887
|
+
if not 0 < n < 32:
|
|
888
|
+
return None # Java class files share the fat magic
|
|
889
|
+
wide = be == 0xCAFEBABF
|
|
890
|
+
raw = f.read(n * (32 if wide else 20))
|
|
891
|
+
slices = [struct.unpack_from(">IIQ" if wide else ">III", raw, i * (32 if wide else 20))[2] for i in range(n)]
|
|
892
|
+
elif be in (0xFEEDFACE, 0xFEEDFACF):
|
|
893
|
+
return {"archs": ["ppc"], "dylibs": [], "rpaths": []}
|
|
894
|
+
info = {"archs": [], "dylibs": [], "rpaths": []}
|
|
895
|
+
for off in slices:
|
|
896
|
+
f.seek(off)
|
|
897
|
+
hdr = f.read(32)
|
|
898
|
+
if len(hdr) < 28:
|
|
899
|
+
return None
|
|
900
|
+
(magic,) = struct.unpack("<I", hdr[:4])
|
|
901
|
+
if magic not in (0xFEEDFACE, 0xFEEDFACF):
|
|
902
|
+
return None
|
|
903
|
+
cputype, _, _, ncmds, sizeofcmds = struct.unpack("<IIIII", hdr[4:24])
|
|
904
|
+
info["archs"].append(CPU_NAMES.get(cputype, hex(cputype)))
|
|
905
|
+
f.seek(off + (32 if magic == 0xFEEDFACF else 28))
|
|
906
|
+
cmds, pos = f.read(sizeofcmds), 0
|
|
907
|
+
for _ in range(ncmds):
|
|
908
|
+
if pos + 12 > len(cmds):
|
|
909
|
+
break
|
|
910
|
+
cmd, size = struct.unpack_from("<II", cmds, pos)
|
|
911
|
+
if size < 8:
|
|
912
|
+
break
|
|
913
|
+
if cmd in LC_DYLIBS or cmd == LC_RPATH:
|
|
914
|
+
(stroff,) = struct.unpack_from("<I", cmds, pos + 8)
|
|
915
|
+
text = cmds[pos + stroff:pos + size].split(b"\0", 1)[0].decode("utf-8", "replace")
|
|
916
|
+
info["rpaths" if cmd == LC_RPATH else "dylibs"].append(text)
|
|
917
|
+
pos += size
|
|
918
|
+
return info
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
def macho_problems(top, target: str, relocatable: bool) -> list:
|
|
922
|
+
want, probs = TARGET_ARCH.get(target), []
|
|
923
|
+
for rel, path, st in entry_items(top):
|
|
924
|
+
if not stat.S_ISREG(st.st_mode):
|
|
925
|
+
continue
|
|
926
|
+
info = macho(path)
|
|
927
|
+
if info is None:
|
|
928
|
+
continue
|
|
929
|
+
if want and want not in info["archs"]:
|
|
930
|
+
probs.append(f"{rel} is built for {','.join(info['archs'])}, not {want}")
|
|
931
|
+
if relocatable:
|
|
932
|
+
bad = [d for d in info["dylibs"] + info["rpaths"] if d.startswith(("/opt/homebrew", "/usr/local"))]
|
|
933
|
+
if bad:
|
|
934
|
+
probs.append(f"{rel} is not relocatable: it loads {bad[0]}")
|
|
935
|
+
return probs
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
def codesign_observed(path) -> dict:
|
|
939
|
+
r = run(["/usr/bin/codesign", "-dv", "--verbose=2", path])
|
|
940
|
+
out = r.stderr + r.stdout
|
|
941
|
+
if "Signature=adhoc" in out:
|
|
942
|
+
return {"expect": "adhoc"}
|
|
943
|
+
team = re.search(r"TeamIdentifier=(\S+)", out)
|
|
944
|
+
if team and team.group(1) != "not":
|
|
945
|
+
return {"expect": "developer-id", "team": team.group(1)}
|
|
946
|
+
return {"expect": "none", "detail": first_line(out)}
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
def codesign_problems(bins: list, expect) -> list:
|
|
950
|
+
kind = (expect or {}).get("expect")
|
|
951
|
+
if kind in (None, "none", "unsigned-bundle"):
|
|
952
|
+
return []
|
|
953
|
+
probs = []
|
|
954
|
+
for b in bins:
|
|
955
|
+
if macho(b) is None:
|
|
956
|
+
continue
|
|
957
|
+
seen = codesign_observed(b)
|
|
958
|
+
if kind == "adhoc":
|
|
959
|
+
if seen["expect"] != "adhoc":
|
|
960
|
+
probs.append(f"{b.name}: expected an ad-hoc signature, found {seen}")
|
|
961
|
+
elif run(["/usr/bin/codesign", "--verify", "--strict", b]).returncode:
|
|
962
|
+
probs.append(f"{b.name}: codesign --verify --strict fails")
|
|
963
|
+
elif kind == "developer-id":
|
|
964
|
+
req = f'anchor apple generic and certificate leaf[subject.OU] = "{expect.get("team")}"'
|
|
965
|
+
if run(["/usr/bin/codesign", "--verify", "--strict", f"-R={req}", b]).returncode:
|
|
966
|
+
probs.append(f"{b.name}: not signed by Developer ID team {expect.get('team')}")
|
|
967
|
+
elif expect.get("notarized"):
|
|
968
|
+
r = run(["/usr/sbin/spctl", "--assess", "--type", "open", "--context", "context:primary-signature", "-v", b])
|
|
969
|
+
if "source=Notarized Developer ID" not in r.stderr + r.stdout:
|
|
970
|
+
probs.append(f"{b.name}: not notarized ({first_line(r.stderr + r.stdout)})")
|
|
971
|
+
else:
|
|
972
|
+
probs.append(f"{b.name}: unknown codesign expectation {kind!r}")
|
|
973
|
+
return probs
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def scrubbed_env() -> dict:
|
|
977
|
+
return {"PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": str(env_home()), "LANG": "C", "LC_ALL": "C",
|
|
978
|
+
"TMPDIR": tempfile.gettempdir()}
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
def run_probe(top: pathlib.Path, row: dict) -> str:
|
|
982
|
+
p = row.get("probe")
|
|
983
|
+
if not p:
|
|
984
|
+
return ""
|
|
985
|
+
exe = top / row["provides"][p["bin"]]
|
|
986
|
+
try:
|
|
987
|
+
r = subprocess.run([str(exe), *p.get("args", [])], cwd=top, env=scrubbed_env(), capture_output=True, timeout=60)
|
|
988
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
989
|
+
raise Refused(f"probe {p['bin']} did not run: {e}")
|
|
990
|
+
out = (r.stdout + r.stderr).decode("utf-8", "replace")
|
|
991
|
+
if p["expect"] not in out:
|
|
992
|
+
raise Refused(f"probe {p['bin']} {' '.join(p.get('args', []))}: expected {p['expect']!r}, got {first_line(out)!r}")
|
|
993
|
+
return out
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
# ── realize ─────────────────────────────────────────────────────────────────
|
|
997
|
+
|
|
998
|
+
class Ctx:
|
|
999
|
+
def __init__(self, args, root=True):
|
|
1000
|
+
self.args = args
|
|
1001
|
+
self.root = resolve_root(getattr(args, "root", None)) if root else None
|
|
1002
|
+
self.manifest_path = manifest_file(getattr(args, "manifest", None))
|
|
1003
|
+
self.manifest_bytes = self.manifest_path.read_bytes()
|
|
1004
|
+
self.manifest = load_manifest(self.manifest_path)
|
|
1005
|
+
self.target = box_target()
|
|
1006
|
+
self.cache = getattr(args, "cache", None)
|
|
1007
|
+
self.offline = bool(getattr(args, "offline", False))
|
|
1008
|
+
|
|
1009
|
+
@property
|
|
1010
|
+
def hosts(self):
|
|
1011
|
+
return self.manifest.get("hosts") or []
|
|
1012
|
+
|
|
1013
|
+
@property
|
|
1014
|
+
def serial(self):
|
|
1015
|
+
return self.manifest.get("serial")
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
def realize(ctx: Ctx, name: str, which: str, row: dict, witness: bool = False) -> dict:
|
|
1019
|
+
"""One verified entry in the store (or, with witness, the facts about one that is thrown away)."""
|
|
1020
|
+
label = f"{name}@{which}" if which == "previous" else name
|
|
1021
|
+
arts = artifacts_for(row, ctx.target)
|
|
1022
|
+
if not arts:
|
|
1023
|
+
raise Refused(f"{label}: no artifact for {ctx.target}")
|
|
1024
|
+
sname = store_name(row, ctx.target)
|
|
1025
|
+
dest = ctx.root / "store" / sname
|
|
1026
|
+
if not witness:
|
|
1027
|
+
if row.get("tree") is None:
|
|
1028
|
+
raise Refused(f"{label} has no witnessed tree (install: {row.get('install')}); land a `toolchain install --witness` patch first")
|
|
1029
|
+
if os.path.lexists(dest):
|
|
1030
|
+
return adopt(dest, row, label)
|
|
1031
|
+
scratch = pathlib.Path(tempfile.mkdtemp(prefix="toolchain-witness-")) if witness else None
|
|
1032
|
+
cas = (scratch / "cas") if witness else ctx.root / "cas"
|
|
1033
|
+
files, sources = {}, set()
|
|
1034
|
+
for a in arts:
|
|
1035
|
+
files[a["sha256"]], src = obtain(a, cas, ctx.hosts, cache=ctx.cache, offline=ctx.offline,
|
|
1036
|
+
also_read=[ctx.root / "cas"] if witness else ())
|
|
1037
|
+
sources.add(src)
|
|
1038
|
+
if witness and ctx.cache and not (pathlib.Path(ctx.cache) / "sha256" / a["sha256"]).exists():
|
|
1039
|
+
copy_blob(files[a["sha256"]], pathlib.Path(ctx.cache) / "sha256" / a["sha256"], a["sha256"])
|
|
1040
|
+
check_checksums(arts, files)
|
|
1041
|
+
payloads = [a for a in arts if role(a) == "payload"]
|
|
1042
|
+
att = (row.get("provenance") or {}).get("attest")
|
|
1043
|
+
attested = attest(files[payloads[0]["sha256"]], att) if att else "none in manifest"
|
|
1044
|
+
if attested.startswith("unavailable"):
|
|
1045
|
+
say(f"warning: {label}: attestation not checked ({attested})")
|
|
1046
|
+
fault("post-download")
|
|
1047
|
+
layout = row.get("layout") or {}
|
|
1048
|
+
if not witness:
|
|
1049
|
+
guard_write(ctx.root / "store")
|
|
1050
|
+
(ctx.root / "store").mkdir(parents=True, exist_ok=True)
|
|
1051
|
+
staging = pathlib.Path(tempfile.mkdtemp(prefix=".staging-", dir=scratch if witness else (ctx.root / "store")))
|
|
1052
|
+
try:
|
|
1053
|
+
raw = staging / "raw"
|
|
1054
|
+
raw.mkdir()
|
|
1055
|
+
for a in payloads:
|
|
1056
|
+
extract(files[a["sha256"]], raw, layout)
|
|
1057
|
+
top = apply_layout(raw, layout)
|
|
1058
|
+
for rel in layout.get("add") or []:
|
|
1059
|
+
out = place(top, member_path(rel))
|
|
1060
|
+
out.touch(mode=0o644)
|
|
1061
|
+
check_extracted(top)
|
|
1062
|
+
fault("post-extract")
|
|
1063
|
+
tree, digest = canonical_tree(top), pm_digest(top)
|
|
1064
|
+
missing = [rel for rel in (row.get("provides") or {}).values() if not (top / rel).is_file()]
|
|
1065
|
+
bins = [top / rel for rel in (row.get("provides") or {}).values() if (top / rel).is_file()]
|
|
1066
|
+
if witness:
|
|
1067
|
+
return witness_report(name, which, row, top, files[payloads[0]["sha256"]], tree, digest, missing, bins, attested)
|
|
1068
|
+
if tree != row["tree"]:
|
|
1069
|
+
raise Refused(f"{label}: realized tree {tree} does not match the manifest's {row['tree']}")
|
|
1070
|
+
if row.get("expect_pm_digest") and digest != row["expect_pm_digest"]:
|
|
1071
|
+
diff = digest_diff(top, env_home() / ".hermes" / "tools" / row["entry"])
|
|
1072
|
+
raise Refused(f"{label}: pm digest {digest} does not match the manifest's expect_pm_digest {row['expect_pm_digest']}"
|
|
1073
|
+
f"; paths that differ from ~/.hermes/tools/{row['entry']}: {diff[:40]}")
|
|
1074
|
+
if missing:
|
|
1075
|
+
raise Refused(f"{label}: provides missing from the archive: {missing}")
|
|
1076
|
+
probs = macho_problems(top, ctx.target, bool(row.get("relocatable"))) + codesign_problems(bins, row.get("codesign"))
|
|
1077
|
+
if probs:
|
|
1078
|
+
raise Refused(f"{label}: " + "; ".join(probs))
|
|
1079
|
+
probe_out = run_probe(top, row)
|
|
1080
|
+
meta = {"name": name, "version": str(row["version"]), "target": ctx.target, "entry": row["entry"], "store_entry": sname,
|
|
1081
|
+
"artifacts": [a["sha256"] for a in arts], "tree": tree, "digest": digest, "manifest_serial": ctx.serial,
|
|
1082
|
+
"source": sorted(sources)[0] if len(sources) == 1 else ",".join(sorted(sources)), "installed_at": now(),
|
|
1083
|
+
"provides": row.get("provides") or {}, "probe": row.get("probe"), "probe_output": first_line(probe_out),
|
|
1084
|
+
"attest": attested}
|
|
1085
|
+
(top / ENTRY_META).write_bytes(canonical(meta))
|
|
1086
|
+
os.chmod(top / ENTRY_META, 0o444)
|
|
1087
|
+
fsync_tree(top)
|
|
1088
|
+
seal(top)
|
|
1089
|
+
fault("pre-publish")
|
|
1090
|
+
guard_write(dest)
|
|
1091
|
+
os.rename(top, dest)
|
|
1092
|
+
fault("pre-seal-entry")
|
|
1093
|
+
os.chmod(dest, 0o555)
|
|
1094
|
+
fsync_path(dest.parent)
|
|
1095
|
+
full_fsync(dest.parent)
|
|
1096
|
+
fault("post-publish")
|
|
1097
|
+
say(f"{label} {row['version']}: sealed store/{sname} ({tree})")
|
|
1098
|
+
return meta
|
|
1099
|
+
finally:
|
|
1100
|
+
force_rmtree(staging)
|
|
1101
|
+
if scratch:
|
|
1102
|
+
force_rmtree(scratch)
|
|
1103
|
+
|
|
1104
|
+
|
|
1105
|
+
def adopt(dest: pathlib.Path, row: dict, label: str) -> dict:
|
|
1106
|
+
"""An entry already in the store is reused only if its bytes still hash to the manifest's tree."""
|
|
1107
|
+
meta = read_json(dest / ENTRY_META)
|
|
1108
|
+
if not isinstance(meta, dict):
|
|
1109
|
+
raise Refused(f"{dest} has no readable {ENTRY_META}; inspect it with toolchain verify --deep")
|
|
1110
|
+
tree = canonical_tree(dest)
|
|
1111
|
+
if tree != row["tree"] or meta.get("tree") != row["tree"]:
|
|
1112
|
+
raise Refused(f"{label}: store entry {dest.name} hashes to {tree}, the manifest says {row['tree']}")
|
|
1113
|
+
if os.access(dest, os.W_OK):
|
|
1114
|
+
os.chmod(dest, 0o555)
|
|
1115
|
+
return meta
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
def witness_report(name, which, row, top, archive, tree, digest, missing, bins, attested) -> dict:
|
|
1119
|
+
payload = [a for a in artifacts_for(row, box_target()) if role(a) == "payload"][0]
|
|
1120
|
+
observed = {}
|
|
1121
|
+
for b in bins:
|
|
1122
|
+
if macho(b) is not None:
|
|
1123
|
+
observed[b.name] = codesign_observed(b)
|
|
1124
|
+
try:
|
|
1125
|
+
probe = first_line(run_probe(top, row)) if row.get("probe") else ""
|
|
1126
|
+
probe_ok = True
|
|
1127
|
+
except Refused as e:
|
|
1128
|
+
probe, probe_ok = str(e), False
|
|
1129
|
+
kinds = sorted({c["expect"] for c in observed.values()})
|
|
1130
|
+
arch = macho_problems(top, box_target(), False)
|
|
1131
|
+
reloc = [p for p in macho_problems(top, box_target(), True) if p not in arch]
|
|
1132
|
+
rep = {"package": name, "row": which, "version": str(row["version"]), "entry": row["entry"], "url": payload["url"],
|
|
1133
|
+
"sha256": payload["sha256"], "size": archive.stat().st_size, "tree": tree, "pm_digest": digest,
|
|
1134
|
+
"tree_matches_manifest": row.get("tree") == tree, "files": len(entry_items(top)), "provides_missing": missing,
|
|
1135
|
+
"arch_problems": arch, "relocatable": not reloc, "relocatable_problems": reloc, "codesign": observed,
|
|
1136
|
+
"codesign_problems": codesign_problems(bins, row.get("codesign")), "probe": probe, "probe_ok": probe_ok,
|
|
1137
|
+
"attest": attested, "expect_pm_digest_ok": None if not row.get("expect_pm_digest") else digest == row["expect_pm_digest"]}
|
|
1138
|
+
rep["clean"] = (probe_ok and not arch and not missing and not rep["codesign_problems"] and rep["expect_pm_digest_ok"] is not False
|
|
1139
|
+
and (rep["relocatable"] or not row.get("relocatable")))
|
|
1140
|
+
rep["patch"] = {"tree": tree, "size": rep["size"], **({"codesign": {"expect": kinds[0]}} if len(kinds) == 1 else {})}
|
|
1141
|
+
return rep
|
|
1142
|
+
|
|
1143
|
+
|
|
1144
|
+
def gen_package(meta: dict, row: dict) -> dict:
|
|
1145
|
+
return {"artifacts": meta["artifacts"], "digest": meta["digest"], "entry": meta["entry"], "env": row.get("env") or {},
|
|
1146
|
+
"provides": row.get("provides") or {}, "store_entry": meta["store_entry"], "target": meta["target"],
|
|
1147
|
+
"tree": meta["tree"], "version": meta["version"]}
|
|
1148
|
+
|
|
1149
|
+
|
|
1150
|
+
# ── generations and consumers ───────────────────────────────────────────────
|
|
1151
|
+
|
|
1152
|
+
def generation_numbers(root: pathlib.Path) -> list:
|
|
1153
|
+
try:
|
|
1154
|
+
return sorted(int(p.name) for p in (root / "generations").iterdir() if p.name.isdigit())
|
|
1155
|
+
except OSError:
|
|
1156
|
+
return []
|
|
1157
|
+
|
|
1158
|
+
|
|
1159
|
+
def load_generation(root: pathlib.Path, n) -> dict | None:
|
|
1160
|
+
return read_json(root / "generations" / str(n) / "generation.json")
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
def find_generation(root: pathlib.Path, packages: dict):
|
|
1164
|
+
for n in generation_numbers(root):
|
|
1165
|
+
g = load_generation(root, n)
|
|
1166
|
+
if g and g.get("packages") == packages:
|
|
1167
|
+
return n
|
|
1168
|
+
return None
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
def cli_git_sha():
|
|
1172
|
+
with contextlib.suppress(OSError, subprocess.SubprocessError):
|
|
1173
|
+
r = run(["git", "-C", HERE, "rev-parse", "HEAD"], timeout=5)
|
|
1174
|
+
if r.returncode == 0 and re.fullmatch(r"[0-9a-f]{40}", r.stdout.strip()):
|
|
1175
|
+
return r.stdout.strip()
|
|
1176
|
+
return None
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
def build_generation(ctx: Ctx, packages: dict, rows: dict) -> int:
|
|
1180
|
+
root = ctx.root
|
|
1181
|
+
for name, p in packages.items():
|
|
1182
|
+
for req in rows[name].get("requires") or []:
|
|
1183
|
+
if req not in packages:
|
|
1184
|
+
raise Refused(f"{name} requires {req}, which this generation does not contain")
|
|
1185
|
+
tools = {}
|
|
1186
|
+
for name, p in sorted(packages.items()):
|
|
1187
|
+
for tool in p["provides"]:
|
|
1188
|
+
if tool in tools:
|
|
1189
|
+
raise Refused(f"{tool} is provided by both {tools[tool]} and {name}")
|
|
1190
|
+
tools[tool] = name
|
|
1191
|
+
n = (generation_numbers(root) or [0])[-1] + 1
|
|
1192
|
+
gens = root / "generations"
|
|
1193
|
+
guard_write(gens)
|
|
1194
|
+
gens.mkdir(parents=True, exist_ok=True)
|
|
1195
|
+
tmp = pathlib.Path(tempfile.mkdtemp(prefix=f".tmp-{n}-", dir=gens))
|
|
1196
|
+
(tmp / "bin").mkdir()
|
|
1197
|
+
facts = {"schema": FACTS_SCHEMA, "packages": {}}
|
|
1198
|
+
for name, p in sorted(packages.items()):
|
|
1199
|
+
os.symlink(f"../../store/{p['store_entry']}", tmp / p["entry"])
|
|
1200
|
+
for tool, rel in sorted(p["provides"].items()):
|
|
1201
|
+
os.symlink(f"../{p['entry']}/{rel}", tmp / "bin" / tool)
|
|
1202
|
+
facts["packages"][name] = {**p, "generation": n, "manifest_serial": ctx.serial, "source": "operator-toolchain"}
|
|
1203
|
+
if "llama-server" in tools:
|
|
1204
|
+
os.symlink("bin/llama-server", tmp / "llama-server")
|
|
1205
|
+
os.symlink(packages[tools["llama-server"]]["entry"], tmp / "llamacpp")
|
|
1206
|
+
gj = {"schema": GEN_SCHEMA, "n": n, "created": now(), "manifest_serial": ctx.serial,
|
|
1207
|
+
"manifest_sha256": hashlib.sha256(ctx.manifest_bytes).hexdigest(), "cli_git_sha": cli_git_sha(),
|
|
1208
|
+
"cli_sha256": sha256_file(__file__), "packages": packages}
|
|
1209
|
+
for fname, data in (("facts.json", canonical(facts)), ("generation.json", canonical(gj))):
|
|
1210
|
+
(tmp / fname).write_bytes(data)
|
|
1211
|
+
os.chmod(tmp / fname, 0o444)
|
|
1212
|
+
fsync_tree(tmp)
|
|
1213
|
+
seal(tmp)
|
|
1214
|
+
fault("pre-generation")
|
|
1215
|
+
dest = gens / str(n)
|
|
1216
|
+
guard_write(dest)
|
|
1217
|
+
os.rename(tmp, dest)
|
|
1218
|
+
fault("pre-seal-generation")
|
|
1219
|
+
os.chmod(dest, 0o555)
|
|
1220
|
+
fsync_path(gens)
|
|
1221
|
+
full_fsync(gens)
|
|
1222
|
+
return n
|
|
1223
|
+
|
|
1224
|
+
|
|
1225
|
+
def seal_generation(root: pathlib.Path, n: int) -> None:
|
|
1226
|
+
"""A run killed between the rename and the chmod leaves the generation's top dir writable (its contents are sealed
|
|
1227
|
+
before the rename, and macOS needs the dir writable to move it); a reused generation is sealed again here."""
|
|
1228
|
+
gdir = root / "generations" / str(n)
|
|
1229
|
+
if os.access(gdir, os.W_OK):
|
|
1230
|
+
guard_write(gdir)
|
|
1231
|
+
os.chmod(gdir, 0o555)
|
|
1232
|
+
|
|
1233
|
+
|
|
1234
|
+
def current_generation(root: pathlib.Path, consumer: str):
|
|
1235
|
+
try:
|
|
1236
|
+
target = os.readlink(root / "consumers" / consumer)
|
|
1237
|
+
except OSError:
|
|
1238
|
+
return None
|
|
1239
|
+
m = re.fullmatch(r"\.\./generations/(\d+)", target)
|
|
1240
|
+
return int(m.group(1)) if m else None
|
|
1241
|
+
|
|
1242
|
+
|
|
1243
|
+
def consumer_names(root: pathlib.Path) -> list:
|
|
1244
|
+
try:
|
|
1245
|
+
return sorted(p.name for p in (root / "consumers").iterdir() if not p.name.startswith("."))
|
|
1246
|
+
except OSError:
|
|
1247
|
+
return []
|
|
1248
|
+
|
|
1249
|
+
|
|
1250
|
+
def parse_consumers(text: str) -> list:
|
|
1251
|
+
out = []
|
|
1252
|
+
for c in [c.strip() for c in (text or "").split(",") if c.strip()]:
|
|
1253
|
+
if c == "agent":
|
|
1254
|
+
raise Refused("consumer 'agent' is reserved for v2")
|
|
1255
|
+
if c not in CONSUMERS:
|
|
1256
|
+
raise Refused(f"unknown consumer {c!r}; one of {', '.join(CONSUMERS)}")
|
|
1257
|
+
if c not in out:
|
|
1258
|
+
out.append(c)
|
|
1259
|
+
if not out:
|
|
1260
|
+
raise Refused("no consumer named")
|
|
1261
|
+
return out
|
|
1262
|
+
|
|
1263
|
+
|
|
1264
|
+
def flip(root: pathlib.Path, consumer: str, n: int) -> None:
|
|
1265
|
+
"""symlink + rename(2) + fsync: a reader sees the old generation or the new one, never ENOENT. Never ln -sf or mv."""
|
|
1266
|
+
cdir = root / "consumers"
|
|
1267
|
+
link, tmp = cdir / consumer, cdir / f".{consumer}.tmp"
|
|
1268
|
+
guard_write(link)
|
|
1269
|
+
cdir.mkdir(parents=True, exist_ok=True)
|
|
1270
|
+
if os.path.lexists(link) and not link.is_symlink():
|
|
1271
|
+
raise Refused(f"{link} is not a symlink; refusing to replace it")
|
|
1272
|
+
if os.path.lexists(tmp):
|
|
1273
|
+
tmp.unlink()
|
|
1274
|
+
os.symlink(f"../generations/{n}", tmp)
|
|
1275
|
+
os.replace(tmp, link)
|
|
1276
|
+
fsync_path(cdir)
|
|
1277
|
+
|
|
1278
|
+
|
|
1279
|
+
def generation_problems(root: pathlib.Path, n) -> list:
|
|
1280
|
+
"""O(1) per package: every entry link resolves into a sealed store entry that matches the generation's record."""
|
|
1281
|
+
gdir = root / "generations" / str(n)
|
|
1282
|
+
g = load_generation(root, n)
|
|
1283
|
+
if not g:
|
|
1284
|
+
return [f"generation {n} has no readable generation.json"]
|
|
1285
|
+
probs, store = [], os.path.realpath(root / "store")
|
|
1286
|
+
if os.access(gdir, os.W_OK):
|
|
1287
|
+
probs.append(f"generation {n} is writable (not sealed; toolchain install seals it again)")
|
|
1288
|
+
for name, p in sorted(g.get("packages", {}).items()):
|
|
1289
|
+
real = os.path.realpath(gdir / p["entry"])
|
|
1290
|
+
if real != os.path.join(store, p["store_entry"]) or not os.path.isdir(real):
|
|
1291
|
+
probs.append(f"gen {n} {name}: {p['entry']} resolves to {real}, not store/{p['store_entry']}")
|
|
1292
|
+
continue
|
|
1293
|
+
if os.access(real, os.W_OK):
|
|
1294
|
+
probs.append(f"gen {n} {name}: store/{p['store_entry']} is writable (not sealed)")
|
|
1295
|
+
meta = read_json(pathlib.Path(real) / ENTRY_META) or {}
|
|
1296
|
+
if meta.get("tree") != p["tree"]:
|
|
1297
|
+
probs.append(f"gen {n} {name}: store/{p['store_entry']} metadata records {meta.get('tree')}, generation says {p['tree']}")
|
|
1298
|
+
for tool in p["provides"]:
|
|
1299
|
+
if not os.path.isfile(gdir / "bin" / tool):
|
|
1300
|
+
probs.append(f"gen {n} {name}: bin/{tool} does not resolve")
|
|
1301
|
+
return probs
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
def parse_ini(path: pathlib.Path) -> dict:
|
|
1305
|
+
sections, cur = {}, None
|
|
1306
|
+
for raw in path.read_text().splitlines():
|
|
1307
|
+
line = raw.strip()
|
|
1308
|
+
if not line or line.startswith(("#", ";")):
|
|
1309
|
+
continue
|
|
1310
|
+
m = re.fullmatch(r"\[(.+)\]", line)
|
|
1311
|
+
if m:
|
|
1312
|
+
cur = sections.setdefault(m.group(1), {})
|
|
1313
|
+
elif cur is not None and "=" in line:
|
|
1314
|
+
k, v = line.split("=", 1)
|
|
1315
|
+
cur[k.strip()] = v.strip()
|
|
1316
|
+
return sections
|
|
1317
|
+
|
|
1318
|
+
|
|
1319
|
+
def is_flag(arg: str) -> bool:
|
|
1320
|
+
return arg.startswith("-") and arg not in ("-", "--") and not re.match(r"-\d", arg)
|
|
1321
|
+
|
|
1322
|
+
|
|
1323
|
+
def live_flags(consumer: str) -> tuple:
|
|
1324
|
+
"""(source, flags) a consumer uses live: aurora from the runtime presets.ini, portal from models.json recipes."""
|
|
1325
|
+
if consumer == "aurora":
|
|
1326
|
+
p = operator_home() / "runtime" / "presets.ini"
|
|
1327
|
+
if not p.is_file():
|
|
1328
|
+
return str(p), set()
|
|
1329
|
+
flags = set(GATEWAY_FLAGS)
|
|
1330
|
+
for keys in parse_ini(p).values():
|
|
1331
|
+
for k in keys:
|
|
1332
|
+
if k != "model":
|
|
1333
|
+
flags.add("--temperature" if k == "temp" else f"--{k}")
|
|
1334
|
+
return str(p), flags
|
|
1335
|
+
if consumer == "portal":
|
|
1336
|
+
p = portal_home() / "models.json"
|
|
1337
|
+
data = read_json(p)
|
|
1338
|
+
if data is None:
|
|
1339
|
+
return str(p), set()
|
|
1340
|
+
flags = set(PORTAL_DEFAULT_FLAGS)
|
|
1341
|
+
for m in data.get("models", []) if isinstance(data, dict) else []:
|
|
1342
|
+
recipe = (m or {}).get("recipe") or {}
|
|
1343
|
+
if os.path.basename(str(recipe.get("command", ""))) == "llama-server":
|
|
1344
|
+
flags.update(a.split("=", 1)[0] for a in recipe.get("args", []) if isinstance(a, str) and is_flag(a))
|
|
1345
|
+
return str(p), flags
|
|
1346
|
+
return "", set()
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
def help_flags(binary) -> set:
|
|
1350
|
+
try:
|
|
1351
|
+
r = subprocess.run([str(binary), "--help"], env=scrubbed_env(), capture_output=True, timeout=60)
|
|
1352
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
1353
|
+
raise Refused(f"{binary} --help did not run: {e}")
|
|
1354
|
+
return set(re.findall(r"(?<![\w-])(--?[A-Za-z][\w-]*)", (r.stdout + r.stderr).decode("utf-8", "replace")))
|
|
1355
|
+
|
|
1356
|
+
|
|
1357
|
+
def flag_precheck(root: pathlib.Path, consumer: str, n: int) -> tuple:
|
|
1358
|
+
src, flags = live_flags(consumer)
|
|
1359
|
+
binary = root / "generations" / str(n) / "bin" / "llama-server"
|
|
1360
|
+
if not flags or not binary.exists():
|
|
1361
|
+
return src, []
|
|
1362
|
+
have = help_flags(binary)
|
|
1363
|
+
return src, sorted(f for f in flags if f not in have)
|
|
1364
|
+
|
|
1365
|
+
|
|
1366
|
+
def plan_activations(ctx: Ctx, targets: list, force_flags: bool) -> list:
|
|
1367
|
+
"""(consumer, generation, previous generation, missing flags) for each target. Everything that can refuse an
|
|
1368
|
+
activation is checked here, before the first flip, so a multi-consumer command applies to all of its consumers or none."""
|
|
1369
|
+
root, plan = ctx.root, []
|
|
1370
|
+
for consumer, n in targets:
|
|
1371
|
+
if n not in generation_numbers(root):
|
|
1372
|
+
raise Refused(f"no generation {n} in {root}/generations")
|
|
1373
|
+
probs = generation_problems(root, n)
|
|
1374
|
+
if probs:
|
|
1375
|
+
raise Refused(f"generation {n} is not sound: " + "; ".join(probs))
|
|
1376
|
+
src, missing = flag_precheck(root, consumer, n)
|
|
1377
|
+
if missing and not force_flags:
|
|
1378
|
+
raise Refused(f"{consumer}: generation {n}'s llama-server --help lacks flags used live in {src}: {' '.join(missing)} "
|
|
1379
|
+
f"(--force-flags to override)")
|
|
1380
|
+
plan.append((consumer, n, current_generation(root, consumer), missing))
|
|
1381
|
+
return plan
|
|
1382
|
+
|
|
1383
|
+
|
|
1384
|
+
def apply_activations(ctx: Ctx, plan: list, reason: str, action: str = "activate") -> list:
|
|
1385
|
+
flips = []
|
|
1386
|
+
for consumer, n, prev, missing in plan:
|
|
1387
|
+
fault("pre-flip")
|
|
1388
|
+
flip(ctx.root, consumer, n)
|
|
1389
|
+
history(ctx.root, action, consumer=consumer, **{"from": prev, "to": n}, manifest_serial=ctx.serial, reason=reason,
|
|
1390
|
+
missing_flags=missing or None)
|
|
1391
|
+
fault("post-flip")
|
|
1392
|
+
flips.append({"consumer": consumer, "from": prev, "to": n, "restart_pending": prev != n, "missing_flags": missing})
|
|
1393
|
+
return flips
|
|
1394
|
+
|
|
1395
|
+
|
|
1396
|
+
def previous_target(root: pathlib.Path, consumer: str, cur):
|
|
1397
|
+
for rec in reversed(read_history(root)):
|
|
1398
|
+
if rec.get("consumer") == consumer and rec.get("action") in FLIP_ACTIONS and rec.get("to") == cur:
|
|
1399
|
+
return rec.get("from")
|
|
1400
|
+
return None
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
# ── box copy and KODE_HOME facts ────────────────────────────────────────────
|
|
1404
|
+
|
|
1405
|
+
def self_install(ctx: Ctx) -> None:
|
|
1406
|
+
"""The box keeps the CLI and manifest it last applied, so `toolchain which` works without a checkout."""
|
|
1407
|
+
bin_dir = ctx.root / "bin"
|
|
1408
|
+
src = pathlib.Path(__file__).resolve()
|
|
1409
|
+
for dest, data, mode in ((bin_dir / "toolchain.py", src.read_bytes(), 0o644), (bin_dir / "toolchain", SHIM.encode(), 0o755),
|
|
1410
|
+
(ctx.root / "manifest.applied.json", ctx.manifest_bytes, 0o644)):
|
|
1411
|
+
with contextlib.suppress(OSError):
|
|
1412
|
+
if dest.read_bytes() == data and stat.S_IMODE(dest.stat().st_mode) == mode:
|
|
1413
|
+
continue
|
|
1414
|
+
durable_write(dest, data, mode)
|
|
1415
|
+
|
|
1416
|
+
|
|
1417
|
+
def write_kode_facts(rows: dict) -> None:
|
|
1418
|
+
"""tools.<pkg> rows in KODE_HOME's facts.json, plus generated and source. toolkit-verify.sh owns `toolkit`; both
|
|
1419
|
+
writers hold .facts.lock and replace the file atomically, and an unparsable file is kept, not reset."""
|
|
1420
|
+
tools_dir = kode_home() / "tools"
|
|
1421
|
+
path = tools_dir / "facts.json"
|
|
1422
|
+
guard_write(path)
|
|
1423
|
+
tools_dir.mkdir(parents=True, exist_ok=True)
|
|
1424
|
+
fd = os.open(tools_dir / ".facts.lock", os.O_CREAT | os.O_RDWR, 0o644)
|
|
1425
|
+
try:
|
|
1426
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
1427
|
+
facts = {}
|
|
1428
|
+
if path.exists():
|
|
1429
|
+
raw = path.read_bytes()
|
|
1430
|
+
try:
|
|
1431
|
+
facts = json.loads(raw)
|
|
1432
|
+
if not isinstance(facts, dict):
|
|
1433
|
+
raise ValueError("not an object")
|
|
1434
|
+
except ValueError:
|
|
1435
|
+
durable_write(path.with_name("facts.json.corrupt"), raw)
|
|
1436
|
+
say(f"warning: {path} was unparsable; kept it as facts.json.corrupt")
|
|
1437
|
+
facts = {}
|
|
1438
|
+
tools = facts.get("tools") if isinstance(facts.get("tools"), dict) else {}
|
|
1439
|
+
tools.update(rows)
|
|
1440
|
+
facts.update({"tools": tools, "generated": now(), "source": "operator-toolchain"})
|
|
1441
|
+
durable_write(path, (json.dumps(facts, indent=1) + "\n").encode())
|
|
1442
|
+
finally:
|
|
1443
|
+
os.close(fd)
|
|
1444
|
+
|
|
1445
|
+
|
|
1446
|
+
def sync_kode_facts(root: pathlib.Path) -> None:
|
|
1447
|
+
"""Rows describe ~/.operator/tools/<entry>, so they are written only once that path is ours (after migrate)."""
|
|
1448
|
+
compat = operator_home() / "tools"
|
|
1449
|
+
if not compat.is_symlink() or os.path.realpath(compat) != os.path.realpath(root / "consumers" / "aurora"):
|
|
1450
|
+
return
|
|
1451
|
+
g = load_generation(root, current_generation(root, "aurora"))
|
|
1452
|
+
if g:
|
|
1453
|
+
write_kode_facts({name: {"path": str(compat / p["entry"]), "version": p["version"]} for name, p in sorted(g["packages"].items())})
|
|
1454
|
+
|
|
1455
|
+
|
|
1456
|
+
# ── live servers ────────────────────────────────────────────────────────────
|
|
1457
|
+
|
|
1458
|
+
def proc_fixture():
|
|
1459
|
+
path = os.environ.get("OPERATOR_TOOLCHAIN_PROCS") if test_mode() else None
|
|
1460
|
+
return read_json(path, {}) if path else None
|
|
1461
|
+
|
|
1462
|
+
|
|
1463
|
+
def llama_pids() -> set:
|
|
1464
|
+
fx = proc_fixture()
|
|
1465
|
+
if fx is not None or test_mode():
|
|
1466
|
+
return {int(p) for p in (fx or {}).get("pgrep", [])}
|
|
1467
|
+
r = run(["/usr/bin/pgrep", "-x", "llama-server"], timeout=10)
|
|
1468
|
+
if r.returncode not in (0, 1):
|
|
1469
|
+
raise ToolchainError(f"pgrep -x llama-server failed: {first_line(r.stderr)}")
|
|
1470
|
+
return {int(p) for p in r.stdout.split()}
|
|
1471
|
+
|
|
1472
|
+
|
|
1473
|
+
def live_servers() -> list:
|
|
1474
|
+
"""Every running llama-server: pid, argv (ps) and mapped files (lsof -a -p PID -d txt; without -a lsof ORs them)."""
|
|
1475
|
+
fx = proc_fixture()
|
|
1476
|
+
out = []
|
|
1477
|
+
for pid in sorted(llama_pids()):
|
|
1478
|
+
if fx is not None:
|
|
1479
|
+
info = (fx.get("procs") or {}).get(str(pid)) or {}
|
|
1480
|
+
command, lsof = info.get("command", ""), info.get("lsof", "")
|
|
1481
|
+
else:
|
|
1482
|
+
command = run(["/bin/ps", "-p", pid, "-o", "command="], timeout=10).stdout.strip()
|
|
1483
|
+
lsof = run(["/usr/sbin/lsof", "-nP", "-a", "-p", pid, "-d", "txt", "-Fn"], timeout=20).stdout
|
|
1484
|
+
if command:
|
|
1485
|
+
out.append({"pid": pid, "argv": command.split(), "txt": [l[1:] for l in lsof.splitlines() if l.startswith("n")]})
|
|
1486
|
+
return out
|
|
1487
|
+
|
|
1488
|
+
|
|
1489
|
+
def classify(root: pathlib.Path, manifest: dict, procs: list, box: str = None, today: dt.date = None) -> list:
|
|
1490
|
+
"""ok, restart pending, unmanaged or exception for each live llama-server."""
|
|
1491
|
+
box, today = box or box_name(), today or utc_today()
|
|
1492
|
+
store, compat = os.path.realpath(root / "store"), str(operator_home() / "tools")
|
|
1493
|
+
compat_is_ours = os.path.realpath(compat) == os.path.realpath(root / "consumers" / "aurora")
|
|
1494
|
+
cdirs = {str(root / "consumers"), os.path.realpath(root / "consumers")}
|
|
1495
|
+
current = {}
|
|
1496
|
+
for c in consumer_names(root):
|
|
1497
|
+
g = load_generation(root, current_generation(root, c)) or {}
|
|
1498
|
+
current[c] = {p["store_entry"] for p in g.get("packages", {}).values()}
|
|
1499
|
+
out = []
|
|
1500
|
+
for p in procs:
|
|
1501
|
+
argv = p.get("argv") or [""]
|
|
1502
|
+
mapped = next((t for t in p.get("txt", []) if os.path.basename(t) == "llama-server"), None) or argv[0]
|
|
1503
|
+
real = os.path.realpath(mapped)
|
|
1504
|
+
entry = os.path.relpath(real, store).split(os.sep)[0] if within(real, store) else None
|
|
1505
|
+
consumer = next((os.path.relpath(argv[0], d).split(os.sep)[0] for d in cdirs if within(argv[0], d)), None)
|
|
1506
|
+
if consumer is None and compat_is_ours and within(argv[0], compat):
|
|
1507
|
+
consumer = "aurora"
|
|
1508
|
+
port = next((argv[i + 1] for i, a in enumerate(argv[:-1]) if a == "--port"), None)
|
|
1509
|
+
exc = next((e for e in manifest.get("exceptions") or [] if (box == e.get("box") or box.startswith(f"{e.get('box')}-"))
|
|
1510
|
+
and e.get("match") and e["match"] in " ".join(argv) and parse_date(e.get("until", "1970-01-01")) >= today), None)
|
|
1511
|
+
if exc:
|
|
1512
|
+
state = "exception"
|
|
1513
|
+
elif consumer in current and entry in current[consumer]:
|
|
1514
|
+
state = "ok"
|
|
1515
|
+
elif consumer in current:
|
|
1516
|
+
state = "restart pending"
|
|
1517
|
+
elif entry and any(entry in v for v in current.values()):
|
|
1518
|
+
state = "ok"
|
|
1519
|
+
elif entry:
|
|
1520
|
+
state = "restart pending"
|
|
1521
|
+
else:
|
|
1522
|
+
state = "unmanaged"
|
|
1523
|
+
meta = read_json(pathlib.Path(store) / entry / ENTRY_META, {}) if entry else {}
|
|
1524
|
+
out.append({"pid": p["pid"], "port": port, "consumer": consumer, "binary": real, "entry": entry,
|
|
1525
|
+
"build": meta.get("version"), "state": state, **({"exception": exc.get("reason")} if exc else {})})
|
|
1526
|
+
return out
|
|
1527
|
+
|
|
1528
|
+
|
|
1529
|
+
def local_http(url: str, data=None, headers=None, timeout: float = 30) -> tuple:
|
|
1530
|
+
"""(status, body) from a loopback server, never through a proxy."""
|
|
1531
|
+
if urllib.parse.urlsplit(url).hostname not in LOOPBACK:
|
|
1532
|
+
raise Refused(f"refusing a non-loopback request: {url}")
|
|
1533
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
1534
|
+
req = urllib.request.Request(url, data=json.dumps(data).encode() if data is not None else None,
|
|
1535
|
+
headers={"Content-Type": "application/json", **(headers or {})})
|
|
1536
|
+
try:
|
|
1537
|
+
with opener.open(req, timeout=timeout) as r:
|
|
1538
|
+
return r.status, r.read()
|
|
1539
|
+
except urllib.error.HTTPError as e:
|
|
1540
|
+
return e.code, e.read()
|
|
1541
|
+
|
|
1542
|
+
|
|
1543
|
+
def probe_build(port, api_key=None):
|
|
1544
|
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
|
1545
|
+
with contextlib.suppress(OSError, ValueError, http.client.HTTPException):
|
|
1546
|
+
status, body = local_http(f"http://127.0.0.1:{port}/props", headers=headers, timeout=5)
|
|
1547
|
+
if status == 200:
|
|
1548
|
+
return json.loads(body).get("build_info")
|
|
1549
|
+
return None
|
|
1550
|
+
|
|
1551
|
+
|
|
1552
|
+
# ── commands: install, activate, rollback, which ────────────────────────────
|
|
1553
|
+
|
|
1554
|
+
def emit(args, obj, text: str) -> None:
|
|
1555
|
+
print(json.dumps(obj, indent=1, sort_keys=True) if getattr(args, "json", False) else text)
|
|
1556
|
+
|
|
1557
|
+
|
|
1558
|
+
def cmd_install(args) -> int:
|
|
1559
|
+
ctx = Ctx(args)
|
|
1560
|
+
specs = args.packages or sorted(n for n, p in (ctx.manifest.get("packages") or {}).items() if p.get("install") == "default")
|
|
1561
|
+
rows = [row_for(ctx.manifest, s) for s in specs]
|
|
1562
|
+
names = [r[0] for r in rows]
|
|
1563
|
+
if len(set(names)) != len(names):
|
|
1564
|
+
raise Refused(f"one row per package per install: {specs}")
|
|
1565
|
+
if args.witness:
|
|
1566
|
+
reports = [realize(ctx, name, which, row, witness=True) for name, which, row in rows]
|
|
1567
|
+
print(json.dumps({"witness": reports}, indent=1, sort_keys=True))
|
|
1568
|
+
return EX_OK if all(r["clean"] for r in reports) else EX_ERROR
|
|
1569
|
+
consumers = parse_consumers(args.activate) if args.activate else []
|
|
1570
|
+
with mutation(ctx.root):
|
|
1571
|
+
packages, row_by_name = {}, {}
|
|
1572
|
+
for name, which, row in rows:
|
|
1573
|
+
packages[name] = gen_package(realize(ctx, name, which, row), row)
|
|
1574
|
+
row_by_name[name] = row
|
|
1575
|
+
n = find_generation(ctx.root, packages)
|
|
1576
|
+
created = n is None
|
|
1577
|
+
if created:
|
|
1578
|
+
n = build_generation(ctx, packages, row_by_name)
|
|
1579
|
+
else:
|
|
1580
|
+
seal_generation(ctx.root, n)
|
|
1581
|
+
history(ctx.root, "install", to=n, manifest_serial=ctx.serial, reason=args.reason, packages=sorted(specs), new=created)
|
|
1582
|
+
fault("post-generation")
|
|
1583
|
+
plan = plan_activations(ctx, [(c, n) for c in consumers], args.force_flags)
|
|
1584
|
+
self_install(ctx)
|
|
1585
|
+
flips = apply_activations(ctx, plan, args.reason or "install")
|
|
1586
|
+
sync_kode_facts(ctx.root)
|
|
1587
|
+
pending = [f["consumer"] for f in flips if f["restart_pending"]]
|
|
1588
|
+
lines = [f"generation {n} ({'new' if created else 'reused'}): " + ", ".join(f"{k} {p['version']}" for k, p in sorted(packages.items()))]
|
|
1589
|
+
lines += [f"{f['consumer']}: {f['from']} -> {f['to']}" for f in flips]
|
|
1590
|
+
if pending:
|
|
1591
|
+
lines.append(f"restart pending: {', '.join(pending)}")
|
|
1592
|
+
elif not consumers:
|
|
1593
|
+
lines.append(f"not activated: toolchain activate {n} --consumer C --reason TEXT")
|
|
1594
|
+
emit(args, {"generation": n, "new": created, "packages": packages, "activated": flips, "restart_pending": pending}, "\n".join(lines))
|
|
1595
|
+
return EX_OK
|
|
1596
|
+
|
|
1597
|
+
|
|
1598
|
+
def cmd_activate(args) -> int:
|
|
1599
|
+
ctx = Ctx(args)
|
|
1600
|
+
consumers = parse_consumers(args.consumer)
|
|
1601
|
+
with mutation(ctx.root):
|
|
1602
|
+
plan = plan_activations(ctx, [(c, args.generation) for c in consumers], args.force_flags)
|
|
1603
|
+
self_install(ctx)
|
|
1604
|
+
flips = apply_activations(ctx, plan, args.reason)
|
|
1605
|
+
sync_kode_facts(ctx.root)
|
|
1606
|
+
pending = [f["consumer"] for f in flips if f["restart_pending"]]
|
|
1607
|
+
emit(args, {"activated": flips, "restart_pending": pending},
|
|
1608
|
+
"\n".join([f"{f['consumer']}: {f['from']} -> {f['to']}" for f in flips] + ([f"restart pending: {', '.join(pending)}"] if pending else [])))
|
|
1609
|
+
return EX_OK
|
|
1610
|
+
|
|
1611
|
+
|
|
1612
|
+
def cmd_rollback(args) -> int:
|
|
1613
|
+
ctx = Ctx(args)
|
|
1614
|
+
consumers = parse_consumers(args.consumer)
|
|
1615
|
+
with mutation(ctx.root):
|
|
1616
|
+
targets = []
|
|
1617
|
+
for c in consumers:
|
|
1618
|
+
cur = current_generation(ctx.root, c)
|
|
1619
|
+
if cur is None:
|
|
1620
|
+
raise Refused(f"consumer {c} is not activated")
|
|
1621
|
+
to = args.to if args.to is not None else previous_target(ctx.root, c, cur)
|
|
1622
|
+
if to is None:
|
|
1623
|
+
raise Refused(f"{c}: history records no generation before {cur}; pass --to GEN")
|
|
1624
|
+
targets.append((c, to))
|
|
1625
|
+
flips = apply_activations(ctx, plan_activations(ctx, targets, args.force_flags), args.reason, action="rollback")
|
|
1626
|
+
sync_kode_facts(ctx.root)
|
|
1627
|
+
emit(args, {"rolled_back": flips}, "\n".join(f"{f['consumer']}: {f['from']} -> {f['to']} (restart pending)" for f in flips))
|
|
1628
|
+
return EX_OK
|
|
1629
|
+
|
|
1630
|
+
|
|
1631
|
+
def resolve_bin(root: pathlib.Path, consumer: str, binary: str) -> tuple:
|
|
1632
|
+
for n in (consumer, binary):
|
|
1633
|
+
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", n):
|
|
1634
|
+
raise Refused(f"invalid name {n!r}")
|
|
1635
|
+
link, cdir = root / "consumers" / consumer / "bin" / binary, root / "consumers" / consumer
|
|
1636
|
+
if not os.path.exists(cdir):
|
|
1637
|
+
raise Refused(f"consumer {consumer} is not activated in {root} ({cdir} is missing or dangling)")
|
|
1638
|
+
gen = os.path.realpath(cdir)
|
|
1639
|
+
if not re.fullmatch(r"\d+", os.path.basename(gen)) or os.path.dirname(gen) != os.path.realpath(root / "generations"):
|
|
1640
|
+
raise Refused(f"{cdir} points at {gen}, not a generation")
|
|
1641
|
+
# through the generation just resolved, as the gateway and engine do: back through the consumer link, a flip in between would pair generation N with another build
|
|
1642
|
+
store, real = os.path.realpath(root / "store"), os.path.realpath(os.path.join(gen, "bin", binary))
|
|
1643
|
+
rel = os.path.relpath(real, store)
|
|
1644
|
+
entry = rel.split(os.sep)[0] if within(real, store) else ""
|
|
1645
|
+
if not entry or entry == rel or entry.startswith(".") or not os.path.isfile(real) or not os.access(real, os.X_OK):
|
|
1646
|
+
raise Refused(f"{link} does not resolve into a sealed entry in {root / 'store'} (it resolves to {real})")
|
|
1647
|
+
if os.access(os.path.join(store, entry), os.W_OK):
|
|
1648
|
+
raise Refused(f"store/{entry} is writable: the entry is no longer sealed (toolchain verify --deep)")
|
|
1649
|
+
return link, real
|
|
1650
|
+
|
|
1651
|
+
|
|
1652
|
+
def cmd_which(args) -> int:
|
|
1653
|
+
root = resolve_root(args.root)
|
|
1654
|
+
link, real = resolve_bin(root, args.consumer, args.bin)
|
|
1655
|
+
print(real if args.resolve else link)
|
|
1656
|
+
return EX_OK
|
|
1657
|
+
|
|
1658
|
+
|
|
1659
|
+
# ── commands: verify, status, gc ────────────────────────────────────────────
|
|
1660
|
+
|
|
1661
|
+
def inspect(ctx: Ctx, deep: bool = False, probe: bool = False) -> dict:
|
|
1662
|
+
root, problems, notes = ctx.root, [], []
|
|
1663
|
+
consumers = {}
|
|
1664
|
+
for c in consumer_names(root):
|
|
1665
|
+
n = current_generation(root, c)
|
|
1666
|
+
if n is None:
|
|
1667
|
+
problems.append(f"consumers/{c} -> {os.readlink(root / 'consumers' / c) if (root / 'consumers' / c).is_symlink() else '?'} is not a generation")
|
|
1668
|
+
continue
|
|
1669
|
+
probs = generation_problems(root, n)
|
|
1670
|
+
problems += [f"{c}: {p}" for p in probs]
|
|
1671
|
+
g = load_generation(root, n) or {}
|
|
1672
|
+
consumers[c] = {"generation": n, "packages": {k: f"{p['version']} ({p['store_entry']})" for k, p in g.get("packages", {}).items()}}
|
|
1673
|
+
for name, p in sorted(g.get("packages", {}).items()):
|
|
1674
|
+
which, row = row_matching(ctx.manifest, p)
|
|
1675
|
+
if row is None:
|
|
1676
|
+
problems.append(f"{c}: gen {n} {name} {p['version']} ({p['store_entry']}) is in neither the current nor the previous manifest row")
|
|
1677
|
+
elif which == "previous" and parse_date(row.get("until", "1970-01-01")) < utc_today():
|
|
1678
|
+
notes.append(f"{c}: {name} {p['version']} is the previous row, whose window closed {row.get('until')}")
|
|
1679
|
+
if deep and not probs:
|
|
1680
|
+
entry = root / "store" / p["store_entry"]
|
|
1681
|
+
if canonical_tree(entry) != p["tree"]:
|
|
1682
|
+
problems.append(f"{c}: store/{p['store_entry']} no longer hashes to {p['tree']}")
|
|
1683
|
+
if pm_digest(entry) != p["digest"]:
|
|
1684
|
+
problems.append(f"{c}: store/{p['store_entry']} pm digest drifted from {p['digest']}")
|
|
1685
|
+
if row is not None:
|
|
1686
|
+
problems += [f"{c}: {x}" for x in codesign_problems([entry / rel for rel in p["provides"].values()], row.get("codesign"))]
|
|
1687
|
+
compat = operator_home() / "tools"
|
|
1688
|
+
if compat.is_symlink():
|
|
1689
|
+
target = os.path.realpath(compat)
|
|
1690
|
+
if target == os.path.realpath(root / "consumers" / "aurora"):
|
|
1691
|
+
notes.append(f"{compat} -> consumers/aurora")
|
|
1692
|
+
elif any(within(target, h) for h in hermes_dirs()):
|
|
1693
|
+
notes.append(f"{compat} still resolves into Hermes ({target}): not migrated")
|
|
1694
|
+
kfacts = read_json(kode_home() / "tools" / "facts.json") or {}
|
|
1695
|
+
for k, v in sorted((kfacts.get("tools") or {}).items() if isinstance(kfacts, dict) else []):
|
|
1696
|
+
if isinstance(v, dict) and any(within(os.path.realpath(str(v.get("path", ""))), h) or within(str(v.get("path", "")), h)
|
|
1697
|
+
for h in hermes_dirs()):
|
|
1698
|
+
notes.append(f"{kode_home() / 'tools/facts.json'} tools.{k} still points into Hermes: {v.get('path')}")
|
|
1699
|
+
try:
|
|
1700
|
+
live = classify(root, ctx.manifest, live_servers())
|
|
1701
|
+
except (ToolchainError, OSError, ValueError, subprocess.SubprocessError) as e:
|
|
1702
|
+
live = []
|
|
1703
|
+
notes.append(f"live llama-servers not inspected: {e}")
|
|
1704
|
+
if probe:
|
|
1705
|
+
key = None
|
|
1706
|
+
with contextlib.suppress(OSError):
|
|
1707
|
+
key = (operator_home() / "runtime" / ".api_key").read_text().strip() or None
|
|
1708
|
+
for s in live:
|
|
1709
|
+
if s["port"]:
|
|
1710
|
+
s["build_info"] = probe_build(s["port"], key if s["consumer"] == "aurora" else None)
|
|
1711
|
+
return {"result": "drift" if problems else "ok", "ts": now(), "root": str(root), "deep": deep, "problems": problems,
|
|
1712
|
+
"notes": notes, "consumers": consumers, "live": live}
|
|
1713
|
+
|
|
1714
|
+
|
|
1715
|
+
def cmd_verify(args) -> int:
|
|
1716
|
+
ctx = Ctx(args)
|
|
1717
|
+
if not (ctx.root / ".lock").exists():
|
|
1718
|
+
emit(args, {"result": "unmanaged", "root": str(ctx.root)}, f"unmanaged: {ctx.root} has no .lock")
|
|
1719
|
+
return EX_OK
|
|
1720
|
+
state = inspect(ctx, deep=args.deep, probe=args.probe)
|
|
1721
|
+
durable_write(ctx.root / "state.json", canonical(state))
|
|
1722
|
+
if not args.quiet or state["problems"]:
|
|
1723
|
+
lines = [f"verify{' --deep' if args.deep else ''}: {state['result']}"]
|
|
1724
|
+
lines += [f" drift: {p}" for p in state["problems"]] + [f" note: {n}" for n in state["notes"]]
|
|
1725
|
+
lines += [f" live pid {s['pid']} :{s['port'] or '?'} {s['consumer'] or '-'} {s['state']}: {s['binary']}" for s in state["live"]]
|
|
1726
|
+
emit(args, state, "\n".join(lines))
|
|
1727
|
+
return EX_DRIFT if state["problems"] else EX_OK
|
|
1728
|
+
|
|
1729
|
+
|
|
1730
|
+
def cmd_status(args) -> int:
|
|
1731
|
+
ctx = Ctx(args)
|
|
1732
|
+
state = inspect(ctx)
|
|
1733
|
+
last = read_json(ctx.root / "state.json") or {}
|
|
1734
|
+
lines = [f"root {ctx.root} ({'managed' if (ctx.root / '.lock').exists() else 'unmanaged'}), manifest serial {ctx.serial}"]
|
|
1735
|
+
for c, v in sorted(state["consumers"].items()):
|
|
1736
|
+
lines.append(f" {c} -> generation {v['generation']}: " + ", ".join(f"{k} {p}" for k, p in sorted(v["packages"].items())))
|
|
1737
|
+
if not state["consumers"]:
|
|
1738
|
+
lines.append(" no consumer is activated")
|
|
1739
|
+
for s in state["live"]:
|
|
1740
|
+
lines.append(f" pid {s['pid']} port {s['port'] or '?'} consumer {s['consumer'] or '-'} entry {s['entry'] or '-'} "
|
|
1741
|
+
f"build {s['build'] or '?'}: {s['state']}{' (' + s['exception'] + ')' if s.get('exception') else ''} {s['binary']}")
|
|
1742
|
+
lines += [f" drift: {p}" for p in state["problems"]] + [f" note: {n}" for n in state["notes"]]
|
|
1743
|
+
if last:
|
|
1744
|
+
lines.append(f" last verify: {last.get('result')} at {last.get('ts')}")
|
|
1745
|
+
emit(args, {**state, "last_verify": last}, "\n".join(lines))
|
|
1746
|
+
return EX_OK
|
|
1747
|
+
|
|
1748
|
+
|
|
1749
|
+
def du(path) -> int:
|
|
1750
|
+
total = 0
|
|
1751
|
+
for d, dirs, files in os.walk(path):
|
|
1752
|
+
for name in dirs + files:
|
|
1753
|
+
with contextlib.suppress(OSError):
|
|
1754
|
+
total += os.lstat(os.path.join(d, name)).st_size
|
|
1755
|
+
return total
|
|
1756
|
+
|
|
1757
|
+
|
|
1758
|
+
def referenced_paths() -> list:
|
|
1759
|
+
"""Paths named by launchd jobs (ProgramArguments) and portal recipes, which may exec a store binary at next start."""
|
|
1760
|
+
out = []
|
|
1761
|
+
agents = env_home() / "Library" / "LaunchAgents"
|
|
1762
|
+
for plist in sorted(agents.glob("*.plist")) if agents.is_dir() else []:
|
|
1763
|
+
with contextlib.suppress(Exception):
|
|
1764
|
+
with open(plist, "rb") as f:
|
|
1765
|
+
d = plistlib.load(f)
|
|
1766
|
+
out += [s for s in [d.get("Program")] + list(d.get("ProgramArguments") or []) if isinstance(s, str) and s.startswith("/")]
|
|
1767
|
+
models = read_json(portal_home() / "models.json") or {}
|
|
1768
|
+
for m in models.get("models", []) if isinstance(models, dict) else []:
|
|
1769
|
+
cmd = ((m or {}).get("recipe") or {}).get("command")
|
|
1770
|
+
if isinstance(cmd, str) and cmd.startswith("/"):
|
|
1771
|
+
out.append(cmd)
|
|
1772
|
+
return out
|
|
1773
|
+
|
|
1774
|
+
|
|
1775
|
+
def open_entries(store: pathlib.Path) -> set:
|
|
1776
|
+
"""Entries any process holds open or maps (lsof +D lists both)."""
|
|
1777
|
+
if not store.is_dir():
|
|
1778
|
+
return set()
|
|
1779
|
+
real = os.path.realpath(store)
|
|
1780
|
+
r = run(["/usr/sbin/lsof", "-nP", "-Fn", "+D", real], timeout=120)
|
|
1781
|
+
return {os.path.relpath(l[1:], real).split(os.sep)[0] for l in r.stdout.splitlines() if l.startswith("n") and within(l[1:], real)}
|
|
1782
|
+
|
|
1783
|
+
|
|
1784
|
+
def gc_plan(ctx: Ctx, keep: int) -> dict:
|
|
1785
|
+
root, today = ctx.root, utc_today()
|
|
1786
|
+
gens, hist = generation_numbers(root), read_history(root)
|
|
1787
|
+
keep_gens, keep_entries = set(), set()
|
|
1788
|
+
for c in consumer_names(root):
|
|
1789
|
+
cur = current_generation(root, c)
|
|
1790
|
+
if cur is not None:
|
|
1791
|
+
keep_gens.add(cur)
|
|
1792
|
+
seen = []
|
|
1793
|
+
for rec in reversed(hist):
|
|
1794
|
+
if rec.get("consumer") == c and rec.get("action") in FLIP_ACTIONS:
|
|
1795
|
+
for g in (rec.get("to"), rec.get("from")):
|
|
1796
|
+
if isinstance(g, int) and g not in seen:
|
|
1797
|
+
seen.append(g)
|
|
1798
|
+
keep_gens.update(seen[:keep])
|
|
1799
|
+
week = dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=7)
|
|
1800
|
+
for rec in hist:
|
|
1801
|
+
with contextlib.suppress(ValueError, TypeError):
|
|
1802
|
+
if parse_ts(rec.get("ts")) >= week:
|
|
1803
|
+
keep_gens.update(g for g in (rec.get("to"), rec.get("from")) if isinstance(g, int))
|
|
1804
|
+
store, gdir = os.path.realpath(root / "store"), os.path.realpath(root / "generations")
|
|
1805
|
+
for p in referenced_paths():
|
|
1806
|
+
real = os.path.realpath(p)
|
|
1807
|
+
for path in (p, real):
|
|
1808
|
+
m = re.search(r"/generations/(\d+)(/|$)", path)
|
|
1809
|
+
if m and (within(path, gdir) or within(path, str(root / "generations"))):
|
|
1810
|
+
keep_gens.add(int(m.group(1)))
|
|
1811
|
+
if within(real, store):
|
|
1812
|
+
keep_entries.add(os.path.relpath(real, store).split(os.sep)[0])
|
|
1813
|
+
keep_entries |= open_entries(root / "store")
|
|
1814
|
+
for name, which, row in manifest_rows(ctx.manifest):
|
|
1815
|
+
if which == "current" or parse_date(row.get("until", "1970-01-01")) >= today:
|
|
1816
|
+
with contextlib.suppress(ToolchainError, KeyError):
|
|
1817
|
+
keep_entries.add(store_name(row, ctx.target))
|
|
1818
|
+
for n in keep_gens:
|
|
1819
|
+
keep_entries |= {p["store_entry"] for p in (load_generation(root, n) or {}).get("packages", {}).values()}
|
|
1820
|
+
keep_blobs = {a["sha256"] for _, _, row in manifest_rows(ctx.manifest) for a in artifacts_for(row, ctx.target)}
|
|
1821
|
+
keep_blobs |= {f.get("sha256") for f in (ctx.manifest.get("fixtures") or {}).values()}
|
|
1822
|
+
entries = sorted(p.name for p in (root / "store").iterdir() if not p.name.startswith(".")) if (root / "store").is_dir() else []
|
|
1823
|
+
for e in entries:
|
|
1824
|
+
if e in keep_entries:
|
|
1825
|
+
keep_blobs |= set((read_json(root / "store" / e / ENTRY_META) or {}).get("artifacts", []))
|
|
1826
|
+
blobs = sorted(p.name for p in (root / "cas" / "sha256").iterdir()) if (root / "cas" / "sha256").is_dir() else []
|
|
1827
|
+
victims = [root / "generations" / str(n) for n in gens if n not in keep_gens]
|
|
1828
|
+
victims += [root / "store" / e for e in entries if e not in keep_entries]
|
|
1829
|
+
victims += [root / "cas" / "sha256" / b for b in blobs if b not in keep_blobs]
|
|
1830
|
+
return {"keep_generations": sorted(keep_gens), "keep_entries": sorted(keep_entries & set(entries)),
|
|
1831
|
+
"delete": [{"path": str(v), "bytes": du(v) if v.is_dir() else v.stat().st_size} for v in victims]}
|
|
1832
|
+
|
|
1833
|
+
|
|
1834
|
+
def cmd_gc(args) -> int:
|
|
1835
|
+
ctx = Ctx(args)
|
|
1836
|
+
if not (ctx.root / ".lock").exists():
|
|
1837
|
+
raise Refused(f"{ctx.root} is not a managed toolchain root")
|
|
1838
|
+
if not args.apply:
|
|
1839
|
+
plan = gc_plan(ctx, args.keep)
|
|
1840
|
+
lines = [f"gc dry run: keep generations {plan['keep_generations']}"]
|
|
1841
|
+
lines += [f" would delete {d['path']} ({d['bytes']} bytes)" for d in plan["delete"]] or [" nothing to delete"]
|
|
1842
|
+
emit(args, plan, "\n".join(lines))
|
|
1843
|
+
return EX_OK
|
|
1844
|
+
with mutation(ctx.root):
|
|
1845
|
+
plan = gc_plan(ctx, args.keep)
|
|
1846
|
+
trash = ctx.root / ".trash"
|
|
1847
|
+
guard_write(trash)
|
|
1848
|
+
trash.mkdir(exist_ok=True)
|
|
1849
|
+
for d in plan["delete"]:
|
|
1850
|
+
p = pathlib.Path(d["path"])
|
|
1851
|
+
if not within(os.path.join(os.path.realpath(p.parent), p.name), os.path.realpath(ctx.root)):
|
|
1852
|
+
raise Refused(f"refusing to delete outside {ctx.root}: {p}")
|
|
1853
|
+
guard_write(p)
|
|
1854
|
+
if p.is_dir() and not p.is_symlink():
|
|
1855
|
+
os.chmod(p, 0o755)
|
|
1856
|
+
os.rename(p, trash / f"{p.parent.name}-{p.name}")
|
|
1857
|
+
fsync_path(ctx.root)
|
|
1858
|
+
for p in list(trash.iterdir()):
|
|
1859
|
+
force_rmtree(p, ctx.root)
|
|
1860
|
+
history(ctx.root, "gc", manifest_serial=ctx.serial, deleted=[d["path"] for d in plan["delete"]])
|
|
1861
|
+
emit(args, plan, "\n".join([f"deleted {d['path']} ({d['bytes']} bytes)" for d in plan["delete"]] or ["nothing to delete"]))
|
|
1862
|
+
return EX_OK
|
|
1863
|
+
|
|
1864
|
+
|
|
1865
|
+
# ── migrate ─────────────────────────────────────────────────────────────────
|
|
1866
|
+
|
|
1867
|
+
def ps_start(pid) -> float | None:
|
|
1868
|
+
"""A process's start time in epoch seconds, as server.cjs records create_time (ps lstart, second resolution). Read
|
|
1869
|
+
from libproc first: /bin/ps is setuid, and a seatbelt profile (the CI sandbox) refuses to exec it."""
|
|
1870
|
+
with contextlib.suppress(Exception):
|
|
1871
|
+
import ctypes
|
|
1872
|
+
buf = ctypes.create_string_buffer(136) # struct proc_bsdinfo; pbi_start_tvsec/usec sit at offset 120
|
|
1873
|
+
if ctypes.CDLL(None).proc_pidinfo(int(pid), 3, ctypes.c_uint64(0), buf, 136) == 136:
|
|
1874
|
+
sec, usec = struct.unpack_from("<QQ", buf.raw, 120)
|
|
1875
|
+
return float(sec) + usec / 1e6
|
|
1876
|
+
with contextlib.suppress(OSError, ValueError, subprocess.SubprocessError):
|
|
1877
|
+
r = run(["/bin/ps", "-p", int(pid), "-o", "lstart="], timeout=10, env={**os.environ, "LC_ALL": "C"})
|
|
1878
|
+
text = " ".join(r.stdout.split())
|
|
1879
|
+
for fmt in ("%a %b %d %H:%M:%S %Y", "%a %d %b %H:%M:%S %Y"):
|
|
1880
|
+
with contextlib.suppress(ValueError):
|
|
1881
|
+
return time.mktime(time.strptime(text, fmt)) if r.returncode == 0 and text else None
|
|
1882
|
+
return None
|
|
1883
|
+
|
|
1884
|
+
|
|
1885
|
+
def aurora_identity() -> dict | None:
|
|
1886
|
+
s = read_json(operator_home() / "runtime" / "server.json")
|
|
1887
|
+
return {"pid": s.get("pid"), "create_time": s.get("create_time")} if isinstance(s, dict) and s.get("pid") else None
|
|
1888
|
+
|
|
1889
|
+
|
|
1890
|
+
def aurora_alive(ident) -> bool:
|
|
1891
|
+
if not ident:
|
|
1892
|
+
return True
|
|
1893
|
+
start = ps_start(ident["pid"])
|
|
1894
|
+
return start is not None and (ident.get("create_time") is None or abs(start - float(ident["create_time"])) < 2)
|
|
1895
|
+
|
|
1896
|
+
|
|
1897
|
+
def link_into(link: pathlib.Path, target: str) -> None:
|
|
1898
|
+
"""Replaces a link (or creates one) with symlink + rename(2) + fsync, atomic when the old one is a link too."""
|
|
1899
|
+
nxt = link.with_name(f".{link.name}.next")
|
|
1900
|
+
guard_write(link)
|
|
1901
|
+
guard_write(nxt)
|
|
1902
|
+
if os.path.lexists(nxt):
|
|
1903
|
+
nxt.unlink()
|
|
1904
|
+
os.symlink(target, nxt)
|
|
1905
|
+
try:
|
|
1906
|
+
os.rename(nxt, link)
|
|
1907
|
+
except OSError as e:
|
|
1908
|
+
with contextlib.suppress(OSError):
|
|
1909
|
+
nxt.unlink()
|
|
1910
|
+
raise ToolchainError(f"cannot replace {link}: {e}")
|
|
1911
|
+
fsync_path(link.parent)
|
|
1912
|
+
|
|
1913
|
+
|
|
1914
|
+
def migrate_from_hermes(ctx: Ctx, args) -> dict:
|
|
1915
|
+
root, compat = ctx.root, operator_home() / "tools"
|
|
1916
|
+
hermes_tools = env_home() / ".hermes" / "tools"
|
|
1917
|
+
hfacts = hermes_tools / "facts.json"
|
|
1918
|
+
if args.undo:
|
|
1919
|
+
last = next((r for r in reversed(read_history(root)) if r.get("action") == "migrate" and r.get("kind") == "from-hermes"), None)
|
|
1920
|
+
if not last:
|
|
1921
|
+
raise Refused("history records no migrate --from-hermes to undo")
|
|
1922
|
+
with mutation(root):
|
|
1923
|
+
if not compat.is_symlink():
|
|
1924
|
+
raise Refused(f"{compat} is not a link; nothing to undo")
|
|
1925
|
+
was = os.readlink(compat)
|
|
1926
|
+
link_into(compat, last["from"])
|
|
1927
|
+
history(root, "migrate", kind="from-hermes-undo", **{"from": was, "to": last["from"]}, reason=args.reason)
|
|
1928
|
+
return {"undone": True, "tools": str(compat), "now": last["from"]}
|
|
1929
|
+
real_hermes = os.path.realpath(hermes_tools)
|
|
1930
|
+
if not compat.is_symlink() or os.path.realpath(compat) != real_hermes:
|
|
1931
|
+
raise Refused(f"{compat} is not a link to {hermes_tools} (it is {os.readlink(compat) if compat.is_symlink() else 'not a link'})")
|
|
1932
|
+
pre = {"hermes_facts_sha256": sha256_file(hfacts) if hfacts.is_file() else None, "aurora": aurora_identity(),
|
|
1933
|
+
"free_bytes": shutil.disk_usage(operator_home()).free, "tools": os.readlink(compat)}
|
|
1934
|
+
if pre["free_bytes"] < 2 << 30:
|
|
1935
|
+
raise Refused(f"less than 2 GB free under {operator_home()}")
|
|
1936
|
+
recorded = (((read_json(hfacts) or {}).get("packages") or {}).get(MIGRATE_PACKAGE) or {}).get("digest")
|
|
1937
|
+
plan = {"preflight": pre, "hermes_digest": recorded, "realize": f"{MIGRATE_PACKAGE}@previous", "consumers": ["aurora", "arena"],
|
|
1938
|
+
"link": f"{compat} -> {os.path.relpath(root / 'consumers' / 'aurora', compat.parent)}"}
|
|
1939
|
+
if args.dry_run:
|
|
1940
|
+
return {"dry_run": True, **plan}
|
|
1941
|
+
if not recorded:
|
|
1942
|
+
raise Refused(f"{hfacts} records no {MIGRATE_PACKAGE} digest to compare against")
|
|
1943
|
+
name, which, row = row_for(ctx.manifest, f"{MIGRATE_PACKAGE}@previous")
|
|
1944
|
+
with mutation(root):
|
|
1945
|
+
meta = realize(ctx, name, which, row)
|
|
1946
|
+
if meta["digest"] != recorded:
|
|
1947
|
+
diff = digest_diff(root / "store" / meta["store_entry"], hermes_tools / meta["entry"])
|
|
1948
|
+
raise Refused(f"{name}@previous pm digest {meta['digest']} != Hermes's recorded {recorded}; differing paths: {diff[:40]}")
|
|
1949
|
+
packages = {name: gen_package(meta, row)}
|
|
1950
|
+
n = find_generation(root, packages)
|
|
1951
|
+
if n is None:
|
|
1952
|
+
n = build_generation(ctx, packages, {name: row})
|
|
1953
|
+
else:
|
|
1954
|
+
seal_generation(root, n)
|
|
1955
|
+
moves = [(c, current_generation(root, c)) for c in ("aurora", "arena")]
|
|
1956
|
+
for c, prev in moves:
|
|
1957
|
+
if prev not in (None, n):
|
|
1958
|
+
raise Refused(f"consumers/{c} is on generation {prev}, not the migrated {n}, so the new link would not run what Aurora runs: "
|
|
1959
|
+
f"toolchain activate {n} --consumer {c} --reason TEXT first")
|
|
1960
|
+
self_install(ctx)
|
|
1961
|
+
for c, prev in moves:
|
|
1962
|
+
flip(root, c, n)
|
|
1963
|
+
history(root, "activate", consumer=c, **{"from": prev, "to": n}, manifest_serial=ctx.serial, reason="migrate --from-hermes")
|
|
1964
|
+
target = os.path.relpath(root / "consumers" / "aurora", compat.parent)
|
|
1965
|
+
link_into(compat, target)
|
|
1966
|
+
history(root, "migrate", kind="from-hermes", **{"from": str(real_hermes), "to": target}, manifest_serial=ctx.serial,
|
|
1967
|
+
reason=args.reason, hermes_facts_sha256=pre["hermes_facts_sha256"])
|
|
1968
|
+
sync_kode_facts(root)
|
|
1969
|
+
return {**plan, "generation": n, "postflight": postflight(ctx, pre, hfacts, row)}
|
|
1970
|
+
|
|
1971
|
+
|
|
1972
|
+
def postflight(ctx: Ctx, pre: dict, hfacts: pathlib.Path, row: dict) -> dict:
|
|
1973
|
+
compat = operator_home() / "tools"
|
|
1974
|
+
out = {"aurora_unchanged": aurora_alive(pre["aurora"]),
|
|
1975
|
+
"tools_link": os.readlink(compat) if compat.is_symlink() else None,
|
|
1976
|
+
"llama_server": os.path.realpath(compat / "llama-server"),
|
|
1977
|
+
"in_store": within(os.path.realpath(compat / "llama-server"), os.path.realpath(ctx.root / "store")),
|
|
1978
|
+
"hermes_facts_unchanged": (sha256_file(hfacts) if hfacts.is_file() else None) == pre["hermes_facts_sha256"]}
|
|
1979
|
+
try:
|
|
1980
|
+
out["probe"] = first_line(run_probe(compat, {**row, "provides": {row["probe"]["bin"]: "llama-server"}})) if row.get("probe") else ""
|
|
1981
|
+
out["probe_ok"] = True
|
|
1982
|
+
except Refused as e:
|
|
1983
|
+
out["probe"], out["probe_ok"] = str(e), False
|
|
1984
|
+
out["verify_deep"] = inspect(ctx, deep=True)["result"]
|
|
1985
|
+
out["ok"] = all([out["aurora_unchanged"], out["in_store"], out["hermes_facts_unchanged"], out["probe_ok"], out["verify_deep"] == "ok"])
|
|
1986
|
+
return out
|
|
1987
|
+
|
|
1988
|
+
|
|
1989
|
+
def migrate_replace_dir(ctx: Ctx, args) -> dict:
|
|
1990
|
+
root, compat = ctx.root, operator_home() / "tools"
|
|
1991
|
+
aside = compat.with_name(f"tools.pre-toolchain-{utc_today().strftime('%Y%m%d')}")
|
|
1992
|
+
if args.undo:
|
|
1993
|
+
last = next((r for r in reversed(read_history(root)) if r.get("action") == "migrate" and r.get("kind") == "replace-tools-dir"), None)
|
|
1994
|
+
if not last or not os.path.isdir(last["from"]):
|
|
1995
|
+
raise Refused("history records no migrate --replace-tools-dir whose directory is still there to restore")
|
|
1996
|
+
with mutation(root):
|
|
1997
|
+
if not compat.is_symlink():
|
|
1998
|
+
raise Refused(f"{compat} is not a link; nothing to undo")
|
|
1999
|
+
guard_write(compat)
|
|
2000
|
+
compat.unlink()
|
|
2001
|
+
os.rename(last["from"], compat)
|
|
2002
|
+
fsync_path(compat.parent)
|
|
2003
|
+
history(root, "migrate", kind="replace-tools-dir-undo", **{"from": last["to"], "to": str(compat)}, reason=args.reason)
|
|
2004
|
+
return {"undone": True, "restored": str(compat)}
|
|
2005
|
+
if compat.is_symlink() or not compat.is_dir():
|
|
2006
|
+
raise Refused(f"{compat} is not a real directory")
|
|
2007
|
+
if current_generation(root, "aurora") is None:
|
|
2008
|
+
raise Refused("consumers/aurora is not activated: run toolchain install --activate aurora,portal,arena first (the link must never dangle)")
|
|
2009
|
+
readers = run(["/usr/sbin/lsof", "-nP", "-Fp", "+D", os.path.realpath(compat)], timeout=60).stdout.split()
|
|
2010
|
+
if readers:
|
|
2011
|
+
raise Refused(f"processes have files open under {compat}: {' '.join(readers)}")
|
|
2012
|
+
if os.path.lexists(aside):
|
|
2013
|
+
raise Refused(f"{aside} already exists")
|
|
2014
|
+
target = os.path.relpath(root / "consumers" / "aurora", compat.parent)
|
|
2015
|
+
with mutation(root):
|
|
2016
|
+
guard_write(compat)
|
|
2017
|
+
guard_write(aside)
|
|
2018
|
+
os.rename(compat, aside)
|
|
2019
|
+
os.symlink(target, compat)
|
|
2020
|
+
fsync_path(compat.parent)
|
|
2021
|
+
history(root, "migrate", kind="replace-tools-dir", **{"from": str(aside), "to": target}, manifest_serial=ctx.serial, reason=args.reason)
|
|
2022
|
+
sync_kode_facts(root)
|
|
2023
|
+
return {"moved_aside": str(aside), "tools": f"{compat} -> {target}"}
|
|
2024
|
+
|
|
2025
|
+
|
|
2026
|
+
def cmd_migrate(args) -> int:
|
|
2027
|
+
ctx = Ctx(args)
|
|
2028
|
+
if args.from_hermes:
|
|
2029
|
+
out = migrate_from_hermes(ctx, args)
|
|
2030
|
+
else:
|
|
2031
|
+
if args.dry_run:
|
|
2032
|
+
raise Refused("--dry-run applies to --from-hermes")
|
|
2033
|
+
out = migrate_replace_dir(ctx, args)
|
|
2034
|
+
emit(args, out, json.dumps(out, indent=1, sort_keys=True))
|
|
2035
|
+
post = out.get("postflight")
|
|
2036
|
+
return EX_ERROR if post and not post["ok"] else EX_OK
|
|
2037
|
+
|
|
2038
|
+
|
|
2039
|
+
# ── smoke ───────────────────────────────────────────────────────────────────
|
|
2040
|
+
|
|
2041
|
+
def stage_fixture(ctx: Ctx, name: str) -> pathlib.Path:
|
|
2042
|
+
fx = (ctx.manifest.get("fixtures") or {}).get(name)
|
|
2043
|
+
if not fx:
|
|
2044
|
+
raise Refused(f"no fixture {name!r} in the manifest")
|
|
2045
|
+
blob = ctx.root / "cas" / "sha256" / fx["sha256"]
|
|
2046
|
+
if blob_ok(blob, fx["sha256"], fx.get("size")):
|
|
2047
|
+
return blob
|
|
2048
|
+
if not (ctx.root / ".lock").exists():
|
|
2049
|
+
raise Refused(f"{ctx.root} is not a managed root to stage the {name} fixture in; pass --gguf PATH")
|
|
2050
|
+
with mutation(ctx.root):
|
|
2051
|
+
path, _ = obtain(fx, ctx.root / "cas", ctx.hosts, cache=ctx.cache, offline=ctx.offline)
|
|
2052
|
+
return path
|
|
2053
|
+
|
|
2054
|
+
|
|
2055
|
+
def stop_own(proc: subprocess.Popen, wait: float) -> dict:
|
|
2056
|
+
"""SIGTERM, then SIGKILL, through the Popen handle: the pid cannot be reused before we reap it."""
|
|
2057
|
+
if proc.poll() is not None:
|
|
2058
|
+
return {"signal": None, "returncode": proc.returncode}
|
|
2059
|
+
proc.send_signal(signal.SIGTERM)
|
|
2060
|
+
try:
|
|
2061
|
+
proc.wait(wait)
|
|
2062
|
+
return {"signal": "SIGTERM", "returncode": proc.returncode}
|
|
2063
|
+
except subprocess.TimeoutExpired:
|
|
2064
|
+
proc.kill()
|
|
2065
|
+
proc.wait()
|
|
2066
|
+
return {"signal": "SIGKILL", "returncode": proc.returncode}
|
|
2067
|
+
|
|
2068
|
+
|
|
2069
|
+
def port_closed(port: int) -> bool:
|
|
2070
|
+
with socket.socket() as s:
|
|
2071
|
+
s.settimeout(1)
|
|
2072
|
+
return s.connect_ex(("127.0.0.1", port)) != 0
|
|
2073
|
+
|
|
2074
|
+
|
|
2075
|
+
def server_argv(binary: str, gguf: pathlib.Path, ngl: int) -> list:
|
|
2076
|
+
return [binary, "--model", str(gguf), "--host", "127.0.0.1", "--port", "0", "-c", "256", "--parallel", "1",
|
|
2077
|
+
"--cache-ram", "0", "--no-webui", "-ngl", str(ngl)]
|
|
2078
|
+
|
|
2079
|
+
|
|
2080
|
+
def exercise_server(rec: dict, log_path: pathlib.Path, died, t0: float, limit: float) -> bool:
|
|
2081
|
+
"""The 'listening on' line, /health and a 4-token completion, which both smoke modes share. died() is None while the
|
|
2082
|
+
server runs, else why it stopped. Fills rec; True when the completion came back."""
|
|
2083
|
+
port = None
|
|
2084
|
+
while time.monotonic() - t0 < limit and port is None and died() is None:
|
|
2085
|
+
m = re.search(r"listening on \S*?:(\d+)", log_path.read_text(errors="replace"))
|
|
2086
|
+
port = int(m.group(1)) if m else None
|
|
2087
|
+
if port is None:
|
|
2088
|
+
time.sleep(0.1)
|
|
2089
|
+
rec["port"] = port
|
|
2090
|
+
if port is None:
|
|
2091
|
+
rec["error"] = f"no 'listening on' line within {limit:.0f} s" if died() is None else died()
|
|
2092
|
+
return False
|
|
2093
|
+
status = None
|
|
2094
|
+
while time.monotonic() - t0 < limit:
|
|
2095
|
+
with contextlib.suppress(OSError, http.client.HTTPException):
|
|
2096
|
+
status, _ = local_http(f"http://127.0.0.1:{port}/health", timeout=5)
|
|
2097
|
+
if status == 200 or died() is not None:
|
|
2098
|
+
break
|
|
2099
|
+
time.sleep(0.25)
|
|
2100
|
+
rec["health"], rec["ready_s"] = status, round(time.monotonic() - t0, 2)
|
|
2101
|
+
if status != 200:
|
|
2102
|
+
rec["error"] = f"/health returned {status}"
|
|
2103
|
+
return False
|
|
2104
|
+
status, body = local_http(f"http://127.0.0.1:{port}/v1/completions", {"prompt": "1+1=", "max_tokens": 4, "temperature": 0}, timeout=60)
|
|
2105
|
+
rec["completion_status"] = status
|
|
2106
|
+
choices = (json.loads(body) if status == 200 else {}).get("choices") or []
|
|
2107
|
+
rec["completion"] = choices[0].get("text") if choices else None
|
|
2108
|
+
if status != 200 or not choices:
|
|
2109
|
+
rec["error"] = f"/v1/completions returned {status}"
|
|
2110
|
+
return False
|
|
2111
|
+
return True
|
|
2112
|
+
|
|
2113
|
+
|
|
2114
|
+
def serve_once(binary: str, gguf: pathlib.Path, ngl: int, term_wait: float, limit: float = 60) -> dict:
|
|
2115
|
+
cmd = server_argv(binary, gguf, ngl)
|
|
2116
|
+
rec = {"ngl": ngl, "argv": cmd, "ok": False}
|
|
2117
|
+
with tempfile.TemporaryDirectory(prefix="toolchain-smoke-") as tmp:
|
|
2118
|
+
log_path = pathlib.Path(tmp) / "server.log"
|
|
2119
|
+
with open(log_path, "wb") as log:
|
|
2120
|
+
t0 = time.monotonic()
|
|
2121
|
+
proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, env=scrubbed_env(),
|
|
2122
|
+
cwd=tmp, start_new_session=True)
|
|
2123
|
+
rec["pid"] = proc.pid
|
|
2124
|
+
try:
|
|
2125
|
+
rec["ok"] = exercise_server(rec, log_path, lambda: None if proc.poll() is None else f"exited {proc.returncode}", t0, limit)
|
|
2126
|
+
except (OSError, ValueError, http.client.HTTPException) as e:
|
|
2127
|
+
rec["ok"], rec["error"] = False, f"{type(e).__name__}: {e}"
|
|
2128
|
+
finally:
|
|
2129
|
+
rec["stop"] = stop_own(proc, term_wait)
|
|
2130
|
+
rec["port_released"] = port_closed(rec["port"]) if rec.get("port") else None
|
|
2131
|
+
rec["ok"] = rec["ok"] and rec["port_released"] is not False
|
|
2132
|
+
if not rec["ok"]:
|
|
2133
|
+
rec["log_tail"] = log_path.read_text(errors="replace").splitlines()[-20:]
|
|
2134
|
+
return rec
|
|
2135
|
+
|
|
2136
|
+
|
|
2137
|
+
def launchctl_bin() -> str:
|
|
2138
|
+
return (os.environ.get("OPERATOR_TOOLCHAIN_LAUNCHCTL") or "/bin/launchctl") if test_mode() else "/bin/launchctl"
|
|
2139
|
+
|
|
2140
|
+
|
|
2141
|
+
def job_pid(domain: str, label: str):
|
|
2142
|
+
m = re.search(r"^\s*pid = (\d+)\s*$", run([launchctl_bin(), "print", f"{domain}/{label}"], timeout=10).stdout, re.M)
|
|
2143
|
+
return int(m.group(1)) if m else None
|
|
2144
|
+
|
|
2145
|
+
|
|
2146
|
+
def job_running(domain: str, label: str) -> bool:
|
|
2147
|
+
return job_pid(domain, label) is not None
|
|
2148
|
+
|
|
2149
|
+
|
|
2150
|
+
def pid_alive(pid: int) -> bool:
|
|
2151
|
+
try:
|
|
2152
|
+
os.kill(pid, 0)
|
|
2153
|
+
except ProcessLookupError:
|
|
2154
|
+
return False
|
|
2155
|
+
except PermissionError:
|
|
2156
|
+
return True
|
|
2157
|
+
return True
|
|
2158
|
+
|
|
2159
|
+
|
|
2160
|
+
def serve_once_launchd(label: str, binary: str, gguf: pathlib.Path, ngl: int, term_wait: float, limit: float) -> dict:
|
|
2161
|
+
"""One run as a one-shot launchd job whose program is llama-server itself, the way portal/src/agent/launchd.ts starts a
|
|
2162
|
+
model: macOS TCC then attributes file access (a Removable Volumes prompt) to llama-server, not to this interpreter.
|
|
2163
|
+
Only the job this call bootstrapped is booted out."""
|
|
2164
|
+
domain, label = f"gui/{os.getuid()}", f"{label}.ngl{ngl}"
|
|
2165
|
+
cmd = server_argv(os.path.abspath(binary), gguf, ngl)
|
|
2166
|
+
rec = {"ngl": ngl, "label": label, "argv": cmd, "ok": False}
|
|
2167
|
+
with tempfile.TemporaryDirectory(prefix="toolchain-launchd-") as tmp:
|
|
2168
|
+
log_path = pathlib.Path(tmp) / "server.log"
|
|
2169
|
+
log_path.touch()
|
|
2170
|
+
plist = pathlib.Path(tmp) / f"{label}.plist"
|
|
2171
|
+
with os.fdopen(os.open(plist, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as f:
|
|
2172
|
+
plistlib.dump({"Label": label, "ProgramArguments": cmd, "EnvironmentVariables": scrubbed_env(), "WorkingDirectory": tmp,
|
|
2173
|
+
"RunAtLoad": True, "KeepAlive": False, "ProcessType": "Background", "AbandonProcessGroup": True,
|
|
2174
|
+
"ExitTimeOut": max(1, int(term_wait)), "StandardOutPath": str(log_path), "StandardErrorPath": str(log_path)}, f)
|
|
2175
|
+
t0 = time.monotonic()
|
|
2176
|
+
r = run([launchctl_bin(), "bootstrap", domain, plist], timeout=30)
|
|
2177
|
+
if r.returncode:
|
|
2178
|
+
raise ToolchainError(f"launchctl bootstrap {label}: {first_line(r.stderr)}")
|
|
2179
|
+
try:
|
|
2180
|
+
rec["ok"] = exercise_server(rec, log_path, lambda: None if job_running(domain, label) else "the launchd job is not running", t0, limit)
|
|
2181
|
+
except (OSError, ValueError, http.client.HTTPException) as e:
|
|
2182
|
+
rec["ok"], rec["error"] = False, f"{type(e).__name__}: {e}"
|
|
2183
|
+
finally:
|
|
2184
|
+
rec["pid"] = job_pid(domain, label) # before bootout, which makes launchd forget the job
|
|
2185
|
+
rec["booted_out"] = run([launchctl_bin(), "bootout", f"{domain}/{label}"], timeout=30).returncode == 0
|
|
2186
|
+
deadline = time.monotonic() + term_wait
|
|
2187
|
+
while rec.get("port") and not port_closed(rec["port"]) and time.monotonic() < deadline:
|
|
2188
|
+
time.sleep(0.1)
|
|
2189
|
+
# bootout returns while llama-server is still exiting, and its port closes before the process does; the caller
|
|
2190
|
+
# compares the box's llama-server pids next, so wait for this job's own pid to be gone as well
|
|
2191
|
+
while rec["pid"] and pid_alive(rec["pid"]) and time.monotonic() < deadline:
|
|
2192
|
+
time.sleep(0.1)
|
|
2193
|
+
rec["port_released"] = port_closed(rec["port"]) if rec.get("port") else None
|
|
2194
|
+
rec["exited"] = not (rec["pid"] and pid_alive(rec["pid"]))
|
|
2195
|
+
if rec["ok"] and not rec["booted_out"]:
|
|
2196
|
+
rec["error"] = "launchctl bootout failed"
|
|
2197
|
+
elif rec["ok"] and rec["port_released"] is False:
|
|
2198
|
+
rec["error"] = f"port {rec['port']} is still open after bootout"
|
|
2199
|
+
elif rec["ok"] and not rec["exited"]:
|
|
2200
|
+
rec["error"] = f"pid {rec['pid']} is still running {term_wait:.0f} s after bootout"
|
|
2201
|
+
rec["ok"] = rec["ok"] and rec["booted_out"] and rec["port_released"] is not False and rec["exited"]
|
|
2202
|
+
if not rec["ok"]:
|
|
2203
|
+
rec["log_tail"] = log_path.read_text(errors="replace").splitlines()[-20:]
|
|
2204
|
+
return rec
|
|
2205
|
+
|
|
2206
|
+
|
|
2207
|
+
def cmd_smoke(args) -> int:
|
|
2208
|
+
ctx = Ctx(args)
|
|
2209
|
+
if args.via_launchd and not re.fullmatch(r"co\.0perator\.toolchain\.smoke\.[A-Za-z0-9.-]+", args.via_launchd):
|
|
2210
|
+
raise Refused("--via-launchd LABEL must start with co.0perator.toolchain.smoke.")
|
|
2211
|
+
gguf = pathlib.Path(args.gguf) if args.gguf else stage_fixture(ctx, "stories260K")
|
|
2212
|
+
real = os.path.realpath(args.bin)
|
|
2213
|
+
store = os.path.realpath(ctx.root / "store")
|
|
2214
|
+
meta = read_json(pathlib.Path(store) / os.path.relpath(real, store).split(os.sep)[0] / ENTRY_META, {}) if within(real, store) else {}
|
|
2215
|
+
expect = args.expect or ((meta.get("probe") or {}).get("expect"))
|
|
2216
|
+
r = subprocess.run([args.bin, "--version"], env=scrubbed_env(), capture_output=True, timeout=60)
|
|
2217
|
+
version = (r.stdout + r.stderr).decode("utf-8", "replace")
|
|
2218
|
+
rep = {"ts": now(), "bin": args.bin, "realpath": real, "entry_version": meta.get("version"), "version": first_line(version),
|
|
2219
|
+
"expect": expect, "probe_ok": not expect or expect in version, "gguf": str(gguf), "gguf_sha256": sha256_file(gguf)}
|
|
2220
|
+
before = llama_pids()
|
|
2221
|
+
rep["pids_before"] = sorted(before)
|
|
2222
|
+
if args.via_launchd:
|
|
2223
|
+
rep["via_launchd"] = args.via_launchd
|
|
2224
|
+
limit = args.ready_timeout or 300.0
|
|
2225
|
+
run_one = lambda ngl: serve_once_launchd(args.via_launchd, args.bin, gguf, ngl, args.term_timeout, limit) # noqa: E731
|
|
2226
|
+
else:
|
|
2227
|
+
run_one = lambda ngl: serve_once(args.bin, gguf, ngl, args.term_timeout, args.ready_timeout or 60.0) # noqa: E731
|
|
2228
|
+
rep["runs"] = [run_one(ngl) for ngl in ([0, 99] if args.metal else [0])] if rep["probe_ok"] else []
|
|
2229
|
+
after = llama_pids()
|
|
2230
|
+
rep["pids_after"], rep["pids_intact"] = sorted(after), before == after
|
|
2231
|
+
rep["ok"] = rep["probe_ok"] and rep["pids_intact"] and bool(rep["runs"]) and all(x["ok"] for x in rep["runs"])
|
|
2232
|
+
name = f"smoke-{time.strftime('%Y%m%dT%H%M%S')}-{os.getpid()}.json"
|
|
2233
|
+
out = pathlib.Path(args.report) if args.report else (ctx.root / "baselines" if (ctx.root / ".lock").exists()
|
|
2234
|
+
else pathlib.Path(tempfile.gettempdir())) / name
|
|
2235
|
+
durable_write(out, canonical(rep))
|
|
2236
|
+
lines = [f"smoke {args.bin}: {'ok' if rep['ok'] else 'FAILED'} ({rep['version']})"]
|
|
2237
|
+
lines += [f" -ngl {x['ngl']}: {'ok' if x['ok'] else 'FAILED ' + x.get('error', '')} port {x.get('port')} stop {x.get('stop', {}).get('signal') or ('booted out' if x.get('booted_out') else None)}"
|
|
2238
|
+
f" released {x.get('port_released')}" for x in rep["runs"]]
|
|
2239
|
+
lines.append(f" pre-existing llama-server pids {'intact' if rep['pids_intact'] else 'CHANGED'}: {rep['pids_before']} -> {rep['pids_after']}")
|
|
2240
|
+
lines.append(f" report: {out}")
|
|
2241
|
+
emit(args, rep, "\n".join(lines))
|
|
2242
|
+
return EX_OK if rep["ok"] else EX_ERROR
|
|
2243
|
+
|
|
2244
|
+
|
|
2245
|
+
# ── gate ────────────────────────────────────────────────────────────────────
|
|
2246
|
+
|
|
2247
|
+
GATE_WORDS = ("harbor lantern meadow cipher falcon timber vector ember glacier mosaic beacon canyon velvet prism summit "
|
|
2248
|
+
"tundra cobalt river stone ledger orbit amber signal quartz willow saffron basalt marrow juniper cinder").split()
|
|
2249
|
+
|
|
2250
|
+
|
|
2251
|
+
def haystack(n_words: int, seed: int) -> str:
|
|
2252
|
+
words, x = [], seed
|
|
2253
|
+
for _ in range(n_words):
|
|
2254
|
+
x = (x * 1103515245 + 12345) & 0x7FFFFFFF
|
|
2255
|
+
words.append(GATE_WORDS[x % len(GATE_WORDS)])
|
|
2256
|
+
return " ".join(words)
|
|
2257
|
+
|
|
2258
|
+
|
|
2259
|
+
def mem_free_pct():
|
|
2260
|
+
with contextlib.suppress(OSError, subprocess.SubprocessError):
|
|
2261
|
+
m = re.search(r"free percentage:\s*(\d+)%", run(["/usr/bin/memory_pressure", "-Q"], timeout=30).stdout)
|
|
2262
|
+
return int(m.group(1)) if m else None
|
|
2263
|
+
return None
|
|
2264
|
+
|
|
2265
|
+
|
|
2266
|
+
def swap_used_mb():
|
|
2267
|
+
with contextlib.suppress(OSError, subprocess.SubprocessError):
|
|
2268
|
+
m = re.search(r"used = ([\d.]+)M", run(["/usr/sbin/sysctl", "-n", "vm.swapusage"], timeout=10).stdout)
|
|
2269
|
+
return float(m.group(1)) if m else None
|
|
2270
|
+
return None
|
|
2271
|
+
|
|
2272
|
+
|
|
2273
|
+
def gate_measure(url: str, suite: str, api_key=None) -> dict:
|
|
2274
|
+
base = url.rstrip("/").removesuffix("/v1")
|
|
2275
|
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
|
2276
|
+
|
|
2277
|
+
def post(path, body, timeout=900):
|
|
2278
|
+
status, raw = local_http(base + path, body, headers, timeout)
|
|
2279
|
+
if status != 200:
|
|
2280
|
+
raise ToolchainError(f"{path} returned {status}: {raw[:200]!r}")
|
|
2281
|
+
return raw
|
|
2282
|
+
|
|
2283
|
+
def complete(prompt, n, cache=False, **extra):
|
|
2284
|
+
return json.loads(post("/completion", {"prompt": prompt, "n_predict": n, "cache_prompt": cache, "temperature": 0, **extra}))
|
|
2285
|
+
|
|
2286
|
+
def sized(tokens, seed):
|
|
2287
|
+
text = haystack(int(tokens / 1.3), seed)
|
|
2288
|
+
with contextlib.suppress(ToolchainError, ValueError):
|
|
2289
|
+
have = len(json.loads(post("/tokenize", {"content": text})).get("tokens", []))
|
|
2290
|
+
if have:
|
|
2291
|
+
text = haystack(int(len(text.split()) * tokens / have), seed)
|
|
2292
|
+
return text
|
|
2293
|
+
|
|
2294
|
+
status, _ = local_http(base + "/health", headers=headers, timeout=10)
|
|
2295
|
+
props_status, props = local_http(base + "/props", headers=headers, timeout=10)
|
|
2296
|
+
m = {"suite": suite, "url": base, "ts": now(), "health": status,
|
|
2297
|
+
"build": json.loads(props).get("build_info") if props_status == 200 else None}
|
|
2298
|
+
swap0 = swap_used_mb()
|
|
2299
|
+
if suite == "quick":
|
|
2300
|
+
t = complete("1+1=", 4).get("timings") or {}
|
|
2301
|
+
m.update(completion_ok=True, prefill_tps=t.get("prompt_per_second"), decode_tps=t.get("predicted_per_second"))
|
|
2302
|
+
else:
|
|
2303
|
+
t = complete(sized(8192, 1), 1).get("timings") or {}
|
|
2304
|
+
m.update(prefill_tps=t.get("prompt_per_second"), prefill_tokens=t.get("prompt_n"))
|
|
2305
|
+
t = complete("Write a long story about a lighthouse keeper.", 256, ignore_eos=True).get("timings") or {}
|
|
2306
|
+
m.update(decode_tps=t.get("predicted_per_second"), decode_tokens=t.get("predicted_n"))
|
|
2307
|
+
m["tool_calls_total"], m["tool_calls_ok"] = 10, sum(stream_tool_call(post, i) for i in range(10))
|
|
2308
|
+
shared = sized(2048, 2)
|
|
2309
|
+
first = (complete(shared, 1, cache=True).get("timings") or {}).get("prompt_n") or 0
|
|
2310
|
+
second = (complete(shared, 1, cache=True).get("timings") or {}).get("prompt_n") or 0
|
|
2311
|
+
m["cache_reuse"] = bool(first) and second <= max(8, first // 10)
|
|
2312
|
+
words = sized(32768, 3).split()
|
|
2313
|
+
at = len(words) * 3 // 5
|
|
2314
|
+
needle = " The vault code is 4719. "
|
|
2315
|
+
prompt = " ".join(words[:at]) + needle + " ".join(words[at:]) + "\nQuestion: what is the vault code? Answer:"
|
|
2316
|
+
m["needle_found"] = "4719" in (complete(prompt, 16).get("content") or "")
|
|
2317
|
+
m["mem_free_pct"] = mem_free_pct()
|
|
2318
|
+
swap1 = swap_used_mb()
|
|
2319
|
+
m["swap_growth_mb"] = round(swap1 - swap0, 1) if swap0 is not None and swap1 is not None else None
|
|
2320
|
+
return m
|
|
2321
|
+
|
|
2322
|
+
|
|
2323
|
+
def stream_tool_call(post, i: int) -> bool:
|
|
2324
|
+
tools = [{"type": "function", "function": {"name": "get_weather", "description": "Current weather for a city",
|
|
2325
|
+
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}]
|
|
2326
|
+
city = ("Lisbon", "Osaka", "Quito", "Tromso", "Accra")[i % 5]
|
|
2327
|
+
raw = post("/v1/chat/completions", {"messages": [{"role": "user", "content": f"What is the weather in {city}? Use the tool."}],
|
|
2328
|
+
"tools": tools, "stream": True, "max_tokens": 256, "temperature": 0})
|
|
2329
|
+
name, arguments = "", ""
|
|
2330
|
+
for line in raw.decode("utf-8", "replace").splitlines():
|
|
2331
|
+
if not line.startswith("data: ") or line.strip() == "data: [DONE]":
|
|
2332
|
+
continue
|
|
2333
|
+
with contextlib.suppress(ValueError, IndexError, AttributeError):
|
|
2334
|
+
for tc in json.loads(line[6:])["choices"][0].get("delta", {}).get("tool_calls") or []:
|
|
2335
|
+
name += (tc.get("function") or {}).get("name") or ""
|
|
2336
|
+
arguments += (tc.get("function") or {}).get("arguments") or ""
|
|
2337
|
+
with contextlib.suppress(ValueError):
|
|
2338
|
+
return name == "get_weather" and isinstance(json.loads(arguments).get("city"), str)
|
|
2339
|
+
return False
|
|
2340
|
+
|
|
2341
|
+
|
|
2342
|
+
GATE_THRESHOLDS = {
|
|
2343
|
+
"quick": [("health", "==", 200), ("completion_ok", "is", True)],
|
|
2344
|
+
"aurora": [("decode_tps", ">=base", 0.90), ("prefill_tps", ">=base", 0.85), ("cold_start_s", "<=", 120),
|
|
2345
|
+
("tool_calls_ok", "==total", "tool_calls_total"), ("cache_reuse", "is", True), ("needle_found", "is", True),
|
|
2346
|
+
("mem_free_pct", ">=", 20), ("swap_growth_mb", "<", 1024)],
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
|
|
2350
|
+
def gate_compare(base: dict, cand: dict, suite: str) -> list:
|
|
2351
|
+
"""(name, ok, detail) per threshold. A value the candidate did not measure is a failure, except cold start, which
|
|
2352
|
+
comes from the restart and is checked only when recorded."""
|
|
2353
|
+
out = []
|
|
2354
|
+
for key, op, ref in GATE_THRESHOLDS[suite]:
|
|
2355
|
+
v = cand.get(key)
|
|
2356
|
+
if v is None:
|
|
2357
|
+
out.append((key, key == "cold_start_s", "not measured"))
|
|
2358
|
+
continue
|
|
2359
|
+
if op == ">=base":
|
|
2360
|
+
b = base.get(key)
|
|
2361
|
+
ok = bool(b) and v >= ref * b
|
|
2362
|
+
detail = f"{v} vs baseline {b} (need >= {ref:.0%})"
|
|
2363
|
+
elif op == "==total":
|
|
2364
|
+
ok, detail = v == cand.get(ref), f"{v}/{cand.get(ref)}"
|
|
2365
|
+
elif op == "is":
|
|
2366
|
+
ok, detail = v is ref, f"{v}"
|
|
2367
|
+
else:
|
|
2368
|
+
ok = {"==": v == ref, "<=": v <= ref, ">=": v >= ref, "<": v < ref}[op]
|
|
2369
|
+
detail = f"{v} (need {op} {ref})"
|
|
2370
|
+
out.append((key, ok, detail))
|
|
2371
|
+
return out
|
|
2372
|
+
|
|
2373
|
+
|
|
2374
|
+
def cmd_gate(args) -> int:
|
|
2375
|
+
ctx = Ctx(args)
|
|
2376
|
+
if bool(args.url) == bool(args.input):
|
|
2377
|
+
raise Refused("pass exactly one of --url (measure now) or --input FILE (a recorded measurement)")
|
|
2378
|
+
if args.input:
|
|
2379
|
+
measured = read_json(args.input)
|
|
2380
|
+
if not isinstance(measured, dict):
|
|
2381
|
+
raise ToolchainError(f"cannot read {args.input}")
|
|
2382
|
+
else:
|
|
2383
|
+
key = pathlib.Path(args.api_key_file).read_text().strip() if args.api_key_file else None
|
|
2384
|
+
measured = gate_measure(args.url, args.suite, key)
|
|
2385
|
+
if args.cold_start is not None:
|
|
2386
|
+
measured["cold_start_s"] = args.cold_start
|
|
2387
|
+
suite = measured.get("suite") or args.suite
|
|
2388
|
+
lines, ok, checks = [], True, []
|
|
2389
|
+
if args.baseline:
|
|
2390
|
+
durable_write(pathlib.Path(args.baseline), canonical(measured))
|
|
2391
|
+
lines.append(f"baseline written: {args.baseline}")
|
|
2392
|
+
if args.compare:
|
|
2393
|
+
base = read_json(args.compare)
|
|
2394
|
+
if not isinstance(base, dict):
|
|
2395
|
+
raise ToolchainError(f"cannot read baseline {args.compare}")
|
|
2396
|
+
checks = gate_compare(base, measured, suite)
|
|
2397
|
+
ok = all(c[1] for c in checks)
|
|
2398
|
+
lines += [f"{'PASS' if c[1] else 'FAIL'} {c[0]}: {c[2]}" for c in checks]
|
|
2399
|
+
lines.append(f"gate {suite}: {'pass' if ok else 'fail'}")
|
|
2400
|
+
if (ctx.root / ".lock").exists():
|
|
2401
|
+
with mutation(ctx.root):
|
|
2402
|
+
history(ctx.root, "gate", reason=args.reason, result="pass" if ok else "fail", suite=suite, url=measured.get("url"),
|
|
2403
|
+
baseline=args.baseline, compare=args.compare, failed=[c[0] for c in checks if not c[1]])
|
|
2404
|
+
else:
|
|
2405
|
+
lines.append(f"(no gate record: {ctx.root} is not a managed root)")
|
|
2406
|
+
emit(args, {"measured": measured, "checks": [{"name": c[0], "ok": c[1], "detail": c[2]} for c in checks], "ok": ok}, "\n".join(lines))
|
|
2407
|
+
return EX_OK if ok else EX_ERROR
|
|
2408
|
+
|
|
2409
|
+
|
|
2410
|
+
# ── manifest check ──────────────────────────────────────────────────────────
|
|
2411
|
+
|
|
2412
|
+
def check_url_field(errs: list, where: str, url, hosts) -> None:
|
|
2413
|
+
if not isinstance(url, str):
|
|
2414
|
+
errs.append(f"E_MISSING {where}.url: missing")
|
|
2415
|
+
return
|
|
2416
|
+
u = urllib.parse.urlsplit(url)
|
|
2417
|
+
if u.scheme != "https" and not (test_mode() and u.scheme == "http" and u.hostname in LOOPBACK):
|
|
2418
|
+
errs.append(f"E_HTTP_URL {where}.url: {url} is not https")
|
|
2419
|
+
elif u.username is not None or u.password is not None:
|
|
2420
|
+
errs.append(f"E_HOST {where}.url: {url} carries userinfo")
|
|
2421
|
+
elif not host_allowed(u.hostname or "", hosts):
|
|
2422
|
+
errs.append(f"E_HOST {where}.url: host {u.hostname!r} is not in hosts")
|
|
2423
|
+
|
|
2424
|
+
|
|
2425
|
+
def check_sha_field(errs: list, where: str, sha) -> None:
|
|
2426
|
+
if not (isinstance(sha, str) and HEX64.fullmatch(sha)):
|
|
2427
|
+
errs.append(f"E_SHA {where}.sha256: {sha!r} is not 64 lowercase hex")
|
|
2428
|
+
|
|
2429
|
+
|
|
2430
|
+
def check_date_field(errs: list, where: str, value) -> dt.date | None:
|
|
2431
|
+
try:
|
|
2432
|
+
return parse_date(value) if isinstance(value, str) else None
|
|
2433
|
+
except ValueError:
|
|
2434
|
+
pass
|
|
2435
|
+
errs.append(f"E_FIELD {where}: {value!r} is not a YYYY-MM-DD date")
|
|
2436
|
+
return None
|
|
2437
|
+
|
|
2438
|
+
|
|
2439
|
+
def check_row(errs: list, m: dict, name: str, row: dict, previous: bool, today: dt.date) -> None:
|
|
2440
|
+
where = f"packages.{name}" + (".previous" if previous else "")
|
|
2441
|
+
default = row.get("install") == "default"
|
|
2442
|
+
for key in ("version", "artifacts", "entry", "layout", "provides") + (() if previous else ("install", "consumers")):
|
|
2443
|
+
if row.get(key) in (None, "", {}, []) and not (key == "consumers" and isinstance(row.get(key), list)):
|
|
2444
|
+
errs.append(f"E_MISSING {where}.{key}: required")
|
|
2445
|
+
if previous and not row.get("until"):
|
|
2446
|
+
errs.append(f"E_MISSING {where}.until: a previous row needs the date its rollback window closes")
|
|
2447
|
+
elif previous:
|
|
2448
|
+
check_date_field(errs, f"{where}.until", row["until"])
|
|
2449
|
+
entry = row.get("entry")
|
|
2450
|
+
if isinstance(entry, str) and (entry in (".", "..") or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.+_-]*", entry)):
|
|
2451
|
+
errs.append(f"E_FIELD {where}.entry: {entry!r} is not a safe entry name")
|
|
2452
|
+
if not previous and row.get("install") not in ("default", "on-demand"):
|
|
2453
|
+
errs.append(f"E_FIELD {where}.install: {row.get('install')!r} is not default or on-demand")
|
|
2454
|
+
if not previous and not set(row.get("consumers") or []) <= set(MANIFEST_CONSUMERS):
|
|
2455
|
+
errs.append(f"E_FIELD {where}.consumers: {row.get('consumers')} names an unknown consumer")
|
|
2456
|
+
layout = row.get("layout") or {}
|
|
2457
|
+
if layout.get("format") not in FORMATS:
|
|
2458
|
+
errs.append(f"E_FIELD {where}.layout.format: {layout.get('format')!r} is not one of {', '.join(FORMATS)}")
|
|
2459
|
+
if layout.get("strip", 0) not in (0, 1):
|
|
2460
|
+
errs.append(f"E_FIELD {where}.layout.strip: only 0 or 1")
|
|
2461
|
+
for tool, rel in (row.get("provides") or {}).items():
|
|
2462
|
+
if not isinstance(rel, str) or rel.startswith("/") or ".." in rel.split("/"):
|
|
2463
|
+
errs.append(f"E_FIELD {where}.provides.{tool}: {rel!r} is not a relative path inside the entry")
|
|
2464
|
+
for target, arts in (row.get("artifacts") or {}).items():
|
|
2465
|
+
if target != "any" and target not in (m.get("targets") or []):
|
|
2466
|
+
errs.append(f"E_FIELD {where}.artifacts.{target}: not one of targets")
|
|
2467
|
+
for i, a in enumerate(arts if isinstance(arts, list) else [arts]):
|
|
2468
|
+
aw = f"{where}.artifacts.{target}[{i}]"
|
|
2469
|
+
check_url_field(errs, aw, a.get("url"), m.get("hosts"))
|
|
2470
|
+
check_sha_field(errs, aw, a.get("sha256"))
|
|
2471
|
+
if "size" in a and not (isinstance(a["size"], int) and a["size"] > 0):
|
|
2472
|
+
errs.append(f"E_FIELD {aw}.size: {a['size']!r} is not a positive integer")
|
|
2473
|
+
if role(a) not in ROLES:
|
|
2474
|
+
errs.append(f"E_FIELD {aw}.role: {role(a)!r} is not one of {', '.join(ROLES)}")
|
|
2475
|
+
tree = row.get("tree")
|
|
2476
|
+
if tree is not None and not (isinstance(tree, str) and re.fullmatch(r"sha256:[0-9a-f]{64}", tree)):
|
|
2477
|
+
errs.append(f"E_FIELD {where}.tree: {tree!r} is not sha256:<64 hex>")
|
|
2478
|
+
if row.get("expect_pm_digest") is not None:
|
|
2479
|
+
check_sha_field(errs, f"{where}.expect_pm_digest", row["expect_pm_digest"])
|
|
2480
|
+
cs = row.get("codesign")
|
|
2481
|
+
if cs is not None and (not isinstance(cs, dict) or cs.get("expect") not in CODESIGN_KINDS
|
|
2482
|
+
or (cs.get("expect") == "developer-id" and not cs.get("team"))):
|
|
2483
|
+
errs.append(f"E_CODESIGN {where}.codesign: {cs!r} is not a known expectation (developer-id needs team)")
|
|
2484
|
+
probe = row.get("probe")
|
|
2485
|
+
if probe is not None and (not isinstance(probe, dict) or probe.get("bin") not in (row.get("provides") or {}) or not probe.get("expect")):
|
|
2486
|
+
errs.append(f"E_FIELD {where}.probe: needs bin (one of provides) and a literal expect")
|
|
2487
|
+
for req in row.get("requires") or []:
|
|
2488
|
+
if req not in (m.get("packages") or {}):
|
|
2489
|
+
errs.append(f"E_FIELD {where}.requires: unknown package {req!r}")
|
|
2490
|
+
prov = row.get("provenance") or {}
|
|
2491
|
+
att = prov.get("attest")
|
|
2492
|
+
if att is not None and not (isinstance(att, dict) and all(att.get(k) for k in ("repo", "signer_workflow", "source_digest"))):
|
|
2493
|
+
errs.append(f"E_FIELD {where}.provenance.attest: needs repo, signer_workflow and source_digest")
|
|
2494
|
+
if prov.get("published_at") and not prov.get("cooldown_exception"):
|
|
2495
|
+
try:
|
|
2496
|
+
age = (today - parse_ts(prov["published_at"]).date()).days
|
|
2497
|
+
if age < 14:
|
|
2498
|
+
errs.append(f"E_COOLDOWN {where}.provenance.published_at: released {age} days ago; 14-day cooldown (or cooldown_exception citing a CVE/GHSA)")
|
|
2499
|
+
except ValueError:
|
|
2500
|
+
errs.append(f"E_FIELD {where}.provenance.published_at: {prov['published_at']!r} is not a timestamp")
|
|
2501
|
+
if default:
|
|
2502
|
+
if not (isinstance(row.get("license"), dict) and row["license"].get("spdx")):
|
|
2503
|
+
errs.append(f"E_LICENSE {where}.license: a default row needs license.spdx")
|
|
2504
|
+
if not prov.get("hash_source"):
|
|
2505
|
+
errs.append(f"E_HASH_SOURCE {where}.provenance.hash_source: a default row needs one")
|
|
2506
|
+
if not isinstance(cs, dict):
|
|
2507
|
+
errs.append(f"E_CODESIGN {where}.codesign: a default row needs a codesign expectation")
|
|
2508
|
+
if tree is None:
|
|
2509
|
+
errs.append(f"E_TREE_NULL {where}.tree: a default row needs a witnessed tree")
|
|
2510
|
+
|
|
2511
|
+
|
|
2512
|
+
def check_manifest(m: dict, base, today: dt.date, check_serial: bool = True) -> list:
|
|
2513
|
+
"""Named errors ('E_CODE where: why'). `base` is main's manifest, or None when this is the first one."""
|
|
2514
|
+
errs = []
|
|
2515
|
+
if m.get("schema") != SCHEMA:
|
|
2516
|
+
errs.append(f"E_SCHEMA schema: {m.get('schema')!r} is not {SCHEMA}")
|
|
2517
|
+
serial = m.get("serial")
|
|
2518
|
+
if not (isinstance(serial, int) and serial >= 1):
|
|
2519
|
+
errs.append(f"E_SERIAL serial: {serial!r} is not a positive integer")
|
|
2520
|
+
elif not check_serial:
|
|
2521
|
+
pass
|
|
2522
|
+
elif base is None and serial != 1:
|
|
2523
|
+
errs.append(f"E_SERIAL serial: the first manifest has serial 1, not {serial}")
|
|
2524
|
+
elif isinstance(base, dict) and base != m and serial != (base.get("serial") or 0) + 1:
|
|
2525
|
+
errs.append(f"E_SERIAL serial: {serial} must be main's {base.get('serial')} + 1")
|
|
2526
|
+
exp = check_date_field(errs, "expires", m.get("expires")) if m.get("expires") else None
|
|
2527
|
+
if not m.get("expires"):
|
|
2528
|
+
errs.append("E_MISSING expires: required")
|
|
2529
|
+
elif exp and exp < today:
|
|
2530
|
+
errs.append(f"E_EXPIRED expires: {exp} has passed; review the manifest and move it out")
|
|
2531
|
+
elif exp and (exp - today).days > 45:
|
|
2532
|
+
errs.append(f"E_EXPIRY_FAR expires: {exp} is more than 45 days out")
|
|
2533
|
+
if not (isinstance(m.get("targets"), list) and m["targets"]):
|
|
2534
|
+
errs.append("E_MISSING targets: required")
|
|
2535
|
+
hosts = m.get("hosts")
|
|
2536
|
+
if not (isinstance(hosts, list) and hosts and all(isinstance(h, str) and re.fullmatch(r"(\*\.)?[a-z0-9.-]+", h) for h in hosts)):
|
|
2537
|
+
errs.append("E_FIELD hosts: a list of hostnames (or *.domain)")
|
|
2538
|
+
pkgs = m.get("packages")
|
|
2539
|
+
if not (isinstance(pkgs, dict) and pkgs):
|
|
2540
|
+
errs.append("E_MISSING packages: required")
|
|
2541
|
+
pkgs = {}
|
|
2542
|
+
for name, ro in (m.get("rollout") or {}).items():
|
|
2543
|
+
if name not in pkgs:
|
|
2544
|
+
errs.append(f"E_FIELD rollout.{name}: unknown package")
|
|
2545
|
+
check_date_field(errs, f"rollout.{name}.until", (ro or {}).get("until"))
|
|
2546
|
+
for i, e in enumerate(m.get("exceptions") or []):
|
|
2547
|
+
for k in ("box", "match", "owner", "until", "reason"):
|
|
2548
|
+
if not (e or {}).get(k):
|
|
2549
|
+
errs.append(f"E_MISSING exceptions[{i}].{k}: required")
|
|
2550
|
+
if (e or {}).get("until"):
|
|
2551
|
+
check_date_field(errs, f"exceptions[{i}].until", e["until"])
|
|
2552
|
+
for name, fx in (m.get("fixtures") or {}).items():
|
|
2553
|
+
check_url_field(errs, f"fixtures.{name}", (fx or {}).get("url"), hosts)
|
|
2554
|
+
check_sha_field(errs, f"fixtures.{name}", (fx or {}).get("sha256"))
|
|
2555
|
+
if not isinstance((fx or {}).get("size"), int):
|
|
2556
|
+
errs.append(f"E_MISSING fixtures.{name}.size: required")
|
|
2557
|
+
for name, row in sorted(pkgs.items()):
|
|
2558
|
+
if not isinstance(row, dict):
|
|
2559
|
+
errs.append(f"E_FIELD packages.{name}: not an object")
|
|
2560
|
+
continue
|
|
2561
|
+
check_row(errs, m, name, {k: v for k, v in row.items() if k != "previous"}, False, today)
|
|
2562
|
+
if isinstance(row.get("previous"), dict):
|
|
2563
|
+
check_row(errs, m, name, row_for(m, f"{name}@previous")[2], True, today)
|
|
2564
|
+
return errs
|
|
2565
|
+
|
|
2566
|
+
|
|
2567
|
+
def manifest_base(path: pathlib.Path, ref: str):
|
|
2568
|
+
"""main's manifest: a FILE, '-' for none (the first manifest), or a git ref. (manifest, warning)."""
|
|
2569
|
+
if ref == "-":
|
|
2570
|
+
return None, None
|
|
2571
|
+
if os.path.isfile(ref):
|
|
2572
|
+
return read_json(ref), None
|
|
2573
|
+
top = run(["git", "-C", path.resolve().parent, "rev-parse", "--show-toplevel"], timeout=10)
|
|
2574
|
+
if top.returncode:
|
|
2575
|
+
return "skip", f"{path} is not in a git checkout; serial not checked against {ref}"
|
|
2576
|
+
rel = os.path.relpath(path.resolve(), top.stdout.strip())
|
|
2577
|
+
if run(["git", "-C", top.stdout.strip(), "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"], timeout=10).returncode:
|
|
2578
|
+
return "skip", f"git ref {ref} is unavailable; serial not checked"
|
|
2579
|
+
shown = run(["git", "-C", top.stdout.strip(), "show", f"{ref}:{rel}"], timeout=10)
|
|
2580
|
+
if shown.returncode:
|
|
2581
|
+
return None, None
|
|
2582
|
+
with contextlib.suppress(ValueError):
|
|
2583
|
+
return json.loads(shown.stdout), None
|
|
2584
|
+
return "skip", f"{ref}:{rel} is not JSON; serial not checked"
|
|
2585
|
+
|
|
2586
|
+
|
|
2587
|
+
def cmd_manifest(args) -> int:
|
|
2588
|
+
path = pathlib.Path(args.file) if args.file else manifest_file(args.manifest)
|
|
2589
|
+
try:
|
|
2590
|
+
m = json.loads(path.read_text())
|
|
2591
|
+
except (OSError, ValueError) as e:
|
|
2592
|
+
print(f"E_PARSE {path}: {e}")
|
|
2593
|
+
return EX_ERROR
|
|
2594
|
+
base, warning = manifest_base(path, args.base)
|
|
2595
|
+
if warning:
|
|
2596
|
+
say(f"warning: {warning}")
|
|
2597
|
+
today = parse_date(args.today) if args.today else utc_today()
|
|
2598
|
+
errs = check_manifest(m, None if base == "skip" else base, today, check_serial=base != "skip") if isinstance(m, dict) \
|
|
2599
|
+
else ["E_SCHEMA not a JSON object"]
|
|
2600
|
+
for e in errs:
|
|
2601
|
+
print(e)
|
|
2602
|
+
if not errs:
|
|
2603
|
+
print(f"{path}: ok (serial {m.get('serial')}, expires {m.get('expires')}, {len(m.get('packages', {}))} packages)")
|
|
2604
|
+
return EX_ERROR if errs else EX_OK
|
|
2605
|
+
|
|
2606
|
+
|
|
2607
|
+
# ── cli ─────────────────────────────────────────────────────────────────────
|
|
2608
|
+
|
|
2609
|
+
def parser() -> argparse.ArgumentParser:
|
|
2610
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
2611
|
+
common.add_argument("--root", default=argparse.SUPPRESS, help="toolchain root (default $OPERATOR_TOOLCHAIN_HOME, else $OPERATOR_HOME/toolchain)")
|
|
2612
|
+
common.add_argument("--manifest", default=argparse.SUPPRESS, help="manifest file (default: beside this script, else <root>/manifest.applied.json)")
|
|
2613
|
+
common.add_argument("--json", action="store_true", default=argparse.SUPPRESS)
|
|
2614
|
+
p = argparse.ArgumentParser(prog="toolchain", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
2615
|
+
p.add_argument("--root", default=None)
|
|
2616
|
+
p.add_argument("--manifest", default=None)
|
|
2617
|
+
p.add_argument("--json", action="store_true", default=False)
|
|
2618
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
2619
|
+
|
|
2620
|
+
s = sub.add_parser("install", parents=[common], help="fetch, verify, seal and build a generation")
|
|
2621
|
+
s.add_argument("packages", nargs="*", metavar="PKG[@previous]")
|
|
2622
|
+
act = s.add_mutually_exclusive_group()
|
|
2623
|
+
act.add_argument("--activate", metavar="C,...")
|
|
2624
|
+
act.add_argument("--no-activate", action="store_true")
|
|
2625
|
+
s.add_argument("--offline", action="store_true")
|
|
2626
|
+
s.add_argument("--cache", metavar="DIR")
|
|
2627
|
+
s.add_argument("--witness", action="store_true", help="compute tree, size, codesign and pm digest in $TMPDIR; install nothing")
|
|
2628
|
+
s.add_argument("--reason", default=None)
|
|
2629
|
+
s.add_argument("--force-flags", action="store_true")
|
|
2630
|
+
s.set_defaults(func=cmd_install)
|
|
2631
|
+
|
|
2632
|
+
s = sub.add_parser("activate", parents=[common], help="point consumers at a generation")
|
|
2633
|
+
s.add_argument("generation", type=int, metavar="GEN")
|
|
2634
|
+
s.add_argument("--consumer", required=True, metavar="C[,C...]")
|
|
2635
|
+
s.add_argument("--reason", required=True)
|
|
2636
|
+
s.add_argument("--force-flags", action="store_true")
|
|
2637
|
+
s.set_defaults(func=cmd_activate)
|
|
2638
|
+
|
|
2639
|
+
s = sub.add_parser("rollback", parents=[common], help="flip consumers back to their previous generation")
|
|
2640
|
+
s.add_argument("--consumer", required=True, metavar="C[,C...]")
|
|
2641
|
+
s.add_argument("--reason", required=True)
|
|
2642
|
+
s.add_argument("--to", type=int, default=None, metavar="GEN")
|
|
2643
|
+
s.add_argument("--force-flags", action="store_true")
|
|
2644
|
+
s.set_defaults(func=cmd_rollback)
|
|
2645
|
+
|
|
2646
|
+
s = sub.add_parser("which", parents=[common], help="the stable consumer path of a binary, or exit 78")
|
|
2647
|
+
s.add_argument("bin")
|
|
2648
|
+
s.add_argument("--consumer", required=True)
|
|
2649
|
+
s.add_argument("--resolve", action="store_true")
|
|
2650
|
+
s.set_defaults(func=cmd_which)
|
|
2651
|
+
|
|
2652
|
+
s = sub.add_parser("verify", parents=[common], help="check consumers, generations and entries (exit 2 on drift)")
|
|
2653
|
+
s.add_argument("--deep", action="store_true")
|
|
2654
|
+
s.add_argument("--probe", action="store_true")
|
|
2655
|
+
s.add_argument("--quiet", action="store_true")
|
|
2656
|
+
s.set_defaults(func=cmd_verify)
|
|
2657
|
+
|
|
2658
|
+
s = sub.add_parser("status", parents=[common], help="consumers, generations and live llama-servers")
|
|
2659
|
+
s.set_defaults(func=cmd_status)
|
|
2660
|
+
|
|
2661
|
+
s = sub.add_parser("gc", parents=[common], help="list (or with --apply delete) unreferenced generations, entries and blobs")
|
|
2662
|
+
s.add_argument("--keep", type=int, default=3)
|
|
2663
|
+
s.add_argument("--apply", action="store_true")
|
|
2664
|
+
s.set_defaults(func=cmd_gc)
|
|
2665
|
+
|
|
2666
|
+
s = sub.add_parser("migrate", parents=[common], help="move ~/.operator/tools onto consumers/aurora")
|
|
2667
|
+
how = s.add_mutually_exclusive_group(required=True)
|
|
2668
|
+
how.add_argument("--from-hermes", action="store_true")
|
|
2669
|
+
how.add_argument("--replace-tools-dir", action="store_true")
|
|
2670
|
+
s.add_argument("--dry-run", action="store_true")
|
|
2671
|
+
s.add_argument("--undo", action="store_true")
|
|
2672
|
+
s.add_argument("--reason", default="migrate")
|
|
2673
|
+
s.add_argument("--cache", metavar="DIR")
|
|
2674
|
+
s.add_argument("--offline", action="store_true")
|
|
2675
|
+
s.set_defaults(func=cmd_migrate)
|
|
2676
|
+
|
|
2677
|
+
s = sub.add_parser("smoke", parents=[common], help="serve-test a llama-server on 127.0.0.1:0, stopping only its own pid")
|
|
2678
|
+
s.add_argument("--bin", required=True)
|
|
2679
|
+
s.add_argument("--gguf")
|
|
2680
|
+
s.add_argument("--metal", action="store_true", help="also run with -ngl 99")
|
|
2681
|
+
s.add_argument("--via-launchd", metavar="LABEL", help="run as one-shot launchd jobs whose program is llama-server (the TCC path)")
|
|
2682
|
+
s.add_argument("--ready-timeout", type=float, metavar="SECONDS", help="wait for /health (default 60, 300 with --via-launchd)")
|
|
2683
|
+
s.add_argument("--expect", help="literal --version substring (default: the entry's probe)")
|
|
2684
|
+
s.add_argument("--report", metavar="FILE")
|
|
2685
|
+
s.add_argument("--term-timeout", type=float, default=10.0)
|
|
2686
|
+
s.add_argument("--cache", metavar="DIR")
|
|
2687
|
+
s.add_argument("--offline", action="store_true")
|
|
2688
|
+
s.set_defaults(func=cmd_smoke)
|
|
2689
|
+
|
|
2690
|
+
s = sub.add_parser("gate", parents=[common], help="rollout measurements against thresholds")
|
|
2691
|
+
s.add_argument("--url")
|
|
2692
|
+
s.add_argument("--input", metavar="FILE")
|
|
2693
|
+
s.add_argument("--suite", choices=sorted(GATE_THRESHOLDS), default="quick")
|
|
2694
|
+
out = s.add_mutually_exclusive_group(required=True)
|
|
2695
|
+
out.add_argument("--baseline", metavar="OUT")
|
|
2696
|
+
out.add_argument("--compare", metavar="FILE")
|
|
2697
|
+
s.add_argument("--api-key-file", metavar="FILE")
|
|
2698
|
+
s.add_argument("--cold-start", type=float, metavar="SECONDS")
|
|
2699
|
+
s.add_argument("--reason", default=None)
|
|
2700
|
+
s.set_defaults(func=cmd_gate)
|
|
2701
|
+
|
|
2702
|
+
s = sub.add_parser("manifest", parents=[common], help="manifest check [FILE]: the CI validator")
|
|
2703
|
+
s.add_argument("action", choices=["check"])
|
|
2704
|
+
s.add_argument("file", nargs="?")
|
|
2705
|
+
s.add_argument("--base", default="origin/main", help="main's manifest: a git ref, a FILE, or '-' for none")
|
|
2706
|
+
s.add_argument("--today", metavar="YYYY-MM-DD")
|
|
2707
|
+
s.set_defaults(func=cmd_manifest)
|
|
2708
|
+
return p
|
|
2709
|
+
|
|
2710
|
+
|
|
2711
|
+
def main(argv=None) -> int:
|
|
2712
|
+
args = parser().parse_args(argv)
|
|
2713
|
+
try:
|
|
2714
|
+
return args.func(args)
|
|
2715
|
+
except ToolchainError as e:
|
|
2716
|
+
say(f"toolchain: {e}")
|
|
2717
|
+
return e.code
|
|
2718
|
+
except KeyboardInterrupt:
|
|
2719
|
+
return 130
|
|
2720
|
+
|
|
2721
|
+
|
|
2722
|
+
if __name__ == "__main__":
|
|
2723
|
+
sys.exit(main())
|