| |
| """Safely verify and restore independently compressed RoboDojo Assets shards.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import concurrent.futures |
| import ctypes |
| import errno |
| import fcntl |
| import hashlib |
| import json |
| import os |
| from pathlib import Path, PurePosixPath |
| import shutil |
| import stat |
| import subprocess |
| import sys |
| import tarfile |
| from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple |
| import uuid |
|
|
|
|
| READ_BLOCK = 8 * 1024 * 1024 |
| RENAME_NOREPLACE = 1 |
| RENAME_EXCHANGE = 2 |
|
|
|
|
| def renameat2(src_dir_fd: int, src: str, dst_dir_fd: int, dst: str, flags: int) -> None: |
| libc = ctypes.CDLL(None, use_errno=True) |
| function = getattr(libc, "renameat2", None) |
| if function is None: |
| raise OSError(errno.ENOSYS, "libc does not expose renameat2", dst) |
| function.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] |
| function.restype = ctypes.c_int |
| result = function(src_dir_fd, os.fsencode(src), dst_dir_fd, os.fsencode(dst), flags) |
| if result != 0: |
| error_number = ctypes.get_errno() |
| raise OSError(error_number, os.strerror(error_number), dst) |
|
|
|
|
| class PublicationRecoveryError(RuntimeError): |
| """The old tree may remain in the private staging directory.""" |
|
|
|
|
| class PublicationRolledBack(RuntimeError): |
| """Publication failed, but the original tree was restored safely.""" |
|
|
| def __init__(self, original: BaseException): |
| super().__init__(f"publication rolled back after: {original}") |
| self.original = original |
|
|
|
|
| def renameat2_unsupported(error: OSError) -> bool: |
| return error.errno in { |
| errno.EINVAL, |
| errno.ENOSYS, |
| getattr(errno, "EOPNOTSUPP", errno.EINVAL), |
| getattr(errno, "ENOTSUP", errno.EINVAL), |
| } |
|
|
|
|
| def publish_new(final_stage_fd: int, output_fd: int) -> None: |
| try: |
| renameat2(final_stage_fd, "Assets", output_fd, "Assets", RENAME_NOREPLACE) |
| except OSError as error: |
| if not renameat2_unsupported(error): |
| raise |
| if lstat_at(output_fd, "Assets") is not None: |
| raise RuntimeError("Assets appeared before fallback publication") |
| os.mkdir("Assets", 0o700, dir_fd=output_fd) |
| reservation = lstat_at(output_fd, "Assets") |
| if reservation is None or not stat.S_ISDIR(reservation.st_mode): |
| raise RuntimeError("failed to reserve Assets for fallback publication") |
| try: |
| current = lstat_at(output_fd, "Assets") |
| if current is None or (current.st_dev, current.st_ino) != (reservation.st_dev, reservation.st_ino): |
| raise RuntimeError("Assets reservation changed before fallback publication") |
| os.rename("Assets", "Assets", src_dir_fd=final_stage_fd, dst_dir_fd=output_fd) |
| except BaseException: |
| current = lstat_at(output_fd, "Assets") |
| if current is not None and (current.st_dev, current.st_ino) == ( |
| reservation.st_dev, |
| reservation.st_ino, |
| ): |
| try: |
| os.rmdir("Assets", dir_fd=output_fd) |
| except OSError: |
| pass |
| raise |
|
|
|
|
| def publish_force(final_stage_fd: int, output_fd: int, backup_name: str) -> None: |
| renameat2(final_stage_fd, "Assets", output_fd, "Assets", RENAME_EXCHANGE) |
| try: |
| os.rename("Assets", backup_name, src_dir_fd=final_stage_fd, dst_dir_fd=output_fd) |
| except BaseException as publication_error: |
| try: |
| renameat2(final_stage_fd, "Assets", output_fd, "Assets", RENAME_EXCHANGE) |
| except BaseException as rollback_error: |
| raise PublicationRecoveryError( |
| f"atomic publication failed and rollback also failed: {rollback_error}" |
| ) from publication_error |
| raise PublicationRolledBack(publication_error) from publication_error |
|
|
|
|
| def lexists(path: Path) -> bool: |
| return os.path.lexists(str(path)) |
|
|
|
|
| def sha256_fd(fd: int) -> str: |
| os.lseek(fd, 0, os.SEEK_SET) |
| info = os.fstat(fd) |
| if not stat.S_ISREG(info.st_mode): |
| raise RuntimeError("file descriptor is not a regular file") |
| digest = hashlib.sha256() |
| while True: |
| block = os.read(fd, READ_BLOCK) |
| if not block: |
| break |
| digest.update(block) |
| return digest.hexdigest() |
|
|
|
|
| def sha256_regular_file(path: Path) -> str: |
| nofollow = getattr(os, "O_NOFOLLOW", 0) |
| if not nofollow: |
| raise RuntimeError("this restore tool requires O_NOFOLLOW support") |
| fd = os.open(str(path), os.O_RDONLY | nofollow) |
| try: |
| return sha256_fd(fd) |
| finally: |
| os.close(fd) |
|
|
|
|
| def validate_payload_path(name: str) -> Tuple[str, ...]: |
| if not name or "\x00" in name or any(ord(char) < 32 or ord(char) == 127 for char in name): |
| raise RuntimeError(f"unsafe control character in payload path: {name!r}") |
| pure = PurePosixPath(name) |
| if pure.is_absolute() or pure.as_posix() != name: |
| raise RuntimeError(f"non-canonical payload path: {name!r}") |
| parts = pure.parts |
| if len(parts) < 2 or parts[0] != "Assets" or any(part in ("", ".", "..") for part in parts): |
| raise RuntimeError(f"unsafe payload path: {name!r}") |
| return parts |
|
|
|
|
| def validate_repo_relative_path(name: str, expected_root: str) -> Tuple[str, ...]: |
| if not name or "\x00" in name or any(ord(char) < 32 or ord(char) == 127 for char in name): |
| raise RuntimeError(f"unsafe repository path: {name!r}") |
| pure = PurePosixPath(name) |
| if pure.is_absolute() or pure.as_posix() != name: |
| raise RuntimeError(f"non-canonical repository path: {name!r}") |
| parts = pure.parts |
| if len(parts) != 2 or parts[0] != expected_root or any(part in ("", ".", "..") for part in parts): |
| raise RuntimeError(f"invalid {expected_root} path: {name!r}") |
| return parts |
|
|
|
|
| def require_regular_repo_file(repo_dir: Path, relative: str, expected_root: str) -> Path: |
| parts = validate_repo_relative_path(relative, expected_root) |
| current = repo_dir |
| for part in parts[:-1]: |
| current = current / part |
| info = os.lstat(str(current)) |
| if not stat.S_ISDIR(info.st_mode): |
| raise RuntimeError(f"repository parent is not a real directory: {current}") |
| path = repo_dir.joinpath(*parts) |
| info = os.lstat(str(path)) |
| if not stat.S_ISREG(info.st_mode): |
| raise RuntimeError(f"repository entry is not a regular file: {path}") |
| return path |
|
|
|
|
| def read_regular_at(directory_fd: int, name: str, max_bytes: int = 64 * 1024 * 1024) -> bytes: |
| fd = os.open( |
| name, |
| os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0), |
| dir_fd=directory_fd, |
| ) |
| try: |
| info = os.fstat(fd) |
| if not stat.S_ISREG(info.st_mode): |
| raise RuntimeError(f"repository entry is not a regular file: {name}") |
| if info.st_size > max_bytes: |
| raise RuntimeError(f"repository metadata is unexpectedly large: {name}") |
| chunks: List[bytes] = [] |
| remaining = max_bytes + 1 |
| while remaining > 0: |
| block = os.read(fd, min(1024 * 1024, remaining)) |
| if not block: |
| break |
| chunks.append(block) |
| remaining -= len(block) |
| raw = b"".join(chunks) |
| if len(raw) > max_bytes: |
| raise RuntimeError(f"repository metadata exceeds limit: {name}") |
| return raw |
| finally: |
| os.close(fd) |
|
|
|
|
| def parse_list0(raw: bytes, label: str) -> List[str]: |
| if not raw or not raw.endswith(b"\x00"): |
| raise RuntimeError(f"NUL-delimited list must end in NUL: {label}") |
| chunks = raw[:-1].split(b"\x00") |
| if any(not chunk for chunk in chunks): |
| raise RuntimeError(f"empty member in list: {label}") |
| names = [chunk.decode("utf-8", errors="strict") for chunk in chunks] |
| for name in names: |
| validate_payload_path(name) |
| return names |
|
|
|
|
| def parse_file_hashes(raw: bytes, label: str) -> Dict[str, str]: |
| entries: Dict[str, str] = {} |
| text = raw.decode("utf-8", errors="strict") |
| for number, line in enumerate(text.splitlines(), 1): |
| if len(line) < 67 or line[64:66] != " ": |
| raise RuntimeError(f"invalid FILES.sha256 line {number}") |
| digest = line[:64] |
| name = line[66:] |
| if digest != digest.lower() or any(char not in "0123456789abcdef" for char in digest): |
| raise RuntimeError(f"invalid SHA-256 digest on line {number}") |
| validate_payload_path(name) |
| if name in entries: |
| raise RuntimeError(f"duplicate path in FILES.sha256: {name}") |
| entries[name] = digest |
| if not entries: |
| raise RuntimeError("FILES.sha256 is empty") |
| return entries |
|
|
|
|
| def check_leaf_ancestor_conflicts(names: Iterable[str]) -> None: |
| name_set = set(names) |
| for name in name_set: |
| parts = PurePosixPath(name).parts |
| for depth in range(1, len(parts)): |
| ancestor = "/".join(parts[:depth]) |
| if ancestor in name_set: |
| raise RuntimeError(f"payload leaf/ancestor conflict: {ancestor!r} and {name!r}") |
|
|
|
|
| def load_metadata( |
| repo_dir: Path, repo_fd: int |
| ) -> Tuple[Dict[str, Any], List[Dict[str, Any]], Dict[str, str], Dict[str, int]]: |
| manifest_raw = read_regular_at(repo_fd, "MANIFEST.json") |
| hashes_raw = read_regular_at(repo_fd, "FILES.sha256") |
| manifest = json.loads(manifest_raw.decode("utf-8", errors="strict")) |
| if manifest.get("format_version") != 1: |
| raise RuntimeError("unsupported manifest format_version") |
| shards = manifest.get("shards") |
| if not isinstance(shards, list) or not shards: |
| raise RuntimeError("manifest shards must be a non-empty list") |
| if manifest.get("shard_count") != len(shards): |
| raise RuntimeError("manifest shard_count mismatch") |
|
|
| file_hashes = parse_file_hashes(hashes_raw, "FILES.sha256") |
| directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) |
| data_fd = os.open("data", directory_flags, dir_fd=repo_fd) |
| lists_fd = os.open("lists", directory_flags, dir_fd=repo_fd) |
| all_names: List[str] = [] |
| path_to_shard: Dict[str, int] = {} |
| archive_paths = set() |
| list_paths = set() |
| normalized_shards: List[Dict[str, Any]] = [] |
| for position, raw_shard in enumerate(shards): |
| if not isinstance(raw_shard, dict) or raw_shard.get("index") != position: |
| raise RuntimeError(f"invalid shard index at position {position}") |
| archive_rel = raw_shard.get("archive") |
| list_rel = raw_shard.get("list") |
| if not isinstance(archive_rel, str) or not isinstance(list_rel, str): |
| raise RuntimeError(f"missing archive/list path for shard {position}") |
| if archive_rel in archive_paths or list_rel in list_paths: |
| raise RuntimeError("duplicate archive or list path in manifest") |
| archive_paths.add(archive_rel) |
| list_paths.add(list_rel) |
| archive_parts = validate_repo_relative_path(archive_rel, "data") |
| list_parts = validate_repo_relative_path(list_rel, "lists") |
| archive = repo_dir / archive_rel |
| list_path = repo_dir / list_rel |
| archive_fd = os.open( |
| archive_parts[1], |
| os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0), |
| dir_fd=data_fd, |
| ) |
| archive_info = os.fstat(archive_fd) |
| if not stat.S_ISREG(archive_info.st_mode): |
| os.close(archive_fd) |
| raise RuntimeError(f"archive is not a regular file: {archive}") |
| names = parse_list0(read_regular_at(lists_fd, list_parts[1]), list_rel) |
| if raw_shard.get("file_count") != len(names): |
| raise RuntimeError(f"file_count mismatch for shard {position}") |
| if not isinstance(raw_shard.get("input_bytes"), int) or raw_shard["input_bytes"] < 0: |
| raise RuntimeError(f"invalid input_bytes for shard {position}") |
| if not isinstance(raw_shard.get("archive_bytes"), int) or raw_shard["archive_bytes"] <= 0: |
| raise RuntimeError(f"invalid archive_bytes for shard {position}") |
| digest = raw_shard.get("sha256") |
| if not isinstance(digest, str) or len(digest) != 64 or any( |
| char not in "0123456789abcdef" for char in digest |
| ): |
| raise RuntimeError(f"invalid archive SHA-256 for shard {position}") |
| for name in names: |
| if name in path_to_shard: |
| raise RuntimeError(f"payload path appears in multiple shards: {name}") |
| path_to_shard[name] = position |
| all_names.extend(names) |
| normalized = dict(raw_shard) |
| normalized["archive_path"] = archive |
| normalized["archive_fd"] = archive_fd |
| normalized["list_path"] = list_path |
| normalized["names"] = names |
| normalized_shards.append(normalized) |
|
|
| os.close(data_fd) |
| os.close(lists_fd) |
|
|
| if set(all_names) != set(file_hashes): |
| missing = sorted(set(file_hashes) - set(all_names))[:10] |
| extra = sorted(set(all_names) - set(file_hashes))[:10] |
| raise RuntimeError(f"list0/FILES.sha256 path mismatch; missing={missing}, extra={extra}") |
| if len(all_names) != len(file_hashes): |
| raise RuntimeError("payload paths are not globally unique") |
| check_leaf_ancestor_conflicts(all_names) |
| if manifest.get("source_file_count") != len(file_hashes): |
| raise RuntimeError("manifest source_file_count mismatch") |
| if sum(int(shard["input_bytes"]) for shard in normalized_shards) != manifest.get("source_bytes"): |
| raise RuntimeError("manifest source_bytes mismatch") |
| return manifest, normalized_shards, file_hashes, path_to_shard |
|
|
|
|
| def validate_tar_member(member: tarfile.TarInfo, expected_name: str) -> None: |
| if member.name != expected_name: |
| raise RuntimeError(f"archive member mismatch: expected {expected_name!r}, got {member.name!r}") |
| validate_payload_path(member.name) |
| sparse = getattr(member, "sparse", None) |
| sparse_pax = any(str(key).startswith("GNU.sparse.") for key in member.pax_headers) |
| if not member.isreg() or member.linkname not in ("", None) or sparse or sparse_pax: |
| raise RuntimeError(f"non-regular/link/sparse archive member rejected: {member.name!r}") |
| if member.size < 0: |
| raise RuntimeError(f"negative archive member size: {member.name!r}") |
|
|
|
|
| def open_tar_stream(archive_fd: int) -> Tuple[subprocess.Popen[bytes], tarfile.TarFile]: |
| os.lseek(archive_fd, 0, os.SEEK_SET) |
| process = subprocess.Popen( |
| ["zstd", "--decompress", "--stdout", "--quiet"], |
| stdin=archive_fd, |
| stdout=subprocess.PIPE, |
| stderr=subprocess.PIPE, |
| ) |
| if process.stdout is None: |
| process.kill() |
| raise RuntimeError("failed to open zstd stdout") |
| try: |
| stream = tarfile.open(fileobj=process.stdout, mode="r|") |
| except Exception: |
| process.kill() |
| process.communicate() |
| raise |
| return process, stream |
|
|
|
|
| def finish_tar_stream(process: subprocess.Popen[bytes], stream: tarfile.TarFile) -> None: |
| stream.close() |
| if process.stdout is not None: |
| process.stdout.close() |
| stderr = process.stderr.read() if process.stderr is not None else b"" |
| returncode = process.wait() |
| if returncode != 0: |
| raise RuntimeError(f"zstd failed with code {returncode}: {stderr.decode(errors='replace')[-2000:]}") |
|
|
|
|
| def abort_tar_stream(process: subprocess.Popen[bytes], stream: tarfile.TarFile) -> None: |
| try: |
| stream.close() |
| finally: |
| process.kill() |
| process.communicate() |
|
|
|
|
| def preflight_shard(shard: Dict[str, Any]) -> Dict[str, int]: |
| archive = Path(shard["archive_path"]) |
| archive_fd = int(shard["archive_fd"]) |
| info = os.fstat(archive_fd) |
| if not stat.S_ISREG(info.st_mode) or info.st_size != int(shard["archive_bytes"]): |
| raise RuntimeError(f"archive size/type mismatch: {archive}") |
| if sha256_fd(archive_fd) != shard["sha256"]: |
| raise RuntimeError(f"archive SHA-256 mismatch: {archive}") |
|
|
| process, stream = open_tar_stream(archive_fd) |
| expected = list(shard["names"]) |
| sizes: Dict[str, int] = {} |
| try: |
| count = 0 |
| total = 0 |
| for member in stream: |
| if count >= len(expected): |
| raise RuntimeError(f"unexpected extra archive member: {member.name!r}") |
| validate_tar_member(member, expected[count]) |
| sizes[member.name] = member.size |
| count += 1 |
| total += member.size |
| if count != len(expected): |
| raise RuntimeError(f"archive member count mismatch: {archive}") |
| if total != int(shard["input_bytes"]): |
| raise RuntimeError(f"archive input byte total mismatch: {archive}") |
| finish_tar_stream(process, stream) |
| except Exception: |
| if process.poll() is None: |
| abort_tar_stream(process, stream) |
| raise |
| return sizes |
|
|
|
|
| def open_or_create_directory_chain(path: Path) -> int: |
| absolute = Path(os.path.abspath(str(path))) |
| if absolute.anchor != "/": |
| raise RuntimeError(f"output path must be absolute on Linux: {absolute}") |
| flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) |
| current_fd = os.open("/", flags) |
| for part in absolute.parts[1:]: |
| try: |
| os.mkdir(part, 0o755, dir_fd=current_fd) |
| except FileExistsError: |
| pass |
| try: |
| next_fd = os.open(part, flags, dir_fd=current_fd) |
| except Exception: |
| os.close(current_fd) |
| raise RuntimeError(f"output path component is not a real directory: {absolute}") |
| os.close(current_fd) |
| current_fd = next_fd |
| return current_fd |
|
|
|
|
| def open_existing_directory_chain(path: Path) -> int: |
| absolute = Path(os.path.abspath(str(path))) |
| if absolute.anchor != "/": |
| raise RuntimeError(f"repository path must be absolute on Linux: {absolute}") |
| flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) |
| current_fd = os.open("/", flags) |
| for part in absolute.parts[1:]: |
| try: |
| next_fd = os.open(part, flags, dir_fd=current_fd) |
| except Exception: |
| os.close(current_fd) |
| raise RuntimeError(f"repository path component is not a real directory: {absolute}") |
| os.close(current_fd) |
| current_fd = next_fd |
| return current_fd |
|
|
|
|
| def lstat_at(directory_fd: int, name: str) -> Optional[os.stat_result]: |
| try: |
| return os.stat(name, dir_fd=directory_fd, follow_symlinks=False) |
| except FileNotFoundError: |
| return None |
|
|
|
|
| def ensure_safe_parents(root: Path, parts: Sequence[str]) -> Path: |
| current = root |
| for part in parts: |
| current = current / part |
| try: |
| os.mkdir(str(current), 0o755) |
| except FileExistsError: |
| info = os.lstat(str(current)) |
| if not stat.S_ISDIR(info.st_mode): |
| raise RuntimeError(f"restore parent is not a real directory: {current}") |
| return current |
|
|
|
|
| def write_member(source: Any, destination: Path, expected_size: int) -> None: |
| flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) |
| fd = os.open(str(destination), flags, 0o644) |
| written = 0 |
| try: |
| with os.fdopen(fd, "wb") as output: |
| fd = -1 |
| while True: |
| block = source.read(READ_BLOCK) |
| if not block: |
| break |
| output.write(block) |
| written += len(block) |
| except Exception: |
| if fd >= 0: |
| os.close(fd) |
| try: |
| destination.unlink() |
| except FileNotFoundError: |
| pass |
| raise |
| if written != expected_size: |
| destination.unlink() |
| raise RuntimeError(f"short archive member: {destination} ({written} != {expected_size})") |
|
|
|
|
| def extract_shard(shard: Dict[str, Any], shard_root: Path) -> int: |
| os.mkdir(str(shard_root), 0o700) |
| process, stream = open_tar_stream(int(shard["archive_fd"])) |
| expected = list(shard["names"]) |
| total = 0 |
| try: |
| count = 0 |
| for member in stream: |
| if count >= len(expected): |
| raise RuntimeError(f"unexpected extra archive member: {member.name!r}") |
| validate_tar_member(member, expected[count]) |
| parts = validate_payload_path(member.name) |
| parent = ensure_safe_parents(shard_root, parts[:-1]) |
| destination = parent / parts[-1] |
| source = stream.extractfile(member) |
| if source is None: |
| raise RuntimeError(f"unable to read regular member: {member.name}") |
| with source: |
| write_member(source, destination, member.size) |
| total += member.size |
| count += 1 |
| if count != len(expected) or total != int(shard["input_bytes"]): |
| raise RuntimeError(f"archive changed between preflight and extraction: {shard['archive_path']}") |
| finish_tar_stream(process, stream) |
| except Exception: |
| if process.poll() is None: |
| abort_tar_stream(process, stream) |
| raise |
| return count |
|
|
|
|
| def scan_tree(root: Path) -> List[str]: |
| names: List[str] = [] |
| for directory, dirnames, filenames in os.walk(str(root), topdown=True, followlinks=False): |
| directory_path = Path(directory) |
| for name in dirnames: |
| path = directory_path / name |
| info = os.lstat(str(path)) |
| if not stat.S_ISDIR(info.st_mode): |
| raise RuntimeError(f"non-directory node in restored tree: {path}") |
| for name in filenames: |
| path = directory_path / name |
| info = os.lstat(str(path)) |
| if not stat.S_ISREG(info.st_mode): |
| raise RuntimeError(f"non-regular node in restored tree: {path}") |
| names.append(path.relative_to(root.parent).as_posix()) |
| return sorted(names) |
|
|
|
|
| def main() -> int: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--repo-dir", type=Path, default=Path(__file__).absolute().parent) |
| parser.add_argument("--output-dir", type=Path, required=True) |
| parser.add_argument("--workers", type=int, default=4, help="parallel extraction workers") |
| parser.add_argument("--hash-workers", type=int, default=16) |
| parser.add_argument("--force", action="store_true", help="atomically replace an existing real Assets directory") |
| parser.add_argument("--skip-file-check", action="store_true", help="skip content hashes, never structural checks") |
| args = parser.parse_args() |
|
|
| if shutil.which("zstd") is None: |
| parser.error("zstd is required") |
| if not getattr(os, "O_NOFOLLOW", 0): |
| parser.error("this platform does not provide O_NOFOLLOW") |
| if args.workers < 1 or args.hash_workers < 1: |
| parser.error("worker counts must be positive") |
|
|
| repo_dir = Path(os.path.abspath(str(args.repo_dir))) |
| repo_fd = open_existing_directory_chain(repo_dir) |
| try: |
| manifest, shards, file_hashes, path_to_shard = load_metadata(repo_dir, repo_fd) |
| finally: |
| os.close(repo_fd) |
| print(f"Preflighting {len(shards)} archives before creating output...", flush=True) |
| all_sizes: Dict[str, int] = {} |
| with concurrent.futures.ThreadPoolExecutor(max_workers=min(args.workers, len(shards))) as pool: |
| for shard, sizes in zip(shards, pool.map(preflight_shard, shards)): |
| all_sizes.update(sizes) |
| print(f" OK {Path(shard['archive_path']).name}", flush=True) |
| if set(all_sizes) != set(file_hashes) or sum(all_sizes.values()) != int(manifest["source_bytes"]): |
| raise RuntimeError("preflight payload set/size mismatch") |
|
|
| output_dir = Path(os.path.abspath(str(args.output_dir))) |
| target_assets = output_dir / "Assets" |
| output_fd = open_or_create_directory_chain(output_dir) |
| lock_name = ".robodojo-restore.lock" |
| lock_fd: Optional[int] = None |
| stage_root: Optional[Path] = None |
| stage_recovery_path: Optional[Path] = None |
| preserve_stage = False |
| backup: Optional[Path] = None |
| backup_name: Optional[str] = None |
|
|
| try: |
| try: |
| lock_fd = os.open( |
| lock_name, |
| os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), |
| 0o600, |
| dir_fd=output_fd, |
| ) |
| lock_info = os.fstat(lock_fd) |
| if not stat.S_ISREG(lock_info.st_mode): |
| raise RuntimeError(f"restore lock is not a regular file in {output_dir}: {lock_name}") |
| fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| except BlockingIOError: |
| raise RuntimeError(f"another restore process holds the lock in {output_dir}") |
|
|
| initial_target = lstat_at(output_fd, "Assets") |
| if initial_target is not None: |
| if not args.force: |
| raise RuntimeError(f"{target_assets} already exists; use --force for atomic replacement") |
| if not stat.S_ISDIR(initial_target.st_mode): |
| raise RuntimeError( |
| f"refusing --force because existing Assets is not a real directory: {target_assets}" |
| ) |
|
|
| proc_fd_root = Path(f"/proc/self/fd/{output_fd}") |
| if not proc_fd_root.is_dir(): |
| raise RuntimeError("Linux /proc/self/fd is required for pinned output directory access") |
| stage_name = f".robodojo-restore-{uuid.uuid4().hex}" |
| os.mkdir(stage_name, 0o700, dir_fd=output_fd) |
| stage_root = proc_fd_root / stage_name |
| stage_recovery_path = output_dir / stage_name |
| shard_stage = stage_root / "shards" |
| final_stage = stage_root / "final" |
| os.mkdir(str(shard_stage), 0o700) |
| os.mkdir(str(final_stage), 0o700) |
| final_assets = final_stage / "Assets" |
| os.mkdir(str(final_assets), 0o755) |
|
|
| print(f"Extracting {len(shards)} isolated shards with {args.workers} workers...", flush=True) |
| shard_roots = [shard_stage / f"{index:03d}" for index in range(len(shards))] |
| with concurrent.futures.ThreadPoolExecutor(max_workers=min(args.workers, len(shards))) as pool: |
| for shard, count in zip(shards, pool.map(extract_shard, shards, shard_roots)): |
| print(f" staged {Path(shard['archive_path']).name} ({count:,} files)", flush=True) |
|
|
| print("Rechecking pinned archive descriptors after extraction...", flush=True) |
| with concurrent.futures.ThreadPoolExecutor(max_workers=min(args.workers, len(shards))) as pool: |
| observed_hashes = list(pool.map(lambda shard: sha256_fd(int(shard["archive_fd"])), shards)) |
| for shard, observed in zip(shards, observed_hashes): |
| if observed != shard["sha256"]: |
| raise RuntimeError(f"archive changed during restore: {shard['archive_path']}") |
|
|
| print("Merging shards into a single verified staging tree...", flush=True) |
| for name in sorted(file_hashes): |
| parts = validate_payload_path(name) |
| shard_index = path_to_shard[name] |
| source = shard_roots[shard_index].joinpath(*parts) |
| info = os.lstat(str(source)) |
| if not stat.S_ISREG(info.st_mode) or info.st_size != all_sizes[name]: |
| raise RuntimeError(f"staged file type/size mismatch: {name}") |
| parent = ensure_safe_parents(final_stage, parts[:-1]) |
| destination = parent / parts[-1] |
| if lexists(destination): |
| raise RuntimeError(f"merge destination already exists: {destination}") |
| os.rename(str(source), str(destination)) |
|
|
| actual_paths = scan_tree(final_assets) |
| expected_paths = sorted(file_hashes) |
| if actual_paths != expected_paths: |
| raise RuntimeError("restored path/type set differs from FILES.sha256") |
|
|
| if not args.skip_file_check: |
| print(f"Hashing {len(file_hashes):,} staged files...", flush=True) |
|
|
| def verify_file(name: str) -> Optional[str]: |
| path = final_stage.joinpath(*validate_payload_path(name)) |
| return None if sha256_regular_file(path) == file_hashes[name] else name |
|
|
| failures: List[str] = [] |
| with concurrent.futures.ThreadPoolExecutor(max_workers=args.hash_workers) as pool: |
| for failure in pool.map(verify_file, expected_paths): |
| if failure is not None: |
| failures.append(failure) |
| if failures: |
| raise RuntimeError(f"{len(failures)} staged files failed SHA-256: {failures[:20]}") |
|
|
| current_target = lstat_at(output_fd, "Assets") |
| if initial_target is None: |
| if current_target is not None: |
| raise RuntimeError("Assets appeared during restore; refusing to replace concurrent output") |
| final_stage_fd = os.open( |
| str(final_stage), |
| os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0), |
| ) |
| try: |
| publish_new(final_stage_fd, output_fd) |
| finally: |
| os.close(final_stage_fd) |
| else: |
| if current_target is None or ( |
| current_target.st_dev, |
| current_target.st_ino, |
| current_target.st_mode, |
| ) != ( |
| initial_target.st_dev, |
| initial_target.st_ino, |
| initial_target.st_mode, |
| ): |
| raise RuntimeError("existing Assets changed during restore; refusing atomic replacement") |
| backup_name = f"Assets.backup.{uuid.uuid4().hex}" |
| backup = output_dir / backup_name |
| final_stage_fd = os.open( |
| str(final_stage), |
| os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0), |
| ) |
| try: |
| preserve_stage = True |
| try: |
| publish_force(final_stage_fd, output_fd, backup_name) |
| except PublicationRolledBack as error: |
| preserve_stage = False |
| raise error.original |
| except OSError: |
| preserve_stage = False |
| raise |
| except PublicationRecoveryError as error: |
| raise RuntimeError( |
| f"{error}; recovery staging preserved at {stage_recovery_path}" |
| ) from error |
| preserve_stage = False |
| finally: |
| os.close(final_stage_fd) |
| finally: |
| if stage_root is not None and preserve_stage: |
| print(f"Recovery staging preserved at {stage_recovery_path}", file=sys.stderr, flush=True) |
| if stage_root is not None and not preserve_stage: |
| shutil.rmtree(str(stage_root), ignore_errors=True) |
| if lock_fd is not None: |
| os.close(lock_fd) |
| os.close(output_fd) |
| for shard in shards: |
| try: |
| os.close(int(shard["archive_fd"])) |
| except OSError: |
| pass |
|
|
| if backup is not None: |
| print(f"Previous Assets preserved at {backup}", flush=True) |
| if args.skip_file_check: |
| print("RESTORE COMPLETE; STRUCTURE VERIFIED; CONTENT HASH CHECK SKIPPED", flush=True) |
| else: |
| print("RESTORE VERIFIED", flush=True) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|