Files
buryan-infra/ops/scripts/hygiene_scan.py

554 lines
27 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Гигиенический скан Buryans Hub (V1, расширенный).
Только чтение. Проверки сгруппированы в реестр — легко добавлять новые.
Отчёт: ops/hygiene/report-YYYY-MM-DD.md
"""
import json
import os
import re
import subprocess
from collections import defaultdict
from datetime import date, datetime
OUT = "/root/buryan-infra/ops/hygiene"
VPS = "193.233.210.184"
FINDINGS = []
def add(sev, kind, what, why, fix):
FINDINGS.append({"sev": sev, "kind": kind, "what": what, "why": why, "fix": fix})
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 shv(cmd, timeout=60):
return sh("ssh -o ConnectTimeout=10 -o BatchMode=yes root@%s '%s'"
% (VPS, cmd.replace("'", "'\\''")), timeout)
def cts():
out = []
for line in sh("pct list").splitlines()[1:]:
p = line.split()
if len(p) >= 2:
out.append({"ct": p[0], "status": p[1], "name": p[2] if len(p) > 2 else ""})
return out
def containers():
res = []
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)
res.append({"ct": c["ct"], "name": n, "image": img})
return res
# ─────────────────────────── проверки ───────────────────────────
def check_duplicates():
SHARED = {"beszel-agent", "promtail", "node-exporter", "node_exporter", "cadvisor",
"watchtower", "docker-proxy", "oauth2-proxy"}
INFRA = {"redis", "postgres", "mariadb", "nginx", "mosquitto", "eclipse-mosquitto",
"syncthing", "server", "traefik", "caddy"}
by_image = defaultdict(list)
for c in containers():
base = c["image"].split("/")[-1].split(":")[0].lower()
by_image[base].append(c)
for img, items in by_image.items():
cts_set = {i["ct"] for i in items}
if len(cts_set) < 2 or img in SHARED:
continue
# один образ ≠ один сервис: сравниваем РОЛИ (имена контейнеров)
roles = {i["name"].lower() for i in items}
same_role = len(roles) < len(items)
detail = "; ".join("CT%s:%s" % (i["ct"], i["name"]) for i in sorted(items, key=lambda x: x["ct"]))
if not same_role:
# разные роли на одном образе (nginx: ha-strip / house3d-web) — это норма
add("info", "один образ, разные сервисы", "`%s` — %s" % (img, detail),
"один и тот же образ используется разными сервисами — не дубль",
"ничего не делать")
continue
sev = "medium" if img in INFRA else "high"
add(sev, "дубль сервиса",
"образ `%s` в CT: %s" % (img, ", ".join(sorted(cts_set))),
"инфраструктурный образ (может быть осознанно)" if img in INFRA
else "вероятно, старый экземпляр — тратит RAM",
"проверить необходимость всех экземпляров" if sev == "medium"
else "оставить один, лишний остановить")
def check_units():
inactive = sh("systemctl list-units --type=service --state=inactive --all --no-legend 2>/dev/null")
enabled_broken, disabled, static = [], [], []
for ln in inactive.splitlines():
name = ln.split()[0] if ln.split() else ""
if not re.match(r"(hub-|hermes|buryan)", name):
continue
en = sh("systemctl is-enabled %s 2>/dev/null" % name, 10).strip()
if en == "enabled":
enabled_broken.append(name)
elif en == "disabled":
disabled.append(name)
elif en == "static":
# static = запускается по требованию/таймером, автозапуск не предусмотрен
static.append(name)
if enabled_broken:
add("high", "включён, но не работает",
"%d юнитов: %s" % (len(enabled_broken), ", ".join(sorted(enabled_broken)[:10])),
"должны работать — но лежат", "journalctl -u <unit>, затем запустить или выключить")
if disabled:
add("medium", "выключенные юниты",
"%d: %s" % (len(disabled), ", ".join(sorted(disabled)[:10])),
"юнит отключён — либо забыт, либо сознательно",
"подтвердить: включить или задокументировать в maintenance.yaml")
if static:
add("info", "статические юниты",
"%d шт. (из %d hub-*)" % (len(static), len(static) + len(disabled) + len(enabled_broken)),
"запускаются по требованию/таймером — автозапуск не предусмотрен, это не «заготовки»",
"—")
def check_failed_units():
out = sh("systemctl --failed --no-legend --no-pager 2>/dev/null")
if not out:
return
names = []
for ln in out.splitlines():
m = re.search(r"([\w@.\-]+\.(?:service|socket|timer|swap|mount))", ln)
if m:
names.append(m.group(1))
if names:
add("high", "упавшие юниты", "%d: %s" % (len(names), ", ".join(names[:12])),
"сервис в состоянии failed — не работает или не стартовал после сбоя",
"systemctl reset-failed <unit> && systemctl start <unit>")
def check_onboot():
for c in cts():
cfg = sh("cat /etc/pve/lxc/%s.conf 2>/dev/null" % c["ct"], 15)
if "onboot: 1" not in cfg:
add("low", "не поднимется сам", "CT%s (%s) onboot=0" % (c["ct"], c["name"]),
"после перезагрузки хоста останется выключенным", "включить onboot или подтвердить")
# VM тоже должны подниматься сами (immich — критичный сервис)
for ln in sh("qm list 2>/dev/null", 20).splitlines()[1:]:
p = ln.split()
if len(p) < 2:
continue
vmid, name = p[0], p[1]
cfg = sh("cat /etc/pve/qemu-server/%s.conf 2>/dev/null" % vmid, 15)
if "onboot: 1" not in cfg:
add("medium", "VM не поднимется сама", "VM%s (%s) onboot=0" % (vmid, name),
"после перезагрузки виртуалка останется выключенной (сервис недоступен)",
"qm set %s -onboot 1" % vmid)
def check_ram():
mem = []
for c in cts():
if c["status"] != "running":
continue
out = sh("pct exec %s -- docker stats --no-stream --format '{{.Name}}|{{.MemUsage}}|{{.CPUPerc}}'"
% 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"])
top = " · ".join("%s %s" % (m["name"], m["raw"].split("/")[0].strip()) for m in mem[:6])
add("info", "потребление RAM", "топ: " + top, "лёджер: следим за ростом", "—")
for m in mem[:3]:
if m["mb"] > 800:
add("medium", "крупный потребитель RAM",
"%s (CT%s) — %s, CPU %s" % (m["name"], m["ct"], m["raw"], m["cpu"]),
"больше 800 МиБ — кандидат на оптимизацию", "проверить лимиты/необходимость")
def check_monitoring():
tg = sh("curl -s -m 15 http://192.168.1.134:9090/api/v1/targets", 25)
try:
d = json.loads(tg)
except Exception:
add("high", "мониторинг недоступен", "Prometheus не ответил на /api/v1/targets",
"система слепа", "проверить CT134 и контейнер prometheus")
return
act = (d.get("data") or {}).get("activeTargets") or []
down = [t for t in act if t.get("health") != "up"]
if down:
add("high", "слепые зоны", "targets down: " + ", ".join(
"%s(%s)" % (t.get("labels", {}).get("job"), t.get("labels", {}).get("instance"))
for t in down[:8]), "метрик по ним нет", "перезапустить экспортёр")
add("info", "мониторинг", "таргетов: %d, up: %d" % (len(act), len(act) - len(down)),
"полнота наблюдения", "—")
def check_disk():
out = sh("df -h / /var/lib/vz /media 2>/dev/null | tail -3")
for line in out.splitlines():
m = re.search(r"(\d+)%", line)
if m and int(m.group(1)) > 80:
add("high", "место на диске", line.strip(), "выше 80% — пора чистить",
"ротация логов, prune образов")
def check_ct_disk():
out = sh("df -h 2>/dev/null | grep -E 'lxc|subvol' | awk '{print $6, $5}' | head -20")
for line in out.splitlines():
parts = line.split()
if len(parts) == 2 and parts[1].rstrip("%").isdigit() and int(parts[1].rstrip("%")) > 85:
add("medium", "диск контейнера", "%s — %s" % (parts[0], parts[1]),
"контейнер близок к заполнению", "почистить внутри CT")
def check_certs():
for label, cmd in (("хост", "for d in /etc/letsencrypt/live/*/; do "
"n=$(basename $d); e=$(openssl x509 -enddate -noout -in $d/fullchain.pem 2>/dev/null | cut -d= -f2); "
"echo \"$n|$e\"; done"),
("VPS", "for d in /etc/letsencrypt/live/*/; do "
"n=$(basename $d); e=$(openssl x509 -enddate -noout -in $d/fullchain.pem 2>/dev/null | cut -d= -f2); "
"echo \"$n|$e\"; done")):
out = shv(cmd, 60) if label == "VPS" else sh(cmd, 60)
for ln in out.splitlines():
if "|" not in ln:
continue
name, enddate = ln.split("|", 1)
try:
exp = datetime.strptime(enddate.strip(), "%b %d %H:%M:%S %Y %Z")
days = (exp - datetime.now()).days
except Exception:
continue
if days < 0:
add("high", "сертификат просрочен", "%s (%s): %d дн." % (name, label, days),
"сайт не откроется по HTTPS", "certbot renew --force-renewal")
elif days < 21:
add("high", "сертификат истекает", "%s (%s): %d дн." % (name, label, days),
"осталось меньше трёх недель", "certbot renew")
def check_backups():
out = sh("ls -lt /var/lib/vz/dump/*.tar.zst /var/lib/vz/dump/*.vma.zst "
"/mnt/backup/*/*.tar.zst 2>/dev/null | head -3", 30)
if not out:
add("medium", "бэкапы", "не найдено свежих архивов в /var/lib/vz/dump",
"не понимаем, есть ли бэкапы", "проверить backup_configs.py и vzdump")
return
first = out.splitlines()[0]
m = re.search(r"(\w{3})\s+(\d+)\s+(\d+):(\d+)", first)
add("info", "бэкапы", "последний: " + first.split()[-1].split("/")[-1][:60],
"проверка свежести вручную по дате", "—")
def check_docker_waste():
total_img, total_vol, total_stopped = 0, 0, 0
for c in cts():
if c["status"] != "running":
continue
d = sh("pct exec %s -- docker system df --format '{{.Type}}|{{.TotalCount}}|{{.Reclaimable}}' 2>/dev/null" % c["ct"], 40)
for ln in d.splitlines():
p = ln.split("|")
if len(p) < 3:
continue
try:
cnt = int(p[1])
except Exception:
continue
if p[0].startswith("Images"):
total_img += cnt
if p[0].startswith("Volumes"):
total_vol += cnt
stopped = sh("pct exec %s -- docker ps -a --filter status=exited --format '{{.Names}}' 2>/dev/null" % c["ct"], 40)
n = len([x for x in stopped.splitlines() if x.strip()])
if n:
total_stopped += n
add("low", "остановленные контейнеры", "CT%s: %d (%s)" % (c["ct"], n, ", ".join(stopped.splitlines()[:5])),
"занимают место и путают инвентарь", "docker rm, если не нужны")
add("info", "docker-мусор", "образов: %d, томов: %d, остановленных: %d" % (total_img, total_vol, total_stopped),
"кандидаты на docker system prune", "docker image prune -a (осторожно)")
def check_logs():
big = sh("find /var/log -type f -size +200M 2>/dev/null | head -5", 60)
for f in big.splitlines():
sz = sh("du -h '%s' 2>/dev/null | cut -f1" % f, 10)
add("medium", "огромный лог", "%s — %s" % (f, sz), "растёт бесконтрольно",
"настроить logrotate или усечь")
jsz = sh("journalctl --disk-usage 2>/dev/null | grep -o '[0-9.]*[GM]' | head -1")
if jsz and (jsz.endswith("G") or (jsz.endswith("M") and float(jsz[:-1]) > 1500)):
add("medium", "журнал systemd", "journal занимает %s" % jsz, "растёт без ротации",
"journalctl --vacuum-size=500M")
def check_secrets_perms():
out = sh("find /root -maxdepth 1 -type f \\( -name '.*key*' -o -name '.*token*' -o -name '.*env' \\) "
"-perm /077 2>/dev/null | head -10", 30)
for f in out.splitlines():
add("high", "права на секрет", "%s доступен группе/всем" % f,
"секрет может утечь", "chmod 600 %s" % f)
def check_swap_pressure():
out = sh("free -m | tail -2")
lines = out.splitlines()
if len(lines) >= 2:
swap = lines[1].split()
if len(swap) >= 3:
used, total = int(swap[2]), int(swap[1])
if total and used / total > 0.5:
add("medium", "swap", "использовано %d из %d МиБ" % (used, total),
"память на пределе — риск лавины (инцидент 04.11)", "проверить топRAM, добавить память")
psi = sh("cat /proc/pressure/memory 2>/dev/null | head -1")
m = re.search(r"full avg10=([\d.]+)", psi or "")
if m and float(m.group(1)) > 20:
add("high", "давление памяти", "PSI full avg10=%.1f%%" % float(m.group(1)),
"процессы ждут память — деградация", "сократить нагрузку немедленно")
def check_cron_hotspots():
out = sh("cat /etc/cron.d/* /var/spool/cron/crontabs/* 2>/dev/null | "
"grep -E '^[0-9*]' | awk '{print $1\" \"$2}' | sort | uniq -c | sort -rn | head -5", 30)
for line in out.splitlines():
p = line.split()
if len(p) >= 3 and int(p[0]) >= 8:
add("medium", "cron-нагрузка", "%s задач в минуту %s %s" % (p[0], p[1], p[2]),
"одновременный старт — риск пиков", "разнести по времени")
def check_compose_drift():
"""Сверка deploy/ctNNN/docker-compose.yml с живыми контейнерами."""
base = "/root/buryan-infra/deploy"
script = "/root/buryan-infra/ops/scripts/check-compose-parity.py"
if not (os.path.isdir(base) and os.path.exists(script)):
return
drift, checked, errors = [], 0, 0
for d in sorted(os.listdir(base)):
if not d.startswith("ct"):
continue
ct = d[2:]
out = sh("cd /root/buryan-infra && timeout 60 /usr/bin/python3 %s %s 2>&1 | tail -2"
% (script, ct), 90)
if not out:
errors += 1
continue
m = re.search(r"расхождений\s+(\d+)", out)
if not m:
errors += 1
continue
checked += 1
if int(m.group(1)) > 0:
drift.append("CT%s: %s расхождений" % (ct, m.group(1)))
if drift:
add("high", "drift compose", "; ".join(drift[:8]),
"живое состояние расходится с git — восстановление из репозитория не сработает",
"python3 ops/scripts/check-compose-parity.py <ct> и обновить compose")
# --- (2) живой compose-файл на CT vs файл в git ---
file_drift = []
multi_project = []
for d in sorted(os.listdir(base)):
if not d.startswith("ct"):
continue
ct = d[2:]
repo_file = os.path.join(base, d, "docker-compose.yml")
if not os.path.exists(repo_file):
continue
wds = sh("pct exec %s -- sh -c 'docker ps -q 2>/dev/null | head -20 | xargs -r docker inspect "
"--format \"{{index .Config.Labels \\\"com.docker.compose.project.working_dir\\\"}}\" 2>/dev/null "
"| sort -u'" % ct, 60).split()
wds = [w for w in wds if w.startswith("/")]
if not wds:
continue
# мультипроектный CT: один файл в git не может повторять несколько проектов
if len(wds) > 1:
multi_project.append("CT%s (%d)" % (ct, len(wds)))
continue
def norm(t):
return "\n".join(x.rstrip() for x in t.splitlines()
if x.strip() and not x.strip().startswith("#"))
repo_norm = norm(open(repo_file, encoding="utf-8").read())
matched = False
for wd in wds:
live = sh("pct exec %s -- sh -c 'cat %s/docker-compose.yml 2>/dev/null'" % (ct, wd), 40)
if live and norm(live) == repo_norm:
matched = True
break
if not matched:
file_drift.append("CT%s (%d каталогов)" % (ct, len(wds)))
if file_drift:
add("medium", "compose-файл ≠ git", "; ".join(file_drift[:8]),
"на CT другая версия compose, чем в репозитории — правки не закоммичены",
"diff <(pct exec <ct> cat <dir>/docker-compose.yml) deploy/ct<N>/docker-compose.yml")
if multi_project:
add("info", "мультипроектные CT", "; ".join(multi_project[:8]),
"несколько compose-проектов в одном CT — файл в git является снимком",
"учитывать при восстановлении: поднимать проекты по отдельности")
add("info", "compose-паритет", "проверено CT: %d, контейнер-дрейф: %d, файл≠git: %d, ошибок: %d"
% (checked, len(drift), len(file_drift), errors), "соответствие репозиторию", "—")
def check_backup_freshness():
"""Проверяет, что задания бэкапа реально отрабатывали за последние сутки."""
jobs = [
("postgres", "/var/log/buryan-hub/backups/cron-pg.log", 26),
("matrix", "/var/log/buryan-hub/backups/cron-matrix.log", 26),
("infra-ops", "/root/buryan-infra/ops/backups/backup.log", 26),
("offsite", "/var/log/buryan-hub/backups/cron-offsite.log", 30),
]
stale, ok = [], []
now = datetime.now().timestamp()
for name, path, hours in jobs:
if not os.path.exists(path):
stale.append("%s (нет лога %s)" % (name, path))
continue
age_h = (now - os.path.getmtime(path)) / 3600
if age_h > hours:
stale.append("%s (%.1f ч назад)" % (name, age_h))
else:
ok.append("%s (%.1f ч)" % (name, age_h))
# vzdump: самый свежий архив
newest = sh("ls -t /var/lib/vz/dump/*.tar.zst 2>/dev/null | head -1", 20)
if newest:
try:
age_h = (now - os.path.getmtime(newest)) / 3600
if age_h > 26:
stale.append("vzdump (%.1f ч назад)" % age_h)
else:
ok.append("vzdump (%.1f ч)" % age_h)
except Exception:
pass
else:
stale.append("vzdump (архивов не найдено)")
if stale:
add("high", "бэкапы не свежие", "; ".join(stale[:6]),
"восстановление будет из устаревших данных",
"проверить cron/логи, запустить вручную")
if ok:
add("info", "бэкапы в норме", ", ".join(ok[:6]), "свежесть подтверждена", "—")
def check_http_health():
"""HTTP-здоровье критичных сервисов (без пересоздания контейнеров).
Любой ответ кроме пустого считается «жив»: 200/302/401 — сервис отвечает.
Это заменяет docker HEALTHCHECK там, где пересоздание рискованно.
"""
targets = [
("Jellyfin", "http://192.168.1.103:8096/health"),
("Home Assistant", "http://192.168.1.106:8123/manifest.json"),
("Authentik", "http://192.168.1.114:9000/-/health/live/"),
("Gitea", "http://192.168.1.140:3000/api/healthz"),
("n8n", "http://192.168.1.108:5680/healthz"),
("Paperless", "http://192.168.1.110:8000/"),
("Immich (VM)", "http://192.168.1.104:2283/api/server/ping"),
("Matrix", "http://192.168.1.155:8008/_matrix/client/versions"),
("qBittorrent", "http://192.168.1.123:8085/"),
]
dead, alive = [], []
for name, url in targets:
code = sh("curl -s -o /dev/null -w '%%{http_code}' -m 8 '%s' 2>/dev/null" % url, 20).strip()
if code and code != "000":
alive.append("%s %s" % (name, code))
else:
dead.append("%s (%s)" % (name, url.replace("http://", "")))
if dead:
add("high", "сервис не отвечает", "; ".join(dead[:6]),
"HTTP-проверка не прошла — сервис лежит или недоступен по сети",
"systemctl status <unit> / docker ps в CT; проверить логи")
add("info", "HTTP-здоровье", "отвечают %d из %d: %s"
% (len(alive), len(targets), ", ".join(alive[:9])), "сервисы живы", "—")
def check_llm_node():
"""Локальный LLM-узел: доступен ли и загружена ли модель."""
host = "http://192.168.1.229:11434"
out = sh("curl -s -m 10 %s/api/tags" % host, 20)
if not out:
add("high", "LLM-узел недоступен", "%s не отвечает" % host,
"batch-задачи (анализ логов, сводки) выполняться не смогут",
"проверить питание/сеть узла, systemctl status ollama")
return
try:
models = [m.get("name") for m in (json.loads(out).get("models") or [])]
except Exception:
models = []
if not models:
add("medium", "LLM-узел без модели", "API отвечает, но моделей нет",
"узел работает вхолостую", "ollama pull qwen2.5:7b")
return
add("info", "LLM-узел", "доступен, моделей: %d (%s)" % (len(models), ", ".join(models[:3])),
"batch-инференс готов", "—")
CHECKS = [check_duplicates, check_units, check_failed_units, check_onboot, check_ram,
check_monitoring, check_disk, check_ct_disk, check_certs, check_backups,
check_backup_freshness, check_compose_drift, check_docker_waste, check_logs,
check_secrets_perms, check_swap_pressure, check_cron_hotspots, check_llm_node,
check_http_health]
def main():
for fn in CHECKS:
try:
fn()
except Exception as e:
add("medium", "ошибка проверки", "%s: %s" % (fn.__name__, str(e)[:120]),
"проверка не отработала", "посмотреть трейс")
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
order = {"high": 0, "medium": 1, "low": 2, "info": 3}
lines = ["# Гигиенический отчёт — %s" % date.today().isoformat(), "",
"Проверок: %d · находок: **%d**" % (len(CHECKS), len(FINDINGS)),
"· high: %d · medium: %d · low: %d · info: %d" % (
counts["high"], counts["medium"], counts["low"], counts["info"]), "",
"## Сводка по категориям", "", "| Тип | Кол-во | Уровень |", "|---|---|---|"]
by_kind = defaultdict(lambda: [0, "info"])
for f in FINDINGS:
by_kind[f["kind"]][0] += 1
if order[f["sev"]] < order[by_kind[f["kind"]][1]]:
by_kind[f["kind"]][1] = f["sev"]
for kind, (n, sev) in sorted(by_kind.items(), key=lambda x: order[x[1][1]]):
lines.append("| %s | %d | %s |" % (kind, n, sev))
lines.append("")
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("проверок: %d | находок: %d | high: %d medium: %d low: %d info: %d"
% (len(CHECKS), len(FINDINGS), counts["high"], counts["medium"], counts["low"], counts["info"]))
for f in sorted(FINDINGS, key=lambda x: order[x["sev"]]):
if f["sev"] in ("high", "medium"):
print(" [%s] %-26s %s" % (f["sev"], f["kind"], f["what"][:80]))
if __name__ == "__main__":
main()