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