aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/vm.py
blob: 772e7b96852e5989ed80b48aaa657bf5911aac49 (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
# 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)