Spaces:
Running

Bot / services /system_telemetry.py
ddosvn's picture
Initial deploy of Panel ThTuanIT full stack and Lighthouse-optimized frontend (part 2)
c06c76a verified
Raw History Blame Contribute Delete
4.45 kB
"""Non-blocking system telemetry helpers for the Admin Dashboard."""
import json
import os
import platform
import time
from pathlib import Path
from config import DOMAINS_FILE
from storage import load_meta
_PROCESS_START = time.monotonic()
def _read_int_file(path: str) -> int | None:
try:
raw = Path(path).read_text(encoding="utf-8").strip()
if raw.isdigit():
return int(raw)
except OSError:
pass
return None
def _get_memory_mb() -> tuple[float, float, float]:
"""Return (total_mb, used_mb, percent) preferring cgroup limits over /proc/meminfo."""
# cgroup v2
cg2_max = _read_int_file("/sys/fs/cgroup/memory.max")
cg2_cur = _read_int_file("/sys/fs/cgroup/memory.current")
if cg2_max and cg2_cur is not None and 0 < cg2_max < (1 << 50):
total_mb = round(cg2_max / (1024 * 1024), 1)
used_mb = round(cg2_cur / (1024 * 1024), 1)
pct = round(min(100.0, (cg2_cur / cg2_max) * 100.0), 1)
return total_mb, used_mb, pct
# cgroup v1
cg1_max = _read_int_file("/sys/fs/cgroup/memory/memory.limit_in_bytes")
cg1_cur = _read_int_file("/sys/fs/cgroup/memory/memory.usage_in_bytes")
if cg1_max and cg1_cur is not None and 0 < cg1_max < (1 << 50):
total_mb = round(cg1_max / (1024 * 1024), 1)
used_mb = round(cg1_cur / (1024 * 1024), 1)
pct = round(min(100.0, (cg1_cur / cg1_max) * 100.0), 1)
return total_mb, used_mb, pct
# Fallback: /proc/meminfo
try:
info: dict[str, int] = {}
for line in Path("/proc/meminfo").read_text(encoding="utf-8", errors="ignore").splitlines():
parts = line.split(":", 1)
if len(parts) == 2:
vals = parts[1].strip().split()
if vals and vals[0].isdigit():
info[parts[0].strip()] = int(vals[0])
total_kb = info.get("MemTotal", 0)
avail_kb = info.get("MemAvailable", info.get("MemFree", 0))
if total_kb > 0:
used_kb = max(0, total_kb - avail_kb)
total_mb = round(total_kb / 1024.0, 1)
used_mb = round(used_kb / 1024.0, 1)
pct = round(min(100.0, (used_kb / total_kb) * 100.0), 1)
return total_mb, used_mb, pct
except OSError:
pass
return 0.0, 0.0, 0.0
def _get_uptime_seconds() -> int:
try:
raw = Path("/proc/uptime").read_text(encoding="utf-8").strip().split()[0]
return max(0, int(float(raw)))
except Exception:
return max(0, int(time.monotonic() - _PROCESS_START))
def _format_uptime(seconds: int) -> str:
days, rem = divmod(max(0, seconds), 86400)
hours, rem = divmod(rem, 3600)
mins, _ = divmod(rem, 60)
if days > 0:
return f"{days}d {hours}h {mins}m"
if hours > 0:
return f"{hours}h {mins}m"
return f"{mins}m"
def _count_domains() -> int:
try:
if DOMAINS_FILE.exists():
data = json.loads(DOMAINS_FILE.read_text(encoding="utf-8"))
if isinstance(data, dict):
return len(data)
except Exception:
pass
return 0
def get_system_telemetry() -> dict:
"""Collect real-time CPU, RAM, uptime, runtime, and zone network counts."""
cores = os.cpu_count() or 1
try:
load_1m, load_5m, load_15m = os.getloadavg()
except (AttributeError, OSError):
load_1m, load_5m, load_15m = 0.0, 0.0, 0.0
cpu_pct = round(min(100.0, (load_1m / max(1, cores)) * 100.0), 1)
ram_total_mb, ram_used_mb, ram_pct = _get_memory_mb()
uptime_sec = _get_uptime_seconds()
meta = load_meta()
total_ports = sum(len(info.get("ports", [])) for info in meta.values())
autostart_zones = sum(
1 for info in meta.values() if str(info.get("autostart_cmd", "")).strip()
)
return {
"cpu_cores": cores,
"load_1m": round(load_1m, 2),
"load_5m": round(load_5m, 2),
"load_15m": round(load_15m, 2),
"cpu_percent": cpu_pct,
"ram_total_mb": ram_total_mb,
"ram_used_mb": ram_used_mb,
"ram_percent": ram_pct,
"uptime_seconds": uptime_sec,
"uptime_display": _format_uptime(uptime_sec),
"total_domains": _count_domains(),
"total_ports": total_ports,
"autostart_zones": autostart_zones,
"python_version": platform.python_version(),
"platform": f"{platform.system()} {platform.machine()}".strip(),
}