122 lines
4.0 KiB
Python
Executable File
122 lines
4.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Валидация правил агента (GitOps-гейт): policy.yaml + jobs.yaml + agents.
|
|
|
|
Запускается в CI перед мержем и локально. Код возврата != 0 = ошибка.
|
|
"""
|
|
import glob
|
|
import os
|
|
import sys
|
|
|
|
ROOT = "/root/buryan-infra"
|
|
ERRORS, WARNINGS = [], []
|
|
|
|
|
|
def err(msg):
|
|
ERRORS.append(msg)
|
|
|
|
|
|
def warn(msg):
|
|
WARNINGS.append(msg)
|
|
|
|
|
|
def load_yaml(path):
|
|
import yaml
|
|
try:
|
|
return yaml.safe_load(open(path, encoding="utf-8"))
|
|
except Exception as e:
|
|
err("%s: не читается (%s)" % (os.path.basename(path), e))
|
|
return None
|
|
|
|
|
|
def check_policy():
|
|
p = ROOT + "/ops/hermes/policy.yaml"
|
|
if not os.path.exists(p):
|
|
err("policy.yaml отсутствует")
|
|
return
|
|
d = load_yaml(p) or {}
|
|
dfl = d.get("defaults") or {}
|
|
for k in ("single_flight", "cooldown", "retry", "circuit_breaker", "budget_per_hour", "dry_run"):
|
|
if k not in dfl:
|
|
err("policy.yaml: нет обязательного defaults.%s" % k)
|
|
levels = set((d.get("autonomy") or {}).get("levels") or {})
|
|
if not levels:
|
|
err("policy.yaml: нет autonomy.levels")
|
|
ids = set()
|
|
for r in (d.get("rules") or []):
|
|
rid = r.get("id")
|
|
if not rid:
|
|
err("policy.yaml: правило без id")
|
|
continue
|
|
if rid in ids:
|
|
err("policy.yaml: дубль правила %s" % rid)
|
|
ids.add(rid)
|
|
if not r.get("match"):
|
|
err("policy.yaml: правило %s без match" % rid)
|
|
if not r.get("action"):
|
|
err("policy.yaml: правило %s без action" % rid)
|
|
lvl = r.get("level")
|
|
if lvl and lvl not in levels:
|
|
err("policy.yaml: правило %s ссылается на неизвестный уровень %s" % (rid, lvl))
|
|
if not r.get("verify"):
|
|
warn("policy.yaml: правило %s без verify" % rid)
|
|
|
|
|
|
def check_jobs():
|
|
p = "/opt/hermes/jobs.yaml"
|
|
if not os.path.exists(p):
|
|
p = ROOT + "/ops/hermes/jobs.yaml"
|
|
if not os.path.exists(p):
|
|
warn("jobs.yaml не найден — пропуск")
|
|
return
|
|
d = load_yaml(p) or {}
|
|
for name, cfg in d.items():
|
|
if not isinstance(cfg, dict):
|
|
err("jobs.yaml: %s — не словарь" % name)
|
|
continue
|
|
if not cfg.get("command"):
|
|
err("jobs.yaml: %s без command" % name)
|
|
if "every_seconds" not in cfg and "daily_at" not in cfg:
|
|
warn("jobs.yaml: %s без расписания" % name)
|
|
if "timeout" not in cfg:
|
|
warn("jobs.yaml: %s без timeout" % name)
|
|
|
|
|
|
def check_scripts():
|
|
for path in glob.glob(ROOT + "/ops/scripts/*.py") + glob.glob(ROOT + "/ops/hermes/*.py"):
|
|
try:
|
|
compile(open(path, encoding="utf-8").read(), path, "exec")
|
|
except SyntaxError as e:
|
|
err("%s: синтаксис — %s (строка %s)" % (os.path.basename(path), e.msg, e.lineno))
|
|
|
|
|
|
def check_agents():
|
|
# проверяем только файлы специалистов (agent-*.yaml), остальные в ops/agents — не наши
|
|
for path in glob.glob(ROOT + "/ops/agents/agent-*.yaml"):
|
|
d = load_yaml(path) or {}
|
|
for k in ("name", "purpose", "rules"):
|
|
if k not in d:
|
|
err("%s: нет поля %s" % (os.path.basename(path), k))
|
|
|
|
|
|
def main():
|
|
check_policy()
|
|
check_jobs()
|
|
check_scripts()
|
|
check_agents()
|
|
print("=== валидация правил агента ===")
|
|
if ERRORS:
|
|
print("ОШИБКИ (%d):" % len(ERRORS))
|
|
for e in ERRORS:
|
|
print(" ✗", e)
|
|
if WARNINGS:
|
|
print("предупреждения (%d):" % len(WARNINGS))
|
|
for w in WARNINGS:
|
|
print(" !", w)
|
|
if not ERRORS:
|
|
print("OK: правил %d, ошибок нет" % len(WARNINGS))
|
|
return 1 if ERRORS else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|