// deck-it - the VMs tab: libvirt power, snapshots and an ssh session // Copyright (C) 2026 Danilo M. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import { offline } from "../offline.js"; import { hold } from "../hold.js"; import { area, line, push } from "../dashboard.js"; // One tile per VM, in one column (deck.css: a running one as tall as the // tab, the whole tab when it is the only one): its screen, a big power // button (tap for the gentle action, hold to force it off), SSH, and // CPU/RAM trends. A tap on the tile // opens a sheet with every action and the snapshot timeline. Buttons are // Nerd Font glyphs; destructive ones fire only on a press and hold. const G = { power: "", ssh: "", more: "", start: "", shutdown: "", reboot: "", suspend: "", resume: "", reset: "", destroy: "", discardsave: "", snapshot: "", revert: "", snapdelete: "", vm: "", }; const LABEL = { ssh: "SSH", start: "Start", shutdown: "Shut down", reboot: "Reboot", suspend: "Suspend", resume: "Resume", reset: "Reset (hold)", destroy: "Force stop (hold)", discardsave: "Discard saved state (hold)", snapshot: "Take a snapshot", revert: "Revert to this snapshot (hold)", snapdelete: "Delete this snapshot (hold)", }; const HOLD = new Set(["reset", "destroy", "discardsave", "revert", "snapdelete"]); const PILL = { running: "good", paused: "warn", suspended: "warn", "shutting down": "warn", crashed: "bad" }; const SHOT = 5000; // the screen preview's refresh, ms const HIST = 90; // trend samples: three minutes at the 2 s poll // The sheet's buttons per state, as keystone's drawer offers them. function actionsFor(st, saved) { if (st === "running") return ["ssh", "shutdown", "reboot", "suspend", "reset", "destroy"]; if (st === "paused" || st === "suspended") return ["resume", "shutdown", "destroy"]; if (st === "shutting down" || st === "crashed") return ["destroy"]; return saved ? ["start", "discardsave"] : ["start"]; } // The tile's power button: [tap, hold]; either may be absent. function powerFor(st) { if (st === "running") return ["shutdown", "destroy"]; if (st === "paused" || st === "suspended") return ["resume", "destroy"]; if (st === "shutting down" || st === "crashed") return [null, "destroy"]; return ["start", null]; } function ago(sec) { const s = Math.max(0, Date.now() / 1000 - sec); for (const [n, u] of [[31536000, "y"], [2592000, "mo"], [86400, "d"], [3600, "h"], [60, "min"]]) { if (s >= n) return `${Math.floor(s / n)} ${u} ago`; } return "just now"; } const gib = (b) => (b == null ? "—" : `${(b / 2 ** 30).toFixed(1)}`); function status(vm) { if (vm.state === "running") { if (vm.ready) return `ssh ready${vm.ip ? ` · ${vm.ip}` : ""}`; return vm.ready === false ? "booting…" : vm.ip; } return vm.saved && vm.state === "shut off" ? "saved state, start restores it" : ""; } async function post(action, body, v) { v.busy(true); let msg = ""; try { const r = await fetch(`/api/vm/${action}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!r.ok) msg = (await r.text()) || r.statusText; } catch (e) { msg = String(e); } v.busy(false); v.error(msg); } function iconButton(action, body, v, cls = "") { const b = document.createElement("button"); b.className = `ib nf ${cls}`; b.textContent = G[action]; b.setAttribute("aria-label", LABEL[action]); b.title = LABEL[action]; const fire = () => post(action, body, v); if (HOLD.has(action)) { b.classList.add("hold"); hold(b, fire); } else { b.addEventListener("click", (e) => { e.stopPropagation(); fire(); }); } return b; } const SPARK = ``; // A VM's tile and sheet, built once; update() sets text every poll and // rebuilds buttons only when what they depend on changed, so a hold in // progress is never torn down under the finger. function view(name, root) { const tile = document.createElement("div"); tile.className = "vm-tile"; tile.innerHTML = `
${G.vm}
`; const sheet = document.createElement("dialog"); sheet.setAttribute("closedby", "any"); sheet.className = "card vm-sheet"; sheet.innerHTML = `
Snapshots
`; root.append(tile, sheet); const $ = (sel) => [tile.querySelector(sel), sheet.querySelector(sel)].filter(Boolean); const open = () => sheet.showModal(); tile.querySelector(".vm-screen").addEventListener("click", open); tile.querySelector(".vm-info").addEventListener("click", open); tile.querySelector(".vm-more").addEventListener("click", open); const v = { tile, sheet, hist: { cpu: [], mem: [] }, keys: {}, pick: null, // the snapshot chip tapped in the sheet busy(on) { tile.classList.toggle("busy", on); sheet.classList.toggle("busy", on); }, error(msg) { for (const e of $(".vm-err")) { e.textContent = msg; e.hidden = !msg; } }, }; sheet.querySelector(".vm-snaphead").append(iconButton("snapshot", { vm: name }, v)); const power = tile.querySelector(".vm-power"); power.textContent = G.power; let powerAct = [null, null]; hold(power, () => powerAct[1] && post(powerAct[1], { vm: name }, v), { tap: () => powerAct[0] && post(powerAct[0], { vm: name }, v) }); const changed = (k, val) => { const s = JSON.stringify(val); if (v.keys[k] === s) return false; v.keys[k] = s; return true; }; v.update = (vm, visible) => { for (const e of $(".vm-name")) e.textContent = vm.name; for (const e of $(".vm-state")) { e.textContent = vm.state; e.className = `vm-state ${PILL[vm.state] ?? ""}`; } for (const e of $(".vm-status")) e.textContent = status(vm); const on = vm.state === "running"; tile.classList.toggle("on", on); // Tap does the gentle thing, hold forces: the fill shows only when a // hold does something. powerAct = powerFor(vm.state); power.classList.toggle("hold", Boolean(powerAct[1])); power.classList.toggle("go", !on && Boolean(powerAct[0])); const pl = [powerAct[0] && LABEL[powerAct[0]], powerAct[1] && LABEL[powerAct[1]]].filter(Boolean).join(", "); power.setAttribute("aria-label", pl); power.title = pl; if (changed("ssh", [on, vm.ready])) { const slot = tile.querySelector(".vm-ssh"); slot.replaceChildren(); if (on) { const b = iconButton("ssh", { vm: vm.name }, v, "vm-sshb"); b.classList.toggle("ready", vm.ready === true); slot.append(b); } } // Screen: refreshed every SHOT ms, only while the tab is on screen. const img = tile.querySelector("img"); if (on && visible) { const url = `/api/vm/image/${encodeURIComponent(vm.name)}?t=${Math.floor(Date.now() / SHOT)}`; if (img.dataset.src !== url) { img.dataset.src = url; img.onload = () => { img.hidden = false; }; img.onerror = () => { img.hidden = true; }; img.src = url; } } else if (!on) { img.hidden = true; delete img.dataset.src; } // Trends: history in the page, cleared while the VM is off. if (on) { push(v.hist.cpu, vm.cpu ?? 0, HIST); push(v.hist.mem, vm.used != null && vm.mem ? (vm.used / vm.mem) * 100 : 0, HIST); } else { v.hist.cpu.length = 0; v.hist.mem.length = 0; } for (const [k, hist] of Object.entries(v.hist)) { const [fill, stroke] = tile.querySelectorAll(`.t-${k} path`); fill.setAttribute("d", area(hist, 100, HIST)); stroke.setAttribute("d", line(hist, 100, HIST)); } tile.querySelector(".t-cpu .v").textContent = on && vm.cpu != null ? `${Math.round(vm.cpu)}%` : "—"; tile.querySelector(".t-mem .v").textContent = !on ? "—" : vm.used != null ? `${gib(vm.used)}/${gib(vm.mem)} GiB` : `${gib(vm.mem)} GiB`; if (changed("acts", [vm.state, vm.saved])) { sheet.querySelector(".vm-acts").replaceChildren( ...actionsFor(vm.state, vm.saved).map((a) => iconButton(a, { vm: vm.name }, v))); } // Snapshot timeline, oldest first: a chip per snapshot with its age, // the current one marked. A tap picks one, and its revert and delete // appear below. const names = vm.snapshots.map((s) => s.name); if (v.pick && !names.includes(v.pick)) v.pick = null; if (changed("snaps", [vm.snapshots, v.pick])) { const tl = sheet.querySelector(".vm-timeline"); tl.replaceChildren(...vm.snapshots.map((s) => { const c = document.createElement("button"); c.className = `vm-snap${s.current ? " current" : ""}${s.name === v.pick ? " on" : ""}`; c.innerHTML = ""; c.firstChild.textContent = s.name; c.lastChild.textContent = ago(s.created); c.title = new Date(s.created * 1000).toLocaleString(); c.onclick = () => { v.pick = s.name === v.pick ? null : s.name; v.update(vm, visible); }; return c; })); if (!vm.snapshots.length) tl.textContent = "None yet."; const acts = sheet.querySelector(".vm-snapacts"); acts.hidden = !v.pick; acts.querySelector(".vm-snapname").textContent = v.pick ?? ""; acts.querySelectorAll("button").forEach((b) => b.remove()); if (v.pick) { acts.append(iconButton("revert", { vm: vm.name, snap: v.pick }, v), iconButton("snapdelete", { vm: vm.name, snap: v.pick }, v)); } } }; return v; } const views = new Map(); export default { title: "VMs", tab: "VMs", interval: 2, mount(el) { el.innerHTML = `
`; }, update(st, el) { const off = el.querySelector(".vm-off"); const grid = el.querySelector(".vm-grid"); off.hidden = !st.offline; grid.hidden = Boolean(st.offline); if (st.offline) { offline(off, { icon: "/icons/virt-manager.svg", title: "libvirt is not answering", detail: "Start libvirtd and the VMs appear here.", reason: st.reason }); return; } const visible = !document.hidden && el.offsetParent !== null; const seen = new Set(); for (const vm of st.vms) { seen.add(vm.name); if (!views.has(vm.name)) views.set(vm.name, view(vm.name, grid)); views.get(vm.name).update(vm, visible); } for (const [name, v] of views) { if (!seen.has(name)) { v.tile.remove(); v.sheet.remove(); views.delete(name); } } grid.classList.toggle("empty", !st.vms.length); grid.classList.toggle("solo", st.vms.filter((vm) => vm.state === "running").length === 1); }, };