Files
buryan-infra/ops/audit/audit360_graph.py
T
architect 768ba209f6
lint / hygiene (push) Failing after 19s
lint / hygiene (pull_request) Failing after 23s
standard / check (push) Successful in 10s
standard / check (pull_request) Successful in 10s
[ARCH] Audit 360 service, collectors, snapshots and sprint tool
2026-11-26 21:45:23 +03:00

94 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Extend audit run 1 with Docker containers and systemd dependency edges."""
import json
import re
import subprocess
from pathlib import Path
import psycopg2
PASS = Path("/root/.pg-superuser-pass").read_text().strip()
conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
cur = conn.cursor()
import sys
RUN = int(sys.argv[1]) if len(sys.argv) > 1 else 1
def cmd(args, timeout=15):
try:
p = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
return (p.stdout or "").strip()
except Exception:
return ""
def ent(kind, name, status="unknown", payload=None):
cur.execute("""insert into audit.entities(run_id,kind,name,status,payload)
values(%s,%s,%s,%s,%s) on conflict(run_id,kind,name) do update set status=excluded.status,payload=excluded.payload""",
(RUN, kind, str(name)[:300], status, json.dumps(payload or {}, ensure_ascii=False)))
def link(src, dst, kind, evidence=""):
cur.execute("""insert into audit.links(run_id,src,dst,kind,evidence) values(%s,%s,%s,%s,%s)
on conflict(run_id,src,dst,kind) do nothing""", (RUN, src, dst, kind, evidence[:500]))
def finding(sev, area, title, evidence="", rec=""):
cur.execute("select 1 from audit.findings where run_id=%s and title=%s", (RUN, title))
if not cur.fetchone():
cur.execute("insert into audit.findings(run_id,severity,area,title,evidence,recommendation) values(%s,%s,%s,%s,%s,%s)",
(RUN, sev, area, title, evidence[:2000], rec[:2000]))
# CT list
pct = cmd(["pct", "list"])
cts = []
for line in pct.splitlines()[1:]:
parts = line.split()
if len(parts) >= 3 and parts[0].isdigit() and parts[1] == "running":
cts.append((parts[0], parts[-1]))
ent("container", parts[-1], "running", {"vmid": parts[0]})
containers = 0
for vmid, ctname in cts:
out = cmd(["pct", "exec", vmid, "--", "docker", "ps", "--format", "{{.Names}}|{{.Image}}|{{.Ports}}"], timeout=12)
for line in out.splitlines():
parts = line.split("|")
if len(parts) < 2:
continue
name, image = parts[0].strip(), parts[1].strip()
ports = parts[2].strip() if len(parts) > 2 else ""
ent("docker", "%s:%s" % (ctname, name), "running", {"ct": ctname, "image": image, "ports": ports})
link("container:%s" % ctname, "docker:%s:%s" % (ctname, name), "runs_in", image)
for port in re.findall(r":(\d+)->", ports):
link("docker:%s:%s" % (ctname, name), "port:%s" % port, "listens", ports)
containers += 1
# systemd dependencies
units = cmd(["systemctl", "list-units", "--type=service", "--state=running", "--no-pager", "--plain", "--no-legend"]).splitlines()
deps = 0
for line in units:
parts = line.split()
if not parts or not parts[0].endswith(".service"):
continue
unit = parts[0]
show = cmd(["systemctl", "show", unit, "-p", "After", "-p", "Wants", "-p", "Requires", "--no-pager"], timeout=8)
for dep in re.findall(r"[A-Za-z0-9@_.-]+\.(?:service|socket|target|mount)", show):
if dep != unit:
link("service:%s" % unit, "service:%s" % dep, "depends_on", dep)
deps += 1
# Risk findings tied to facts
finding("high", "data", "Все базы данных на одном CT151",
"PostgreSQL CT151 обслуживает 50 баз; при отказе CT останавливаются Matrix, Gitea, Vaultwarden, Authentik, Prism.",
"Реплика + проверенный failover для критичных БД.")
finding("medium", "ai", "LLM-контур зависит от одного ПК/GPU",
"Ollama 192.168.1.229 + qwen2.5:3b-32k; очередь Prism и аудит используют один GPU.",
"Второй провайдер/модель или облачный fallback; бюджет токенов и SLA.")
finding("medium", "inventory", "Расхождение количества CT с документацией",
"Живой pct list: 30 running; docs/INFRASTRUCTURE-MAP.md: 30, из них 29 running.",
"Обновить карту через ops/inventory/build-map.py и зафиксировать владельцев.")
finding("medium", "observability", "Kuma не различает «порт открыт» и «сервис работает»",
"5 down-мониторов: recipes, sync, Mealie, Syncthing-105, Seerr; проверки портов.",
"Функциональные HTTP/бизнес-проверки для критичных сервисов.")
cur.execute("update audit.runs set summary=jsonb_set(jsonb_set(summary,'{facts,docker_containers}',%s::jsonb,true),'{facts,systemd_links}',%s::jsonb,true) where id=%s",
(json.dumps(containers), json.dumps(deps), RUN))
conn.commit()
print("docker", containers, "systemd_links", deps)
cur.close(); conn.close()