#!/usr/bin/env python3 """Observe local Linux flock identity using disposable files and fresh processes.""" # SPDX-License-Identifier: MIT import argparse from datetime import datetime, timezone import errno import fcntl import hashlib import json import os from pathlib import Path import platform import subprocess import sys import tempfile SOURCE = Path(__file__).resolve() def identity(fd): stat = os.fstat(fd) return [stat.st_dev, stat.st_ino] def probe(path): with open(path, "r+b", buffering=0) as handle: result = {"identity": identity(handle.fileno())} try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) result["acquired"] = True except OSError as error: if error.errno not in (errno.EAGAIN, errno.EACCES): raise result["acquired"] = False return result def peer(path, holder_identity): process = subprocess.run( [sys.executable, str(SOURCE), "--probe", str(path)], check=True, capture_output=True, text=True, timeout=10, close_fds=True, ) result = json.loads(process.stdout) result["sameFileAsHolder"] = result["identity"] == holder_identity return result def run_case(directory, case): directory.mkdir() target = directory / "target" target.write_bytes(b"old\n") lock_path = target if case == "replaced-target" else directory / "coordination.lock" if lock_path != target: lock_path.touch(exist_ok=False) # The alias lets a fresh process verify the original file stays locked. alias = directory / "original-lock-file" os.link(lock_path, alias) with open(lock_path, "r+b", buffering=0) as holder: fcntl.flock(holder, fcntl.LOCK_EX) holder_identity = identity(holder.fileno()) before = peer(lock_path, holder_identity) replacement = directory / "replacement" replacement.write_bytes(b"new\n") os.replace(replacement, target) if case == "recreated-sidecar": lock_path.unlink() lock_path.touch(exist_ok=False) during = peer(lock_path, holder_identity) original = peer(alias, holder_identity) fcntl.flock(holder, fcntl.LOCK_UN) after = peer(lock_path, holder_identity) return { "case": case, "holderIdentity": holder_identity, "beforeReplacement": before, "whileHolderLocked": during, "originalFileWhileHeld": original, "afterRelease": after, "targetContent": target.read_text(encoding="ascii").strip(), } def observe(): if platform.system() != "Linux": raise RuntimeError("This demonstration is scoped to Linux") with tempfile.TemporaryDirectory(prefix="hesela-lock-identity-") as temporary: root = Path(temporary) fs_type = subprocess.run( ["stat", "-f", "-c", "%T", str(root)], check=True, capture_output=True, text=True, timeout=10, ).stdout.strip() if fs_type in {"nfs", "nfs4", "cifs", "smb2", "smb3", "9p"}: raise RuntimeError("Use a disposable local filesystem, not a network mount") rows = [run_case(root / case, case) for case in ( "replaced-target", "retained-sidecar", "recreated-sidecar" )] return { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "method": "Ordered nonblocking probes by fresh subprocesses while the parent holds flock", "environment": {"python": platform.python_version(), "kernelRelease": platform.release(), "temporaryFilesystem": fs_type}, "sourceSha256": hashlib.sha256(SOURCE.read_bytes()).hexdigest(), "rows": rows, "limitations": [ "One local-filesystem run, not a probability estimate or a crash test.", "No fsync, power loss, network filesystem or F_OFD_* operation was tested.", "The original file has a temporary hard-link alias for the held-lock control.", "A filesystem label is not a full mount configuration; inspect your own environment.", ], } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, help="Create a new JSON file; never overwrite") parser.add_argument("--probe", type=Path, help=argparse.SUPPRESS) args = parser.parse_args() if args.probe: print(json.dumps(probe(args.probe))) return payload = json.dumps(observe(), indent=2) + "\n" if args.output: with args.output.open("x", encoding="utf-8") as output: output.write(payload) else: print(payload, end="") if __name__ == "__main__": main()