110 lines
4.1 KiB
Python
Executable File
110 lines
4.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Ночной отчёт по связи: собирает все три монитора и останавливает их.
|
|
|
|
Запускается утром (Hermes, 08:00): пишет отчёт и выключает сбор,
|
|
чтобы не копилось «на сутки».
|
|
"""
|
|
import glob
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import time
|
|
|
|
OUT = "/root/buryan-infra/ops/audits"
|
|
|
|
|
|
def load(path):
|
|
rows = []
|
|
try:
|
|
for line in open(path, encoding="utf-8", errors="replace"):
|
|
try:
|
|
rows.append(json.loads(line))
|
|
except Exception:
|
|
pass
|
|
except FileNotFoundError:
|
|
pass
|
|
return rows
|
|
|
|
|
|
def today(path_glob):
|
|
day = time.strftime("%Y-%m-%d")
|
|
for f in glob.glob(path_glob):
|
|
if day in f:
|
|
return f
|
|
return None
|
|
|
|
|
|
def main():
|
|
os.makedirs(OUT, exist_ok=True)
|
|
day = time.strftime("%Y-%m-%d")
|
|
lines = ["# Ночь: связь до VDS (%s)" % day, ""]
|
|
|
|
# 1. net-monitor
|
|
f = today("/var/lib/net-monitor/*.jsonl")
|
|
net = load(f) if f else []
|
|
if net:
|
|
gw_bad = [r for r in net if r.get("gw", {}).get("loss", 0) > 0]
|
|
tcp_bad = [r for r in net if not r.get("vps_tcp", {}).get("ok")]
|
|
tls_rows = [r for r in net if r.get("vps_tls")]
|
|
tls_bad = [r for r in tls_rows if not r["vps_tls"]["ok"]]
|
|
lines += ["## Общий канал", "",
|
|
"| Проверка | Сбоев | Из |", "|---|---|---|",
|
|
"| Шлюз | %d | %d |" % (len(gw_bad), len(net)),
|
|
"| TCP до VDS | %d | %d |" % (len(tcp_bad), len(net)),
|
|
"| TLS до VDS | %d | %d |" % (len(tls_bad), len(tls_rows)), ""]
|
|
for r in tls_bad[-10:]:
|
|
lines.append("- %s TLS таймаут" % r["ts"][11:])
|
|
|
|
# 2. path-monitor
|
|
f = today("/var/lib/path-monitor/*.jsonl")
|
|
path = load(f) if f else []
|
|
if path:
|
|
bad = []
|
|
for r in path:
|
|
fails = [p for p, v in (r.get("vds") or {}).items() if not v.get("ok")]
|
|
tun = r.get("tunnel") or {}
|
|
if fails or (tun and not tun.get("ok")):
|
|
bad.append((r["ts"], fails, tun.get("ok")))
|
|
lines += ["## Путь", "", "Замеров: **%d**, сбоев: **%d**" % (len(path), len(bad)), ""]
|
|
for ts, fails, tun in bad[-10:]:
|
|
lines.append("- %s порты=%s туннель=%s" % (ts[11:], fails or "ok", tun))
|
|
|
|
# 3. router-monitor
|
|
f = today("/var/lib/router-monitor/*.jsonl")
|
|
wifi = load(f) if f else []
|
|
if wifi:
|
|
n = len(wifi)
|
|
last = wifi[-1]
|
|
lines += ["## Wi-Fi", "",
|
|
"Замеров: **%d**. Последний: канал 2.4 = %s, клиентов = %d."
|
|
% (n, (last.get("wifi24") or {}).get("channel"),
|
|
len(last.get("clients") or [])), ""]
|
|
for c in (last.get("clients") or []):
|
|
lines.append("- %s %s ГГц tx=%s RSSI=%s" % (c.get("mac"), c.get("band"),
|
|
c.get("tx"), c.get("rssi")))
|
|
|
|
path_out = os.path.join(OUT, "night-%s.md" % day)
|
|
open(path_out, "w", encoding="utf-8").write("\n".join(lines) + "\n")
|
|
print("отчёт:", path_out)
|
|
|
|
# 4. останавливаем сбор (ночь закончилась)
|
|
for svc in ("path-monitor", "net-monitor", "router-monitor"):
|
|
subprocess.run("systemctl stop %s" % svc, shell=True, timeout=60)
|
|
print(" остановлен:", svc)
|
|
|
|
# 5. уведомление
|
|
try:
|
|
import urllib.request as u
|
|
msg = "🌙 Ночной отчёт по связи готов: %s\nМониторы остановлены." % path_out
|
|
body = json.dumps({"title": "Ночь: связь", "message": msg, "priority": "normal"}).encode()
|
|
req = u.Request("http://127.0.0.1:9120/notify", data=body,
|
|
headers={"Content-Type": "application/json"})
|
|
u.urlopen(req, timeout=10).read()
|
|
except Exception:
|
|
pass
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|