230 lines
11 KiB
Python
230 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Audit 360 collector: deterministic facts only. No LLM here."""
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import psycopg2
|
|
|
|
DB = dict(host="192.168.1.151", dbname="rag", user="postgres",
|
|
password=Path("/root/.pg-superuser-pass").read_text().strip(), client_encoding="UTF8")
|
|
OUT = Path("/root/buryan-infra/ops/audit/runs")
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
def cmd(args, timeout=25):
|
|
try:
|
|
p = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
|
|
return (p.stdout or "").strip()
|
|
except Exception as e:
|
|
return "ERR: %s" % e
|
|
|
|
|
|
def db():
|
|
return psycopg2.connect(**DB)
|
|
|
|
|
|
def init_schema(c):
|
|
cur = c.cursor()
|
|
cur.execute("create schema if not exists audit")
|
|
cur.execute("""create table if not exists audit.runs(
|
|
id bigserial primary key, started_at timestamptz default now(), finished_at timestamptz,
|
|
status text default 'running', summary jsonb default '{}'::jsonb)""")
|
|
cur.execute("""create table if not exists audit.entities(
|
|
id bigserial primary key, run_id bigint references audit.runs(id) on delete cascade,
|
|
kind text not null, name text not null, status text, owner text,
|
|
payload jsonb default '{}'::jsonb, unique(run_id,kind,name))""")
|
|
cur.execute("""create table if not exists audit.links(
|
|
id bigserial primary key, run_id bigint references audit.runs(id) on delete cascade,
|
|
src text not null, dst text not null, kind text not null, evidence text,
|
|
unique(run_id,src,dst,kind))""")
|
|
cur.execute("""create table if not exists audit.findings(
|
|
id bigserial primary key, run_id bigint references audit.runs(id) on delete cascade,
|
|
severity text not null, area text not null, title text not null, evidence text,
|
|
recommendation text)""")
|
|
c.commit()
|
|
|
|
|
|
def main():
|
|
c = db(); init_schema(c); cur = c.cursor()
|
|
cur.execute("insert into audit.runs default values returning id")
|
|
run_id = cur.fetchone()[0]; c.commit()
|
|
facts = {"run_id": run_id, "started_at": datetime.now(timezone.utc).isoformat()}
|
|
|
|
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_id, 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_id, src, dst, kind, evidence[:500]))
|
|
|
|
def finding(sev, area, title, evidence="", rec=""):
|
|
cur.execute("insert into audit.findings(run_id,severity,area,title,evidence,recommendation) values(%s,%s,%s,%s,%s,%s)",
|
|
(run_id, sev, area, title, evidence[:2000], rec[:2000]))
|
|
|
|
# Proxmox containers
|
|
pct = cmd(["pct", "list"])
|
|
for line in pct.splitlines()[1:]:
|
|
parts = line.split()
|
|
if len(parts) >= 3 and parts[0].isdigit():
|
|
name = parts[-1]
|
|
ent("container", name, parts[1], {"vmid": parts[0]})
|
|
facts["containers"] = len([l for l in pct.splitlines()[1:] if l.split()[:1] and l.split()[0].isdigit()])
|
|
|
|
# systemd services
|
|
units = cmd(["systemctl", "list-units", "--type=service", "--all", "--no-pager", "--plain", "--no-legend"])
|
|
running = 0
|
|
for line in units.splitlines():
|
|
parts = line.split()
|
|
if not parts or not parts[0].endswith(".service"):
|
|
continue
|
|
name, load, active, sub = parts[:4]
|
|
if active == "active" and sub == "running":
|
|
running += 1
|
|
if active == "active" or name in ("hub-yandex-bridge.service",):
|
|
ent("service", name, active + "/" + sub, {"description": " ".join(parts[4:])[:300]})
|
|
facts["services_running"] = running
|
|
|
|
# listening sockets
|
|
ss = cmd(["ss", "-ltnp"])
|
|
for line in ss.splitlines()[1:]:
|
|
parts = line.split()
|
|
if len(parts) < 4 or ":" not in parts[3]:
|
|
continue
|
|
addr = parts[3]
|
|
port = addr.rsplit(":", 1)[-1]
|
|
if not port.isdigit():
|
|
continue
|
|
ent("port", port, "listening", {"address": addr})
|
|
facts["ports"] = len(set(re.findall(r"(?m)^LISTEN\s+\S+\s+\S+\s+\S+:(\d+)", ss)))
|
|
|
|
# nginx proxies and config names
|
|
confs = cmd(["bash", "-lc", "ls /etc/nginx/conf.d/*.conf 2>/dev/null"])
|
|
for p in confs.splitlines():
|
|
ent("nginx", Path(p).name, "configured", {"path": p})
|
|
proxies = cmd(["bash", "-lc", "grep -RhoE 'proxy_pass[[:space:]]+[^;]+' /etc/nginx/conf.d 2>/dev/null | sort -u"])
|
|
for line in proxies.splitlines():
|
|
v = line.split("proxy_pass", 1)[-1].strip()
|
|
m = re.search(r"https?://([^/;:]+)(?::(\d+))?", v)
|
|
if not m:
|
|
continue
|
|
host, port = m.group(1), m.group(2)
|
|
dst = "port:%s" % (port or ("443" if v.startswith("https") else "80"))
|
|
link("nginx", dst, "proxies", v)
|
|
if host:
|
|
link("nginx", "host:%s" % host, "upstream_host", v)
|
|
facts["nginx_proxies"] = len(proxies.splitlines())
|
|
|
|
# PostgreSQL databases
|
|
try:
|
|
cur.execute("select datname from pg_database where datistemplate=false order by 1")
|
|
dbs = [x[0] for x in cur.fetchall()]
|
|
for d in dbs:
|
|
ent("database", d, "present")
|
|
facts["databases"] = len(dbs)
|
|
except Exception as e:
|
|
facts["databases_error"] = str(e)
|
|
|
|
# Prism data facts
|
|
try:
|
|
cur.execute("select count(*) from prism.models where coalesce(status,'active')<>'archived'")
|
|
models = cur.fetchone()[0]
|
|
cur.execute("select count(*) from prism.tasks where status in ('pending','running')")
|
|
tasks = cur.fetchone()[0]
|
|
cur.execute("select count(*) from prism.model_practices")
|
|
practices = cur.fetchone()[0]
|
|
cur.execute("select count(*) from prism.model_requirements")
|
|
reqs = cur.fetchone()[0]
|
|
facts["prism"] = {"models": models, "open_tasks": tasks, "practices": practices, "requirements": reqs}
|
|
except Exception as e:
|
|
facts["prism_error"] = str(e)
|
|
|
|
# Kuma
|
|
try:
|
|
km = urllib.request.urlopen("http://192.168.1.107:3010/metrics", timeout=8).read().decode()
|
|
down = re.search(r"^kuma_monitors_down\s+(\d+)", km, re.M)
|
|
total = re.search(r"^kuma_monitors_total\s+(\d+)", km, re.M)
|
|
facts["kuma"] = {"down": int(down.group(1)) if down else None, "total": int(total.group(1)) if total else None}
|
|
if facts["kuma"]["down"]:
|
|
finding("high", "monitoring", "Kuma: %s мониторов down" % facts["kuma"]["down"],
|
|
"kuma_monitors_down=%s, total=%s" % (facts["kuma"]["down"], facts["kuma"]["total"]),
|
|
"Проверить конкретные down-мониторы и владельцев сервисов.")
|
|
except Exception as e:
|
|
facts["kuma_error"] = str(e)
|
|
|
|
# Backups
|
|
try:
|
|
candidates = []
|
|
for pattern in ("/mnt/backups/configs/*.tar.gz", "/mnt/backups/db/*.gz",
|
|
"/mnt/archive/backups/db/*.sql.gz",
|
|
"/mnt/backups/postgresql/*.sql.gz", "/mnt/backups/n8n/*.tar.gz"):
|
|
candidates.extend(Path("/").glob(pattern.lstrip("/")))
|
|
candidates = [p for p in candidates if p.is_file()]
|
|
latest = max(candidates, key=lambda p: p.stat().st_mtime) if candidates else None
|
|
age = (datetime.now().timestamp() - latest.stat().st_mtime) / 86400 if latest else None
|
|
facts["backups"] = {"latest": str(latest) if latest else None, "age_days": round(age, 1) if age else None}
|
|
if latest:
|
|
ent("backup", latest.name, "latest", {"path": str(latest), "age_days": round(age, 1)})
|
|
if age and age > 7:
|
|
finding("high", "backups", "Последний бэкап старше 7 дней",
|
|
"%s, возраст %.1f дней" % (latest, age),
|
|
"Проверить таймеры backup и прислать тестовое восстановление.")
|
|
except Exception as e:
|
|
facts["backups_error"] = str(e)
|
|
|
|
# Disk
|
|
du = shutil.disk_usage("/")
|
|
facts["disk"] = {"total_gb": round(du.total/1e9, 1), "used_pct": round(du.used/du.total*100, 1)}
|
|
|
|
# Repo
|
|
repo = Path("/root/buryan-infra")
|
|
if repo.exists():
|
|
branch = cmd(["git", "-C", str(repo), "branch", "--show-current"])
|
|
head = cmd(["git", "-C", str(repo), "log", "-1", "--oneline"])
|
|
dirty = cmd(["git", "-C", str(repo), "status", "--porcelain"])
|
|
ent("repo", "buryan-infra", "git", {"branch": branch, "head": head, "dirty_files": len(dirty.splitlines())})
|
|
facts["repo"] = {"branch": branch, "head": head, "dirty_files": len(dirty.splitlines())}
|
|
|
|
# Hub status
|
|
try:
|
|
hs = json.loads(urllib.request.urlopen("http://127.0.0.1:9120/status.json", timeout=10).read().decode())
|
|
facts["hub"] = {"up": hs.get("up"), "total": hs.get("total"),
|
|
"down": [s.get("name") for s in hs.get("services", []) if not s.get("up")]}
|
|
ent("hub", "hub-core", "up=%s/%s" % (hs.get("up"), hs.get("total")), {})
|
|
except Exception as e:
|
|
facts["hub_error"] = str(e)
|
|
|
|
# Important inactive/legacy units
|
|
for name in ("hub-yandex-bridge.service", "hub-agents.timer", "hub-brain.timer", "hub-selfheal.timer", "hub-inbox.timer"):
|
|
state = cmd(["systemctl", "is-active", name])
|
|
if state != "active":
|
|
finding("medium", "services", "%s не active" % name, "systemctl is-active = %s" % state,
|
|
"Проверить, должен ли сервис/таймер работать; если нет — зафиксировать в документации.")
|
|
legacy = [n for n in ("combine-web.service", "combine-web2.service", "combine-engine.service", "combine-project.service", "llm-dispatcher.service") if cmd(["systemctl", "is-active", n]) == "active"]
|
|
if legacy:
|
|
finding("medium", "legacy", "Старые/параллельные сервисы активны", ", ".join(legacy),
|
|
"Определить владельца и судьбу: Prism replacement, legacy fallback или удаление.")
|
|
|
|
summary = {"facts": facts, "entities": sum(1 for _ in []), "findings": 0}
|
|
cur.execute("select count(*) from audit.entities where run_id=%s", (run_id,)); summary["entities"] = cur.fetchone()[0]
|
|
cur.execute("select count(*) from audit.findings where run_id=%s", (run_id,)); summary["findings"] = cur.fetchone()[0]
|
|
cur.execute("update audit.runs set finished_at=now(), status='done', summary=%s where id=%s",
|
|
(json.dumps(summary, ensure_ascii=False), run_id))
|
|
c.commit()
|
|
(OUT / ("audit-%s.json" % run_id)).write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print("audit run", run_id, "entities", summary["entities"], "findings", summary["findings"])
|
|
cur.close(); c.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|