1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
|
// deck-it - the VMs tab: libvirt power, snapshots and an ssh session
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// 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) {
if (!Number.isFinite(sec) || sec <= 0) return ""; // no time is not "just now"
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 = `<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-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;
};
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">
<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 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);
},
};
|