[SPRINT-V1.1][4] В Matrix только экстренное: гигиена шлёт при high>0, дайджест — при критичных словах; остальное в /var/log/hub/notifications.log

This commit is contained in:
root committed 2026-11-06 11:15:35 +03:00
1 parent 9d7434c36c
commit b670bb35e5
3 files changed
+95 -25

No files matched your search

+20
View File
@@ -11,6 +11,12 @@ from datetime import date
REPORT = "/root/buryan-infra/ops/hygiene/report-%s.md" % date.today().isoformat()
def quiet_hours():
"""Тихие часы: 23:00–07:00 не отправляем ничего, кроме критичного."""
from datetime import datetime
h = datetime.now().hour
return h >= 23 or h < 7
def read_env(path):
out = {}
try:
@@ -25,6 +31,20 @@ def read_env(path):
def main():
# _policy_high: в Matrix только экстренное (high-находки)
try:
import glob as _g, re as _re
_rep = sorted(_g.glob('/root/buryan-infra/ops/hygiene/report-*.md'))[-1]
_txt = open(_rep, encoding='utf-8').read()
_m = _re.search(r'high: (\d+)', _txt)
_high = int(_m.group(1)) if _m else 0
except Exception:
_high = 0
if _high == 0:
print('гигиена: high нет — в Matrix не отправляем (только файл)')
return 0
print('гигиена: high=%d — экстренное' % _high)
try:
text = open(REPORT, encoding="utf-8").read()
except Exception as e:
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Центральная политика уведомлений: в Matrix только экстренное.
Правило:
critical → отправляется всегда (сервис лежит, бэкап не прошёл, CT упал)
normal → только в файл /var/log/hub/notifications.log
info → только в файл
Использование из скриптов:
from notify_policy import send
send("critical", "Jellyfin не отвечает")
send("normal", "Гигиена: найдено 20, high 0")
"""
import json
import os
import urllib.request
from datetime import datetime
LOG = "/var/log/hub/notifications.log"
HUB = "http://127.0.0.1:9120/notify"
def _quiet():
h = datetime.now().hour
return h >= 23 or h < 7
def _log(level, text):
try:
os.makedirs(os.path.dirname(LOG), exist_ok=True)
with open(LOG, "a", encoding="utf-8") as f:
f.write("%s\t%s\t%s\n" % (datetime.now().isoformat(timespec="seconds"), level, text[:500]))
except Exception:
pass
def send(level, text, force=False):
"""level: critical | normal | info. Возвращает True, если ушло в Matrix."""
_log(level, text)
if level != "critical" and not force:
return False
if _quiet() and not force:
_log("deferred", "тихие часы: " + text[:200])
return False
try:
body = json.dumps({"message": text, "source": "hub", "level": level}).encode()
req = urllib.request.Request(HUB, data=body, method="POST")
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=30) as r:
return r.status == 200
except Exception:
return False
if __name__ == "__main__":
import sys
if len(sys.argv) > 2:
ok = send(sys.argv[1], " ".join(sys.argv[2:]))
print("отправлено" if ok else "записано в лог (не экстренное)")