293 lines
12 KiB
Python
293 lines
12 KiB
Python
"""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)
|