1#!/usr/bin/env python3
2import concurrent.futures
3import contextlib
4import fcntl
5import importlib.util
6import json
7import math
8import os
9from pathlib import Path
10import pwd
11import re
12import selectors
13import select
14import stat
15import signal
16import socket
17import struct
18import subprocess
19import threading
20import time
21import vms
22import tty
23
24spec = importlib.util.spec_from_file_location("copyparty", Path(__file__).resolve().parent.parent / "service/copyparty/manage.py")
25copyparty = importlib.util.module_from_spec(spec)
26spec.loader.exec_module(copyparty)
27
28
29dashboard_runs = importlib.import_module("dashboard-run")
30shale_labels = importlib.import_module("shale-labels")
31
32
33FIELDS = (
34 "name", "used", "usedbydataset", "usedbysnapshots", "referenced", "available",
35 "compressratio", "logicalused", "compression", "recordsize", "mountpoint",
36 "quota", "origin", "mounted",
37)
38TEXT_FIELDS = {"name", "compression", "mountpoint", "origin", "mounted"}
39PROTOCOL = json.loads((Path(__file__).resolve().parent.parent / "dashboard/src/host-protocol.json").read_text())
40MAX_REQUEST = PROTOCOL['request']
41MAX_RESPONSE = PROTOCOL['response']
42WORKERS = 12
43CONNECTIONS = WORKERS + 4
44WORK_SLOTS = threading.BoundedSemaphore(WORKERS)
45STREAM_SLOTS = threading.BoundedSemaphore(4)
46GUEST_SLOTS = threading.BoundedSemaphore(4)
47VM_PREPARATION_SLOT = threading.BoundedSemaphore(1)
48INDEX_SNAPSHOT = r"index-[0-9]+(?:-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})?"
49
50
51class Rejected(Exception):
52 pass
53
54
55class Host:
56 def __init__(self, pool):
57 if not re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_.:-]*", pool):
58 raise ValueError("incorrect storage pool")
59 self.pool = pool
60 self.containers = None
61 self.inventory_lock = threading.Lock()
62
63 def dataset(self, value):
64 if (not isinstance(value, str) or len(value) > 255
65 or not re.fullmatch(r"[\w.: ][\w.: -]*(/[\w.: -]+)*", value)
66 or any(part in {".", ".."} for part in value.split("/"))
67 or not (value == self.pool or value.startswith(self.pool + "/"))):
68 raise Rejected("Choose a dataset from this storage pool.")
69 return value
70
71 def snapshot(self, value):
72 if (not isinstance(value, str) or len(value) > 255
73 or not re.fullmatch(r"[\w.: ][\w.: -]*", value)
74 or value in {".", ".."}):
75 raise Rejected("Choose a snapshot from the list.")
76 return value
77
78 def handle(self, request, *, active_snapshot=None):
79 if not isinstance(request, dict):
80 raise Rejected("Choose a supported host operation.")
81 operation = request.get("operation")
82 parameters = {
83 "storage.datasets": set(),
84 "storage.pool": set(),
85 "storage.mounts": set(),
86 "storage.snapshots": {"dataset"},
87 "storage.reclaim": {"dataset", "from", "to"},
88 "storage.destroy": {"dataset", "from", "to"},
89 "storage.removed": {"dataset", "snapshot"},
90 "files.snapshot": {"datasets"},
91 "files.snapshots": {"datasets"},
92 "files.discard": {"dataset", "snapshot"},
93 "index.snapshot": {"dataset"},
94 "index.snapshots": {"dataset"},
95 "index.diff": {"dataset", "from", "to"},
96 "index.discard": {"dataset", "snapshot"},
97 "shale.metadata": {"repository", "accounts"},
98 "shale.write": {"grant", "repository", "action", "arguments"},
99 "host.sample": set(),
100 "host.usage": {"refresh"},
101 "copyparty.manage": {"action", "payload", "users"},
102 "vm.ai": {"payload"},
103 **dashboard_runs.FIELDS,
104 **{"vm." + action: set() if fields is None else {"payload"} for action, fields in vms.ACTION_FIELDS.items()},
105 }
106 if not isinstance(operation, str) or operation not in parameters:
107 raise Rejected("Choose a supported host operation.")
108 if set(request) != parameters[operation] | {"operation"}:
109 raise Rejected("Use only the fields required by this host operation.")
110 if operation == "copyparty.manage":
111 return copyparty.handle(request)
112 if operation == "shale.metadata":
113 return shale_labels.metadata(request)
114 if operation == "shale.write":
115 return shale_labels.handle(request)
116 if operation in dashboard_runs.FIELDS:
117 return dashboard_runs.handle(request)
118 if operation == "host.sample":
119 stat = Path("/proc/stat").read_text().splitlines()
120 # Guest columns are already included in user and nice time.
121 cpu = list(map(int, stat[0].split()[1:9]))
122 total = sum(cpu)
123 memory = {line.split()[0].rstrip(":"): int(line.split()[1]) * 1024
124 for line in Path("/proc/meminfo").read_text().splitlines()}
125 arc = None
126 try:
127 arc = next(int(line.split()[-1]) for line in Path("/proc/spl/kstat/zfs/arcstats").read_text().splitlines() if line.split()[0] == "size")
128 except (OSError, StopIteration):
129 pass
130 temperature = None
131 for root in Path("/sys/class/hwmon").glob("hwmon*"):
132 try:
133 if root.joinpath("name").read_text().strip() in {"k10temp", "coretemp", "zenpower"}:
134 value = float(root.joinpath("temp1_input").read_text()) / 1000
135 if math.isfinite(value) and value > 0:
136 temperature = value
137 break
138 except (OSError, ValueError):
139 pass
140 rx, tx = 0, 0
141 for line in Path("/proc/net/dev").read_text().splitlines():
142 name, separator, values = line.partition(":")
143 if separator and name.strip().startswith(("en", "eth", "wl")):
144 values = values.split()
145 rx += int(values[0])
146 tx += int(values[8])
147 gpu = None
148 try:
149 values = [float(line) for line in command("nvidia-smi", "--query-gpu=utilization.gpu", "--format=csv,noheader,nounits", timeout=3).splitlines()]
150 values = [value for value in values if math.isfinite(value)]
151 if values:
152 gpu = sum(values) / len(values)
153 except (OSError, ValueError, subprocess.SubprocessError, TimeoutError):
154 pass
155 return {"at": time.monotonic(), "cpu": {"busy": total - cpu[3] - cpu[4], "total": total},
156 "cores": sum(bool(re.match(r"cpu[0-9]+\b", line)) for line in stat),
157 "memory": {"used": memory["MemTotal"] - memory["MemAvailable"], "total": memory["MemTotal"]},
158 "bootedAt": time.time() - float(Path("/proc/uptime").read_text().split()[0]),
159 "load": os.getloadavg()[1], "arc": arc, "temperature": temperature, "gpu": gpu,
160 "network": {"rx": rx, "tx": tx}}
161 if operation == "host.usage":
162 if type(request["refresh"]) is not bool:
163 raise Rejected("Choose whether to refresh the container list.")
164 with self.inventory_lock:
165 if request["refresh"] or not self.containers:
166 self.containers = json.loads(command("podman", "--remote", "--url", "unix:///run/podman/podman.sock", "ps", "--format", "json", timeout=10))
167 rows = []
168 for container in self.containers:
169 pid, identity = container["Pid"], container["Id"]
170 if not isinstance(pid, int) or pid <= 0 or not re.fullmatch(r"[0-9a-f]{64}", identity):
171 continue
172 try:
173 cgroup = next(line[3:] for line in Path(f"/proc/{pid}/cgroup").read_text().splitlines() if line.startswith("0::"))
174 if f"libpod-{identity}.scope" not in Path(cgroup).parts:
175 raise ValueError("container cgroup changed")
176 root = Path("/sys/fs/cgroup") / cgroup.lstrip("/")
177 cpu = next(int(line.split()[1]) for line in root.joinpath("cpu.stat").read_text().splitlines() if line.startswith("usage_usec "))
178 memory = int(root.joinpath("memory.current").read_text())
179 rows.append({"id": identity, "name": container["Names"][0], "cpu": cpu, "memory": memory})
180 except (OSError, ValueError, StopIteration):
181 self.containers = None
182 return {"at": time.monotonic(), "containers": rows}
183 if operation == "vm.ai":
184 if not VM_PREPARATION_SLOT.acquire(blocking=False):
185 raise Rejected("A test VM operation is running. Wait for it to finish.")
186 try:
187 process = subprocess.run(["python3", str(Path(__file__).with_name("vm-ai.py"))],
188 input=json.dumps(request["payload"]), capture_output=True, text=True, timeout=900)
189 if process.returncode == 2:
190 raise Rejected(process.stderr.strip())
191 process.check_returncode()
192 return json.loads(process.stdout)
193 finally:
194 VM_PREPARATION_SLOT.release()
195 if operation.startswith("vm."):
196 action = operation[3:]
197 payload = request.get("payload")
198 try:
199 vms.validate(action, payload)
200 except ValueError as error:
201 raise Rejected(str(error)) from error
202 if action == "computer":
203 try:
204 return importlib.import_module("vm-computer").handle(payload["name"], payload["request"], active_snapshot=active_snapshot)
205 except (BlockingIOError, InterruptedError) as error:
206 raise dashboard_runs.Error(409, str(error) or "Another computer operation is running. Read computer_status before retrying.") from None
207 except (TimeoutError, subprocess.TimeoutExpired):
208 raise dashboard_runs.Error(504, "The computer operation timed out. Read computer_status before retrying.") from None
209 except ValueError as error:
210 raise Rejected(str(error)) from error
211 if action == "clipboard":
212 if not vms.mac_vms.owns(payload["name"]):
213 raise Rejected("This VM does not support this guest operation.")
214 try:
215 return vms.mac_vms.handle(action, payload)
216 except ValueError as error:
217 raise Rejected(str(error)) from error
218 args = ["python3", str(Path(__file__).with_name("vms.py")), action]
219 if payload is not None:
220 args.append(json.dumps(payload))
221 try:
222 if action in {"create", "media", "preset"}:
223 if not VM_PREPARATION_SLOT.acquire(blocking=False):
224 raise Rejected("A VM image is being prepared. Wait for it to finish, then retry.")
225 try:
226 return json.loads(command(*args, timeout=900))
227 finally:
228 VM_PREPARATION_SLOT.release()
229 return json.loads(command(*args, timeout=230 if action == "act" else 60))
230 except subprocess.CalledProcessError as error:
231 if error.returncode == 2:
232 raise Rejected(error.stderr) from error
233 raise
234 if operation in {"files.snapshot", "files.snapshots"}:
235 values = request["datasets"]
236 if not isinstance(values, list) or not values:
237 raise Rejected("Choose at least one dataset.")
238 datasets = sorted({self.dataset(value) for value in values})
239 if operation == "files.snapshot":
240 name = f"dash-{time.time_ns()}"
241 command("zfs", "snapshot", *(f"{dataset}@{name}" for dataset in datasets))
242 return name
243 text = command("zfs", "list", "-H", "-t", "snapshot", "-o", "name", "-d", "1", *datasets)
244 return [name for name in text.splitlines() if re.fullmatch(r"dash-[0-9]+", name.partition("@")[2])]
245 dataset = self.dataset(request["dataset"]) if "dataset" in request else None
246 if operation.startswith("index."):
247 if operation == "index.snapshot":
248 snapshot = f"{dataset}@index-{time.time_ns()}"
249 command("zfs", "snapshot", snapshot)
250 return snapshot
251 if operation == "index.snapshots":
252 text = command("zfs", "list", "-H", "-t", "snapshot", "-o", "name", "-d", "1", dataset)
253 return [name for name in text.splitlines() if re.fullmatch(INDEX_SNAPSHOT, name.partition("@")[2])]
254 names = [request["from"], request["to"]] if operation == "index.diff" else [request["snapshot"]]
255 if any(not re.fullmatch(INDEX_SNAPSHOT, self.snapshot(name)) for name in names):
256 raise Rejected("Choose an index snapshot.")
257 snapshots = [f"{dataset}@{name}" for name in names]
258 if operation == "index.diff":
259 return command("zfs", "diff", "-FH", *snapshots)
260 command("zfs", "destroy", "-d", *snapshots)
261 return None
262 if operation == "storage.datasets":
263 text = command("zfs", "list", "-Hp", "-r", "-t", "filesystem",
264 "-o", ",".join(FIELDS), self.pool)
265 rows = []
266 for line in text.splitlines():
267 values = line.split("\t")
268 if len(values) != len(FIELDS):
269 raise ValueError("unexpected ZFS dataset response")
270 row = dict(zip(FIELDS, values))
271 for field in FIELDS:
272 if field not in TEXT_FIELDS:
273 row[field] = numeric(row[field])
274 if row.pop("mounted") != "yes" or row["mountpoint"] == "none":
275 row["mountpoint"] = None
276 if row["origin"] == "-":
277 row["origin"] = None
278 rows.append(row)
279 return rows
280 if operation == "storage.pool":
281 fields = ("size", "allocated", "free", "fragmentation")
282 summary = command("zpool", "list", "-Hp", "-o", ",".join(fields), self.pool)
283 status = json.loads(command("zpool", "status", "-jp", "--json-int", self.pool))
284 return {"summary": dict(zip(fields, map(numeric, summary.strip().split("\t")))),
285 "status": status, "name": self.pool}
286 if operation == "storage.mounts":
287 mounts = json.loads(command("findmnt", "-J", "-l", "-t", "zfs", "-o", "SOURCE,TARGET"))
288 return {"filesystems": [item for item in mounts.get("filesystems", [])
289 if "@" not in item["source"]
290 and (item["source"] == self.pool or item["source"].startswith(self.pool + "/"))]}
291 if operation == "storage.snapshots":
292 text = command("zfs", "list", "-Hp", "-t", "snapshot", "-d", "1", "-s", "creation",
293 "-o", "name,creation,used,referenced,clones", dataset)
294 rows = []
295 for line in text.splitlines():
296 name, creation, used, referenced, clones = line.split("\t")
297 rows.append({"name": name.split("@", 1)[1], "creation": numeric(creation),
298 "used": numeric(used), "referenced": numeric(referenced),
299 "clones": [] if clones == "-" else clones.split(",")})
300 return rows
301 if operation in {"storage.reclaim", "storage.destroy"}:
302 start, end = self.snapshot(request["from"]), self.snapshot(request["to"])
303 flags = ["-nvp"] if operation == "storage.reclaim" else []
304 return command("zfs", "destroy", *flags, f"{dataset}@{start}%{end}")
305 snapshot = self.snapshot(request["snapshot"])
306 if operation == "files.discard":
307 if not re.fullmatch(r"dash-[0-9]+", snapshot):
308 raise Rejected("Choose a file undo snapshot.")
309 command("zfs", "destroy", f"{dataset}@{snapshot}")
310 return None
311 return command("zfs", "diff", "-H", f"{dataset}@{snapshot}", dataset)
312
313
314def numeric(value):
315 try:
316 return float(value.rstrip("x"))
317 except ValueError:
318 return 0
319
320
321def command(*args, timeout=60):
322 with subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
323 stderr=subprocess.PIPE, start_new_session=True) as process:
324 output, errors = bytearray(), bytearray()
325 deadline = time.monotonic() + timeout
326 try:
327 with selectors.DefaultSelector() as selector:
328 selector.register(process.stdout, selectors.EVENT_READ, output)
329 selector.register(process.stderr, selectors.EVENT_READ, errors)
330 while selector.get_map():
331 remaining = deadline - time.monotonic()
332 if remaining <= 0:
333 raise TimeoutError("host command timed out")
334 for key, _ in selector.select(remaining):
335 chunk = os.read(key.fd, 65536)
336 if not chunk:
337 selector.unregister(key.fileobj)
338 continue
339 key.data.extend(chunk)
340 if len(output) + len(errors) > MAX_RESPONSE // 2:
341 raise RuntimeError("The host response is too large. Narrow the selection.")
342 process.wait(timeout=max(0.001, deadline - time.monotonic()))
343 except BaseException:
344 try:
345 os.killpg(process.pid, signal.SIGKILL)
346 except ProcessLookupError:
347 pass
348 raise
349 if process.returncode:
350 raise subprocess.CalledProcessError(process.returncode, args, stderr=errors.decode(errors="replace").strip())
351 return output.decode()
352
353
354def send_response(connection, response):
355 payload = json.dumps(response, allow_nan=False).encode()
356 if len(payload) > MAX_RESPONSE:
357 payload = b'{"error":"The host response is too large. Narrow the selection.","status":502}'
358 connection.sendall(struct.pack("!I", len(payload)) + payload)
359
360
361def stream_console(connection, host, request):
362 details = host.handle(request)
363 with contextlib.ExitStack() as resources:
364 if request["operation"] == "vm.serial":
365 descriptor = os.open(details["path"], os.O_RDWR | os.O_NOCTTY | os.O_NOFOLLOW | os.O_NONBLOCK)
366 screen = resources.enter_context(os.fdopen(descriptor, "r+b", buffering=0))
367 if not stat.S_ISCHR(os.fstat(descriptor).st_mode):
368 raise Rejected("This VM's serial console is unavailable. Restart the VM and reconnect.")
369 try:
370 fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
371 except BlockingIOError:
372 raise Rejected("This console is already open. Close its other console tab, then reconnect.") from None
373 tty.setraw(descriptor)
374 elif request["operation"] == "vm.guest":
375 screen = resources.enter_context(socket.socket(socket.AF_UNIX, socket.SOCK_STREAM))
376 screen.settimeout(10)
377 screen.connect(details["path"])
378 screen.setblocking(False)
379 elif details.get("remote"):
380 _, screen = resources.enter_context(vms.mac_vms.connect(details["name"], {"action": "console"}, timeout=20))
381 screen.setblocking(False)
382 else:
383 identity = details["uuid"]
384 deadline = time.monotonic() + 5
385 while True:
386 try:
387 screen = resources.enter_context(socket.create_connection(("127.0.0.1", details["port"]), timeout=10))
388 break
389 except ConnectionRefusedError:
390 if time.monotonic() >= deadline:
391 raise Rejected("This VM's screen isn't ready. Wait a moment, then reconnect.") from None
392 time.sleep(0.1)
393 details = host.handle(request)
394 if details["uuid"] != identity:
395 raise Rejected("The VM changed while its screen was opening. Open it again.")
396 screen.setblocking(False)
397 send_response(connection, {"value": {"guestDisplay": False} if details.get("remote") else None})
398 try:
399 connection.setblocking(False)
400 with selectors.DefaultSelector() as selector:
401 selector.register(connection, selectors.EVENT_READ, screen)
402 selector.register(screen, selectors.EVENT_READ, connection)
403 deadline = time.monotonic() + 8 * 3600
404 while time.monotonic() < deadline:
405 ready = selector.select(300)
406 if not ready:
407 continue
408 for key, _ in ready:
409 try:
410 data = os.read(key.fd, 65536)
411 except BlockingIOError:
412 continue
413 if not data:
414 return
415 remaining = memoryview(data)
416 stalled = time.monotonic() + 30
417 while remaining:
418 try:
419 written = os.write(key.data.fileno(), remaining)
420 if written == 0:
421 return
422 remaining = remaining[written:]
423 except BlockingIOError:
424 if not select.select([], [key.data], [], max(0, stalled - time.monotonic()))[1]:
425 return
426 except OSError:
427 return
428
429
430def stream_upload(connection, request):
431 if set(request) != {"operation", "payload"}:
432 raise Rejected("Use only the fields required to upload an ISO.")
433 spec = request["payload"]
434 try:
435 vms.validate("upload", spec)
436 except ValueError as error:
437 raise Rejected(str(error)) from error
438 directory = vms.UPLOADS
439 vms.managed_directory(directory)
440 target = directory / spec["volume"]
441 if target.exists() or target.is_symlink():
442 raise Rejected("An ISO already has this filename. Rename the file before uploading.")
443 import tempfile
444 fd, temporary = tempfile.mkstemp(prefix=".upload-", dir=directory)
445 try:
446 send_response(connection, {"value": None})
447 connection.settimeout(120)
448 deadline = time.monotonic() + 2 * 3600
449 with os.fdopen(fd, "wb") as outgoing:
450 remaining = spec["size"]
451 while remaining:
452 if time.monotonic() > deadline:
453 raise TimeoutError("ISO upload timed out. Try uploading again.")
454 data = connection.recv(min(1024 * 1024, remaining))
455 if not data:
456 raise Rejected("The ISO upload was interrupted. Upload the file again.")
457 outgoing.write(data)
458 remaining -= len(data)
459 outgoing.flush()
460 os.fsync(outgoing.fileno())
461 # Never overwrite a file that another upload published in the meantime.
462 os.link(temporary, target)
463 send_response(connection, {"value": {"volume": vms.image_id(target)}})
464 finally:
465 Path(temporary).unlink(missing_ok=True)
466
467
468def serve_connection(connection, host, allowed_uid, allowed_operations=None):
469 with connection, contextlib.ExitStack() as resources:
470 connection.settimeout(65)
471 _, uid, _ = struct.unpack("3i", connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
472 if uid != allowed_uid:
473 return
474 try:
475 # Leave stream payload bytes on the socket after the JSON header.
476 line = bytearray()
477 while len(line) <= MAX_REQUEST:
478 chunk = connection.recv(min(65536, MAX_REQUEST + 1 - len(line)), socket.MSG_PEEK)
479 if not chunk:
480 break
481 end = chunk.find(b"\n")
482 chunk = connection.recv(len(chunk) if end < 0 else end + 1)
483 line.extend(chunk)
484 if line.endswith(b"\n"):
485 break
486 if len(line) > MAX_REQUEST or not line.endswith(b"\n"):
487 raise Rejected("The host request is too large or incomplete.")
488 request = json.loads(line)
489 if allowed_operations is not None and (
490 not isinstance(request, dict) or not isinstance(request.get("operation"), str)
491 or request["operation"] not in allowed_operations
492 ):
493 raise dashboard_runs.Error(403, "This preview cannot change Snow Globe. Use production for host controls.")
494 operation = request.get("operation") if isinstance(request, dict) else None
495 operation = operation if isinstance(operation, str) else None
496 active_snapshot = None
497 control = operation == "vm.computers"
498 if operation in {"vm.owner", "vm.act", "vm.computer"}:
499 payload = request.get("payload")
500 try:
501 vms.validate(operation[3:], payload)
502 except ValueError as error:
503 raise Rejected(str(error)) from error
504 if operation == "vm.owner":
505 control = True
506 elif operation == "vm.act":
507 control = payload["action"] in {"reset", "destroy"}
508 else:
509 action = payload["request"]
510 identity = action.get("id")
511 operation_handle = action.get("action") == "process" and isinstance(identity, str) and identity.startswith("operation:")
512 control = operation_handle and action.get("operation") == "status"
513 if (action.get("action") == "status" or operation_handle and action.get("operation") == "stop") and (
514 not vms.mac_vms.owns(payload["name"])
515 ):
516 active_snapshot = vms.computer_activity(payload["name"])
517 control = active_snapshot is not None
518 if not control:
519 if not WORK_SLOTS.acquire(blocking=False):
520 raise dashboard_runs.Error(503, "The host is busy. Wait for an operation to finish, then retry.")
521 resources.callback(WORK_SLOTS.release)
522 if operation in {"vm.console", "vm.serial", "vm.guest", "vm.upload"}:
523 streams = GUEST_SLOTS if operation == "vm.guest" else STREAM_SLOTS
524 if not streams.acquire(blocking=False):
525 raise Rejected("Four VM connections or uploads are open. Close one and try again.")
526 try:
527 if operation in {"vm.console", "vm.serial", "vm.guest"}:
528 stream_console(connection, host, request)
529 else:
530 stream_upload(connection, request)
531 return
532 finally:
533 streams.release()
534 response = {"value": host.handle(request, active_snapshot=active_snapshot) if active_snapshot is not None else host.handle(request)}
535 except Rejected as error:
536 response = {"error": str(error), "status": 400}
537 except dashboard_runs.Error as error:
538 response = {"error": str(error), "status": error.status}
539 except (json.JSONDecodeError, UnicodeDecodeError):
540 response = {"error": "Send the host request as UTF-8 JSON.", "status": 400}
541 except Exception as error:
542 message = error.stderr if isinstance(error, subprocess.CalledProcessError) else str(error)
543 print(f"host operation: {message}", flush=True)
544 if isinstance(error, subprocess.CalledProcessError) and any(line.endswith(": snapshot has dependent clones") for line in message.splitlines()):
545 response = {"error": "A snapshot has clones. Delete its clones before deleting the snapshot.", "status": 409}
546 else:
547 response = {"error": "The host operation couldn't finish. Check its logs, then retry.", "status": 502}
548 try:
549 send_response(connection, response)
550 except (BrokenPipeError, ConnectionResetError):
551 pass
552
553
554def main():
555 host = Host(os.environ["SNOWGLOBE_POOL"])
556 allowed_uid = pwd.getpwnam(os.environ["SNOWGLOBE_DASHBOARD_USER"]).pw_uid
557 socket_path = Path(os.environ.get("SNOWGLOBE_HOST_SOCKET", "/run/snowglobe-host/host.sock"))
558 socket_path.unlink(missing_ok=True)
559 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener:
560 listener.bind(str(socket_path))
561 socket_path.chmod(0o660)
562 listener.listen(CONNECTIONS)
563 if address := os.environ.get("NOTIFY_SOCKET"):
564 with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as notification:
565 notification.connect("\0" + address[1:] if address.startswith("@") else address)
566 notification.sendall(b"READY=1")
567 slots = threading.BoundedSemaphore(CONNECTIONS)
568 with concurrent.futures.ThreadPoolExecutor(max_workers=CONNECTIONS) as workers:
569 while True:
570 connection, _ = listener.accept()
571 if not slots.acquire(blocking=False):
572 connection.close()
573 continue
574 work = workers.submit(serve_connection, connection, host, allowed_uid)
575 work.add_done_callback(lambda _: slots.release())
576
577
578if __name__ == "__main__":
579 main()