diff options
Diffstat (limited to 'deckit/modules/vm.py')
| -rw-r--r-- | deckit/modules/vm.py | 97 |
1 files changed, 82 insertions, 15 deletions
diff --git a/deckit/modules/vm.py b/deckit/modules/vm.py index 772e7b9..ae915b3 100644 --- a/deckit/modules/vm.py +++ b/deckit/modules/vm.py @@ -17,23 +17,28 @@ """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. +poll. The slower per-VM reads (managed save, snapshots, the guest agent's IP, +whether sshd answers) run in a thread at most every SLOW seconds, BOOT while a +VM is booting, 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 socket import subprocess +import tempfile import threading import time +from datetime import datetime from pathlib import Path from ..module import Module, ModuleError from .windows import hypr_lua SLOW = 10 +BOOT = 2 # re-read this often while a running VM's sshd is not up yet +BOOT_FOR = 300 # ...for this long after it was first seen booting STATES = {1: "running", 2: "blocked", 3: "paused", 4: "shutting down", 5: "shut off", 6: "crashed", 7: "suspended"} POWER = { @@ -58,12 +63,21 @@ def _spawn(fn): threading.Thread(target=fn, daemon=True).start() +def _probe(host, port): + try: + socket.create_connection((host, port), timeout=1).close() + return True + except OSError: + return False + + 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}) + cur = doms.setdefault(m[1], {"state": "unknown", "vcpus": 0, "ns": None, "mem": None, + "available": None, "usable": None}) continue kv = line.strip().split("=", 1) if cur is None or len(kv) != 2: @@ -77,9 +91,20 @@ def parse_domstats(text: str) -> dict: cur["ns"] = int(v) elif k == "balloon.current": cur["mem"] = int(v) * 1024 + elif k in ("balloon.available", "balloon.usable"): + cur[k.split(".")[1]] = int(v) * 1024 return doms +def parse_snapshots(table: str, current: str) -> list: + """`virsh snapshot-list`'s table, oldest first, with epoch creation times.""" + snaps = [] + for name, when in re.findall(r"^\s*(\S+)\s+(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4})", table, re.M): + created = int(datetime.strptime(when, "%Y-%m-%d %H:%M:%S %z").timestamp()) + snaps.append({"name": name, "created": created, "current": name == current}) + return sorted(snaps, key=lambda s: s["created"]) + + def _ip(text: str) -> str: for addr in re.findall(r"\sipv4\s+(\d+\.\d+\.\d+\.\d+)/", text): if not addr.startswith("127."): @@ -92,22 +117,47 @@ def make(cfg: dict) -> Module: clock = cfg.get("clock", time.monotonic) spawn = cfg.get("spawn", _spawn) popen = cfg.get("popen", _popen) + probe = cfg.get("probe", _probe) 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": {}} + booting = {} # name -> when first seen running without sshd + targets = {} # name -> (host, port) from `ssh -G` + + def ssh_target(name, ip): + """An ssh alias named after the VM may move sshd off port 22, so host + and port come from `ssh -G`; with no alias it echoes the name back, and + the agent's address is used instead.""" + if name not in targets: + out = run(["ssh", "-G", name]).stdout + host = re.search(r"^hostname (\S+)", out, re.M) + port = re.search(r"^port (\d+)", out, re.M) + targets[name] = (host[1] if host else name, int(port[1]) if port else 22) + host, port = targets[name] + return (ip if host == name else host), port 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 "" + current = run(["virsh", "snapshot-current", "--name", name]) + snaps = parse_snapshots(run(["virsh", "snapshot-list", name]).stdout, + current.stdout.strip() if current.returncode == 0 else "") + ip, ready = "", None + if d["state"] == "running": + ip = _ip(run(["virsh", "domifaddr", name, "--source", "agent"]).stdout) + host, port = ssh_target(name, ip) + ready = bool(host) and probe(host, port) + if ready: + booting.pop(name, None) + else: + booting.setdefault(name, clock()) + else: + booting.pop(name, None) 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} + "snapshots": snaps, "ip": ip, "ready": ready} slow["data"] = data slow["busy"] = False @@ -122,7 +172,8 @@ def make(cfg: dict) -> Module: return {"offline": True, "reason": (p.stderr or "").strip()} doms.clear() doms.update(parse_domstats(p.stdout)) - if clock() - slow["at"] >= SLOW: + boot = any(clock() - t < BOOT_FOR for t in booting.values()) + if clock() - slow["at"] >= (BOOT if boot else SLOW): kick() now, vms = clock(), [] for name, d in sorted(doms.items()): @@ -134,9 +185,11 @@ def make(cfg: dict) -> Module: / (d["vcpus"] or 1) * 100)) last[name] = (d["ns"], now) extra = slow["data"].get(name, {}) + used = d["available"] - d["usable"] if d["available"] and d["usable"] is not None else None 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", [])}) + "mem": d["mem"], "used": used, "ip": extra.get("ip", ""), + "ready": extra.get("ready") if d["state"] == "running" else None, + "saved": extra.get("saved", False), "snapshots": extra.get("snapshots", [])}) return {"offline": False, "vms": vms} def virsh(*args, timeout=120): @@ -152,7 +205,7 @@ def make(cfg: dict) -> Module: if not snap: return name, None s = str(body.get("snap", "")) - if s not in slow["data"].get(name, {}).get("snapshots", []): + if s not in [x["name"] for x in slow["data"].get(name, {}).get("snapshots", [])]: raise ModuleError(f"unknown snapshot: {s}") return name, s @@ -182,6 +235,20 @@ def make(cfg: dict) -> Module: return popen(["kitty", "ssh", name]) + def image(key): + """The VM's display, as a small JPEG; only a running VM the last state listed.""" + if doms.get(key, {}).get("state") != "running": + return None + with tempfile.TemporaryDirectory() as d: + raw, jpg = f"{d}/screen", f"{d}/screen.jpg" + if run(["virsh", "screenshot", key, "--file", raw], timeout=5).returncode != 0: + return None + run(["ffmpeg", "-v", "error", "-i", raw, "-vf", "scale=640:-2", "-q:v", "5", "-y", jpg], timeout=5) + try: + return Path(jpg).read_bytes(), "image/jpeg" + except OSError: + return None + 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) + return Module(name="vm", title="VMs", state=state, actions=actions, image=image) |
