"""Проверка бэкапа PostgreSQL: что реально лежит внутри дампа. Считает строки в COPY-блоках критичных таблиц и сравнивает с живой базой. """ import gzip import re import subprocess import sys DUMP = sys.argv[1] if len(sys.argv) > 1 else None # (база, таблица) — что считаем критичным TARGETS = [ ("authentik_db", "authentik_core_user"), ("authentik_db", "authentik_core_application"), ("matrix_db", "users"), ("matrix_db", "events"), ("immich_db", "asset"), ("paperless_db", "documents_document"), ("gitea_db", "repository"), ("hub_core", "entities"), ] def count_in_dump(path): """Считает строки в COPY-блоках нужных таблиц.""" want = {(db, tbl) for db, tbl in TARGETS} found = {} db = None cur = None n = 0 with gzip.open(path, "rt", encoding="utf-8", errors="replace") as f: for line in f: if line.startswith("\\connect"): db = line.split()[1] if len(line.split()) > 1 else None continue if cur is None: m = re.match(r"^COPY public\.(\w+) ", line) if m and db and (db, m.group(1)) in want: cur = (db, m.group(1)) n = 0 else: if line.startswith("\\."): found[cur] = n cur = None else: n += 1 return found def live_counts(): out = {} for db, tbl in TARGETS: sql = f"select count(*) from {tbl};" p = subprocess.run(["pct", "exec", "151", "--", "bash", "-c", f"su - postgres -c \"psql -d {db} -tAc '{sql}'\""], capture_output=True, text=True, timeout=60) val = (p.stdout or "").strip() out[(db, tbl)] = int(val) if val.isdigit() else None return out def main(): if not DUMP: print("укажите путь к дампу") return 2 print(f"дамп: {DUMP}") in_dump = count_in_dump(DUMP) live = live_counts() print(f"{'база.таблица':45} {'в дампе':>9} {'в живой':>9} статус") bad = 0 for key in TARGETS: d = in_dump.get(key) l = live.get(key) if d is None: if key[0] == "hub_core": status = "базы ещё не было в дампе (создана позже)" else: status = "нет в дампе" bad += 1 elif l is None: status = "нет живой таблицы" elif d == 0 and (l is None or l == 0): status = "пусто (норма)" elif d == 0: status = "пусто, а в живой данные есть" bad += 1 elif l and d < l * 0.5: status = "подозрительно мало" bad += 1 else: status = "ок" name = f"{key[0]}.{key[1]}" print(f"{name:45} {str(d):>9} {str(l):>9} {status}") print(f"\nпроблемных: {bad}") return 0 if bad == 0 else 1 if __name__ == "__main__": sys.exit(main())