[HUB] Планировщики: единый реестр из 4 источников (146 записей), детектор расхождений registry-drift, исправлены 2 реальных дубля (check_updates, mesh_watch). Бэкапы и системные задачи решено оставить в systemd — они должны работать при падении Hermes
This commit is contained in:
1 parent
6b7c9b0725
commit
73e81c22c1
5 files changed
+421
-557
No files matched your search
Executable
+100
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Единый реестр автоматизаций: cron, cron.d, systemd-таймеры, Hermes.
|
||||
|
||||
Один файл — одна картина. Запуск: build_automations_registry.py
|
||||
"""
|
||||
import datetime
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
OUT = "/root/buryan-infra/ops/automations/registry.yaml"
|
||||
|
||||
|
||||
def sh(cmd, t=25):
|
||||
try:
|
||||
return subprocess.run(cmd, shell=True, capture_output=True, text=True,
|
||||
timeout=t).stdout or ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def main():
|
||||
items = []
|
||||
|
||||
# 1. crontab
|
||||
for line in sh("crontab -l").splitlines():
|
||||
s = line.strip()
|
||||
if s and not s.startswith("#"):
|
||||
items.append({"source": "crontab", "line": s[:200]})
|
||||
|
||||
# 2. cron.d
|
||||
for f in sorted(glob.glob("/etc/cron.d/*")):
|
||||
if ".disabled" in f:
|
||||
continue
|
||||
for line in open(f, encoding="utf-8", errors="ignore"):
|
||||
s = line.strip()
|
||||
if not s or s.startswith(("#", "SHELL", "PATH", "MAILTO")):
|
||||
continue
|
||||
items.append({"source": "cron.d/" + os.path.basename(f), "line": s[:200]})
|
||||
|
||||
# 3. systemd-таймеры
|
||||
timer_re = re.compile(r"[a-zA-Z0-9@_.-]+\.timer")
|
||||
for u in sorted(set(timer_re.findall(sh("systemctl list-timers --all --no-legend")))):
|
||||
sched = sh("systemctl show %s -p TimersCalendar -p TimersMonotonic" % u)
|
||||
m = re.search(r"OnCalendar=([^ ;]+)", sched)
|
||||
if not m:
|
||||
m = re.search(r"OnUnitActiveUSec=([^ ;]+)", sched)
|
||||
act = sh("systemctl show %s -p Unit" % u)
|
||||
am = re.search(r"Unit=(.+)", act)
|
||||
items.append({"source": "systemd", "timer": u,
|
||||
"schedule": m.group(1).strip() if m else "?",
|
||||
"unit": am.group(1).strip() if am else "?"})
|
||||
|
||||
# 4. Hermes
|
||||
try:
|
||||
import yaml
|
||||
d = yaml.safe_load(open("/opt/hermes/jobs.yaml")) or {}
|
||||
for name, job in d.items():
|
||||
j = job or {}
|
||||
if j.get("every_seconds"):
|
||||
sch = "every %ss" % j["every_seconds"]
|
||||
elif j.get("daily_at"):
|
||||
sch = "daily %s" % j["daily_at"]
|
||||
else:
|
||||
sch = "?"
|
||||
items.append({"source": "hermes", "job": name, "schedule": sch,
|
||||
"command": str(j.get("command") or "")[:160]})
|
||||
except Exception as e:
|
||||
print("hermes:", e)
|
||||
|
||||
counts = {}
|
||||
for i in items:
|
||||
src = i["source"].split("/")[0]
|
||||
counts[src] = counts.get(src, 0) + 1
|
||||
|
||||
lines = [
|
||||
"# Реестр автоматизаций Buryans Hub",
|
||||
"# Сгенерировано: %s (ops/scripts/build_automations_registry.py)"
|
||||
% datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
|
||||
"total: %d" % len(items),
|
||||
"by_source:",
|
||||
]
|
||||
for k, v in sorted(counts.items()):
|
||||
lines.append(" %s: %d" % (k, v))
|
||||
lines.append("items:")
|
||||
for i in items:
|
||||
lines.append("- " + json.dumps(i, ensure_ascii=False))
|
||||
os.makedirs(os.path.dirname(OUT), exist_ok=True)
|
||||
open(OUT, "w", encoding="utf-8").write("\n".join(lines) + "\n")
|
||||
|
||||
print("записано:", OUT)
|
||||
print("всего записей:", len(items))
|
||||
for k, v in sorted(counts.items()):
|
||||
print(" %-12s %d" % (k, v))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка расхождений реестра автоматизаций.
|
||||
|
||||
Реестр — это карта того, что запускается. Если он молча устарел, карта врёт.
|
||||
Скрипт пересобирает реестр и сообщает в шину, если он изменился.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
REG = "/root/buryan-infra/ops/automations/registry.yaml"
|
||||
GEN = "/root/buryan-infra/ops/scripts/build_automations_registry.py"
|
||||
|
||||
|
||||
def event(sev, title, body=""):
|
||||
try:
|
||||
p = {"source": "hermes:registry", "type": "drift", "severity": sev,
|
||||
"title": title, "body": (body or "")[:500],
|
||||
"dedup_key": "registry-drift"}
|
||||
req = urllib.request.Request("http://127.0.0.1:9130/event",
|
||||
data=json.dumps(p).encode(), method="POST",
|
||||
headers={"Content-Type": "application/json"})
|
||||
urllib.request.urlopen(req, timeout=8).read()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
old = open(REG, encoding="utf-8").read()
|
||||
except OSError:
|
||||
old = ""
|
||||
subprocess.run([sys.executable, GEN], capture_output=True, timeout=600)
|
||||
try:
|
||||
new = open(REG, encoding="utf-8").read()
|
||||
except OSError:
|
||||
print("реестр не создан")
|
||||
return 1
|
||||
# сравниваем без строки с датой генерации
|
||||
strip = lambda s: "\n".join(l for l in s.splitlines() if not l.startswith("# Сгенерировано"))
|
||||
if strip(old) != strip(new):
|
||||
oldn = len([l for l in strip(old).splitlines() if l.startswith("- ")])
|
||||
newn = len([l for l in strip(new).splitlines() if l.startswith("- ")])
|
||||
event("medium", "Реестр автоматизаций изменился",
|
||||
"было записей: %d, стало: %d" % (oldn, newn))
|
||||
print("изменился: %d → %d" % (oldn, newn))
|
||||
else:
|
||||
print("без изменений")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -42,6 +42,27 @@ def counts_from(path, prefix=r"находок|Найдено"):
|
||||
return {"total": m.group(1), "high": (m2.group(1) if m2 else "?")}
|
||||
|
||||
|
||||
WEEKDAY_ONLY = 0 # 0 = понедельник
|
||||
|
||||
|
||||
def _should_run_today():
|
||||
"""Отчёт недельный: запускается из дневного расписания, но только по понедельникам."""
|
||||
import datetime as _dt
|
||||
return _dt.datetime.now().weekday() == WEEKDAY_ONLY
|
||||
|
||||
|
||||
def _deliver(text, title):
|
||||
"""Единственный канал — секретарь (раньше отчёт шёл своим ботом)."""
|
||||
try:
|
||||
import sys as _s
|
||||
_s.path.insert(0, "/opt/buryan-hub/scripts")
|
||||
import send_content
|
||||
return send_content.send(text, title)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print("доставка не удалась:", str(e)[:120])
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
iso = date.today().isocalendar()
|
||||
@@ -121,4 +142,10 @@ def main():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
import sys as _sys
|
||||
if "--force" not in _sys.argv and not _should_run_today():
|
||||
print("не понедельник — отчёт не формируется")
|
||||
_sys.exit(0)
|
||||
_out = main() if "main" in globals() else None
|
||||
if isinstance(_out, str):
|
||||
_deliver(_out[:3000], "Недельный отчёт")
|
||||
Reference in new issue
Block a user