335 lines
13 KiB
Python
335 lines
13 KiB
Python
"""Lossless, restartable closeout for an explicitly terminal owned job.
|
|
|
|
No age-based discovery, shared source cleanup or archive eviction. The caller
|
|
must release all producers and confirm delivery before calling closeout().
|
|
Archive roots are separately retained persistent data, outside job roots.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import shutil
|
|
import stat
|
|
import zipfile
|
|
from contextlib import contextmanager
|
|
from pathlib import Path, PurePosixPath
|
|
from uuid import uuid4
|
|
|
|
GIB = 1024**3
|
|
|
|
|
|
def digest(path):
|
|
with Path(path).open("rb") as f:
|
|
return hashlib.file_digest(f, "sha256").hexdigest()
|
|
|
|
|
|
def regular(path):
|
|
s = path.lstat()
|
|
if not stat.S_ISREG(s.st_mode) or getattr(s, "st_file_attributes", 0) & 0x400:
|
|
raise ValueError("Unsafe evidence file")
|
|
return s
|
|
|
|
|
|
def confined(root, relative):
|
|
p = PurePosixPath(relative)
|
|
if p.is_absolute() or not p.parts or ".." in p.parts or "\\" in relative or ":" in relative:
|
|
raise ValueError("Unsafe evidence path")
|
|
target = root.joinpath(*p.parts)
|
|
if not target.resolve().is_relative_to(root.resolve()):
|
|
raise ValueError("Evidence path escaped root")
|
|
for parent in [target, *target.parents]:
|
|
if parent == root.parent:
|
|
break
|
|
if parent.exists() and (
|
|
parent.is_symlink() or getattr(parent.lstat(), "st_file_attributes", 0) & 0x400
|
|
):
|
|
raise ValueError("Evidence links are not owned files")
|
|
return target
|
|
|
|
|
|
def canonical(path):
|
|
path = Path(path).expanduser().absolute()
|
|
for part in [path, *path.parents]:
|
|
if part.is_symlink() or (
|
|
part.exists() and getattr(part.lstat(), "st_file_attributes", 0) & 0x400
|
|
):
|
|
raise ValueError("Linked evidence owner path")
|
|
return path
|
|
|
|
|
|
def atomic_json(path, value):
|
|
canonical(path)
|
|
if path.exists():
|
|
regular(path)
|
|
tmp = path.with_name(path.name + "." + uuid4().hex + ".tmp")
|
|
with tmp.open("x", encoding="utf-8") as f:
|
|
json.dump(value, f, ensure_ascii=False, sort_keys=True)
|
|
f.flush()
|
|
os.fsync(f.fileno())
|
|
os.replace(tmp, path)
|
|
|
|
|
|
@contextmanager
|
|
def lock(root):
|
|
root = canonical(root)
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
path = root / "owner.lock"
|
|
canonical(path)
|
|
if path.exists():
|
|
regular(path)
|
|
with path.open("a+b") as f:
|
|
if f.tell() == 0:
|
|
f.write(b"0")
|
|
f.flush()
|
|
f.seek(0)
|
|
if os.name == "nt":
|
|
import msvcrt
|
|
|
|
msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
|
|
else:
|
|
import fcntl
|
|
|
|
fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
try:
|
|
yield
|
|
finally:
|
|
f.seek(0)
|
|
if os.name == "nt":
|
|
msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
|
|
else:
|
|
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
|
|
|
|
|
|
def usage(root):
|
|
total = 0
|
|
for base, dirs, files in os.walk(root, followlinks=False):
|
|
for name in dirs:
|
|
p = Path(base) / name
|
|
if p.is_symlink() or getattr(p.lstat(), "st_file_attributes", 0) & 0x400:
|
|
raise ValueError("Unexpected linked evidence directory")
|
|
for name in files:
|
|
total += regular(Path(base) / name).st_size
|
|
return total
|
|
|
|
|
|
def closeout(root, store, owner, *, keep=(), limit=128 * GIB, reserve=40 * GIB):
|
|
"""Archive all files, verify every member, unlink exact non-kept copies.
|
|
|
|
Owner is a stable identity (job key/revision), never a caller-chosen path.
|
|
Interrupted unlink resumes only from durable intent and a verified archive.
|
|
"""
|
|
root, store = canonical(root), canonical(store)
|
|
if not owner or any(
|
|
c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_" for c in owner
|
|
):
|
|
raise ValueError("Invalid closeout owner")
|
|
if root == store or store.is_relative_to(root) or root.is_relative_to(store):
|
|
raise ValueError("Archive and working data must have separate ownership")
|
|
control = canonical(store / owner)
|
|
control.mkdir(parents=True, exist_ok=True)
|
|
with lock(store):
|
|
state_path = control / "closeout.json"
|
|
archive = control / "evidence.zip"
|
|
journal = control / "deletions.jsonl"
|
|
for p in (state_path, archive, journal, control / "evidence.partial.zip"):
|
|
canonical(p)
|
|
if p.exists():
|
|
regular(p)
|
|
if (root / "RETAIN.json").exists():
|
|
raise ValueError("Job is explicitly pinned")
|
|
if state_path.exists():
|
|
state = json.loads(state_path.read_text())
|
|
if state["root"] != str(root) or state["owner"] != owner:
|
|
raise ValueError("Closeout owner changed")
|
|
if state["phase"] == "complete":
|
|
if digest(archive) != state["archive_sha256"]:
|
|
raise ValueError("Retained archive changed")
|
|
atomic_json(
|
|
root / "ARCHIVED.json",
|
|
{k: state[k] for k in ("owner", "archive", "archive_sha256", "retention")},
|
|
)
|
|
return state
|
|
else:
|
|
files = []
|
|
for base, dirs, names in os.walk(root, followlinks=False):
|
|
for name in dirs:
|
|
confined(root, (Path(base) / name).relative_to(root).as_posix())
|
|
for name in names:
|
|
p = Path(base) / name
|
|
relative = p.relative_to(root).as_posix()
|
|
confined(root, relative)
|
|
s = regular(p)
|
|
if relative in ("RETAIN.json", "CLOSEOUT-MANIFEST.json"):
|
|
raise ValueError("Job is explicitly pinned")
|
|
files.append(
|
|
dict(
|
|
path=relative,
|
|
size=s.st_size,
|
|
mtime_ns=s.st_mtime_ns,
|
|
mode=stat.S_IMODE(s.st_mode),
|
|
sha256=digest(p),
|
|
keep=relative in keep,
|
|
)
|
|
)
|
|
required = (
|
|
sum(f["size"] + f["size"] // 100 for f in files) + len(files) * 1024 + 1024**2
|
|
)
|
|
if (
|
|
usage(store) + required > limit
|
|
or shutil.disk_usage(store).free < required + reserve
|
|
):
|
|
raise RuntimeError("Archive quota/reserve reached; job preserved")
|
|
state = dict(
|
|
schema="missioncore.evidence-closeout/v1",
|
|
root=str(root),
|
|
owner=owner,
|
|
phase="planned",
|
|
files=files,
|
|
archive=str(archive),
|
|
retention="explicit-pin-no-TTL",
|
|
)
|
|
atomic_json(state_path, state)
|
|
if state["phase"] == "planned" and archive.exists():
|
|
# Crash after publishing ZIP but before committing archived state.
|
|
# Accept only this exact planned content, without reserving a second copy.
|
|
with zipfile.ZipFile(archive) as z:
|
|
if set(z.namelist()) != {r["path"] for r in state["files"]} | {
|
|
"CLOSEOUT-MANIFEST.json"
|
|
}:
|
|
raise ValueError("Uncommitted archive inventory changed")
|
|
if json.loads(z.read("CLOSEOUT-MANIFEST.json")) != state:
|
|
raise ValueError("Uncommitted archive owner changed")
|
|
for row in state["files"]:
|
|
with z.open(row["path"]) as f:
|
|
if (
|
|
z.getinfo(row["path"]).file_size != row["size"]
|
|
or hashlib.file_digest(f, "sha256").hexdigest() != row["sha256"]
|
|
):
|
|
raise ValueError("Uncommitted archive content changed")
|
|
state.update(phase="archived", archive_sha256=digest(archive))
|
|
atomic_json(state_path, state)
|
|
if state["phase"] == "planned":
|
|
temporary = control / "evidence.partial.zip"
|
|
temporary.unlink(missing_ok=True) # Only this owner's unfinished archive.
|
|
required = (
|
|
sum(r["size"] + r["size"] // 100 for r in state["files"])
|
|
+ len(state["files"]) * 1024
|
|
+ 1024**2
|
|
)
|
|
if (
|
|
usage(store) + required > limit
|
|
or shutil.disk_usage(store).free < required + reserve
|
|
):
|
|
raise RuntimeError("Archive quota/reserve reached; job preserved")
|
|
with zipfile.ZipFile(
|
|
temporary, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=1
|
|
) as z:
|
|
for row in state["files"]:
|
|
p = confined(root, row["path"])
|
|
if regular(p).st_size != row["size"] or digest(p) != row["sha256"]:
|
|
raise ValueError("Evidence changed before archival")
|
|
z.write(p, row["path"])
|
|
z.writestr("CLOSEOUT-MANIFEST.json", json.dumps(state, sort_keys=True))
|
|
with temporary.open("rb+") as f:
|
|
os.fsync(f.fileno())
|
|
os.replace(temporary, archive)
|
|
state.update(phase="archived", archive_sha256=digest(archive))
|
|
atomic_json(state_path, state)
|
|
if digest(archive) != state["archive_sha256"]:
|
|
raise ValueError("Archive checksum changed")
|
|
with zipfile.ZipFile(archive) as z:
|
|
if set(z.namelist()) != {r["path"] for r in state["files"]} | {
|
|
"CLOSEOUT-MANIFEST.json"
|
|
}:
|
|
raise ValueError("Archive inventory mismatch")
|
|
for row in state["files"]:
|
|
with z.open(row["path"]) as f:
|
|
if (
|
|
z.getinfo(row["path"]).file_size != row["size"]
|
|
or hashlib.file_digest(f, "sha256").hexdigest() != row["sha256"]
|
|
):
|
|
raise ValueError("Archive member checksum mismatch")
|
|
if (root / "RETAIN.json").exists():
|
|
raise ValueError("Job was pinned during closeout")
|
|
intents = set()
|
|
if journal.exists():
|
|
data = journal.read_bytes()
|
|
# Only an uncommitted final fragment can be discarded. A corrupt
|
|
# complete line still blocks recovery; durable intents are retained.
|
|
prefix = data.rfind(b"\n") + 1
|
|
for line in data[:prefix].splitlines():
|
|
item = json.loads(line)
|
|
if item["action"] == "intent":
|
|
intents.add(item["path"])
|
|
if prefix != len(data):
|
|
with journal.open("r+b") as f:
|
|
f.truncate(prefix)
|
|
f.flush()
|
|
os.fsync(f.fileno())
|
|
# Validate the complete deletion set before starting/resuming any unlink.
|
|
for row in state["files"]:
|
|
p = confined(root, row["path"])
|
|
if not p.exists():
|
|
if row["keep"] or row["path"] not in intents:
|
|
raise ValueError("Unexplained missing evidence")
|
|
elif regular(p).st_size != row["size"] or digest(p) != row["sha256"]:
|
|
raise ValueError("Evidence changed after archival")
|
|
with journal.open("a", encoding="utf-8") as log:
|
|
|
|
def record(action, row):
|
|
log.write(
|
|
json.dumps(
|
|
dict(
|
|
action=action, path=row["path"], sha256=row["sha256"], size=row["size"]
|
|
)
|
|
)
|
|
+ "\n"
|
|
)
|
|
log.flush()
|
|
os.fsync(log.fileno())
|
|
|
|
for row in state["files"]:
|
|
if row["keep"]:
|
|
continue
|
|
if (root / "RETAIN.json").exists():
|
|
raise ValueError("Job was pinned during closeout")
|
|
p = confined(root, row["path"])
|
|
if not p.exists():
|
|
record("reconciled", row)
|
|
continue
|
|
if regular(p).st_size != row["size"] or digest(p) != row["sha256"]:
|
|
raise ValueError("Evidence changed at unlink")
|
|
record("intent", row)
|
|
p.unlink()
|
|
record("removed", row)
|
|
state.update(
|
|
phase="complete", retired_bytes=sum(r["size"] for r in state["files"] if not r["keep"])
|
|
)
|
|
atomic_json(
|
|
root / "ARCHIVED.json",
|
|
{k: state[k] for k in ("owner", "archive", "archive_sha256", "retention")},
|
|
)
|
|
atomic_json(state_path, state)
|
|
return state
|
|
|
|
|
|
def restore_file(state_path, relative, destination):
|
|
state = json.loads(Path(state_path).read_text())
|
|
row = next(r for r in state["files"] if r["path"] == relative)
|
|
archive = Path(state["archive"])
|
|
if digest(archive) != state["archive_sha256"]:
|
|
raise ValueError("Archive changed")
|
|
with (
|
|
zipfile.ZipFile(archive) as z,
|
|
z.open(relative) as src,
|
|
Path(destination).open("xb") as dst,
|
|
):
|
|
shutil.copyfileobj(src, dst)
|
|
if digest(destination) != row["sha256"]:
|
|
Path(destination).unlink()
|
|
raise ValueError("Restoration checksum mismatch")
|
|
os.chmod(destination, row["mode"])
|
|
os.utime(destination, ns=(row["mtime_ns"], row["mtime_ns"]))
|