#!/usr/bin/env python3 """Own the UI stub's lifetime, and serialize reuse from preparation to exit.""" import fcntl import hashlib import os from pathlib import Path import re import shutil import subprocess import sys import time MARKER = '// Written by scripts/ui-tests-stub.sh' def sweep(root, current, started): """Only older generated legacy packages, with no open files, are ours.""" if root.is_symlink() or not root.is_dir(): return for candidate in root.iterdir(): if candidate.is_symlink() or not candidate.is_dir() or not re.fullmatch(r'[0-9a-f]{12}', candidate.name): continue if candidate.resolve() == current.resolve(): continue manifest = candidate / 'Package.swift' if manifest.is_symlink(): continue try: text = manifest.read_text() if MARKER not in text or 'name: "CottonUITestsStub"' not in text: continue if max(p.stat().st_mtime for p in [candidate, *candidate.iterdir()]) >= started: continue # Old runs predate our locks. An open build/log/cwd prevents adoption. active = subprocess.run(['lsof', '-t', '+D', str(candidate)], capture_output=True, timeout=30) if active.returncode != 1 or active.stdout or active.stderr: continue old_lock = root / (candidate.name + '.lock') if old_lock.is_symlink(): continue with old_lock.open('a') as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: continue shutil.rmtree(candidate) print(f'ui-tests-stub: swept old generated package {candidate}', flush=True) except (OSError, subprocess.TimeoutExpired): # An unread folder or unavailable lsof is unknown, never permission. continue def main(): script, *args = sys.argv[1:] checkout = Path(script).resolve().parent.parent directory = None i = 0 while i < len(args) and args[i] != '--': if args[i] in ('--checkout', '--dir') and i + 1 < len(args): if args[i] == '--checkout': checkout = Path(args[i + 1]).resolve() else: directory = Path(args[i + 1]) i += 2 else: i += 1 if sys.platform == 'darwin': sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'lib')) from mac_disk_policy import ancestor, run_build monitor = os.environ.get('COTTON_DISK_MONITOR_PID', '') if not monitor.isdigit() or not ancestor(int(monitor)): # Volume admission precedes the UI package lock, matching every # outer build and preventing a cache-lock/admission-lock deadlock. return run_build([sys.executable, str(Path(__file__).resolve()), *sys.argv[1:]], checkout, Path.home(), need=int(os.environ.get('COTTON_BUILD_DISK_BYTES', '1'))) root = Path(os.environ.get('TMPDIR', '/tmp')) / 'cotton-ui-tests-stub' ci = bool(os.environ.get('GITHUB_WORKSPACE')) started = time.time() if directory is None: if ci: kind = os.environ.get('GITHUB_JOB', 'job') if not re.fullmatch(r'[A-Za-z0-9_-]+', kind): sys.exit('ui-tests-stub: invalid CI job name') directory = root / ('ci-' + kind) else: directory = root / hashlib.sha1(str(checkout).encode()).hexdigest()[:12] # Validate before creating even the sibling lock: --dir may name a home # folder, a relative path, or a symlink resolving to an unowned root. guard = Path(__file__).resolve().parent.parent / 'lib/owned-root.sh' checked = subprocess.run(['bash', '-c', 'source "$1"; refuse_wide_root "the UI stub workspace" "$2"', 'ui-stub', str(guard), str(directory)]) if checked.returncode: return checked.returncode # Lock a sibling so the lock survives removal of the job's package. directory.parent.mkdir(parents=True, exist_ok=True) lock_path = directory.parent / (directory.name + '.lock') if lock_path.is_symlink(): sys.exit('ui-tests-stub: workspace lock must not be a symlink') with lock_path.open('a') as lock: fcntl.flock(lock, fcntl.LOCK_EX) sweep(root, directory, started) env = dict(os.environ, COTTON_STUB_LOCK_FD=str(lock.fileno())) policy = Path(__file__).resolve().parent.parent / 'lib/mac_disk_policy.py' result = subprocess.run([sys.executable, str(policy), '--path', str(checkout), '--', 'bash', script, '--dir', str(directory), *args], env=env, pass_fds=(lock.fileno(),)) return result.returncode if __name__ == '__main__': sys.exit(main())