Add branded Windows resource monitor

Introduce a native tray monitor for local and Linux-over-SSH telemetry, with configurable graphs, optional SQLite history, remote target management, and Windows packaging. Add Design Creations branding, an About tab, project documentation, and automated validation.
This commit is contained in:
2026-11-26 06:20:05 -06:00
parent 2efae3fcd8
commit 7628161f07
49 changed files with 5926 additions and 0 deletions

17
arm/providers/__init__.py Normal file
View File

@@ -0,0 +1,17 @@
"""Independent telemetry providers."""
import logging
LOG = logging.getLogger(__name__)
class Provider:
def close(self):
"""Release resources in the sampling worker."""
def cancel(self):
"""Request cancellation without waiting on a blocking query."""
class WindowsRemoteProvider(Provider):
def sample(self):
raise NotImplementedError("Remote Windows telemetry is planned")

212
arm/providers/gpu.py Normal file
View File

@@ -0,0 +1,212 @@
import logging
import re
from collections import Counter, defaultdict
from time import perf_counter as monotonic, time
from . import Provider
from .native import Pdh, adapter_identity, adapters
from ..model import LOCAL, Device, Sample, aggregate, readings, usage
LOG = logging.getLogger(__name__)
LUID = re.compile(r"(luid_0x[0-9a-f]+_0x[0-9a-f]+)(?:_phys_(\d+))?", re.I)
ENGINE = re.compile(r"_eng_(\d+)_engtype_(.+?)(?:#\d+)?$", re.I)
GPU_UNITS = {
"util": "%", "vram_used": "B", "vram_total": "B", "vram_free": "B", "vram_pct": "%",
"shared_used": "B", "shared_total": "B", "shared_pct": "%",
"temperature": "°C", "clock": "MHz", "memory_clock": "MHz", "power": "W",
"power_limit": "W", "fan": "%", "encode": "%", "decode": "%", "compute": "%",
}
def gpu_metrics(values):
for key, capacity, used in (("vram", "vram_total", "vram_used"),
("shared", "shared_total", "shared_used")):
values[f"{key}_pct"] = usage(values.get(used), values.get(capacity))
if values.get("vram_used") is not None and values.get("vram_total"):
values.setdefault("vram_free", max(0, values["vram_total"] - values["vram_used"]))
return {f"gpu.{key}": (values.get(key), unit) for key, unit in GPU_UNITS.items()}
def engine_usage(rows):
engines = defaultdict(lambda: defaultdict(float))
for label, value in rows.items():
adapter, engine = LUID.search(label), ENGINE.search(label)
if adapter and engine:
engines[adapter[1].lower()][(adapter[2], engine[1], engine[2].lower())] += value
result = {}
for identifier, nodes in engines.items():
values = {"util": min(100, max(nodes.values()))}
for key, tokens in {"encode": ("videoencode",), "decode": ("videodecode",),
"compute": ("compute", "cuda")}.items():
values[key] = max((min(100, value) for node, value in nodes.items()
if any(token in node[-1] for token in tokens)), default=None)
result[identifier] = values
return result
def memory_usage(rows):
values = defaultdict(float)
for label, value in rows.items():
adapter = LUID.search(label)
if adapter:
values[adapter[1].lower()] += value
return values
class Nvml:
def __init__(self):
self.api = None
self.devices = []
try:
import pynvml
pynvml.nvmlInit()
self.api = pynvml
for index in range(pynvml.nvmlDeviceGetCount()):
handle = self.get("HandleByIndex", index)
if handle is None:
continue
name, pci, identifier = (self.get(key, handle) for key in ("Name", "PciInfo", "UUID"))
if name and pci and identifier:
if isinstance(name, bytes):
name = name.decode("utf-8", "replace")
if isinstance(identifier, bytes):
identifier = identifier.decode("ascii", "replace")
self.devices.append((str(identifier), name, pci.pciDeviceId >> 16,
(pci.bus, pci.device), handle))
LOG.info("NVML found %d GPU(s)", len(self.devices))
except (ImportError, OSError):
LOG.info("NVML unavailable")
except Exception as exc:
LOG.info("NVML unavailable (%s)", type(exc).__name__)
def get(self, key, *args):
try:
return getattr(self.api, "nvmlDeviceGet" + key)(*args)
except (self.api.NVMLError, AttributeError):
return None
def metrics(self, handle):
n = self.api
sensors = {}
utilization = self.get("UtilizationRates", handle)
if utilization is not None:
sensors["util"] = utilization.gpu
mem = self.get("MemoryInfo", handle)
if mem is not None:
for attr in ("total", "used", "free"):
sensors[f"vram_{attr}"] = getattr(mem, attr)
for key, command, args, factor in (
("temperature", "Temperature", (n.NVML_TEMPERATURE_GPU,), 1),
("clock", "ClockInfo", (n.NVML_CLOCK_GRAPHICS,), 1),
("memory_clock", "ClockInfo", (n.NVML_CLOCK_MEM,), 1),
("power", "PowerUsage", (), .001), ("power_limit", "PowerManagementLimit", (), .001),
("fan", "FanSpeed", (), 1), ("encode", "EncoderUtilization", (), 1),
("decode", "DecoderUtilization", (), 1),
):
value = self.get(command, handle, *args)
if value is not None:
sensors[key] = value[0] * factor if isinstance(value, (tuple, list)) else value * factor
return sensors
def close(self):
if self.api:
try:
self.api.nvmlShutdown()
except self.api.NVMLError as exc:
LOG.debug("NVML shutdown returned %s", type(exc).__name__)
class WddmGpu(Provider):
identifier = "GPU"
def __init__(self, settings):
self.selected = settings.gpus
self.interval = settings.local_interval
self.last_tick = 0
self.nvml = Nvml()
try:
self.devices = adapters()
except OSError:
LOG.warning("DXGI hardware enumeration failed", exc_info=True)
self.devices = []
self.counters = Pdh({
"engine": r"\GPU Engine(*)\Utilization Percentage",
"dedicated": r"\GPU Adapter Memory(*)\Dedicated Usage",
"shared": r"\GPU Adapter Memory(*)\Shared Usage",
})
groups = {}
self.locations = {}
identities = [(adapter, *adapter_identity(adapter)) for adapter in self.devices]
physical = {(a.vendor, a.device, a.subsystem) for a, location, _ in identities if location is not None}
for adapter, location, flags in identities:
if location is None and (adapter.vendor, adapter.device, adapter.subsystem) in physical:
LOG.info("Skipping non-PCI DXGI alias %s (%s, type %s)", adapter.identifier, adapter.name, flags)
continue
identifier = (f"pci:{adapter.vendor:04x}:{location[0]:02x}:{location[1]:02x}.{location[2]}"
if location is not None else adapter.identifier)
groups.setdefault(identifier, []).append(adapter)
self.locations[identifier] = location
LOG.info("DXGI adapter %s %s (%s)", adapter.identifier, adapter.name, identifier)
self.groups = groups
nvml_counts = Counter(device for _, _, device, _, _ in self.nvml.devices)
self.matches = {}
for identifier, name, device, pci, handle in self.nvml.devices:
candidates = [key for key, group in groups.items()
if group[0].vendor == 0x10de and group[0].device == device]
matches = [key for key in candidates
if self.locations[key] is not None and self.locations[key][:2] == pci]
if len(matches) == 1:
self.matches[matches[0]] = handle
elif len(candidates) == 1 and nvml_counts[device] == 1:
self.matches[candidates[0]] = handle
elif not matches and not any(a.vendor == 0x10de for a in self.devices):
self.matches[identifier] = (name, handle)
else:
LOG.info("NVML adapter identity unresolved for %s; using WDDM for that adapter", name)
def sample(self):
stamp, tick = time(), monotonic()
baseline = not 0 < tick - self.last_tick <= max(self.interval * 3, 2)
self.last_tick = tick
data = self.counters.collect()
engines = engine_usage(data.get("engine", {})) if not baseline else {}
dedicated = memory_usage(data.get("dedicated", {}))
shared = memory_usage(data.get("shared", {}))
items, devices, totals = [], [], []
def collect(identifier, name, metrics):
devices.append(Device("gpu", identifier, name))
values = gpu_metrics(metrics)
items.extend(readings(LOCAL, stamp, identifier, values))
if not self.selected or identifier in self.selected:
totals.append(values)
for identifier, group in self.groups.items():
adapter = group[0]
aliases = [item.identifier for item in group]
# Driver aliases refer to one PCI function. Take the largest reported
# adapter reading instead of adding capacity or mirrored counters twice.
metrics = {engine: max((engines[key][engine] for key in aliases
if key in engines and engines[key].get(engine) is not None),
default=None)
for engine in ("util", "encode", "decode", "compute")}
if adapter.dedicated:
metrics["vram_used"] = max((dedicated[key] for key in aliases if key in dedicated),
default=None)
metrics["vram_total"] = adapter.dedicated or None
metrics["shared_total"] = adapter.shared or None
metrics["shared_used"] = max((shared[key] for key in aliases if key in shared), default=None)
if identifier in self.matches:
metrics.update(self.nvml.metrics(self.matches[identifier]))
collect(identifier, adapter.name, metrics)
for identifier, match in self.matches.items():
if isinstance(match, tuple):
name, handle = match
collect(identifier, name, self.nvml.metrics(handle))
return Sample(LOCAL, self.identifier, stamp, tuple(items) + aggregate(LOCAL, stamp, "gpu", totals),
tuple(devices))
def close(self):
self.counters.close()
self.nvml.close()

View File

@@ -0,0 +1,101 @@
# The client sends a single dot for each observation over the existing channel.
export LC_ALL=C
os=$(uname -sr)
nvidia=$(command -v nvidia-smi || :)
sample() {
printf '@arm-begin\nos\t%s\n' "$os"
while read -r name value; do
case "$name" in
cpu|cpu[0-9]*) printf 'cpu\t%s\t%s\n' "$name" "$value";;
btime) printf 'boot\t%s\n' "$value";;
esac
done < /proc/stat
while read -r name value unit; do
case "$name" in
MemTotal:|MemAvailable:|SwapTotal:|SwapFree:|Committed_AS:|CommitLimit:)
printf 'ram\t%s\t%s\n' "${name%:}" "$value";;
esac
done < /proc/meminfo
model= frequency= physical= core= processor=
while IFS=: read -r key value; do
case "${key// /}" in
processor*) processor=$value;;
modelname*|Hardware*) [[ -n $model ]] || model=$value;;
cpuMHz*) [[ -n $frequency ]] || frequency=$value;;
physicalid*) physical=$value;;
coreid*) core=$value;;
'') [[ -z $processor ]] || printf 'core\t%s\t%s\t%s\n' "$processor" "$physical" "$core"
physical= core= processor=;;
esac
done < /proc/cpuinfo
[[ -z $processor ]] || printf 'core\t%s\t%s\t%s\n' "$processor" "$physical" "$core"
printf 'cpuinfo\t%s\t%s\n' "$model" "$frequency"
for sensor in /sys/class/hwmon/hwmon*; do
[[ -r $sensor/name ]] || continue
read -r driver < "$sensor/name"
case "$driver" in
coretemp|k10temp|zenpower)
temp= power=
[[ ! -r $sensor/temp1_input ]] || read -r temp < "$sensor/temp1_input"
[[ ! -r $sensor/power1_input ]] || read -r power < "$sensor/power1_input"
printf 'cpusensor\t%s\t%s\n' "$temp" "$power";;
esac
done
while read -r major minor dev rest; do
[[ -d /sys/block/$dev && -e /sys/block/$dev/device ]] || continue
printf 'disk\t%s\t%s\n' "$dev" "$rest"
done < /proc/diskstats
while IFS=: read -r dev rest; do
[[ -n $rest ]] || continue
dev=${dev//[[:space:]]/}
path=/sys/class/net/$dev
[[ -d $path ]] || continue
speed= state= physical=0
[[ ! -e $path/device ]] || physical=1
[[ ! -r $path/operstate ]] || read -r state < "$path/operstate"
{ [[ ! -r $path/speed ]] || read -r speed < "$path/speed"; } 2>/dev/null
printf 'net\t%s\t%s\t%s\t%s\t%s\n' "$dev" "$physical" "$state" "$speed" "$rest"
done < /proc/net/dev
for path in /sys/class/drm/card[0-9]*; do
[[ ${path##*/} =~ ^card[0-9]+$ && -r $path/device/vendor ]] || continue
dev=$path/device
vendor= id= slot= busy= used= total= temperature= clock= memory_clock= power= cap=
read -r vendor < "$dev/vendor"
if [[ $vendor == 0x10de && -n $nvidia ]]; then continue; fi
[[ ! -r $dev/device ]] || read -r id < "$dev/device"
if [[ -r $dev/uevent ]]; then
while IFS== read -r key value; do
[[ $key != PCI_SLOT_NAME ]] || slot=$value
done < "$dev/uevent"
fi
[[ ! -r $dev/gpu_busy_percent ]] || read -r busy < "$dev/gpu_busy_percent"
[[ ! -r $dev/mem_info_vram_used ]] || read -r used < "$dev/mem_info_vram_used"
[[ ! -r $dev/mem_info_vram_total ]] || read -r total < "$dev/mem_info_vram_total"
[[ ! -r $dev/pp_dpm_sclk ]] || while read -r _ val tag; do
[[ $tag != '*' ]] || clock=${val%[Mm][Hh][Zz]}
done < "$dev/pp_dpm_sclk"
[[ ! -r $dev/pp_dpm_mclk ]] || while read -r _ val tag; do
[[ $tag != '*' ]] || memory_clock=${val%[Mm][Hh][Zz]}
done < "$dev/pp_dpm_mclk"
for sensor in "$dev"/hwmon/hwmon*; do
[[ -d $sensor ]] || continue
[[ ! -r $sensor/temp1_input ]] || read -r temperature < "$sensor/temp1_input"
[[ ! -r $sensor/power1_average ]] || read -r power < "$sensor/power1_average"
[[ ! -r $sensor/power1_cap ]] || read -r cap < "$sensor/power1_cap"
break
done
printf 'drm\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
"${slot:-${path##*/}}" "$vendor" "$id" "$busy" "$used" "$total" "$temperature" \
"$clock" "$memory_clock" "$power,$cap"
done
if [[ -n $nvidia ]] && command -v timeout >/dev/null; then
timeout 2 "$nvidia" --format=csv,noheader,nounits \
--query-gpu=pci.bus_id,name,utilization.gpu,memory.used,memory.total,temperature.gpu,clocks.gr,clocks.mem,power.draw,power.limit,fan.speed,utilization.encoder,utilization.decoder \
2>/dev/null | while IFS= read -r gpu; do printf 'nvidia\t%s\n' "$gpu"; done
fi
printf '@arm-end\n'
}
while IFS= read -r action; do
[[ $action == . ]] || break
sample
done

266
arm/providers/native.py Normal file
View File

@@ -0,0 +1,266 @@
"""Windows performance data and adapter identity."""
import ctypes as ct
from ctypes import wintypes as w
import logging
from mmap import PAGESIZE
import uuid
import winreg
LOG = logging.getLogger(__name__)
class _Double(ct.Structure):
_fields_ = [("status", w.DWORD), ("value", ct.c_double)]
class _Item(ct.Structure):
_fields_ = [("name", w.LPWSTR), ("data", _Double)]
class Pdh:
MORE_DATA = 0x800007D2
def __init__(self, paths):
self.dll = ct.WinDLL("pdh")
hndl = w.HANDLE
for name, args in {
"PdhOpenQueryW": [w.LPCWSTR, ct.c_size_t, ct.POINTER(hndl)],
"PdhAddEnglishCounterW": [hndl, w.LPCWSTR, ct.c_size_t, ct.POINTER(hndl)],
"PdhCollectQueryData": [hndl],
"PdhGetFormattedCounterArrayW": [
hndl, w.DWORD, ct.POINTER(w.DWORD), ct.POINTER(w.DWORD), ct.c_void_p],
"PdhCloseQuery": [hndl],
}.items():
fn = getattr(self.dll, name)
fn.argtypes = args
fn.restype = w.DWORD
self.query = hndl()
result = self.dll.PdhOpenQueryW(None, 0, ct.byref(self.query))
if result:
raise OSError(f"PdhOpenQuery returned {result:#x}")
self.counters = {}
for key, path in paths.items():
counter = hndl()
result = self.dll.PdhAddEnglishCounterW(self.query, path, 0, ct.byref(counter))
if result:
LOG.info("Windows counter unavailable %s (%#x)", key, result)
else:
self.counters[key] = counter
def collect(self):
result = self.dll.PdhCollectQueryData(self.query)
if result and self.counters:
LOG.debug("Windows query unavailable (%#x)", result)
return {key: self._array(counter) for key, counter in self.counters.items()}
def _array(self, counter):
length, count = w.DWORD(), w.DWORD()
getter = self.dll.PdhGetFormattedCounterArrayW
for _ in range(3):
result = getter(counter, 0x200, ct.byref(length), ct.byref(count), None)
if result != self.MORE_DATA or not 0 < length.value <= 32 * 1024 * 1024:
return {}
data = ct.create_string_buffer(length.value)
result = getter(counter, 0x200, ct.byref(length), ct.byref(count), data)
if not result:
rows = ct.cast(data, ct.POINTER(_Item))
return {rows[i].name: rows[i].data.value for i in range(count.value)
if rows[i].data.status in (0, 1) and rows[i].name}
if result != self.MORE_DATA:
break
return {}
def close(self):
if self.query:
self.dll.PdhCloseQuery(self.query)
self.query = None
class _Luid(ct.Structure):
_fields_ = [("low", w.DWORD), ("high", w.LONG)]
class Adapter(ct.Structure):
_fields_ = [("name", w.WCHAR * 128), ("vendor", w.UINT), ("device", w.UINT),
("subsystem", w.UINT), ("revision", w.UINT), ("dedicated", ct.c_size_t),
("system", ct.c_size_t), ("shared", ct.c_size_t), ("luid", _Luid),
("flags", w.UINT)]
@property
def identifier(self):
return f"luid_0x{self.luid.high & 0xffffffff:08x}_0x{self.luid.low:08x}"
class _OpenAdapter(ct.Structure):
_fields_ = [("luid", _Luid), ("handle", w.UINT)]
class _QueryAdapter(ct.Structure):
_fields_ = [("handle", w.UINT), ("kind", w.UINT), ("data", ct.c_void_p), ("size", w.UINT)]
def adapter_identity(adapter):
gdi = ct.WinDLL("gdi32")
opened = _OpenAdapter(adapter.luid)
create = gdi.D3DKMTOpenAdapterFromLuid
create.argtypes = [ct.POINTER(_OpenAdapter)]
if create(ct.byref(opened)):
return None, None
close = gdi.D3DKMTCloseAdapter
close.argtypes = [ct.POINTER(w.UINT)]
try:
result = (w.UINT * 3)()
query = gdi.D3DKMTQueryAdapterInfo
query.argtypes = [ct.POINTER(_QueryAdapter)]
args = _QueryAdapter(opened.handle, 6, ct.addressof(result), ct.sizeof(result))
location = (tuple(result) if not query(ct.byref(args)) and result[0] <= 255
and result[1] <= 31 and result[2] <= 7 else None)
flags = w.UINT()
args = _QueryAdapter(opened.handle, 15, ct.addressof(flags), ct.sizeof(flags))
return location, flags.value if not query(ct.byref(args)) else None
finally:
close(ct.byref(w.UINT(opened.handle)))
def _method(ptr, slot, result, *args):
table = ct.cast(ptr, ct.POINTER(ct.POINTER(ct.c_void_p))).contents
return ct.WINFUNCTYPE(result, ct.c_void_p, *args)(table[slot])
def adapters():
create = ct.WinDLL("dxgi").CreateDXGIFactory1
create.argtypes = [ct.c_void_p, ct.POINTER(ct.c_void_p)]
create.restype = ct.c_long
factory = ct.c_void_p()
identifier = ct.create_string_buffer(uuid.UUID("770aae78-f26f-4dba-a829-253c83d1b387").bytes_le)
result = create(identifier, ct.byref(factory))
if result:
raise OSError(f"DXGI initialization returned {result & 0xffffffff:#x}")
devices = []
try:
enum = _method(factory, 12, ct.c_long, w.UINT, ct.POINTER(ct.c_void_p))
for index in range(128):
adapter = ct.c_void_p()
if enum(factory, index, ct.byref(adapter)):
break
try:
description = Adapter()
if not _method(adapter, 10, ct.c_long, ct.POINTER(Adapter))(adapter, ct.byref(description)):
if not description.flags & 2 and description.vendor in (0x10de, 0x1002, 0x8086):
devices.append(description)
finally:
_method(adapter, 2, w.ULONG)(adapter)
finally:
_method(factory, 2, w.ULONG)(factory)
return devices
class _Perf(ct.Structure):
_fields_ = [("size", w.DWORD)] + [(name, ct.c_size_t) for name in (
"commit", "commit_limit", "commit_peak", "physical", "available", "cache",
"kernel", "paged", "nonpaged", "page_size")] + [
(name, w.DWORD) for name in ("handles", "processes", "threads")]
def commit():
info = _Perf()
info.size = ct.sizeof(info)
get = ct.WinDLL("kernel32").K32GetPerformanceInfo
get.argtypes = [ct.POINTER(_Perf), w.DWORD]
get.restype = w.BOOL
if get(ct.byref(info), info.size):
return info.commit * info.page_size, info.commit_limit * info.page_size
return None, None
class _PageFile(ct.Structure):
_fields_ = [("size", w.DWORD), ("reserved", w.DWORD), ("total", ct.c_size_t),
("used", ct.c_size_t), ("peak", ct.c_size_t)]
def pagefiles():
rows = []
callback = ct.WINFUNCTYPE(w.BOOL, ct.c_void_p, ct.POINTER(_PageFile), w.LPCWSTR)
@callback
def collect(_context, info, _filename):
rows.append((info.contents.used, info.contents.total))
return True
enumerate_files = ct.WinDLL("psapi").EnumPageFilesW
enumerate_files.argtypes = [callback, ct.c_void_p]
enumerate_files.restype = w.BOOL
if enumerate_files(collect, None):
return (sum(used for used, _ in rows) * PAGESIZE,
sum(total for _, total in rows) * PAGESIZE)
return None, None
def cpu_identity():
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as key:
return winreg.QueryValueEx(key, "ProcessorNameString")[0].strip()
except OSError:
return "Windows CPU"
def physical_cores():
get = ct.WinDLL("kernel32").GetLogicalProcessorInformationEx
get.argtypes = [ct.c_int, ct.c_void_p, ct.POINTER(w.DWORD)]
get.restype = w.BOOL
length = w.DWORD()
get(0, None, ct.byref(length))
if not length.value:
return []
buf = ct.create_string_buffer(length.value)
if not get(0, buf, ct.byref(length)):
return []
offset, cores = 0, []
while offset + 32 <= length.value:
size = w.DWORD.from_buffer(buf, offset + 4).value
groups = w.WORD.from_buffer(buf, offset + 30).value
if size < 32 + groups * 16 or offset + size > length.value:
break
processors = []
for group_index in range(groups):
start = offset + 32 + group_index * 16
mask = ct.c_uint64.from_buffer(buf, start).value
group = w.WORD.from_buffer(buf, start + 8).value
processors.extend(group * 64 + bit for bit in range(64) if mask & (1 << bit))
if processors:
cores.append(processors)
offset += size
return cores
class _InterfaceRow(ct.Structure):
_fields_ = [("luid", ct.c_uint64), ("index", w.ULONG), ("guid", ct.c_byte * 16),
("alias", w.WCHAR * 257), ("description", w.WCHAR * 257),
("address_length", w.ULONG), ("address", ct.c_byte * 32),
("permanent", ct.c_byte * 32), ("mtu", w.ULONG), ("type", w.ULONG),
("tunnel", w.ULONG), ("media", w.ULONG), ("physical_medium", w.ULONG),
("access", w.ULONG), ("direction", w.ULONG), ("flags", ct.c_ubyte),
("oper_status", w.ULONG), ("admin_status", w.ULONG), ("connect", w.ULONG),
("network_guid", ct.c_byte * 16), ("connection_type", w.ULONG),
("transmit", ct.c_uint64), ("receive", ct.c_uint64),
("counters", ct.c_uint64 * 18)]
def interface_info():
ip = ct.WinDLL("iphlpapi")
get = ip.GetIfTable2
get.argtypes = [ct.POINTER(ct.c_void_p)]
get.restype = w.ULONG
free = ip.FreeMibTable
free.argtypes = [ct.c_void_p]
free.restype = None
table = ct.c_void_p()
if get(ct.byref(table)):
return {}
try:
count = w.ULONG.from_address(table.value).value
rows = (_InterfaceRow * count).from_address(table.value + ct.alignment(_InterfaceRow))
return {row.alias: (bool(row.flags & 1) and row.type in (6, 71),
row.transmit, row.receive) for row in rows}
finally:
free(table)

367
arm/providers/ssh.py Normal file
View File

@@ -0,0 +1,367 @@
import base64
import csv
import hashlib
import io
from math import isfinite
from pathlib import Path
import socket
import shlex
import threading
from collections import defaultdict
from dataclasses import dataclass
import logging
from time import perf_counter as monotonic, time
import paramiko
from . import Provider
from .gpu import gpu_metrics
from .windows import cpu_group, disk_metrics, net_metrics
from ..model import Device, Sample, TOTAL, aggregate, rate, readings, usage
LOG = logging.getLogger(__name__)
SCRIPT = Path(__file__).with_name("linux_probe.sh")
HOST_LOCK = threading.Lock()
MAX_FRAME = 1024 * 1024
VENDORS = {"0x1002": "AMD", "0x8086": "Intel", "0x10de": "NVIDIA"}
def probe_command():
# Passing the fixed program in -c leaves channel stdin dedicated to tokens.
return "bash --noprofile --norc -c " + shlex.quote(SCRIPT.read_text(encoding="utf-8"))
@dataclass(frozen=True)
class HostKey:
label: str
key: object
@property
def fingerprint(self):
sha = hashlib.sha256(self.key.asbytes()).digest()
return "SHA256:" + base64.b64encode(sha).decode("ascii").rstrip("=")
class UntrustedHost(paramiko.SSHException):
def __init__(self, label, key):
super().__init__("New SSH host key")
self.host_key = HostKey(label, key)
class RecordUnknownKey(paramiko.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
raise UntrustedHost(hostname, key)
def known_hosts(path):
keys = paramiko.HostKeys()
if path.is_file():
keys.load(str(path))
return keys
def update_host_key(path, label, key=None):
with HOST_LOCK:
keys = known_hosts(path)
if key is None:
if label in keys:
del keys[label]
else:
if label in keys and not keys.check(label, key):
raise ValueError("A different key is already stored for this host")
keys.add(label, key.get_name(), key)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(".tmp")
try:
keys.save(str(temporary))
temporary.replace(path)
finally:
temporary.unlink(missing_ok=True)
class LinuxSsh(Provider):
identifier = "Linux SSH"
def __init__(self, target, secrets, hosts):
self.target = target
self.secrets = secrets
self.hosts = hosts
self.transport = None
self.channel = None
self.sock = None
self.pending = bytearray()
self.cancelled = threading.Event()
self.collector = LinuxParser(target)
self.os = "Linux"
self.command = probe_command()
def _resolve(self):
target = self.target
resolved = []
done = threading.Event()
def resolve():
try:
resolved.extend(socket.getaddrinfo(target.host, target.port, type=socket.SOCK_STREAM))
except OSError:
pass
finally:
done.set()
threading.Thread(target=resolve, daemon=True, name="ARM SSH DNS").start()
deadline = monotonic() + target.timeout
while not self.cancelled.is_set() and not done.wait(.1):
if monotonic() >= deadline:
raise TimeoutError("SSH hostname lookup timed out")
if not resolved or self.cancelled.is_set():
raise OSError("SSH hostname could not be resolved")
return resolved
def connect(self):
expired = threading.Event()
def timeout():
expired.set()
self.close_socket()
watchdog = threading.Timer(self.target.timeout, timeout)
watchdog.daemon = True
watchdog.start()
try:
self._connect(expired)
except Exception:
if expired.is_set():
raise TimeoutError("SSH handshake or channel setup timed out") from None
raise
finally:
watchdog.cancel()
if expired.is_set():
raise TimeoutError("SSH handshake or channel setup timed out")
def _connect(self, expired):
target = self.target
deadline = monotonic() + target.timeout
for family, mode, proto, _, addr in self._resolve():
if expired.is_set() or self.cancelled.is_set() or monotonic() >= deadline:
break
sock = socket.socket(family, mode, proto)
self.sock = sock
try:
sock.settimeout(max(.1, deadline - monotonic()))
sock.connect(addr)
if self.cancelled.is_set():
raise OSError("SSH connection cancelled")
break
except OSError:
sock.close()
self.sock = None
if self.sock is None or self.cancelled.is_set():
raise OSError("SSH connection unavailable")
client = paramiko.SSHClient()
self.transport = client
if self.hosts.is_file():
with HOST_LOCK:
client.load_host_keys(str(self.hosts))
client.set_missing_host_key_policy(RecordUnknownKey())
secret = self.secrets.read(target.credential)
if target.auth == "Password" and secret is None:
raise paramiko.AuthenticationException("No saved password")
if target.auth == "Private key" and not target.key_file:
raise paramiko.AuthenticationException("No private key selected")
client.connect(target.host, port=target.port, username=target.username,
password=secret if target.auth == "Password" else None,
passphrase=secret if target.auth == "Private key" else None,
key_filename=target.key_file if target.auth == "Private key" else None,
timeout=target.timeout, banner_timeout=target.timeout, auth_timeout=target.timeout,
channel_timeout=target.timeout, allow_agent=False, look_for_keys=False, sock=self.sock)
transport = client.get_transport()
transport.set_keepalive(15)
self.channel = transport.open_session(timeout=target.timeout)
self.channel.settimeout(.25)
self.channel.set_combine_stderr(True)
self.channel.exec_command(self.command)
def sample(self):
if self.channel is None:
self.connect()
self.channel.sendall(b".\n")
deadline = monotonic() + self.target.timeout
while monotonic() < deadline and not self.cancelled.is_set():
start = self.pending.find(b"@arm-begin\n")
if start >= 0:
end = self.pending.find(b"@arm-end\n", start)
if end >= 0:
frame = bytes(self.pending[start + 11:end])
del self.pending[:end + 9]
stamp = time()
packet, self.os = self.collector.parse(frame.decode("utf-8", "replace"), stamp, monotonic())
return packet
try:
chunk = self.channel.recv(32768)
except socket.timeout:
continue
if not chunk:
raise EOFError("SSH telemetry channel closed")
self.pending.extend(chunk)
if len(self.pending) > MAX_FRAME:
raise ValueError("SSH telemetry response exceeds limit")
raise TimeoutError("SSH telemetry response timed out")
def cancel(self):
self.cancelled.set()
self.close_socket()
def close_socket(self):
sock = self.sock
if sock is not None:
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
sock.close()
def close(self):
self.cancel()
if self.transport is not None:
self.transport.close()
def num(value, factor=1):
try:
n = float(value) * factor
return n if isfinite(n) else None
except (TypeError, ValueError):
return None
def integers(row, count):
result = row.split()
if len(result) >= count and all(v.isdecimal() for v in result):
return tuple(map(int, result))
return ()
class LinuxParser:
def __init__(self, target):
self.target = target
self.previous = {}
self.last = 0
self.boot = ""
def parse(self, frame, stamp, tick):
sections = defaultdict(list)
for line in frame.splitlines():
key, *values = line.split("\t")
sections[key].append(values)
boot = sections["boot"][0][0] if sections["boot"] and sections["boot"][0] else ""
if boot != self.boot:
self.previous.clear()
elapsed = tick - self.last
self.boot, self.last = boot, tick
machine = self.target.identifier
items, devices = [], []
next_counters = {}
def add(kind, identifier, name, values):
devices.append(Device(kind, identifier, name))
items.extend(readings(machine, stamp, identifier, values))
def counters(key, current):
previous = self.previous.get(key, [None] * len(current))
next_counters[key] = current
return [rate(old, now, elapsed, self.target.interval) for old, now in zip(previous, current)]
cpu_values = {}
for name, row in (row for row in sections["cpu"] if len(row) == 2):
raw = integers(row, 5)
if raw:
total = sum(raw[:8])
busy = total - raw[3] - raw[4]
d_busy, d_total = counters(name, (busy, total))
cpu_values[name] = (d_busy, d_total)
if name != "cpu":
add("cpu", name, f"Logical processor {name[3:]}", {"cpu.util": (usage(d_busy, d_total), "%")})
core_map = defaultdict(list)
for proc, package, core in (row for row in sections["core"] if len(row) == 3):
package, core = package.strip(), core.strip()
if core:
core_map[(package, core)].append("cpu" + proc.strip())
for (package, core), processors in core_map.items():
add("cpu", f"core:{package}:{core}", f"Package {package or '0'} core {core}",
{"cpu.util": (cpu_group(cpu_values, processors), "%")})
model, frequency = (sections["cpuinfo"][0] + ["", ""])[:2] if sections["cpuinfo"] else ("", "")
if model.strip():
devices.append(Device("cpu-info", "identity", model.strip()))
sensors = [row for row in sections["cpusensor"] if len(row) == 2]
temperatures = [val for temp, _ in sensors if (val := num(temp, .001)) is not None]
powers = [val for _, power in sensors if (val := num(power, .000001)) is not None]
items.extend(readings(machine, stamp, TOTAL, {
"cpu.util": (usage(*cpu_values.get("cpu", (None, None))), "%"),
"cpu.physical": (len(core_map) or None, "count"),
"cpu.logical": (sum(key != "cpu" for key in cpu_values) if cpu_values else None, "count"),
"cpu.frequency": (num(frequency), "MHz"), "cpu.temperature": (max(temperatures, default=None), "°C"),
"cpu.power": (sum(powers) if powers else None, "W"),
}))
mem = {key: num(value, 1024) for key, value in sections["ram"] if value} if all(
len(row) == 2 for row in sections["ram"]) else {}
total, available = mem.get("MemTotal"), mem.get("MemAvailable")
used = difference(total, available)
items.extend(readings(machine, stamp, TOTAL, {
"ram.total": (total, "B"), "ram.available": (available, "B"), "ram.used": (used, "B"),
"ram.util": (usage(used, total), "%"),
"ram.pagefile_total": (mem.get("SwapTotal"), "B"),
"ram.pagefile_used": (difference(mem.get("SwapTotal"), mem.get("SwapFree")), "B"),
"ram.committed": (mem.get("Committed_AS"), "B"), "ram.commit_limit": (mem.get("CommitLimit"), "B"),
}))
filtered = {"disk": [], "net": [], "gpu": []}
def selected(kind, identifier, name, values, included):
add(kind, identifier, name, values)
if included:
filtered[kind].append(values)
for key, row in (row for row in sections["disk"] if len(row) == 2):
v = integers(row, 11)
if v:
read, write, reads, writes, active = counters("disk:" + key, (v[2]*512, v[6]*512, v[0], v[4], v[9]))
selected("disk", key, key, disk_metrics(read, write, reads, writes,
min(100, active / 10) if active is not None else None),
not self.target.disks or key in self.target.disks)
for key, physical, state, speed, row in (row for row in sections["net"] if len(row) == 5):
v = integers(row, 16)
if v:
receive, transmit = counters("net:" + key, (v[0], v[8]))
link = num(speed)
up = state == "up" if state in ("up", "down", "lowerlayerdown", "dormant") else None
link = link if link and link > 0 and up else None
selected("net", key, key, net_metrics(receive, transmit, up, link, link),
key in self.target.interfaces if self.target.interfaces else physical == "1")
for key, vendor, ident, util, used, total, temp, clock, memclk, power in (
row for row in sections["drm"] if len(row) == 10):
parts = power.split(",", 1)
metrics = gpu_metrics({"util": num(util), "vram_used": num(used), "vram_total": num(total),
"temperature": num(temp, .001), "clock": num(clock), "memory_clock": num(memclk),
"power": num(parts[0], .000001), "power_limit": num(parts[-1], .000001)})
name = f"{VENDORS.get(vendor, vendor)} {ident} ({key})"
selected("gpu", key, name, metrics, not self.target.gpus or key in self.target.gpus)
for row in csv.reader(io.StringIO("\n".join("\t".join(row) for row in sections["nvidia"])), skipinitialspace=True):
if len(row) != 13:
continue
key, name, util, used, total, temp, clock, memclk, power, limit, fan, enc, dec = row
metrics = gpu_metrics({"util": num(util), "vram_used": num(used, 2**20),
"vram_total": num(total, 2**20), "temperature": num(temp), "clock": num(clock),
"memory_clock": num(memclk), "power": num(power), "power_limit": num(limit),
"fan": num(fan), "encode": num(enc), "decode": num(dec)})
selected("gpu", key, name, metrics, not self.target.gpus or key in self.target.gpus)
self.previous = next_counters
for kind, values in filtered.items():
items.extend(aggregate(machine, stamp, kind, values))
if not cpu_values or not mem:
raise ValueError("Linux telemetry response lacks required system information")
return Sample(machine, "Linux SSH", stamp, tuple(items), tuple(devices)), (
sections["os"][0][0] if sections["os"] and sections["os"][0] else "Linux")
def difference(total, available):
return max(0, total - available) if total is not None and available is not None else None

197
arm/providers/windows.py Normal file
View File

@@ -0,0 +1,197 @@
import logging
import platform
from time import perf_counter as monotonic, time
import psutil
from . import Provider
from .native import Pdh, commit, cpu_identity, interface_info, pagefiles, physical_cores
from ..model import (
LOCAL, TOTAL, Availability, Device, Reading, Sample, aggregate, rate, readings, usage,
)
LOG = logging.getLogger(__name__)
class Cpu(Provider):
identifier = "CPU"
def __init__(self, settings):
self.interval = settings.local_interval
self.last = {}
self.name = cpu_identity()
self.cores = physical_cores()
self.stamp = 0
@staticmethod
def times(row):
return row.user + row.system + row.idle, row.user + row.system
def sample(self):
stamp, now = time(), monotonic()
times = {index: self.times(value) for index, value in enumerate(psutil.cpu_times(percpu=True))}
elapsed = now - self.stamp
devices = [Device("cpu", f"cpu:{i}", f"Logical processor {i}") for i in times]
devices.append(Device("cpu-info", "identity", self.name))
values = {}
items = []
for index, (total, busy) in times.items():
previous = self.last.get(index, (None, None))
values[index] = (
rate(previous[1], busy, elapsed, self.interval),
rate(previous[0], total, elapsed, self.interval),
)
items.extend(readings(LOCAL, stamp, f"cpu:{index}", {
"cpu.util": (usage(*values[index]), "%")
}))
cores = self.cores if {p for core in self.cores for p in core} == set(times) else []
for index, core in enumerate(cores):
device = f"core:{index}"
devices.append(Device("cpu", device, f"Physical core {index}"))
items.extend(readings(LOCAL, stamp, device, {"cpu.util": (cpu_group(values, core), "%")}))
self.last, self.stamp = times, now
frequency = psutil.cpu_freq()
items.extend(readings(LOCAL, stamp, TOTAL, {
"cpu.util": (cpu_group(values, times), "%"),
"cpu.frequency": (frequency.current if frequency else None, "MHz"),
"cpu.physical": (len(cores) or psutil.cpu_count(logical=False), "count"),
"cpu.logical": (len(times), "count"),
}))
items.extend(Reading(LOCAL, TOTAL, metric, None, unit, stamp, Availability.UNSUPPORTED,
"No supported Windows CPU sensor provider")
for metric, unit in (("cpu.temperature", "°C"), ("cpu.power", "W")))
return Sample(LOCAL, self.identifier, stamp, tuple(items), tuple(devices))
def cpu_group(values, indexes):
pairs = [values[index] for index in indexes if index in values]
if pairs and all(busy is not None and total is not None for busy, total in pairs):
return usage(sum(busy for busy, _ in pairs), sum(total for _, total in pairs))
return None
class Memory(Provider):
identifier = "Memory"
def __init__(self, settings):
pass
def sample(self):
stamp = time()
mem = psutil.virtual_memory()
swap_used, swap_total = pagefiles()
used = mem.total - mem.available
committed, limit = commit()
return Sample(LOCAL, self.identifier, stamp, readings(LOCAL, stamp, TOTAL, {
"ram.util": (usage(used, mem.total), "%"), "ram.total": (mem.total, "B"),
"ram.used": (used, "B"), "ram.available": (mem.available, "B"),
"ram.pagefile_used": (swap_used, "B"), "ram.pagefile_total": (swap_total, "B"),
"ram.committed": (committed, "B"), "ram.commit_limit": (limit, "B"),
}))
class Counters(Provider):
def __init__(self, settings):
self.interval = settings.local_interval
self.stamp = 0
self.last = {}
def measure(self, stamp, now, rows, selected, convert):
items, devices, totals = [], [], []
elapsed = now - self.stamp
for key, row in rows.items():
devices.append(Device(self.kind, key, key))
values = convert(key, row, self.last.get(key), elapsed)
items.extend(readings(LOCAL, stamp, key, values))
if key in selected:
totals.append(values)
self.last, self.stamp = rows, now
return Sample(LOCAL, self.identifier, stamp, tuple(items) +
aggregate(LOCAL, stamp, self.kind, totals), tuple(devices))
def deltas(current, previous, fields, elapsed, interval):
return [rate(getattr(previous, key, None), getattr(current, key, None), elapsed, interval) for key in fields]
def combined(first, second):
return first + second if first is not None and second is not None else None
def disk_metrics(read, write, reads, writes, active):
return {"disk.read": (read, "B/s"), "disk.write": (write, "B/s"),
"disk.total": (combined(read, write), "B/s"), "disk.read_ops": (reads, "ops/s"),
"disk.write_ops": (writes, "ops/s"), "disk.active": (active, "%")}
def net_metrics(receive, transmit, up, rx_link, tx_link):
link = max(rx_link or 0, tx_link or 0) or None
rx_util = usage(receive * 8, rx_link * 1e6) if up and rx_link and receive is not None else None
tx_util = usage(transmit * 8, tx_link * 1e6) if up and tx_link and transmit is not None else None
return {"net.receive": (receive, "B/s"), "net.transmit": (transmit, "B/s"),
"net.total": (combined(receive, transmit), "B/s"), "net.up": (up, "bool"),
"net.link": (link, "Mb/s"), "net.util": (max(rx_util, tx_util) if
rx_util is not None and tx_util is not None else None, "%")}
class Disk(Counters):
identifier = "Storage"
kind = "disk"
def __init__(self, settings):
super().__init__(settings)
self.selected = settings.disks
self.native = Pdh({"idle": r"\PhysicalDisk(*)\% Idle Time"})
def sample(self):
stamp, now = time(), monotonic()
rows = psutil.disk_io_counters(perdisk=True, nowrap=False) or {}
rows = {key: row for key, row in rows.items() if key.lower().startswith("physicaldrive")}
idle = self.native.collect().get("idle", {})
idle = {key.split(" ", 1)[0]: max(0, min(100, 100 - value)) for key, value in idle.items()
if key[0].isdigit()}
def convert(key, row, previous, elapsed):
values = deltas(row, previous, ("read_bytes", "write_bytes", "read_count", "write_count"),
elapsed, self.interval)
active = idle.get(key.removeprefix("PhysicalDrive")) if values[0] is not None else None
return disk_metrics(*values, active)
return self.measure(stamp, now, rows, self.selected or rows, convert)
def close(self):
self.native.close()
class Network(Counters):
identifier = "Network"
kind = "net"
def __init__(self, settings):
super().__init__(settings)
self.selected = settings.interfaces
def sample(self):
stamp, now = time(), monotonic()
rows = psutil.net_io_counters(pernic=True, nowrap=False) or {}
stats = psutil.net_if_stats()
native = interface_info()
selected = self.selected or [key for key in rows if native.get(key, (False, 0, 0))[0]]
def convert(key, row, previous, elapsed):
values = deltas(row, previous, ("bytes_recv", "bytes_sent"), elapsed, self.interval)
stat = stats.get(key)
up = stat.isup if stat else None
_, tx_link, rx_link = native.get(key, (False, 0, 0))
if tx_link in (0, 2**64 - 1):
tx_link = (stat.speed * 1e6) if stat and stat.speed > 0 else 0
if rx_link in (0, 2**64 - 1):
rx_link = (stat.speed * 1e6) if stat and stat.speed > 0 else 0
return net_metrics(*values, up, rx_link / 1e6 if up else None, tx_link / 1e6 if up else None)
return self.measure(stamp, now, rows, selected, convert)
def os_name():
build = platform.version().rsplit(".", 1)[-1]
return f"Windows {'11' if build.isdecimal() and int(build) >= 22000 else '10'} ({build})"