Version2.0Commit
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Температура MI50 в Linux Mint → pyspark-log-stream.
|
||||
|
||||
Порядок чтения:
|
||||
1) rocm-smi --showtemp --json
|
||||
2) sysfs /sys/class/drm/card*/device/hwmon/hwmon*/temp{1,2}_input
|
||||
При неудаче обоих — ERROR с причиной, чтобы это было видно в агрегации.
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
SOCKET_HOST = "192.168.1.99"
|
||||
SOCKET_PORT = 9999
|
||||
|
||||
WARN_C = 75
|
||||
ERROR_C = 90
|
||||
CHECK_INTERVAL_SEC = 30
|
||||
|
||||
|
||||
def read_temp_rocm() -> int | None:
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["rocm-smi", "--showtemp", "--json"],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
)
|
||||
if out.returncode != 0:
|
||||
return None
|
||||
data = json.loads(out.stdout)
|
||||
for card, info in data.items():
|
||||
if not card.startswith("card"):
|
||||
continue
|
||||
# разные версии rocm-smi используют разные ключи
|
||||
for key in (
|
||||
"Temperature (Sensor edge) (C)",
|
||||
"Temperature (Sensor junction) (C)",
|
||||
"temperature",
|
||||
):
|
||||
if key in info and info[key] not in ("N/A", "", None):
|
||||
return int(float(info[key]))
|
||||
except (FileNotFoundError, json.JSONDecodeError, subprocess.TimeoutExpired, ValueError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def read_temp_sysfs() -> int | None:
|
||||
# приоритет edge (temp1), fallback junction (temp2)
|
||||
for pattern in (
|
||||
"/sys/class/drm/card*/device/hwmon/hwmon*/temp1_input",
|
||||
"/sys/class/drm/card*/device/hwmon/hwmon*/temp2_input",
|
||||
):
|
||||
for path in sorted(glob.glob(pattern)):
|
||||
try:
|
||||
with open(path) as f:
|
||||
millideg = int(f.read().strip())
|
||||
return millideg // 1000
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def read_temp_c() -> tuple[int | None, str]:
|
||||
"""(temp_c, source) или (None, причина)."""
|
||||
t = read_temp_rocm()
|
||||
if t is not None:
|
||||
return t, "rocm-smi"
|
||||
t = read_temp_sysfs()
|
||||
if t is not None:
|
||||
return t, "sysfs"
|
||||
return None, "no_source"
|
||||
|
||||
|
||||
def classify(temp: int | None, source: str) -> tuple[str, str]:
|
||||
if temp is None:
|
||||
return "ERROR", f"MI50_0_temp_c=read_failed:{source}"
|
||||
if temp >= ERROR_C:
|
||||
return "ERROR", f"MI50_0_temp_c={temp}"
|
||||
if temp >= WARN_C:
|
||||
return "WARN", f"MI50_0_temp_c={temp}"
|
||||
return "INFO", f"MI50_0_temp_c={temp}"
|
||||
|
||||
|
||||
def send_log(sock, level: str, message: str) -> None:
|
||||
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
line = f"{ts} [{level}] [linux-mint/gpu-temp] {message}\n"
|
||||
sock.sendall(line.encode("utf-8"))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
print(f"[mint-gpu] Подключаюсь к {SOCKET_HOST}:{SOCKET_PORT} ...", flush=True)
|
||||
with socket.create_connection((SOCKET_HOST, SOCKET_PORT), timeout=10) as sock:
|
||||
print("[mint-gpu] Подключено, начинаю опрос", flush=True)
|
||||
while True:
|
||||
temp, source = read_temp_c()
|
||||
level, msg = classify(temp, source)
|
||||
try:
|
||||
send_log(sock, level, msg)
|
||||
print(f"[mint-gpu] {level}: {msg} (source={source})", flush=True)
|
||||
except (BrokenPipeError, ConnectionResetError) as exc:
|
||||
print(f"[mint-gpu] Соединение потеряно: {exc}", file=sys.stderr, flush=True)
|
||||
break
|
||||
time.sleep(CHECK_INTERVAL_SEC)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user