#!/usr/bin/env python3 """Очередь заявок класса C: агент предлагает — владелец одобряет. Использование: approvals.py list — показать ожидающие approvals.py approve — выполнить (только из actions_allowed) approvals.py reject — отклонить """ import json import os import subprocess import sys from datetime import datetime QUEUE = "/var/lib/hub-agents/approvals.json" JOURNAL = "/var/lib/hub-agents/journal" ALLOWED = {"restart_container"} def load(): try: return json.load(open(QUEUE, encoding="utf-8")) except Exception: return [] def save(items): os.makedirs(os.path.dirname(QUEUE), exist_ok=True) json.dump(items, open(QUEUE, "w", encoding="utf-8"), ensure_ascii=False, indent=1) def next_id(items): return (max([i.get("id", 0) for i in items] or [0]) + 1) def add(proposals, agent): """Добавляет предложения агента в очередь (без дублей).""" items = load() added = [] for p in proposals: if (p.get("class") or "").upper() != "C": continue action = p.get("action") target = p.get("target") if not action or not target: continue dup = [i for i in items if i.get("action") == action and i.get("target") == target and i.get("status") == "pending"] if dup: continue item = { "id": next_id(items), "agent": agent, "action": action, "target": target, "why": p.get("why", ""), "status": "pending", "created": datetime.now().isoformat(timespec="seconds"), } items.append(item) added.append(item) save(items) return added def find(items, ident): for i in items: if str(i.get("id")) == str(ident): return i return None def log(entry): os.makedirs(JOURNAL, exist_ok=True) path = os.path.join(JOURNAL, datetime.now().strftime("%Y-%m-%d") + "-approvals.jsonl") with open(path, "a", encoding="utf-8") as f: f.write(json.dumps(entry, ensure_ascii=False) + "\n") def execute(item): action, target = item.get("action"), item.get("target") if action not in ALLOWED: return False, f"действие {action} не разрешено к исполнению" # ищем контейнер: сначала на хосте, потом по CT try: r = subprocess.run(["docker", "restart", target], capture_output=True, text=True, timeout=90) if r.returncode == 0: return True, "перезапущен на хосте" except Exception: pass try: cts = subprocess.run(["pct", "list"], capture_output=True, text=True, timeout=20).stdout for line in cts.splitlines()[1:]: parts = line.split() if len(parts) < 3: continue ct = parts[0] names = subprocess.run(["pct", "exec", ct, "--", "docker", "ps", "--format", "{{.Names}}"], capture_output=True, text=True, timeout=15).stdout if target in names.split(): r = subprocess.run(["pct", "exec", ct, "--", "docker", "restart", target], capture_output=True, text=True, timeout=120) return (r.returncode == 0), f"перезапущен в CT{ct}" except Exception as e: return False, str(e)[:120] return False, "контейнер не найден" def cmd_list(): items = [i for i in load() if i.get("status") == "pending"] if not items: print("заявок нет") return for i in items: print(f"#{i['id']} [{i['agent']}] {i['action']} {i['target']} — {i.get('why', '')[:90]}") def cmd_approve(ident): items = load() item = find(items, ident) if not item or item.get("status") != "pending": print("заявка не найдена или уже обработана") return ok, detail = execute(item) item["status"] = "done" if ok else "failed" item["result"] = detail item["decided"] = datetime.now().isoformat(timespec="seconds") save(items) log(item) print(("✅ " if ok else "❌ ") + f"#{item['id']} {item['action']} {item['target']}: {detail}") def cmd_reject(ident): items = load() item = find(items, ident) if not item or item.get("status") != "pending": print("заявка не найдена") return item["status"] = "rejected" item["decided"] = datetime.now().isoformat(timespec="seconds") save(items) log(item) print(f"отклонено #{item['id']}") if __name__ == "__main__": if len(sys.argv) < 2: cmd_list() elif sys.argv[1] == "list": cmd_list() elif sys.argv[1] == "approve" and len(sys.argv) > 2: cmd_approve(sys.argv[2]) elif sys.argv[1] == "reject" and len(sys.argv) > 2: cmd_reject(sys.argv[2]) else: print(__doc__)