1#!/usr/bin/env python3
2import fcntl
3import json
4import os
5from pathlib import Path
6import re
7import selectors
8import secrets
9import signal
10import stat
11import subprocess
12import sys
13import time
14import uuid
15import urllib.error
16import urllib.request
17
18import release
19
20
21FIELDS = {
22 "deploy.current": set(), "deploy.main": set(), "deploy.history": set(), "deploy.stages": set(), "deploy.managed": set(),
23 "deploy.release": {"release"}, "deploy.output": {"kind", "target"},
24 "deploy.last": set(), "deploy.run": {"id"}, "deploy.start": {"action", "target"},
25 "deploy.secret.get": {"service", "key"}, "deploy.secret.set": {"service", "key", "value"},
26 "deploy.secret.rotate": {"service", "key"},
27}
28ACTIONS = {"deploy", "destroy", "rollback", "start", "stop", "restart", "secret-set", "secret-rotate", "gpu"}
29MAX_LOG = 1024 * 1024
30MAX_METADATA = 65536
31HOST_STATE = Path(os.environ.get("SNOWGLOBE_HOST_STATE_ROOT", "/var/lib/snowglobe/host"))
32
33
34class Error(Exception):
35 def __init__(self, status, message):
36 super().__init__(message)
37 self.status = status
38
39
40def read(path, limit=MAX_METADATA, missing=None):
41 try:
42 fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
43 except FileNotFoundError:
44 return missing
45 with os.fdopen(fd, "rb") as source:
46 if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
47 raise ValueError("deployment state must be a regular file")
48 data = source.read(limit + 1)
49 if len(data) > limit:
50 raise ValueError("deployment state is too large")
51 return data.decode(errors="replace")
52
53
54def history():
55 entries = json.loads(read(release.HISTORY, missing="[]"))
56 if not isinstance(entries, list) or any(not isinstance(entry, dict) for entry in entries):
57 raise ValueError("invalid deployment history")
58 return entries
59
60
61def managed():
62 jobs = json.loads(read(release.STATE / "managed-jobs.json", missing="[]"))
63 if not isinstance(jobs, list) or any(not isinstance(job, str) or not release.STAGE_ID.fullmatch(job) for job in jobs):
64 raise ValueError("invalid managed job list")
65 return jobs
66
67
68def service(target, key=None):
69 if not isinstance(target, str) or not release.STAGE_ID.fullmatch(target):
70 raise Error(400, "Choose a service from the list.")
71 if target not in managed():
72 raise Error(404, "That service is no longer managed. Reload services.")
73 if key is not None and (not isinstance(key, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,127}", key)):
74 raise Error(400, "Choose a secret from this service's list.")
75
76
77def nomad(path, method="GET", body=None, timeout=10):
78 token = read(release.STATE / "nomad.token", missing="").strip()
79 if not token:
80 raise Error(503, "Nomad credentials are unavailable. Check the host service configuration.")
81 request = urllib.request.Request("http://127.0.0.1:4646/v1/" + path, method=method,
82 data=json.dumps(body).encode() if body is not None else None,
83 headers={"X-Nomad-Token": token, "Content-Type": "application/json"})
84 try:
85 with urllib.request.urlopen(request, timeout=timeout) as response:
86 data = response.read(MAX_LOG + 1)
87 except urllib.error.HTTPError as error:
88 if error.code == 404 and method == "GET":
89 return None
90 if error.code == 409:
91 raise Error(409, "The secret changed during this update. Reload it before retrying.") from None
92 raise Error(502, "Nomad refused the secret request. Check its service logs.") from None
93 if len(data) > MAX_LOG:
94 raise Error(502, "The secret response is too large. Check the service configuration.")
95 return json.loads(data)
96
97
98def secret(action, target, key, value=None):
99 service(target, key)
100 job = nomad("job/" + target)
101 specs = json.loads((job or {}).get("Meta", {}).get("snowglobe_secrets", "[]"))
102 if not isinstance(specs, list):
103 raise Error(502, "The service's secret names couldn't be read. Deploy its current release again.")
104 matches = [spec for spec in specs if isinstance(spec, dict) and spec.get("name") == key]
105 if len(matches) != 1:
106 raise Error(404, "That secret is unavailable. Reload the service's secret list.")
107 path = "nomad/jobs/" + target
108 existing = nomad("var/" + path)
109 items = dict(existing["Items"]) if existing else {}
110 if action == "get":
111 if key not in items:
112 raise Error(404, "That secret has no value. Set it from the service page.")
113 return items[key]
114 if action == "rotate":
115 count = matches[0].get("bytes")
116 if matches[0].get("generated") is not True or type(count) is not int or not 1 <= count <= 4096:
117 raise Error(409, "This secret comes from outside the server. Set it instead of generating it.")
118 value = secrets.token_hex(count)
119 if not isinstance(value, str) or not value or len(value.encode()) > 8192 or any(c in value for c in "\r\n\0"):
120 raise Error(400, "Enter a single-line secret under 8 KiB.")
121 items[key] = value
122 nomad("var/" + path + "?cas=" + str(existing["ModifyIndex"] if existing else 0), "PUT",
123 {"Namespace": "default", "Path": path, "Items": items})
124 restarted = subprocess.run(["nomad", "job", "restart", "-yes", target], capture_output=True, text=True, timeout=55,
125 env={**os.environ, "NOMAD_TOKEN": read(release.STATE / "nomad.token").strip()})
126 if restarted.returncode:
127 raise Error(502, "The secret was saved, but the service couldn't restart. Check its run before retrying.")
128 print("Updated " + target + "/" + key, flush=True)
129
130
131def stage(target):
132 if not isinstance(target, str) or not release.STAGE_ID.fullmatch(target):
133 raise Error(400, "Choose a stage from the list.")
134 text = read(release.STATE / "stages" / (target + ".json"))
135 if text is None:
136 raise Error(404, "That stage is no longer available. Reload deploys.")
137 return json.loads(text)
138
139
140def entry(target):
141 if not isinstance(target, str) or not re.fullmatch(r"[1-9][0-9]{0,9}", target):
142 raise Error(400, "Choose a deployment from history.")
143 entries = history()
144 if int(target) > len(entries):
145 raise Error(404, "That deployment is outside history. Reload deploys.")
146 return entries[int(target) - 1]
147
148
149def command(action, target, key=None):
150 if not isinstance(action, str) or action not in ACTIONS:
151 raise Error(400, "Choose a supported deployment action.")
152 if action in {"start", "stop", "restart", "secret-set", "secret-rotate"}:
153 service(target, key)
154 if action.startswith("secret-"):
155 if key is None:
156 raise Error(400, "Choose a secret from this service's list.")
157 return [sys.executable, str(Path(__file__)), "--secret", action.removeprefix("secret-"), target, key]
158 if action in {"stop", "restart"}:
159 return ["nomad", "job", action, "-yes", target]
160 version = release.current_release()
161 if version is None:
162 raise Error(409, "No release is running. Deploy a release before starting this service.")
163 return [sys.executable, str(release.check_release(version) / "tools/snowglobe.py"), "deploy", target]
164 if action == "gpu":
165 if not isinstance(target, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", target):
166 raise Error(400, "Choose games or a service that uses the GPU.")
167 return [sys.executable, str(Path(__file__).with_name("vms.py")), "gpu", target]
168 if action == "rollback":
169 saved = entry(target)
170 version = saved["release"]
171 release.check_release(version)
172 return [sys.executable, str(Path(__file__).with_name("release.py")), "rollback", version]
173 if action == "deploy":
174 candidate = release.main_release()
175 if not candidate or target != candidate["release"]:
176 raise Error(409, "Main changed or isn't uploaded. Reload deploys before deploying.")
177 release.check_release(target)
178 return [sys.executable, str(Path(__file__).with_name("release.py")), "deploy", target]
179 metadata = stage(target)
180 version = metadata.get("release")
181 if not isinstance(version, str):
182 raise Error(409, "This stage has no release. Stage it again.")
183 root = release.check_release(version)
184 return [sys.executable, str(root / "tools/snowglobe.py"), "destroy", target]
185
186
187def last():
188 text = read(HOST_STATE / "last-run.json")
189 if text is None:
190 return None
191 return json.loads(text)
192
193
194def run(identity):
195 if not isinstance(identity, str) or not re.fullmatch(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", identity):
196 raise Error(400, "Choose a deployment run from the list.")
197 root = HOST_STATE / "runs"
198 text = read(root / (identity + ".log"), MAX_LOG + 4096)
199 if text is None:
200 legacy = read(release.STATE / "runs" / (identity + ".log"), MAX_LOG)
201 if legacy is not None:
202 root, text = release.STATE / "runs", legacy
203 latest = last()
204 if text is None and (not latest or latest.get("id") != identity):
205 raise Error(404, "That run is no longer available.")
206 code = read(root / (identity + ".exit"), 64)
207 if code is None:
208 shown = subprocess.run(["systemctl", "show", "--property=ActiveState,ExecMainStatus,LoadState", "snowglobe-run-" + identity],
209 capture_output=True, text=True, timeout=5)
210 state = dict(line.split("=", 1) for line in shown.stdout.splitlines() if "=" in line)
211 if shown.returncode and state.get("LoadState") != "not-found":
212 shown.check_returncode()
213 if state.get("ActiveState") not in {"active", "activating", "deactivating"}:
214 code = read(root / (identity + ".exit"), 64)
215 if code is None:
216 code = int(state.get("ExecMainStatus", 0)) or 1
217 return {"lines": [line for line in (text or "").splitlines() if line], "code": int(code) if code is not None else None}
218
219
220def start(action, target, key=None, value=None):
221 if action == "secret-set" and (not isinstance(value, str) or not value or len(value.encode()) > 8192 or any(c in value for c in "\r\n\0")):
222 raise Error(400, "Enter a single-line secret under 8 KiB.")
223 HOST_STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
224 with (HOST_STATE / "run.lock").open("a") as lock:
225 fcntl.flock(lock, fcntl.LOCK_EX)
226 previous = last()
227 if previous and run(previous["id"])["code"] is None:
228 raise Error(409, "A deployment is running. Wait for it to finish, then retry.")
229 command(action, target, key)
230 identity = str(uuid.uuid4())
231 metadata = {"id": identity, "action": action, "target": target}
232 if key is not None:
233 metadata["key"] = key
234 root = HOST_STATE / "runs"
235 root.mkdir(mode=0o700, parents=True, exist_ok=True)
236 input_file = root / (identity + ".input")
237 try:
238 if action == "secret-set":
239 with os.fdopen(os.open(input_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as source:
240 source.write(value)
241 pending = HOST_STATE / "last-run.pending"
242 pending.write_text(json.dumps(metadata) + "\n")
243 pending.replace(HOST_STATE / "last-run.json")
244 args = ["systemd-run", "--unit=snowglobe-run-" + identity, "--collect", "--quiet",
245 "--property=RuntimeMaxSec=3600", "--property=TimeoutStopSec=10",
246 "--property=MemoryMax=4G", "--property=TasksMax=1024", "--property=CPUWeight=10"]
247 args.extend("--setenv=" + key + "=" + value for key, value in os.environ.items() if key == "PATH" or key.startswith("SNOWGLOBE_"))
248 subprocess.run([*args, "--", sys.executable, str(Path(__file__)), identity, action, target, *([key] if key is not None else [])],
249 check=True, capture_output=True, timeout=10)
250 except BaseException:
251 input_file.unlink(missing_ok=True)
252 raise
253 return metadata
254
255
256def handle(request):
257 operation = request["operation"]
258 if operation == "deploy.secret.get":
259 if not isinstance(request["key"], str):
260 raise Error(400, "Choose a secret from this service's list.")
261 service(request["service"], request["key"])
262 process = subprocess.run(["systemd-run", "--pipe", "--wait", "--collect", "--quiet",
263 "--unit=snowglobe-secret-read-" + str(uuid.uuid4()), "--property=RuntimeMaxSec=25",
264 "--property=MemoryMax=128M", "--property=TasksMax=8", "--property=ProtectSystem=strict",
265 "--property=ProtectHome=yes", "--property=NoNewPrivileges=yes", "--property=CapabilityBoundingSet=",
266 "--property=RestrictAddressFamilies=AF_INET AF_UNIX", "--property=IPAddressDeny=any",
267 "--property=IPAddressAllow=localhost", "--", sys.executable,
268 str(Path(__file__)), "--secret", "get", request["service"], request["key"]],
269 capture_output=True, text=True, timeout=30, check=True)
270 response = json.loads(process.stdout)
271 if "error" in response:
272 raise Error(response["status"], response["error"])
273 return response["value"]
274 if operation in {"deploy.secret.set", "deploy.secret.rotate"}:
275 return start("secret-" + operation.rpartition(".")[2], request["service"], request["key"], request.get("value"))
276 if operation == "deploy.current":
277 return release.current_release()
278 if operation == "deploy.main":
279 return release.main_release()
280 if operation == "deploy.history":
281 return history()
282 if operation == "deploy.managed":
283 return managed()
284 if operation == "deploy.stages":
285 values = []
286 for path in (release.STATE / "stages").glob("*.json"):
287 metadata = stage(path.stem)
288 values.append({"id": path.stem, "service": metadata["sourceId"], "release": metadata.get("release"),
289 "ready": metadata.get("ready", True), "created": path.stat().st_mtime,
290 "overrides": [value.partition("=")[0] for value in metadata.get("overrides", [])],
291 "clone": metadata.get("clone"), "mount": metadata.get("mount")})
292 return values
293 if operation == "deploy.release":
294 version = request["release"]
295 if not isinstance(version, str) or not release.RELEASE_ID.fullmatch(version):
296 raise Error(400, "Choose a release from deployment history.")
297 root = release.RELEASES / version / "service"
298 if root.parent.is_symlink():
299 raise ValueError("release directory is a symlink")
300 if not root.is_dir():
301 return None
302 values = {}
303 for path in root.iterdir():
304 if path.is_symlink():
305 raise ValueError("release service directory is a symlink")
306 if path.is_dir():
307 text = read(path / "service.pkl")
308 if text is not None:
309 values[path.name] = text
310 return values
311 if operation == "deploy.output":
312 kind, target = request["kind"], request["target"]
313 if kind == "stages":
314 value = stage(target)
315 elif kind == "history":
316 value = entry(target)
317 else:
318 raise Error(400, "Choose a stage or deployment from history.")
319 found = []
320 for path in (release.STATE / "runs").glob("*.log"):
321 name = path.name
322 if kind == "stages":
323 if not name.endswith("-stage-" + value["sourceId"] + ".log"):
324 continue
325 text = read(path, MAX_LOG)
326 if "stage=" + target in text.splitlines():
327 found.append((name, 0, text))
328 else:
329 source, version = value["source"], value["release"]
330 selected = name.endswith(("-prod-" + source + ".log", "-prod-" + version + ".log", "-rollback-" + version + ".log"))
331 if not selected and not re.fullmatch(r"[0-9a-f-]{36}\.log", name):
332 continue
333 delta = abs(path.stat().st_mtime - value["time"])
334 if delta >= 600:
335 continue
336 text = read(path, MAX_LOG)
337 first = next(iter(text.splitlines()), "")
338 if selected or first.endswith(" deploy " + version) or first.endswith(" promote " + source) or first.endswith(" rollback " + version):
339 found.append((name, delta, text))
340 if kind == "history":
341 for path in (HOST_STATE / "runs").glob("*.log"):
342 delta = abs(path.stat().st_mtime - value["time"])
343 if delta >= 600:
344 continue
345 text = read(path, MAX_LOG + 4096)
346 first = next(iter(text.splitlines()), "")
347 if first.endswith(" deploy " + value["release"]) or first.endswith(" promote " + value["source"]) or first.endswith(" rollback " + value["release"]):
348 found.append((path.name, delta, text))
349 found.sort(key=lambda item: item[0] if kind == "stages" else item[1], reverse=kind == "stages")
350 return [line for line in found[0][2].splitlines() if line] if found else None
351 if operation == "deploy.last":
352 value = last()
353 return {**value, "code": run(value["id"])["code"]} if value else None
354 if operation == "deploy.run":
355 return run(request["id"])
356 return start(request["action"], request["target"])
357
358
359def worker(identity, action, target, key=None):
360 if not re.fullmatch(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}", identity):
361 raise ValueError("incorrect deployment run ID")
362 saved = last()
363 expected = {"id": identity, "action": action, "target": target}
364 if key is not None:
365 expected["key"] = key
366 if saved != expected:
367 raise ValueError("deployment run is outside host state")
368 root = HOST_STATE / "runs"
369 root.mkdir(mode=0o700, parents=True, exist_ok=True)
370 os.umask(0o077)
371 code = 1
372 def interrupted(signum, frame):
373 raise RuntimeError("Deployment stopped before completion.")
374 signal.signal(signal.SIGTERM, interrupted)
375 with (root / (identity + ".log")).open("xb", buffering=0) as output:
376 try:
377 argv = command(action, target, key)
378 output.write(("$ " + " ".join(argv) + "\n").encode())
379 environment = None
380 if action in {"stop", "restart"}:
381 environment = {**os.environ, "NOMAD_TOKEN": read(release.STATE / "nomad.token", missing="").strip()}
382 if not environment["NOMAD_TOKEN"]:
383 raise RuntimeError("Nomad credentials are unavailable. Check the host service configuration.")
384 input_file = root / (identity + ".input")
385 with subprocess.Popen(argv, stdin=subprocess.PIPE if action == "secret-set" else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
386 start_new_session=True, env=environment) as process:
387 try:
388 if action == "secret-set":
389 process.stdin.write(read(input_file, 8192).encode())
390 process.stdin.close()
391 input_file.unlink()
392 total = 0
393 deadline = time.monotonic() + 3500
394 with selectors.DefaultSelector() as selector:
395 selector.register(process.stdout, selectors.EVENT_READ)
396 while selector.get_map():
397 remaining = deadline - time.monotonic()
398 if remaining <= 0:
399 raise TimeoutError("Deployment exceeded its time limit.")
400 for key, _ in selector.select(remaining):
401 chunk = os.read(key.fd, 65536)
402 if not chunk:
403 selector.unregister(key.fileobj)
404 continue
405 total += len(chunk)
406 if total > MAX_LOG:
407 raise RuntimeError("Deployment output exceeded its size limit.")
408 output.write(chunk)
409 code = process.wait(timeout=max(.001, deadline - time.monotonic()))
410 except BaseException:
411 try:
412 os.killpg(process.pid, signal.SIGKILL)
413 except ProcessLookupError:
414 pass
415 raise
416 except Exception as error:
417 output.write((str(error) + "\n").encode())
418 finally:
419 (root / (identity + ".input")).unlink(missing_ok=True)
420 output.write(("exit " + str(code) + "\n").encode())
421 pending = root / (identity + ".exit.tmp")
422 pending.write_text(str(code))
423 pending.replace(root / (identity + ".exit"))
424 return code
425
426
427if __name__ == "__main__":
428 if len(sys.argv) == 5 and sys.argv[1] == "--secret" and sys.argv[2] in {"get", "set", "rotate"}:
429 action, target, key = sys.argv[2:]
430 try:
431 result = secret(action, target, key, sys.stdin.read(8193) if action == "set" else None)
432 except Error as error:
433 if action != "get":
434 raise SystemExit(str(error))
435 result = {"error": str(error), "status": error.status}
436 else:
437 result = {"value": result}
438 if action == "get":
439 print(json.dumps(result))
440 raise SystemExit(0)
441 if len(sys.argv) not in {4, 5}:
442 raise SystemExit("Expected a run ID, action, and target")
443 raise SystemExit(worker(*sys.argv[1:]))