118 lines
3.8 KiB
Python
118 lines
3.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Голова роя: собирает отчёты агентов в одну сводку."""
|
|
import glob
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
|
|
JOURNAL = "/var/lib/hub-agents/journal"
|
|
STATE = "/var/lib/hub-agents/state.json"
|
|
APPROVALS = "/var/lib/hub-agents/approvals.json"
|
|
NOTIFY = "http://127.0.0.1:9120/notify"
|
|
|
|
|
|
def load(path, default):
|
|
try:
|
|
return json.load(open(path, encoding="utf-8"))
|
|
except Exception:
|
|
return default
|
|
|
|
|
|
def status():
|
|
try:
|
|
with urllib.request.urlopen("http://127.0.0.1:9120/status.json",
|
|
timeout=25) as r:
|
|
return json.loads(r.read())
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def work_section():
|
|
import datetime as _dt
|
|
import glob as _g
|
|
path = f"/var/lib/hub-agents/journal/{_dt.date.today().isoformat()}-work.json"
|
|
try:
|
|
d = json.load(open(path, encoding="utf-8"))
|
|
except Exception:
|
|
return None
|
|
loc = d.get("local") or {}
|
|
lines = [f"💼 Работа: клиентов {loc.get('clients', 0)}, "
|
|
f"встреч {loc.get('meetings', 0)}, файлов {loc.get('files', 0)}"]
|
|
for p in (d.get("problems") or [])[:3]:
|
|
lines.append(f"⚠️ {p}")
|
|
return lines
|
|
|
|
|
|
def main():
|
|
today = time.strftime("%Y-%m-%d")
|
|
lines = ["🧠 **Сводка роя**", time.strftime("%d.%m.%Y"), ""]
|
|
|
|
st = status()
|
|
total, up = st.get("total", 0), st.get("up", 0)
|
|
if total:
|
|
pct = round(100 * up / total)
|
|
lines.append(f"Сервисы: **{up}/{total}** ({pct}%)")
|
|
|
|
# последние LLM-отчёты
|
|
latest = {}
|
|
for p in glob.glob(os.path.join(JOURNAL, "*-llm.json")):
|
|
try:
|
|
if time.time() - os.path.getmtime(p) > 6 * 3600:
|
|
continue
|
|
d = json.load(open(p, encoding="utf-8"))
|
|
except Exception:
|
|
continue
|
|
agent = d.get("agent")
|
|
prev = latest.get(agent)
|
|
if not prev or os.path.getmtime(p) > prev[0]:
|
|
latest[agent] = (os.path.getmtime(p), d)
|
|
fresh = [v[1] for v in latest.values()]
|
|
if fresh:
|
|
lines.append("")
|
|
lines.append("**Диагнозы (свежие, до 6 ч):**")
|
|
for d in fresh:
|
|
sev = {"ok": "✅", "warn": "⚠️", "crit": "🔴"}.get(d.get("severity"), "•")
|
|
summary = (d.get("summary") or d.get("diagnosis") or "")[:110]
|
|
lines.append(f"{sev} {d.get('agent')}: {summary}")
|
|
else:
|
|
lines.append("")
|
|
lines.append("Диагнозов за сутки нет — проблем не находили.")
|
|
|
|
# заявки
|
|
pending = [a for a in load(APPROVALS, []) if a.get("status") == "pending"]
|
|
if pending:
|
|
lines.append("")
|
|
lines.append(f"**Ждут подтверждения:** {len(pending)}")
|
|
for a in pending[:5]:
|
|
lines.append(f"• #{a['id']} {a['action']} {a['target']}")
|
|
|
|
work = work_section()
|
|
if work:
|
|
lines.append("")
|
|
lines.extend(work)
|
|
|
|
# состояние агентов
|
|
stt = load(STATE, {})
|
|
if stt.get("last_run"):
|
|
lines.append("")
|
|
lines.append(f"_последний прогон: {stt['last_run']}_")
|
|
|
|
text = "\n".join(lines)
|
|
print(text)
|
|
|
|
body = json.dumps({"title": "Сводка роя", "message": text,
|
|
"priority": "low"}).encode()
|
|
req = urllib.request.Request(NOTIFY, data=body, method="POST",
|
|
headers={"Content-Type": "application/json"})
|
|
try:
|
|
urllib.request.urlopen(req, timeout=20).read()
|
|
print("\nотправлено в очередь дайджеста")
|
|
except Exception as e:
|
|
print("не отправлено:", e)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|