#!/usr/bin/env python3 """Недельный сводный отчёт: гигиена + развитие + доверие + состояние. Собирает свежие отчёты агентов и формирует единый документ для владельца. Отчёт: ops/weekly/WEEKLY-YYYY-WNN.md """ import glob import json import os import re import subprocess from datetime import date ROOT = "/root/buryan-infra" OUT = ROOT + "/ops/weekly" 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 latest(pattern): files = sorted(glob.glob(pattern)) return files[-1] if files else None def counts_from(path, prefix=r"находок|Найдено"): if not path: return None try: text = open(path, encoding="utf-8").read() except Exception: return None m = re.search(r"(?:находок|Найдено):\s*\*\*(\d+)\*\*", text, re.I) m2 = re.search(r"· high: (\d+) · medium: (\d+) · low: (\d+) · info: (\d+)", text) if not m: return None return {"total": m.group(1), "high": (m2.group(1) if m2 else "?")} def main(): os.makedirs(OUT, exist_ok=True) iso = date.today().isocalendar() path = os.path.join(OUT, "WEEKLY-%d-W%02d.md" % (iso[0], iso[1])) hyg = latest(ROOT + "/ops/hygiene/report-*.md") evo = latest(ROOT + "/ops/evolution/report-*.md") trust = latest(ROOT + "/ops/trust/report-*.md") L = ["# Недельная сводка — %s" % date.today().isoformat(), ""] # состояние L += ["## Состояние", ""] up = sh("pct list | grep -c running") total = sh("pct list | tail -n +2 | wc -l") failed = sh("systemctl --failed --no-legend --no-pager | wc -l") mem = sh("free -h | awk '/^Mem:/{print $3\" / \"$2}'") L += ["| Метрика | Значение |", "|---|---|", "| Контейнеры | %s из %s |" % (up, total), "| Упавших юнитов | %s |" % failed, "| Память | %s |" % mem, "| Uptime | %s |" % sh("uptime -p"), ""] # гигиена L += ["## Гигиена", ""] hc = counts_from(hyg) if hc: L.append("- находок: **%s** (high: %s)" % (hc["total"], hc["high"])) L.append("- отчёт: `%s`" % os.path.basename(hyg)) else: L.append("- отчёт не найден") L.append("") # развитие L += ["## Развитие", ""] if evo: try: text = open(evo, encoding="utf-8").read() m = re.search(r"RETIRE-кандидатов: (\d+)", text) or re.search(r"Сервисов в реестре \| (\d+)", text) L.append("- отчёт: `%s`" % os.path.basename(evo)) row = [ln for ln in text.splitlines() if ln.startswith("| `")] if row: L.append("- кандидаты/сервисы: %d строк" % len(row)) except Exception: L.append("- отчёт не читается") else: L.append("- отчёт не найден") L.append("") # доверие L += ["## Доверие агента", ""] if trust: text = open(trust, encoding="utf-8").read() m = re.search(r"готовы к повышению: \*\*(\d+)\*\*", text) m2 = re.search(r"требуют внимания: \*\*(\d+)\*\*", text) L.append("- готовы к повышению: %s" % (m.group(1) if m else "?")) L.append("- требуют внимания: %s" % (m2.group(1) if m2 else "?")) L.append("- отчёт: `%s`" % os.path.basename(trust)) else: L.append("- отчёт не найден") L.append("") # задачи владельцу L += ["## Задачи владельцу", ""] todo = ROOT + "/ops/OWNER-TODO.md" if os.path.exists(todo): for ln in open(todo, encoding="utf-8").read().splitlines(): if ln.strip().startswith("- [ ]"): L.append(ln.replace("- [ ]", "- ☐")) L.append("") open(path, "w", encoding="utf-8").write("\n".join(L) + "\n") print("отчёт:", path) print("контейнеры: %s/%s | упавших: %s | память: %s" % (up, total, failed, mem)) return 0 if __name__ == "__main__": raise SystemExit(main())