# Virtual Machines **Page:** kit/vm [Download Raw Markdown](./kit/vm.md) --- # Virtual Machines Hoody VM runs full virtual machines inside your computer, so you can run Windows or another Linux distribution beside its own system. Each VM is a QEMU process accelerated by KVM, with its own disk, firmware and operating system. VMs need KVM; there is no software emulation. Check first: ```bash # Every `hoody vm` command acts on this computer (or pass -c COMPUTER_ID) export HOODY_COMPUTER="$COMPUTER_ID" hoody vm capabilities get ``` ```typescript import { HoodyClient } from 'hoody-sdk'; const hoody = new HoodyClient({ baseURL: 'https://api.hoody.com', token: process.env.HOODY_TOKEN }); const box = await hoody.withComputer({ id: COMPUTER_ID, project_id: PROJECT_ID, server: SERVER }); const caps = await box.vm.kit.getCapabilities(); console.log(caps.data.kvm_present); // false: every start is refused with KvmUnavailable console.log(caps.data.provisioning); // uefi, tpm, secure_boot, templates, file_sharing, audio, ... ``` ```bash curl "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/capabilities" ``` Shows whether KVM is usable, memory, free storage and the features new VMs can use. With `kvm_present: false`, VMs can be stored but every start is refused with `KvmUnavailable`. To give a stopped computer KVM, run `hoody computers kvm enable` (`disable` turns it off; [API](/api/computers/#put-apiv1computersidkvm)), on a rented dedicated server only. In the Hub, open **Computers**, select the computer, and on the **Overview** tab turn on **Virtual machines (KVM)** under **Features**. If the computer is running, choose **Stop computer** when prompted. Once it has stopped, turn on **Virtual machines (KVM)**, then start the computer again. For a new computer, turn on **Virtual machine** under **More options** in **Get a computer**. Replace `PROJECT_ID`, `COMPUTER_ID` and `SERVER` with your computer's. The HTTP examples send no credentials: add what its [proxy permissions](/foundation/proxy/permissions/) require. ## Create a VM A create needs `name` (1 to 63 lowercase letters, digits and `-`, starting with a letter or digit), `source`, `memory_mib` and `vcpus`. The source gives the disk: | `source.type` | Needs | Disk | |---|---|---| | `template` | `id` | From a template | | `blank` | `gib` | Empty, `gib` GiB | | `iso` | `gib`, and `sha256` or `path` | Empty, with the installer image attached | | `offline-file` | `path` | A copy of a disk image in a permitted import directory. By default, the file must be inside an existing stopped VM's directory under `/hoody/storage/vms/`. A path outside the permitted directories fails during background creation: poll for `progress.phase: "failed"` and read `progress.error` for `SpecInvalid` | | `vm-disk` | `name` | A copy of another stopped VM's disk (`name` is that VM), with a new VM identity. If TPM is enabled, it gets a fresh TPM; the source's TPM state is not copied. | | `snapshot-artifact` | `sha256` | A snapshot [from another computer](#move-a-vm-to-another-computer) | ```bash # Create from an installer image in the store, on X display :5 hoody vm create --name dev-vm \ --source-type iso --source-sha256 "$SHA" --source-gib 40 \ --memory-mib 4096 --vcpus 2 --display 5 # Poll until progress.phase is committed or failed hoody vm get dev-vm ``` ```typescript await box.vm.vms.create({ name: 'dev-vm', source: { type: 'iso', sha256: SHA, gib: 40 }, memory_mib: 4096, vcpus: 2, display: 5, }); const vm = await box.vm.vms.get('dev-vm'); console.log(vm.data.progress?.phase); // reserving, importing, committing, committed or failed ``` ```bash curl -X POST "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms" \ -H "Content-Type: application/json" \ -d "$(jq -n --arg sha "$SHA" '{ name: "dev-vm", source: { type: "iso", sha256: $sha, gib: 40 }, memory_mib: 4096, vcpus: 2, display: 5 }')" # The Location header names the VM to poll curl "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms/dev-vm" ``` Replace `SHA` with the image's SHA-256, then open Create, then Check progress until it finishes. The create answers `202` and continues in the background: poll until `progress.phase` is `committed` or `failed`, with any failure in `progress.error`. Right after a commit a read can briefly answer `409 OperationInProgress`; poll again. Firmware, TPM, disk bus and the other [hardware](/kit/vm/reference/#hardware-fixed-at-create) are fixed at create. An `os` preset (`windows-11`, `windows-server` or `linux`) sets what that OS needs; fields you set win. ## Start, stop and pause a VM ```bash hoody -o json vm start dev-vm # inspect error; if populated, the start was refused: stop here hoody vm get dev-vm # repeat until state is Running; on Failed, read error and reason and stop here hoody vm pause dev-vm hoody vm get dev-vm # repeat until state is Paused hoody vm resume dev-vm hoody vm get dev-vm # repeat until state is Running hoody vm stop dev-vm # asks the guest to power down hoody vm get dev-vm # repeat until state is Stopped ``` `hoody vm stop dev-vm --force` stops it at once without asking the guest. ```typescript // start, pause, resume and stop return before the change finishes, // so wait for each state before asking for the next change async function waitFor(name: string, want: string) { for (;;) { const vm = await box.vm.vms.get(name); if (vm.data.state === want) return; if (vm.data.state === 'Failed') { throw new Error(vm.data.error?.error.code ?? vm.data.reason ?? 'Failed'); } await new Promise((resolve) => setTimeout(resolve, 1000)); } } const started = await box.vm.vms.start('dev-vm'); if (started.data.error) { // The start was refused, even if state still reads Starting throw new Error(started.data.error.error.code); } await waitFor('dev-vm', 'Running'); await box.vm.vms.pause('dev-vm'); await waitFor('dev-vm', 'Paused'); await box.vm.vms.resume('dev-vm'); await waitFor('dev-vm', 'Running'); await box.vm.vms.stop('dev-vm'); ``` ```bash VMS="https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms" # poll until the VM reads the wanted state. Exit on Failed, on an answer # that is not 2xx (404: the VM is gone) and on a reply that is not a VM. wait_for() { while true; do BODY=$(curl -fsS "$VMS/dev-vm") || { echo "reading the VM failed" >&2; exit 1; } STATE=$(echo "$BODY" | jq -er .state) || { echo "unexpected reply: $BODY" >&2; exit 1; } [ "$STATE" = "$1" ] && return 0 if [ "$STATE" = "Failed" ]; then echo "$BODY" | jq '{reason, error}' >&2; exit 1; fi sleep 1 done } # check the request first; a refused start still answers 200, with the refusal in error BODY=$(curl -fsS -X POST "$VMS/dev-vm/start") || { echo "start request failed" >&2; exit 1; } echo "$BODY" | jq -e 'has("state")' > /dev/null || { echo "unexpected reply: $BODY" >&2; exit 1; } ERROR=$(echo "$BODY" | jq -c '.error // empty') if [ -n "$ERROR" ]; then echo "start refused: $ERROR" >&2; exit 1; fi wait_for Running curl -fsS -X POST "$VMS/dev-vm/pause" > /dev/null || exit 1 wait_for Paused curl -fsS -X POST "$VMS/dev-vm/resume" > /dev/null || exit 1 wait_for Running curl -fsS -X POST "$VMS/dev-vm/stop" > /dev/null || exit 1 wait_for Stopped ``` `POST "$VMS/dev-vm/force-stop"` stops it at once without asking the guest. Each link is one action. After each, open Read state until it reads the new state. Most [refused starts](/kit/vm/reference/#refused-starts) still answer `200`. If the VM's `error` is set, the start was refused, even while `state` reads `Starting`; the code is at `error.error.code`. Otherwise poll until `Running` or `Failed`. | Action | What happens | |---|---| | `stop` | Presses the power button, forcing it off after a timeout. Reads `Stopping` until it exits. | | `force stop` | For a guest that does not respond. Like pulling the power cord: unsaved guest data is lost. | | `pause` | Freezes the CPUs but keeps the memory; stop to release it. | Only `autostart` (off by default; `--autostart` at create, or `hoody vm update` while stopped) brings a VM back after the computer restarts, even one you stopped on purpose. ## Let connections reach the VM A VM has outbound access. Inbound, only the forwards in `ports` reach it; without one, nothing can connect, not even the computer or the display service. A forward opens `host` for its protocol on every address of the computer and passes it to `guest`. Another VM declaring the same protocol and host port, even while stopped, causes `409 PortForwardConflict`. TCP and UDP reservations are separate. ```bash hoody vm create --name web-vm --source-type template --source-id TEMPLATE_ID \ --memory-mib 2048 --vcpus 2 --ports proto=tcp,host=2222,guest=22 ``` ```typescript await box.vm.vms.create({ name: 'web-vm', source: { type: 'template', id: TEMPLATE_ID }, memory_mib: 2048, vcpus: 2, ports: [{ proto: 'tcp', host: 2222, guest: 22 }], }); ``` ```bash curl -X POST "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms" \ -H "Content-Type: application/json" \ -d '{ "name": "web-vm", "source": { "type": "template", "id": "'"$TEMPLATE_ID"'" }, "memory_mib": 2048, "vcpus": 2, "ports": [{ "proto": "tcp", "host": 2222, "guest": 22 }] }' ``` Creates `web-vm` with port 2222 forwarded to its port 22. Replace `TEMPLATE_ID`. To change forwards, stop the VM and update `ports`. The list replaces the old one, so resend every rule. ## See the VM's screen A VM with a `display` number draws on that X display, which [Displays](/kit/displays/) serves in the browser: `display: 5` is at `https://PROJECT_ID-COMPUTER_ID-display-5.SERVER.computers.hoody.com`. Read through its `vm` URL, the VM's `display_url` holds that address. Each VM needs a display of its own, and a number in use is refused with `409 DisplayInUse`. `"auto"` picks the lowest free number from 7001 to 8000 (by default) on create, above the desktop, terminals and browsers. On update, a VM already in that range keeps its number while it is still usable; otherwise it gets the lowest free number. To give a stopped VM a display of its own: ```bash hoody vm update dev-vm --display auto ``` ```typescript const updated = await box.vm.vms.update('dev-vm', { display: 'auto' }); console.log(updated.data.spec.display); // the number it got ``` ```bash curl -X PATCH "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms/dev-vm" \ -H 'Content-Type: application/json' \ -d '{"display": "auto"}' ``` Gives the stopped VM a free display number, shown in `spec.display`. Keys and clicks go to the VM, Alt+Tab included; if keys stop, click its window. Copy and paste with the browser is not supported. Without `display` the VM is headless. The display has its own proxy permissions: access to the VM API alone does not open the screen. See [display rules](/kit/vm/reference/#displays). ## Snapshot and restore a VM Snapshot before a risky change, restore after. A snapshot saves a stopped VM's disk, UEFI varstore and TPM state under a label; the list says whether each fits this VM (`restorable`) and, if not, why (`blocked_reason`). Wait for `Stopped` first: a `Stopping` VM is refused. A successful restore response includes the VM's new `generation`. If your client might stop waiting, open an [event stream](#follow-changes-live) including `snapshot` before the call: a successful restore emits a `snapshot` event with `action: "restored"` and the new generation. The event can be missed if the stream disconnects. ```bash hoody vm snapshots create dev-vm --label before-upgrade hoody vm snapshots list dev-vm # Replaces the VM's disk, varstore and TPM state; asks for confirmation on a terminal hoody vm snapshots restore dev-vm before-upgrade ``` ```typescript await box.vm.snapshots.create('dev-vm', { label: 'before-upgrade' }); const snapshots = await box.vm.snapshots.list('dev-vm'); for (const s of snapshots.data) console.log(s.label, s.restorable, s.blocked_reason); await box.vm.snapshots.restore('dev-vm', 'before-upgrade'); ``` ```bash VMS="https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms" curl -X POST "$VMS/dev-vm/snapshots" \ -H "Content-Type: application/json" \ -d '{ "label": "before-upgrade" }' curl "$VMS/dev-vm/snapshots" # Replaces the VM's disk, varstore and TPM state curl -X POST "$VMS/dev-vm/snapshots/before-upgrade/restore" ``` Each link is one action on the stopped VM. A restore has no undo; configuration, shared folder and other snapshots stay. Do not blindly retry a restore whose answer you missed. ## Get an installer image Installer images (ISOs) live in a store addressed by SHA-256. Download one, then create the VM from its `sha256`. `hoody vm osinfo list` shows installable systems and their image URLs. ```bash hoody vm osinfo list hoody vm isos downloads start --url https://example.com/installer.iso hoody vm isos downloads get DOWNLOAD_ID # poll while running or verifying; stop on a terminal state ``` ```typescript const job = await box.vm.isos.downloads.start({ url: 'https://example.com/installer.iso' }); const status = await box.vm.isos.downloads.get(job.data.id); console.log(status.data.state, status.data.fetched_bytes, status.data.sha256); ``` ```bash curl -X POST "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/isos/downloads" \ -H "Content-Type: application/json" \ -d '{ "url": "https://example.com/installer.iso" }' ``` Starts the download and answers with the job to poll. Poll while `state` is `running` or `verifying`. On `ready`, use `sha256`. On `failed`, `cancelled` or `interrupted`, stop polling and read `error` if present; start a new download when appropriate. Pass the vendor's `sha256` when you have it: a mismatch publishes nothing. Without it, the image is published under its own hash, trusted on first use (`verification: "tofu"`). You can also [upload an image](/kit/vm/reference/#uploading-in-parts). ## Move a VM to another computer Export a snapshot, download its parts, import them on the other computer and create a VM from them. The artifact does not include shared-folder files. The imported VM starts with an empty shared folder; copy those files separately and verify the destination before deleting the original VM: ```bash # On the first computer: the answer gives bytes, part_size, parts and sha256 EXPORT=$(hoody -o json vm snapshots export create dev-vm before-upgrade) SHA=$(echo "$EXPORT" | jq -r '.sha256') BYTES=$(echo "$EXPORT" | jq -r '.bytes') hoody vm snapshots export get dev-vm before-upgrade --part 0 --out-file part-0 # ...repeat for every part, join them in order and check against sha256, then: hoody vm snapshots export delete dev-vm before-upgrade # Select the destination computer export HOODY_COMPUTER="$DESTINATION_COMPUTER_ID" PARTS=$(echo "$EXPORT" | jq -r '.parts') IMPORT=$(hoody -o json vm imports create "$SHA" --bytes "$BYTES") if [ "$(echo "$IMPORT" | jq -r '.phase')" != ready ]; then # ready: already published, skip the upload and finalize NEXT=$(echo "$IMPORT" | jq -r '.next_part // empty') # 0 for a new upload, the resume point otherwise; absent or past the last part once every byte is stored for ((i=${NEXT:-$PARTS}; i&2; exit 1; } done hoody vm imports finalize "$SHA" fi # --bus is required: give the bus the original VM was installed on. # Add --source-duplicate-tpm-identity if the artifact carries TPM state (every Windows 11 guest). hoody vm create --name dev-vm-copy --source-type snapshot-artifact --source-sha256 "$SHA" \ --bus virtio --memory-mib 4096 --vcpus 2 ``` Part transfers are shown in the CLI only. The SDK calls are `box.vm.snapshots.export.create`, `getPart` and `delete`, then `box.vm.imports.create`, `uploadPart` and `finalize`. Give the original `bus`: a guest does not boot from the other one. If the original VM had audio, add `--display auto` to the create command: an imported VM with a sound card needs a display. A copy made with `duplicate_tpm_identity` holds the original's TPM secrets. The [reference](/kit/vm/reference/#snapshots-and-imports) has the rest. ## Read the console, logs and guest agent Read the serial console when a VM has no screen: it is often the only place a failed boot or install shows. A write is typed exactly as sent, so end a command with a newline. ```bash hoody vm console read dev-vm printf 'uname -a\n' | hoody vm console write dev-vm ``` ```typescript const out = await box.vm.console.read('dev-vm'); console.log(new TextDecoder().decode(out.data)); await box.vm.console.write('dev-vm', 'uname -a\n'); ``` ```bash # -D - prints the cursor and gap headers curl -D - "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms/dev-vm/console" curl -X POST "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms/dev-vm/console" \ --data-binary $'uname -a\n' ``` Read returns console output. Type a command sends `uname -a` and a newline. Many guests' consoles are a root shell, so treat write access like shell access. Output is untrusted guest data. The console gives raw live output. `hoody vm logs get dev-vm --source console` gives cleaned console text, or a helper's log with `qemu`, `passt`, `swtpm` or `virtiofsd`. With the QEMU guest agent, `hoody vm guestagent inventory get dev-vm` reports the guest's OS, addresses and users. See the [details](/kit/vm/reference/#console-logs-and-guest-agent). ## Follow changes live Two Server-Sent Events streams push changes as they happen, as an alternative to polling. `GET /api/v1/vm/vms/{name}/events` follows one VM, opening with a `state` frame. `GET /api/v1/vm/events` (`hoody vm events stream` with no VM name) follows every VM, new ones too, with no opening state. `?events=state,snapshot` filters kinds. ```bash hoody vm events stream dev-vm --events state,snapshot ``` ```typescript const stream = await box.vm.events.stream('dev-vm', { events: 'state,snapshot' }); for await (const frame of stream) { if (frame.declared) console.log(frame.event, frame.data); } ``` ```bash curl -N "https://$PROJECT_ID-$COMPUTER_ID-vm-1.$SERVER.computers.hoody.com/api/v1/vm/vms/dev-vm/events?events=state,snapshot" ``` Nothing is replayed: after a disconnect, open a new stream and read the current state. The CLI reconnects unless given `--no-reconnect`. A slow reader gets `resync`: read the state again. ## Advanced - **Change a stopped VM:** `hoody vm update` changes memory, CPUs, disk size, CD-ROMs and more for the next start. See [reconfigure](/kit/vm/reference/#reconfigure-a-stopped-vm). - **Clone a VM:** a `vm-disk` source gives you a copy to test on. See [Create a VM](/api/vm/vms/#create-a-vm). - **Shared folder:** `share: true` shares a `share/` folder with the guest, with an optional quota. See the [VMs API](/api/vm/vms/#create-a-vm). - **Disk limits:** `disk_bps` and `disk_iops` cap disk throughput. See the [VMs API](/api/vm/vms/#create-a-vm). - **Templates:** `hoody vm templates list` lists templates, with the drivers their OS needs. See the [service API](/api/vm/#list-vm-templates). - **KVM for new computers:** set `kvm` when you create or copy a computer on a rented dedicated server; a copy never inherits it. See [computers](/api/computers/) and [copy](/api/computer-copy-sync/). - **View of every VM:** keep a correct list from the all-VMs stream. See [the steps](/kit/vm/reference/#a-view-of-every-vm). - **Recovery:** adopt or mark dead an `Orphaned` VM or a run holding memory under no VM name. See [recovery](/kit/vm/reference/#recovery). - **Health and metrics:** `hoody vm health` checks the service; `hoody vm metrics` gives Prometheus text. See [health and metrics](/kit/vm/reference/#health-and-metrics). - **Delete:** `hoody vm delete` removes the VM, its snapshots and its shared-folder files. Download backups and copy shared files elsewhere first. See what each [destructive operation](/kit/vm/reference/#destructive-operations) loses. ## Reference The [Virtual Machines reference](/kit/vm/reference/) holds hardware fields, states, display rules, event details, destructive operations and [troubleshooting](/kit/vm/reference/#troubleshooting). ## What's Next - [VM API reference](/api/vm/): every endpoint, parameter and error - [Lifecycle API](/api/vm/lifecycle/): start, stop, pause and resume - [Events API](/api/vm/events/): follow one VM or every VM - [Displays](/kit/displays/): see and control a VM's screen in the browser