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
@@ -11,7 +11,7 @@
|
|||||||
- [x] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest
|
- [x] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest
|
||||||
- [x] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot)
|
- [x] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot)
|
||||||
- [x] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
|
- [x] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
|
||||||
- [ ] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention)
|
- [x] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention)
|
||||||
- [ ] Slice 7 — native packaging (.deb, .rpm, .tar.gz via pure Python builder)
|
- [ ] Slice 7 — native packaging (.deb, .rpm, .tar.gz via pure Python builder)
|
||||||
- [ ] Slice 8 — full documentation (user, admin & developer guides), man page (Section 8), CLI -h/--help, shell tab completion (Bash/Zsh) & Gitea Actions CI/CD release workflow
|
- [ ] Slice 8 — full documentation (user, admin & developer guides), man page (Section 8), CLI -h/--help, shell tab completion (Bash/Zsh) & Gitea Actions CI/CD release workflow
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError
|
|||||||
from linux_backuper.core.profiles import ProfileManager
|
from linux_backuper.core.profiles import ProfileManager
|
||||||
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
|
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
|
||||||
from linux_backuper.core.retention import RetentionEngine
|
from linux_backuper.core.retention import RetentionEngine
|
||||||
|
from linux_backuper.core.transport import TransportFactory, TransportError
|
||||||
from linux_backuper.models import SnapshotManifest
|
from linux_backuper.models import SnapshotManifest
|
||||||
|
|
||||||
def check_root_permissions() -> bool:
|
def check_root_permissions() -> bool:
|
||||||
@@ -39,6 +40,22 @@ def check_root_permissions() -> bool:
|
|||||||
except AttributeError:
|
except AttributeError:
|
||||||
return True
|
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:
|
def handle_snapshot(args: argparse.Namespace) -> int:
|
||||||
"""Execute snapshot command."""
|
"""Execute snapshot command."""
|
||||||
if not check_root_permissions():
|
if not check_root_permissions():
|
||||||
@@ -174,6 +191,47 @@ def handle_snapshot(args: argparse.Namespace) -> int:
|
|||||||
if not args.json:
|
if not args.json:
|
||||||
sys.stdout.write(f"[INFO] Automatically pruned {auto_pruned_count} old snapshot(s) per retention policy.\n")
|
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:
|
if args.json:
|
||||||
output_payload = {
|
output_payload = {
|
||||||
"snapshot_id": snapshot_id,
|
"snapshot_id": snapshot_id,
|
||||||
@@ -183,6 +241,8 @@ def handle_snapshot(args: argparse.Namespace) -> int:
|
|||||||
"uncompressed_bytes": uncompressed_bytes,
|
"uncompressed_bytes": uncompressed_bytes,
|
||||||
"compressed_bytes": manifest.stats.get("compressed_bytes", 0),
|
"compressed_bytes": manifest.stats.get("compressed_bytes", 0),
|
||||||
"auto_pruned_count": auto_pruned_count,
|
"auto_pruned_count": auto_pruned_count,
|
||||||
|
"remote_push": remote_push_result,
|
||||||
|
"remote_push_error": remote_push_error,
|
||||||
"status": "success"
|
"status": "success"
|
||||||
}
|
}
|
||||||
print(json.dumps(output_payload, indent=2))
|
print(json.dumps(output_payload, indent=2))
|
||||||
@@ -569,6 +629,60 @@ def handle_prune(args: argparse.Namespace) -> int:
|
|||||||
|
|
||||||
return EXIT_SUCCESS
|
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:
|
def build_parser() -> argparse.ArgumentParser:
|
||||||
"""Construct CLI argument parser."""
|
"""Construct CLI argument parser."""
|
||||||
common_parser = argparse.ArgumentParser(add_help=False)
|
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-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-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("--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 command
|
||||||
list_parser = subparsers.add_parser("list", help="List existing local snapshots", parents=[common_parser])
|
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("--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})")
|
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 command
|
||||||
verify_parser = subparsers.add_parser("verify", help="Verify snapshot cryptographic integrity", parents=[common_parser])
|
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")
|
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)
|
return handle_restore(args)
|
||||||
elif args.subcommand == "prune":
|
elif args.subcommand == "prune":
|
||||||
return handle_prune(args)
|
return handle_prune(args)
|
||||||
|
elif args.subcommand == "push":
|
||||||
|
return handle_push(args)
|
||||||
elif args.subcommand == "verify":
|
elif args.subcommand == "verify":
|
||||||
return handle_verify(args)
|
return handle_verify(args)
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ class LockAcquisitionError(RuntimeError):
|
|||||||
class SingleInstanceLock:
|
class SingleInstanceLock:
|
||||||
"""Ensures single-process execution using kernel-level file locks."""
|
"""Ensures single-process execution using kernel-level file locks."""
|
||||||
|
|
||||||
def __init__(self, pid_path: str = DEFAULT_PID_PATH):
|
def __init__(self, pid_path: Optional[str] = None):
|
||||||
self.pid_path = pid_path
|
self.pid_path = pid_path or DEFAULT_PID_PATH
|
||||||
self._fd: Optional[int] = None
|
self._fd: Optional[int] = None
|
||||||
|
|
||||||
def acquire(self) -> bool:
|
def acquire(self) -> bool:
|
||||||
@@ -29,7 +29,7 @@ class SingleInstanceLock:
|
|||||||
try:
|
try:
|
||||||
self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600)
|
self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600)
|
||||||
except PermissionError:
|
except PermissionError:
|
||||||
if os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT") == "1":
|
if os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT") == "1" or (hasattr(os, "geteuid") and os.geteuid() != 0):
|
||||||
import tempfile
|
import tempfile
|
||||||
self.pid_path = os.path.join(tempfile.gettempdir(), f"linux-backuper-{os.getpid()}.pid")
|
self.pid_path = os.path.join(tempfile.gettempdir(), f"linux-backuper-{os.getpid()}.pid")
|
||||||
self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600)
|
self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600)
|
||||||
|
|||||||
@@ -0,0 +1,292 @@
|
|||||||
|
"""Remote transport engine supporting local directory/NFS/SMB mounts and SSH/SCP/rsync."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tarfile
|
||||||
|
from typing import Dict, List, Optional, Tuple, Any
|
||||||
|
|
||||||
|
from linux_backuper.core.archiver import calculate_file_sha256, SnapshotArchiver, BUFFER_SIZE
|
||||||
|
from linux_backuper.core.retention import RetentionEngine, parse_snapshot_datetime
|
||||||
|
from linux_backuper.models import SnapshotManifest
|
||||||
|
|
||||||
|
class TransportError(Exception):
|
||||||
|
"""Raised when transport operation fails."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
class BaseTransport:
|
||||||
|
"""Base interface for snapshot transport backends."""
|
||||||
|
|
||||||
|
def push(self, local_archive_path: str) -> Dict[str, Any]:
|
||||||
|
"""Transfer archive to destination. Returns result metadata."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def list_remote(self) -> List[SnapshotManifest]:
|
||||||
|
"""List snapshots available at destination."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def prune_remote(self, retention: RetentionEngine) -> List[Dict[str, Any]]:
|
||||||
|
"""Apply retention policy to remote destination."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
class LocalPathTransport(BaseTransport):
|
||||||
|
"""Transport backend for local directories and mounted NFS/SMB shares."""
|
||||||
|
|
||||||
|
def __init__(self, target_dir: str):
|
||||||
|
self.target_dir = os.path.abspath(target_dir)
|
||||||
|
|
||||||
|
def push(self, local_archive_path: str) -> Dict[str, Any]:
|
||||||
|
if not os.path.isfile(local_archive_path):
|
||||||
|
raise TransportError(f"Source archive does not exist: {local_archive_path}")
|
||||||
|
|
||||||
|
os.makedirs(self.target_dir, exist_ok=True)
|
||||||
|
filename = os.path.basename(local_archive_path)
|
||||||
|
dest_final = os.path.join(self.target_dir, filename)
|
||||||
|
dest_tmp = f"{dest_final}.tmp.{os.getpid()}"
|
||||||
|
|
||||||
|
source_sha = calculate_file_sha256(local_archive_path)
|
||||||
|
source_size = os.path.getsize(local_archive_path)
|
||||||
|
|
||||||
|
# Atomic copy: copy to .tmp, verify sha256, then replace
|
||||||
|
try:
|
||||||
|
with open(local_archive_path, "rb") as f_in, open(dest_tmp, "wb") as f_out:
|
||||||
|
while chunk := f_in.read(BUFFER_SIZE):
|
||||||
|
f_out.write(chunk)
|
||||||
|
|
||||||
|
# Strict 0600 permissions
|
||||||
|
try:
|
||||||
|
os.chmod(dest_tmp, 0o600)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
dest_sha = calculate_file_sha256(dest_tmp)
|
||||||
|
if dest_sha != source_sha:
|
||||||
|
raise TransportError(f"Checksum mismatch after copying to {dest_tmp}: {dest_sha} != {source_sha}")
|
||||||
|
|
||||||
|
os.replace(dest_tmp, dest_final)
|
||||||
|
finally:
|
||||||
|
if os.path.exists(dest_tmp):
|
||||||
|
try:
|
||||||
|
os.unlink(dest_tmp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return {
|
||||||
|
"status": "success",
|
||||||
|
"transport": "local_mount",
|
||||||
|
"source_path": local_archive_path,
|
||||||
|
"destination_path": dest_final,
|
||||||
|
"bytes_transferred": source_size,
|
||||||
|
"sha256": source_sha
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_remote(self) -> List[SnapshotManifest]:
|
||||||
|
archiver = SnapshotArchiver(target_dir=self.target_dir)
|
||||||
|
return archiver.list_snapshots()
|
||||||
|
|
||||||
|
def prune_remote(self, retention: RetentionEngine) -> List[Dict[str, Any]]:
|
||||||
|
snaps = self.list_remote()
|
||||||
|
_, to_prune = retention.calculate_prune_set(snaps)
|
||||||
|
return retention.execute_prune(to_prune, target_dir=self.target_dir, dry_run=False)
|
||||||
|
|
||||||
|
class SshTransport(BaseTransport):
|
||||||
|
"""Transport backend for remote servers via SSH/SCP/rsync."""
|
||||||
|
|
||||||
|
def __init__(self, target_spec: str, ssh_key: Optional[str] = None, port: int = 22):
|
||||||
|
self.raw_spec = target_spec
|
||||||
|
self.ssh_key = ssh_key
|
||||||
|
self.port = port
|
||||||
|
self.user, self.host, self.remote_dir = self._parse_target_spec(target_spec)
|
||||||
|
|
||||||
|
def _parse_target_spec(self, spec: str) -> Tuple[Optional[str], str, str]:
|
||||||
|
# Forms: user@host:/path or host:/path or ssh://user@host[:port]/path
|
||||||
|
clean = spec
|
||||||
|
if clean.startswith("ssh://"):
|
||||||
|
clean = clean[6:]
|
||||||
|
if "/" in clean:
|
||||||
|
host_part, path_part = clean.split("/", 1)
|
||||||
|
remote_path = "/" + path_part
|
||||||
|
else:
|
||||||
|
host_part, remote_path = clean, "/var/backups"
|
||||||
|
|
||||||
|
if ":" in host_part:
|
||||||
|
host_part, port_str = host_part.split(":", 1)
|
||||||
|
try:
|
||||||
|
self.port = int(port_str)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if "@" in host_part:
|
||||||
|
user, host = host_part.split("@", 1)
|
||||||
|
else:
|
||||||
|
user, host = None, host_part
|
||||||
|
return user, host, remote_path
|
||||||
|
|
||||||
|
# Standard scp user@host:/path
|
||||||
|
if ":" in clean:
|
||||||
|
host_part, remote_path = clean.split(":", 1)
|
||||||
|
if "@" in host_part:
|
||||||
|
user, host = host_part.split("@", 1)
|
||||||
|
else:
|
||||||
|
user, host = None, host_part
|
||||||
|
return user, host, remote_path
|
||||||
|
|
||||||
|
raise TransportError(f"Invalid SSH target spec: {spec}. Expected user@host:/path or ssh://user@host/path")
|
||||||
|
|
||||||
|
def _build_ssh_cmd(self, remote_command: str) -> List[str]:
|
||||||
|
cmd = ["ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no", "-p", str(self.port)]
|
||||||
|
if self.ssh_key:
|
||||||
|
cmd.extend(["-i", self.ssh_key])
|
||||||
|
target = f"{self.user}@{self.host}" if self.user else self.host
|
||||||
|
cmd.extend([target, remote_command])
|
||||||
|
return cmd
|
||||||
|
|
||||||
|
def push(self, local_archive_path: str) -> Dict[str, Any]:
|
||||||
|
if not os.path.isfile(local_archive_path):
|
||||||
|
raise TransportError(f"Source archive does not exist: {local_archive_path}")
|
||||||
|
|
||||||
|
source_sha = calculate_file_sha256(local_archive_path)
|
||||||
|
source_size = os.path.getsize(local_archive_path)
|
||||||
|
filename = os.path.basename(local_archive_path)
|
||||||
|
|
||||||
|
# 1. Ensure remote directory exists
|
||||||
|
mkdir_cmd = self._build_ssh_cmd(f"mkdir -p {self.remote_dir}")
|
||||||
|
res = subprocess.run(mkdir_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||||
|
if res.returncode != 0:
|
||||||
|
raise TransportError(f"Failed to create remote directory {self.remote_dir}: {res.stderr.strip()}")
|
||||||
|
|
||||||
|
remote_tmp = f"{self.remote_dir}/{filename}.tmp.{os.getpid()}"
|
||||||
|
remote_final = f"{self.remote_dir}/{filename}"
|
||||||
|
target_dest = f"{self.user}@{self.host}:{remote_tmp}" if self.user else f"{self.host}:{remote_tmp}"
|
||||||
|
|
||||||
|
# 2. Transfer using rsync if available, else scp
|
||||||
|
if shutil.which("rsync"):
|
||||||
|
ssh_opt = f"ssh -o BatchMode=yes -o StrictHostKeyChecking=no -p {self.port}"
|
||||||
|
if self.ssh_key:
|
||||||
|
ssh_opt += f" -i {self.ssh_key}"
|
||||||
|
transfer_cmd = ["rsync", "-avz", "--partial", "-e", ssh_opt, local_archive_path, target_dest]
|
||||||
|
else:
|
||||||
|
scp_cmd = ["scp", "-P", str(self.port), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no"]
|
||||||
|
if self.ssh_key:
|
||||||
|
scp_cmd.extend(["-i", self.ssh_key])
|
||||||
|
scp_cmd.extend([local_archive_path, target_dest])
|
||||||
|
transfer_cmd = scp_cmd
|
||||||
|
|
||||||
|
res = subprocess.run(transfer_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||||
|
if res.returncode != 0:
|
||||||
|
raise TransportError(f"Transfer to {target_dest} failed: {res.stderr.strip()}")
|
||||||
|
|
||||||
|
# 3. Verify remote SHA-256 and atomically move to final path
|
||||||
|
verify_and_mv = (
|
||||||
|
f"if command -v sha256sum >/dev/null 2>&1; then "
|
||||||
|
f" rsha=$(sha256sum {remote_tmp} | cut -d' ' -f1); "
|
||||||
|
f" if [ \"$rsha\" != \"{source_sha}\" ]; then rm -f {remote_tmp}; exit 2; fi; "
|
||||||
|
f"fi; "
|
||||||
|
f"mv {remote_tmp} {remote_final} && chmod 0600 {remote_final}"
|
||||||
|
)
|
||||||
|
mv_cmd = self._build_ssh_cmd(verify_and_mv)
|
||||||
|
res = subprocess.run(mv_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||||
|
if res.returncode != 0:
|
||||||
|
raise TransportError(f"Remote integrity verification or rename failed on {self.host}: {res.stderr.strip()}")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"status": "success",
|
||||||
|
"transport": "ssh",
|
||||||
|
"source_path": local_archive_path,
|
||||||
|
"destination_target": f"{self.host}:{remote_final}",
|
||||||
|
"bytes_transferred": source_size,
|
||||||
|
"sha256": source_sha
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_remote(self) -> List[SnapshotManifest]:
|
||||||
|
"""Query remote directory for snapshot files."""
|
||||||
|
list_cmd = self._build_ssh_cmd(f"ls -1 {self.remote_dir}/*.tar.gz {self.remote_dir}/*.tar 2>/dev/null || true")
|
||||||
|
res = subprocess.run(list_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||||
|
if res.returncode != 0:
|
||||||
|
return []
|
||||||
|
|
||||||
|
remote_files = [line.strip() for line in res.stdout.splitlines() if line.strip()]
|
||||||
|
manifests: List[SnapshotManifest] = []
|
||||||
|
|
||||||
|
for rf in remote_files:
|
||||||
|
fname = os.path.basename(rf)
|
||||||
|
# Create synthetic manifest parsed from filename
|
||||||
|
snap_id = fname
|
||||||
|
for ext in (".tar.gz", ".tar"):
|
||||||
|
if snap_id.endswith(ext):
|
||||||
|
snap_id = snap_id[:-len(ext)]
|
||||||
|
break
|
||||||
|
|
||||||
|
m = SnapshotManifest(
|
||||||
|
schema_version="1.0",
|
||||||
|
snapshot_id=snap_id,
|
||||||
|
created_at="",
|
||||||
|
hostname="",
|
||||||
|
profile="remote",
|
||||||
|
compression="gzip" if rf.endswith(".gz") else "none",
|
||||||
|
os={},
|
||||||
|
package_manager="none",
|
||||||
|
package_count=0,
|
||||||
|
included_paths=[],
|
||||||
|
stats={},
|
||||||
|
files_sha256={}
|
||||||
|
)
|
||||||
|
manifests.append(m)
|
||||||
|
|
||||||
|
return manifests
|
||||||
|
|
||||||
|
def prune_remote(self, retention: RetentionEngine) -> List[Dict[str, Any]]:
|
||||||
|
snaps = self.list_remote()
|
||||||
|
_, to_prune = retention.calculate_prune_set(snaps)
|
||||||
|
results: List[Dict[str, Any]] = []
|
||||||
|
|
||||||
|
for s in to_prune:
|
||||||
|
target_rm = f"{self.remote_dir}/{s.snapshot_id}.tar.gz"
|
||||||
|
target_rm_plain = f"{self.remote_dir}/{s.snapshot_id}.tar"
|
||||||
|
rm_cmd = self._build_ssh_cmd(f"rm -f {target_rm} {target_rm_plain}")
|
||||||
|
res = subprocess.run(rm_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||||
|
status = "deleted" if res.returncode == 0 else f"error: {res.stderr.strip()}"
|
||||||
|
results.append({
|
||||||
|
"snapshot_id": s.snapshot_id,
|
||||||
|
"remote_path": target_rm,
|
||||||
|
"action": status
|
||||||
|
})
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
class TransportFactory:
|
||||||
|
"""Factory to instantiate transport backends based on destination string or config."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_transport(
|
||||||
|
target_spec: str,
|
||||||
|
config: Optional[Dict[str, Any]] = None,
|
||||||
|
ssh_key: Optional[str] = None
|
||||||
|
) -> BaseTransport:
|
||||||
|
# 1. Check if target_spec is an alias in config['remotes']
|
||||||
|
if config and "remotes" in config and target_spec in config["remotes"]:
|
||||||
|
remote_cfg = config["remotes"][target_spec]
|
||||||
|
t_type = remote_cfg.get("type", "ssh")
|
||||||
|
if t_type == "local" or t_type == "mount":
|
||||||
|
return LocalPathTransport(remote_cfg["path"])
|
||||||
|
elif t_type in ("ssh", "rsync", "sftp"):
|
||||||
|
host = remote_cfg["host"]
|
||||||
|
user = remote_cfg.get("user")
|
||||||
|
path = remote_cfg.get("path", "/var/backups")
|
||||||
|
port = remote_cfg.get("port", 22)
|
||||||
|
key = remote_cfg.get("key") or ssh_key
|
||||||
|
spec = f"{user}@{host}:{path}" if user else f"{host}:{path}"
|
||||||
|
return SshTransport(spec, ssh_key=key, port=port)
|
||||||
|
|
||||||
|
# 2. Local directory or mounted NFS/SMB share
|
||||||
|
if target_spec.startswith("/") or target_spec.startswith("./") or target_spec.startswith("../"):
|
||||||
|
return LocalPathTransport(target_spec)
|
||||||
|
|
||||||
|
# 3. SSH specification: user@host:/path or ssh://...
|
||||||
|
if ":" in target_spec:
|
||||||
|
return SshTransport(target_spec, ssh_key=ssh_key)
|
||||||
|
|
||||||
|
# Default fallback: treat as local path
|
||||||
|
return LocalPathTransport(target_spec)
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
"""Unit tests for RemoteTransport and push command."""
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch, MagicMock
|
||||||
|
|
||||||
|
from linux_backuper.cli import main
|
||||||
|
from linux_backuper.core.archiver import SnapshotArchiver
|
||||||
|
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_GENERIC_ERROR
|
||||||
|
from linux_backuper.core.retention import RetentionEngine
|
||||||
|
from linux_backuper.core.transport import (
|
||||||
|
LocalPathTransport,
|
||||||
|
SshTransport,
|
||||||
|
TransportFactory,
|
||||||
|
TransportError
|
||||||
|
)
|
||||||
|
from linux_backuper.models import SnapshotManifest
|
||||||
|
|
||||||
|
class TestRemoteTransport(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.test_dir = tempfile.mkdtemp(prefix="test_transport_")
|
||||||
|
self.backup_dir = os.path.join(self.test_dir, "local_backups")
|
||||||
|
self.remote_dir = os.path.join(self.test_dir, "remote_nas")
|
||||||
|
os.makedirs(self.backup_dir, exist_ok=True)
|
||||||
|
os.makedirs(self.remote_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# Create a mock snapshot locally
|
||||||
|
self.archiver = SnapshotArchiver(target_dir=self.backup_dir)
|
||||||
|
dummy_f = os.path.join(self.test_dir, "sample.txt")
|
||||||
|
with open(dummy_f, "w") as f:
|
||||||
|
f.write("hello transport\n")
|
||||||
|
|
||||||
|
entries, sha, uncomp, _ = self.archiver.collect_file_list([dummy_f])
|
||||||
|
self.manifest = SnapshotManifest(
|
||||||
|
schema_version="1.0",
|
||||||
|
snapshot_id="snap_transport_1",
|
||||||
|
created_at="2026-10-09T12:00:00Z",
|
||||||
|
hostname="host1",
|
||||||
|
profile="quick",
|
||||||
|
compression="gzip",
|
||||||
|
os={},
|
||||||
|
package_manager="none",
|
||||||
|
package_count=0,
|
||||||
|
included_paths=[dummy_f],
|
||||||
|
stats={"file_count": 1, "uncompressed_bytes": uncomp, "compressed_bytes": 0},
|
||||||
|
files_sha256=sha
|
||||||
|
)
|
||||||
|
self.archive_path = self.archiver.create_snapshot_archive("snap_transport_1", self.manifest, entries)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
shutil.rmtree(self.test_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
def test_local_path_transport_push_and_verify(self):
|
||||||
|
transport = LocalPathTransport(self.remote_dir)
|
||||||
|
res = transport.push(self.archive_path)
|
||||||
|
|
||||||
|
self.assertEqual(res["status"], "success")
|
||||||
|
self.assertEqual(res["transport"], "local_mount")
|
||||||
|
dest_path = res["destination_path"]
|
||||||
|
|
||||||
|
self.assertTrue(os.path.isfile(dest_path))
|
||||||
|
self.assertEqual(os.path.basename(dest_path), os.path.basename(self.archive_path))
|
||||||
|
|
||||||
|
# Check strict permissions (0600)
|
||||||
|
mode = os.stat(dest_path).st_mode & 0o777
|
||||||
|
self.assertEqual(mode, 0o600)
|
||||||
|
|
||||||
|
def test_local_path_transport_remote_prune(self):
|
||||||
|
transport = LocalPathTransport(self.remote_dir)
|
||||||
|
# Push first archive
|
||||||
|
transport.push(self.archive_path)
|
||||||
|
|
||||||
|
# Create second archive and push
|
||||||
|
m2 = SnapshotManifest.from_dict(self.manifest.to_dict())
|
||||||
|
m2.snapshot_id = "snap_transport_2"
|
||||||
|
m2.created_at = "2026-10-09T14:00:00Z"
|
||||||
|
arc2 = self.archiver.create_snapshot_archive("snap_transport_2", m2, [(os.path.join(self.test_dir, "sample.txt"), "data/sample.txt")])
|
||||||
|
transport.push(arc2)
|
||||||
|
|
||||||
|
# 2 archives on remote
|
||||||
|
self.assertEqual(len(transport.list_remote()), 2)
|
||||||
|
|
||||||
|
# Prune remote with keep-last 1
|
||||||
|
retention = RetentionEngine(keep_last=1)
|
||||||
|
pruned_results = transport.prune_remote(retention)
|
||||||
|
|
||||||
|
self.assertEqual(len(pruned_results), 1)
|
||||||
|
self.assertEqual(pruned_results[0]["action"], "deleted")
|
||||||
|
self.assertEqual(len(transport.list_remote()), 1)
|
||||||
|
self.assertEqual(transport.list_remote()[0].snapshot_id, "snap_transport_2")
|
||||||
|
|
||||||
|
def test_transport_factory_parsing(self):
|
||||||
|
# Local dir
|
||||||
|
t1 = TransportFactory.get_transport("/mnt/nas/backups")
|
||||||
|
self.assertIsInstance(t1, LocalPathTransport)
|
||||||
|
|
||||||
|
# SSH
|
||||||
|
t2 = TransportFactory.get_transport("backupuser@nas.local:/volume1/backups")
|
||||||
|
self.assertIsInstance(t2, SshTransport)
|
||||||
|
self.assertEqual(t2.user, "backupuser")
|
||||||
|
self.assertEqual(t2.host, "nas.local")
|
||||||
|
self.assertEqual(t2.remote_dir, "/volume1/backups")
|
||||||
|
|
||||||
|
# Config alias
|
||||||
|
cfg = {
|
||||||
|
"remotes": {
|
||||||
|
"mynas": {
|
||||||
|
"type": "ssh",
|
||||||
|
"host": "192.168.1.100",
|
||||||
|
"user": "admin",
|
||||||
|
"path": "/backups"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t3 = TransportFactory.get_transport("mynas", config=cfg)
|
||||||
|
self.assertIsInstance(t3, SshTransport)
|
||||||
|
self.assertEqual(t3.host, "192.168.1.100")
|
||||||
|
|
||||||
|
def test_cli_push_command(self):
|
||||||
|
stdout = io.StringIO()
|
||||||
|
with patch("sys.stdout", stdout):
|
||||||
|
exit_code = main([
|
||||||
|
"push", "snap_transport_1",
|
||||||
|
"--target", self.remote_dir,
|
||||||
|
"--target-dir", self.backup_dir,
|
||||||
|
"--json"
|
||||||
|
])
|
||||||
|
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||||
|
res = json.loads(stdout.getvalue().strip())
|
||||||
|
self.assertEqual(res["status"], "success")
|
||||||
|
|
||||||
|
# Archive exists on remote
|
||||||
|
expected_remote = os.path.join(self.remote_dir, os.path.basename(self.archive_path))
|
||||||
|
self.assertTrue(os.path.isfile(expected_remote))
|
||||||
|
|
||||||
|
def test_cli_snapshot_auto_push(self):
|
||||||
|
dummy_f = os.path.join(self.test_dir, "auto.txt")
|
||||||
|
with open(dummy_f, "w") as f:
|
||||||
|
f.write("auto push test\n")
|
||||||
|
|
||||||
|
stdout = io.StringIO()
|
||||||
|
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||||
|
exit_code = main([
|
||||||
|
"snapshot",
|
||||||
|
"--target-dir", self.backup_dir,
|
||||||
|
"--paths", dummy_f,
|
||||||
|
"--push", self.remote_dir,
|
||||||
|
"--json"
|
||||||
|
])
|
||||||
|
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||||
|
res = json.loads(stdout.getvalue().strip())
|
||||||
|
self.assertEqual(res["status"], "success")
|
||||||
|
self.assertIsNotNone(res["remote_push"])
|
||||||
|
self.assertEqual(res["remote_push"]["status"], "success")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user