Files

249 lines
9.8 KiB
Python

"""System and snapshot comparison engine (DiffEngine)."""
import difflib
import hashlib
import os
import tarfile
from typing import Dict, List, Optional, Tuple, Any
from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256, BUFFER_SIZE
from linux_backuper.core.detector import detect_distro
from linux_backuper.core.inspector import SystemInspector
from linux_backuper.models import PackageItem, SnapshotManifest
MAX_DIFF_TEXT_BYTES = 1024 * 1024 # 1 MB threshold for generating unified diffs
class DiffEngine:
"""Computes differences between snapshots, and between live system and snapshot."""
def __init__(self, target_dir: str):
self.target_dir = target_dir
def _resolve_archive(self, snapshot_id: str) -> str:
archive_path = SnapshotArchiver.resolve_archive_path(self.target_dir, snapshot_id)
if not os.path.isfile(archive_path):
raise FileNotFoundError(f"Snapshot archive not found: {archive_path}")
return archive_path
@staticmethod
def _parse_packages_txt(content: Optional[str]) -> Dict[str, str]:
"""Parse meta/packages.txt lines into {name: version}."""
packages: Dict[str, str] = {}
if not content:
return packages
for line in content.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
if len(parts) >= 2:
packages[parts[0]] = parts[1]
elif len(parts) == 1:
packages[parts[0]] = "unknown"
return packages
def diff_snapshots(self, id1: str, id2: str) -> Dict[str, Any]:
"""
Compare two snapshots.
Returns detailed dictionary of file differences and package differences.
"""
path1 = self._resolve_archive(id1)
path2 = self._resolve_archive(id2)
m1 = SnapshotArchiver.read_manifest_from_archive(path1)
m2 = SnapshotArchiver.read_manifest_from_archive(path2)
hashes1 = {k: v for k, v in m1.files_sha256.items() if k.startswith("data/")}
hashes2 = {k: v for k, v in m2.files_sha256.items() if k.startswith("data/")}
keys1 = set(hashes1.keys())
keys2 = set(hashes2.keys())
added_files = sorted(list(keys2 - keys1))
removed_files = sorted(list(keys1 - keys2))
modified_files = sorted([k for k in (keys1 & keys2) if hashes1[k] != hashes2[k]])
unchanged_files = sorted([k for k in (keys1 & keys2) if hashes1[k] == hashes2[k]])
# Package comparison
pkg_txt1 = SnapshotArchiver.read_meta_file(path1, "meta/packages.txt")
pkg_txt2 = SnapshotArchiver.read_meta_file(path2, "meta/packages.txt")
pkgs1 = self._parse_packages_txt(pkg_txt1)
pkgs2 = self._parse_packages_txt(pkg_txt2)
p_keys1 = set(pkgs1.keys())
p_keys2 = set(pkgs2.keys())
pkgs_added = {p: pkgs2[p] for p in sorted(p_keys2 - p_keys1)}
pkgs_removed = {p: pkgs1[p] for p in sorted(p_keys1 - p_keys2)}
pkgs_changed = {}
for p in sorted(p_keys1 & p_keys2):
if pkgs1[p] != pkgs2[p]:
pkgs_changed[p] = {"old": pkgs1[p], "new": pkgs2[p]}
return {
"type": "snapshot_vs_snapshot",
"snapshot_1": m1.snapshot_id,
"snapshot_2": m2.snapshot_id,
"files": {
"added": added_files,
"removed": removed_files,
"modified": modified_files,
"unchanged_count": len(unchanged_files)
},
"packages": {
"added": pkgs_added,
"removed": pkgs_removed,
"changed": pkgs_changed
}
}
def diff_with_live(self, snapshot_id: str, target_root: str = "/") -> Dict[str, Any]:
"""
Compare live system state against a snapshot.
Checks:
- Files present in snapshot vs live filesystem under target_root
- Files added on live system in snapshot's included paths
- Live packages vs snapshot packages
"""
archive_path = self._resolve_archive(snapshot_id)
manifest = SnapshotArchiver.read_manifest_from_archive(archive_path)
data_hashes = {k: v for k, v in manifest.files_sha256.items() if k.startswith("data/")}
missing_on_live: List[str] = []
modified_on_live: List[str] = []
unchanged_on_live: List[str] = []
file_diffs: Dict[str, str] = {}
target_root_clean = os.path.abspath(target_root)
for rel_data_path, archived_sha in data_hashes.items():
# rel_data_path is like 'data/etc/hosts'
clean_subpath = rel_data_path[5:].lstrip("/") # 'etc/hosts'
live_abs_path = os.path.join(target_root_clean, clean_subpath)
if not os.path.exists(live_abs_path) and not os.path.islink(live_abs_path):
missing_on_live.append("/" + clean_subpath)
continue
try:
live_sha = calculate_file_sha256(live_abs_path)
except OSError:
modified_on_live.append("/" + clean_subpath)
continue
if live_sha != archived_sha:
modified_on_live.append("/" + clean_subpath)
else:
unchanged_on_live.append("/" + clean_subpath)
# Check for added files on live system within included_paths
added_on_live: List[str] = []
for inc_path in manifest.included_paths:
if inc_path.startswith(target_root_clean):
live_scan_dir = inc_path
else:
live_scan_dir = os.path.join(target_root_clean, inc_path.lstrip("/"))
if not os.path.isdir(live_scan_dir):
continue
for root, _, files in os.walk(live_scan_dir):
for f in files:
full_p = os.path.join(root, f)
rel_to_target = os.path.relpath(full_p, target_root_clean)
archive_key = "data/" + rel_to_target.lstrip("/")
if archive_key not in data_hashes:
candidate_found = any(dk.endswith("/" + rel_to_target.lstrip("/")) for dk in data_hashes)
if not candidate_found:
added_on_live.append("/" + rel_to_target.lstrip("/"))
# Packages diff
pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt")
archived_pkgs = self._parse_packages_txt(pkg_txt)
distro_id = manifest.os.get("distro_id", detect_distro().distro_id)
inspector = SystemInspector(distro_id=distro_id)
live_packages = inspector.inspect_packages()
live_pkgs_dict = {p.name: p.version for p in live_packages}
archived_keys = set(archived_pkgs.keys())
live_keys = set(live_pkgs_dict.keys())
pkgs_installed_since = {p: live_pkgs_dict[p] for p in sorted(live_keys - archived_keys)}
pkgs_removed_since = {p: archived_pkgs[p] for p in sorted(archived_keys - live_keys)}
pkgs_version_changed = {}
for p in sorted(archived_keys & live_keys):
if live_pkgs_dict[p] != archived_pkgs[p]:
pkgs_version_changed[p] = {
"snapshot": archived_pkgs[p],
"live": live_pkgs_dict[p]
}
return {
"type": "live_vs_snapshot",
"snapshot_id": manifest.snapshot_id,
"target_root": target_root_clean,
"files": {
"modified": sorted(modified_on_live),
"missing_on_live": sorted(missing_on_live),
"added_on_live": sorted(added_on_live),
"unchanged_count": len(unchanged_on_live)
},
"packages": {
"installed_since_backup": pkgs_installed_since,
"removed_since_backup": pkgs_removed_since,
"version_changed": pkgs_version_changed
}
}
def generate_unified_file_diff(
self,
snapshot_id: str,
file_path: str,
target_root: str = "/"
) -> Optional[str]:
"""
Generate unified diff for a single file between snapshot and live filesystem.
Returns unified diff string, or None if files are binary or identical.
"""
archive_path = self._resolve_archive(snapshot_id)
clean_subpath = file_path.lstrip("/")
archive_member = f"data/{clean_subpath}"
live_path = os.path.join(os.path.abspath(target_root), clean_subpath)
archived_content: Optional[str] = None
with tarfile.open(archive_path, "r:*") as tar:
try:
member = tar.getmember(archive_member)
if member.isreg() and member.size <= MAX_DIFF_TEXT_BYTES:
f = tar.extractfile(member)
if f:
archived_content = f.read().decode("utf-8", errors="replace")
except KeyError:
return None
live_content: Optional[str] = None
if os.path.isfile(live_path):
if os.path.getsize(live_path) <= MAX_DIFF_TEXT_BYTES:
try:
with open(live_path, "r", encoding="utf-8", errors="replace") as f:
live_content = f.read()
except OSError:
pass
if archived_content is None and live_content is None:
return None
archived_lines = archived_content.splitlines(keepends=True) if archived_content is not None else []
live_lines = live_content.splitlines(keepends=True) if live_content is not None else []
diff = list(difflib.unified_diff(
archived_lines,
live_lines,
fromfile=f"snapshot:{snapshot_id}:/{clean_subpath}",
tofile=f"live:/{clean_subpath}"
))
return "".join(diff) if diff else None