#!/usr/bin/env python3 """Бэкап конфигураций: собирает bind-монтирования контейнеров (без данных).""" import os import subprocess import tarfile import time DEST = "/mnt/backups/configs" SKIP = ("/mnt/media", "/data", "/music", "/photos", "/downloads", "/library", "/calibre-library", "/cwa-book-ingest") MAX_FILE = 20 * 1024 * 1024 def sh(cmd, timeout=60): r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout) return (r.stdout or "").strip() def containers(): out = [] for line in sh("pct list | tail -n +2").splitlines(): parts = line.split() if len(parts) < 3: continue ct = parts[0] names = sh(f"pct exec {ct} -- docker ps --format '{{{{.Names}}}}'").split() for n in names: out.append((ct, n)) for n in sh("docker ps --format '{{.Names}}'").split(): out.append(("0", n)) return out def mounts(ct, name): if ct == "0": cmd = f"docker inspect {name} --format '{{{{json .Mounts}}}}'" else: cmd = f"pct exec {ct} -- docker inspect {name} --format '{{{{json .Mounts}}}}'" raw = sh(cmd) import json try: return json.loads(raw or "[]") except Exception: return [] def add_dir(tar, src, arc): if not os.path.isdir(src): return 0 if any(src.startswith(p) for p in SKIP): return 0 n = 0 for root, dirs, files in os.walk(src): dirs[:] = [d for d in dirs if not d.startswith(".")][:20] for f in files[:200]: p = os.path.join(root, f) try: if os.path.getsize(p) > MAX_FILE: continue rel = os.path.relpath(p, src) tar.add(p, arcname=os.path.join(arc, rel)) n += 1 except Exception: continue if n > 800: break return n def main(): os.makedirs(DEST, exist_ok=True) stamp = time.strftime("%Y%m%d-%H%M") path = os.path.join(DEST, f"configs-{stamp}.tar.gz") total, count = 0, 0 import glob with tarfile.open(path, "w:gz") as tar: seen = set() for ct, name in containers(): for m in mounts(ct, name): src = m.get("Source") or "" if not src.startswith("/opt") or src in seen: continue seen.add(src) n = add_dir(tar, src, os.path.join(name, src.strip("/").replace("/", "_"))) if n: count += 1 total += n # конфиги CT-сервисов лежат на хосте в /opt/<...>/<сервис>/config for src in (glob.glob("/opt/*/config") + glob.glob("/opt/*/*/config") + glob.glob("/opt/*/conf") + glob.glob("/opt/*/*/conf")): if src in seen or not os.path.isdir(src): continue seen.add(src) n = add_dir(tar, src, src.strip("/").replace("/", "_")) if n: count += 1 total += n size = os.path.getsize(path) # ротация for f in sorted(os.listdir(DEST)): full = os.path.join(DEST, f) if f.startswith("configs-") and os.path.getmtime(full) < time.time() - 30 * 86400: os.remove(full) print(f"{time.strftime('%Y-%m-%dT%H:%M:%S')} configs: dirs={count} files={total} " f"size={size} -> {path}") if __name__ == "__main__": main()