#!/usr/bin/env python3 """Гигиенический скан (V1, Фаза B): дубли, осиротевшие юниты, RAM-долги, слепые зоны. Только чтение. Пишет ops/hygiene/report-YYYY-MM-DD.md """ import json import os import re import subprocess from collections import defaultdict from datetime import date OUT = "/root/buryan-infra/ops/hygiene" TOPO = "/root/buryan-infra/ops/topology/topology.json" def sh(cmd, timeout=60): try: r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout) return (r.stdout or "").strip() except Exception: return "" def main(): findings = [] # ---------- 1. контейнеры и CT ---------- cts = [] for line in sh("pct list").splitlines()[1:]: p = line.split() if len(p) >= 2: cts.append({"ct": p[0], "status": p[1], "name": p[2] if len(p) > 2 else ""}) containers = [] for c in cts: if c["status"] != "running": continue out = sh("pct exec %s -- docker ps --format '{{.Names}}|{{.Image}}' 2>/dev/null" % c["ct"], 40) for ln in out.splitlines(): if "|" in ln: n, img = ln.split("|", 1) containers.append({"ct": c["ct"], "name": n, "image": img}) # ---------- 2. дубли образов ---------- # служебные агенты ставятся на КАЖДЫЙ CT — это норма, не дубль SHARED_AGENTS = {"beszel-agent", "promtail", "node-exporter", "node_exporter", "cadvisor", "watchtower", "docker-proxy", "oauth2-proxy"} # инфраструктурные образы: могут жить в нескольких CT осознанно INFRA = {"redis", "postgres", "mariadb", "nginx", "mosquitto", "eclipse-mosquitto", "syncthing", "server", "traefik", "caddy"} by_image = defaultdict(list) for ct in containers: base = ct["image"].split("/")[-1].split(":")[0].lower() by_image[base].append(ct) for img, items in by_image.items(): cts_set = {i["ct"] for i in items} if len(cts_set) < 2: continue if img in SHARED_AGENTS: continue sev = "medium" if img in INFRA else "high" note = ("инфраструктурный образ — может быть осознанно" if img in INFRA else "вероятно, остался старый экземпляр — тратит RAM/CPU") findings.append({ "sev": sev, "kind": "дубль сервиса", "what": "образ `%s` живёт в нескольких CT: %s" % (img, ", ".join(sorted(cts_set))), "why": note, "fix": "определить нужный экземпляр и остановить лишний" if sev == "high" else "проверить, нужны ли все экземпляры", }) # ---------- 3. осиротевшие юниты ---------- inactive = sh("systemctl list-units --type=service --state=inactive --all --no-legend 2>/dev/null") orphans_enabled, orphans_disabled = [], [] for ln in inactive.splitlines(): parts = ln.split() if not parts: continue name = parts[0] if not re.match(r"(hub-|hermes|buryan)", name): continue en = sh("systemctl is-enabled %s 2>/dev/null" % name, 10).strip() (orphans_enabled if en == "enabled" else orphans_disabled).append(name) if orphans_enabled: findings.append({ "sev": "high", "kind": "включён, но не работает", "what": "%d юнитов enabled, но inactive: %s" % ( len(orphans_enabled), ", ".join(sorted(orphans_enabled)[:12])), "why": "должны работать — но лежат. Либо сломаны при старте, либо остановлены вручную", "fix": "проверить `journalctl -u ` и запустить или выключить", }) if orphans_disabled: findings.append({ "sev": "medium", "kind": "заготовки без запуска", "what": "%d юнитов существуют, но disabled: %s" % ( len(orphans_disabled), ", ".join(sorted(orphans_disabled)[:12])), "why": "спроектированы, но не введены в работу — незавершённость", "fix": "решить: внедрять, законсервировать или удалить", }) # ---------- 4. CT с onboot=0 ---------- for c in cts: cfg = sh("cat /etc/pve/lxc/%s.conf 2>/dev/null" % c["ct"], 15) if "onboot: 1" not in cfg: findings.append({ "sev": "low", "kind": "не поднимется сам", "what": "CT%s (%s) — onboot=0" % (c["ct"], c["name"]), "why": "после перезагрузки хоста останется выключенным", "fix": "включить onboot или подтвердить, что так задумано", }) # ---------- 5. RAM-долги ---------- mem = [] for c in cts: if c["status"] != "running": continue out = sh("pct exec %s -- docker stats --no-stream --format '{{.Name}}|{{.MemUsage}}|{{.CPUPerc}}' 2>/dev/null" % c["ct"], 45) for ln in out.splitlines(): p = ln.split("|") if len(p) >= 2: m = re.search(r"([\d.]+)\s*([KMG])iB", p[1]) if m: val = float(m.group(1)) * {"K": 1 / 1024, "M": 1, "G": 1024}[m.group(2)] mem.append({"name": p[0], "ct": c["ct"], "mb": val, "raw": p[1], "cpu": p[2] if len(p) > 2 else ""}) mem.sort(key=lambda x: -x["mb"]) for m in mem[:10]: findings.append({ "sev": "info", "kind": "потребление RAM", "what": "`%s` (CT%s) — %s, CPU %s" % (m["name"], m["ct"], m["raw"], m["cpu"]), "why": "для лёджера: следим за ростом", "fix": "—", }) # ---------- 6. слепые зоны мониторинга ---------- try: tg = json.loads(sh("curl -s -m 15 http://192.168.1.134:9090/api/v1/targets", 25) or "{}") act = (tg.get("data") or {}).get("activeTargets") or [] for t in act: if t.get("health") != "up": findings.append({ "sev": "high", "kind": "слепая зона", "what": "target down: %s (%s)" % (t.get("labels", {}).get("job"), t.get("scrapeUrl")), "why": "метрик нет — система не видит эту часть", "fix": "перезапустить экспортёр / проверить порт", }) except Exception: pass # ---------- 7. диск ---------- for line in sh("df -h / /var/lib/vz 2>/dev/null | tail -2").splitlines(): m = re.search(r"(\d+)%", line) if m and int(m.group(1)) > 80: findings.append({ "sev": "high", "kind": "место на диске", "what": line.strip(), "why": "выше 80% — пора чистить", "fix": "ротация логов, prune образов", }) # ---------- отчёт ---------- os.makedirs(OUT, exist_ok=True) path = os.path.join(OUT, "report-%s.md" % date.today().isoformat()) counts = defaultdict(int) for f in findings: counts[f["sev"]] += 1 lines = ["# Гигиенический отчёт — %s" % date.today().isoformat(), "", "Найдено: **%d**" % len(findings), "· high: %d · medium: %d · low: %d · info: %d" % ( counts["high"], counts["medium"], counts["low"], counts["info"]), ""] order = {"high": 0, "medium": 1, "low": 2, "info": 3} for f in sorted(findings, key=lambda x: order[x["sev"]]): lines += ["## [%s] %s" % (f["sev"].upper(), f["kind"]), "", "**Что:** %s" % f["what"], "", "**Почему важно:** %s" % f["why"], "", "**Что делать:** %s" % f["fix"], ""] open(path, "w", encoding="utf-8").write("\n".join(lines) + "\n") print("отчёт:", path) print("найдено:", len(findings), "| high:", counts["high"], "medium:", counts["medium"], "low:", counts["low"], "info:", counts["info"]) for f in sorted(findings, key=lambda x: order[x["sev"]]): if f["sev"] in ("high", "medium"): print(" [%s] %s — %s" % (f["sev"], f["kind"], f["what"][:90])) if __name__ == "__main__": main()