1#!/usr/bin/env python3
2import argparse
3from contextlib import nullcontext
4import fcntl
5import hashlib
6import json
7import os
8from pathlib import Path
9import re
10import secrets
11import shutil
12import subprocess
13import sys
14import tempfile
15import time
16
17from data import cloned_postgres, dataset_for
18
19
20REPO = Path(__file__).resolve().parent.parent
21SERVICES = REPO / "service"
22STATE = Path("/var/lib/snowglobe")
23IDENTITIES = STATE / "identities.json"
24ASSETS = Path("/var/lib/caddy/snowglobe")
25NAME = re.compile(r"[a-z][a-z0-9-]*\Z")
26
27
28def command(*args, capture=False, **kwargs):
29 return subprocess.run(args, check=True, text=True, capture_output=capture, **kwargs)
30
31
32def service_files():
33 files = {}
34 for directory in SERVICES.iterdir():
35 if not directory.is_dir():
36 continue
37 for path in directory.glob("*.pkl"):
38 name = directory.name if path.name == "service.pkl" else path.stem
39 if name in files:
40 raise ValueError(f"duplicate service definition: {name}")
41 files[name] = path
42 return files
43
44
45def services():
46 return sorted(service_files())
47
48
49def service_dir(name):
50 path = service_files()[name]
51 return path.parent if path.name == "service.pkl" else path.parent / name
52
53
54def dependencies(data):
55 return set(data["dependsOn"]) | {item["provider"] for item in data["inputs"].values() if item["provider"] != "snowglobe"}
56
57
58def gpu(data):
59 return any(device.startswith("/dev/nvidia") for task in data["containers"].values() for device in task["devices"])
60
61
62def gpu_holder(data):
63 """The guest passing the GPU through while it's on, else the running job that needs the GPU."""
64 if not any(gpu(item) for item in data):
65 return None
66 vms = __import__("vms")
67 guest = vms.gpu_guest()
68 if guest and vms.virsh("domstate", guest) != "shut off":
69 return guest
70 return next((job for job, stopped in vms.gpu_jobs().items() if not stopped), None)
71
72
73def ordered(data):
74 pending = {item["id"]: item for item in data}
75 result = []
76 while pending:
77 ready = [
78 item
79 for item in pending.values()
80 if not dependencies(item) & pending.keys()
81 ]
82 if not ready:
83 raise ValueError("cycle in service dependencies")
84 for item in ready:
85 result.append(item)
86 del pending[item["id"]]
87 return result
88
89
90def identity(name):
91 STATE.mkdir(parents=True, exist_ok=True)
92 if not IDENTITIES.exists():
93 write_private(IDENTITIES, (REPO / "config/identities.json").read_text())
94 with (IDENTITIES.parent / ".identities.lock").open("w") as lock:
95 fcntl.flock(lock, fcntl.LOCK_EX)
96 with IDENTITIES.open() as file:
97 ids = json.load(file)
98 if len(set(ids.values())) != len(ids):
99 raise ValueError("duplicate service UIDs")
100 if name not in ids:
101 used = set(ids.values())
102 ids[name] = next(uid for uid in range(3100, 60000) if uid not in used)
103 pending = IDENTITIES.with_suffix(".pending")
104 pending.write_text(json.dumps(ids, indent=2) + "\n")
105 pending.replace(IDENTITIES)
106 return ids[name]
107
108
109def load(name, properties, instance_id=None):
110 files = service_files()
111 if not NAME.fullmatch(name) or name not in files:
112 raise ValueError(f"unknown service: {name}")
113 instance_id = instance_id or name
114 if not NAME.fullmatch(instance_id):
115 raise ValueError(f"invalid instance ID: {instance_id}")
116 uid = identity(name)
117 result = command(
118 "pkl",
119 "eval",
120 *(
121 part
122 for key, value in {**properties, "serviceId": instance_id, "uid": uid, "preview": str(instance_id != name).lower()}.items()
123 for part in ("-p", f"{key}={value}")
124 ),
125 str(files[name]),
126 capture=True,
127 )
128 data = json.loads(result.stdout)
129 if data["id"] != instance_id:
130 raise ValueError(f"service ID must match deployment: {instance_id}")
131 inputs = {}
132 for requirement in data.pop("requirements"):
133 alias = requirement["alias"]
134 if not NAME.fullmatch(alias) or alias == "own" or alias in inputs:
135 raise ValueError(f"invalid or duplicate requirement alias: {alias}")
136 inputs[alias] = requirement
137 issuer_hosts = [request.pop("issuerHostname") for request in inputs.values()
138 if request["provider"] == "snowglobe" and request["kind"] == "client"]
139 data["inputs"] = inputs
140 data["uid"] = uid
141 data["sourceId"] = name
142 for task_name, task in data["containers"].items():
143 task["extraHosts"] = list(dict.fromkeys(task["extraHosts"]))
144 for hostname in issuer_hosts:
145 if all(host.split(":", 1)[0].lower() != hostname.lower() for host in task["extraHosts"]):
146 task["extraHosts"].append(f"{hostname}:host-gateway")
147 if bool(task.get("image")) == bool(task.get("build")):
148 raise ValueError(f"{name}.{task_name} needs one image or build directory")
149 if task.get("build"):
150 if REPO.parent == Path("/opt/snowglobe/releases").resolve():
151 context = build_context(name, task["build"])
152 digest = hashlib.sha256()
153 for path in sorted(context.rglob("*")):
154 if path.is_file():
155 digest.update(str(path.relative_to(context)).encode() + b"\0")
156 digest.update(path.read_bytes())
157 tag = digest.hexdigest()[:16]
158 elif not (service_dir(name) / task["build"] / "Dockerfile").is_file() and not (service_dir(name) / "build-source.json").is_file():
159 raise ValueError(f"missing build source: {name}.{task_name}")
160 else:
161 tag = REPO.name
162 task["image"] = f"localhost/snowglobe/{name}-{task_name}:{tag}"
163 return data
164
165
166def q(value):
167 return json.dumps(value, ensure_ascii=False)
168
169
170def write_private(path, content):
171 pending = None
172 try:
173 with tempfile.NamedTemporaryFile("w", dir=path.parent, delete=False) as file:
174 pending = Path(file.name)
175 file.write(content)
176 pending.replace(path)
177 finally:
178 if pending:
179 pending.unlink(missing_ok=True)
180
181
182def host_path(root, relative):
183 if relative == ".":
184 return root
185 part = Path(relative)
186 if part.is_absolute() or ".." in part.parts or not part.parts:
187 raise ValueError(f"invalid relative path: {relative}")
188 return str(Path(root) / part)
189
190
191def config_path(service, relative):
192 root = service_dir(service).resolve()
193 source = (root / relative).resolve()
194 if not source.is_relative_to(root) or not source.exists():
195 raise ValueError(f"invalid config path: {relative}")
196 return source
197
198
199def build_context(service, relative):
200 source = (service_dir(service) / relative).resolve()
201 if not source.is_relative_to((REPO / "service").resolve()) or not (source / "Dockerfile").is_file():
202 raise ValueError(f"invalid build context: {relative}")
203 return source
204
205
206def config_assets(data):
207 paths = set()
208 for task in data["containers"].values():
209 paths.update(volume["config"] for volume in task["volumes"].values() if volume.get("config"))
210 if task.get("http"):
211 paths.update(task["http"]["overrideFiles"].values())
212 sources = {rel: config_path(data.get("sourceId", data["id"]), rel) for rel in paths}
213 digest = hashlib.sha256()
214 for rel, source in sorted(sources.items()):
215 digest.update(rel.encode())
216 files = sorted(source.rglob("*")) if source.is_dir() else [source]
217 for file in files:
218 if file.is_symlink():
219 raise ValueError(f"config asset cannot be a symlink: {file}")
220 if file.is_file():
221 digest.update(str(Path(rel) / file.relative_to(source)).encode() if source.is_dir() else rel.encode())
222 digest.update(file.read_bytes())
223 return ASSETS / data["id"] / digest.hexdigest()[:16], sources
224
225
226def render(data, definitions):
227 if not data["containers"]:
228 return ""
229 name = data["id"]
230 asset_dir, _ = config_assets(data)
231 prepare_digest = None
232 if data.get("prepare"):
233 source = service_dir(data.get("sourceId", name))
234 digest = hashlib.sha256()
235 for path in sorted(source.rglob("*")):
236 if not path.is_file() or "__pycache__" in path.parts or path.suffix == ".pyc":
237 continue
238 if path.name == "service.pkl" or path.name.startswith("icon"):
239 continue
240 digest.update(str(path.relative_to(source)).encode() + b"\0")
241 digest.update(path.read_bytes())
242 prepare_digest = digest.hexdigest()[:16]
243 routed = [task["http"] for task in data["containers"].values()
244 if task.get("http") and task["http"].get("hostname")]
245 primary = routed[0] if routed else {}
246 requirements = {provider: "startup" for provider in data["dependsOn"]}
247 requirements.update({item["provider"]: item["kind"] for item in data["inputs"].values()})
248 secrets_meta = [
249 {"name": name, "generated": True, "bytes": spec["bytes"]}
250 for name, spec in data["secrets"].items()
251 ] + [{"name": name, "generated": False} for name in data["requiredSecrets"]]
252 lines = [
253 f"job {q(name)} {{",
254 ' datacenters = ["clover"]',
255 ' type = "service"',
256 ' meta {',
257 f" snowglobe_service = {q(data['sourceId'])}",
258 f" snowglobe_name = {q(data['name'])}",
259 f" snowglobe_tagline = {q(data['tagline'])}",
260 f" snowglobe_hostname = {q(primary.get('hostname') or '')}",
261 f" snowglobe_launcher = {q(str(data['launcher']).lower())}",
262 f" snowglobe_auth_role = {q(data.get('access') or primary.get('authRole') or '')}",
263 f" snowglobe_trace_service = {q(data.get('traceServiceName') or '')}",
264 f" snowglobe_metrics_pushed = {q(str(data['metricsPushed']).lower())}",
265 f" snowglobe_requires = {q(json.dumps(requirements))}",
266 f" snowglobe_secrets = {q(json.dumps(secrets_meta))}",
267 ' }',
268 ' group "app" {',
269 ]
270 if dependencies(data):
271 lines += [
272 " restart {",
273 " attempts = 3",
274 ' delay = "1m"',
275 ' interval = "4m"',
276 ' mode = "delay"',
277 " }",
278 ]
279 if data["rollout"] == "overlapped":
280 for task in data["containers"].values():
281 if task["hostNetwork"] or any(
282 endpoint and endpoint.get("hostPort") is not None
283 for endpoint in (task.get("http"), *task["tcp"])
284 ) or any(not volume["readOnly"] for volume in task["volumes"].values()):
285 raise ValueError(f"overlapped rollout requires dynamic ports and read-only mounts: {name}")
286 elif data["rollout"] != "simple":
287 raise ValueError(f"unknown rollout: {data['rollout']}")
288 if data["rollout"] == "overlapped" or data.get("healthyDeadline"):
289 lines.append(" update {")
290 if data["rollout"] == "overlapped":
291 lines += [" canary = 1", " auto_promote = true", " auto_revert = true"]
292 if data.get("healthyDeadline"):
293 lines += [f" healthy_deadline = {q(data['healthyDeadline'])}", ' progress_deadline = "0"']
294 lines.append(" }")
295 if data.get("healthyDeadline"):
296 lines += [" migrate {", f" healthy_deadline = {q(data['healthyDeadline'])}", " }"]
297 ports = {}
298 network = []
299 host_network = any(task["hostNetwork"] for task in data["containers"].values())
300 if host_network and not all(task["hostNetwork"] for task in data["containers"].values()):
301 raise ValueError("mixed host and bridge networking in one group")
302 restricted = any(task["restrictedEgress"] for task in data["containers"].values())
303 if restricted and (host_network or not all(task["restrictedEgress"] for task in data["containers"].values())):
304 raise ValueError("restricted egress must cover every container in a bridge group")
305 for task_name, task in data["containers"].items():
306 for kind, endpoint in [("http", task.get("http")), *((port["name"], port) for port in task["tcp"])]:
307 if endpoint:
308 label = kind if len(data["containers"]) == 1 else f"{task_name}-{kind}"
309 if label in ports.values():
310 raise ValueError(f"duplicate port label: {label}")
311 ports[(task_name, kind)] = label
312 network.append(f" port {q(label)} {{")
313 if endpoint.get("hostPort") is not None:
314 network.append(f" static = {endpoint['hostPort']}")
315 if not task["hostNetwork"]:
316 network.append(f" to = {endpoint['containerPort']}")
317 if endpoint.get("loopback") or (not task["hostNetwork"] and kind == "http" and endpoint.get("hostPort") is None):
318 network.append(' host_network = "loopback"')
319 network.append(" }")
320 if network or restricted:
321 lines.append(" network {")
322 if host_network:
323 lines.append(' mode = "host"')
324 elif restricted:
325 lines.append(' mode = "cni/sandbox"')
326 lines += network + [" }"]
327 for provider_id in sorted(dependencies(data)):
328 provider = definitions[provider_id]
329 for provider_task, container in provider["containers"].items():
330 endpoint = container.get("http")
331 if not endpoint or not endpoint.get("hostname") or endpoint.get("authRole"):
332 continue
333 host = endpoint["hostname"]
334 task_name = f"wait-{provider_id}-{provider_task}"
335 lines += [
336 f" task {q(task_name)} {{",
337 ' driver = "podman"',
338 " lifecycle {",
339 ' hook = "prestart"',
340 " sidecar = false",
341 " }",
342 " config {",
343 ' image = "docker.io/curlimages/curl@sha256:43ebaa53d3806db6b1ce4353b6b26ae638ec1c167ee351524b05690f988bb20d"',
344 f" extra_hosts = {q([host + ':host-gateway'])}",
345 f" args = {q(['--insecure', '--fail', '--silent', '--show-error', '--retry', '999999', '--retry-all-errors', '--retry-delay', '5', '--connect-timeout', '3', '--max-time', '5', 'https://' + host + endpoint['checkPath']])}",
346 " }",
347 " resources {",
348 " cpu = 50",
349 " memory = 64",
350 " }",
351 " }",
352 ]
353 for task_name, task in data["containers"].items():
354 if task.get("http") or task.get("tcp"):
355 kind = "http" if task.get("http") else "tcp"
356 endpoint = task["http"] if kind == "http" else task["tcp"][0]
357 label = ports[(task_name, "http" if kind == "http" else endpoint["name"])]
358 lines += [" service {", f" name = {q(name if task_name == 'app' else name + '-' + task_name)}", ' provider = "nomad"', f" port = {q(label)}"]
359 if len(data["containers"]) == 1:
360 lines.append(f" task = {q(task_name)}")
361 tags = []
362 if kind == "http" and endpoint.get("metricsPath"):
363 tags.append("snowglobe-metrics-path=" + endpoint["metricsPath"])
364 if kind == "http" and endpoint.get("hostname"):
365 tags.append("caddy-host=" + endpoint["hostname"])
366 tags += ["caddy-plain-host=" + host for host in endpoint["plainHostnames"]]
367 if endpoint.get("authRole"):
368 tags.append("caddy-auth-role=" + endpoint["authRole"])
369 if endpoint.get("userHeader"):
370 tags.append("caddy-user-header=" + endpoint["userHeader"])
371 if endpoint["forwardRealIp"]:
372 tags.append("caddy-real-ip=true")
373 if endpoint.get("secureCookies"):
374 tags.append("caddy-secure-cookies=true")
375 if endpoint["tlsInternal"]:
376 tags.append("caddy-internal=true")
377 if tags:
378 lines.append(f" tags = {q(tags)}")
379 lines += [" check {", f" type = {q(kind)}"]
380 if kind == "http":
381 lines.append(f" path = {q(endpoint['checkPath'])}")
382 if endpoint["checkHeaders"]:
383 lines.append(" header {")
384 for key, value in endpoint["checkHeaders"].items():
385 if not re.fullmatch(r"[A-Za-z][A-Za-z0-9-]*", key):
386 raise ValueError(f"invalid health check header: {key}")
387 lines.append(f" {key} = [{q(value)}]")
388 lines.append(" }")
389 lines += [
390 ' interval = "10s"',
391 ' timeout = "15s"',
392 ' check_restart {',
393 ' limit = 12',
394 f" grace = {q(data.get('healthRestartGrace') or data.get('healthyDeadline') or '5m')}",
395 ' }',
396 ' }',
397 ' }',
398 ]
399 for task_name, task in data["containers"].items():
400 lines += [f" task {q(task_name)} {{", ' driver = "podman"']
401 if task.get("killTimeout"):
402 lines.append(f" kill_timeout = {q(task['killTimeout'])}")
403 if task["lifecycle"] != "main":
404 lines += [' lifecycle {', ' hook = "prestart"',
405 f" sidecar = {str(task['lifecycle'] == 'prestartSidecar').lower()}", ' }']
406 if not task["imageUser"]:
407 uses_clover = any(
408 volume.get("clover") or (
409 volume.get("src")
410 and Path(volume["src"]).resolve().is_relative_to(Path(data["cloverRoot"]).resolve())
411 )
412 for volume in task["volumes"].values()
413 )
414 gid = data["cloverGid"] if uses_clover else 0 if task["rootGroup"] else data["uid"]
415 lines.append(f" user = {q(str(data['uid']) + ':' + str(gid))}")
416 lines += [" config {", f" image = {q(task['image'])}"]
417 if task.get("entrypoint"):
418 lines.append(f" entrypoint = {q(task['entrypoint'])}")
419 if task["args"]:
420 lines.append(f" args = {q(task['args'])}")
421 if task["hostNetwork"]:
422 lines.append(' network_mode = "host"')
423 if task.get("readOnlyRoot"):
424 lines.append(' readonly_rootfs = true')
425 task_ports = [label for (owner, _), label in ports.items() if owner == task_name]
426 if task_ports and not task["hostNetwork"] and not restricted:
427 lines.append(f" ports = {q(task_ports)}")
428 for field, values in (("cap_add", task["capAdd"]), ("devices", task["devices"]), ("extra_hosts", task["extraHosts"])):
429 if values:
430 lines.append(f" {field} = {q(values)}")
431 volumes = []
432 secret_files = task.get("secretFiles", {})
433 filenames = set()
434 for target, template in secret_files.items():
435 filename = Path(target).name
436 if (not re.fullmatch(r"/[A-Za-z0-9_./-]+", target) or target.endswith("/")
437 or any(part in {".", "..", ""} for part in target[1:].split("/"))
438 or filename in filenames
439 or filename in {task_name + ".env", task_name + "-secret.env", "nomad_token"}
440 or target in task["volumes"] or target == "/secrets" or target.startswith("/secrets/")):
441 raise ValueError(f"invalid secret file target: {target}")
442 if task["imageUser"]:
443 raise ValueError("secret files require a service-owned container user")
444 if re.search(r"(?m)^EOF\r?$", template):
445 raise ValueError("invalid secret template delimiter")
446 filenames.add(filename)
447 volumes.append(f"secrets/{filename}:{target}:ro")
448 for target, volume in task["volumes"].items():
449 if not target.startswith("/") or ":" in target:
450 raise ValueError(f"invalid volume target: {target}")
451 if volume.get("config") is not None:
452 if volume.get("src") is not None or not volume["readOnly"]:
453 raise ValueError("config mounts must be read only and have no host source")
454 config_path(data.get("sourceId", name), volume["config"])
455 source = host_path(str(asset_dir), volume["config"])
456 elif volume.get("src") is not None:
457 source = volume["src"]
458 if not Path(source).is_absolute():
459 raise ValueError(f"volume source must be absolute: {source}")
460 else:
461 source = host_path(data["hostRoot"], target.lstrip("/"))
462 if ":" in source:
463 raise ValueError(f"invalid volume source: {source}")
464 volumes.append(f"{source}:{target}" + (":ro" if volume["readOnly"] else ""))
465 if volumes:
466 lines.append(f" volumes = {q(volumes)}")
467 if task["tmpfs"]:
468 lines.append(f" tmpfs = {q(task['tmpfs'])}")
469 lines.append(" }")
470 secret_env = []
471 plain_env = {}
472 for key, value in task["env"].items():
473 if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):
474 raise ValueError(f"invalid env key: {key}")
475 parts = re.split(r"(\$\{secret\.[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*\})", value)
476 if len(parts) == 1:
477 if "${secret." in value:
478 raise ValueError(f"invalid secret reference: {value}")
479 plain_env[key] = value
480 continue
481 args = []
482 paths = {}
483 for part in parts:
484 match = re.fullmatch(r"\$\{secret\.([A-Za-z_][A-Za-z0-9_]*)\.([A-Za-z_][A-Za-z0-9_]*)\}", part)
485 if match:
486 alias, field = match.groups()
487 if alias != "own" and alias not in data["inputs"]:
488 raise ValueError(f"unknown secret alias: {alias}")
489 path = f"nomad/jobs/{name}" + (f"/inputs/{alias}" if alias != "own" else "")
490 variable = paths.setdefault(path, f"$s{len(paths)}")
491 args.append(f"(index {variable} {q(field)}).Value")
492 elif part:
493 args.append(q(part))
494 start = "".join(f'{{{{ with {variable} := nomadVar {q(path)} }}}}' for path, variable in paths.items())
495 end = "{{ end }}" * len(paths)
496 secret_env.append(f'{start}{key}={{{{ print {" ".join(args)} | toJSON }}}}{end}')
497 if "SNOWGLOBE_PREPARE_DIGEST" in task["env"]:
498 raise ValueError("SNOWGLOBE_PREPARE_DIGEST is reserved")
499 lines.append(" env {")
500 for key, value in plain_env.items():
501 lines.append(f" {key} = {q(value)}")
502 if prepare_digest:
503 lines.append(f" SNOWGLOBE_PREPARE_DIGEST = {q(prepare_digest)}")
504 lines.append(" }")
505 if secret_env:
506 lines += [" template {", " data = <<EOF", *secret_env, "EOF", f' destination = {q("secrets/" + task_name + "-secret.env")}', " env = true", " error_on_missing_key = true", " }"]
507 if task.get("envTemplate"):
508 if "\nEOF\n" in task["envTemplate"]:
509 raise ValueError("invalid env template delimiter")
510 lines += [" template {", " data = <<EOF", task["envTemplate"].rstrip(), "EOF", f' destination = {q("secrets/" + task_name + ".env")}', " env = true", " }"]
511 for target, template in secret_files.items():
512 lines += [" template {", " data = <<EOF", template.rstrip(), "EOF",
513 f' destination = {q("secrets/" + Path(target).name)}', ' perms = "0400"',
514 f' uid = {data["uid"]}', f' gid = {data["uid"]}',
515 " error_on_missing_key = true", " }"]
516 lines += [" resources {", f" cpu = {task['cpu']}", f" memory = {task['memory']}", " }", " }"]
517 lines += [" }", "}"]
518 return "\n".join(lines) + "\n"
519
520
521def token():
522 if "NOMAD_TOKEN" not in os.environ:
523 os.environ["NOMAD_TOKEN"] = (STATE / "nomad.token").read_text().strip()
524
525
526def get_variable(path):
527 result = subprocess.run(["nomad", "var", "get", "-out=json", path], capture_output=True, text=True)
528 if result.returncode == 0:
529 return json.loads(result.stdout)
530 if "Variable not found" in result.stderr + result.stdout:
531 return None
532 raise RuntimeError(f"Nomad variable read failed for {path}: {result.stderr.strip()}")
533
534
535def provision(data):
536 if not data["containers"]:
537 return
538 if os.geteuid() != 0:
539 raise PermissionError("provisioning requires root")
540 root = Path(data["hostRoot"])
541 if data["hasManagedVolumes"]:
542 root.mkdir(parents=True, exist_ok=True)
543 if command(
544 "findmnt", "-n", "-o", "FSTYPE", "--mountpoint", str(root), capture=True
545 ).stdout.strip() != "zfs":
546 raise ValueError(f"expected ZFS dataset at {root}")
547 for task in data["containers"].values():
548 gid = 0 if task["rootGroup"] else data["uid"]
549 for target, volume in task["volumes"].items():
550 if volume.get("config") is not None or volume.get("src") is not None:
551 continue
552 path = Path(host_path(str(root), target.lstrip("/")))
553 path.mkdir(parents=True, exist_ok=True)
554 os.chown(path, data["uid"], gid)
555 path.chmod(0o750)
556 if data["sourceId"] == "ytdl" and target == "/data":
557 command("systemd-tmpfiles", "--create", "--prefix=" + str(path))
558 bundle = STATE / "ca-bundle.crt"
559 if any(
560 volume.get("src") == str(bundle)
561 for task in data["containers"].values()
562 for volume in task["volumes"].values()
563 ):
564 contents = Path("/etc/ssl/certs/ca-certificates.crt").read_bytes()
565 local_ca = Path("/var/lib/caddy/.local/share/caddy/pki/authorities/local/root.crt")
566 if local_ca.exists():
567 contents += b"\n" + local_ca.read_bytes()
568 if not bundle.exists() or bundle.read_bytes() != contents:
569 pending = bundle.with_suffix(".pending")
570 pending.write_bytes(contents)
571 pending.chmod(0o644)
572 pending.replace(bundle)
573 route_dir = STATE / "routes"
574 route_dir.mkdir(parents=True, exist_ok=True)
575 asset_dir, assets = config_assets(data)
576 static = {}
577 directories = {}
578 identity = {}
579 head_html = {}
580 metrics_paths = {}
581 api_paths = {}
582 for task in data["containers"].values():
583 if task.get("http"):
584 http = task["http"]
585 if http["identityHeaders"]:
586 identity[http["hostname"]] = http["identityHeaders"]
587 if http["headHtml"]:
588 head_html[http["hostname"]] = http["headHtml"]
589 if http.get("metricsPath") and http["hostname"]:
590 metrics_paths[http["hostname"]] = http["metricsPath"]
591 if http.get("apiPaths"):
592 targets = {}
593 for path, task_name in http["apiPaths"].items():
594 target = data["containers"].get(task_name)
595 if (not http["hostname"] or not re.fullmatch(r"/[A-Za-z0-9/._-]+\*?", path)
596 or not target or not (target.get("http") or target.get("tcp"))):
597 raise ValueError(f"invalid API route for {data['id']}: {path}")
598 targets[path] = data["id"] if task_name == "app" else data["id"] + "-" + task_name
599 api_paths[http["hostname"]] = targets
600 for request, rel in http["overrideFiles"].items():
601 origin = assets[rel]
602 target = directories if origin.is_dir() else static
603 target[request] = host_path(str(asset_dir), rel)
604 if assets:
605 asset_dir.parent.mkdir(parents=True, exist_ok=True)
606 asset_dir.parent.chmod(0o755)
607 if assets and not asset_dir.exists():
608 temporary = tempfile.mkdtemp(dir=asset_dir.parent)
609 try:
610 for rel, origin in assets.items():
611 destination = Path(temporary) / rel
612 destination.parent.mkdir(parents=True, exist_ok=True)
613 if origin.is_dir():
614 shutil.copytree(origin, destination)
615 for child in destination.rglob("*"):
616 child.chmod(0o755 if child.is_dir() else 0o644)
617 else:
618 shutil.copy2(origin, destination)
619 destination.chmod(0o644)
620 Path(temporary).chmod(0o755)
621 os.replace(temporary, asset_dir)
622 finally:
623 shutil.rmtree(temporary, ignore_errors=True)
624 secret_dir = STATE / "secrets"
625 secret_dir.mkdir(parents=True, exist_ok=True)
626 secret_file = secret_dir / f"{data['id']}.nv.hcl"
627 generated = data["secrets"]
628 required = data["requiredSecrets"]
629 secret_path = "nomad/jobs/" + data["id"]
630 existing = get_variable(secret_path) if generated or required else None
631 if generated and not existing and secret_file.exists():
632 command("nomad", "var", "put", "-in=hcl", "-out=none", secret_path, "@" + str(secret_file))
633 existing = get_variable(secret_path)
634 values = dict(existing["Items"]) if existing else {}
635 if generated:
636 for item, spec in generated.items():
637 if item not in values:
638 values[item] = secrets.token_hex(spec["bytes"])
639 if not existing or values != existing["Items"]:
640 put_variable(secret_path, values, existing["ModifyIndex"] if existing else 0)
641 backup = "items {\n" + "".join(f" {item} = {q(value)}\n" for item, value in values.items()) + "}\n"
642 if not secret_file.exists() or secret_file.read_text() != backup:
643 write_private(secret_file, backup)
644 if required:
645 missing = [name for name in required if not values.get(name)]
646 if missing:
647 raise ValueError(f"missing required secrets for {data['id']}: {', '.join(missing)}")
648 proof = {}
649 for task in data["containers"].values():
650 http = task.get("http")
651 if http and http.get("identityProofSecret"):
652 name = http["identityProofSecret"]
653 if not http["identityHeaders"] or name not in values:
654 raise ValueError(f"missing identity proof secret for {data['id']}")
655 proof[http["hostname"]] = "X-Snowglobe-Idp-" + values[name]
656 write_private(route_dir / f"{data['id']}.json", json.dumps({
657 "files": static, "dirs": directories, "identity": identity,
658 "identityProof": proof, "headHtml": head_html, "metricsPaths": metrics_paths, "apiPaths": api_paths,
659 }))
660
661
662def submit(data, mode, definitions, stopped=False):
663 """`stopped` registers the job with no allocations, as `nomad job stop` leaves it."""
664 if not data["containers"]:
665 return
666 with tempfile.NamedTemporaryFile("w", suffix=".nomad.hcl", delete=False) as file:
667 file.write(render(data, definitions))
668 path = file.name
669 try:
670 if stopped:
671 job = json.loads(command("nomad", "job", "run", "-output", path, capture=True).stdout)
672 job["Job"]["Stop"] = True
673 Path(path).write_text(json.dumps(job))
674 command("nomad", "job", "run", "-detach", "-json", path)
675 else:
676 command("nomad", "job", mode, path)
677 finally:
678 Path(path).unlink()
679
680
681def build_images(data):
682 for task in data["containers"].values():
683 if task.get("build"):
684 image = task["image"]
685 if subprocess.run(["podman", "image", "exists", image]).returncode:
686 command("podman", "build", "-t", image, str(build_context(data["sourceId"], task["build"])))
687
688
689def clone_dataset(source, snapshot, dataset, mount):
690 acltype = command("zfs", "get", "-H", "-o", "value", "acltype", source, capture=True).stdout.strip()
691 command("zfs", "clone", "-o", "mountpoint=" + mount, "-o", "acltype=" + acltype, snapshot, dataset)
692
693
694def check_http(host, path, tls_internal=False, attempts=120):
695 for attempt in range(attempts):
696 try:
697 if subprocess.run(
698 ["curl", "--noproxy", "*", "-sf", *(["--cacert", "/var/lib/caddy/.local/share/caddy/pki/authorities/local/root.crt"] if tls_internal else []), "--resolve", f"{host}:443:127.0.0.1", f"https://{host}{path}"],
699 capture_output=True, timeout=3,
700 ).returncode == 0:
701 print(f"Healthy {host}")
702 return
703 except subprocess.TimeoutExpired:
704 pass
705 time.sleep(2)
706 raise RuntimeError(f"HTTPS route is unhealthy: {host}")
707
708
709def put_variable(path, items, index=None):
710 with tempfile.NamedTemporaryFile("w", suffix=".nv.hcl", delete=False) as file:
711 file.write("items {\n" + "".join(f" {key} = {q(value)}\n" for key, value in items.items()) + "}\n")
712 filename = file.name
713 try:
714 command("nomad", "var", "put", "-in=hcl", "-out=none", *([f"-check-index={index}"] if index is not None else []), path, "@" + filename)
715 finally:
716 Path(filename).unlink()
717
718
719def configure(data):
720 if not data.get("setup"):
721 return
722 if data["setup"].startswith("tools/"):
723 script = (REPO / data["setup"]).resolve()
724 if not script.is_relative_to(REPO / "tools") or not script.is_file():
725 raise ValueError(f"invalid shared setup script: {data['setup']}")
726 else:
727 script = config_path(data.get("sourceId", data["id"]), data["setup"])
728 routes = [task["http"] for task in data["containers"].values()
729 if task.get("http") and task["http"].get("hostname")]
730 if len(routes) != 1:
731 raise ValueError("service setup requires one HTTP hostname")
732 route = routes[0]
733 check_http(route["hostname"], route["checkPath"], route["tlsInternal"], attempts=600)
734 variable = get_variable("nomad/jobs/" + data["id"])
735 own = variable["Items"] if variable else {}
736 command("python3", str(script), input=json.dumps({
737 "serviceId": data["id"], "host": route["hostname"], "hostRoot": data["hostRoot"],
738 "preview": data["id"] != data.get("sourceId", data["id"]),
739 "ownerEmail": data["ownerEmail"], **own,
740 }))
741 print(f"Configured {data['id']}")
742
743
744def prepare(data):
745 if data.get("prepare"):
746 script = config_path(data.get("sourceId", data["id"]), data["prepare"])
747 command("python3", str(script), input=json.dumps({
748 "hostRoot": data["hostRoot"], "uid": data["uid"],
749 }))
750
751
752def provision_inputs(data, definitions, stage_id=None, postgres_source=None):
753 for alias, request in data["inputs"].items():
754 if not NAME.fullmatch(alias):
755 raise ValueError(f"invalid input alias: {alias}")
756 native = request["provider"] == "snowglobe"
757 provider = {"id": "snowglobe", "provide": True, "containers": {}} if native else definitions[request["provider"]]
758 if not provider.get("provide"):
759 raise ValueError(f"{provider['id']} does not provide inputs")
760 path = f"nomad/jobs/{data['id']}/inputs/{alias}"
761 variable = get_variable(path)
762 own = (get_variable("nomad/jobs/" + provider["id"]) or {}).get("Items", {})
763 http = next((task["http"] for task in provider["containers"].values()
764 if task.get("http") and task["http"].get("hostname")), None)
765 if http:
766 check_http(http["hostname"], http["checkPath"], http["tlsInternal"])
767 payload = {
768 "request": request,
769 "existing": variable["Items"] if variable else None,
770 "providerSecrets": own,
771 "host": http["hostname"] if http else None,
772 }
773 if stage_id:
774 payload["stageId"] = stage_id
775 if postgres_source and provider["id"] == "postgres":
776 payload["sourceContainer"] = postgres_source
777 script = REPO / "tools/oidc-provider.py" if native else config_path(provider["id"], provider["provide"])
778 result = command("python3", str(script), input=json.dumps(payload), capture=True)
779 values = json.loads(result.stdout)
780 if not isinstance(values, dict) or not values or any(
781 not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key) or not isinstance(value, str) or not value
782 for key, value in values.items()
783 ):
784 raise ValueError(f"invalid outputs from {provider['id']}")
785 if not variable or variable["Items"] != values:
786 put_variable(path, values, variable["ModifyIndex"] if variable else None)
787 print(f"Allocated {data['id']}.{alias} from {provider['id']}")
788
789
790def bootstrap(all_data):
791 if os.geteuid() != 0:
792 raise PermissionError("bootstrap requires root")
793 STATE.mkdir(parents=True, exist_ok=True)
794 if not (STATE / "nomad.token").exists():
795 result = command("nomad", "acl", "bootstrap", "-json", capture=True)
796 write_private(STATE / "nomad.token", json.loads(result.stdout)["SecretID"] + "\n")
797 token()
798 command(
799 "nomad",
800 "acl",
801 "policy",
802 "apply",
803 "snowglobe-router",
804 str(REPO / "config/policies/router.hcl"),
805 )
806 command("nomad", "acl", "policy", "apply", "snowglobe-dashboard",
807 str(REPO / "config/policies/dashboard.hcl"))
808 router_token = STATE / "router.token"
809 if not router_token.exists():
810 result = command(
811 "nomad",
812 "acl",
813 "token",
814 "create",
815 "-policy=snowglobe-router",
816 "-name=snowglobe-router",
817 "-json",
818 capture=True,
819 )
820 write_private(router_token, json.loads(result.stdout)["SecretID"] + "\n")
821 dashboard_token = STATE / "dashboard.token"
822 if not dashboard_token.exists():
823 result = command("nomad", "acl", "token", "create", "-policy=snowglobe-dashboard",
824 "-name=snowglobe-dashboard", "-json", capture=True)
825 write_private(dashboard_token, json.loads(result.stdout)["SecretID"] + "\n")
826 for data in all_data:
827 paths = {
828 f"nomad/jobs/{data['id']}/inputs/{alias}" for alias in data["inputs"]
829 }
830 if paths and data["containers"]:
831 policy = (
832 'namespace "default" {\n variables {\n'
833 + "".join(
834 f' path {q(path)} {{ capabilities = ["read"] }}\n'
835 for path in sorted(paths)
836 )
837 + " }\n}\n"
838 )
839 with tempfile.NamedTemporaryFile("w", delete=False) as file:
840 file.write(policy)
841 path = file.name
842 try:
843 for task_name in data["containers"]:
844 command(
845 "nomad", "acl", "policy", "apply", "-namespace", "default",
846 "-job", data["id"], "-group", "app", "-task", task_name,
847 data["id"] + "-" + task_name + "-imports", path,
848 )
849 finally:
850 Path(path).unlink()
851 current = Path("/opt/snowglobe/current")
852 if current.is_symlink():
853 command("systemctl", "start", "snowglobe-router.service")
854
855
856def destroy_stage(stage, metadata, definitions):
857 subprocess.run(["nomad", "job", "stop", "-purge", "-yes", stage], check=False)
858 for alias, request in metadata["inputs"].items():
859 native = request["provider"] == "snowglobe"
860 provider = {"id": "snowglobe", "provide": True, "containers": {}} if native else definitions[request["provider"]]
861 own = (get_variable("nomad/jobs/" + provider["id"]) or {}).get("Items", {})
862 variable = get_variable(f"nomad/jobs/{stage}/inputs/{alias}")
863 existing = variable["Items"] if variable else None
864 hosts = [task["http"]["hostname"] for task in provider["containers"].values()
865 if task.get("http") and task["http"].get("hostname")]
866 script = REPO / "tools/oidc-provider.py" if native else config_path(provider["id"], provider["provide"])
867 command("python3", str(script), input=json.dumps({
868 "operation": "delete", "request": request, "stageId": stage,
869 "providerSecrets": own, "host": hosts[0] if hosts else None,
870 "existing": existing,
871 }))
872 datasets = list(metadata.get("external", {}).values())
873 if metadata.get("clone"):
874 datasets.append({"clone": metadata["clone"], "snapshot": metadata.get("snapshot")})
875 for dataset in datasets:
876 for attempt in range(30):
877 if subprocess.run(["zfs", "destroy", dataset["clone"]], capture_output=True).returncode == 0:
878 break
879 time.sleep(1)
880 else:
881 raise RuntimeError("preview dataset is still in use")
882 if dataset.get("snapshot"):
883 command("zfs", "destroy", dataset["snapshot"])
884 if not metadata.get("clone"):
885 shutil.rmtree(metadata["mount"], ignore_errors=True)
886 for alias in metadata["inputs"]:
887 subprocess.run(["nomad", "var", "purge", f"nomad/jobs/{stage}/inputs/{alias}"], check=False)
888 subprocess.run(["nomad", "var", "purge", "nomad/jobs/" + stage], check=False)
889 for task in metadata["tasks"]:
890 subprocess.run(["nomad", "acl", "policy", "delete", stage + "-" + task + "-imports"], check=False)
891 for path in (
892 STATE / "stages" / f"{stage}.json",
893 STATE / "routes" / f"{stage}.json",
894 STATE / "secrets" / f"{stage}.nv.hcl",
895 ):
896 path.unlink(missing_ok=True)
897 shutil.rmtree(ASSETS / stage, ignore_errors=True)
898
899
900def check_pool(data):
901 if os.geteuid() != 0:
902 raise PermissionError("pool setup requires root")
903 clover = subprocess.run(
904 ["findmnt", "-n", "-o", "SOURCE,FSTYPE", "--mountpoint", data[0]["cloverRoot"]],
905 capture_output=True, text=True,
906 )
907 clover_info = clover.stdout.split()
908 if clover.returncode or len(clover_info) != 2 or clover_info[1] != "zfs":
909 raise ValueError(f"clover must be a mounted ZFS dataset: {data[0]['cloverRoot']}")
910 media = data[0]["mediaRoot"]
911 mounted = subprocess.run(
912 ["findmnt", "-n", "-o", "SOURCE,FSTYPE", "--mountpoint", media],
913 capture_output=True, text=True,
914 )
915 media_info = mounted.stdout.split()
916 expected = {"fuse"} if os.environ.get("SNOWGLOBE_MEDIA_READ_ONLY") == "true" else {"zfs"}
917 if mounted.returncode or len(media_info) != 2 or media_info[1] not in expected or media_info[0] == clover_info[0]:
918 raise ValueError(f"media must be a separate mounted dataset: {media}")
919 for path, info in ((data[0]["cloverRoot"], clover_info), (media, media_info)):
920 if info[1] == "zfs":
921 acltype = command("zfs", "get", "-H", "-o", "value", "acltype", info[0], capture=True).stdout.strip()
922 if acltype == "nfsv4":
923 raise ValueError(f"{path} uses NFSv4 ACLs, which NixOS cannot enforce. Rehearse a POSIX permission conversion on a ZFS clone before migration.")
924 pool = data[0]["pool"]
925 if subprocess.run(["zpool", "list", pool], capture_output=True).returncode:
926 raise ValueError(f"ZFS pool is unavailable: {pool}")
927 prod = pool + "/prod"
928 acl_source = prod if subprocess.run(["zfs", "list", prod], capture_output=True).returncode == 0 else pool
929 if command("zfs", "get", "-H", "-o", "value", "acltype", acl_source, capture=True).stdout.strip() == "nfsv4":
930 raise ValueError(f"{acl_source} uses NFSv4 ACLs; service datasets need POSIX ACLs on NixOS.")
931 encrypted = any(
932 command("zfs", "get", "-H", "-o", "value", "encryption", info[0], capture=True).stdout.strip() != "off"
933 for info in (clover_info, media_info) if info[1] == "zfs"
934 )
935 if encrypted:
936 root = str(Path(data[0]["hostRoot"]).parent)
937 mounted = subprocess.run(["findmnt", "-n", "-o", "SOURCE", "--mountpoint", root], capture_output=True, text=True)
938 encryption = subprocess.run(["zfs", "get", "-H", "-o", "value", "encryption", prod], capture_output=True, text=True)
939 if encryption.returncode or encryption.stdout.strip() == "off" or mounted.stdout.strip() != prod:
940 raise ValueError(f"Create and mount encrypted {prod} at {root} before deployment; the existing storage is encrypted.")
941
942
943def check_staging_pool(data):
944 check_pool([data])
945 prod = data["pool"] + "/prod"
946 staging = data["pool"] + "/staging"
947 acl_source = staging if subprocess.run(["zfs", "list", staging], capture_output=True).returncode == 0 else data["pool"]
948 if command("zfs", "get", "-H", "-o", "value", "acltype", acl_source, capture=True).stdout.strip() == "nfsv4":
949 raise ValueError(f"{acl_source} uses NFSv4 ACLs; staged datasets need POSIX ACLs on NixOS.")
950 encryption = subprocess.run(["zfs", "get", "-H", "-o", "value", "encryption", prod], capture_output=True, text=True)
951 if encryption.returncode or encryption.stdout.strip() == "off":
952 return
953 mounted = subprocess.run(["findmnt", "-n", "-o", "SOURCE", "--mountpoint", data["stagingRoot"]], capture_output=True, text=True)
954 staging_encryption = subprocess.run(["zfs", "get", "-H", "-o", "value", "encryption", staging], capture_output=True, text=True)
955 if staging_encryption.returncode or staging_encryption.stdout.strip() == "off" or mounted.stdout.strip() != staging:
956 raise ValueError(f"Create and mount encrypted {staging} at {data['stagingRoot']} before staging.")
957
958
959def ensure_pool(data):
960 check_pool(data)
961 STATE.mkdir(parents=True, exist_ok=True)
962 pool = data[0]["pool"]
963 for item in data:
964 if item["hasManagedVolumes"]:
965 dataset = pool + "/prod/" + item["id"]
966 if subprocess.run(["zfs", "list", dataset], capture_output=True).returncode:
967 root = Path(item["hostRoot"])
968 if root.exists() and any(root.iterdir()):
969 raise ValueError(f"refusing to mount over {root}")
970 if subprocess.run(["zfs", "list", pool + "/prod"], capture_output=True).returncode:
971 parent = str(root.parent)
972 if Path(parent).exists() and any(Path(parent).iterdir()):
973 raise ValueError(f"refusing to mount over {parent}")
974 command("zfs", "create", "-o", "mountpoint=" + parent, pool + "/prod")
975 command("zfs", "create", "-o", "mountpoint=" + str(root), dataset)
976 command("zfs", "set", "snowglobe:snapshots=" + str(item["snapshots"]).lower(), dataset)
977
978
979def main():
980 parser = argparse.ArgumentParser()
981 parser.add_argument(
982 "mode",
983 choices=[
984 "render",
985 "secrets",
986 "validate",
987 "check",
988 "bootstrap",
989 "deploy",
990 "preflight",
991 "pool",
992 "allocate",
993 "stage",
994 "destroy",
995 ],
996 )
997 parser.add_argument("name", nargs="?")
998 parser.add_argument("--computer")
999 parser.add_argument("--base-domain")
1000 parser.add_argument("--root")
1001 parser.add_argument("--pool")
1002 parser.add_argument("--media-root")
1003 parser.add_argument("--env", action="append", default=[])
1004 parser.add_argument("--key", action="append", default=[])
1005 args = parser.parse_args()
1006 if args.computer and (args.mode != "stage" or args.name != "dashboard"):
1007 parser.error("--computer requires stage dashboard")
1008 if args.mode == "stage" and args.name == "dashboard":
1009 if args.env or args.base_domain or args.root or args.pool or args.media_root:
1010 parser.error("dashboard staging uses the host configuration")
1011 __import__("dashboard-stage").stage(args.computer)
1012 return
1013 if args.mode == "destroy" and args.name and NAME.fullmatch(args.name):
1014 saved = STATE / "stages" / f"{args.name}.json"
1015 if saved.exists() and json.loads(saved.read_text()).get("sourceId") == "dashboard":
1016 __import__("dashboard-stage").destroy(args.name)
1017 return
1018 if args.mode == "allocate" and not args.name:
1019 parser.error("allocate requires a service name")
1020 if args.key and args.mode != "secrets":
1021 parser.error("--key is available only for secrets")
1022 if args.name and args.mode != "destroy" and args.name not in service_files():
1023 raise ValueError(f"unknown service: {args.name}")
1024 properties = {
1025 key: value
1026 for key, value in (("domain", args.base_domain), ("root", args.root), ("pool", args.pool), ("mediaRoot", args.media_root))
1027 if value
1028 }
1029 names = [args.name] if args.name else services()
1030 if args.mode == "secrets":
1031 if not args.name or not NAME.fullmatch(args.name):
1032 parser.error("secrets requires a service name")
1033 data = load(args.name, properties)
1034 declared = [*data["requiredSecrets"], *data["secrets"]]
1035 fields = args.key or declared
1036 if not declared or len(set(declared)) != len(declared) or any(not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", field) for field in declared):
1037 raise ValueError(f"invalid required secrets for {args.name}")
1038 if len(set(fields)) != len(fields) or any(field not in declared for field in fields):
1039 raise ValueError(f"unknown or duplicate secret key for {args.name}")
1040 values = sys.stdin.read().splitlines()
1041 if len(values) != len(fields) or any(not value for value in values):
1042 raise ValueError(f"expected {len(fields)} nonempty secret lines for {args.name}")
1043 token()
1044 path = "nomad/jobs/" + args.name
1045 existing = get_variable(path)
1046 items = dict(existing["Items"]) if existing else {}
1047 items.update(zip(fields, values))
1048 put_variable(path, items, existing["ModifyIndex"] if existing else 0)
1049 print(f"Imported {len(fields)} secrets for {args.name}")
1050 return
1051 if args.mode == "destroy":
1052 if not args.name or not NAME.fullmatch(args.name):
1053 parser.error("destroy requires a stage ID")
1054 token()
1055 metadata = json.loads((STATE / "stages" / f"{args.name}.json").read_text())
1056 names = {metadata["sourceId"]} | {request["provider"] for request in metadata["inputs"].values() if request["provider"] != "snowglobe"}
1057 definitions = {name: load(name, properties) for name in names}
1058 destroy_stage(args.name, metadata, definitions)
1059 return
1060 if args.mode == "stage":
1061 if not args.name:
1062 parser.error("stage requires a service name")
1063 token()
1064 data = load(args.name, properties)
1065 check_staging_pool(data)
1066 definitions = {args.name: data}
1067 definitions.update({provider: load(provider, properties) for provider in dependencies(data)})
1068 if not data["containers"]:
1069 raise ValueError(f"service has no container to stage: {args.name}")
1070 stage_dir = STATE / "stages"
1071 previous = []
1072 for path in stage_dir.glob("*.json"):
1073 saved = json.loads(path.read_text())
1074 if saved.get("sourceId") == args.name:
1075 previous.append((path, saved))
1076 if len(previous) > 1:
1077 raise ValueError(f"multiple stages exist for {args.name}; destroy one first")
1078 created = not previous
1079 stage = f"{args.name}-preview-{secrets.token_hex(4)}" if created else previous[0][0].stem
1080 http = [task["http"] for task in data["containers"].values() if task.get("http") and task["http"].get("hostname")]
1081 if len(http) > 1:
1082 raise ValueError("preview requires at most one HTTP route")
1083 original_host = http[0].get("hostname") if http else None
1084 hostname = stage + "." + original_host.split(".", 1)[1] if original_host else None
1085 data = load(args.name, properties, stage)
1086 data["rollout"] = "simple"
1087 data["hostRoot"] = str(Path(data["stagingRoot"]) / stage)
1088 if data["stageIsolation"] == "fresh" and any(
1089 volume.get("src") and not volume["readOnly"]
1090 for task in data["containers"].values()
1091 for volume in task["volumes"].values()
1092 ):
1093 raise ValueError("fresh stages cannot use writable external mounts")
1094 for task in data["containers"].values():
1095 if task.get("tcp") and not task["hostNetwork"]:
1096 for port in task["tcp"]:
1097 port["hostPort"] = None
1098 if hostname:
1099 hosts = {original_host: hostname, **{host: stage + "-" + host for host in http[0]["plainHostnames"]}}
1100 for task in data["containers"].values():
1101 if task.get("http") and task["http"].get("hostname") == original_host:
1102 task["http"]["hostname"] = hostname
1103 task["http"]["plainHostnames"] = [hosts[host] for host in task["http"]["plainHostnames"]]
1104 for source, target in hosts.items():
1105 task["env"] = {key: value.replace(source, target) for key, value in task["env"].items()}
1106 if task.get("secretFiles"):
1107 task["secretFiles"] = {key: value.replace(source, target) for key, value in task["secretFiles"].items()}
1108 for request in data["inputs"].values():
1109 if request["provider"] == "snowglobe":
1110 request["redirectUris"] = [uri.replace(original_host, hostname) for uri in request["redirectUris"]]
1111 for assignment in args.env:
1112 key, separator, value = assignment.partition("=")
1113 if not separator or len(data["containers"]) != 1:
1114 parser.error(f"unknown environment override: {key}")
1115 env = next(iter(data["containers"].values()))["env"]
1116 if key not in env:
1117 parser.error(f"unknown environment override: {key}")
1118 env[key] = value
1119 metadata = (
1120 {"mount": data["hostRoot"], "inputs": data["inputs"],
1121 "tasks": list(data["containers"]), "sourceId": args.name,
1122 "stageIsolation": data["stageIsolation"]}
1123 if created else previous[0][1]
1124 )
1125 if not created:
1126 if metadata.get("stageIsolation", "clone") != data["stageIsolation"]:
1127 raise ValueError("stage isolation changed; destroy the stage before recreating it")
1128 if bool(metadata.get("clone")) != data["hasManagedVolumes"]:
1129 raise ValueError("storage layout changed; destroy the stage before recreating it")
1130 for alias, request in data["inputs"].items():
1131 if alias in metadata["inputs"] and metadata["inputs"][alias] != request:
1132 raise ValueError(f"requirement {alias} changed; destroy the stage before recreating it")
1133 if alias not in metadata["inputs"] and request["provider"] == "postgres":
1134 raise ValueError("new database requirement needs a new stage")
1135 metadata["inputs"].update(data["inputs"])
1136 metadata["tasks"] = sorted(set(metadata["tasks"]) | set(data["containers"]))
1137 stage_dir.mkdir(parents=True, exist_ok=True)
1138 postgres_snapshot = None
1139 pending_snapshots = set()
1140 try:
1141 postgres_inputs = created and data["stageIsolation"] == "clone" and any(
1142 request["provider"] == "postgres" and request["kind"] == "database"
1143 for request in data["inputs"].values()
1144 )
1145 snapshots = []
1146 source = None
1147 if created and data["hasManagedVolumes"]:
1148 pool = data["pool"]
1149 source = subprocess.run(
1150 ["findmnt", "-n", "-o", "SOURCE", "--mountpoint", definitions[args.name]["hostRoot"]],
1151 capture_output=True, text=True,
1152 ).stdout.strip()
1153 dataset = pool + "/staging/" + stage
1154 if subprocess.run(["zfs", "list", pool + "/staging"], capture_output=True).returncode:
1155 command("zfs", "create", "-o", "mountpoint=none", pool + "/staging")
1156 if source and data["stageIsolation"] == "clone":
1157 if source.split("/", 1)[0] != pool:
1158 raise ValueError(f"production dataset belongs to another pool: {source}")
1159 snapshot = source + "@" + stage
1160 snapshots.append(snapshot)
1161 if postgres_inputs:
1162 postgres_dataset = dataset_for("postgres")
1163 if not postgres_dataset:
1164 raise ValueError("Postgres needs a ZFS dataset for consistent stages")
1165 postgres_snapshot = postgres_dataset + "@" + stage
1166 snapshots.append(postgres_snapshot)
1167 external = {}
1168 for task in data["containers"].values():
1169 for volume in task["volumes"].values():
1170 if volume.get("src") and not volume["readOnly"]:
1171 external.setdefault(volume["src"], []).append(volume)
1172 external_mounts = {}
1173 for external_source in external:
1174 path = Path(external_source).resolve(strict=True)
1175 mount = json.loads(command(
1176 "findmnt", "--json", "-o", "SOURCE,TARGET,FSTYPE,OPTIONS", "--target", str(path), capture=True,
1177 ).stdout)["filesystems"][0]
1178 if "ro" not in mount["options"].split(",") and mount["fstype"] != "zfs":
1179 raise ValueError(f"writable external mount is not ZFS: {external_source}")
1180 external_mounts[external_source] = (path, mount)
1181 if created and mount["fstype"] == "zfs" and "ro" not in mount["options"].split(","):
1182 target = mount["source"] + "@" + stage
1183 if target not in snapshots:
1184 snapshots.append(target)
1185 if snapshots:
1186 if len({target.split("/", 1)[0] for target in snapshots}) != 1:
1187 raise ValueError("staged datasets must belong to one ZFS pool")
1188 command("zfs", "snapshot", *snapshots)
1189 pending_snapshots.update(snapshots)
1190 if created and data["hasManagedVolumes"]:
1191 if source and data["stageIsolation"] == "clone":
1192 try:
1193 clone_dataset(source, snapshot, dataset, data["hostRoot"])
1194 except Exception:
1195 command("zfs", "destroy", snapshot)
1196 pending_snapshots.remove(snapshot)
1197 raise
1198 metadata["snapshot"] = snapshot
1199 pending_snapshots.remove(snapshot)
1200 else:
1201 command("zfs", "create", "-o", "mountpoint=" + data["hostRoot"], dataset)
1202 metadata["clone"] = dataset
1203 bindings = {}
1204 for source, volumes in sorted(external.items()):
1205 path, mount = external_mounts[source]
1206 if "ro" in mount["options"].split(","):
1207 binding = {"src": source, "readOnly": True}
1208 elif mount["fstype"] == "zfs":
1209 dataset = mount["source"]
1210 if metadata.get("snapshot") == dataset + "@" + stage:
1211 clone_mount = data["hostRoot"]
1212 else:
1213 staged = metadata.setdefault("external", {})
1214 if dataset not in staged:
1215 if not created:
1216 raise ValueError("external storage changed; destroy the stage before recreating it")
1217 suffix = hashlib.sha256(dataset.encode()).hexdigest()[:8]
1218 pool = dataset.split("/", 1)[0]
1219 clone = pool + "/staging/" + stage + "-external-" + suffix
1220 clone_mount = str(Path(data["stagingRoot"]) / (stage + "-external-" + suffix))
1221 snapshot = dataset + "@" + stage
1222 if subprocess.run(["zfs", "list", pool + "/staging"], capture_output=True).returncode:
1223 command("zfs", "create", "-o", "mountpoint=none", pool + "/staging")
1224 try:
1225 clone_dataset(dataset, snapshot, clone, clone_mount)
1226 except Exception:
1227 command("zfs", "destroy", snapshot)
1228 pending_snapshots.remove(snapshot)
1229 raise
1230 staged[dataset] = {"clone": clone, "snapshot": snapshot, "mount": clone_mount}
1231 pending_snapshots.remove(snapshot)
1232 clone_mount = staged[dataset]["mount"]
1233 relative = path.relative_to(Path(mount["target"]).resolve())
1234 binding = {"src": str(Path(clone_mount) / relative), "readOnly": False}
1235 else:
1236 raise ValueError(f"writable external mount is not ZFS: {source}")
1237 bindings[source] = binding
1238 for volume in volumes:
1239 if path.is_relative_to(Path(data["cloverRoot"]).resolve()):
1240 volume["clover"] = True
1241 volume.update(binding)
1242 if not created and bindings != metadata.get("externalSources", {}):
1243 raise ValueError("external storage changed; destroy the stage before recreating it")
1244 metadata["externalSources"] = bindings
1245 if REPO.parent == Path("/opt/snowglobe/releases").resolve():
1246 metadata["release"] = REPO.name
1247 metadata["ready"] = False
1248 write_private(stage_dir / f"{stage}.json", json.dumps(metadata))
1249 bootstrap([data])
1250 if created and data["stageIsolation"] == "clone" and (data["secrets"] or data["requiredSecrets"]):
1251 source = get_variable("nomad/jobs/" + args.name)
1252 if source:
1253 put_variable("nomad/jobs/" + stage, source["Items"], 0)
1254 if postgres_snapshot:
1255 postgres_clone = postgres_dataset.rsplit("/prod/", 1)[0] + "/staging/" + stage + "-postgres"
1256 postgres_mount = Path(data["stagingRoot"]) / (stage + "-postgres")
1257 source_context = cloned_postgres(postgres_snapshot, postgres_clone, postgres_mount)
1258 else:
1259 source_context = nullcontext(None)
1260 with source_context as postgres_source:
1261 provision_inputs(data, definitions, stage, postgres_source)
1262 provision(data)
1263 prepare(data)
1264 build_images(data)
1265 submit(data, "run", definitions)
1266 except Exception:
1267 if created:
1268 destroy_stage(stage, metadata, definitions)
1269 raise
1270 finally:
1271 for snapshot in sorted(pending_snapshots):
1272 command("zfs", "destroy", snapshot)
1273 if hostname:
1274 check_http(hostname, http[0]["checkPath"], http[0]["tlsInternal"])
1275 configure(data)
1276 if REPO.parent == Path("/opt/snowglobe/releases").resolve():
1277 metadata = {**json.loads((stage_dir / f"{stage}.json").read_text()), **metadata}
1278 metadata["ready"] = True
1279 metadata["overrides"] = [assignment.partition("=")[0] for assignment in args.env]
1280 write_private(stage_dir / f"{stage}.json", json.dumps(metadata))
1281 print(f"stage={stage}\nrelease={metadata.get('release', '')}\nhost={hostname}\ndataset={metadata.get('clone', '')}")
1282 return
1283 definitions = {name: load(name, properties) for name in services()}
1284 if args.name and args.name not in definitions:
1285 raise ValueError(f"unknown service: {args.name}")
1286 if not args.name and args.mode == "deploy":
1287 names = [name for name in names if definitions[name]["containers"]]
1288 selected = set(names)
1289 while True:
1290 required = selected | set().union(*(dependencies(definitions[name]) for name in selected))
1291 missing = required - definitions.keys()
1292 if missing:
1293 raise ValueError(f"unknown dependency: {sorted(missing)}")
1294 if required == selected:
1295 break
1296 selected = required
1297 data = ordered([definitions[name] for name in sorted(selected)])
1298 if args.mode == "render":
1299 for item in data:
1300 if item["containers"]:
1301 print(render(item, definitions))
1302 elif args.mode == "validate":
1303 token()
1304 for item in data:
1305 submit(item, "validate", definitions)
1306 elif args.mode == "check":
1307 holder = gpu_holder(data)
1308 for item in data:
1309 if gpu(item) and item["id"] != holder:
1310 continue
1311 for task in item["containers"].values():
1312 if task.get("http") and task["http"].get("hostname"):
1313 check_http(task["http"]["hostname"], task["http"]["checkPath"], task["http"]["tlsInternal"])
1314 elif args.mode == "preflight":
1315 check_pool(data)
1316 token()
1317 missing_secrets = {}
1318 for item in data:
1319 if item["containers"] and item["requiredSecrets"]:
1320 variable = get_variable("nomad/jobs/" + item["id"])
1321 values = variable["Items"] if variable else {}
1322 missing = [name for name in item["requiredSecrets"] if not values.get(name)]
1323 if missing:
1324 missing_secrets[item["id"]] = missing
1325 if missing_secrets:
1326 raise ValueError("missing required secrets: " + "; ".join(
1327 f"{name}: {', '.join(keys)}" for name, keys in missing_secrets.items()))
1328 elif args.mode == "pool":
1329 ensure_pool(data)
1330 elif args.mode == "allocate":
1331 ensure_pool(data)
1332 bootstrap(data)
1333 for item in data:
1334 provision_inputs(item, definitions)
1335 provision(item)
1336 prepare(item)
1337 build_images(item)
1338 elif args.mode == "bootstrap":
1339 bootstrap(data)
1340 elif args.mode == "deploy":
1341 bootstrap(data)
1342 holder = gpu_holder(data)
1343 if args.name and gpu(definitions[args.name]) and holder not in {None, args.name}:
1344 raise ValueError(f"{holder} has the GPU. Switch the GPU to {args.name} from the dashboard.")
1345 for item in data:
1346 # Deploys never move the GPU: only its holder runs, or the named service while nothing has it.
1347 stopped = gpu(item) and item["id"] != (holder or args.name)
1348 provision_inputs(item, definitions)
1349 provision(item)
1350 prepare(item)
1351 if stopped:
1352 print(f"Registering {item['id']} stopped while {holder or 'nothing'} has the GPU", flush=True)
1353 submit(item, "run", definitions, stopped=True)
1354 continue
1355 build_images(item)
1356 submit(item, "run", definitions)
1357 configure(item)
1358
1359
1360if __name__ == "__main__":
1361 try:
1362 main()
1363 except (OSError, RuntimeError, ValueError, subprocess.CalledProcessError) as error:
1364 print(error, file=sys.stderr)
1365 sys.exit(1)