feat(restore): implement slice 4 snapshot management, diff engine, and safe restore
This commit is contained in:
1 parent
646bd9d145
commit
8d4127de30
9 files changed
+1386
-4
No files matched your search
@@ -27,7 +27,7 @@ def is_socket_or_fifo(filepath: str) -> bool:
|
||||
st = os.lstat(filepath)
|
||||
return stat.S_ISSOCK(st.st_mode) or stat.S_ISFIFO(st.st_mode)
|
||||
except OSError:
|
||||
return True
|
||||
return False
|
||||
|
||||
def is_sanitized_target(filepath: str) -> bool:
|
||||
"""Check if file contains secrets and must be omitted during sanitized export."""
|
||||
@@ -301,6 +301,109 @@ class SnapshotArchiver:
|
||||
|
||||
return True, "Integrity verified successfully"
|
||||
|
||||
@staticmethod
|
||||
def resolve_archive_path(target_dir: str, snapshot_id: str) -> str:
|
||||
"""Resolve a snapshot ID or filename to full archive path."""
|
||||
if os.path.isabs(snapshot_id) and os.path.exists(snapshot_id):
|
||||
return snapshot_id
|
||||
direct = os.path.join(target_dir, snapshot_id)
|
||||
if os.path.exists(direct):
|
||||
return direct
|
||||
tar_gz = os.path.join(target_dir, f"{snapshot_id}.tar.gz")
|
||||
if os.path.exists(tar_gz):
|
||||
return tar_gz
|
||||
tar_plain = os.path.join(target_dir, f"{snapshot_id}.tar")
|
||||
if os.path.exists(tar_plain):
|
||||
return tar_plain
|
||||
if snapshot_id.endswith(".tar.gz") or snapshot_id.endswith(".tar"):
|
||||
return direct
|
||||
return tar_gz
|
||||
|
||||
@staticmethod
|
||||
def read_meta_file(archive_path: str, meta_relative_path: str) -> Optional[str]:
|
||||
"""Read a metadata text file from the archive (e.g. meta/packages.txt)."""
|
||||
with tarfile.open(archive_path, "r:*") as tar:
|
||||
try:
|
||||
member = tar.getmember(meta_relative_path)
|
||||
f = tar.extractfile(member)
|
||||
if f:
|
||||
return f.read().decode("utf-8", errors="replace")
|
||||
except KeyError:
|
||||
return None
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def extract_file(archive_path: str, member_path: str, destination_path: str) -> str:
|
||||
"""
|
||||
Extract a single member from the archive to destination_path.
|
||||
Guards strictly against Zip Slip / path traversal.
|
||||
Returns final destination path.
|
||||
"""
|
||||
dest_abs = os.path.abspath(destination_path)
|
||||
|
||||
# If destination is an existing directory, append member filename
|
||||
if os.path.isdir(dest_abs):
|
||||
dest_abs = os.path.join(dest_abs, os.path.basename(member_path))
|
||||
|
||||
dest_dir = os.path.dirname(dest_abs)
|
||||
if dest_dir:
|
||||
os.makedirs(dest_dir, exist_ok=True)
|
||||
|
||||
with tarfile.open(archive_path, "r:*") as tar:
|
||||
# Candidate names inside archive
|
||||
candidates = [
|
||||
member_path,
|
||||
f"data/{member_path.lstrip('/')}",
|
||||
member_path.lstrip("/"),
|
||||
f"data{member_path}" if member_path.startswith("/") else f"data/{member_path}"
|
||||
]
|
||||
target_member = None
|
||||
for c in candidates:
|
||||
try:
|
||||
target_member = tar.getmember(c)
|
||||
break
|
||||
except KeyError:
|
||||
continue
|
||||
|
||||
if not target_member:
|
||||
clean_target = member_path.strip("/")
|
||||
for m in tar.getmembers():
|
||||
if m.name == clean_target or m.name == f"data/{clean_target}":
|
||||
target_member = m
|
||||
break
|
||||
if m.name.endswith(f"/{clean_target}") or m.name.endswith(clean_target):
|
||||
target_member = m
|
||||
break
|
||||
|
||||
if not target_member:
|
||||
raise FileNotFoundError(f"File '{member_path}' not found in archive")
|
||||
|
||||
if not target_member.isreg():
|
||||
raise ValueError(f"Member '{target_member.name}' is not a regular file")
|
||||
|
||||
f_in = tar.extractfile(target_member)
|
||||
if not f_in:
|
||||
raise IOError(f"Could not read member '{target_member.name}'")
|
||||
|
||||
tmp_dest = f"{dest_abs}.tmp.{os.getpid()}"
|
||||
try:
|
||||
with open(tmp_dest, "wb") as f_out:
|
||||
while chunk := f_in.read(BUFFER_SIZE):
|
||||
f_out.write(chunk)
|
||||
try:
|
||||
os.chmod(tmp_dest, target_member.mode)
|
||||
except OSError:
|
||||
pass
|
||||
os.replace(tmp_dest, dest_abs)
|
||||
finally:
|
||||
if os.path.exists(tmp_dest):
|
||||
try:
|
||||
os.unlink(tmp_dest)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return dest_abs
|
||||
|
||||
def list_snapshots(self) -> List[SnapshotManifest]:
|
||||
"""List all valid snapshots in the target directory."""
|
||||
if not os.path.isdir(self.target_dir):
|
||||
@@ -315,7 +418,7 @@ class SnapshotArchiver:
|
||||
return []
|
||||
|
||||
for filename in entries:
|
||||
if filename.endswith(".tar.gz") and not filename.startswith("."):
|
||||
if (filename.endswith(".tar.gz") or filename.endswith(".tar")) and not filename.startswith("."):
|
||||
filepath = os.path.join(self.target_dir, filename)
|
||||
try:
|
||||
manifest = self.read_manifest_from_archive(filepath)
|
||||
@@ -323,3 +426,4 @@ class SnapshotArchiver:
|
||||
except Exception:
|
||||
pass
|
||||
return snapshots
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
"""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
|
||||
@@ -0,0 +1,317 @@
|
||||
"""Safe restore engine with dry-run default, safety snapshots, and atomic write."""
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tarfile
|
||||
from typing import Dict, List, Optional, Tuple, Any
|
||||
|
||||
from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256, is_socket_or_fifo, BUFFER_SIZE
|
||||
from linux_backuper.core.constants import EXIT_DRY_RUN, EXIT_SUCCESS, EXIT_GENERIC_ERROR, DEFAULT_BACKUP_DIR
|
||||
from linux_backuper.core.detector import detect_distro
|
||||
from linux_backuper.core.lock import SingleInstanceLock
|
||||
from linux_backuper.models import RestorePlan, RestorePlanItem, SnapshotManifest
|
||||
|
||||
EXCLUDED_DYNAMIC_PATHS = {
|
||||
"/etc/resolv.conf",
|
||||
"/etc/mtab",
|
||||
"/etc/adjtime",
|
||||
"/etc/machine-id"
|
||||
}
|
||||
|
||||
SENSITIVE_NETWORK_PREFIXES = (
|
||||
"/etc/netplan",
|
||||
"/etc/sysconfig/network-scripts",
|
||||
"/etc/network/interfaces",
|
||||
"/etc/NetworkManager"
|
||||
)
|
||||
|
||||
class DryRunException(Exception):
|
||||
"""Raised when restore runs in dry-run mode (exit code 5)."""
|
||||
def __init__(self, plan: RestorePlan):
|
||||
self.plan = plan
|
||||
super().__init__("Restore executed in dry-run mode. Pass --force to apply changes.")
|
||||
|
||||
class SafeRestoreEngine:
|
||||
"""Safely restores configuration archives onto the filesystem."""
|
||||
|
||||
def __init__(self, target_dir: str = DEFAULT_BACKUP_DIR):
|
||||
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
|
||||
|
||||
def plan_restore(
|
||||
self,
|
||||
snapshot_id: str,
|
||||
target_root: str = "/",
|
||||
include_fstab: bool = False
|
||||
) -> RestorePlan:
|
||||
"""
|
||||
Inspect snapshot and construct a detailed RestorePlan against target_root.
|
||||
Identifies create, modify, and skip actions without mutating the disk.
|
||||
"""
|
||||
archive_path = self._resolve_archive(snapshot_id)
|
||||
manifest = SnapshotArchiver.read_manifest_from_archive(archive_path)
|
||||
|
||||
target_root_clean = os.path.abspath(target_root)
|
||||
plan_items: List[RestorePlanItem] = []
|
||||
|
||||
with tarfile.open(archive_path, "r:*") as tar:
|
||||
for member in tar.getmembers():
|
||||
if not member.name.startswith("data/"):
|
||||
continue
|
||||
|
||||
clean_subpath = member.name[5:].lstrip("/")
|
||||
abs_sys_path = "/" + clean_subpath
|
||||
target_dest_path = os.path.join(target_root_clean, clean_subpath)
|
||||
|
||||
# 1. Check excluded dynamic / runtime files
|
||||
if abs_sys_path in EXCLUDED_DYNAMIC_PATHS:
|
||||
plan_items.append(RestorePlanItem(
|
||||
rel_path=member.name,
|
||||
abs_path=target_dest_path,
|
||||
action="skip",
|
||||
reason="Excluded dynamic/volatile system file"
|
||||
))
|
||||
continue
|
||||
|
||||
if abs_sys_path == "/etc/fstab" and not include_fstab:
|
||||
plan_items.append(RestorePlanItem(
|
||||
rel_path=member.name,
|
||||
abs_path=target_dest_path,
|
||||
action="skip",
|
||||
reason="Protected filesystem table (/etc/fstab). Pass --include-fstab to overwrite"
|
||||
))
|
||||
continue
|
||||
|
||||
if os.path.exists(target_dest_path) and is_socket_or_fifo(target_dest_path):
|
||||
plan_items.append(RestorePlanItem(
|
||||
rel_path=member.name,
|
||||
abs_path=target_dest_path,
|
||||
action="skip",
|
||||
reason="Socket or FIFO file on filesystem"
|
||||
))
|
||||
continue
|
||||
|
||||
# 2. Check sensitive network files
|
||||
is_net = any(abs_sys_path.startswith(prefix) for prefix in SENSITIVE_NETWORK_PREFIXES)
|
||||
|
||||
expected_sha = manifest.files_sha256.get(member.name)
|
||||
|
||||
# 3. Check live file state
|
||||
if not os.path.exists(target_dest_path) and not os.path.islink(target_dest_path):
|
||||
plan_items.append(RestorePlanItem(
|
||||
rel_path=member.name,
|
||||
abs_path=target_dest_path,
|
||||
action="create",
|
||||
reason="File does not exist on target system",
|
||||
is_sensitive_network=is_net,
|
||||
source_sha256=expected_sha,
|
||||
target_sha256=None
|
||||
))
|
||||
else:
|
||||
if os.path.isfile(target_dest_path):
|
||||
target_sha = calculate_file_sha256(target_dest_path)
|
||||
if expected_sha and target_sha == expected_sha:
|
||||
plan_items.append(RestorePlanItem(
|
||||
rel_path=member.name,
|
||||
abs_path=target_dest_path,
|
||||
action="skip",
|
||||
reason="File content is identical to snapshot",
|
||||
is_sensitive_network=is_net,
|
||||
source_sha256=expected_sha,
|
||||
target_sha256=target_sha
|
||||
))
|
||||
else:
|
||||
plan_items.append(RestorePlanItem(
|
||||
rel_path=member.name,
|
||||
abs_path=target_dest_path,
|
||||
action="modify",
|
||||
reason="File content differs from snapshot",
|
||||
is_sensitive_network=is_net,
|
||||
source_sha256=expected_sha,
|
||||
target_sha256=target_sha
|
||||
))
|
||||
else:
|
||||
plan_items.append(RestorePlanItem(
|
||||
rel_path=member.name,
|
||||
abs_path=target_dest_path,
|
||||
action="modify",
|
||||
reason="Target exists as non-regular file",
|
||||
is_sensitive_network=is_net,
|
||||
source_sha256=expected_sha,
|
||||
target_sha256=None
|
||||
))
|
||||
|
||||
return RestorePlan(
|
||||
snapshot_id=manifest.snapshot_id,
|
||||
target_root=target_root_clean,
|
||||
items=plan_items,
|
||||
requires_force=True
|
||||
)
|
||||
|
||||
def create_safety_snapshot(self, target_root: str = "/") -> Tuple[str, str]:
|
||||
"""
|
||||
Create a pre-restore safety snapshot of /etc before any file modifications.
|
||||
Returns (snapshot_id, archive_path).
|
||||
"""
|
||||
hostname = socket.gethostname().split(".")[0]
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
safety_id = f"pre_restore_{hostname}_{timestamp}"
|
||||
|
||||
etc_path = os.path.join(os.path.abspath(target_root), "etc")
|
||||
included_paths = [etc_path] if os.path.isdir(etc_path) else ["/etc"]
|
||||
|
||||
archiver = SnapshotArchiver(target_dir=self.target_dir, compression="gzip")
|
||||
file_entries, files_sha256, uncompressed_bytes, _ = archiver.collect_file_list(included_paths)
|
||||
|
||||
manifest = SnapshotManifest(
|
||||
schema_version="1.0",
|
||||
snapshot_id=safety_id,
|
||||
created_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
hostname=socket.gethostname(),
|
||||
profile="safety_pre_restore",
|
||||
compression="gzip",
|
||||
os=detect_distro().to_dict(),
|
||||
package_manager="none",
|
||||
package_count=0,
|
||||
included_paths=included_paths,
|
||||
stats={
|
||||
"file_count": len(file_entries),
|
||||
"uncompressed_bytes": uncompressed_bytes,
|
||||
"compressed_bytes": 0
|
||||
},
|
||||
files_sha256=files_sha256
|
||||
)
|
||||
|
||||
archive_path = archiver.create_snapshot_archive(safety_id, manifest, file_entries)
|
||||
|
||||
# Verify safety snapshot integrity immediately
|
||||
valid, msg = SnapshotArchiver.verify_archive(archive_path)
|
||||
if not valid:
|
||||
raise RuntimeError(f"Safety snapshot failed integrity check: {msg}")
|
||||
|
||||
return safety_id, archive_path
|
||||
|
||||
def execute_restore(
|
||||
self,
|
||||
plan: RestorePlan,
|
||||
force: bool = False,
|
||||
pid_path: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute file restoration based on RestorePlan.
|
||||
If force=False: raises DryRunException (exit code 5).
|
||||
If force=True: creates safety snapshot, atomically restores files, runs restorecon on SELinux.
|
||||
"""
|
||||
if not force:
|
||||
raise DryRunException(plan)
|
||||
|
||||
lock = SingleInstanceLock(pid_path=pid_path)
|
||||
lock.acquire()
|
||||
|
||||
restored_files: List[str] = []
|
||||
restored_dirs: set = set()
|
||||
safety_id = None
|
||||
safety_path = None
|
||||
|
||||
try:
|
||||
# 1. Capture unalterable pre-restore safety snapshot
|
||||
safety_id, safety_path = self.create_safety_snapshot(target_root=plan.target_root)
|
||||
plan.safety_snapshot_id = safety_id
|
||||
|
||||
archive_path = self._resolve_archive(plan.snapshot_id)
|
||||
|
||||
with tarfile.open(archive_path, "r:*") as tar:
|
||||
for item in plan.items:
|
||||
if item.action not in ("create", "modify"):
|
||||
continue
|
||||
|
||||
# Zip slip security check
|
||||
dest_abs = os.path.abspath(item.abs_path)
|
||||
if not dest_abs.startswith(plan.target_root):
|
||||
raise SecurityError(f"Zip slip path traversal detected: {dest_abs} outside {plan.target_root}")
|
||||
|
||||
member = tar.getmember(item.rel_path)
|
||||
dest_dir = os.path.dirname(dest_abs)
|
||||
os.makedirs(dest_dir, exist_ok=True)
|
||||
restored_dirs.add(dest_dir)
|
||||
|
||||
if member.isreg():
|
||||
f_in = tar.extractfile(member)
|
||||
if not f_in:
|
||||
continue
|
||||
|
||||
tmp_dest = f"{dest_abs}.tmp.{os.getpid()}"
|
||||
try:
|
||||
with open(tmp_dest, "wb") as f_out:
|
||||
while chunk := f_in.read(BUFFER_SIZE):
|
||||
f_out.write(chunk)
|
||||
|
||||
# Apply permissions
|
||||
try:
|
||||
os.chmod(tmp_dest, member.mode)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Apply ownership if root
|
||||
if os.geteuid() == 0:
|
||||
try:
|
||||
os.chown(tmp_dest, member.uid, member.gid)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Atomic replacement
|
||||
os.replace(tmp_dest, dest_abs)
|
||||
restored_files.append(dest_abs)
|
||||
finally:
|
||||
if os.path.exists(tmp_dest):
|
||||
try:
|
||||
os.unlink(tmp_dest)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
elif member.issym():
|
||||
# Symlink restoration
|
||||
tmp_link = f"{dest_abs}.tmp.{os.getpid()}"
|
||||
try:
|
||||
if os.path.lexists(tmp_link):
|
||||
os.unlink(tmp_link)
|
||||
os.symlink(member.linkname, tmp_link)
|
||||
os.replace(tmp_link, dest_abs)
|
||||
restored_files.append(dest_abs)
|
||||
finally:
|
||||
if os.path.lexists(tmp_link):
|
||||
try:
|
||||
os.unlink(tmp_link)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# 2. SELinux context restoration
|
||||
selinux_restored = False
|
||||
if os.path.exists("/sys/fs/selinux") and shutil.which("restorecon"):
|
||||
for d in restored_dirs:
|
||||
try:
|
||||
subprocess.run(["restorecon", "-R", d], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except Exception:
|
||||
pass
|
||||
selinux_restored = True
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"snapshot_id": plan.snapshot_id,
|
||||
"safety_snapshot_id": safety_id,
|
||||
"safety_archive_path": safety_path,
|
||||
"restored_count": len(restored_files),
|
||||
"restored_files": restored_files,
|
||||
"selinux_context_restored": selinux_restored
|
||||
}
|
||||
|
||||
finally:
|
||||
lock.release()
|
||||
Reference in new issue
Block a user