1#!/usr/bin/env python3
2"""Restricted SSH entry point for the managed Mac VMs."""
3import fcntl
4from importlib import import_module
5import json
6import os
7import selectors
8import signal
9import struct
10import subprocess
11import sys
12import tempfile
13import time
14
15vm = import_module("mac-agent-vm")
16# Dashboard names mapped to Tart VMs. The first is managed end to end by mac-agent-vm.py; the others are
17# network-locked guests with their own start script, reached only through Tart's guest agent.
18VMS = {"m3-devbox": vm.NAME, "m3-phoenix-box": "m3-phoenix-box"}
19LOCKED_START = vm.ROOT / "runtime/control/start-m3-phoenix-box"
20
21
22def status():
23 current = json.loads(vm.tart("get", vm.NAME, "--format", "json", capture_output=True, text=True, timeout=5).stdout)
24 disk = vm.ROOT / "state/vms" / vm.NAME / "disk.img"
25 pending = None
26 with (vm.PRIVATE / "lifecycle.lock").open("a+") as lock:
27 try:
28 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
29 except BlockingIOError:
30 lock.seek(0)
31 pending = lock.read(32) or "start"
32 agent = None
33 if current["Running"]:
34 try:
35 vm.guest_ready(capture_output=True, timeout=5)
36 agent = "connected"
37 except subprocess.SubprocessError:
38 agent = "disconnected"
39 return {"state": {"running": "running", "stopped": "shutoff", "suspended": "pmsuspended"}[current["State"]],
40 "vcpus": current["CPU"], "memory": current["Memory"] * 2**20,
41 "disk": {"capacity": disk.stat().st_size, "allocation": disk.stat().st_blocks * 512},
42 "agent": agent, "pendingAction": pending, "mac": current["MACAddress"]}
43
44
45def locked_status(name):
46 current = json.loads(vm.tart("get", name, "--format", "json", capture_output=True, text=True, timeout=5).stdout)
47 disk = vm.ROOT / "state/vms" / name / "disk.img"
48 return {"state": {"running": "running", "stopped": "shutoff", "suspended": "pmsuspended"}[current["State"]],
49 "vcpus": current["CPU"], "memory": current["Memory"] * 2**20,
50 "disk": {"capacity": disk.stat().st_size, "allocation": disk.stat().st_blocks * 512},
51 "agent": None, "pendingAction": None, "mac": current["MACAddress"]}
52
53
54def respond(value):
55 data = json.dumps(value).encode()
56 sys.stdout.buffer.write(struct.pack("!I", len(data)) + data)
57 sys.stdout.buffer.flush()
58
59
60def computer(name, request):
61 with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector:
62 source.write(json.dumps(request).encode())
63 source.seek(0)
64 # Recovery must work when the selected Xcode is unavailable.
65 process = subprocess.Popen([str(vm.TART), "exec", "-i", name, "/Library/Developer/CommandLineTools/usr/bin/python3",
66 "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE,
67 stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")})
68 output = bytearray()
69 errors = 0
70 selector.register(process.stdout, selectors.EVENT_READ, True)
71 selector.register(process.stderr, selectors.EVENT_READ, False)
72 deadline = time.monotonic() + 205
73 try:
74 while selector.get_map():
75 remaining = deadline - time.monotonic()
76 if remaining <= 0:
77 raise ValueError("The guest command timed out. Check its status before retrying.")
78 for key, _ in selector.select(remaining):
79 data = os.read(key.fd, 65536)
80 if not data:
81 selector.unregister(key.fileobj)
82 elif key.data:
83 output.extend(data)
84 else:
85 errors += len(data)
86 if len(output) > 16 * 1024 * 1024 or errors > 65536:
87 raise ValueError("The computer response is too large.")
88 if process.wait(timeout=max(.001, deadline - time.monotonic())):
89 raise ValueError("The Mac guest did not answer. Check its agent and retry.")
90 value = json.loads(output)
91 if not isinstance(value, dict):
92 raise ValueError("The Mac guest returned an incomplete response.")
93 if "error" in value:
94 if value.get("status") == 409:
95 raise BlockingIOError(str(value["error"]))
96 raise ValueError(str(value["error"]))
97 return value
98 finally:
99 if process.poll() is None:
100 try:
101 os.killpg(process.pid, signal.SIGKILL)
102 except ProcessLookupError:
103 pass
104 process.wait()
105 process.stdout.close()
106 process.stderr.close()
107
108
109def lifecycle(action):
110 process = subprocess.Popen([sys.executable, vm.__file__, action], stdout=subprocess.DEVNULL,
111 start_new_session=True)
112 try:
113 if process.wait(timeout=210):
114 raise ValueError("The power operation failed. Check the VM status before retrying.")
115 finally:
116 # Tart's detached VM runner survives; unfinished lifecycle commands do not.
117 try:
118 os.killpg(process.pid, signal.SIGKILL)
119 except ProcessLookupError:
120 pass
121 process.wait()
122
123
124def locked_power(name, action):
125 if action in {"stop", "reboot"}:
126 (vm.PRIVATE / name / "stopped").touch()
127 vm.tart("stop", name, timeout=120)
128 if action in {"start", "reboot"}:
129 subprocess.run([str(LOCKED_START)], check=True, stdout=subprocess.DEVNULL, timeout=30)
130 for _ in range(60):
131 if json.loads(vm.tart("get", name, "--format", "json", capture_output=True, text=True, timeout=5).stdout)["Running"]:
132 return
133 time.sleep(1)
134 raise ValueError("The VM did not start.")
135
136
137def main():
138 line = sys.stdin.buffer.readline(1048577)
139 if len(line) > 1048576 or not line.endswith(b"\n"):
140 raise ValueError("The VM request is too large or incomplete.")
141 request = json.loads(line)
142 if not isinstance(request, dict):
143 raise ValueError("Choose a supported VM operation.")
144 # Hosts that predate multiple VMs omit the name.
145 requested = request.pop("vm", "m3-devbox")
146 name = VMS.get(requested) if isinstance(requested, str) else None
147 if name is None:
148 raise ValueError("Choose a managed VM.")
149 primary = name == vm.NAME
150 action = request.get("action")
151 if action == "status" and set(request) == {"action"}:
152 respond({"value": {**(status() if primary else locked_status(name)), "name": name}})
153 elif action in {"start", "shutdown", "reboot", "suspend", "resume"} and set(request) == {"action"}:
154 if not primary and action in {"suspend", "resume"}:
155 raise ValueError("This operation is unavailable for this Mac VM.")
156 action = {"shutdown": "stop", "resume": "start"}.get(action, action)
157 if primary:
158 lifecycle(action)
159 else:
160 locked_power(name, action)
161 respond({"value": None})
162 elif action == "clipboard" and set(request) == {"action", "text"}:
163 value = request["text"]
164 if not isinstance(value, str) or len(value.encode()) > 262144:
165 raise ValueError("Shorten the clipboard text, then send it again.")
166 vm.tart("exec", "-i", name, "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy",
167 input=value.encode(), capture_output=True, timeout=15)
168 respond({"value": None})
169 elif action == "computer" and set(request) == {"action", "request"}:
170 if not isinstance(request["request"], dict):
171 raise ValueError("Send a computer operation.")
172 respond({"value": computer(name, request["request"])})
173 elif action == "console" and set(request) == {"action"} and primary:
174 with vm.guest_screen() as upstream:
175 respond({"value": None})
176 try:
177 vm.relay_screen(upstream, sys.stdin.fileno(), sys.stdout.fileno())
178 except OSError:
179 pass
180 else:
181 raise ValueError("This operation is unavailable for this Mac VM.")
182
183
184if __name__ == "__main__":
185 python = vm.ROOT / "runtime/venv/bin/python"
186 if sys.prefix != str(python.parent.parent):
187 os.execv(str(python), [str(python), __file__])
188 def disconnected(signum, frame):
189 raise SystemExit(0)
190 signal.signal(signal.SIGHUP, disconnected)
191 signal.signal(signal.SIGTERM, disconnected)
192 try:
193 main()
194 except BlockingIOError as error:
195 respond({"error": str(error), "status": 409})
196 sys.exit(1)
197 except (ValueError, OSError, subprocess.SubprocessError) as error:
198 print(type(error).__name__, file=sys.stderr)
199 respond({"error": str(error) if isinstance(error, ValueError) else "The Mac VM did not answer. Check its host, then retry."})
200 sys.exit(1)