Files
linux-backuper/linux_backuper/core/archiver.py
T

271 lines
10 KiB
Python

"""Archive creation, extraction, and verification using Python standard library."""
import gzip
import hashlib
import json
import os
import stat
import tarfile
import time
from typing import Dict, List, Optional, Tuple, Any
from linux_backuper.models import SnapshotManifest
BUFFER_SIZE = 64 * 1024 # 64 KB chunks for hashing and streaming
def calculate_file_sha256(filepath: str) -> str:
"""Calculate SHA-256 checksum of a file."""
hasher = hashlib.sha256()
with open(filepath, "rb") as f:
while chunk := f.read(BUFFER_SIZE):
hasher.update(chunk)
return hasher.hexdigest()
def is_socket_or_fifo(filepath: str) -> bool:
"""Check if path is a UNIX socket, named pipe (FIFO) or character device."""
try:
st = os.lstat(filepath)
return stat.S_ISSOCK(st.st_mode) or stat.S_ISFIFO(st.st_mode)
except OSError:
return True
class SnapshotArchiver:
"""Manages creation, listing, and verification of snapshot archives."""
def __init__(self, target_dir: str, compression: str = "gzip"):
self.target_dir = target_dir
self.compression = "gzip" if compression in ("gz", "gzip") else "none"
def _ensure_target_dir() -> None:
pass
def _ensure_target_dir_inst(self) -> None:
"""Ensure target directory exists with 0700 permissions."""
os.makedirs(self.target_dir, exist_ok=True)
try:
os.chmod(self.target_dir, 0o700)
except OSError:
pass
def collect_file_list(
self,
paths: List[str],
exclude_patterns: Optional[List[str]] = None
) -> Tuple[List[Tuple[str, str]], Dict[str, str], int]:
"""
Scan paths and compute pre-archive hashes and metadata.
Returns:
- list of (filesystem_abs_path, tar_rel_path)
- dict of {tar_rel_path: sha256_hash}
- total uncompressed bytes
"""
file_entries: List[Tuple[str, str]] = []
files_sha256: Dict[str, str] = {}
total_bytes = 0
exclude_patterns = exclude_patterns or []
for base_path in paths:
abs_base = os.path.abspath(base_path)
if not os.path.exists(abs_base):
continue
if os.path.isfile(abs_base) or os.path.islink(abs_base):
if not is_socket_or_fifo(abs_base):
rel_name = os.path.join("data", os.path.basename(abs_base))
file_entries.append((abs_base, rel_name))
if not os.path.islink(abs_base):
sha = calculate_file_sha256(abs_base)
files_sha256[rel_name] = sha
total_bytes += os.path.getsize(abs_base)
continue
# Directory tree traversal
for root, dirs, files in os.walk(abs_base, followlinks=False):
# Filter subdirectories in place
dirs[:] = [d for d in dirs if not any(p in d for p in exclude_patterns)]
for filename in files:
abs_filepath = os.path.join(root, filename)
if is_socket_or_fifo(abs_filepath):
continue
# Calculate archive path under data/
rel_to_base = os.path.relpath(abs_filepath, os.path.dirname(abs_base))
arc_path = os.path.join("data", rel_to_base)
file_entries.append((abs_filepath, arc_path))
if not os.path.islink(abs_filepath):
try:
sha = calculate_file_sha256(abs_filepath)
files_sha256[arc_path] = sha
total_bytes += os.path.getsize(abs_filepath)
except (OSError, IOError):
pass
return file_entries, files_sha256, total_bytes
def create_snapshot_archive(
self,
snapshot_id: str,
manifest: SnapshotManifest,
file_entries: List[Tuple[str, str]]
) -> str:
"""
Create atomic .tar.gz archive with manifest.json as the very first member.
Enforces 0600 file permissions.
"""
self._ensure_target_dir_inst()
ext = ".tar.gz" if self.compression == "gzip" else ".tar"
final_archive_path = os.path.join(self.target_dir, f"{snapshot_id}{ext}")
temp_archive_path = os.path.join(self.target_dir, f".{snapshot_id}.tmp{ext}")
# Encode manifest JSON bytes
manifest_dict = manifest.to_dict()
manifest_bytes = json.dumps(manifest_dict, indent=2, sort_keys=True).encode("utf-8")
# Open temp archive for writing with gzip or plain tar
tar_mode = "w:gz" if self.compression == "gzip" else "w:"
with tarfile.open(temp_archive_path, tar_mode) as tar:
# 1. ADD MANIFEST.JSON AS THE VERY FIRST MEMBER
manifest_info = tarfile.TarInfo(name="manifest.json")
manifest_info.size = len(manifest_bytes)
manifest_info.mtime = int(time.time())
manifest_info.mode = 0o600
manifest_info.type = tarfile.REGTYPE
import io
tar.addfile(tarinfo=manifest_info, fileobj=io.BytesIO(manifest_bytes))
# 2. ADD ALL COLLECTED DATA FILES
for abs_path, arc_path in file_entries:
try:
tar.add(abs_path, arcname=arc_path, recursive=False)
except (OSError, IOError):
pass
# Set strict 0600 permissions
try:
os.chmod(temp_archive_path, 0o600)
except OSError:
pass
# Atomic rename to final path
os.replace(temp_archive_path, final_archive_path)
# Update manifest compressed size stat
compressed_size = os.path.getsize(final_archive_path)
manifest.stats["compressed_bytes"] = compressed_size
return final_archive_path
@staticmethod
def read_manifest_from_archive(archive_path: str) -> SnapshotManifest:
"""
Read manifest.json from the first member of the archive stream.
Ultra-fast: avoids decompressing the rest of the archive.
"""
with tarfile.open(archive_path, "r:*") as tar:
first_member = tar.next()
if not first_member or first_member.name != "manifest.json":
# Fallback: scan for manifest.json if not first
member = tar.getmember("manifest.json")
else:
member = first_member
manifest_file = tar.extractfile(member)
if not manifest_file:
raise ValueError(f"Could not read manifest from {archive_path}")
data = json.loads(manifest_file.read().decode("utf-8"))
manifest = SnapshotManifest.from_dict(data)
if manifest.stats.get("compressed_bytes", 0) == 0 and os.path.isfile(archive_path):
manifest.stats["compressed_bytes"] = os.path.getsize(archive_path)
return manifest
@staticmethod
def verify_archive(archive_path: str) -> Tuple[bool, str]:
"""
Verify gzip stream integrity and all file SHA-256 checksums against manifest.json.
Returns (is_valid, error_message).
"""
if not os.path.isfile(archive_path):
return False, f"Archive not found: {archive_path}"
# 1. Check if file is gzip by inspecting header
is_gz = False
try:
with open(archive_path, "rb") as f:
header = f.read(2)
is_gz = (header == b"\x1f\x8b")
except OSError as e:
return False, f"Cannot open archive: {e}"
# If gzipped, verify complete stream integrity
if is_gz:
try:
with gzip.open(archive_path, "rb") as gz:
while gz.read(BUFFER_SIZE):
pass
except Exception as e:
return False, f"Gzip stream corrupted: {e}"
# 2. Manifest and member checksum verification
try:
with tarfile.open(archive_path, "r:*") as tar:
# Read manifest
try:
manifest_member = tar.getmember("manifest.json")
manifest_data = json.loads(tar.extractfile(manifest_member).read().decode("utf-8"))
except Exception as e:
return False, f"Invalid or missing manifest.json: {e}"
expected_hashes: Dict[str, str] = manifest_data.get("files_sha256", {})
for arc_name, expected_sha in expected_hashes.items():
try:
member = tar.getmember(arc_name)
except KeyError:
return False, f"Missing file in archive: {arc_name}"
if member.isreg():
f = tar.extractfile(member)
if not f:
return False, f"Unable to read file: {arc_name}"
hasher = hashlib.sha256()
while chunk := f.read(BUFFER_SIZE):
hasher.update(chunk)
actual_sha = hasher.hexdigest()
if actual_sha != expected_sha:
return False, f"Checksum mismatch for {arc_name}: expected {expected_sha}, got {actual_sha}"
except Exception as e:
return False, f"Tar archive corrupted: {e}"
return True, "Integrity verified successfully"
def list_snapshots(self) -> List[SnapshotManifest]:
"""List all valid snapshots in the target directory."""
if not os.path.isdir(self.target_dir):
return []
snapshots: List[SnapshotManifest] = []
try:
entries = sorted(os.listdir(self.target_dir), reverse=True)
except PermissionError:
raise PermissionError(f"Permission denied accessing backup directory: {self.target_dir}")
except OSError:
return []
for filename in entries:
if filename.endswith(".tar.gz") and not filename.startswith("."):
filepath = os.path.join(self.target_dir, filename)
try:
manifest = self.read_manifest_from_archive(filepath)
snapshots.append(manifest)
except Exception:
pass
return snapshots