SUMI-OpenCT / scripts /storage_guard.py
MitakaKuma's picture
Update collection metadata and safe collectors
dc0b89d verified
Raw
History Blame Contribute Delete
6.31 kB
#!/usr/bin/env python3
"""Shared, fail-closed storage guards for collection scripts.
The guards enforce both a workspace staging cap and a filesystem free-space
reserve. Checks happen before and during writes so a misleading or missing
Content-Length cannot fill the disk. A workspace-wide advisory lock prevents
the bundled collectors from staging large archives concurrently.
"""
from __future__ import annotations
import fcntl
import os
import shutil
import zipfile
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import BinaryIO, Callable, Iterator
GIB = 1024**3
COPY_CHUNK_BYTES = 1024 * 1024
class StorageLimitError(RuntimeError):
"""Raised before a write would violate a configured storage limit."""
def bytes_in_tree(path: Path) -> int:
"""Return allocated file sizes below *path* without following symlinks."""
if not path.exists():
return 0
total = 0
for item in path.rglob("*"):
if item.is_file() and not item.is_symlink():
total += item.stat().st_size
return total
@dataclass(frozen=True)
class StorageBudget:
"""A staging-directory cap plus a whole-filesystem free-space reserve."""
staging_root: Path
max_local_bytes: int
min_free_bytes: int
@classmethod
def from_gib(
cls,
staging_root: Path,
max_local_gib: float,
min_free_gib: float,
) -> "StorageBudget":
if max_local_gib <= 0:
raise ValueError("max_local_gib must be positive")
if min_free_gib < 0:
raise ValueError("min_free_gib cannot be negative")
root = staging_root.resolve()
root.mkdir(parents=True, exist_ok=True)
return cls(
staging_root=root,
max_local_bytes=int(max_local_gib * GIB),
min_free_bytes=int(min_free_gib * GIB),
)
def check(self, additional_bytes: int = 0, context: str = "operation") -> None:
"""Fail if writing *additional_bytes* would exceed either limit."""
if additional_bytes < 0:
raise ValueError("additional_bytes cannot be negative")
staged = bytes_in_tree(self.staging_root)
if staged + additional_bytes > self.max_local_bytes:
raise StorageLimitError(
f"Refusing {context}: staging would use "
f"{(staged + additional_bytes) / GIB:.2f} GiB, above the "
f"{self.max_local_bytes / GIB:.2f} GiB cap at {self.staging_root}."
)
free = shutil.disk_usage(self.staging_root).free
if free - additional_bytes < self.min_free_bytes:
raise StorageLimitError(
f"Refusing {context}: projected filesystem free space is "
f"{max(0, free - additional_bytes) / GIB:.2f} GiB, below the "
f"{self.min_free_bytes / GIB:.2f} GiB reserve."
)
def copy_bounded(
source: BinaryIO,
destination: Path,
budget: StorageBudget,
*,
expected_bytes: int | None = None,
context: str = "write",
on_chunk: Callable[[int], None] | None = None,
) -> int:
"""Copy a binary stream while checking the budget before every chunk."""
if expected_bytes is not None:
budget.check(expected_bytes, context=context)
else:
budget.check(context=context)
destination.parent.mkdir(parents=True, exist_ok=True)
written = 0
try:
with destination.open("wb") as output:
while True:
chunk = source.read(COPY_CHUNK_BYTES)
if not chunk:
break
budget.check(len(chunk), context=context)
output.write(chunk)
written += len(chunk)
if on_chunk is not None:
on_chunk(len(chunk))
except BaseException:
destination.unlink(missing_ok=True)
raise
if expected_bytes is not None and written != expected_bytes:
destination.unlink(missing_ok=True)
raise RuntimeError(
f"Incomplete {context}: wrote {written} bytes, expected {expected_bytes}."
)
return written
def validated_zip_member(zf: zipfile.ZipFile, member_name: str) -> zipfile.ZipInfo:
"""Resolve a regular ZIP member and reject traversal or link-like entries."""
path = PurePosixPath(member_name)
if path.is_absolute() or ".." in path.parts:
raise RuntimeError(f"Unsafe ZIP member path: {member_name}")
info = zf.getinfo(member_name)
if info.is_dir():
raise RuntimeError(f"Expected a file, found ZIP directory: {member_name}")
unix_mode = info.external_attr >> 16
if unix_mode and (unix_mode & 0o170000) not in (0, 0o100000):
raise RuntimeError(f"Refusing non-regular ZIP member: {member_name}")
return info
def extract_member_bounded(
zf: zipfile.ZipFile,
member_name: str,
destination: Path,
budget: StorageBudget,
) -> int:
"""Extract one regular ZIP member with traversal and storage checks."""
info = validated_zip_member(zf, member_name)
with zf.open(info, "r") as source:
return copy_bounded(
source,
destination,
budget,
expected_bytes=info.file_size,
context=f"extracting {member_name}",
)
@contextmanager
def exclusive_collection_lock(lock_path: Path) -> Iterator[None]:
"""Prevent bundled collectors from running large staging jobs together."""
path = lock_path.resolve()
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a+", encoding="utf-8") as lock_file:
try:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
lock_file.seek(0)
owner = lock_file.read().strip() or "another process"
raise RuntimeError(f"Collection lock {path} is held by {owner}.") from exc
lock_file.seek(0)
lock_file.truncate()
lock_file.write(f"pid={os.getpid()}")
lock_file.flush()
try:
yield
finally:
lock_file.seek(0)
lock_file.truncate()
lock_file.flush()
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)