69 lines
2.5 KiB
Python
Executable File
69 lines
2.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Проверка восстановления ОДНОГО файла из restic (не только check).
|
|
|
|
Берёт последний снапшот pve-config, восстанавливает /etc/pve/storage.cfg
|
|
во временный каталог, проверяет содержимое, удаляет. Раз в неделю.
|
|
"""
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
|
|
ENV = dict(os.environ,
|
|
RESTIC_PASSWORD_FILE="/root/.restic-password",
|
|
RESTIC_REPOSITORY="sftp:root@10.88.0.1:/backup/restic-repo")
|
|
TMP = "/tmp/restic-file-restore"
|
|
TARGET = "/etc/pve/storage.cfg"
|
|
NOTIFY = "/opt/buryan-hub/scripts/notify.py"
|
|
|
|
|
|
def run(cmd, t=300):
|
|
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=t, env=ENV)
|
|
return r.returncode, ((r.stdout or "") + (r.stderr or ""))
|
|
|
|
|
|
def notify(title, text, priority="high"):
|
|
try:
|
|
subprocess.run(["/usr/bin/python3", NOTIFY, "--priority", priority,
|
|
"--title", title, text], capture_output=True,
|
|
text=True, timeout=120, env=ENV)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def main():
|
|
rc, out = run("restic snapshots --json --tag pve-config --latest 1")
|
|
start = out.find("[")
|
|
if rc != 0 or start < 0:
|
|
notify("restic: нет снапшота pve-config", out[-300:])
|
|
return 1
|
|
try:
|
|
snaps = json.loads(out[start:])
|
|
snap = snaps[-1]["short_id"]
|
|
except Exception as e:
|
|
notify("restic: не разобрал снапшоты", str(e)[:200])
|
|
return 1
|
|
|
|
shutil.rmtree(TMP, ignore_errors=True)
|
|
os.makedirs(TMP, exist_ok=True)
|
|
rc, out = run("restic restore %s --target %s --include %s" % (snap, TMP, TARGET))
|
|
path = os.path.join(TMP, TARGET.lstrip("/"))
|
|
if rc == 0 and os.path.isfile(path) and os.path.getsize(path) > 0:
|
|
size = os.path.getsize(path)
|
|
txt = open(path, encoding="utf-8", errors="replace").read()
|
|
looks_ok = (":" in txt)
|
|
notify("restic: восстановление файла ok",
|
|
"Снапшот %s, %s — %d байт" % (snap, TARGET, size),
|
|
"normal" if looks_ok else "high")
|
|
print("ok:", snap, size)
|
|
shutil.rmtree(TMP, ignore_errors=True)
|
|
return 0
|
|
notify("restic: восстановление файла ПРОВАЛЕНО", out[-400:])
|
|
print("fail:", out[-500:])
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|