"""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,3600],...} that is min, average and max, and how many samples carried the metric (a sensor can drop out for part of an hour; its average is over the samples that had it). Lines written before the count existed have three numbers and count as `n` samples. The hour in progress is checkpointed to records-current.json every minute and on exit, and resumed at the next start: a restart, even a hard stop such as `schtasks /End`, loses at most a minute. Should two lines ever exist for one hour, the reader merges them. Recording is best effort: a failing write is logged at most once an hour and retried; finished hours wait in memory (up to two days of them) until the disk takes them again. """ 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 CHECKPOINT_SECONDS = 60 MAX_PENDING = 48 # finished hours kept in memory while writes fail REPORT_SECONDS = 3600 # a failing disk is logged at most this often _FILE = "records-%s.jsonl" _CURRENT = "records-current.json" 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, count] self._pending: list[dict] = [] # finished hours not written yet self._checkpoint_at = 0.0 self._reported: float | None = None # when a failure was last logged self._prune() self._resume() def on_sample(self, sample) -> None: try: hour = int(sample.t // 3600) * 3600 if hour != self._hour: self._finish_hour() 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.get(name) if s is None: self._stats[name] = [value, value, value, 1] else: s[0], s[1], s[2], s[3] = min(s[0], value), max(s[1], value), s[2] + value, s[3] + 1 if abs(sample.t - self._checkpoint_at) >= CHECKPOINT_SECONDS: self._checkpoint_at = sample.t self._save_checkpoint() except Exception: self._report("Telemetry recording failed") def close(self) -> None: """Checkpoint the hour in progress (the next start carries on with it) and write anything pending.""" try: self._save_checkpoint() self._write_pending() except Exception: self._report("Telemetry recording failed while closing") # ------------------------------------------------------------------ the hour in progress def _row(self) -> dict: 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] / s[3], 1), round(s[1], 1), s[3]] if s else None return row def _finish_hour(self) -> None: if self._hour and self._n: self._pending.append(self._row()) del self._pending[:-MAX_PENDING] self._write_pending() def _save_checkpoint(self) -> None: if not self._hour or not self._n: return try: os.makedirs(self.directory, exist_ok=True) path = os.path.join(self.directory, _CURRENT) with open(path + ".tmp", "w", encoding="utf-8") as f: json.dump({"hour": self._hour, "n": self._n, "stats": self._stats}, f, separators=(",", ":")) os.replace(path + ".tmp", path) except OSError: self._report("Couldn't checkpoint the hour's telemetry") def _resume(self) -> None: """Carry on with the checkpointed hour if it is this hour; otherwise it is finished: write it.""" path = os.path.join(self.directory, _CURRENT) try: with open(path, encoding="utf-8") as f: saved = json.load(f) hour, n, stats = int(saved["hour"]), int(saved["n"]), saved["stats"] if not all(isinstance(v, list) and len(v) == 4 for v in stats.values()): raise ValueError("bad stats") except (FileNotFoundError, NotADirectoryError): return # nothing to resume (a broken data dir shows up at the first write) except (OSError, ValueError, KeyError, TypeError, AttributeError): log.warning("Ignoring an unreadable telemetry checkpoint", exc_info=True) return self._hour, self._n, self._stats = hour, n, {k: v for k, v in stats.items() if k in METRICS} if hour != int(time.time() // 3600) * 3600: self._finish_hour() self._hour, self._n, self._stats = 0, 0, {} if not self._pending: # written: the checkpoint must not be written again next start try: os.remove(path) except OSError: pass # ------------------------------------------------------------------ the month files def _write_pending(self) -> None: while self._pending: row = self._pending[0] month = time.strftime("%Y-%m", time.gmtime(row["hour"])) try: 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") except OSError: self._report(f"Couldn't write telemetry records ({len(self._pending)} hours waiting)") return self._pending.pop(0) def _report(self, what: str) -> None: now = time.monotonic() if self._reported is None or now - self._reported >= REPORT_SECONDS: self._reported = now log.warning("%s; will keep trying", what, exc_info=True) 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"}. Each metric of a row is [min, avg, max] (or null); lines for the same hour are merged, their averages weighted by how many samples carried the metric.""" 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 merged["n"] += n for metric in METRICS: stats = row.get(metric) if not isinstance(stats, list) or len(stats) not in (3, 4): continue count = stats[3] if len(stats) == 4 else n # older lines: every sample counted cur = merged.get(metric) if cur is None: merged[metric] = [stats[0], stats[1], stats[2], count] else: cur[0] = min(cur[0], stats[0]) cur[2] = max(cur[2], stats[2]) if cur[3] + count: cur[1] = (cur[1] * cur[3] + stats[1] * count) / (cur[3] + count) cur[3] += count for row in rows.values(): for metric in METRICS: if row.get(metric) is not None: row[metric] = row[metric][:3] return {"metrics": list(METRICS), "rows": [rows[h] for h in sorted(rows)], "days": days}