114 lines
3.9 KiB
Python
Executable File
114 lines
3.9 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""Собирает реестр автоматизаций из живых источников.
|
||
|
||
Источники: crontab root, /etc/cron.d/*, systemd-таймеры, задания Hermes.
|
||
Пишет ops/automations/registry.yaml. Ручная правка файла бессмысленна —
|
||
он перезаписывается этим скриптом.
|
||
|
||
python3 build-automations-registry.py
|
||
"""
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
|
||
import yaml
|
||
|
||
REPO = "/root/buryan-infra"
|
||
OUT = os.path.join(REPO, "ops/automations/registry.yaml")
|
||
HERMES_JOBS = "/opt/hermes/jobs.yaml"
|
||
|
||
|
||
def sh(cmd):
|
||
return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout
|
||
|
||
|
||
def crontab_jobs():
|
||
out = []
|
||
for line in sh("crontab -l 2>/dev/null").splitlines():
|
||
line = line.strip()
|
||
if not line or line.startswith("#"):
|
||
continue
|
||
parts = line.split(None, 5)
|
||
if len(parts) < 6:
|
||
continue
|
||
out.append({"schedule": " ".join(parts[:5]), "command": parts[5], "source": "crontab", "user": "root"})
|
||
return out
|
||
|
||
|
||
def cron_d_jobs():
|
||
out = []
|
||
base = "/etc/cron.d"
|
||
if not os.path.isdir(base):
|
||
return out
|
||
for name in sorted(os.listdir(base)):
|
||
p = os.path.join(base, name)
|
||
if not os.path.isfile(p) or "." in name:
|
||
continue
|
||
try:
|
||
text = open(p, encoding="utf-8", errors="ignore").read()
|
||
except Exception:
|
||
continue
|
||
for line in text.splitlines():
|
||
line = line.strip()
|
||
if not line or line.startswith("#") or "=" in line.split(None, 1)[0]:
|
||
continue
|
||
parts = line.split(None, 6)
|
||
if len(parts) < 7:
|
||
continue
|
||
out.append({"schedule": " ".join(parts[:5]), "user": parts[5], "command": parts[6],
|
||
"source": "cron.d/" + name})
|
||
return out
|
||
|
||
|
||
def systemd_timers():
|
||
out = []
|
||
units = sh("systemctl list-unit-files --type=timer --state=enabled --no-legend 2>/dev/null").split()
|
||
for unit in sorted(set(u for u in units if u.endswith(".timer"))):
|
||
props = sh(f"systemctl show {unit} -p OnCalendar -p OnUnitActiveSec -p Unit 2>/dev/null")
|
||
d = dict(l.split("=", 1) for l in props.splitlines() if "=" in l)
|
||
when = d.get("OnCalendar") or d.get("OnUnitActiveSec") or "?"
|
||
out.append({"schedule": when.strip(), "command": d.get("Unit", unit.replace(".timer", ".service")),
|
||
"source": "systemd", "unit": unit})
|
||
return out
|
||
|
||
|
||
def hermes_jobs():
|
||
out = []
|
||
if not os.path.exists(HERMES_JOBS):
|
||
return out
|
||
data = yaml.safe_load(open(HERMES_JOBS, encoding="utf-8")) or {}
|
||
for name, job in data.items():
|
||
if not isinstance(job, dict):
|
||
continue
|
||
sched = job.get("daily_at") or job.get("every_seconds")
|
||
out.append({"name": name,
|
||
"schedule": ("ежедневно %s" % sched) if job.get("daily_at") else ("каждые %s с" % sched),
|
||
"command": job.get("command"), "source": "hermes"})
|
||
return out
|
||
|
||
|
||
def main():
|
||
items = crontab_jobs() + cron_d_jobs() + systemd_timers() + hermes_jobs()
|
||
counts = {}
|
||
for it in items:
|
||
key = it["source"].split("/")[0]
|
||
counts[key] = counts.get(key, 0) + 1
|
||
doc = {
|
||
"generated": subprocess.run(["date", "+%Y-%m-%d"], capture_output=True, text=True).stdout.strip(),
|
||
"generator": "ops/scripts/build-automations-registry.py",
|
||
"total": len(items),
|
||
"by_source": counts,
|
||
"automations": sorted(items, key=lambda x: (x["source"], x.get("schedule", ""))),
|
||
}
|
||
os.makedirs(os.path.dirname(OUT), exist_ok=True)
|
||
with open(OUT, "w", encoding="utf-8") as f:
|
||
yaml.safe_dump(doc, f, allow_unicode=True, sort_keys=False)
|
||
print("записей:", len(items), "| по источникам:", counts)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|