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