[SPRINT-V1][C/F] Закрытие контура: лёджер v2 (диск/образы/запросы), мультиагентные специалисты, валидатор правил, уверенность в дайджесте, журнал гипотез

This commit is contained in:
root committed 2026-11-05 22:55:04 +03:00
1 parent c5e35f0b18
commit 107d8ca5c2
11 files changed
+362 -4

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Дополнение лёджера: диск по CT, возраст образов, использование по доменам.
Дописывает в ops/topology/ledger.md разделы, которых не хватало для
оценки «стоимости» сервиса (пункт 3 контура V1).
"""
import json
import os
import re
import subprocess
from datetime import datetime
ROOT = "/root/buryan-infra"
LEDGER = ROOT + "/ops/topology/ledger.md"
VPS = "193.233.210.184"
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():
sections = []
# 1) диск по контейнерам
rows = []
for line in sh("pct list").splitlines()[1:]:
p = line.split()
if len(p) < 2 or p[1] != "running":
continue
ct, name = p[0], (p[2] if len(p) > 2 else "")
out = sh("pct exec %s -- sh -c \"df -h / | tail -1\" " % ct, 30)
m = re.search(r"(\d+)%\s+/\s*$", out)
if m:
rows.append((int(m.group(1)), ct, name))
rows.sort(reverse=True)
sections.append(("Диск по контейнерам (топ по заполнению)", rows and
["| CT | Имя | Заполнено |", "|---|---|---|"] +
["| CT%s | %s | %d%% |" % (ct, name, pct) for pct, ct, name in rows[:12]] or
["нет данных"]))
# 2) возраст образов (сколько старше 180 дней)
old, total = 0, 0
for line in sh("pct list").splitlines()[1:]:
p = line.split()
if len(p) < 2 or p[1] != "running":
continue
ct = p[0]
out = sh("pct exec %s -- sh -c 'docker ps --format \"{{.Image}}\" 2>/dev/null'" % ct, 40)
for img in set(x for x in out.splitlines() if x.strip()):
total += 1
created = sh("pct exec %s -- sh -c 'docker inspect --format \"{{.Created}}\" %s 2>/dev/null'"
% (ct, img), 25)
m = re.match(r"(\d{4}-\d{2}-\d{2})", created)
if m:
try:
age = (datetime.now() - datetime.strptime(m.group(1), "%Y-%m-%d")).days
if age > 180:
old += 1
except Exception:
pass
sections.append(("Возраст образов", [
"| Метрика | Значение |", "|---|---|",
"| Образов (уникальных) | %d |" % total,
"| Старше 180 дней | %d |" % old,
"| Вывод | %s |" % ("есть кандидаты на обновление" if old else "всё свежее"),
]))
# 3) использование по доменам (nginx host + VPS, за текущий лог)
usage = {}
host_log = sh("awk '{print $1}' /var/log/nginx/access.log 2>/dev/null | wc -l", 30)
usage["хост"] = host_log or "0"
vps_log = sh("ssh -o ConnectTimeout=10 -o BatchMode=yes root@%s "
"'awk \"{print \\\\$1}\" /var/log/nginx/access.log 2>/dev/null | wc -l'" % VPS, 40)
usage["VPS"] = vps_log or "0"
sections.append(("Использование (запросов в текущем логе nginx)", [
"| Узел | Запросов |", "|---|---|",
"| хост | %s |" % usage["хост"],
"| VPS | %s |" % usage["VPS"],
]))
# запись
try:
text = open(LEDGER, encoding="utf-8").read()
except Exception:
text = "# Лёджер сервисов (V1, Фаза A)\n"
# удаляем предыдущие доп.разделы
text = text.split("\n## Дополнение:")[0].rstrip() + "\n"
text += "\n## Дополнение: стоимость и использование\n"
text += "\n_Обновлено: %s_\n" % datetime.now().isoformat(timespec="seconds")
for title, lines in sections:
text += "\n### %s\n\n" % title
text += "\n".join(lines) + "\n"
open(LEDGER, "w", encoding="utf-8").write(text)
print("лёджер дополнен:", LEDGER)
for title, lines in sections:
print(" ", title, "—", len(lines), "строк")
if __name__ == "__main__":
main()
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Валидация правил агента (GitOps-гейт): policy.yaml + jobs.yaml + agents.
Запускается в CI перед мержем и локально. Код возврата != 0 = ошибка.
"""
import glob
import os
import sys
ROOT = "/root/buryan-infra"
ERRORS, WARNINGS = [], []
def err(msg):
ERRORS.append(msg)
def warn(msg):
WARNINGS.append(msg)
def load_yaml(path):
import yaml
try:
return yaml.safe_load(open(path, encoding="utf-8"))
except Exception as e:
err("%s: не читается (%s)" % (os.path.basename(path), e))
return None
def check_policy():
p = ROOT + "/ops/hermes/policy.yaml"
if not os.path.exists(p):
err("policy.yaml отсутствует")
return
d = load_yaml(p) or {}
dfl = d.get("defaults") or {}
for k in ("single_flight", "cooldown", "retry", "circuit_breaker", "budget_per_hour", "dry_run"):
if k not in dfl:
err("policy.yaml: нет обязательного defaults.%s" % k)
levels = set((d.get("autonomy") or {}).get("levels") or {})
if not levels:
err("policy.yaml: нет autonomy.levels")
ids = set()
for r in (d.get("rules") or []):
rid = r.get("id")
if not rid:
err("policy.yaml: правило без id")
continue
if rid in ids:
err("policy.yaml: дубль правила %s" % rid)
ids.add(rid)
if not r.get("match"):
err("policy.yaml: правило %s без match" % rid)
if not r.get("action"):
err("policy.yaml: правило %s без action" % rid)
lvl = r.get("level")
if lvl and lvl not in levels:
err("policy.yaml: правило %s ссылается на неизвестный уровень %s" % (rid, lvl))
if not r.get("verify"):
warn("policy.yaml: правило %s без verify" % rid)
def check_jobs():
p = "/opt/hermes/jobs.yaml"
if not os.path.exists(p):
p = ROOT + "/ops/hermes/jobs.yaml"
if not os.path.exists(p):
warn("jobs.yaml не найден — пропуск")
return
d = load_yaml(p) or {}
for name, cfg in d.items():
if not isinstance(cfg, dict):
err("jobs.yaml: %s — не словарь" % name)
continue
if not cfg.get("command"):
err("jobs.yaml: %s без command" % name)
if "every_seconds" not in cfg and "daily_at" not in cfg:
warn("jobs.yaml: %s без расписания" % name)
if "timeout" not in cfg:
warn("jobs.yaml: %s без timeout" % name)
def check_scripts():
for path in glob.glob(ROOT + "/ops/scripts/*.py") + glob.glob(ROOT + "/ops/hermes/*.py"):
try:
compile(open(path, encoding="utf-8").read(), path, "exec")
except SyntaxError as e:
err("%s: синтаксис — %s (строка %s)" % (os.path.basename(path), e.msg, e.lineno))
def check_agents():
# проверяем только файлы специалистов (agent-*.yaml), остальные в ops/agents — не наши
for path in glob.glob(ROOT + "/ops/agents/agent-*.yaml"):
d = load_yaml(path) or {}
for k in ("name", "purpose", "rules"):
if k not in d:
err("%s: нет поля %s" % (os.path.basename(path), k))
def main():
check_policy()
check_jobs()
check_scripts()
check_agents()
print("=== валидация правил агента ===")
if ERRORS:
print("ОШИБКИ (%d):" % len(ERRORS))
for e in ERRORS:
print(" ✗", e)
if WARNINGS:
print("предупреждения (%d):" % len(WARNINGS))
for w in WARNINGS:
print(" !", w)
if not ERRORS:
print("OK: правил %d, ошибок нет" % len(WARNINGS))
return 1 if ERRORS else 0
if __name__ == "__main__":
sys.exit(main())