Files
buryan-infra/ops/scripts/build_automations_registry.py
T

101 lines
3.3 KiB
Python
Executable File

#!/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()