# deck-it - libvirt VMs: power, snapshots, ssh in kitty # 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. """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)