utm: vmnet host-only networking and serial text console
diff --git a/utm/README.txt b/utm/README.txt index fde8600..1ee2925 100644 --- a/utm/README.txt +++ b/utm/README.txt
@@ -51,9 +51,13 @@ create Clone the template VM (APFS clone, so it is cheap), name it after the CloudStack instance's internal name, set CPU cores, memory and NIC MAC addresses, then start it. The - clone is removed again when any step fails. + clone is removed again when any step fails. See Networks + for how the NICs are connected. start, stop, reboot, delete, status, statuses - getconsole Not supported, UTM has no VNC endpoint to hand out. + getconsole Only with console_url set (see Configuration details): + returns console_url with the instance's websocket port and + name as a direct console. The QEMU console arguments are + applied when the VM is created or started while stopped. Custom actions (register them with addCustomAction, no parameters): Suspend Pause the VM in memory @@ -79,11 +83,51 @@ otherwise template NICs keep their mode and additional NICs use shared bridge_interface macOS interface for bridged mode, e.g. en0 + isolated_network_uuid + Optional UUID of a private vmnet host-only segment (QEMU + backend). When set, NICs that are not on a vmnet + extension network are attached to it instead of using + network_mode; VMs with the same UUID share one L2 + segment without DHCP server or host address wait_timeout Optional, seconds to wait for state changes, default 120 + console_url Optional URL of a noVNC page that takes ?port=<websocket + port>. When set, each instance gets a QEMU VNC server on + 127.0.0.1 with a websocket, showing its serial console as + a text console, and getconsole returns this URL as a + direct console (QEMU backend only) + console_websocket_base + Optional, websocket port = this + instance id, default 5700 + console_vnc_display_base + Optional, VNC display = this + instance id, default 200 Template, service offering or instance details: template_name UTM VM to clone, overrides the host/extension value +Networks +-------- + +Without further configuration the NICs use UTM's network modes (see +network_mode). The QEMU backend can also attach them to private vmnet +host-only segments: L2 segments on the Mac, without DHCP server and without +a host address, that only VMs with the same segment UUID share. + + - A NIC on a CloudStack network of the vmnet network extension (an L2 + network whose broadcast URI looks like vs://cs-net-42?mode=internal, + see the vmnet extension's README.txt) gets a segment of its own, with a + UUID derived from the network name. All instances on that CloudStack + network on the same Mac share it, and other networks cannot reach it. + Only mode internal is supported, deploying to a nat network fails. + - With isolated_network_uuid set, the other NICs are attached to that + segment, e.g. one served by a router VM. + - Otherwise, when at least one NIC is on a vmnet extension network, the + other NICs use vmnet-shared, vmnet-host or vmnet-bridged according to + network_mode (emulated is not supported then). + +These NICs are passed to QEMU as additional arguments (-netdev/-device with +ids csnic1, csnic2, ...) in place of UTM's network interfaces. Guests need +their addresses configured by other means than DHCP, for instance a second +NIC on a network with DHCP. + Setup ----- @@ -119,9 +163,12 @@ - No VLAN isolation: UTM cannot tag VLANs. Instances get the CloudStack MAC addresses and the configured network mode only, so the guest network - must be reachable through the Mac's shared or bridged networking. - - No console access and no snapshots (neither is exposed by utmctl or - UTM's AppleScript dictionary). + must be reachable through the Mac's shared or bridged networking, unless + vmnet extension networks or isolated_network_uuid are used (see + Networks), which are local to one Mac. + - No snapshots (not exposed by utmctl or UTM's AppleScript dictionary). + - Console access only through console_url, as a text console on the + guest's serial port, and only for the QEMU backend. - The UTM VM name equals the CloudStack internal instance name; renaming the VM in UTM breaks the mapping. - Tested against UTM 4.6.4 (clone, configure, status, delete). Starting
diff --git a/utm/utm.py b/utm/utm.py index 4e07119..9e9c9f5 100755 --- a/utm/utm.py +++ b/utm/utm.py
@@ -28,6 +28,13 @@ set from the CloudStack instance. The UTM virtual machine is named after the CloudStack instance's internal name. +A NIC on a network of the vmnet network extension carries a broadcast URI +such as vs://cs-net-42?mode=internal. It is attached to a private vmnet +host-only segment (QEMU backend only) whose UUID is derived from the network +name, so all instances on that CloudStack network on the same Mac share one +L2 segment, isolated from other networks. Such a segment has no DHCP server +and no host address. Mode nat is not supported. + Details (host details override extension details): url Mac hostname/IP, or "localhost" to run locally username SSH user owning the UTM library (logged in to the GUI) @@ -43,7 +50,20 @@ applied to every NIC, otherwise the template's mode is kept and added NICs use "shared" bridge_interface optional, macOS interface for bridged mode, e.g. en0 + isolated_network_uuid optional, UUID of a private vmnet host-only network + (QEMU backend only). When set, the instance NICs that + are not on a vmnet extension network are attached to + that network instead of UTM's network modes: VMs using + the same UUID share one L2 segment that has no macOS + DHCP server and no host address wait_timeout optional, seconds to wait for state changes (120) + console_url optional, URL of a noVNC page that takes ?port=<websocket + port>. When set, each instance gets a QEMU VNC server on + 127.0.0.1 with a websocket, showing its serial console as + a text console, and getconsole returns this URL as a + direct console (QEMU backend only) + console_websocket_base optional, websocket port = this + instance id (5700) + console_vnc_display_base optional, VNC display = this + instance id (200) Instance/template details: template_name UTM VM to clone, overrides the host/extension value @@ -55,11 +75,16 @@ import subprocess import sys import time +import uuid DEFAULT_UTMCTL = "/Applications/UTM.app/Contents/MacOS/utmctl" UTM_BUNDLE_ID = "com.utmapp.UTM" NETWORK_MODES = ("shared", "bridged", "host", "emulated") LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1") +# Broadcast URI scheme of the networks named by the vmnet network extension +VMNET_SCHEME = "vs://" +# Namespace of the segment UUIDs derived from vmnet extension network names +VMNET_UUID_NAMESPACE = uuid.uuid5(uuid.NAMESPACE_URL, "https://cloudstack.apache.org/extensions/vmnet") POWER_ON_STATES = ("started", "starting", "paused", "pausing", "resuming") POWER_OFF_STATES = ("stopped",) @@ -98,6 +123,94 @@ """ +# Replaces UTM's network interfaces by QEMU arguments, one -netdev/-device pair +# per NIC with the given netdev options and MAC address, keeping other arguments +QEMU_NICS_CONFIGURE_SCRIPT = """ +on run argv + set vmName to item 1 of argv + set cpuCount to (item 2 of argv) as integer + set memMib to (item 3 of argv) as integer + tell application "UTM" + set vm to virtual machine named vmName + set config to configuration of vm + set qemuArgs to qemu additional arguments of config + -- drop the -netdev/-device pairs of an earlier configuration + set kept to {} + set i to 1 + repeat while i <= (count of qemuArgs) + set s to argument string of item i of qemuArgs + if (s is "-netdev" or s is "-device") and i < (count of qemuArgs) and (argument string of item (i + 1) of qemuArgs) contains "csnic" then + set i to i + 2 + else + set end of kept to item i of qemuArgs + set i to i + 1 + end if + end repeat + repeat with i from 4 to (count of argv) by 2 + set nicId to "csnic" & ((i - 2) div 2) + set end of kept to {argument string:"-netdev"} + set end of kept to {argument string:(item i of argv) & ",id=" & nicId} + set end of kept to {argument string:"-device"} + set end of kept to {argument string:"virtio-net-pci,netdev=" & nicId & ",mac=" & (item (i + 1) of argv)} + end repeat + set cpu cores of config to cpuCount + set memory of config to memMib + set network interfaces of config to {} + set qemu additional arguments of config to kept + update configuration of vm with config + end tell +end run +""" + + +# Replaces UTM's own serial port (a pseudo TTY) and any earlier console arguments +# with a QEMU VNC server whose text console is the guest's serial port +CONSOLE_SCRIPT = """ +on run argv + set vmName to item 1 of argv + tell application "UTM" + set vm to virtual machine named vmName + set config to configuration of vm + set qemuArgs to {} + set skipNext to false + repeat with arg in (qemu additional arguments of config) + set s to argument string of arg + if skipNext then + set skipNext to false + else if s is "-vnc" or s is "-serial" then + set skipNext to true + else + set end of qemuArgs to contents of arg + end if + end repeat + repeat with i from 2 to count of argv + set end of qemuArgs to {argument string:(item i of argv)} + end repeat + set qemu additional arguments of config to qemuArgs + -- "serial ports" compiles to a different code than the record uses + set \u00abclass SrPt\u00bb of config to {} + update configuration of vm with config + end tell +end run +""" + + +def vmnet_network(broadcast_uri): + """The (name, mode) of a vmnet extension network broadcast URI, or None.""" + if not broadcast_uri or not broadcast_uri.startswith(VMNET_SCHEME): + return None + name, _, query = broadcast_uri[len(VMNET_SCHEME):].partition("?") + if not name or not all(c.islower() or c.isdigit() or c == "-" for c in name): + raise ValueError(f"invalid vmnet network name in broadcast URI '{broadcast_uri}'") + params = dict(p.split("=", 1) for p in query.split("&") if "=" in p) + return name, params.get("mode", "nat") + + +def vmnet_segment_uuid(name): + """The vmnet host-only segment UUID of a vmnet extension network.""" + return str(uuid.uuid5(VMNET_UUID_NAMESPACE, name)).upper() + + def fail(message): print(json.dumps({"status": "error", "error": message})) sys.exit(1) @@ -138,13 +251,22 @@ "utmctl": detail("utmctl_path"), "network_mode": detail("network_mode").lower(), "bridge_interface": detail("bridge_interface"), + "isolated_network_uuid": detail("isolated_network_uuid"), "wait_timeout": int(detail("wait_timeout", "120")), "template_name": vm.get("template_name") or detail("template_name"), + "console_url": detail("console_url"), + "console_websocket_base": int(detail("console_websocket_base", "5700")), + "console_vnc_display_base": int(detail("console_vnc_display_base", "200")), } if not data["url"]: fail("Missing required field in JSON: url") if data["network_mode"] and data["network_mode"] not in NETWORK_MODES: fail(f"Invalid network_mode '{data['network_mode']}', expected one of {', '.join(NETWORK_MODES)}") + if data["isolated_network_uuid"]: + try: + data["isolated_network_uuid"] = str(uuid.UUID(data["isolated_network_uuid"])).upper() + except ValueError: + fail(f"Invalid isolated_network_uuid '{data['isolated_network_uuid']}'") if data["network_mode"] == "bridged" and not data["bridge_interface"]: fail("Missing required field in JSON: bridge_interface (required for bridged network_mode)") data["local"] = data["url"].lower() in LOCAL_HOSTS and not data["username"] @@ -153,10 +275,16 @@ vm_details = json_data.get("cloudstack.vm.details", {}) or {} data["vmname"] = vm_details.get("name", "") + data["vmid"] = vm_details.get("id") data["cpus"] = vm_details.get("cpus") data["memory"] = vm_details.get("minRam") - nics = sorted(vm_details.get("nics", []) or [], key=lambda n: n.get("deviceId", 0)) - data["macs"] = [nic["mac"] for nic in nics if nic.get("mac")] + nics = sorted(vm_details.get("nics", []) or [], key=lambda n: int(n.get("deviceId", 0))) + nics = [nic for nic in nics if nic.get("mac")] + data["macs"] = [nic["mac"] for nic in nics] + data["vmnet_networks"] = [vmnet_network(nic.get("broadcastUri")) for nic in nics] + for network in data["vmnet_networks"]: + if network and network[1] != "internal": + fail(f"vmnet network {network[0]} has mode {network[1]}, UTM supports only mode internal") data["parameters"] = json_data.get("parameters", {}) or {} return data @@ -256,6 +384,54 @@ new_nic = f"set nic to {{mode:{new_mode}, address:item i of macs{host_interface}}}" return CONFIGURE_SCRIPT % {"set_mode": set_mode, "new_nic": new_nic} + def qemu_netdevs(self): + """QEMU -netdev options per NIC, or None when UTM's own network interfaces are used.""" + isolated = self.data["isolated_network_uuid"] + if not isolated and not any(self.data["vmnet_networks"]): + return None + mode = self.data["network_mode"] or "shared" + if not isolated and mode not in ("shared", "host", "bridged"): + raise UtmError(f"network_mode {mode} cannot be combined with vmnet extension networks") + netdevs = [] + for network in self.data["vmnet_networks"]: + if network: + netdevs.append(f"vmnet-host,net-uuid={vmnet_segment_uuid(network[0])}") + elif isolated: + netdevs.append(f"vmnet-host,net-uuid={isolated}") + elif mode == "bridged": + netdevs.append(f"vmnet-bridged,ifname={self.data['bridge_interface']}") + else: + netdevs.append(f"vmnet-{mode}") + return netdevs + + def configure(self, vm_name): + memory_mib = int(self.data["memory"]) // (1024 * 1024) + netdevs = self.qemu_netdevs() + if netdevs is None: + self.osascript(self.configure_script(), vm_name, str(self.data["cpus"]), str(memory_mib), + self.data["bridge_interface"], *self.data["macs"]) + return + args = [] + for netdev, mac in zip(netdevs, self.data["macs"]): + args += [netdev, mac] + self.osascript(QEMU_NICS_CONFIGURE_SCRIPT, vm_name, str(self.data["cpus"]), str(memory_mib), *args) + + def console_ports(self): + vm_id = int(self.data["vmid"]) + return (self.data["console_websocket_base"] + vm_id, + self.data["console_vnc_display_base"] + vm_id) + + def ensure_console(self, name): + # The configuration can only be updated while the VM is stopped + if not self.data["console_url"] or self.data["vmid"] is None: + return + if self.vm_state(name) not in POWER_OFF_STATES: + return + websocket_port, vnc_display = self.console_ports() + self.osascript(CONSOLE_SCRIPT, name, + "-vnc", f"127.0.0.1:{vnc_display},websocket={websocket_port}", + "-serial", "vc:120Cx36C") + def stop_vm(self, name): state = self.vm_state(name) if state is None or state in POWER_OFF_STATES: @@ -282,9 +458,8 @@ try: self.utmctl("clone", template, "--name", vm_name) cloned = True - memory_mib = int(self.data["memory"]) // (1024 * 1024) - self.osascript(self.configure_script(), vm_name, str(self.data["cpus"]), str(memory_mib), - self.data["bridge_interface"], *self.data["macs"]) + self.configure(vm_name) + self.ensure_console(vm_name) self.utmctl("start", vm_name) succeed({"status": "success", "message": "Instance created"}) except UtmError as e: @@ -298,6 +473,7 @@ def start(self): self.require_vmname() + self.ensure_console(self.data["vmname"]) self.utmctl("start", self.data["vmname"]) succeed({"status": "success", "message": "Instance started"}) @@ -309,6 +485,7 @@ def reboot(self): self.require_vmname() self.stop_vm(self.data["vmname"]) + self.ensure_console(self.data["vmname"]) self.utmctl("start", self.data["vmname"]) succeed({"status": "success", "message": "Instance rebooted"}) @@ -337,7 +514,14 @@ succeed({"status": "success", "power_state": power_state}) def get_console(self): - fail("Operation not supported") + self.require_vmname() + if not self.data["console_url"] or self.data["vmid"] is None: + fail("Operation not supported, set the console_url detail to enable consoles") + websocket_port, _ = self.console_ports() + separator = "&" if "?" in self.data["console_url"] else "?" + url = f"{self.data['console_url']}{separator}port={websocket_port}&name={self.data['vmname']}" + succeed({"status": "success", "message": "Console retrieved", + "console": {"url": url, "protocol": "direct"}}) def suspend(self): self.require_vmname()