474 lines
19 KiB
Python
474 lines
19 KiB
Python
"""Local system metric collection for the compute dashboard.
|
||
|
||
The monitor samples every two seconds so sparklines and peak badges stay
|
||
smooth, keeps a ten-minute ring buffer to seed the resource detail views,
|
||
and degrades every platform-specific source (nvidia-smi, /sys, sensors,
|
||
per-process permission) to None/[] instead of failing the whole snapshot.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import csv
|
||
import os
|
||
import platform
|
||
import shutil
|
||
import socket
|
||
import subprocess
|
||
import time
|
||
from collections import deque
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import psutil
|
||
|
||
HISTORY_MAXLEN = 600 # 600 samples × 1s ≈ 10 minutes (daozai cadence: one sample per second)
|
||
PROCESS_TOP_N = 8
|
||
|
||
_GPU_QUERY_FIELDS = (
|
||
"index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,"
|
||
"utilization.encoder,utilization.decoder,power.draw,power.limit,"
|
||
"clocks.current.graphics,clocks.current.memory,uuid"
|
||
)
|
||
|
||
|
||
def optional_number(value: str) -> float | None:
|
||
"""Parse an nvidia-smi CSV cell, treating N/A-style placeholders as missing."""
|
||
normalized = value.strip().strip("[]").lower()
|
||
if normalized in {"", "n/a", "not supported", "-"}:
|
||
return None
|
||
try:
|
||
return float(normalized)
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
class LocalSystemMonitor:
|
||
"""Collect host metrics in-process using local OS counters, not a remote monitor API."""
|
||
|
||
def __init__(self) -> None:
|
||
self.latest: dict[str, Any] | None = None
|
||
self.error: str | None = None
|
||
self.history: deque[dict[str, Any]] = deque(maxlen=HISTORY_MAXLEN)
|
||
# Process rankings refresh on a slower loop (process_iter is the only
|
||
# expensive collection pass); snapshots always read the last result.
|
||
self._processes: dict[str, list[dict[str, Any]]] = {"cpu": [], "memory": []}
|
||
self._last_network = psutil.net_io_counters()
|
||
self._last_nic = psutil.net_io_counters(pernic=True)
|
||
self._last_at = time.monotonic()
|
||
self._last_disk_io: Any | None = None
|
||
self._last_proc_io: dict[int, int] = {}
|
||
self._last_proc_at = time.monotonic()
|
||
self._link_speeds: dict[str, int | None] = {}
|
||
try:
|
||
self._last_disk_io = psutil.disk_io_counters()
|
||
except Exception:
|
||
self._last_disk_io = None
|
||
# Open the CPU diff windows once so the first real sample is meaningful.
|
||
try:
|
||
psutil.cpu_percent(None)
|
||
psutil.cpu_percent(None, percpu=True)
|
||
except Exception:
|
||
pass
|
||
|
||
@staticmethod
|
||
def _cpu_split() -> dict[str, float | None]:
|
||
"""User/kernel split matching the same window as cpu_percent."""
|
||
try:
|
||
times = psutil.cpu_times_percent(None)
|
||
return {"user_percent": times.user, "system_percent": times.system}
|
||
except Exception:
|
||
return {"user_percent": None, "system_percent": None}
|
||
|
||
@staticmethod
|
||
def _cpu_names() -> list[str]:
|
||
name = platform.processor().strip()
|
||
if not name and Path("/proc/cpuinfo").exists():
|
||
try:
|
||
for line in Path("/proc/cpuinfo").read_text(errors="replace").splitlines():
|
||
if line.lower().startswith(("model name", "hardware")) and ":" in line:
|
||
name = line.split(":", 1)[1].strip()
|
||
if name:
|
||
break
|
||
except OSError:
|
||
pass
|
||
return [name or platform.machine() or "CPU"]
|
||
|
||
@staticmethod
|
||
def _gpu_metrics() -> tuple[list[str], list[dict[str, Any]]]:
|
||
"""Read NVIDIA telemetry when the vendor utility is installed; other GPUs stay empty."""
|
||
command = shutil.which("nvidia-smi")
|
||
if not command:
|
||
return [], []
|
||
try:
|
||
result = subprocess.run(
|
||
[command, f"--query-gpu={_GPU_QUERY_FIELDS}", "--format=csv,noheader,nounits"],
|
||
check=False,
|
||
capture_output=True,
|
||
text=True,
|
||
encoding="utf-8",
|
||
errors="replace",
|
||
timeout=3,
|
||
)
|
||
except (OSError, subprocess.TimeoutExpired):
|
||
return [], []
|
||
if result.returncode != 0:
|
||
return [], []
|
||
names: list[str] = []
|
||
gpus: list[dict[str, Any]] = []
|
||
for row in csv.reader(result.stdout.splitlines(), skipinitialspace=True):
|
||
if len(row) < 3:
|
||
continue
|
||
try:
|
||
index = int(row[0].strip())
|
||
except ValueError:
|
||
continue
|
||
name = row[1].strip()
|
||
if not name:
|
||
continue
|
||
|
||
# Some integrated GPUs (including GB10) expose utilization but report
|
||
# framebuffer memory as N/A; keep the GPU row and leave only memory blank.
|
||
cell = lambda i: optional_number(row[i]) if len(row) > i else None
|
||
gpus.append({
|
||
"index": index,
|
||
"name": name,
|
||
"utilization": cell(2),
|
||
"memory_used_mb": cell(3),
|
||
"memory_total_mb": cell(4),
|
||
"temperature_c": cell(5),
|
||
"encoder_pct": cell(6),
|
||
"decoder_pct": cell(7),
|
||
"power_w": cell(8),
|
||
"power_limit_w": cell(9),
|
||
"graphics_clock_mhz": cell(10),
|
||
"memory_clock_mhz": cell(11),
|
||
"uuid": row[12].strip() if len(row) > 12 else "",
|
||
"processes": [],
|
||
})
|
||
LocalSystemMonitor._attach_gpu_processes(command, gpus)
|
||
return names, gpus
|
||
|
||
@staticmethod
|
||
def _attach_gpu_processes(command: str, gpus: list[dict[str, Any]]) -> None:
|
||
"""Attach CUDA process rows to their GPU entry; desktop processes stay invisible."""
|
||
try:
|
||
result = subprocess.run(
|
||
[
|
||
command,
|
||
"--query-compute-apps=gpu_name,pid,process_name,used_memory",
|
||
"--format=csv,noheader,nounits",
|
||
],
|
||
check=False,
|
||
capture_output=True,
|
||
text=True,
|
||
encoding="utf-8",
|
||
errors="replace",
|
||
timeout=3,
|
||
)
|
||
except (OSError, subprocess.TimeoutExpired):
|
||
return
|
||
if result.returncode != 0:
|
||
return
|
||
by_name = {gpu["name"]: gpu for gpu in gpus}
|
||
for row in csv.reader(result.stdout.splitlines(), skipinitialspace=True):
|
||
if len(row) < 4:
|
||
continue
|
||
gpu = by_name.get(row[0].strip())
|
||
if gpu is None:
|
||
continue
|
||
try:
|
||
pid = int(row[1].strip())
|
||
except ValueError:
|
||
continue
|
||
gpu["processes"].append({
|
||
"pid": pid,
|
||
"name": row[2].strip() or f"pid {pid}",
|
||
"memory_mb": optional_number(row[3]) or 0.0,
|
||
})
|
||
for gpu in gpus:
|
||
gpu["processes"].sort(key=lambda entry: entry["memory_mb"], reverse=True)
|
||
del gpu["processes"][PROCESS_TOP_N:]
|
||
|
||
def _process_ranking(self) -> dict[str, list[dict[str, Any]]]:
|
||
"""Top CPU, top memory and top disk-IO processes.
|
||
|
||
The first pass primes each Process object's cpu counter (psutil caches
|
||
instances per pid, so later passes diff against it) and mainly reports
|
||
the memory ranking; the second pass reports meaningful CPU and IO rates.
|
||
"""
|
||
entries: list[dict[str, Any]] = []
|
||
own_pid = os.getpid()
|
||
# psutil reports per-logical-core percent (a busy thread can hit 100% x cores);
|
||
# normalize to whole-machine share so the ranking sums stay under 100%.
|
||
core_count = max(1, psutil.cpu_count(logical=True) or 1)
|
||
now = time.monotonic()
|
||
elapsed = max(now - getattr(self, "_last_proc_at", now), 0.001)
|
||
self._last_proc_at = now
|
||
current_io: dict[int, int] = {}
|
||
for proc in psutil.process_iter(["pid", "name", "username", "memory_info", "io_counters"]):
|
||
try:
|
||
info = proc.info
|
||
name = info.get("name") or f"pid {info['pid']}"
|
||
# Windows' idle task and this panel itself would otherwise top the CPU chart.
|
||
if info["pid"] == own_pid or name in {"System Idle Process", "Idle"}:
|
||
continue
|
||
io = info.get("io_counters")
|
||
total_io = int(io.read_bytes + io.write_bytes) if io else 0
|
||
current_io[info["pid"]] = total_io
|
||
last_io = self._last_proc_io.get(info["pid"])
|
||
io_rate = max(total_io - last_io, 0) / elapsed if last_io is not None else 0
|
||
entries.append({
|
||
"pid": info["pid"],
|
||
"name": name,
|
||
"user": info.get("username") or "",
|
||
"cpu_percent": proc.cpu_percent(None) / core_count,
|
||
"memory_bytes": info["memory_info"].rss if info.get("memory_info") else 0,
|
||
"io_bytes_per_second": io_rate,
|
||
})
|
||
except (psutil.Error, OSError):
|
||
continue
|
||
self._last_proc_io = current_io
|
||
by_cpu = sorted(entries, key=lambda entry: entry["cpu_percent"], reverse=True)[:PROCESS_TOP_N]
|
||
by_mem = sorted(entries, key=lambda entry: entry["memory_bytes"], reverse=True)[:PROCESS_TOP_N]
|
||
by_io = sorted(entries, key=lambda entry: entry["io_bytes_per_second"], reverse=True)[:PROCESS_TOP_N]
|
||
return {"cpu": by_cpu, "memory": by_mem, "io": by_io}
|
||
|
||
@staticmethod
|
||
def _disk_volumes() -> list[dict[str, Any]]:
|
||
volumes: list[dict[str, Any]] = []
|
||
try:
|
||
partitions = psutil.disk_partitions(all=False)
|
||
except Exception:
|
||
return volumes
|
||
for partition in partitions:
|
||
try:
|
||
usage = psutil.disk_usage(partition.mountpoint)
|
||
except (PermissionError, OSError):
|
||
continue
|
||
volumes.append({
|
||
"path": partition.device,
|
||
"mountpoint": partition.mountpoint,
|
||
"fstype": partition.fstype,
|
||
"percent": usage.percent,
|
||
"used_bytes": usage.used,
|
||
"total_bytes": usage.total,
|
||
})
|
||
volumes.sort(key=lambda volume: volume["total_bytes"], reverse=True)
|
||
return volumes
|
||
|
||
def _link_speed_mbps(self, nic: str) -> int | None:
|
||
if nic in self._link_speeds:
|
||
return self._link_speeds[nic]
|
||
speed: int | None = None
|
||
try:
|
||
raw = Path(f"/sys/class/net/{nic}/speed").read_text().strip()
|
||
parsed = int(float(raw))
|
||
speed = parsed if parsed > 0 else None
|
||
except (OSError, ValueError):
|
||
speed = None
|
||
self._link_speeds[nic] = speed
|
||
return speed
|
||
|
||
def _network(self, elapsed: float) -> dict[str, Any]:
|
||
counters = psutil.net_io_counters()
|
||
incoming = max(counters.bytes_recv - self._last_network.bytes_recv, 0) / elapsed
|
||
outgoing = max(counters.bytes_sent - self._last_network.bytes_sent, 0) / elapsed
|
||
self._last_network = counters
|
||
per_nic: list[dict[str, Any]] = []
|
||
try:
|
||
nic_counters = psutil.net_io_counters(pernic=True)
|
||
except Exception:
|
||
nic_counters = {}
|
||
for name, counters_nic in nic_counters.items():
|
||
last = self._last_nic.get(name)
|
||
if last is not None:
|
||
rx = max(counters_nic.bytes_recv - last.bytes_recv, 0) / elapsed
|
||
tx = max(counters_nic.bytes_sent - last.bytes_sent, 0) / elapsed
|
||
per_nic.append({
|
||
"name": name,
|
||
"rx_bps": rx,
|
||
"tx_bps": tx,
|
||
"link_mbps": self._link_speed_mbps(name),
|
||
})
|
||
self._last_nic = nic_counters
|
||
per_nic.sort(key=lambda nic: nic["rx_bps"] + nic["tx_bps"], reverse=True)
|
||
return {
|
||
"in_bytes_per_second": incoming,
|
||
"out_bytes_per_second": outgoing,
|
||
"received_bytes_total": counters.bytes_recv,
|
||
"sent_bytes_total": counters.bytes_sent,
|
||
"per_nic": per_nic,
|
||
}
|
||
|
||
def _disk_rates(self, elapsed: float) -> dict[str, float | None]:
|
||
try:
|
||
io = psutil.disk_io_counters()
|
||
except Exception:
|
||
io = None
|
||
rates: dict[str, float | None] = {"read_bps": None, "write_bps": None, "active_percent": None}
|
||
if io is not None:
|
||
if self._last_disk_io is not None:
|
||
rates["read_bps"] = max(io.read_bytes - self._last_disk_io.read_bytes, 0) / elapsed
|
||
rates["write_bps"] = max(io.write_bytes - self._last_disk_io.write_bytes, 0) / elapsed
|
||
busy_ms = getattr(io, "busy_time", None)
|
||
last_busy = getattr(self._last_disk_io, "busy_time", None)
|
||
if busy_ms is not None and last_busy is not None:
|
||
# busy_time counts milliseconds the device had queued IO.
|
||
rates["active_percent"] = min(100.0, max(busy_ms - last_busy, 0) / (elapsed * 1000) * 100)
|
||
self._last_disk_io = io
|
||
return rates
|
||
|
||
def collect(self) -> dict[str, Any]:
|
||
"""Build the full local snapshot consumed by the compute monitor page."""
|
||
# Every counter here is a non-blocking diff against the previous pass;
|
||
# __init__ primed the windows, so the loop never sleeps inside collect().
|
||
cpu_percent = psutil.cpu_percent(None)
|
||
percpu = psutil.cpu_percent(None, percpu=True)
|
||
captured_at = datetime.now(timezone.utc)
|
||
now = time.monotonic()
|
||
elapsed = max(now - self._last_at, 0.001)
|
||
self._last_at = now
|
||
memory = psutil.virtual_memory()
|
||
disk_path = Path.home().anchor or os.path.abspath(os.sep)
|
||
disk = psutil.disk_usage(disk_path)
|
||
cpu_freq = psutil.cpu_freq()
|
||
cpu_names = self._cpu_names()
|
||
gpu_names, gpus = self._gpu_metrics()
|
||
try:
|
||
load_1m = os.getloadavg()[0]
|
||
except (AttributeError, OSError):
|
||
load_1m = None
|
||
try:
|
||
temperatures = [
|
||
{"name": name, "temperature": entry.current}
|
||
for name, entries in psutil.sensors_temperatures(fahrenheit=False).items()
|
||
for entry in entries
|
||
if entry.current is not None
|
||
]
|
||
except (AttributeError, NotImplementedError, OSError):
|
||
temperatures = []
|
||
host_name = socket.gethostname()
|
||
uptime = max(int(time.time() - psutil.boot_time()), 0)
|
||
network = self._network(elapsed)
|
||
disk_rates = self._disk_rates(elapsed)
|
||
return {
|
||
"source": "local",
|
||
"connection_status": "connected",
|
||
"captured_at": captured_at.isoformat(),
|
||
"server": {
|
||
"id": None,
|
||
"name": host_name,
|
||
"platform": f"{platform.system()} {platform.release()}".strip(),
|
||
"cpu_names": cpu_names,
|
||
"gpu_names": gpu_names,
|
||
"uptime_seconds": uptime,
|
||
"last_active": captured_at.isoformat(),
|
||
"is_online": True,
|
||
},
|
||
"cpu": {
|
||
"percent": cpu_percent,
|
||
"percpu": percpu,
|
||
"frequency_mhz": cpu_freq.current if cpu_freq else None,
|
||
"load_1m": load_1m,
|
||
"cores": psutil.cpu_count(logical=True),
|
||
"cores_physical": psutil.cpu_count(logical=False),
|
||
"cpu_names": cpu_names,
|
||
**self._cpu_split(),
|
||
},
|
||
"memory": {
|
||
"used_bytes": memory.used,
|
||
"total_bytes": memory.total,
|
||
"percent": memory.percent,
|
||
"available_bytes": memory.available,
|
||
"cached_bytes": getattr(memory, "cached", 0),
|
||
"buffered_bytes": getattr(memory, "buffers", 0),
|
||
"shared_bytes": getattr(memory, "shared", 0),
|
||
},
|
||
"disk": {
|
||
"path": disk_path,
|
||
"used_bytes": disk.used,
|
||
"total_bytes": disk.total,
|
||
"percent": disk.percent,
|
||
**disk_rates,
|
||
},
|
||
"disks": self._disk_volumes(),
|
||
"gpus": gpus,
|
||
"network": network,
|
||
"processes": self._processes,
|
||
"temperatures": temperatures,
|
||
"error": None,
|
||
}
|
||
|
||
@staticmethod
|
||
def history_sample(snapshot: dict[str, Any], epoch: float) -> dict[str, Any]:
|
||
"""Compact per-cycle series entry shared by the ring buffer and the detail charts."""
|
||
gpus = snapshot.get("gpus") or []
|
||
gpu_values = [gpu.get("utilization") for gpu in gpus if gpu.get("utilization") is not None]
|
||
cpu = snapshot.get("cpu") or {}
|
||
memory = snapshot.get("memory") or {}
|
||
disk = snapshot.get("disk") or {}
|
||
network = snapshot.get("network") or {}
|
||
return {
|
||
"t": epoch,
|
||
"cpu": cpu.get("percent"),
|
||
"percpu": cpu.get("percpu"),
|
||
"gpu": max(gpu_values) if gpu_values else None,
|
||
"mem": memory.get("percent"),
|
||
"disk_read": disk.get("read_bps"),
|
||
"disk_write": disk.get("write_bps"),
|
||
"net_in": network.get("in_bytes_per_second"),
|
||
"net_out": network.get("out_bytes_per_second"),
|
||
}
|
||
|
||
async def run(self) -> None:
|
||
"""Sample on a fixed 1-second grid like the island, skipping time already spent collecting."""
|
||
while True:
|
||
started = time.monotonic()
|
||
try:
|
||
snapshot = await asyncio.to_thread(self.collect)
|
||
self.history.append(self.history_sample(snapshot, time.time()))
|
||
self.latest = snapshot
|
||
self.error = None
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
self.latest = None
|
||
self.error = f"本机资源采集失败:{str(exc)[:240]}"
|
||
await asyncio.sleep(max(0.05, 1.0 - (time.monotonic() - started)))
|
||
|
||
async def run_processes(self, interval: float = 6.0) -> None:
|
||
"""Refresh the process ranking on its own slower loop so the 2s cycle stays cheap."""
|
||
while True:
|
||
try:
|
||
self._processes = await asyncio.to_thread(self._process_ranking)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception:
|
||
pass # keep the previous ranking; process data is best-effort
|
||
await asyncio.sleep(interval)
|
||
|
||
def history_snapshot(self, seconds: float) -> list[dict[str, Any]]:
|
||
cutoff = time.time() - seconds
|
||
return [sample for sample in self.history if sample["t"] >= cutoff]
|
||
|
||
def snapshot(self) -> dict[str, Any]:
|
||
if self.latest is not None:
|
||
return dict(self.latest)
|
||
return {
|
||
"source": "local",
|
||
"connection_status": "unavailable" if self.error else "sampling",
|
||
"captured_at": None,
|
||
"server": None,
|
||
"cpu": None,
|
||
"memory": None,
|
||
"disk": None,
|
||
"disks": [],
|
||
"gpus": [],
|
||
"network": None,
|
||
"processes": {"cpu": [], "memory": []},
|
||
"temperatures": [],
|
||
"error": self.error,
|
||
}
|