167 lines
6.1 KiB
Python
167 lines
6.1 KiB
Python
import os
|
|
import re
|
|
import zipfile
|
|
from datetime import datetime
|
|
import paramiko
|
|
|
|
SERIAL_RE = re.compile(r"^\s*>\s*(\S+)\s*$")
|
|
FIELD_RE = re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*\|\s*(.*?)\s*$")
|
|
SEP_RE = re.compile(r"^[\s\-+|]+$")
|
|
|
|
|
|
def parse_rdcli(text: str):
|
|
drives, cur_serial, cur = [], None, {}
|
|
|
|
def flush():
|
|
nonlocal cur_serial, cur
|
|
if cur_serial is not None:
|
|
rec = {"serial": cur_serial}
|
|
rec.update(cur)
|
|
if rec.get("uid") is not None:
|
|
try:
|
|
rec["uid"] = int(rec["uid"])
|
|
except ValueError:
|
|
pass
|
|
drives.append(rec)
|
|
cur_serial, cur = None, {}
|
|
|
|
for raw in text.splitlines():
|
|
s = raw.strip()
|
|
if not s or s.startswith("[COMMAND]") or s.startswith("[RESULT]") or (
|
|
s.startswith("show") and "drive" in s) or s.startswith("Всего дисков"):
|
|
continue
|
|
if SEP_RE.match(raw):
|
|
continue
|
|
m = SERIAL_RE.match(raw)
|
|
if m:
|
|
flush();
|
|
cur_serial = m.group(1);
|
|
continue
|
|
fm = FIELD_RE.match(raw)
|
|
if fm and cur_serial is not None:
|
|
cur[fm.group(1)] = fm.group(2) if fm.group(2) != "" else None
|
|
flush()
|
|
return drives
|
|
|
|
|
|
def ssh_connect(host, user, password=None, key_path=None, port=22, timeout=30):
|
|
c = paramiko.SSHClient()
|
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
kw = dict(hostname=host, port=port, username=user, timeout=timeout)
|
|
if password:
|
|
kw.update(password=password, look_for_keys=False, allow_agent=False)
|
|
else:
|
|
kw.update(allow_agent=True, look_for_keys=True)
|
|
if key_path: kw["key_filename"] = key_path
|
|
c.connect(**kw)
|
|
return c
|
|
|
|
|
|
def run_remote(client, cmd, timeout=120):
|
|
_, out, err = client.exec_command(cmd, timeout=timeout)
|
|
return out.channel.recv_exit_status(), out.read().decode("utf-8", errors="replace"), err.read().decode("utf-8",
|
|
errors="replace")
|
|
|
|
|
|
def get_remote_hostname(client):
|
|
rc, out, err = run_remote(client, "hostname", timeout=15)
|
|
if rc != 0 or not out.strip(): raise RuntimeError(f"hostname: {err}")
|
|
return out.strip()
|
|
|
|
|
|
def fetch_rdcli(client):
|
|
rc, out, err = run_remote(client, "rdcli drive show", timeout=60)
|
|
if rc != 0 or not out.strip(): raise RuntimeError(f"rdcli: {err}")
|
|
return out
|
|
|
|
|
|
def safe(s): return re.sub(r"[^A-Za-z0-9._-]+", "_", str(s))
|
|
|
|
|
|
def smart_filename(hostname, d):
|
|
return f"{safe(hostname)}_{safe(d.get('uid'))}_{safe(d.get('serial') or 'noserial')}_{safe(d.get('name') or 'noname')}.txt"
|
|
|
|
|
|
# --- ЖЕЛЕЗОБЕТОННЫЙ ПАРСЕР ---
|
|
TEMP_RE = re.compile(r"Current Drive Temperature:\s*(\d+)", re.IGNORECASE)
|
|
|
|
|
|
def parse_smart_metrics(text, bdev=""):
|
|
temp = poh = health = nonmed = 0
|
|
|
|
if m := TEMP_RE.search(text):
|
|
temp = int(m.group(1))
|
|
|
|
for line in text.splitlines():
|
|
line_lower = line.lower()
|
|
|
|
if "accumulated power on time" in line_lower:
|
|
if m := re.search(r"(\d+):\d{2}", line):
|
|
poh = int(m.group(1))
|
|
|
|
if "non-medium error count" in line_lower:
|
|
digits = re.findall(r"\d+", line)
|
|
if digits:
|
|
nonmed = int(digits[0])
|
|
# ВЫВОДИМ В КОНСОЛЬ, ЧТОБЫ ВИДЕТЬ, ЧТО ПАРСЕР РАБОТАЕТ
|
|
if nonmed > 0:
|
|
print(f"[SMART] {bdev}: найдено {nonmed} ошибок! (строка: '{line.strip()}')")
|
|
|
|
if "smart health status" in line_lower:
|
|
parts = line.split(":")
|
|
if len(parts) > 1: health = parts[1].strip()
|
|
|
|
return {"temperature": temp, "power_on_hours": poh, "health": health, "non_medium_errors": nonmed}
|
|
|
|
|
|
def collect_smart(client, hostname, drives, outdir):
|
|
os.makedirs(outdir, exist_ok=True)
|
|
results = []
|
|
for d in drives:
|
|
bdev = d.get("bdev")
|
|
if not bdev:
|
|
results.append({**d, "smart_rc": None, "smart_file": None, "smart_error": "no bdev", "temperature": None,
|
|
"power_on_hours": None, "health": None, "non_medium_errors": None})
|
|
continue
|
|
cmd = f"smartctl -x -d scsi {bdev}"
|
|
rc, stdout, stderr = run_remote(client, cmd)
|
|
fname = os.path.join(outdir, smart_filename(hostname, d))
|
|
with open(fname, "w", encoding="utf-8") as f:
|
|
f.write(
|
|
f"# hostname: {hostname}\n# cmd: {cmd}\n# serial: {d.get('serial')} name: {d.get('name')} uid: {d.get('uid')}\n# rc: {rc}\n# ---- stdout ----\n{stdout}")
|
|
if stderr: f.write(f"\n# ---- stderr ----\n{stderr}")
|
|
|
|
metrics = parse_smart_metrics(stdout, bdev)
|
|
results.append({**d, **metrics, "smart_rc": rc, "smart_file": fname,
|
|
"smart_error": None if rc in (0, 4) else (stderr.strip() or f"rc={rc}")})
|
|
return results
|
|
|
|
|
|
def make_archive_name(hostname):
|
|
now = datetime.now()
|
|
return f"{safe(hostname)}_{now.strftime('%Y%m%d_%H%M%S')}_{now.microsecond // 1000:03d}.zip"
|
|
|
|
|
|
def pack_zip(files, hostname, outdir):
|
|
os.makedirs(outdir, exist_ok=True)
|
|
path = os.path.join(outdir, make_archive_name(hostname))
|
|
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as z:
|
|
for f in files:
|
|
if f and os.path.isfile(f): z.write(f, arcname=os.path.basename(f))
|
|
return path
|
|
|
|
|
|
def collect(ssh_host, user, password=None, key_path=None, port=22, hostname_override=None, runs_dir="data/runs"):
|
|
client = ssh_connect(ssh_host, user, password, key_path, port)
|
|
try:
|
|
hostname = hostname_override or get_remote_hostname(client)
|
|
text = fetch_rdcli(client)
|
|
drives = parse_rdcli(text)
|
|
if not drives: raise RuntimeError("Парсер rdcli вернул 0 дисков")
|
|
run_dir = os.path.join(runs_dir, hostname)
|
|
drives = collect_smart(client, hostname, drives, run_dir)
|
|
finally:
|
|
client.close()
|
|
files = [d["smart_file"] for d in drives if d.get("smart_file")]
|
|
archive = pack_zip(files, hostname, run_dir) if files else None
|
|
return hostname, drives, archive |