aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/vm.py
blob: ae915b3cffb3f17397ff37e7d416e6961442875d (plain)
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
# 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,
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 = {
    "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 _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,
                                         "available": None, "usable": 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
        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."):
            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)
    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
            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": snaps, "ip": ip, "ready": ready}
        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))
        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()):
            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, {})
            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"], "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):
        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 [x["name"] for x 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])

    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, image=image)