"""Long-term telemetry: hourly min/avg/max per metric, one JSON line per hour. The live history in the service keeps ten minutes; this keeps about a year, so the web UI can draw weeks and months. Files are append-only JSONL in the data dir, one per month (records-YYYY-MM.jsonl); each line looks like: {"hour":1764892800,"n":3600,"cpu_temp":[41.0,55.3,78.0],...} Recording is best effort: a failing disk logs once and stops the recorder; nothing else notices. Restarting within an hour writes a second line for that hour; the reader merges lines per hour, so that is harmless. """ from __future__ import annotations import glob import json import logging import os import time log = logging.getLogger(__name__) METRICS = ("cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used") RETENTION_DAYS = 400 # a little over a year of monthly files _FILE = "records-%s.jsonl" def _values(sample) -> dict[str, float | None]: return {"cpu_temp": sample.cpu.temp, "gpu_temp": sample.gpu.temp, "cpu_load": sample.cpu.load, "gpu_load": sample.gpu.load, "cpu_w": sample.cpu.power, "gpu_w": sample.gpu.power, "other_w": sample.power.other, "total_w": sample.power.total, "vram_used": None if sample.vram is None else sample.vram[0]} class Recorder: """Subscribed to Telemetry (called once per sample); writes each finished hour to its month file.""" def __init__(self, directory: str, retention_days: int = RETENTION_DAYS): self.directory = directory self.retention_days = retention_days self._hour = 0 self._n = 0 self._stats: dict[str, list[float]] = {} # metric -> [min, max, sum] self._stopped = False self._prune() def on_sample(self, sample) -> None: if self._stopped: return try: hour = int(sample.t // 3600) * 3600 if hour != self._hour: self._flush() self._hour, self._n, self._stats = hour, 0, {} self._n += 1 for name, value in _values(sample).items(): if value is None: continue s = self._stats.setdefault(name, [value, value, 0.0]) s[0], s[1], s[2] = min(s[0], value), max(s[1], value), s[2] + value except Exception: self._stopped = True log.warning("Telemetry recording stopped for this run", exc_info=True) def close(self) -> None: """Write the hour still in progress; a short line is fine, the reader merges per hour.""" if self._stopped: return try: self._flush() except Exception: self._stopped = True log.warning("Telemetry recording stopped while closing", exc_info=True) def _flush(self) -> None: if not self._hour or not self._n: return row = {"hour": self._hour, "n": self._n} for name in METRICS: s = self._stats.get(name) row[name] = [round(s[0], 1), round(s[2] / self._n, 1), round(s[1], 1)] if s else None month = time.strftime("%Y-%m", time.gmtime(self._hour)) os.makedirs(self.directory, exist_ok=True) with open(os.path.join(self.directory, _FILE % month), "a", encoding="utf-8") as f: f.write(json.dumps(row, separators=(",", ":")) + "\n") def _prune(self) -> None: """Delete month files whose whole month is older than the retention window.""" # Drop a month file only once its whole month is past the window: it can end up to 31 # days after the month it is named for starts. cutoff = time.time() - (self.retention_days + 31) * 86400 try: for path in glob.glob(os.path.join(self.directory, _FILE % "*")): try: month = os.path.basename(path)[len("records-"):-len(".jsonl")] when = time.mktime(time.strptime(month, "%Y-%m")) except ValueError: continue if when < cutoff: os.remove(path) log.info("Removed telemetry file older than %s days: %s", self.retention_days, path) except OSError: log.warning("Couldn't prune old telemetry files", exc_info=True) def load(directory: str, days: int) -> dict: """Hourly rollups for the last `days` days, oldest first: {"metrics", "rows", "days"}.""" since = time.time() - days * 86400 rows: dict[int, dict] = {} try: names = sorted(os.listdir(directory)) except OSError: names = [] for name in names: if not (name.startswith("records-") and name.endswith(".jsonl")): continue try: with open(os.path.join(directory, name), encoding="utf-8") as f: lines = f.readlines() except OSError: log.warning("Couldn't read telemetry file %s", name) continue for line in lines: line = line.strip() if not line: continue try: row = json.loads(line) except ValueError: continue # a torn last line from a crash: skip it hour = row.get("hour") if not isinstance(hour, (int, float)) or hour < since: continue merged = rows.setdefault(int(hour), {"hour": int(hour), "n": 0}) n = row.get("n") if isinstance(row.get("n"), int) else 0 before = merged["n"] merged["n"] = before + n for metric in METRICS: stats = row.get(metric) if not isinstance(stats, list) or len(stats) != 3: continue cur = merged.get(metric) if cur is None: merged[metric] = list(stats) else: cur[0] = min(cur[0], stats[0]) cur[2] = max(cur[2], stats[2]) if before + n: cur[1] = (cur[1] * before + stats[1] * n) / (before + n) return {"metrics": list(METRICS), "rows": [rows[h] for h in sorted(rows)], "days": days}