aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--AGENTS.md6
-rw-r--r--README.md9
-rw-r--r--config.toml1
-rw-r--r--deckit/modules/vm.py187
-rw-r--r--static/app.js2
-rw-r--r--static/deck.css21
-rw-r--r--static/modules/vm.js149
-rw-r--r--tests/test_vm.py140
8 files changed, 512 insertions, 3 deletions
diff --git a/AGENTS.md b/AGENTS.md
index 1ad334d..22ce6f5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -69,6 +69,12 @@ Keep the server dependency-free apart from that one package.
is the emergency stop, a press-and-hold button on the tab. While the printer
is off it backs off 10s between tries. The camera snapshot and the slicer
thumbnail are loaded by the tablet straight from the printer.
+- `vm` drives libvirt's default connection (qemu:///system) through `virsh`:
+ `domstats` each poll, `dominfo`/`snapshot-list`/agent `domifaddr` in a
+ thread every 10s and after an action. A vm or snapshot name must be one
+ the last state listed. `ssh` opens `ssh <vm>` as a tab in the first
+ `$XDG_RUNTIME_DIR/kitty-<pid>` that answers `kitty @` and focuses it,
+ else spawns kitty. Destructive buttons are press and hold.
- `sbbuilder` has no tab, only a running slot. It reads `sbb-remote jobs
--active` (sb-builder 0.13.1+); a running build's `progress` (done of
total with dependencies, the package building, its ETA, the estimated end,
diff --git a/README.md b/README.md
index 9de9f73..1f371bf 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ Turns an Android tablet into a second monitor, a stream-deck and an always-on
control surface for a Slackware Hyprland desktop.
A web page on the tablet has tabs for a dashboard, windows, OBS, the K1C
-printer and the assistant. A second headless output is streamed to AVNC as an extra
+printer, the assistant and the VMs. A second headless output is streamed to AVNC as an extra
monitor. Everything runs on the PC and reaches the tablet through `adb reverse`;
there is no cloud, account or app-store install.
@@ -50,7 +50,7 @@ launchers included, with a Restart button to apply a save.
## Usage
-- Tabs: **Dashboard**, **Windows**, **OBS**, **K1C**, **Assistant**. Swipe the content sideways to change
+- Tabs: **Dashboard**, **Windows**, **OBS**, **K1C**, **Assistant**, **VMs**. Swipe the content sideways to change
tab; ⟳ at the top right reloads the page.
- `deck-it install` prints the `exec-once` line for USB autostart.
- `config.toml` holds the defaults: display, Wi-Fi address, workspaces,
@@ -71,6 +71,11 @@ launchers included, with a Restart button to apply a save.
- The K1C tab follows a Klipper printer through Moonraker (`[k1c] url`):
state, progress with the slicer's model preview, temperatures, camera, and
a red emergency stop that fires on a press and hold.
+- The VMs tab manages libvirt's `qemu:///system` VMs: state, CPU and
+ memory, start, shutdown, reboot, suspend, snapshots (take, revert,
+ delete), and SSH, a tab in a running kitty or a new one. Force stop,
+ reset, revert and delete fire on a press and hold. SSH connects to the
+ VM's name, so give each VM an `~/.ssh/config` alias.
- The Assistant tab talks to desktop-assistant: tap the mic to ask,
pick the model, and use the canvas's Ask presets and Do ops on a file you
choose in a dialog on the PC (add a Translate preset on keystone's Ask
diff --git a/config.toml b/config.toml
index cbaf6ee..afd2667 100644
--- a/config.toml
+++ b/config.toml
@@ -48,6 +48,7 @@ obs = true
llm = true
sbbuilder = true
k1c = true
+vm = true
assistant = true
tablet = true
actions = true
diff --git a/deckit/modules/vm.py b/deckit/modules/vm.py
new file mode 100644
index 0000000..772e7b9
--- /dev/null
+++ b/deckit/modules/vm.py
@@ -0,0 +1,187 @@
+# deck-it - libvirt VMs: power, snapshots, ssh in kitty
+# 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.
+
+"""The VMs on libvirt's default connection (qemu:///system), through virsh.
+
+`virsh domstats` gives every VM's state, CPU time and memory in one call each
+poll. The slower per-VM reads (managed save, snapshots, the guest agent's IP)
+run in a thread at most every SLOW seconds, and after any action, so the poll
+never waits on them. Shelling out to virsh, like keystone's drawer, adds no
+dependency.
+"""
+
+import os
+import re
+import subprocess
+import threading
+import time
+from pathlib import Path
+
+from ..module import Module, ModuleError
+from .windows import hypr_lua
+
+SLOW = 10
+STATES = {1: "running", 2: "blocked", 3: "paused", 4: "shutting down",
+ 5: "shut off", 6: "crashed", 7: "suspended"}
+POWER = {
+ "start": ["start"], "shutdown": ["shutdown", "--mode", "acpi"], "reboot": ["reboot"],
+ "reset": ["reset"], "destroy": ["destroy"], "suspend": ["suspend"], "resume": ["resume"],
+ "discardsave": ["managedsave-remove"],
+}
+
+
+def _run(cmd, timeout=10):
+ try:
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ return subprocess.CompletedProcess(cmd, 1, "", str(e))
+
+
+def _popen(cmd):
+ subprocess.Popen(cmd, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+
+
+def _spawn(fn):
+ threading.Thread(target=fn, daemon=True).start()
+
+
+def parse_domstats(text: str) -> dict:
+ doms, cur = {}, None
+ for line in text.splitlines():
+ m = re.match(r"^Domain: '(.+)'$", line)
+ if m:
+ cur = doms.setdefault(m[1], {"state": "unknown", "vcpus": 0, "ns": None, "mem": None})
+ continue
+ kv = line.strip().split("=", 1)
+ if cur is None or len(kv) != 2:
+ continue
+ k, v = kv
+ if k == "state.state":
+ cur["state"] = STATES.get(int(v), "unknown")
+ elif k == "vcpu.current":
+ cur["vcpus"] = int(v)
+ elif k == "cpu.time":
+ cur["ns"] = int(v)
+ elif k == "balloon.current":
+ cur["mem"] = int(v) * 1024
+ return doms
+
+
+def _ip(text: str) -> str:
+ for addr in re.findall(r"\sipv4\s+(\d+\.\d+\.\d+\.\d+)/", text):
+ if not addr.startswith("127."):
+ return addr
+ return ""
+
+
+def make(cfg: dict) -> Module:
+ run = cfg.get("run", _run)
+ clock = cfg.get("clock", time.monotonic)
+ spawn = cfg.get("spawn", _spawn)
+ popen = cfg.get("popen", _popen)
+ runtime = cfg.get("runtime") or os.environ.get("XDG_RUNTIME_DIR", "/tmp")
+ lua = hypr_lua(cfg)
+ doms = {} # last domstats, by name
+ last = {} # name -> (cpu ns, at)
+ slow = {"at": float("-inf"), "busy": False, "data": {}}
+
+ def read_slow():
+ data = {}
+ for name, d in list(doms.items()):
+ info = run(["virsh", "dominfo", name]).stdout
+ snaps = run(["virsh", "snapshot-list", name, "--name"]).stdout
+ ip = _ip(run(["virsh", "domifaddr", name, "--source", "agent"]).stdout) \
+ if d["state"] == "running" else ""
+ data[name] = {"saved": bool(re.search(r"^Managed save:\s+yes$", info, re.M)),
+ "snapshots": [s.strip() for s in snaps.splitlines() if s.strip()],
+ "ip": ip}
+ slow["data"] = data
+ slow["busy"] = False
+
+ def kick():
+ if not slow["busy"]:
+ slow.update(busy=True, at=clock())
+ spawn(read_slow)
+
+ def state():
+ p = run(["virsh", "domstats", "--state", "--cpu-total", "--balloon", "--vcpu"])
+ if p.returncode != 0:
+ return {"offline": True, "reason": (p.stderr or "").strip()}
+ doms.clear()
+ doms.update(parse_domstats(p.stdout))
+ if clock() - slow["at"] >= SLOW:
+ kick()
+ now, vms = clock(), []
+ for name, d in sorted(doms.items()):
+ cpu = None
+ prev = last.get(name)
+ if d["ns"] is not None:
+ if prev and now > prev[1] and d["state"] == "running":
+ cpu = max(0.0, min(100.0, (d["ns"] - prev[0]) / ((now - prev[1]) * 1e9)
+ / (d["vcpus"] or 1) * 100))
+ last[name] = (d["ns"], now)
+ extra = slow["data"].get(name, {})
+ vms.append({"name": name, "state": d["state"], "vcpus": d["vcpus"], "cpu": cpu,
+ "mem": d["mem"], "ip": extra.get("ip", ""), "saved": extra.get("saved", False),
+ "snapshots": extra.get("snapshots", [])})
+ return {"offline": False, "vms": vms}
+
+ def virsh(*args, timeout=120):
+ p = run(["virsh", *args], timeout=timeout)
+ slow["at"] = float("-inf") # re-read snapshots and save state next poll
+ if p.returncode != 0:
+ raise ModuleError((p.stderr or "").strip() or f"virsh {args[0]} failed")
+
+ def target(body, snap=False):
+ name = str(body.get("vm", ""))
+ if name not in doms:
+ raise ModuleError(f"unknown vm: {name}")
+ if not snap:
+ return name, None
+ s = str(body.get("snap", ""))
+ if s not in slow["data"].get(name, {}).get("snapshots", []):
+ raise ModuleError(f"unknown snapshot: {s}")
+ return name, s
+
+ def power(verb):
+ return lambda body: virsh(*POWER[verb], target(body)[0])
+
+ def snapshot(body):
+ name, _ = target(body)
+ virsh("snapshot-create-as", "--domain", name, "--name", f"{name}_{time.strftime('%d%m%Y_%H%M%S')}")
+
+ def revert(body):
+ virsh("snapshot-revert", *target(body, snap=True))
+
+ def snapdelete(body):
+ virsh("snapshot-delete", *target(body, snap=True))
+
+ def ssh(body):
+ """A tab in a running kitty, focused; a new kitty when none answers.
+ The host is the VM's name, so an ssh alias named after it is expected."""
+ name, _ = target(body)
+ for sock in sorted(Path(runtime).glob("kitty-*")):
+ p = run(["kitty", "@", "--to", f"unix:{sock}", "launch", "--type=tab", "ssh", name], timeout=3)
+ if p.returncode == 0:
+ pid = sock.name.split("-", 1)[1]
+ run(["hyprctl", "eval", f'hl.dispatch(hl.dsp.focus({{window = "pid:{pid}"}}))'] if lua
+ else ["hyprctl", "dispatch", "focuswindow", f"pid:{pid}"], timeout=2)
+ return
+ popen(["kitty", "ssh", name])
+
+ actions = {verb: power(verb) for verb in POWER}
+ actions.update(snapshot=snapshot, revert=revert, snapdelete=snapdelete, ssh=ssh)
+ return Module(name="vm", title="VMs", state=state, actions=actions)
diff --git a/static/app.js b/static/app.js
index 60cbb9f..5d1688a 100644
--- a/static/app.js
+++ b/static/app.js
@@ -29,7 +29,7 @@ const tabs = {};
// Tab icons, glyphs in the Nerd Font the server serves, or a brand logo from
// static/logos; a tab with neither shows its name. The name also shows next
// to the active one.
-const TAB_ICONS = { Dashboard: "\uf0e4", Windows: "\uf2d2", Assistant: "\uf086", K1C: "\u{f0e5b}" };
+const TAB_ICONS = { Dashboard: "\uf0e4", Windows: "\uf2d2", Assistant: "\uf086", K1C: "\u{f0e5b}", VMs: "\uf233" };
const TAB_LOGOS = { OBS: "obs" };
function ensureTab(name) {
diff --git a/static/deck.css b/static/deck.css
index a08f037..c316ff3 100644
--- a/static/deck.css
+++ b/static/deck.css
@@ -812,3 +812,24 @@ select {
/* Hyprland: speed 30 * 100 ms, flatlinetwo = linear, style = loop */
animation: border-rotate 3s linear infinite;
}
+
+/* VMs tab. Destructive buttons are press and hold, filled over --hold. */
+.vm-list { display: flex; flex-direction: column; gap: 12px; padding: 4px 2px; }
+.vm-list[hidden], .vm-off[hidden], .vm-use[hidden], .vm-err[hidden] { display: none; }
+.vm-card { display: flex; flex-direction: column; gap: 10px; padding: 12px 14px; border-radius: 12px; background: var(--udt-surface0); }
+.vm-card.busy { opacity: .6; pointer-events: none; }
+.vm-head { display: flex; align-items: center; gap: 12px; }
+.vm-name { font-size: 1.286rem; font-weight: 600; }
+.vm-state { padding: 2px 10px; border-radius: 999px; background: var(--udt-surface2); font-size: 0.857rem; }
+.vm-state.good { background: var(--udt-green); color: var(--udt-crust); }
+.vm-state.warn { background: var(--udt-yellow); color: var(--udt-crust); }
+.vm-state.bad { background: var(--udt-red); color: var(--udt-crust); }
+.vm-ip { margin-left: auto; color: var(--udt-subtext0); }
+.vm-use { display: grid; grid-template-columns: auto 1fr auto auto auto; align-items: center; gap: 10px; }
+.vm-err { color: var(--udt-red); font-size: 0.857rem; }
+.vm-acts { margin-bottom: 0; }
+.vm-snap { display: flex; align-items: center; gap: 8px; padding: 4px 0; border-top: 1px solid var(--udt-surface1); }
+.vm-snap > span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.vm .hold { position: relative; overflow: hidden; isolation: isolate; border-color: var(--udt-red); touch-action: none; }
+.vm .hold::before { content: ""; position: absolute; inset: 0; z-index: -1; background: var(--udt-red); transform: scaleX(0); transform-origin: left; }
+.vm .hold.holding::before { transform: scaleX(1); transition: transform var(--hold, 800ms) linear; }
diff --git a/static/modules/vm.js b/static/modules/vm.js
new file mode 100644
index 0000000..fdffd09
--- /dev/null
+++ b/static/modules/vm.js
@@ -0,0 +1,149 @@
+// 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";
+
+// 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;
+const HOLD = new Set(["reset", "destroy", "discardsave", "revert", "snapdelete"]);
+const PILL = { running: "good", paused: "warn", suspended: "warn", "shutting down": "warn", crashed: "bad" };
+
+// The 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"]];
+}
+
+const gib = (b) => (b == null ? "—" : `${(b / 2 ** 30).toFixed(1)} GiB`);
+
+async function post(action, body, card) {
+ const err = card.querySelector(".vm-err");
+ card.classList.add("busy");
+ 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;
+ } catch (e) {
+ err.textContent = String(e);
+ }
+ err.hidden = !err.textContent;
+ card.classList.remove("busy");
+}
+
+function button(label, action, body, card) {
+ const b = document.createElement("button");
+ b.textContent = label;
+ const fire = () => post(action, body, card);
+ if (!HOLD.has(action)) {
+ b.onclick = fire;
+ return b;
+ }
+ // 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>
+ <div class="vm-err" hidden></div>
+ <div class="vm-snaps"></div>`;
+ return c;
+}
+
+// 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;
+ }));
+}
+
+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>`;
+ },
+
+ update(st, el) {
+ const off = el.querySelector(".vm-off");
+ const list = el.querySelector(".vm-list");
+ off.hidden = !st.offline;
+ list.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.";
+ },
+};
diff --git a/tests/test_vm.py b/tests/test_vm.py
new file mode 100644
index 0000000..b84ec97
--- /dev/null
+++ b/tests/test_vm.py
@@ -0,0 +1,140 @@
+# deck-it - tests for the libvirt VM module
+# 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 sys
+import tempfile
+from pathlib import Path
+from types import SimpleNamespace
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import unittest
+
+import deckit.modules.vm as vm
+from deckit.module import ModuleError
+
+DOMSTATS = """Domain: 'alpha'
+ state.state=1
+ state.reason=1
+ cpu.time={ns}
+ balloon.current=4194304
+ vcpu.current=2
+
+Domain: 'beta'
+ state.state=5
+ state.reason=1
+ cpu.time=0
+ balloon.current=2097152
+ vcpu.current=1
+"""
+
+
+class Fake:
+ """virsh/kitty/hyprctl stand-in: records commands, answers by verb."""
+
+ def __init__(self):
+ self.cmds = []
+ self.ns = 1_000_000_000
+ self.fail = None
+ self.kitty_ok = True
+
+ def __call__(self, cmd, timeout=10):
+ self.cmds.append(cmd)
+ out, code, err = "", 0, ""
+ if cmd[:2] == ["virsh", "domstats"]:
+ out = DOMSTATS.format(ns=self.ns)
+ elif cmd[:2] == ["virsh", "dominfo"]:
+ out = "Managed save: yes\n" if cmd[2] == "beta" else "Managed save: no\n"
+ elif cmd[:2] == ["virsh", "snapshot-list"]:
+ out = "clean\nworking\n\n" if cmd[2] == "alpha" else ""
+ elif cmd[:2] == ["virsh", "domifaddr"]:
+ out = (" Name MAC address Protocol Address\n---\n"
+ " lo 00:00:00:00:00:00 ipv4 127.0.0.1/8\n"
+ " eth0 52:54:00:aa:bb:cc ipv4 192.0.2.5/24\n")
+ elif cmd[:2] == ["kitty", "@"]:
+ code = 0 if self.kitty_ok else 1
+ if self.fail and self.fail in cmd:
+ code, err = 1, "error: boom"
+ return SimpleNamespace(returncode=code, stdout=out, stderr=err)
+
+
+def make(fake, now, **extra):
+ cfg = {"run": fake, "clock": lambda: now[0], "spawn": lambda f: f(), "hyprland": "classic"}
+ cfg.update(extra)
+ return vm.make(cfg)
+
+
+class VmTest(unittest.TestCase):
+ def setUp(self):
+ self.fake = Fake()
+ self.now = [100.0]
+ self.spawned = []
+ self.mod = make(self.fake, self.now, popen=self.spawned.append)
+
+ def test_state_and_cpu_delta(self):
+ st = self.mod.state()
+ a, b = st["vms"]
+ self.assertEqual((a["name"], a["state"], a["vcpus"]), ("alpha", "running", 2))
+ self.assertIsNone(a["cpu"]) # one sample: no rate yet
+ self.assertEqual(a["mem"], 4194304 * 1024)
+ self.assertEqual(a["ip"], "192.0.2.5")
+ self.assertEqual(a["snapshots"], ["clean", "working"])
+ self.assertEqual((b["state"], b["saved"], b["ip"]), ("shut off", True, ""))
+ self.fake.ns += 1_000_000_000 # 1 s of CPU over 2 s, 2 vCPUs
+ self.now[0] += 2
+ self.assertAlmostEqual(self.mod.state()["vms"][0]["cpu"], 25.0)
+
+ def test_offline(self):
+ self.fake.fail = "domstats"
+ st = self.mod.state()
+ self.assertTrue(st["offline"])
+ self.assertIn("boom", st["reason"])
+
+ def test_actions_validated(self):
+ self.mod.state()
+ act = self.mod.actions
+ with self.assertRaises(ModuleError):
+ act["start"]({"vm": "gamma"})
+ with self.assertRaises(ModuleError):
+ act["revert"]({"vm": "alpha", "snap": "nope"})
+ act["start"]({"vm": "beta"})
+ self.assertIn(["virsh", "start", "beta"], self.fake.cmds)
+ act["revert"]({"vm": "alpha", "snap": "clean"})
+ self.assertIn(["virsh", "snapshot-revert", "alpha", "clean"], self.fake.cmds)
+ act["snapshot"]({"vm": "alpha"})
+ create = next(c for c in self.fake.cmds if "snapshot-create-as" in c)
+ self.assertRegex(create[-1], r"^alpha_\d{8}_\d{6}$")
+ self.fake.fail = "destroy"
+ with self.assertRaisesRegex(ModuleError, "boom"):
+ act["destroy"]({"vm": "alpha"})
+
+ def test_ssh_attaches_to_kitty_or_spawns(self):
+ self.mod.state()
+ with tempfile.TemporaryDirectory() as d:
+ (Path(d) / "kitty-4242").touch()
+ mod = make(self.fake, self.now, popen=self.spawned.append, runtime=d)
+ mod.state()
+ mod.actions["ssh"]({"vm": "alpha"})
+ self.assertIn(["kitty", "@", "--to", f"unix:{d}/kitty-4242", "launch", "--type=tab", "ssh", "alpha"],
+ self.fake.cmds)
+ self.assertIn(["hyprctl", "dispatch", "focuswindow", "pid:4242"], self.fake.cmds)
+ self.fake.kitty_ok = False
+ mod.actions["ssh"]({"vm": "alpha"})
+ self.assertEqual(self.spawned, [["kitty", "ssh", "alpha"]])
+
+
+if __name__ == "__main__":
+ unittest.main()