| 1 | import concurrent.futures |
| 2 | import contextlib |
| 3 | import json |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import socket |
| 7 | import struct |
| 8 | import subprocess |
| 9 | import tempfile |
| 10 | |
| 11 | |
| 12 | CONFIG = json.loads(os.environ.get("SNOWGLOBE_MAC_VM", "null")) |
| 13 | CACHE = Path(os.environ.get("SNOWGLOBE_MAC_VM_CACHE", "/var/lib/snowglobe/host/mac-vm.json")) |
| 14 | |
| 15 | |
| 16 | def vm(name): |
| 17 | return next((entry for entry in CONFIG["vms"] if entry["name"] == name), None) if CONFIG else None |
| 18 | |
| 19 | |
| 20 | def owns(name): |
| 21 | return vm(name) is not None |
| 22 | |
| 23 | |
| 24 | @contextlib.contextmanager |
| 25 | def connect(name, request, timeout=10): |
| 26 | if not CONFIG: |
| 27 | raise ValueError("The Mac VM is not configured on this host.") |
| 28 | parent, child = socket.socketpair() |
| 29 | process = None |
| 30 | try: |
| 31 | process = subprocess.Popen([ |
| 32 | "ssh", "-T", "-F", "/dev/null", "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", |
| 33 | "-o", "ForwardAgent=no", "-o", "ConnectTimeout=3", "-o", "ConnectionAttempts=1", |
| 34 | "-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=2", |
| 35 | "-o", "StrictHostKeyChecking=yes", "-o", "HostKeyAlias=mac-studio", |
| 36 | "-o", "UserKnownHostsFile=" + CONFIG["knownHosts"], "-o", "GlobalKnownHostsFile=/dev/null", |
| 37 | "-i", CONFIG["identity"], "-p", str(CONFIG["port"]), CONFIG["user"] + "@" + CONFIG["address"], |
| 38 | ], stdin=child, stdout=child, stderr=subprocess.DEVNULL) |
| 39 | child.close() |
| 40 | parent.settimeout(timeout) |
| 41 | parent.sendall(json.dumps({**request, "vm": name}).encode() + b"\n") |
| 42 | |
| 43 | def read(size): |
| 44 | data = bytearray() |
| 45 | while len(data) < size: |
| 46 | chunk = parent.recv(size - len(data)) |
| 47 | if not chunk: |
| 48 | raise ConnectionError("The Mac connection closed.") |
| 49 | data.extend(chunk) |
| 50 | return data |
| 51 | |
| 52 | size, = struct.unpack("!I", read(4)) |
| 53 | if size > (16 * 1024 * 1024 if request["action"] == "computer" else 65536): |
| 54 | raise ValueError("The Mac response is too large.") |
| 55 | reply = json.loads(read(size)) |
| 56 | if "error" in reply: |
| 57 | if reply.get("status") == 409: |
| 58 | raise BlockingIOError(reply["error"]) |
| 59 | raise ValueError(reply["error"]) |
| 60 | if "value" not in reply: |
| 61 | raise ValueError("The Mac response is incomplete.") |
| 62 | yield reply["value"], parent |
| 63 | except BlockingIOError: |
| 64 | raise |
| 65 | except OSError as error: |
| 66 | raise ValueError("Mac Studio is unreachable. Check its power and network, then retry.") from error |
| 67 | finally: |
| 68 | parent.close() |
| 69 | child.close() |
| 70 | if process: |
| 71 | process.terminate() |
| 72 | try: |
| 73 | process.wait(timeout=5) |
| 74 | except subprocess.TimeoutExpired: |
| 75 | process.kill() |
| 76 | process.wait() |
| 77 | |
| 78 | |
| 79 | def ownership(entry): |
| 80 | return {"owner": entry["owner"], "ownerOnly": True} |
| 81 | |
| 82 | |
| 83 | def power(entry): |
| 84 | return ["start", "shutdown", "reboot"] + (["suspend", "resume"] if entry["suspend"] else []) |
| 85 | |
| 86 | |
| 87 | def observe(entry): |
| 88 | value = {"name": entry["name"], **ownership(entry), "host": "Mac Studio", "arch": "aarch64", |
| 89 | "state": "unreachable", "reason": None, |
| 90 | "os": "macOS", "vcpus": None, "memory": None, "balloon": None, "pinned": None, |
| 91 | "autostart": False, "startedAt": None, "agent": None, "setup": None, "pendingAction": None, |
| 92 | "disks": [], "media": [], "firmware": "uefi", "platform": "macos", "console": entry["console"], |
| 93 | "serial": False, "interfaces": [], "hostdevs": [], "capabilities": power(entry) + ["clipboard", "computer"]} |
| 94 | try: |
| 95 | with connect(entry["name"], {"action": "status"}, timeout=8) as (status, _): |
| 96 | value.update({key: status[key] for key in ("state", "vcpus", "memory", "agent", "pendingAction")}) |
| 97 | value["balloon"] = value["memory"] |
| 98 | value["disks"] = [{"target": "disk", "pool": "Mac Studio", "source": status.get("name", entry["name"]), **status["disk"]}] |
| 99 | value["interfaces"] = [{"source": "Mac Studio NAT", "mac": status["mac"], "addresses": []}] |
| 100 | except (ValueError, OSError, KeyError, TypeError): |
| 101 | try: |
| 102 | previous = json.loads(CACHE.read_text())[entry["name"]] |
| 103 | for key in ("vcpus", "memory", "balloon", "disks", "interfaces"): |
| 104 | value[key] = previous[key] |
| 105 | except (ValueError, OSError, KeyError, TypeError): |
| 106 | pass |
| 107 | value.update(state="unreachable", agent=None, pendingAction=None) |
| 108 | return value, value["state"] != "unreachable" |
| 109 | |
| 110 | |
| 111 | def domain(): |
| 112 | if not CONFIG: |
| 113 | return [] |
| 114 | with concurrent.futures.ThreadPoolExecutor(len(CONFIG["vms"])) as pool: |
| 115 | observed = list(pool.map(observe, CONFIG["vms"])) |
| 116 | live = {value["name"]: value for value, reachable in observed if reachable} |
| 117 | if live: |
| 118 | try: |
| 119 | CACHE.parent.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 120 | try: |
| 121 | live = {**json.loads(CACHE.read_text()), **live} |
| 122 | except (ValueError, OSError): |
| 123 | pass |
| 124 | descriptor, temporary = tempfile.mkstemp(dir=CACHE.parent, prefix=".mac-vm-") |
| 125 | try: |
| 126 | with os.fdopen(descriptor, "w") as outgoing: |
| 127 | json.dump(live, outgoing) |
| 128 | os.replace(temporary, CACHE) |
| 129 | finally: |
| 130 | Path(temporary).unlink(missing_ok=True) |
| 131 | except OSError: |
| 132 | pass |
| 133 | return [value for value, _ in observed] |
| 134 | |
| 135 | |
| 136 | def handle(action, payload): |
| 137 | entry = vm(payload["name"]) |
| 138 | if action == "owner": |
| 139 | return ownership(entry) |
| 140 | if action == "access": |
| 141 | return None |
| 142 | if action == "console" and entry["console"]: |
| 143 | return {"remote": True, "name": entry["name"]} |
| 144 | if action == "act" and payload["action"] in power(entry): |
| 145 | request = {"action": payload["action"]} |
| 146 | elif action == "clipboard": |
| 147 | request = {"action": "clipboard", "text": payload["text"]} |
| 148 | elif action == "computer": |
| 149 | request = {"action": "computer", "request": payload["request"]} |
| 150 | else: |
| 151 | raise ValueError("This operation is unavailable for this Mac VM.") |
| 152 | with connect(entry["name"], request, timeout=220) as (value, _): |
| 153 | return value |