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
|
||||
|
||||
Reference in new issue
Block a user