# -*- coding: utf-8 -*- """Host CPU / memory snapshot (no extra deps — reads /proc).""" from __future__ import annotations import os import time from pathlib import Path from typing import Any _prev_cpu: tuple[int, int] | None = None _snapshot_cache: dict[str, Any] | None = None _snapshot_cache_at = 0.0 _SNAPSHOT_TTL_SEC = 2.0 def _read_cpu_totals() -> tuple[int, int]: line = Path("/proc/stat").read_text(encoding="utf-8", errors="replace").splitlines()[0] parts = line.split() if not parts or parts[0] != "cpu": return 0, 0 nums = [int(x) for x in parts[1:]] idle = nums[3] + (nums[4] if len(nums) > 4 else 0) total = sum(nums[:10]) if len(nums) >= 10 else sum(nums) return idle, total def _cpu_percent(sample: bool = True) -> float: """Return busy CPU % since last call (or brief sleep sample on first call).""" global _prev_cpu idle, total = _read_cpu_totals() if _prev_cpu is None: if sample: time.sleep(0.12) idle2, total2 = _read_cpu_totals() _prev_cpu = (idle2, total2) dt = total2 - total if dt <= 0: return 0.0 return round(100.0 * (1.0 - (idle2 - idle) / dt), 1) _prev_cpu = (idle, total) return 0.0 prev_idle, prev_total = _prev_cpu _prev_cpu = (idle, total) dt = total - prev_total if dt <= 0: return 0.0 busy = 100.0 * (1.0 - (idle - prev_idle) / dt) return round(max(0.0, min(100.0, busy)), 1) def _mem_info() -> dict[str, float]: kv: dict[str, int] = {} for line in Path("/proc/meminfo").read_text(encoding="utf-8", errors="replace").splitlines(): if ":" not in line: continue k, v = line.split(":", 1) num = v.strip().split()[0] try: kv[k.strip()] = int(num) except ValueError: continue total_kb = float(kv.get("MemTotal") or 0) avail_kb = float(kv.get("MemAvailable") or kv.get("MemFree") or 0) used_kb = max(0.0, total_kb - avail_kb) pct = round(100.0 * used_kb / total_kb, 1) if total_kb > 0 else 0.0 return { "memory_total_gb": round(total_kb / 1024 / 1024, 2), "memory_used_gb": round(used_kb / 1024 / 1024, 2), "memory_available_gb": round(avail_kb / 1024 / 1024, 2), "memory_percent": pct, } def snapshot(*, sample_cpu: bool = False) -> dict[str, Any]: """CPU % uses /proc delta between calls (no blocking sleep). First call may be 0.""" global _snapshot_cache, _snapshot_cache_at now = time.time() if ( not sample_cpu and _snapshot_cache is not None and (now - _snapshot_cache_at) < _SNAPSHOT_TTL_SEC ): return dict(_snapshot_cache) mem = _mem_info() load1 = 0.0 try: load1 = round(float(Path("/proc/loadavg").read_text().split()[0]), 2) except Exception: pass nproc = max(1, int(os.cpu_count() or 1)) out = { "ts": now, "cpu_percent": _cpu_percent(sample=sample_cpu), "load1": load1, "cpu_cores": nproc, **mem, } _snapshot_cache = out _snapshot_cache_at = now return dict(out)