aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/stats.py
blob: 121572e70bcc45092ee50b0882ee0b1ed5ec5da4 (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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# deck-it - stats 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.

"""System stats: CPU, memory, GPU (Intel xe), network, uptime, pending updates.

The Arc driver exposes temperature and fan through hwmon and no VRAM capacity;
VRAM in use and engine busy cycles come from the DRM fdinfo scan, as quickshell's perf panel does.
"""

import json
import os
import platform
import re
import shlex
import socket
import subprocess
import threading
import time
from pathlib import Path

from ..module import Module

UNITS = {"": 1, "K": 1024, "M": 1024 ** 2, "G": 1024 ** 3, "T": 1024 ** 4}


def _read(path, default=""):
    try:
        return Path(path).read_text().strip()
    except OSError:
        return default


def _parse_bytes(value):
    if isinstance(value, int):
        return value
    m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([KMGT]?)(?:i?B)?", str(value).strip(), re.I)
    if not m:
        return None
    return int(float(m[1]) * UNITS[m[2].upper()])


ENGINES = ("rcs", "ccs")   # render (games) and compute (local LLMs)


def _intel_fdinfo(root=Path("/proc")):
    """One pass over xe clients, each client id counted once.

    Returns (VRAM bytes, {engine: busy cycles summed}, {engine: GPU cycles}).
    """
    seen, total, busy, clock = set(), 0, dict.fromkeys(ENGINES, 0), {}
    for fdinfo in root.glob("[0-9]*/fdinfo/*"):
        try:
            text = fdinfo.read_text()
        except OSError:
            continue
        fields = {}
        for line in text.splitlines():
            key, sep, value = line.partition(":")
            if sep and key.startswith("drm-"):
                fields[key] = value.strip()
        client = fields.get("drm-client-id")
        if fields.get("drm-driver") != "xe" or not client or client in seen:
            continue
        seen.add(client)
        for e in ENGINES:
            if fields.get(f"drm-cycles-{e}", "").isdigit():
                busy[e] += int(fields[f"drm-cycles-{e}"])
                clock[e] = max(clock.get(e, 0), int(fields.get(f"drm-total-cycles-{e}", "0") or 0))
        m = re.match(r"(\d+)\s*([KMGT]?)(?:i?B)?", fields.get("drm-resident-vram0", ""))
        if m:
            total += int(m[1]) * UNITS[m[2].upper()]
    return total, busy, clock


def _gpu_util(before, after):
    """Busiest engine's percentage between two _intel_fdinfo samples, or None."""
    if not before:
        return None
    pcts = []
    for e in ENGINES:
        dt = after[2].get(e, 0) - before[2].get(e, 0)
        if dt > 0:
            # ponytail: a client exiting mid-sample takes its cycles with it,
            # so the delta can dip below zero; clamp rather than track clients.
            pcts.append(min(100, max(0, 100 * (after[1][e] - before[1][e]) / dt)))
    return round(max(pcts)) if pcts else None


def _cpu_sensor(hw):
    names = {_read(h / "name"): h for h in Path("/sys/class/hwmon").glob("hwmon*")}
    want = hw.get("cpu_sensor", "auto")
    for name in ([want] if want != "auto" else ["k10temp", "zenpower", "coretemp", "cpu_thermal", "acpitz"]):
        if name in names:
            return names[name] / "temp1_input"
    return None


def _battery(hw):
    want = hw.get("battery", "auto")
    if want != "auto":
        return Path("/sys/class/power_supply") / want
    for p in sorted(Path("/sys/class/power_supply").glob("*")):
        if _read(p / "type") == "Battery":
            return p
    return None


def _cpu_name(cpuinfo):
    """'AMD Ryzen 7 9700X 8-Core Processor' -> 'AMD Ryzen 7 9700X'."""
    for line in cpuinfo.splitlines():
        if line.startswith("model name"):
            name = re.sub(r"\((R|TM)\)|\bCPU\b|@.*|\d+-Core|Processor", "", line.partition(":")[2])
            return " ".join(name.split()) or None
    return None


def _os(text):
    """/etc/os-release -> {"id", "name", "codename"}."""
    f = {k: v.strip().strip('"') for k, _, v in
         (line.partition("=") for line in text.splitlines()) if v}
    name = " ".join(filter(None, (f.get("NAME"), f.get("VERSION_ID"))))
    return {"id": f.get("ID", "linux"), "name": name or "Linux",
            "codename": f.get("VERSION_CODENAME", "")}


def _gpu_name(lspci):
    """lspci -mm's line -> 'Intel Arc B580': the vendor's first word, then the
    marketing name in brackets, else the whole device name."""
    try:
        f = shlex.split(lspci)
    except ValueError:
        return None
    if len(f) < 4:
        return None
    m = re.search(r"\[(.+?)\]", f[3])
    return f"{f[2].split()[0]} {m[1] if m else f[3]}"


def _gpu(hw):
    if hw.get("gpu", "auto") == "none":
        return None
    for name in Path("/sys/class/hwmon").glob("hwmon*/name"):
        if _read(name) == "xe":
            slot = (name.parent / "device").resolve().name
            try:
                out = subprocess.run(["lspci", "-mm", "-s", slot], capture_output=True,
                                     text=True, timeout=2).stdout
            except (OSError, subprocess.TimeoutExpired):
                out = ""
            return {"hwmon": name.parent, "name": _gpu_name(out) or "GPU"}
    return None


def _net_iface(hw):
    if hw.get("net", "auto") != "auto":
        return hw["net"]
    for line in _read("/proc/net/route").splitlines()[1:]:
        f = line.split()
        if f[1] == "00000000":
            return f[0]
    return None


def _to_install(doc):
    """updatesctl's JSON -> what keystone's tile counts "to install"."""
    sw = doc.get("slackware", {})
    return sum(len(sw.get(k, [])) for k in ("upgrade", "new", "removed")) + len(doc.get("upgrade", []))


def make(cfg: dict) -> Module:
    hw = cfg.get("hardware", {})
    updatesctl = os.path.expanduser(cfg.get("dashboard", {}).get("updates", ""))
    upd = {"n": None, "t": 0, "busy": False}

    def read_updates():
        try:
            out = subprocess.run([updatesctl], capture_output=True, text=True, timeout=30).stdout
            upd["n"] = _to_install(json.loads(out))
        except (OSError, subprocess.TimeoutExpired, ValueError):
            pass
        upd.update(t=time.monotonic(), busy=False)

    def updates():
        # ponytail: re-read every 5 min in a thread, so the NAS reads never stall the 1 s poll
        if updatesctl and not upd["busy"] and (not upd["t"] or time.monotonic() - upd["t"] > 300):
            upd["busy"] = True
            threading.Thread(target=read_updates, daemon=True).start()
        return upd["n"]
    cpu_sensor = _cpu_sensor(hw)
    battery = _battery(hw)
    gpu = _gpu(hw)
    cpu_name = _cpu_name(_read("/proc/cpuinfo")) or "CPU"
    os_info = {**_os(_read("/etc/os-release")), "kernel": platform.release()}
    gpu_total = _parse_bytes(hw.get("gpu_mem_total", "")) if gpu else None
    prev = {"cpu": None, "net": None, "t": None, "gpu_t": 0, "gpu_v": None, "gpu_s": None}

    def cpu_percent():
        fields = list(map(int, _read("/proc/stat").splitlines()[0].split()[1:]))
        idle, total = fields[3] + fields[4], sum(fields)
        last, prev["cpu"] = prev["cpu"], (idle, total)
        if not last or total == last[1]:
            return 0
        return round(100 * (1 - (idle - last[0]) / (total - last[1])))

    def net_rates(now):
        iface = _net_iface(hw)
        for line in _read("/proc/net/dev").splitlines():
            if iface and line.strip().startswith(iface + ":"):
                v = line.split(":")[1].split()
                cur = (iface, int(v[0]), int(v[8]))
                break
        else:
            return 0, 0
        last, lt = prev["net"], prev["t"]
        prev["net"], prev["t"] = cur, now
        if not last or last[0] != iface or now == lt:
            return 0, 0
        return round((cur[1] - last[1]) / (now - lt)), round((cur[2] - last[2]) / (now - lt))

    def read_gpu():
        if not gpu:
            return None
        # The fdinfo scan touches every process, so keep it to once every 2 s.
        if time.time() - prev["gpu_t"] < 2:
            return prev["gpu_v"]
        sample = _intel_fdinfo()
        temp = _read(gpu["hwmon"] / "temp2_input")
        fan = _read(gpu["hwmon"] / "fan1_input")
        v = {
            "name": gpu["name"],
            "util": _gpu_util(prev["gpu_s"], sample),
            "temp": round(int(temp) / 1000) if temp else None,
            "fan": int(fan) if fan else None,
            "memUsed": sample[0],
            "memTotal": gpu_total,
        }
        prev.update(gpu_t=time.time(), gpu_v=v, gpu_s=sample)
        return v

    def state():
        now = time.monotonic()
        mem = {line.split(":")[0]: int(line.split()[1]) for line in _read("/proc/meminfo").splitlines()}
        down, up = net_rates(now)
        t = _read(cpu_sensor) if cpu_sensor else ""
        return {
            "host": socket.gethostname(),
            "os": os_info,
            "uptime": int(float(_read("/proc/uptime", "0").split()[0])),
            "cpu": cpu_percent(),
            "cpuName": cpu_name,
            "cpuTemp": round(int(t) / 1000) if t else None,
            "memUsed": mem["MemTotal"] - mem["MemAvailable"],
            "memTotal": mem["MemTotal"],
            "gpu": read_gpu(),
            "battery": {"level": int(_read(battery / "capacity", "0")), "status": _read(battery / "status")}
            if battery else None,
            "net": {"down": down, "up": up},
            "updates": updates(),
        }

    return Module(name="stats", title="System", state=state)