#!/usr/bin/env python3 """Резервное копирование Docker volumes через временный контейнер.""" from __future__ import annotations import argparse import hashlib import json import re import shutil import subprocess import sys import time from pathlib import Path VOLUME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$") def file_digest(path: Path, chunk_size: int = 1024 * 1024) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while block := handle.read(chunk_size): digest.update(block) return digest.hexdigest() def run(command: list[str], check: bool = True) -> subprocess.CompletedProcess: result = subprocess.run(command, capture_output=True, text=True, check=False) if check and result.returncode != 0: message = result.stderr.strip() or result.stdout.strip() raise RuntimeError(message) return result def main() -> int: parser = argparse.ArgumentParser(description="Копия Docker volumes") parser.add_argument("--dest", type=Path, required=True) parser.add_argument("--volume", action="append", default=[], help="Имя volume, можно повторять") parser.add_argument("--image", default="alpine:3.20", help="Образ с tar") parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() if not shutil.which("docker"): print("docker не найден. Установите Docker.", file=sys.stderr) return 3 dest = args.dest.expanduser().resolve() if not args.dry_run: dest.mkdir(parents=True, exist_ok=True) if args.volume: volumes = args.volume else: result = run(["docker", "volume", "ls", "--format", "{{.Name}}"]) volumes = [line.strip() for line in result.stdout.splitlines() if line.strip()] if not volumes: print("Volumes не найдены.") return 0 stamp = time.strftime("%Y%m%d-%H%M%S") manifest = [] failed = 0 for volume in volumes: if not VOLUME_RE.fullmatch(volume): print(f"Пропуск: недопустимое имя volume {volume}", file=sys.stderr) failed += 1 continue inspect = run(["docker", "volume", "inspect", volume], check=False) if inspect.returncode != 0: print(f"Пропуск: volume {volume} не найден", file=sys.stderr) failed += 1 continue target = dest / f"{volume}-{stamp}.tar.gz" if target.exists(): print(f"Пропуск: файл уже существует {target}", file=sys.stderr) continue command = [ "docker", "run", "--rm", "-v", f"{volume}:/source:ro", "-v", f"{dest}:/backup", args.image, "tar", "-czf", f"/backup/{target.name}", "-C", "/source", ".", ] if args.dry_run: print("Будет выполнено: " + " ".join(command)) continue result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode != 0: target.unlink(missing_ok=True) message = result.stderr.strip() or result.stdout.strip() print(f"Ошибка volume {volume}: {message}", file=sys.stderr) failed += 1 continue manifest.append( { "volume": volume, "target": str(target), "size": target.stat().st_size, "sha256": file_digest(target), } ) print(f"Сохранён: {target}") if args.dry_run: print("Предпросмотр. Для запуска уберите --dry-run.") return 0 manifest_path = dest / f"docker-volumes-{stamp}.json" manifest_path.write_text( json.dumps({"volumes": manifest}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Manifest: {manifest_path}") print(f"Volumes: {len(volumes)}, успешно: {len(manifest)}, ошибок: {failed}") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())