diff --git a/dashboard/src/computer-tools.json b/dashboard/src/computer-tools.json index 51b545620f44cebdeb1d98a904fa3bb01f94c457..8fd3f6584265d027bfad8c2a6102db629fe4426b 100644 --- a/dashboard/src/computer-tools.json +++ b/dashboard/src/computer-tools.json @@ -594,7 +594,7 @@ }, { "name": "computer_vm", - "description": "Start, shut down, or reboot a granted VM. For AI-owned test VMs only: extend idle expiry by up to 24 hours from now, or delete the VM and its disposable disk. Listing VMs does not extend expiry.", + "description": "Start, shut down, reboot, force off, or reset a granted VM. Force off and reset lose unsaved work and are unavailable on managed Macs. For AI-owned test VMs, extend idle expiry by up to 24 hours or delete the VM and disk. Listing does not extend expiry.", "inputSchema": { "type": "object", "properties": { @@ -607,6 +607,8 @@ "start", "shutdown", "reboot", + "force_off", + "reset", "extend", "delete" ] diff --git a/dashboard/src/computer.rs b/dashboard/src/computer.rs index 13f8bbfbde229073773c5034d0c61ec9482b2a69..4675da3010a437b4c0e58d5911b56daf4bbcee41 100644 --- a/dashboard/src/computer.rs +++ b/dashboard/src/computer.rs @@ -173,11 +173,12 @@ impl ServerHandler for Computer { return match arguments.get("operation").and_then(Value::as_str) { Some(operation @ ("extend" | "delete")) => host::call(json!({"operation":"vm.ai","payload":{ "action":operation,"name":vm,"owner":grant["user"],"seconds":arguments.get("seconds").unwrap_or(&json!(3600))}})).await, - Some(operation @ ("start" | "shutdown" | "reboot")) if !arguments.contains_key("seconds") => { - host::call(json!({"operation":"vm.act","payload":{"name":vm,"action":operation}})).await?; + Some(operation @ ("start" | "shutdown" | "reboot" | "force_off" | "reset")) if !arguments.contains_key("seconds") => { + let host_action = if operation == "force_off" { "destroy" } else { operation }; + host::call(json!({"operation":"vm.act","payload":{"name":vm,"action":host_action}})).await?; Ok(json!({"id":vm,"requested":operation})) }, - _ => Err(Error::new(400,"Choose start, shutdown, reboot, extend, or delete.")), + _ => Err(Error::new(400,"Choose start, shutdown, reboot, force_off, reset, extend, or delete.")), }; } if matches!(action,"upload"|"download") { diff --git a/tools/computer-client-test.py b/tools/computer-client-test.py index dc50038eea4989b673d65b56e958fbbc583175ec..dc33c2887dde4c6268319db7ed6b785579519a6e 100644 --- a/tools/computer-client-test.py +++ b/tools/computer-client-test.py @@ -29,6 +29,7 @@ HOST = "snowglobe.paperclover.net" class Host(socketserver.StreamRequestHandler): owner = None files = {} + power_actions = [] def handle(self): request = json.loads(self.rfile.readline()) @@ -48,6 +49,9 @@ class Host(socketserver.StreamRequestHandler): "os": "Fedora", "arch": "x86_64", "state": "running", "aiOwned": False}] if operation == "vm.owner": return {"owner": self.owner} + if operation == "vm.act": + self.power_actions.append(payload["action"]) + return None if operation != "vm.computer": raise KeyError(operation) request, files = payload["request"], self.files @@ -164,6 +168,10 @@ class Client(unittest.TestCase): self.assertEqual([c["id"] for c in vm.call("computer_list")["computers"]], ["test-vm"]) ran = vm.call("computer_exec", vm="test-vm", script="uname") self.assertEqual((ran["stdout"], ran["png"]), ("ran uname", base64.b64decode(PNG))) + for operation in ["force_off", "reset"]: + self.assertEqual(vm.call("computer_vm", vm="test-vm", operation=operation), + {"id":"test-vm", "requested":operation}) + self.assertEqual(Host.power_actions, ["destroy", "reset"]) with self.assertRaisesRegex(computer.ComputerError, "granted"): vm.call("computer_shot", vm="other-vm") diff --git a/tools/dashboard-vms-test.py b/tools/dashboard-vms-test.py index 89403fbbdf15330d62fd2f4582bbf084bcca62fe..5bb7771d5763464379c4e502677ad4e03c3442ec 100644 --- a/tools/dashboard-vms-test.py +++ b/tools/dashboard-vms-test.py @@ -427,6 +427,43 @@ class VMTests(unittest.TestCase): vms.validate('upload', {'volume': filename, 'size': 32768}) +class PowerControls(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + (self.root / 'fixture').mkdir() + patcher = patch.object(vms, 'DISKS', self.root) + patcher.start() + self.addCleanup(patcher.stop) + + def test_force_controls_cancel_the_active_call_without_waiting_for_it(self): + for action in ['reset', 'destroy']: + with self.subTest(action=action), vms.computer_lock('fixture', 'exec') as active: + with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':action})]), patch.object(vms, 'virsh', return_value='') as virsh: + self.assertIsNone(vms.main()) + virsh.assert_called_once_with(action, 'fixture', timeout=15) + with vms.computer_control('fixture') as control: + self.assertEqual(control.read(), active['id']) + self.assertEqual(vms.computer_activity('fixture')['id'], active['id']) + + def test_failed_force_request_keeps_the_cancellation_intent(self): + with vms.computer_lock('fixture', 'exec') as active: + with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':'reset'})]), \ + patch.object(vms, 'virsh', side_effect=vms.subprocess.CalledProcessError(1, 'virsh', stderr='Connection lost')): + with self.assertRaises(vms.subprocess.CalledProcessError): + vms.main() + with vms.computer_control('fixture') as control: + self.assertEqual(control.read(), active['id']) + + def test_graceful_actions_preserve_the_active_command_guard(self): + with vms.computer_lock('fixture', 'exec'), patch.object(vms, 'virsh') as virsh: + for action in ['start', 'shutdown', 'reboot', 'suspend', 'resume']: + with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':action})]): + with self.assertRaises(BlockingIOError): + vms.main() + virsh.assert_not_called() + class DisposableStorage(unittest.TestCase): def setUp(self): temporary = tempfile.TemporaryDirectory() diff --git a/tools/vm-computer.py b/tools/vm-computer.py index 41123566ae908d5c3d6d63bcec67bbd68c14813f..8649d6481a9a40e0c8a3ff5f884682daa860ed8e 100644 --- a/tools/vm-computer.py +++ b/tools/vm-computer.py @@ -530,10 +530,7 @@ def handle(name, request): if active.get('id') != identity: return {'running': False} if request['operation'] == 'stop': - control.seek(0) - control.truncate() - control.write(identity) - control.flush() + vms.computer_cancel(control, identity) else: active['stopping'] = control.read() == identity return {'running': True, **active, 'stopping': request['operation'] == 'stop' or active.get('stopping', False)} diff --git a/tools/vms.py b/tools/vms.py index d973628c87f5d53c0a4a7931e31639762b48b84d..d82b077e84e0fa98dcaea6f9122ff45b4ac817fa 100644 --- a/tools/vms.py +++ b/tools/vms.py @@ -176,7 +176,7 @@ def validate(action, payload): for field in ("autostart", "start", "disks"): if field in payload and not isinstance(payload[field], bool): raise ValueError(f"Choose whether to enable {field}.") - if action == "act" and (not isinstance(payload["action"], str) or payload["action"] not in {"start", "shutdown", "reboot", "destroy", "resume", "suspend"}): + if action == "act" and (not isinstance(payload["action"], str) or payload["action"] not in {"start", "shutdown", "reboot", "reset", "destroy", "resume", "suspend"}): raise ValueError("Choose a supported VM action.") if action == "clipboard" and (not isinstance(payload["text"], str) or len(payload["text"].encode()) > 262144): raise ValueError("Shorten the clipboard text, then send it again.") @@ -238,6 +238,13 @@ def computer_control(name): yield control +def computer_cancel(control, identity): + control.seek(0) + control.truncate() + control.write(identity) + control.flush() + + def computer_activity(name): try: with os.fdopen(open_regular(DISKS / name / "computer.lock")) as incoming: @@ -309,7 +316,7 @@ def domains(*, computers=False): "arch": root.find("./os/type").get("arch"), "state": state, "aiOwned": ai is not None, "ownerOnly": ai is not None, "expiresAt": ai["expiresAt"] if ai else None, - "capabilities": ["start", "shutdown", "reboot", "destroy", "resume", "suspend", "edit", "delete", "media", "preset", "computer"], + "capabilities": ["start", "shutdown", "reboot", "reset", "destroy", "resume", "suspend", "edit", "delete", "media", "preset", "computer"], } if computers: result.append(entry) @@ -1138,14 +1145,19 @@ def main(): elif action == "act": name = payload["name"] ensure_name(name) - with computer_lock(name): + forced = payload["action"] in {"reset", "destroy"} + with computer_control(name) if forced else computer_lock(name) as control: + if forced: + active = computer_activity(name) + if active is not None and active.get("id"): + computer_cancel(control, active["id"]) if payload["action"] == "start": root = ET.fromstring(virsh("dumpxml", name, "--inactive")) if root.find("./devices/interface/source[@network='default']") is not None: ensure_network() ai = import_module("vm-ai") ai.lease(name, ai.LIMITS["idle_seconds"]) - virsh({"start": "start", "shutdown": "shutdown", "reboot": "reboot", "destroy": "destroy", "resume": "resume", "suspend": "suspend"}[payload["action"]], name) + virsh(payload["action"], name, timeout=15 if forced else None) elif action == "update": name = payload["name"] ensure_name(name)