feat(transport): implement slice 6 local-first remote transport sync
This commit is contained in:
1 parent
361640f5ae
commit
e7aa5a54a4
5 files changed
+591
-4
No files matched your search
@@ -28,6 +28,7 @@ from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError
|
||||
from linux_backuper.core.profiles import ProfileManager
|
||||
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
|
||||
from linux_backuper.core.retention import RetentionEngine
|
||||
from linux_backuper.core.transport import TransportFactory, TransportError
|
||||
from linux_backuper.models import SnapshotManifest
|
||||
|
||||
def check_root_permissions() -> bool:
|
||||
@@ -39,6 +40,22 @@ def check_root_permissions() -> bool:
|
||||
except AttributeError:
|
||||
return True
|
||||
|
||||
def resolve_default_ssh_key(explicit_key: Optional[str]) -> Optional[str]:
|
||||
"""Resolve SSH identity key, looking up SUDO_USER if running as root."""
|
||||
if explicit_key and os.path.isfile(explicit_key):
|
||||
return explicit_key
|
||||
sudo_user = os.environ.get("SUDO_USER")
|
||||
if sudo_user:
|
||||
for ck in (
|
||||
f"/home/{sudo_user}/.ssh/id_ed25519",
|
||||
f"/home/{sudo_user}/.ssh/id_rsa",
|
||||
f"/Users/{sudo_user}/.ssh/id_ed25519",
|
||||
f"/Users/{sudo_user}/.ssh/id_rsa",
|
||||
):
|
||||
if os.path.isfile(ck):
|
||||
return ck
|
||||
return explicit_key
|
||||
|
||||
def handle_snapshot(args: argparse.Namespace) -> int:
|
||||
"""Execute snapshot command."""
|
||||
if not check_root_permissions():
|
||||
@@ -174,6 +191,47 @@ def handle_snapshot(args: argparse.Namespace) -> int:
|
||||
if not args.json:
|
||||
sys.stdout.write(f"[INFO] Automatically pruned {auto_pruned_count} old snapshot(s) per retention policy.\n")
|
||||
|
||||
# Remote push if requested (--push <target>)
|
||||
remote_push_result = None
|
||||
remote_push_error = None
|
||||
push_target = getattr(args, "push", None)
|
||||
if push_target:
|
||||
try:
|
||||
config_path = getattr(args, "config", None) or DEFAULT_CONFIG_PATH
|
||||
config_data = None
|
||||
if os.path.isfile(config_path):
|
||||
try:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config_data = json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ssh_key = getattr(args, "ssh_key", None)
|
||||
transport = TransportFactory.get_transport(push_target, config=config_data, ssh_key=ssh_key)
|
||||
if not args.json:
|
||||
sys.stdout.write(f"[INFO] Initiating remote transfer to '{push_target}'...\n")
|
||||
|
||||
remote_push_result = transport.push(archive_path)
|
||||
|
||||
# Remote retention
|
||||
rem_retention = RetentionEngine(
|
||||
keep_last=getattr(args, "remote_keep_last", 0) or 0,
|
||||
keep_daily=getattr(args, "remote_keep_daily", 0) or 0,
|
||||
keep_weekly=getattr(args, "remote_keep_weekly", 0) or 0,
|
||||
keep_monthly=getattr(args, "remote_keep_monthly", 0) or 0
|
||||
)
|
||||
if rem_retention.is_active():
|
||||
prune_res = transport.prune_remote(rem_retention)
|
||||
remote_push_result["remote_pruned"] = prune_res
|
||||
if not args.json:
|
||||
sys.stdout.write(f"[INFO] Pruned {len(prune_res)} remote snapshot(s) per retention policy.\n")
|
||||
|
||||
if not args.json:
|
||||
sys.stdout.write(f"[SUCCESS] Remote push completed: {push_target}\n")
|
||||
except TransportError as e:
|
||||
remote_push_error = str(e)
|
||||
sys.stderr.write(f"[WARNING] Local snapshot succeeded, but remote push to '{push_target}' failed: {e}\n")
|
||||
|
||||
if args.json:
|
||||
output_payload = {
|
||||
"snapshot_id": snapshot_id,
|
||||
@@ -183,6 +241,8 @@ def handle_snapshot(args: argparse.Namespace) -> int:
|
||||
"uncompressed_bytes": uncompressed_bytes,
|
||||
"compressed_bytes": manifest.stats.get("compressed_bytes", 0),
|
||||
"auto_pruned_count": auto_pruned_count,
|
||||
"remote_push": remote_push_result,
|
||||
"remote_push_error": remote_push_error,
|
||||
"status": "success"
|
||||
}
|
||||
print(json.dumps(output_payload, indent=2))
|
||||
@@ -569,6 +629,60 @@ def handle_prune(args: argparse.Namespace) -> int:
|
||||
|
||||
return EXIT_SUCCESS
|
||||
|
||||
def handle_push(args: argparse.Namespace) -> int:
|
||||
"""Execute push command to transfer snapshot to remote destination."""
|
||||
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
|
||||
archive_path = SnapshotArchiver.resolve_archive_path(target_dir, args.snapshot_id)
|
||||
if not os.path.isfile(archive_path):
|
||||
sys.stderr.write(f"[ERROR] Snapshot archive not found: {archive_path}\n")
|
||||
return EXIT_GENERIC_ERROR
|
||||
|
||||
# Load optional config
|
||||
config_path = getattr(args, "config", None) or DEFAULT_CONFIG_PATH
|
||||
config_data = None
|
||||
if os.path.isfile(config_path):
|
||||
try:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
config_data = json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
ssh_key = getattr(args, "ssh_key", None)
|
||||
transport = TransportFactory.get_transport(args.target, config=config_data, ssh_key=ssh_key)
|
||||
if not args.json:
|
||||
sys.stdout.write(f"[INFO] Transferring snapshot to '{args.target}'...\n")
|
||||
|
||||
push_res = transport.push(archive_path)
|
||||
|
||||
# Check if remote retention requested
|
||||
rem_retention = RetentionEngine(
|
||||
keep_last=getattr(args, "remote_keep_last", 0) or 0,
|
||||
keep_daily=getattr(args, "remote_keep_daily", 0) or 0,
|
||||
keep_weekly=getattr(args, "remote_keep_weekly", 0) or 0,
|
||||
keep_monthly=getattr(args, "remote_keep_monthly", 0) or 0
|
||||
)
|
||||
if rem_retention.is_active():
|
||||
if not args.json:
|
||||
sys.stdout.write("[INFO] Applying retention policy to remote destination...\n")
|
||||
prune_res = transport.prune_remote(rem_retention)
|
||||
push_res["remote_pruned"] = prune_res
|
||||
|
||||
except TransportError as e:
|
||||
sys.stderr.write(f"[ERROR] Transport sync failed: {e}\n")
|
||||
return EXIT_GENERIC_ERROR
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(push_res, indent=2))
|
||||
else:
|
||||
mb = push_res.get("bytes_transferred", 0) / (1024 * 1024)
|
||||
sys.stdout.write(f"[SUCCESS] Snapshot pushed successfully to '{args.target}' ({mb:.2f} MB transferred, SHA-256 verified).\n")
|
||||
if "remote_pruned" in push_res:
|
||||
p_count = len(push_res["remote_pruned"])
|
||||
sys.stdout.write(f"[INFO] Pruned {p_count} remote snapshot(s) per remote retention policy.\n")
|
||||
|
||||
return EXIT_SUCCESS
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
"""Construct CLI argument parser."""
|
||||
common_parser = argparse.ArgumentParser(add_help=False)
|
||||
@@ -599,6 +713,12 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
snap_parser.add_argument("--keep-daily", type=int, default=0, help="Prune old backups, keeping latest snapshot for D days")
|
||||
snap_parser.add_argument("--keep-weekly", type=int, default=0, help="Prune old backups, keeping latest snapshot for W weeks")
|
||||
snap_parser.add_argument("--keep-monthly", type=int, default=0, help="Prune old backups, keeping latest snapshot for M months")
|
||||
snap_parser.add_argument("--push", help="Transfer snapshot to remote destination after local creation")
|
||||
snap_parser.add_argument("--ssh-key", help="Private SSH key path for remote authentication")
|
||||
snap_parser.add_argument("--remote-keep-last", type=int, default=0, help="Remote retention: keep N latest snapshots")
|
||||
snap_parser.add_argument("--remote-keep-daily", type=int, default=0, help="Remote retention: keep D daily snapshots")
|
||||
snap_parser.add_argument("--remote-keep-weekly", type=int, default=0, help="Remote retention: keep W weekly snapshots")
|
||||
snap_parser.add_argument("--remote-keep-monthly", type=int, default=0, help="Remote retention: keep M monthly snapshots")
|
||||
|
||||
# List command
|
||||
list_parser = subparsers.add_parser("list", help="List existing local snapshots", parents=[common_parser])
|
||||
@@ -647,6 +767,18 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
prune_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing snapshots")
|
||||
prune_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})")
|
||||
|
||||
# Push command
|
||||
push_parser = subparsers.add_parser("push", help="Push an existing snapshot to remote storage", parents=[common_parser])
|
||||
push_parser.add_argument("snapshot_id", help="Snapshot ID or archive filename to push")
|
||||
push_parser.add_argument("--target", required=True, help="Remote destination (e.g. /mnt/nas or user@host:/path or alias)")
|
||||
push_parser.add_argument("--ssh-key", help="Private SSH key path for authentication")
|
||||
push_parser.add_argument("--remote-keep-last", type=int, default=0, help="Remote retention: keep N latest snapshots")
|
||||
push_parser.add_argument("--remote-keep-daily", type=int, default=0, help="Remote retention: keep D daily snapshots")
|
||||
push_parser.add_argument("--remote-keep-weekly", type=int, default=0, help="Remote retention: keep W weekly snapshots")
|
||||
push_parser.add_argument("--remote-keep-monthly", type=int, default=0, help="Remote retention: keep M monthly snapshots")
|
||||
push_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the local snapshot")
|
||||
push_parser.add_argument("--config", help=f"Path to JSON configuration file (default: {DEFAULT_CONFIG_PATH})")
|
||||
|
||||
# Verify command
|
||||
verify_parser = subparsers.add_parser("verify", help="Verify snapshot cryptographic integrity", parents=[common_parser])
|
||||
verify_parser.add_argument("snapshot_id", help="Snapshot ID or archive filename to verify")
|
||||
@@ -677,6 +809,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
return handle_restore(args)
|
||||
elif args.subcommand == "prune":
|
||||
return handle_prune(args)
|
||||
elif args.subcommand == "push":
|
||||
return handle_push(args)
|
||||
elif args.subcommand == "verify":
|
||||
return handle_verify(args)
|
||||
|
||||
|
||||
Reference in new issue
Block a user