Files
glassMxrph/quickshell/helpers/metrics.py
T
mxandClaude Opus 5.5 99e64a7713 Add glassMxrph shell sources
Initial commit of the Quickshell desktop suite: bar, dock, launcher,
settings, Control Center, dashboard, OSD, lock screen, desktop widgets,
plugin host with the vendored Noctalia/Omarchy compatibility layer,
helpers, packaging, tests and phase documentation.

Includes the optimization work so far: usage widgets and dashboard
gauges no longer animate continuously, desktop widgets pause while
covered, system controls stop flickering on background polls, dock app
matching uses an indexed catalog, and workspace ghosts are created only
for occupied slots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 22:36:17 +02:00

195 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Read-only Linux telemetry. One streaming process owns all sampling/deltas."""
import csv
import json
import math
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time
def read(path):
try:
return Path(path).read_text().strip()
except OSError:
return ''
def number(value, divisor=1):
try:
result = float(value) / divisor
return result if math.isfinite(result) and result >= 0 else None
except (ValueError, TypeError):
return None
def cpu_counts(text):
row = next(line for line in text.splitlines() if line.startswith('cpu '))
v = [int(n) for n in row.split()[1:9]] # guest already included in user/nice
return sum(v), v[3] + (v[4] if len(v) > 4 else 0)
def cpu_percent(previous, current):
if previous is None:
return None
total, idle = current[0] - previous[0], current[1] - previous[1]
return max(0, min(100, 100 * (total - idle) / total)) if total > 0 and idle >= 0 else None
def memory(text):
v = {line.split(':')[0]: int(line.split()[1]) * 1024 for line in text.splitlines() if ':' in line}
total, available = v.get('MemTotal', 0), v.get('MemAvailable')
if not total or available is None:
return {'available': False}
used = max(0, total - available)
return dict(available=True, total=total, used=used, free=available, percent=100 * used / total)
def net_counts(text):
result = {}
for line in text.splitlines():
if ':' not in line:
continue
name, data = line.rsplit(':', 1)
fields = data.split()
if len(fields) >= 16:
result[name.strip()] = (int(fields[0]), int(fields[8]))
return result
def net_rates(previous, current, elapsed):
return {name: {'download': max(0, values[0] - previous[name][0]) / elapsed,
'upload': max(0, values[1] - previous[name][1]) / elapsed}
for name, values in current.items() if name in previous and elapsed > 0}
def nvidia_rows(text):
result = []
for row in csv.reader(text.splitlines(), skipinitialspace=True):
if len(row) != 8:
continue
uid, name, busy, temp, used, total, clock, power = row
result.append(dict(id=uid, name=name, provider='nvidia-smi', percent=number(busy),
temperature=number(temp), used=number(used, 1 / 1048576),
total=number(total, 1 / 1048576), frequency=number(clock), power=number(power)))
return result
class Collector:
def __init__(self, options):
self.options = options
self.previous_cpu = None
self.previous_net = {}
self.previous_time = None
self.gpus = []
self.gpu_time = -100
self.storage = []
self.storage_time = -100
self.nvidia = shutil.which('nvidia-smi')
self.cpu_name = next((line.split(':', 1)[1].strip() for line in read('/proc/cpuinfo').splitlines()
if line.startswith('model name')), 'CPU')
def gpu(self):
result = []
if self.nvidia:
try:
p = subprocess.run([self.nvidia, '--query-gpu=uuid,name,utilization.gpu,temperature.gpu,memory.used,memory.total,clocks.gr,power.draw',
'--format=csv,noheader,nounits'], capture_output=True, text=True, timeout=2)
if p.returncode == 0:
result.extend(nvidia_rows(p.stdout))
except (OSError, subprocess.TimeoutExpired):
pass
for device in sorted(Path('/sys/class/drm').glob('card[0-9]*/device')):
if not re.fullmatch(r'card\d+', device.parent.name):
continue
vendor = read(device / 'vendor')
if vendor == '0x10de':
continue # NVIDIA handled above, no duplicate device
hwm = next(iter(device.glob('hwmon/hwmon*')), None)
def sensor(name, divisor=1):
return number(read(hwm / name), divisor) if hwm else None
result.append(dict(id=str(device.resolve()), name=read(device / 'product_name') or
('AMD' if vendor == '0x1002' else 'Intel' if vendor == '0x8086' else 'GPU') + ' · ' + device.parent.name,
provider='sysfs', percent=number(read(device / 'gpu_busy_percent')),
temperature=sensor('temp1_input', 1000), used=number(read(device / 'mem_info_vram_used')),
total=number(read(device / 'mem_info_vram_total')), frequency=sensor('freq1_input', 1000000),
power=sensor('power1_average', 1000000)))
return result
def sample(self):
now = time.monotonic()
warnings = []
cpu = dict(name=self.cpu_name, percent=None, temperature=None, frequency=None, power=None)
try:
counts = cpu_counts(read('/proc/stat'))
cpu['percent'] = cpu_percent(self.previous_cpu, counts)
self.previous_cpu = counts
except (ValueError, StopIteration, IndexError):
warnings.append('CPU counters unavailable')
frequencies = [number(line.split(':', 1)[1]) for line in read('/proc/cpuinfo').splitlines() if line.startswith('cpu MHz')]
frequencies = [v for v in frequencies if v is not None]
cpu['frequency'] = sum(frequencies) / len(frequencies) if frequencies else None
temperatures = []
for hw in Path('/sys/class/hwmon').glob('hwmon*'):
if read(hw / 'name') in ('k10temp', 'coretemp', 'zenpower', 'cpu_thermal'):
temperatures += [number(read(p), 1000) for p in hw.glob('temp*_input')]
temperatures = [v for v in temperatures if v is not None]
cpu['temperature'] = max(temperatures) if temperatures else None
try:
ram = memory(read('/proc/meminfo'))
except (ValueError, IndexError):
ram = {'available': False}
current = net_counts(read('/proc/net/dev'))
rates = net_rates(self.previous_net, current, now - self.previous_time) if self.previous_time else {}
interfaces = []
for name in sorted(current):
if name == 'lo':
continue
values = rates.get(name, {'download': None, 'upload': None})
interfaces.append(dict(name=name, **values))
selected = self.options.get('networkInterface', 'auto')
# Auto uses physical interfaces; excludes VPN/bridge/veth double counting.
names = [i['name'] for i in interfaces if (Path('/sys/class/net') / i['name'] / 'device').exists()] if selected == 'auto' else [selected]
valid = [rates[n] for n in names if n in rates]
network = dict(interfaces=interfaces, selected=names,
download=sum(v['download'] for v in valid) if valid else None,
upload=sum(v['upload'] for v in valid) if valid else None)
self.previous_net, self.previous_time = current, now
if now - self.gpu_time >= max(5, self.options.get('interval', 2)):
self.gpus, self.gpu_time = self.gpu(), now
if now - self.storage_time >= 15:
self.storage = []
for path in self.options.get('storagePaths', ['/']):
try:
s = os.statvfs(path)
total, free, available = s.f_blocks * s.f_frsize, s.f_bfree * s.f_frsize, s.f_bavail * s.f_frsize
used = total - free
self.storage.append(dict(path=path, available=True, total=total, used=used, free=free,
availableBytes=available, percent=100 * used / total if total else 0))
except OSError:
self.storage.append(dict(path=path, available=False))
self.storage_time = now
return dict(cpu=cpu, ram=ram, gpus=self.gpus, storage=self.storage, network=network,
timestamp=time.time(), warnings=warnings)
def main():
options = json.loads(sys.argv[1]) if len(sys.argv) > 1 else {}
interval = min(30, max(1, float(options.get('interval', 2))))
collector = Collector(options)
while True:
started = time.monotonic()
print(json.dumps(collector.sample(), allow_nan=False), flush=True)
time.sleep(max(.1, interval - (time.monotonic() - started)))
if __name__ == '__main__':
try:
main()
except (BrokenPipeError, KeyboardInterrupt):
pass