| 1 | import { VMMenu } from "../components/VMMenu.tsx"; |
| 2 | import { useSearchParams } from "@solidjs/router"; |
| 3 | import CircuitBoard from "lucide-solid/icons/circuit-board"; |
| 4 | import HardDrive from "lucide-solid/icons/hard-drive"; |
| 5 | import Network from "lucide-solid/icons/network"; |
| 6 | import Monitor from "lucide-solid/icons/monitor"; |
| 7 | import SquareTerminal from "lucide-solid/icons/square-terminal"; |
| 8 | import Plus from "lucide-solid/icons/plus"; |
| 9 | import Power from "lucide-solid/icons/power"; |
| 10 | import Play from "lucide-solid/icons/play"; |
| 11 | import Disc3 from "lucide-solid/icons/disc-3"; |
| 12 | import Disc2 from "lucide-solid/icons/disc-2"; |
| 13 | import RotateCw from "lucide-solid/icons/rotate-cw"; |
| 14 | import Save from "lucide-solid/icons/save"; |
| 15 | import Trash from "lucide-solid/icons/trash"; |
| 16 | import Square from "lucide-solid/icons/square"; |
| 17 | import KeyRound from "lucide-solid/icons/key-round"; |
| 18 | import Usb from "lucide-solid/icons/usb"; |
| 19 | import { createEffect, createMemo, createResource, createSignal, For, lazy, onCleanup, Show } from "solid-js"; |
| 20 | import { LIVE_INTERVAL } from "../types/model.ts"; |
| 21 | import type { Domain, DOMAIN_ACTIONS, Hostdev, VMLibrary } from "../types/vms.ts"; |
| 22 | import { DetailedError, parseResponse } from "hono/client"; |
| 23 | import { api, queries, reason, unconnected } from "../api.ts"; |
| 24 | import { VMConsole } from "../components/VMConsole.tsx"; |
| 25 | import { Checkbox } from "../components/Checkbox.tsx"; |
| 26 | import { Copy } from "../components/Copy.tsx"; |
| 27 | import { showConfirmDialog, showTextDialog } from "../components/Dialog.tsx"; |
| 28 | import { ListPage } from "../components/ListPage.tsx"; |
| 29 | import { lastGood, Loaded } from "../components/Loaded.tsx"; |
| 30 | import { Meter } from "../components/Meter.tsx"; |
| 31 | import { type StatusKind, StatusLabel } from "../components/Status.tsx"; |
| 32 | import { TimeChart } from "../components/TimeChart.tsx"; |
| 33 | import { TabBar } from "../components/TabBar.tsx"; |
| 34 | import { toast } from "../components/Toast.tsx"; |
| 35 | import { bytes, datetime, duration, percent, plural } from "../format.ts"; |
| 36 | import "./VMs.css"; |
| 37 | |
| 38 | const VMSerial = lazy(() => import("../components/VMSerial.tsx")); |
| 39 | |
| 40 | const GiB = 2 ** 30; |
| 41 | /** A guest whose agent hasn't answered this long after power-on counts as up anyway; many never install one. */ |
| 42 | const STARTING = 180; |
| 43 | |
| 44 | const REASONS: Record<string, string> = { |
| 45 | user: "paused manually", |
| 46 | ioerror: "paused after a disk error, check the vms pool's free space", |
| 47 | watchdog: "paused by its watchdog", |
| 48 | panicked: "the guest kernel panicked", |
| 49 | }; |
| 50 | |
| 51 | const isOff = (vm: Domain) => vm.state === "shutoff" || vm.state === "crashed"; |
| 52 | const running = (vm: Domain) => vm.state === "running" || vm.state === "blocked"; |
| 53 | |
| 54 | function status(vm: Domain): [StatusKind, string, tip?: string] { |
| 55 | if (running(vm)) { |
| 56 | if (vm.startedAt === null) return ["healthy", "up"]; |
| 57 | const up = Date.now() / 1000 - vm.startedAt!; |
| 58 | const started = `started ${datetime(vm.startedAt!)}`; |
| 59 | if (vm.agent !== "disconnected") return ["healthy", `up ${duration(up)}`, started]; |
| 60 | if (up < STARTING) return ["starting", "starting", started]; |
| 61 | return ["healthy", `up ${duration(up)}`, `${started}, guest agent not answering`]; |
| 62 | } |
| 63 | const tip = vm.reason ? REASONS[vm.reason] ?? vm.reason : undefined; |
| 64 | switch (vm.state) { |
| 65 | case "paused": return ["stopped", "paused", tip]; |
| 66 | case "pmsuspended": return ["stopped", "asleep", tip]; |
| 67 | case "shutdown": return ["restarting", "stopping"]; |
| 68 | case "crashed": return ["down", "crashed", tip]; |
| 69 | default: return ["stopped", "off"]; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /** "/dev/disk/by-id/nvme-Samsung_SSD_980_PRO_1TB_S5GX…" reads as "Samsung SSD 980 PRO 1TB": no bus, no serial. */ |
| 74 | const drive = (path: string) => path.split("/").at(-1)!.replace(/^[a-z]+-/, "").replace(/_[^_]+$/, "").replaceAll("_", " "); |
| 75 | |
| 76 | /** [8, 9, 10, 12] reads "8–10, 12". */ |
| 77 | const threads = (list: number[]) => list |
| 78 | .reduce<[number, number][]>((runs, n) => { |
| 79 | const last = runs.at(-1); |
| 80 | if (last && n === last[1] + 1) last[1] = n; |
| 81 | else runs.push([n, n]); |
| 82 | return runs; |
| 83 | }, []) |
| 84 | .map(([from, to]) => (from === to ? `${from}` : `${from}–${to}`)) |
| 85 | .join(", "); |
| 86 | |
| 87 | /** Current and max memory, like "16 GiB", or "8–12 GiB" while the balloon holds some back. */ |
| 88 | const allocated = (vm: Domain) => (vm.balloon < vm.memory ? `${+(vm.balloon / GiB).toFixed(1)}–${bytes(vm.memory)}` : bytes(vm.memory)); |
| 89 | |
| 90 | /** Remote desktop for Windows, the web UI for Home Assistant, ssh for the rest. */ |
| 91 | function remote(os: string, address: string): [href: string, label: string] { |
| 92 | const host = address.includes(":") ? `[${address}]` : address; |
| 93 | if (os.startsWith("Windows")) return [`rdp://full%20address=s:${host}:3389`, "rdp"]; |
| 94 | if (os.startsWith("Home Assistant")) return [`http://${host}:8123`, "open"]; |
| 95 | return [`ssh://${host}`, "ssh"]; |
| 96 | } |
| 97 | |
| 98 | /** Devices sharing an IOMMU group pass through together, so a GPU and its audio function read as one. */ |
| 99 | function groups(devices: Hostdev[]) { |
| 100 | const byGroup = new Map<number | Hostdev, Hostdev[]>(); |
| 101 | for (const dev of devices) byGroup.set(dev.iommuGroup ?? dev, [...(byGroup.get(dev.iommuGroup ?? dev) ?? []), dev]); |
| 102 | return [...byGroup.values()]; |
| 103 | } |
| 104 | |
| 105 | async function act(vm: Domain, action: (typeof DOMAIN_ACTIONS)[number], refetch: () => unknown) { |
| 106 | await parseResponse(api.vms[":name"][":action"].$post({ param: { name: vm.name, action } })); |
| 107 | await refetch(); |
| 108 | } |
| 109 | |
| 110 | const stop = (vm: Domain, refetch: () => unknown) => showConfirmDialog({ |
| 111 | title: `Stop ${vm.name}?`, |
| 112 | description: `${vm.name} shuts down as if its power button were pressed. If it hangs, force it off.`, |
| 113 | confirmLabel: "stop", |
| 114 | destructive: true, |
| 115 | onConfirm: () => act(vm, "shutdown", refetch), |
| 116 | }); |
| 117 | |
| 118 | const restart = (vm: Domain, refetch: () => unknown) => showConfirmDialog({ |
| 119 | title: `Restart ${vm.name}?`, |
| 120 | description: `${vm.name} shuts down and boots again. Anyone using it is interrupted.`, |
| 121 | confirmLabel: "restart", |
| 122 | onConfirm: () => act(vm, "reboot", refetch), |
| 123 | }); |
| 124 | |
| 125 | const forceOff = (vm: Domain, refetch: () => unknown) => showConfirmDialog({ |
| 126 | title: `Force off ${vm.name}?`, |
| 127 | description: `${vm.name} loses power without shutting down. Unsaved work in it is lost.`, |
| 128 | confirmLabel: "force off", |
| 129 | destructive: true, |
| 130 | onConfirm: () => act(vm, "destroy", refetch), |
| 131 | }); |
| 132 | |
| 133 | const describe = (vm: Domain, refetch: () => unknown) => showTextDialog({ |
| 134 | title: `Describe ${vm.name}`, |
| 135 | label: "what it's for", |
| 136 | placeholder: "game streaming to the TV…", |
| 137 | initialValue: vm.description, |
| 138 | validateInput: () => true, |
| 139 | confirmLabel: "save", |
| 140 | onConfirm: async (description) => { |
| 141 | await parseResponse(api.vms[":name"].$patch({ param: { name: vm.name }, json: { description } })); |
| 142 | await refetch(); |
| 143 | }, |
| 144 | }); |
| 145 | |
| 146 | function remove(vm: Domain, refetch: () => unknown) { |
| 147 | const volumes = vm.disks.filter((disk) => disk.pool); |
| 148 | const size = bytes(volumes.reduce((sum, disk) => sum + disk.capacity, 0)); |
| 149 | showConfirmDialog({ |
| 150 | title: `Delete ${vm.name}?`, |
| 151 | description: () => ( |
| 152 | <> |
| 153 | <p>{isOff(vm) ? "" : `${vm.name} is forced off first. `}<Show when={volumes.length}>Its managed disks ({size}) will be deleted. </Show>This can't be undone.</p> |
| 154 | <Show when={vm.disks.length > volumes.length}><p>Passed-through drives are left as they are.</p></Show> |
| 155 | </> |
| 156 | ), |
| 157 | confirmLabel: "delete", |
| 158 | destructive: true, |
| 159 | onConfirm: async () => { |
| 160 | await parseResponse(api.vms[":name"].$delete({ param: { name: vm.name }, query: { disks: "1" } })); |
| 161 | await refetch(); |
| 162 | }, |
| 163 | }); |
| 164 | } |
| 165 | |
| 166 | function uploadIso(refetch: () => unknown, onUploaded?: (volume: string) => void) { |
| 167 | let progress: (value: number) => void = () => {}; |
| 168 | showConfirmDialog({ |
| 169 | title: "Upload ISO", |
| 170 | confirmLabel: "upload", |
| 171 | body: () => { |
| 172 | const [percent, setPercent] = createSignal<number | null>(null); |
| 173 | progress = setPercent; |
| 174 | return <> |
| 175 | <label class="field">ISO file<input name="iso" class="search" type="file" accept=".iso" required /></label> |
| 176 | <span class="hint">Up to 32 GiB. The ISO stays in your library for future VMs</span> |
| 177 | <Show when={percent() !== null}><div class="vm-upload-progress" role="status"> |
| 178 | <progress max="100" value={percent()!} /> |
| 179 | <span>{percent() === 100 ? "Saving…" : `Uploading… ${percent()}%`}</span> |
| 180 | </div></Show> |
| 181 | </>; |
| 182 | }, |
| 183 | onConfirm: async (form) => { |
| 184 | const file = form.get("iso"); |
| 185 | if (!(file instanceof File) || !file.name.toLowerCase().endsWith(".iso")) throw new DetailedError("Choose an ISO file.", { detail: { data: "Choose an ISO file." } }); |
| 186 | if (file.size < 32768 || file.size > 32 * GiB) throw new DetailedError("Choose an ISO between 32 KiB and 32 GiB.", { detail: { data: "Choose an ISO between 32 KiB and 32 GiB." } }); |
| 187 | progress(0); |
| 188 | const volume = await new Promise<string>((resolve, reject) => { |
| 189 | const upload = new XMLHttpRequest(); |
| 190 | upload.open("PUT", `/api/vms/iso?name=${encodeURIComponent(file.name)}`); |
| 191 | upload.upload.onprogress = (event) => event.lengthComputable && progress(Math.round(event.loaded / event.total * 100)); |
| 192 | upload.onload = async () => { |
| 193 | try { |
| 194 | const value = upload.getResponseHeader("content-type")?.includes("json") ? JSON.parse(upload.responseText) : upload.responseText; |
| 195 | if (upload.status < 200 || upload.status >= 300) throw new DetailedError("ISO upload", { statusCode: upload.status, detail: { data: value } }); |
| 196 | if (typeof value?.volume !== "string") throw new Error("Missing ISO identity"); |
| 197 | resolve(value.volume); |
| 198 | } catch (failure) { reject(failure); } |
| 199 | }; |
| 200 | upload.onerror = () => reject(new DetailedError("Upload interrupted", { detail: { data: "The upload was interrupted. Check your connection and try again." } })); |
| 201 | upload.send(file); |
| 202 | }); |
| 203 | await refetch(); |
| 204 | onUploaded?.(volume); |
| 205 | }, |
| 206 | }); |
| 207 | } |
| 208 | |
| 209 | function create(node: { cpus: number; memory: number; availableMemory: number }, library: () => VMLibrary, domains: Domain[], refetch: () => unknown, onCreated: (name: string) => void) { |
| 210 | const installers = () => library().installers.filter((item) => item.arch === library().arch); |
| 211 | showConfirmDialog({ |
| 212 | title: "New virtual machine", |
| 213 | confirmLabel: "create vm", |
| 214 | body: () => { |
| 215 | const suffix = Array.from(crypto.getRandomValues(new Uint8Array(4)), (byte) => byte.toString(16).padStart(2, "0")).join(""); |
| 216 | const [choice, setChoice] = createSignal(library().presets[0]?.id ?? ""); |
| 217 | const [iso, setIso] = createSignal(installers()[0]?.volume ?? "blank"); |
| 218 | const selected = () => library().presets.find((item) => item.id === choice()); |
| 219 | const generatedName = () => `testbox-${(choice() || "custom").slice(0, 46)}-${suffix}`; |
| 220 | const [name, setName] = createSignal(generatedName()); |
| 221 | const recommended = () => selected()?.recommended ?? { vcpus: 2, memory: 4 * GiB, disk: 32 * GiB }; |
| 222 | const [vcpus, setVcpus] = createSignal(Math.min(node.cpus, recommended().vcpus)); |
| 223 | const [memory, setMemory] = createSignal(Math.min(node.memory, recommended().memory) / GiB); |
| 224 | const [disk, setDisk] = createSignal(Math.ceil(recommended().disk / GiB)); |
| 225 | const minimumDisk = () => Math.max(1, Math.ceil((selected()?.capacity ?? 0) / GiB)); |
| 226 | const installer = () => installers().find((item) => item.volume === iso()); |
| 227 | const problem = () => domains.some((vm) => vm.name === name()) ? `${name()} already exists. Pick another name` : ""; |
| 228 | return <div class="vm-create"> |
| 229 | <input type="hidden" name="mode" value={selected() ? "preset" : "iso"} /> |
| 230 | <input type="hidden" name="image" value={selected()?.id ?? iso()} /> |
| 231 | <label class="field">OS Preset<select class="search" onChange={(event) => { |
| 232 | const previousName = generatedName(); |
| 233 | setChoice(event.currentTarget.value); |
| 234 | if (name() === previousName) setName(generatedName()); |
| 235 | setVcpus(Math.min(node.cpus, recommended().vcpus)); |
| 236 | setMemory(Math.min(node.memory, recommended().memory) / GiB); |
| 237 | setDisk(Math.ceil(recommended().disk / GiB)); |
| 238 | }}> |
| 239 | <For each={library().presets}>{(item) => <option value={item.id} selected={choice() === item.id}>{item.os}</option>}</For> |
| 240 | <option value="" selected={!choice()}>Custom (Upload ISO)</option> |
| 241 | </select></label> |
| 242 | <Show when={!selected()}> |
| 243 | <div class="vm-custom-iso"> |
| 244 | <label class="field">Installer ISO<select class="search" onChange={(event) => setIso(event.currentTarget.value)}> |
| 245 | <For each={installers()}>{(item) => <option value={item.volume} selected={iso() === item.volume}>{item.os}</option>}</For> |
| 246 | <option value="blank" selected={iso() === "blank"}>Attach an ISO later</option> |
| 247 | </select></label> |
| 248 | <button type="button" class="button small" onClick={() => uploadIso(refetch, setIso)}>upload ISO</button> |
| 249 | </div> |
| 250 | </Show> |
| 251 | <label class="field">name<input name="name" class="search" required pattern="[a-z0-9][a-z0-9\-]{0,62}" value={name()} |
| 252 | autocomplete="off" spellcheck={false} aria-invalid={!!problem()} aria-describedby="vm-name-problem" |
| 253 | ref={(input) => createEffect(() => input.setCustomValidity(problem()))} onInput={(event) => setName(event.currentTarget.value)} /> |
| 254 | <Show when={problem()}><span id="vm-name-problem" class="error">{problem()}</span></Show> |
| 255 | </label> |
| 256 | <div class="vm-resources"> |
| 257 | <label class="vm-resource"><span>CPUs<output>{vcpus()}</output></span> |
| 258 | <input name="vcpus" aria-label="CPUs" type="range" min="1" max={node.cpus} value={vcpus()} onInput={(event) => setVcpus(Number(event.currentTarget.value))} /> |
| 259 | <span class="vm-resource-scale"><span>1</span><span>{node.cpus}</span></span> |
| 260 | </label> |
| 261 | <label class="vm-resource"><span>Memory<output>{bytes(memory() * GiB)}</output></span> |
| 262 | <input name="memory" aria-label="Memory" type="range" min="0.5" max={Math.floor(node.memory / GiB)} step="0.5" value={memory()} onInput={(event) => setMemory(Number(event.currentTarget.value))} /> |
| 263 | <span class="vm-resource-scale"><span>512 MiB</span><span>{bytes(node.availableMemory)} unallocated</span></span> |
| 264 | </label> |
| 265 | <label class="vm-resource"><span>Disk<output>{bytes(disk() * GiB)}</output></span> |
| 266 | <input name="disk" aria-label="Disk" type="range" min={minimumDisk()} max={Math.max(1024, minimumDisk() * 2)} value={disk()} onInput={(event) => setDisk(Number(event.currentTarget.value))} /> |
| 267 | <span class="vm-resource-scale"><span>{bytes(minimumDisk() * GiB)}</span><span>{bytes(Math.max(1024, minimumDisk() * 2) * GiB)}</span></span> |
| 268 | </label> |
| 269 | </div> |
| 270 | <Show when={!selected()} fallback={<> |
| 271 | <input type="hidden" name="firmware" value={selected()?.firmware ?? "bios"} /> |
| 272 | <input type="hidden" name="platform" value={selected()?.platform ?? "linux"} /> |
| 273 | </>}> |
| 274 | <details class="vm-hardware"><summary>Hardware settings</summary><div class="row"> |
| 275 | <label class="field">firmware<select name="firmware" class="search" value={/windows (xp|vista|7|8)/i.test(installer()?.os ?? "") ? "bios" : "uefi"}><option value="uefi">UEFI</option><option value="bios">Legacy BIOS</option></select></label> |
| 276 | <label class="field">guest hardware<select name="platform" class="search" value={/windows|win11|win10/i.test(installer()?.os ?? "") ? "windows" : "linux"}><option value="linux">Linux (VirtIO)</option><option value="windows">Windows (SATA)</option></select></label> |
| 277 | </div></details> |
| 278 | </Show> |
| 279 | <Show when={!selected()}><p class="hint">Created powered off. Use the Machine menu to boot your installer</p></Show> |
| 280 | </div>; |
| 281 | }, |
| 282 | onConfirm: async (form) => { |
| 283 | const name = String(form.get("name")); |
| 284 | await parseResponse(api.vms.$post({ json: { |
| 285 | name, image: String(form.get("image")), mode: form.get("mode") === "preset" ? "preset" : "iso", |
| 286 | firmware: form.get("firmware") === "uefi" ? "uefi" : "bios", platform: form.get("platform") === "windows" ? "windows" : "linux", |
| 287 | vcpus: Number(form.get("vcpus")), memory: Math.round(Number(form.get("memory")) * GiB), disk: Math.round(Number(form.get("disk")) * GiB), |
| 288 | } })); |
| 289 | await refetch(); |
| 290 | onCreated(name); |
| 291 | }, |
| 292 | }); |
| 293 | } |
| 294 | function attachIso(vm: Domain, library: () => VMLibrary, refetch: () => unknown) { |
| 295 | const [image, setImage] = createSignal(""); |
| 296 | showConfirmDialog({ |
| 297 | title: `Attach ISO to ${vm.name}`, |
| 298 | confirmLabel: "attach ISO", |
| 299 | canConfirm: () => !!image(), |
| 300 | body: () => <> |
| 301 | <label class="field">Installer ISO<select name="image" class="search" required value={image()} onChange={(event) => setImage(event.currentTarget.value)}> |
| 302 | <option value="">Choose an installer</option> |
| 303 | <For each={library().installers.filter((item) => item.arch === library().arch)}>{(item) => <option value={item.volume}>{item.os}</option>}</For> |
| 304 | </select></label> |
| 305 | <button type="button" class="button small" onClick={() => uploadIso(refetch)}>upload ISO</button> |
| 306 | </>, |
| 307 | onConfirm: async (form) => { |
| 308 | await parseResponse(api.vms[":name"].media.$put({ param: { name: vm.name }, json: { image: String(form.get("image")) } })); |
| 309 | await refetch(); |
| 310 | }, |
| 311 | }); |
| 312 | } |
| 313 | |
| 314 | function savePreset(vm: Domain, refetch: () => unknown) { |
| 315 | showConfirmDialog({ |
| 316 | title: `Save ${vm.name} as preset`, |
| 317 | description: "New VMs start from this prepared OS. Finish setup and remove private files before saving.", |
| 318 | confirmLabel: "save preset", |
| 319 | body: () => <> |
| 320 | <label class="field">preset ID<input name="id" class="search" required pattern="[a-z0-9][a-z0-9\-]{0,62}" value={vm.name} /></label> |
| 321 | <label class="field">operating system<input name="os" class="search" required maxlength="100" value={vm.os} /></label> |
| 322 | <label class="field">description<input name="description" class="search" maxlength="200" value={vm.description} /></label> |
| 323 | </>, |
| 324 | onConfirm: async (form) => { |
| 325 | await parseResponse(api.vms[":name"].preset.$post({ param: { name: vm.name }, json: { id: String(form.get("id")), os: String(form.get("os")), description: String(form.get("description")) } })); |
| 326 | await refetch(); |
| 327 | }, |
| 328 | }); |
| 329 | } |
| 330 | |
| 331 | function Hardware(props: { vm: Domain; refetch: () => unknown; username?: string; hostname?: string }) { |
| 332 | const [history, { refetch }] = createResource(() => props.vm.name, (name) => |
| 333 | parseResponse(api.vms.history.$get({ query: { range: "3600", name } }))); |
| 334 | const timer = setInterval(refetch, 30_000); |
| 335 | onCleanup(() => clearInterval(timer)); |
| 336 | const [saving, setSaving] = createSignal(false); |
| 337 | const setAutostart = async (autostart: boolean) => { |
| 338 | setSaving(true); |
| 339 | try { |
| 340 | await parseResponse(api.vms[":name"].$patch({ param: { name: props.vm.name }, json: { autostart } })); |
| 341 | await props.refetch(); |
| 342 | } catch (failure) { |
| 343 | toast(`Couldn't change autostart. ${reason(failure)}`); |
| 344 | } finally { |
| 345 | setSaving(false); |
| 346 | } |
| 347 | }; |
| 348 | return ( |
| 349 | <div class="vm-detail"> |
| 350 | <div class="vm-media"> |
| 351 | <span class="muted">CD drive</span> |
| 352 | <span class="source">{props.vm.media.find((item) => item.source)?.source ?? "No ISO attached"}</span> |
| 353 | <span class="spacer" /><span class="muted">{props.vm.firmware === "uefi" ? "UEFI" : "Legacy BIOS"}</span> |
| 354 | </div> |
| 355 | <Loaded data={history} what="usage history" retry={refetch} skeleton={ |
| 356 | <div class="vm-charts"><div class="skeleton" /><div class="skeleton" /></div> |
| 357 | }> |
| 358 | {(latest) => { |
| 359 | const samples = () => latest().domains[props.vm.name]; |
| 360 | return ( |
| 361 | <Show when={samples()?.cpu.some((v) => v !== null)} fallback={<p class="off-hour">Off for the last hour</p>}> |
| 362 | <div class="vm-charts"> |
| 363 | <TimeChart series={[{ name: "cpu", t: latest().t, v: samples()!.cpu }]} format={percent} max={100} |
| 364 | colors={["var(--series-1)"]} height={104} inline sync={`vm-${props.vm.name}`} /> |
| 365 | <TimeChart series={[{ name: "memory", t: latest().t, v: samples()!.memory }]} format={bytes} max={props.vm.memory} |
| 366 | colors={["var(--series-2)"]} height={104} inline sync={`vm-${props.vm.name}`} /> |
| 367 | </div> |
| 368 | </Show> |
| 369 | ); |
| 370 | }} |
| 371 | </Loaded> |
| 372 | <div class="facts"> |
| 373 | <div class="settings"> |
| 374 | <dl class="kv"> |
| 375 | <Show when={props.username}><dt>guest user</dt><dd>{props.username}</dd></Show> |
| 376 | <Show when={props.hostname}>{(hostname) => <><dt>hostname</dt><dd><Copy value={hostname()} /></dd></>}</Show> |
| 377 | <dt>for</dt> |
| 378 | <dd> |
| 379 | <button class="describe" classList={{ empty: !props.vm.description }} data-tip="edit" |
| 380 | onClick={() => describe(props.vm, props.refetch)}> |
| 381 | {props.vm.description || "add a description"} |
| 382 | </button> |
| 383 | </dd> |
| 384 | <dt>autostart</dt> |
| 385 | <dd> |
| 386 | <Checkbox checked={props.vm.autostart} disabled={saving()} onChange={setAutostart}>start with the host</Checkbox> |
| 387 | </dd> |
| 388 | <dt>cpu</dt> |
| 389 | <dd>{props.vm.pinned ? `pinned to threads ${threads(props.vm.pinned)}` : "floats over all threads"}</dd> |
| 390 | </dl> |
| 391 | </div> |
| 392 | <dl class="kv"> |
| 393 | <dt>disks</dt> |
| 394 | <dd class="lines disks"> |
| 395 | <For each={props.vm.disks}> |
| 396 | {(disk) => ( |
| 397 | <div> |
| 398 | <span class="muted mono">{disk.target}</span> |
| 399 | <span class="source" classList={{ mono: !!disk.pool }}> |
| 400 | <Copy value={disk.source} label={disk.pool ? "volume name" : "device path"}> |
| 401 | {disk.pool ? disk.source : drive(disk.source)} |
| 402 | </Copy> |
| 403 | </span> |
| 404 | <Show when={disk.pool} fallback={<span class="muted used">whole drive</span>}> |
| 405 | <span class="used" data-tip={`${bytes(disk.allocation)} / ${bytes(disk.capacity)} (${percent((disk.allocation / disk.capacity) * 100)})`}> |
| 406 | <Meter value={disk.allocation} max={disk.capacity} /> |
| 407 | </span> |
| 408 | </Show> |
| 409 | <span class="num">{bytes(disk.capacity)}</span> |
| 410 | </div> |
| 411 | )} |
| 412 | </For> |
| 413 | </dd> |
| 414 | <dt>network</dt> |
| 415 | <dd class="lines nics"> |
| 416 | <For each={props.vm.interfaces}> |
| 417 | {(nic) => ( |
| 418 | <div> |
| 419 | <span class="muted mono">{nic.source}</span> |
| 420 | <span class="mono"> |
| 421 | <Show when={nic.addresses[0]} fallback={<span class="muted">{running(props.vm) ? "no address" : ""}</span>}> |
| 422 | {(address) => <Copy value={address()} />} |
| 423 | </Show> |
| 424 | </span> |
| 425 | <span class="mono muted"><Copy value={nic.mac} label="MAC address" /></span> |
| 426 | </div> |
| 427 | )} |
| 428 | </For> |
| 429 | </dd> |
| 430 | <Show when={props.vm.hostdevs.length}> |
| 431 | <dt>passthrough</dt> |
| 432 | <dd class="lines devices"> |
| 433 | <For each={props.vm.hostdevs}> |
| 434 | {(dev) => ( |
| 435 | <div> |
| 436 | <span class="mono muted"><Copy value={dev.address}>{dev.address.replace(/^0000:/, "")}</Copy></span> |
| 437 | <span>{dev.name}</span> |
| 438 | </div> |
| 439 | )} |
| 440 | </For> |
| 441 | </dd> |
| 442 | </Show> |
| 443 | </dl> |
| 444 | </div> |
| 445 | </div> |
| 446 | ); |
| 447 | } |
| 448 | |
| 449 | function PowerControls(props: { vm: Domain; refetch: () => unknown }) { |
| 450 | const [pending, setPending] = createSignal(false); |
| 451 | const run = async (action: "start" | "resume") => { |
| 452 | setPending(true); |
| 453 | try { |
| 454 | await act(props.vm, action, props.refetch); |
| 455 | } catch (failure) { |
| 456 | toast(`Couldn't ${action} ${props.vm.name}. ${reason(failure)}`); |
| 457 | } finally { |
| 458 | setPending(false); |
| 459 | } |
| 460 | }; |
| 461 | return <> |
| 462 | <Show when={isOff(props.vm)}> |
| 463 | <button class="button small" disabled={pending()} aria-busy={pending()} onClick={() => run("start")}><Play size={14} aria-hidden="true" />start</button> |
| 464 | </Show> |
| 465 | <Show when={props.vm.state === "paused" || props.vm.state === "pmsuspended"}> |
| 466 | <button class="button small" disabled={pending()} aria-busy={pending()} onClick={() => run("resume")}><Play size={14} aria-hidden="true" />resume</button> |
| 467 | </Show> |
| 468 | <Show when={props.vm.state === "shutdown"}> |
| 469 | <button class="button small danger" onClick={() => forceOff(props.vm, props.refetch)}><Square size={14} aria-hidden="true" />force off</button> |
| 470 | </Show> |
| 471 | <Show when={running(props.vm)}> |
| 472 | <button class="button small" onClick={() => stop(props.vm, props.refetch)}><Power size={14} aria-hidden="true" />stop</button> |
| 473 | </Show> |
| 474 | </>; |
| 475 | } |
| 476 | |
| 477 | function Row(props: { |
| 478 | vm: Domain; |
| 479 | hostCpus: number; |
| 480 | onOpen: () => void; |
| 481 | refetch: () => unknown; |
| 482 | }) { |
| 483 | const state = () => status(props.vm); |
| 484 | const pinned = () => props.vm.pinned && `pinned to threads ${threads(props.vm.pinned)}`; |
| 485 | const cpuTip = () => { |
| 486 | if (!props.vm.usage) return pinned() || undefined; |
| 487 | const busy = (props.vm.usage.cpu / 100) * props.vm.vcpus; |
| 488 | return [`${busy.toFixed(1)} of ${props.vm.vcpus} vcpus busy, ${percent((busy / props.hostCpus) * 100)} of the host`, pinned()] |
| 489 | .filter(Boolean).join(", "); |
| 490 | }; |
| 491 | const memoryTip = () => { |
| 492 | const used = props.vm.usage?.memory; |
| 493 | const grows = props.vm.balloon < props.vm.memory && `can grow to ${bytes(props.vm.memory)}`; |
| 494 | if (used === undefined) return grows ? `boots with ${bytes(props.vm.balloon)}, ${grows}` : undefined; |
| 495 | return [`${bytes(used)} / ${bytes(props.vm.balloon)} (${percent((used / props.vm.balloon) * 100)})`, grows] |
| 496 | .filter(Boolean).join(", "); |
| 497 | }; |
| 498 | return ( |
| 499 | <tbody class="vm" classList={{ off: isOff(props.vm) }} onClick={props.onOpen}> |
| 500 | <tr class="top"> |
| 501 | <td class="title"> |
| 502 | <button> |
| 503 | <span class="vm-name">{props.vm.name}</span> |
| 504 | <Show when={props.vm.description}><span class="for">{props.vm.description}</span></Show> |
| 505 | </button> |
| 506 | </td> |
| 507 | <td class="state" tabindex={state()[2] ? 0 : undefined} data-tip={state()[2]}> |
| 508 | <StatusLabel health={state()[0]}>{state()[1]}</StatusLabel> |
| 509 | </td> |
| 510 | <td class="num" data-tip={cpuTip()}>{props.vm.usage && percent(props.vm.usage.cpu)}</td> |
| 511 | <td class="num" data-tip={memoryTip()}>{props.vm.usage && bytes(props.vm.usage.memory)}</td> |
| 512 | <td class="actions" rowspan="2" onClick={(event) => event.stopPropagation()}> |
| 513 | <div> |
| 514 | <Show when={!isOff(props.vm) && props.vm.console}><button onClick={props.onOpen}>screen</button></Show> |
| 515 | <Show when={running(props.vm) && props.vm.interfaces.flatMap((nic) => nic.addresses)[0]}> |
| 516 | {(value) => { |
| 517 | const target = () => remote(props.vm.os, value()); |
| 518 | return <a href={target()[0]} target="_blank" rel="noreferrer">{target()[1]}</a>; |
| 519 | }} |
| 520 | </Show> |
| 521 | <PowerControls vm={props.vm} refetch={props.refetch} /> |
| 522 | </div> |
| 523 | </td> |
| 524 | </tr> |
| 525 | <tr class="bottom"> |
| 526 | <td class="specs" colspan="2"> |
| 527 | <div onClick={(event) => event.stopPropagation()}> |
| 528 | <span>{props.vm.os}</span> |
| 529 | <For each={props.vm.interfaces}> |
| 530 | {(nic) => ( |
| 531 | <span> |
| 532 | <Network size={12} aria-label={nic.source} /> |
| 533 | <Show when={nic.addresses[0]} fallback={nic.source}>{(value) => <span class="mono"><Copy value={value()} /></span>}</Show> |
| 534 | </span> |
| 535 | )} |
| 536 | </For> |
| 537 | <For each={groups(props.vm.hostdevs)}> |
| 538 | {(group) => ( |
| 539 | <span tabindex="0" data-tip={[ |
| 540 | group[0]!.address.replace(/^0000:/, ""), |
| 541 | group[0]!.iommuGroup !== null && `iommu group ${group[0]!.iommuGroup}`, |
| 542 | ...group.slice(1).map((dev) => `with ${dev.address.replace(/^0000:/, "")} ${dev.name}`), |
| 543 | ].filter(Boolean).join(", ")}> |
| 544 | {group[0]!.iommuGroup === null ? <Usb size={12} aria-label="usb" /> : <CircuitBoard size={12} aria-label="pci" />} |
| 545 | {group[0]!.name.match(/\[(.+)\]/)?.[1] ?? group[0]!.name} |
| 546 | </span> |
| 547 | )} |
| 548 | </For> |
| 549 | <For each={props.vm.disks}> |
| 550 | {(disk) => ( |
| 551 | <span tabindex="0" data-tip={disk.pool |
| 552 | ? `${bytes(disk.allocation)} / ${bytes(disk.capacity)} (${percent((disk.allocation / disk.capacity) * 100)})` |
| 553 | : `${drive(disk.source)}, whole drive`}> |
| 554 | <HardDrive size={12} aria-label="disk" />{bytes(disk.capacity)} |
| 555 | </span> |
| 556 | )} |
| 557 | </For> |
| 558 | <Show when={props.vm.autostart}><span><Power size={12} aria-hidden="true" />autostart</span></Show> |
| 559 | </div> |
| 560 | </td> |
| 561 | <td class="num" tabindex={cpuTip() ? 0 : undefined} data-tip={cpuTip()}>{plural(props.vm.vcpus, "vcpu")}</td> |
| 562 | <td class="num" tabindex={memoryTip() ? 0 : undefined} data-tip={memoryTip()}>{allocated(props.vm)}</td> |
| 563 | </tr> |
| 564 | |
| 565 | </tbody> |
| 566 | ); |
| 567 | } |
| 568 | |
| 569 | export function VMs() { |
| 570 | const [data, { refetch }] = queries.vms.use(); |
| 571 | const timer = setInterval(() => data.loading || unconnected(data.error) || refetch(), LIVE_INTERVAL * 1000); |
| 572 | onCleanup(() => clearInterval(timer)); |
| 573 | const [params, setParams] = useSearchParams<{ vm?: string; tab?: string }>(); |
| 574 | const loaded = lastGood(data); |
| 575 | const activeTab = createMemo(() => { |
| 576 | if (params.tab === "hardware") return "hardware"; |
| 577 | const vm = loaded()?.domains.find((vm) => vm.name === params.vm); |
| 578 | return params.tab === "console" && vm?.platform === "linux" && vm.serial ? "console" : "screen"; |
| 579 | }); |
| 580 | const newVm = () => { |
| 581 | const latest = loaded(); |
| 582 | if (latest) create(latest.node, () => loaded()?.library ?? latest.library, latest.domains, refetch, |
| 583 | (name) => setParams({ vm: name, tab: undefined })); |
| 584 | }; |
| 585 | const newButton = (label: string) => <button class="button primary" disabled={!loaded()} onClick={newVm}><Plus size={14} />{label}</button>; |
| 586 | return <ListPage id="vms" class={`vms ${params.vm ? "vm-active" : ""}`} flush head={ |
| 587 | <Show when={!params.vm}><div class="page-head"> |
| 588 | <h1>virtual machines</h1> |
| 589 | <Show when={loaded()}>{(value) => <span class="muted vm-count">{plural(value().domains.length, "vm")}</span>}</Show> |
| 590 | <span class="spacer" /> |
| 591 | <button class="button" disabled={!loaded()} onClick={() => uploadIso(refetch)}>upload ISO</button> |
| 592 | {newButton("new vm")} |
| 593 | </div></Show> |
| 594 | }> |
| 595 | <Loaded data={data} what="virtual machines" retry={refetch} skeleton={ |
| 596 | <div class="edge vms-list"><For each={Array(4)}>{() => <div class="skeleton row-skeleton" />}</For></div> |
| 597 | }>{(latest) => <Show when={params.vm} keyed fallback={ |
| 598 | <> |
| 599 | <Show when={latest().domains.length} fallback={ |
| 600 | <div class="empty vms-empty"><p>No virtual machines yet.</p>{newButton("create vm")}</div> |
| 601 | }> |
| 602 | <div class="edge vms-list"><table class="data"> |
| 603 | <thead><tr><th>name</th><th>state</th><th class="num">cpu</th><th class="num">memory</th><th><span class="sr-only">actions</span></th></tr></thead> |
| 604 | <For each={latest().domains.map((vm) => vm.name)}>{(name) => <Show when={latest().domains.find((vm) => vm.name === name)}>{(vm) => |
| 605 | <Row vm={vm()} hostCpus={latest().node.cpus} |
| 606 | onOpen={() => setParams({ vm: name, tab: undefined })} refetch={refetch} /> |
| 607 | }</Show>}</For> |
| 608 | </table></div> |
| 609 | </Show> |
| 610 | <section class="vm-library"> |
| 611 | <h2>OS library <span class="muted">{plural(latest().library.presets.length, "preset")}</span></h2> |
| 612 | <Show when={latest().library.presets.length} fallback={<p class="muted">No presets yet. Install an OS to prepare your first one.</p>}> |
| 613 | <For each={latest().library.presets}>{(preset) => <div class="vm-library-item"><span>{preset.os}</span><span class="muted">{preset.description}</span><span class="spacer" /><span class="muted">{datetime(preset.createdAt)}</span><span>{bytes(preset.capacity)}</span></div>}</For> |
| 614 | </Show> |
| 615 | <details><summary>Installer ISOs ({latest().library.installers.filter((item) => item.arch === latest().library.arch).length})</summary><For each={latest().library.installers.filter((item) => item.arch === latest().library.arch)}>{(iso) => |
| 616 | <div class="vm-library-item"><span>{iso.os}</span><span class="spacer" /><span class="muted">{bytes(iso.capacity)}</span></div> |
| 617 | }</For></details> |
| 618 | </section> |
| 619 | </> |
| 620 | }>{(name) => { |
| 621 | const [access] = createResource(() => name, (name) => parseResponse(api.vms[":name"].access.$get({ param: { name } }))); |
| 622 | const [consoleOpened, setConsoleOpened] = createSignal(false); |
| 623 | createEffect(() => { if (activeTab() === "console") setConsoleOpened(true); }); |
| 624 | return <Show when={latest().domains.find((vm) => vm.name === name)} fallback={ |
| 625 | <div class="empty vms-empty"><p>This VM isn't in your account.</p><button class="button" onClick={() => setParams({ vm: undefined, tab: undefined })}>VM home</button></div> |
| 626 | }>{(vm) => <section class="vm-workspace" aria-label={`${name} workspace`}> |
| 627 | <h1 class="sr-only">{name}</h1> |
| 628 | <VMConsole name={name} enabled={!isOff(vm())} active={activeTab() === "screen"} |
| 629 | content={(toolbar) => <> |
| 630 | <Show when={consoleOpened()}><VMSerial name={name} enabled={running(vm()) && vm().platform === "linux" && vm().serial} active={activeTab() === "console"} toolbar={toolbar} /></Show> |
| 631 | <Show when={activeTab() === "hardware"}><Hardware vm={vm()} refetch={refetch} username={access()?.username} hostname={access()?.hostname} /></Show> |
| 632 | </>} |
| 633 | toolbar={<> |
| 634 | <TabBar label="VM workspace"> |
| 635 | <button aria-pressed={activeTab() === "screen"} onClick={() => setParams({ tab: undefined })}><Monitor size={13} />Screen</button> |
| 636 | <Show when={vm().platform === "linux" && vm().serial}><button aria-pressed={activeTab() === "console"} onClick={() => setParams({ tab: "console" })}><SquareTerminal size={13} />Console</button></Show> |
| 637 | <button aria-pressed={activeTab() === "hardware"} onClick={() => setParams({ tab: "hardware" })}><CircuitBoard size={13} />Hardware</button> |
| 638 | </TabBar> |
| 639 | <VMMenu label="Machine"> |
| 640 | <PowerControls vm={vm()} refetch={refetch} /> |
| 641 | <button disabled={!running(vm())} onClick={() => restart(vm(), refetch)}><RotateCw size={14} aria-hidden="true" />Restart</button> |
| 642 | <Show when={vm().state !== "shutdown"}><button disabled={isOff(vm())} onClick={() => forceOff(vm(), refetch)}><Square size={14} aria-hidden="true" />Force off</button></Show> |
| 643 | <Show when={latest().canPublish}><button disabled={vm().state !== "shutoff"} title={vm().state !== "shutoff" ? "Shut down before saving a preset" : undefined} onClick={() => savePreset(vm(), refetch)}><Save size={14} aria-hidden="true" />Save preset</button></Show> |
| 644 | <button class="danger" onClick={() => remove(vm(), refetch)}><Trash size={14} aria-hidden="true" />Delete</button> |
| 645 | </VMMenu> |
| 646 | <VMMenu label="Media"> |
| 647 | <button onClick={() => attachIso(vm(), () => latest().library, refetch)}><Disc3 size={14} aria-hidden="true" />Attach ISO</button> |
| 648 | <button disabled={!vm().media.some((item) => item.source)} onClick={async () => { |
| 649 | try { await parseResponse(api.vms[":name"].media.$put({ param: { name }, json: { image: "" } })); await refetch(); } |
| 650 | catch (failure) { toast(`Unable to eject ISO. ${reason(failure)}`); } |
| 651 | }}><Disc2 size={14} aria-hidden="true" />Eject ISO</button> |
| 652 | <span class="muted vm-menu-info">{vm().media.find((item) => item.source)?.source ?? "No ISO attached"}</span> |
| 653 | </VMMenu> |
| 654 | <Show when={access()}>{(login) => <VMMenu label="Password"> |
| 655 | <label class="vm-password">Guest password<input aria-label="Guest password" value={login().password} readOnly spellcheck={false} /></label> |
| 656 | <Copy value={login().password} label="guest password"><KeyRound size={14} aria-hidden="true" />Copy password</Copy> |
| 657 | </VMMenu>}</Show> |
| 658 | </>} /> |
| 659 | </section>}</Show>; |
| 660 | }}</Show>}</Loaded> |
| 661 | </ListPage>; |
| 662 | } |