aboutsummaryrefslogtreecommitdiffstats
path: root/static/modules/vm.js
diff options
context:
space:
mode:
Diffstat (limited to 'static/modules/vm.js')
-rw-r--r--static/modules/vm.js333
1 files changed, 244 insertions, 89 deletions
diff --git a/static/modules/vm.js b/static/modules/vm.js
index fdffd09..df68a07 100644
--- a/static/modules/vm.js
+++ b/static/modules/vm.js
@@ -15,135 +15,290 @@
// 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";
-// Destructive actions fire only after a hold this long, so a stray touch on
-// an always-on tablet cannot force a VM off.
-const HOLD_MS = 800;
+// One tile per VM: 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 buttons per state, as keystone's drawer offers them.
+// The sheet's buttons per state, as keystone's drawer offers them.
function actionsFor(st, saved) {
- if (st === "running")
- return [["ssh", "SSH"], ["shutdown", "Shutdown"], ["reboot", "Reboot"], ["suspend", "Suspend"],
- ["reset", "Reset"], ["destroy", "Force stop"]];
- if (st === "paused" || st === "suspended")
- return [["resume", "Resume"], ["shutdown", "Shutdown"], ["destroy", "Force stop"]];
- return saved ? [["start", "Start"], ["discardsave", "Discard saved state"]] : [["start", "Start"]];
+ 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];
}
-const gib = (b) => (b == null ? "—" : `${(b / 2 ** 30).toFixed(1)} GiB`);
+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, card) {
- const err = card.querySelector(".vm-err");
- card.classList.add("busy");
+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),
});
- err.textContent = r.ok ? "" : (await r.text()) || r.statusText;
+ if (!r.ok) msg = (await r.text()) || r.statusText;
} catch (e) {
- err.textContent = String(e);
+ msg = String(e);
}
- err.hidden = !err.textContent;
- card.classList.remove("busy");
+ v.busy(false);
+ v.error(msg);
}
-function button(label, action, body, card) {
+function iconButton(action, body, v, cls = "") {
const b = document.createElement("button");
- b.textContent = label;
- const fire = () => post(action, body, card);
- if (!HOLD.has(action)) {
- b.onclick = fire;
- return b;
+ 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(); });
}
- // Press and hold: the fill grows over HOLD_MS, releasing early cancels.
- b.className = "hold";
- b.title = "Press and hold";
- b.style.setProperty("--hold", `${HOLD_MS}ms`);
- let timer = null;
- const cancel = () => { clearTimeout(timer); b.classList.remove("holding"); };
- b.addEventListener("pointerdown", (e) => {
- e.preventDefault();
- b.setPointerCapture(e.pointerId);
- b.classList.add("holding");
- timer = setTimeout(() => { cancel(); fire(); }, HOLD_MS);
- });
- b.addEventListener("pointerup", cancel);
- b.addEventListener("pointercancel", cancel);
return b;
}
-function card() {
- const c = document.createElement("div");
- c.className = "vm-card";
- c.innerHTML = `<div class="vm-head"><span class="vm-name"></span><span class="vm-state"></span>
- <span class="vm-ip num"></span></div>
- <div class="vm-use"><span class="mlabel">CPU</span><div class="gbar"><i></i></div><span class="vm-cpu num"></span>
- <span class="mlabel">RAM</span><span class="vm-mem num"></span></div>
- <div class="row vm-acts"></div>
+const SPARK = `<svg viewBox="0 0 120 100" preserveAspectRatio="none"><path class="hy"/><path class="hy ln"/></svg>`;
+
+// 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 = `<div class="vm-screen"><i class="nf vm-glyph">${G.vm}</i><img alt="" hidden>
+ <span class="vm-state"></span></div>
+ <div class="vm-info"><b class="vm-name"></b><span class="vm-status"></span></div>
+ <div class="vm-trends">
+ <div class="vm-trend t-cpu">${SPARK}<span class="k">CPU</span><span class="v num"></span></div>
+ <div class="vm-trend t-mem">${SPARK}<span class="k">RAM</span><span class="v num"></span></div>
+ </div>
<div class="vm-err" hidden></div>
- <div class="vm-snaps"></div>`;
- return c;
-}
+ <div class="vm-bar"><button class="vm-power nf hold"></button><span class="vm-ssh"></span>
+ <button class="ib nf vm-more" aria-label="All actions and snapshots" title="All actions and snapshots">${G.more}</button></div>`;
+ const sheet = document.createElement("dialog");
+ sheet.setAttribute("closedby", "any");
+ sheet.className = "card vm-sheet";
+ sheet.innerHTML = `<div class="vm-info"><b class="vm-name"></b><span class="vm-state"></span>
+ <span class="vm-status"></span></div>
+ <div class="vm-acts"></div>
+ <div class="vm-err" hidden></div>
+ <div class="vm-snaphead"><span class="k">Snapshots</span></div>
+ <div class="vm-timeline"></div>
+ <div class="vm-snapacts" hidden><span class="vm-snapname"></span></div>`;
+ 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;
+ };
-// Text every poll; buttons only when what they depend on changed, so a
-// hold in progress is not torn down under the finger.
-function fill(c, vm) {
- c.querySelector(".vm-name").textContent = vm.name;
- const pill = c.querySelector(".vm-state");
- pill.textContent = vm.saved && vm.state === "shut off" ? "saved" : vm.state;
- pill.className = `vm-state ${PILL[vm.state] ?? ""}`;
- c.querySelector(".vm-ip").textContent = vm.ip;
- const on = vm.state === "running";
- c.querySelector(".vm-use").hidden = !on;
- c.querySelector(".gbar > i").style.width = `${vm.cpu ?? 0}%`;
- c.querySelector(".vm-cpu").textContent = vm.cpu == null ? "—" : `${Math.round(vm.cpu)}% of ${vm.vcpus}`;
- c.querySelector(".vm-mem").textContent = gib(vm.mem);
-
- const key = JSON.stringify([vm.state, vm.saved, vm.snapshots]);
- if (c.dataset.key === key) return;
- c.dataset.key = key;
- const acts = c.querySelector(".vm-acts");
- acts.replaceChildren(...actionsFor(vm.state, vm.saved).map(([a, l]) => button(l, a, { vm: vm.name }, c)),
- button("Snapshot", "snapshot", { vm: vm.name }, c));
- c.querySelector(".vm-snaps").replaceChildren(...vm.snapshots.map((s) => {
- const row = document.createElement("div");
- row.className = "vm-snap";
- const name = document.createElement("span");
- name.textContent = s;
- row.append(name, button("Revert", "revert", { vm: vm.name, snap: s }, c),
- button("Delete", "snapdelete", { vm: vm.name, snap: s }, c));
- return row;
- }));
+ 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 = "<b></b><span></span>";
+ 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 = `<div class="vm"><div class="vm-off"></div><div class="vm-list"></div></div>`;
+ el.innerHTML = `<div class="vm">
+ <svg width="0" height="0" aria-hidden="true" style="position:absolute"><defs>
+ <linearGradient id="vmline" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="120" y2="0"><stop offset="0" style="stop-color:var(--udt-border-1)"/>
+ <stop offset=".5" style="stop-color:var(--udt-border-2)"/><stop offset="1" style="stop-color:var(--udt-border-3)"/></linearGradient>
+ <linearGradient id="vmfill" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="0" y2="100">
+ <stop offset="0" style="stop-color:var(--udt-border-2);stop-opacity:.45"/>
+ <stop offset="1" style="stop-color:var(--udt-border-1);stop-opacity:.05"/></linearGradient>
+ </defs></svg>
+ <div class="vm-off"></div><div class="vm-grid"></div></div>`;
},
update(st, el) {
const off = el.querySelector(".vm-off");
- const list = el.querySelector(".vm-list");
+ const grid = el.querySelector(".vm-grid");
off.hidden = !st.offline;
- list.hidden = Boolean(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 cards = new Map([...list.children].map((c) => [c.dataset.vm, c]));
- list.replaceChildren(...st.vms.map((vm) => {
- const c = cards.get(vm.name) ?? card();
- c.dataset.vm = vm.name;
- fill(c, vm);
- return c;
- }));
- if (!st.vms.length) list.textContent = "No VMs defined.";
+ 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);
},
};