From df9ae158c47200db159e554cec968ab2cc801274 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Sun, 25 Oct 2026 10:10:53 +0100 Subject: [PATCH] Run native macOS local CI lanes through Aqua LaunchAgents [#346] --- cmake/local-ci/macos_worker.py | 394 +++++++++++++++++++++++++++ cmake/local-ci/native_worker.py | 89 +++++++ cmake/local-ci/orchestrator.py | 30 ++- cmake/local-ci/windows_worker.py | 80 +----- cmake/local-ci/worker.py | 6 +- docs/LOCAL_CI.md | 82 +++++- docs/PROJECT_STATUS.md | 5 +- test/cmake/TestLocalCi.py | 3 + test/cmake/TestLocalCiMacOS.py | 438 +++++++++++++++++++++++++++++++ test/unit/CMakeLists.txt | 3 + 10 files changed, 1035 insertions(+), 95 deletions(-) create mode 100644 cmake/local-ci/macos_worker.py create mode 100644 cmake/local-ci/native_worker.py create mode 100644 test/cmake/TestLocalCiMacOS.py diff --git a/cmake/local-ci/macos_worker.py b/cmake/local-ci/macos_worker.py new file mode 100644 index 00000000..34f0cb27 --- /dev/null +++ b/cmake/local-ci/macos_worker.py @@ -0,0 +1,394 @@ +"""Native AppleClang/WKWebView lane in the dedicated account's Aqua session.""" +import contextlib +import ctypes +import errno +import json +import os +from pathlib import Path, PurePosixPath +import plistlib +import shutil +import socket +import subprocess +import sys +import threading +import time + +from orchestrator import command, digest, extract, verifyKit, runProcess, STOP, validateMatrix +from worker import ctestCommand +from native_worker import collect, cleanTree, runLock + +# Applied to the worker before any tested code (including CMake) executes. +# System XPC services are outside this inherited process policy; see LOCAL_CI.md. +NETWORK_POLICY = '''(version 1) +(allow default) +(deny network*) +(allow network-bind (local ip "localhost:*")) +(allow network-inbound (local ip "localhost:*")) +(allow network-outbound (remote ip "localhost:*")) +(allow network-bind (local unix-socket)) +(allow network-outbound (remote unix-socket)) +''' + +STARTUP_WARNING_SECONDS = 15 +SESSION_FINISH_GRACE_SECONDS = 5 +PREPARE_CLONE_TIMEOUT_SECONDS = 300 + + +class NoDesktop(ValueError): + pass + + +def guiDomain(): + return f"gui/{os.getuid()}" + + +def commandBudget(deadline, seconds): + return seconds if deadline is None else min(seconds, max(0.1, deadline - time.monotonic())) + + +def checkConsole(deadline=None): + if os.getuid() == 0: + raise ValueError("Use a dedicated non-administrator macOS account") + if Path('/dev/console').stat().st_uid != os.getuid(): + raise NoDesktop("Log on graphically with the dedicated macOS SSH account") + result = subprocess.run(['/bin/launchctl', 'print', guiDomain()], capture_output=True, timeout=commandBudget(deadline, 10)) + if result.returncode: + raise NoDesktop("The dedicated account has no usable Aqua launchd domain") + + +def sessionInfo(): + cg = ctypes.CDLL('/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics') + cf = ctypes.CDLL('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation') + cg.CGSessionCopyCurrentDictionary.restype = ctypes.c_void_p + cf.CFPropertyListCreateData.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_long, + ctypes.c_ulong, ctypes.POINTER(ctypes.c_void_p)] + cf.CFPropertyListCreateData.restype = ctypes.c_void_p + cf.CFDataGetLength.argtypes = [ctypes.c_void_p] + cf.CFDataGetLength.restype = ctypes.c_long + cf.CFDataGetBytePtr.argtypes = [ctypes.c_void_p] + cf.CFDataGetBytePtr.restype = ctypes.c_void_p + cf.CFRelease.argtypes = [ctypes.c_void_p] + cf.CFErrorGetCode.argtypes = [ctypes.c_void_p] + cf.CFErrorGetCode.restype = ctypes.c_long + info = cg.CGSessionCopyCurrentDictionary() + if not info: + raise NoDesktop("No CoreGraphics login session") + data = None + error = ctypes.c_void_p() + try: + data = cf.CFPropertyListCreateData(None, info, 100, 0, ctypes.byref(error)) # XML plist + if error.value: + raise NoDesktop(f"Cannot serialize CoreGraphics session: CoreFoundation error {cf.CFErrorGetCode(error)}") + if not data: + raise NoDesktop("Cannot inspect CoreGraphics login session") + return plistlib.loads(ctypes.string_at(cf.CFDataGetBytePtr(data), cf.CFDataGetLength(data))) + finally: + if data: + cf.CFRelease(data) + if error.value: + cf.CFRelease(error) + cf.CFRelease(info) + + +def consoleUsers(deadline=None): + result = command(['/usr/sbin/ioreg', '-n', 'Root', '-d', '1', '-a'], + capture_output=True, timeout=commandBudget(deadline, 10)) + registry = plistlib.loads(result.stdout) + # Older ioreg versions emit an array containing the registry root. + if isinstance(registry, list): + registry = registry[0] + return registry.get('IOConsoleUsers', []) + + +def checkDesktop(deadline=None): + checkConsole(deadline) + info = sessionInfo() + users = [user for user in consoleUsers(deadline) + if user.get('kCGSSessionUserIDKey') == os.getuid() + and user.get('kCGSSessionAuditIDKey') == info.get('kCGSSessionAuditIDKey')] + if (len(users) != 1 or users[0].get('CGSSessionScreenIsLocked', False) is not False + or not users[0].get('kCGSSessionOnConsoleKey') + or info.get('kCGSSessionUserIDKey') != os.getuid() + or not info.get('kCGSSessionOnConsoleKey') + or not info.get('kCGSessionLoginDoneKey') + or info.get('CGSSessionScreenIsLocked', False)): + raise NoDesktop("Unlock the dedicated macOS account's active graphical session") + + +def checkNetwork(): + # Fail closed if sandbox-exec did not apply the inherited outbound restriction. + for family, address in ((socket.AF_INET, ('192.0.2.1', 443)), + (socket.AF_INET6, ('2001:db8::1', 443))): + with socket.socket(family, socket.SOCK_STREAM) as probe: + probe.settimeout(0.2) + if probe.connect_ex(address) not in {errno.EPERM, errno.EACCES}: + raise ValueError('macOS process network restriction is absent or ineffective') + + +def buildCommands(lane, jobs, workspace, dependencies, cache): + workspace, dependencies, cache = map(PurePosixPath, (workspace, dependencies, cache)) + build = workspace / 'build-local-0' + configure = ['cmake', '-S', str(workspace), '-B', str(build), '-G', 'Ninja', + '-C', str(dependencies / 'preload.cmake'), '-DCMAKE_BUILD_TYPE=' + lane['build_type']] + configure += lane['common_options'] + lane['options'] + configure += ['-DENABLE_CACHE=OFF', '-DCMAKE_CXX_COMPILER=/usr/bin/clang++', + '-DCMAKE_CXX_COMPILER_LAUNCHER=ccache', '-DFETCHCONTENT_FULLY_DISCONNECTED=ON', + '-DCPM_SOURCE_CACHE=' + str(cache / 'cpm'), + '-DWEBFRONT_BOOTSTRAP_DIR=' + str(dependencies / 'bootstrap'), + '-DWEBFRONT_REGISTRY_DIR=' + str(dependencies / 'registry')] + buildArgs = ['cmake', '--build', str(build), '--parallel', str(min(jobs, 4))] + if lane['targets']: + buildArgs += ['--target'] + lane['targets'] + return [configure, buildArgs, ctestCommand(lane, build) + ['-C', lane['build_type'], + '--output-junit', str(build / 'test-results.xml')]] + + +def prepare(root, expected): + if os.getuid() == 0: + raise ValueError('Use a dedicated non-administrator macOS account') + if digest(root / 'kit.tgz') != expected: + raise ValueError('Transferred macOS kit SHA-256 mismatch') + dependencies = root / 'dependencies' + dependencies.mkdir() + # Default APFS is case insensitive: use the portable Windows archive subset. + extract(root / 'kit.tgz', dependencies, windows=True) + manifest = verifyKit(dependencies) + if manifest.get('platform') != 'macos' or manifest['images']: + raise ValueError('Mac needs a platform=macos kit without Docker images') + cache = root.parent.parent / 'cache/cpm/cpm' + cache.mkdir(parents=True, exist_ok=True) + for module in (dependencies / 'cpm').glob('CPM_*.cmake'): + temporary = cache / (module.name + '.' + root.name) + shutil.copyfile(module, temporary) + temporary.replace(cache / module.name) + command(['git', 'clone', '--mirror', str(root / 'commit.bundle'), str(root / 'repo.git')], + timeout=PREPARE_CLONE_TIMEOUT_SECONDS) + + +def taskName(root, lane): + return 'org.webfront.local-ci.' + root.name + '.' + lane + + +def startTask(root, args): + checkConsole(getattr(args, 'deadline', None)) + profile = root / (args.lane + '.sb') + profile.write_text(NETWORK_POLICY) + # Inherit only explicit tool locations, never SSH tokens/proxies or the owner's keychain settings. + path = os.pathsep.join(dict.fromkeys([str(Path(sys.executable).parent), + *[str(Path(shutil.which(tool) or tool).absolute().parent) + for tool in ('cmake', 'ninja', 'ccache', 'git')], + '/usr/bin', '/bin', '/usr/sbin', '/sbin'])) + label = taskName(root, args.lane) + plist = {'Label': label, 'ProgramArguments': ['/usr/bin/sandbox-exec', '-f', str(profile), + sys.executable, '-u', str(root / 'worker.py'), 'session', '--lane', args.lane, + '--sha', args.sha, '--jobs', str(min(args.jobs, 4)), '--timeout', str(args.timeout), + '--deadline', str(getattr(args, 'deadline', time.monotonic() + args.timeout))], + 'WorkingDirectory': str(root), 'RunAtLoad': True, 'KeepAlive': False, + 'LimitLoadToSessionType': 'Aqua', 'AbandonProcessGroup': False, 'ExitTimeOut': 5, + 'EnvironmentVariables': {'PATH': path, 'HOME': str(Path.home()), 'LANG': 'en_US.UTF-8'}, + 'StandardOutPath': str(root / (args.lane + '.launch.log')), + 'StandardErrorPath': str(root / (args.lane + '.launch.log'))} + target = root / (args.lane + '.plist') + target.write_bytes(plistlib.dumps(plist)) + command(['/bin/launchctl', 'bootstrap', guiDomain(), str(target)], + timeout=commandBudget(getattr(args, 'deadline', None), 15)) + + +def stopTask(root, lane): + (root / (lane + '.cancel')).touch() + if not (root / (lane + '.plist')).exists(): + return + service = guiDomain() + '/' + taskName(root, lane) + result = subprocess.run(['/bin/launchctl', 'bootout', '--wait', service], capture_output=True, text=True, timeout=15) + if result.returncode: + # Only an explicit not-found diagnosis is idempotent. Permissions/IPC failures retain the run. + probe = subprocess.run(['/bin/launchctl', 'print', service], capture_output=True, text=True, + env=dict(os.environ, LC_ALL='C'), timeout=10) + if not probe.returncode or 'Could not find service' not in probe.stderr: + raise ValueError('LaunchAgent stop not confirmed: ' + result.stderr + probe.stderr) + + +def reportToolchain(lane, log, deadline=None): + def budget(seconds): + return commandBudget(deadline, seconds) + version = command(['cmake', '--version'], capture_output=True, text=True, timeout=budget(10)).stdout + print(version, flush=True) + if version.splitlines()[0] != 'cmake version ' + lane['cmake_version']: + raise ValueError('CMake version does not match the macOS lane') + for invocation in (['/usr/bin/xcode-select', '-p'], ['/usr/bin/xcodebuild', '-version'], + ['/usr/bin/xcrun', '--find', 'clang++'], ['/usr/bin/clang++', '--version'], + ['/usr/bin/sw_vers'], ['ccache', '--version']): + command(invocation, stdout=log, stderr=log, timeout=budget(15)) + print('GitHub selects Xcode latest; compare these versions with the same-commit GitHub run. ' + 'No automatic parity with the mutable runner image is claimed.', flush=True) + + +def session(root, args, lane): + result = root / (args.lane + '.result.json') + with open(root / (args.lane + '.session.log'), 'w', encoding='utf-8', buffering=1) as log, \ + contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): + deadline = getattr(args, 'deadline', None) + if deadline is None: + deadline = time.monotonic() + args.timeout + done = threading.Event() + def watch(): + while not done.wait(0.1): + if time.monotonic() >= deadline or (root / (args.lane + '.cancel')).exists(): + STOP.set() + return + watcher = threading.Thread(target=watch, daemon=True) + watcher.start() + code = 1 + try: + checkDesktop(deadline) + checkNetwork() + reportToolchain(lane, log, deadline) + cache = root.parent.parent / 'cache' + (cache / 'ccache').mkdir(parents=True, exist_ok=True) + # Independent CTest configure projects need the offline module too. + os.environ.update(lane.get('env', {})) + os.environ.update(CPM_SOURCE_CACHE=str(cache / 'cpm'), CCACHE_DIR=str(cache / 'ccache'), + CCACHE_BASEDIR=str(root / args.lane)) + workspace = root / args.lane + command(['git', 'clone', '--no-hardlinks', str(root / 'repo.git'), str(workspace)], + stdout=log, stderr=log, timeout=max(0.1, deadline - time.monotonic())) + command(['git', '-C', str(workspace), 'checkout', '--detach', args.sha], + stdout=log, stderr=log, timeout=max(0.1, deadline - time.monotonic())) + for invocation in buildCommands(lane, args.jobs, workspace, root / 'dependencies', cache): + print('+', repr(invocation), flush=True) + runProcess(invocation, log, max(0.1, deadline - time.monotonic())) + if time.monotonic() >= deadline: + raise TimeoutError('macOS session deadline expired') + code = 0 + except NoDesktop as error: + code = 125 + print('skipped (no interactive session): ' + str(error), flush=True) + except (ValueError, OSError, subprocess.SubprocessError, InterruptedError, TimeoutError) as error: + code = 124 if time.monotonic() >= deadline else 1 + print(f'macOS lane: {error}', flush=True) + finally: + done.set() + watcher.join() + # Close/flush the log before publishing completion to the SSH coordinator. + temporary = result.with_suffix('.tmp') + temporary.write_text(json.dumps({'code': code}), encoding='utf-8') + temporary.replace(result) + return code + + +def finishLane(root, args): + errors = [] + stopped = False + for stage, action in [('LaunchAgent stop', lambda: stopTask(root, args.lane)), + ('Artifact collection', lambda: collect(root, args.lane)), + ('Session log', lambda: printLogs(root, args.lane))]: + try: + action() + if stage == 'LaunchAgent stop': + stopped = True + except Exception as error: + errors.append((stage, error)) + if stopped and not errors and not args.keep and (root / args.lane).exists(): + try: + cleanTree(root, root / args.lane) + except Exception as error: + errors.append(('Checkout cleanup', error)) + return errors + + +def printLogs(root, lane): + for suffix in ('.launch.log', '.session.log'): + path = root / (lane + suffix) + if path.exists(): + print(path.read_text(encoding='utf-8', errors='replace'), flush=True) + + +def runLane(root, args): + started = time.monotonic() + args.deadline = started + args.timeout + startupWarningAt = started + min(STARTUP_WARNING_SECONDS, args.timeout) + warned = False + try: + with runLock(root): + if not root.exists() or (root / (args.lane + '.cancel')).exists(): + raise InterruptedError('macOS run already stopped or removed') + if time.monotonic() >= args.deadline: + raise TimeoutError('macOS lane deadline expired before launch') + try: + startTask(root, args) + except subprocess.TimeoutExpired as error: + if time.monotonic() >= args.deadline: + raise TimeoutError('macOS launch deadline expired') from error + raise + except NoDesktop as error: + print('skipped (no interactive session): ' + str(error), flush=True) + return 125 + result = root / (args.lane + '.result.json') + while not result.exists(): + if STOP.wait(0.1) or not root.exists() or (root / (args.lane + '.cancel')).exists(): + raise InterruptedError('macOS lane interrupted') + now = time.monotonic() + if now >= args.deadline + SESSION_FINISH_GRACE_SECONDS: + raise TimeoutError('macOS lane deadline expired; inspect the launch and session logs') + if not warned and now >= startupWarningAt and not (root / (args.lane + '.session.log')).exists(): + print('LaunchAgent has not written its session log yet; waiting until the shared deadline', flush=True) + warned = True + code = json.loads(result.read_text(encoding='utf-8'))['code'] + if code == 125: + return code + if code == 124: + raise TimeoutError('macOS session deadline expired') + if code: + raise subprocess.CalledProcessError(code, 'macOS graphical session') + return 0 + finally: + original = sys.exc_info()[1] + try: + with runLock(root): + errors = finishLane(root, args) if root.exists() else [] + except Exception as error: + errors = [('Finalization lock', error)] + for stage, error in errors: + print(f'{stage} failed: {error}', file=sys.stderr, flush=True) + if errors and original is None: + raise errors[0][1] + + +def dispatch(args, matrix, root): + validateMatrix(matrix) + lane = None + if args.lane: + lane = next(row for row in matrix['lanes'] if row['id'] == args.lane) + if lane['machine'] != 'Mac' or lane['runtime'] != 'native:appleclang': + raise ValueError('macOS worker accepts only Mac native:appleclang lanes') + if args.action == 'prepare': + prepare(root, args.kit_sha256) + elif args.action == 'lane': + return runLane(root, args) + elif args.action == 'session': + return session(root, args, lane) + elif args.action == 'stop': + with runLock(root): + if root.exists(): + args.keep = True + errors = finishLane(root, args) + if errors: + raise errors[0][1] + elif args.action == 'artifacts': + with runLock(root): + with open(root / (args.lane + '-artifacts.tar'), 'rb') as source: + shutil.copyfileobj(source, sys.stdout.buffer) + elif args.action == 'cleanup': + with runLock(root): + if root.exists(): + for row in matrix['lanes']: + if row['machine'] == 'Mac': + args.lane = row['id'] + args.keep = True + errors = finishLane(root, args) + if errors: + raise errors[0][1] + cleanTree(root, root) + else: + raise ValueError('Unsupported macOS action') + return 0 diff --git a/cmake/local-ci/native_worker.py b/cmake/local-ci/native_worker.py new file mode 100644 index 00000000..38555057 --- /dev/null +++ b/cmake/local-ci/native_worker.py @@ -0,0 +1,89 @@ +"""Shared diagnostic collection, cleanup and cross-channel locking for native lanes.""" +import contextlib +import os +from pathlib import Path +import shutil +import stat +import sys +import tarfile +import time + + +def collect(root, lane): + workspace = root / lane + destination = root / (lane + "-artifacts.tar") + # A recovery stop may arrive after the original channel archived and removed + # its checkout. Preserve that complete archive rather than replacing it with just a log. + if destination.exists() and not workspace.exists(): + return + temporary = destination.with_suffix(".tmp") + with tarfile.open(temporary, "w") as archive: + for suffix in (".session.log", ".launch.log"): + log = root / (lane + suffix) + if log.is_file(): + archive.add(log, arcname=log.name) + for pattern in ("**/test-results.xml", "**/LastTest.log", "**/CMakeConfigureLog.yaml"): + for path in workspace.glob(pattern): + if path.is_file() and not path.is_symlink(): + archive.add(path, arcname=path.relative_to(workspace), recursive=False) + temporary.replace(destination) + + +def cleanTree(root, target): + root, target = root.resolve(), target.resolve() + if (root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci" + or not target.is_relative_to(root)): + raise ValueError("Refusing cleanup outside a local CI run") + def readonly(function, path, error): + # Git object files are read-only on Windows, even in an owned disposable clone. + if not Path(path).resolve().is_relative_to(target): + raise ValueError("Cleanup path escaped the local CI run") + if not os.stat(path).st_mode & stat.S_IWRITE: + os.chmod(path, stat.S_IWRITE) + function(path) + else: + raise error + if sys.version_info >= (3, 12): + shutil.rmtree(target, onexc=readonly) + else: + shutil.rmtree(target, onerror=lambda function, path, error: readonly(function, path, error[1])) + + +@contextlib.contextmanager +def runLock(root, timeout=60): + """Serialize finalization and recovery SSH channels, including run-directory removal.""" + root = root.resolve() + if root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci": + raise ValueError("Refusing lock outside a local CI run") + # Outside the removable run: every channel must keep opening the same lock file. + locks = root.parent.parent / "locks" + locks.mkdir(exist_ok=True) + with open(locks / (root.name + ".lock"), "a+b") as lock: + if lock.tell() == 0: + lock.write(b"\0") + lock.flush() + deadline = time.monotonic() + timeout + while True: + try: + lock.seek(0) + if os.name == "nt": + import msvcrt + msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except OSError: + if time.monotonic() >= deadline: + raise TimeoutError("Another native CI channel is still finalizing this run") + time.sleep(0.1) + try: + yield + finally: + lock.seek(0) + if os.name == "nt": + msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(lock.fileno(), fcntl.LOCK_UN) + + diff --git a/cmake/local-ci/orchestrator.py b/cmake/local-ci/orchestrator.py index e61a8ba8..83dd7253 100644 --- a/cmake/local-ci/orchestrator.py +++ b/cmake/local-ci/orchestrator.py @@ -1,4 +1,4 @@ -"""Transfer a commit and verified offline kits, then run Linux/Windows lanes over SSH.""" +"""Transfer a commit and verified offline kits, then run Linux/Windows/macOS lanes over SSH.""" import argparse import base64 import concurrent.futures @@ -103,8 +103,8 @@ def pack(args): if args.output.resolve().is_relative_to(root): raise ValueError("The output archive must be outside the dependency directory") config = json.loads((root / "provision.json").read_text()) - if not config.get("sources") or not (config.get("images") or config.get("platform") == "windows"): - raise ValueError("provision.json must describe images or platform=windows, and source provenance") + if not config.get("sources") or not (config.get("images") or config.get("platform") in {"windows", "macos"}): + raise ValueError("provision.json must describe images or platform=windows/macos, and source provenance") config.setdefault("images", {}) # Require provenance for every top-level tree (archives retain their upstream checksums). for path in root.iterdir(): @@ -278,6 +278,11 @@ def execute(args): if digest(windowsKit) != args.windows_kit_sha256: raise ValueError("Windows offline kit SHA-256 mismatch") kits["CurmudgeonWindows"] = (windowsKit.resolve(), args.windows_kit_sha256) + macosKit = getattr(args, "macos_kit", None) + if macosKit: + if digest(macosKit) != args.macos_kit_sha256: + raise ValueError("macOS offline kit SHA-256 mismatch") + kits["Mac"] = (macosKit.resolve(), args.macos_kit_sha256) bundle = scratch / "commit.bundle" # A temporary private ref lets git bundle include detached and unpushed commits. ref = "refs/local-ci/" + runId @@ -295,6 +300,8 @@ def execute(args): with tarfile.open(payload, "w") as archive: for path, name in [(bundle, "commit.bundle"), (HERE / "worker.py", "worker.py"), (HERE / "windows_worker.py", "windows_worker.py"), + (HERE / "macos_worker.py", "macos_worker.py"), + (HERE / "native_worker.py", "native_worker.py"), (HERE / "orchestrator.py", "orchestrator.py"), (selectedMatrix, "lanes.json"), (kits[machine][0], "kit.tgz")]: archive.add(path, arcname=name) @@ -311,8 +318,6 @@ def prepare(machine): return "interrupted" except (subprocess.SubprocessError, TimeoutError, OSError): return "unreachable" - if machine not in {"RyzenLinux", "CurmudgeonWindows"}: - return "skipped (native session support pending step 3)" if machine not in kits: log.write(b"Missing offline kit and SHA-256 for this machine.\n") return "failed" @@ -353,20 +358,21 @@ def laneTask(lane): except TimeoutError: status = "timeout" except subprocess.CalledProcessError as error: - status = "timeout" if error.returncode == 124 else "failed" + status = ("timeout" if error.returncode == 124 else + "skipped (no interactive session)" if machine == "Mac" and error.returncode == 125 else "failed") except (subprocess.SubprocessError, OSError): status = "failed" if status in {"interrupted", "timeout", "failed"}: # A second SSH channel stops the container even if the execution channel was lost. try: command(workerCommand(machine, "stop", "--lane", laneId), stdout=log, - stderr=subprocess.STDOUT, timeout=90 if machine == "CurmudgeonWindows" else 15) + stderr=subprocess.STDOUT, timeout=90 if machine in {"CurmudgeonWindows", "Mac"} else 15) except (subprocess.SubprocessError, OSError): - log.write(b"Remote cancellation could not be confirmed; inspect the container.\n") + log.write(b"Remote cancellation could not be confirmed; inspect the remote run.\n") try: with open(output / (laneId + "-artifacts.tar"), "wb") as artifacts: command(workerCommand(machine, "artifacts", "--lane", laneId), stdout=artifacts, - stderr=log, timeout=90 if machine == "CurmudgeonWindows" else 60) + stderr=log, timeout=90 if machine in {"CurmudgeonWindows", "Mac"} else 60) except (subprocess.SubprocessError, OSError): log.write(b"Artifact collection failed.\n") if status == "passed": @@ -386,7 +392,7 @@ def laneTask(lane): with open(output / (machine + "-cleanup.log"), "wb") as log: try: command(workerCommand(machine, "cleanup"), stdout=log, stderr=subprocess.STDOUT, - timeout=90 if machine == "CurmudgeonWindows" else 30) + timeout=90 if machine in {"CurmudgeonWindows", "Mac"} else 30) except (subprocess.SubprocessError, OSError): print(f"Cleanup not confirmed on {machine}; run {runId} retained") finally: @@ -414,6 +420,8 @@ def main(argv=None): run.add_argument("--kit-sha256") run.add_argument("--windows-kit", type=Path) run.add_argument("--windows-kit-sha256") + run.add_argument("--macos-kit", type=Path) + run.add_argument("--macos-kit-sha256") run.add_argument("--parallel-lanes", type=int, default=2) run.add_argument("--jobs", type=int, default=4) run.add_argument("--timeout", type=int, default=3600) @@ -428,6 +436,8 @@ def main(argv=None): raise ValueError("--kit and --kit-sha256 must be supplied together") if bool(args.windows_kit) != bool(args.windows_kit_sha256): raise ValueError("--windows-kit and --windows-kit-sha256 must be supplied together") + if bool(args.macos_kit) != bool(args.macos_kit_sha256): + raise ValueError("--macos-kit and --macos-kit-sha256 must be supplied together") return execute(args) except (ValueError, OSError, subprocess.SubprocessError) as error: print(f"local-ci: {error}", file=__import__('sys').stderr) diff --git a/cmake/local-ci/windows_worker.py b/cmake/local-ci/windows_worker.py index 547134f6..fc24c6a0 100644 --- a/cmake/local-ci/windows_worker.py +++ b/cmake/local-ci/windows_worker.py @@ -12,15 +12,14 @@ from pathlib import Path, PureWindowsPath import shutil import socket -import stat import subprocess import sys -import tarfile import threading import time from orchestrator import command, digest, extract, verifyKit, psQuote, STOP, runProcess, validateMatrix from worker import ctestCommand +from native_worker import collect, cleanTree, runLock def ps(script, **kwargs): @@ -311,83 +310,6 @@ def watch(): return code -def collect(root, lane): - workspace = root / lane - destination = root / (lane + "-artifacts.tar") - # A recovery stop may arrive after the original channel archived and removed - # its checkout. Preserve that complete archive rather than replacing it with just a log. - if destination.exists() and not workspace.exists(): - return - temporary = destination.with_suffix(".tmp") - with tarfile.open(temporary, "w") as archive: - log = root / (lane + ".session.log") - if log.is_file(): - archive.add(log, arcname=log.name) - for pattern in ("**/test-results.xml", "**/LastTest.log", "**/CMakeConfigureLog.yaml"): - for path in workspace.glob(pattern): - if path.is_file() and not path.is_symlink(): - archive.add(path, arcname=path.relative_to(workspace), recursive=False) - temporary.replace(destination) - - -def cleanTree(root, target): - root, target = root.resolve(), target.resolve() - if (root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci" - or not target.is_relative_to(root)): - raise ValueError("Refusing cleanup outside a local CI run") - def readonly(function, path, error): - # Git object files are read-only on Windows, even in an owned disposable clone. - if not Path(path).resolve().is_relative_to(target): - raise ValueError("Cleanup path escaped the local CI run") - if not os.stat(path).st_mode & stat.S_IWRITE: - os.chmod(path, stat.S_IWRITE) - function(path) - else: - raise error - if sys.version_info >= (3, 12): - shutil.rmtree(target, onexc=readonly) - else: - shutil.rmtree(target, onerror=lambda function, path, error: readonly(function, path, error[1])) - - -@contextlib.contextmanager -def runLock(root, timeout=60): - """Serialize finalization and recovery SSH channels, including run-directory removal.""" - root = root.resolve() - if root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci": - raise ValueError("Refusing lock outside a local CI run") - # Outside the removable run: every channel must keep opening the same lock file. - locks = root.parent.parent / "locks" - locks.mkdir(exist_ok=True) - with open(locks / (root.name + ".lock"), "a+b") as lock: - if lock.tell() == 0: - lock.write(b"\0") - lock.flush() - deadline = time.monotonic() + timeout - while True: - try: - lock.seek(0) - if os.name == "nt": - import msvcrt - msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) - else: - import fcntl - fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - break - except OSError: - if time.monotonic() >= deadline: - raise TimeoutError("Another Windows CI channel is still finalizing this run") - time.sleep(0.1) - try: - yield - finally: - lock.seek(0) - if os.name == "nt": - msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) - else: - fcntl.flock(lock.fileno(), fcntl.LOCK_UN) - - def finishLane(root, args): """Return secondary errors; always try both diagnostic paths, never delete a live checkout.""" errors = [] diff --git a/cmake/local-ci/worker.py b/cmake/local-ci/worker.py index 468468fd..b0c109f6 100644 --- a/cmake/local-ci/worker.py +++ b/cmake/local-ci/worker.py @@ -243,7 +243,7 @@ def runLane(args, matrix): cleanWorkspace(workspace, image, args.lane) -def main(): +def main(hostPlatform=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=["prepare", "lane", "inside", "stop", "cleanup", "artifacts", "session"]) parser.add_argument("--kit-sha256") @@ -251,6 +251,7 @@ def main(): parser.add_argument("--sha") parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--timeout", type=int, default=3600) + parser.add_argument("--deadline", type=float) parser.add_argument("--keep", action="store_true") args = parser.parse_args() signal.signal(signal.SIGTERM, lambda *_: STOP.set()) @@ -261,6 +262,9 @@ def main(): validateMatrix(matrix) if args.lane and not any(row["id"] == args.lane for row in matrix["lanes"]): raise ValueError("Unknown lane") + if (hostPlatform or sys.platform) == "darwin": + import macos_worker + return macos_worker.dispatch(args, matrix, ROOT) if os.name == "nt": import windows_worker return windows_worker.dispatch(args, matrix, ROOT) diff --git a/docs/LOCAL_CI.md b/docs/LOCAL_CI.md index 5ee5b87d..c3d4f638 100644 --- a/docs/LOCAL_CI.md +++ b/docs/LOCAL_CI.md @@ -13,7 +13,7 @@ The story is delivered in three verifiable steps; a partial step does not close | --- | --- | --- | | 1 | The eleven lanes in `cmake/local-ci/lanes.json` and the offline drift check `LocalCiLanesMatchWorkflows` | delivered | | 2 | Commit transport, offline-kit verification, Linux containers and the orchestrator | implemented; real-host/image qualification pending | -| 3 | Native Windows and macOS sessions, result collection, full qualification and timings | Windows implementation delivered; host qualification and macOS pending | +| 3 | Native Windows and macOS sessions, result collection, full qualification and timings | Windows and macOS implementations delivered; real-host qualification and timings pending | ## The lanes @@ -287,9 +287,10 @@ sessions. `LocalCiLanesMatchWorkflows` and its negative suite still check the wo Actual Linux image builds, the nine lanes on RyzenLinux, warm-cache timings and comparison with GitHub on the same commit remain to be qualified. The Windows implementation below still needs qualification on CurmudgeonWindows with its dedicated -account and network policy. Delivery step 3 also needs the macOS graphical session and Xcode reporting, and the eleven-lane run. -A reachable Mac reports `skipped (native session support pending step 3)`; an unreachable machine reports `unreachable`. -Neither counts as passed, and `--require-all` fails when either is selected. The story remains open. +account and network policy. The macOS implementation below also needs qualification with its dedicated Aqua account and full Xcode installation, +and all eleven lanes must still run together. Missing macOS graphical sessions report `skipped (no interactive session)`; +unreachable machines report `unreachable`. Neither counts as passed, and `--require-all` fails when either is selected. +Although GitHub currently marks #346 closed, the full acceptance evidence remains incomplete. ### Native Windows execution @@ -393,3 +394,76 @@ In particular, verify from the actual **non-elevated SSH account** that `Get-Net effective policy. These permissions have not been tested on the dedicated host: denial fails preparation before any build, and the worker does not elevate or bypass the check. Also qualify public egress blocking, multicast/broadcast effects, MSVC/Evergreen version differences, and a real SSH disconnect followed by recovery collection and cleanup. + + +### Native macOS execution + +The Mac lane now transfers an unpushed commit and a separate `platform=macos` kit over SSH, then runs the AppleClang/Release +configuration with `WEBFRONT_EMBED_WKWEBVIEW=ON` and `WEBFRONT_WEBTEST_FRONTEND=WKWebView`. All metadata-selected CTest cases, +including browser tests, run with `--no-tests=error`, the declared parallelism and JUnit output. Compilation is capped at four +jobs. Local macOS uses ccache (without a background server) instead of GitHub's sccache; the verified CPM module and compiler +cache persist under the dedicated account's `.webfront-local-ci/cache/`. CTest child configurations inherit `CPM_SOURCE_CACHE`. + +Prepare a dedicated **standard, non-administrator** macOS account without the principal user's files, credentials, keychain +items or cloud sessions. Enable key-only Remote Login for that account, verify the host key, and configure the development +workstation's `Mac` SSH alias to select it explicitly. Install Python 3.10+ (`python3` on the SSH PATH), Git, Ninja, ccache, +the lane's exact CMake version and full Xcode before execution. Accept Xcode's license and complete its first-launch setup +while provisioning; select it with `xcode-select` then. Command Line Tools alone are insufficient: `xcodebuild -version` +must succeed. No installer, `sudo`, Xcode selection change or runtime update runs during a lane. + +Log the **same dedicated account** into an unlocked, active graphical console session. SSH alone and a background `user/UID` +domain do not provide Aqua. A unique, one-shot LaunchAgent is bootstrapped into `gui/UID`, with its plist/profile/logs inside +the disposable run directory (no installation in `~/Library/LaunchAgents`). It inherits an explicit tool PATH, HOME and locale, +without forwarding the SSH environment, tokens or proxy variables. It checks console ownership, the Aqua domain and the +CoreGraphics session's user, login and on-console state, plus IORegistry's lock state for that audit session (an omitted lock key means unlocked) before building. No graphical session or a locked/inactive +session returns worker code 125 and `skipped (no interactive session)` in the summary; `--require-all` fails. Failure to start +an agent despite a usable domain is a failed lane with a launch log, never a pass or a silent skip. + +The log records `xcode-select -p`, `xcodebuild -version`, `xcrun --find clang++`, the effective AppleClang banner and macOS +version. CMake must match `lanes.json` exactly. GitHub's `xcode-version: latest` is mutable: compare these records against the +same-commit GitHub run, recording any difference. There is no automatic claim that the host matches GitHub's Xcode or OS image. + +The agent starts under `/usr/bin/sandbox-exec` with an inherited network policy: ordinary worker/build/test descendants can +use IPv4/IPv6 loopback and Unix sockets, but cannot connect directly to external IP addresses. A probe checks that IPv4 and +IPv6 connects are denied before any CMake command executes. Missing sandbox support or an ineffective restriction fails closed. +This keeps a CMake fallback download from reaching GitHub. The worker does not alter the host firewall. **This process policy +does not constrain system XPC services started outside the agent's process tree**, including WebKit services. Unix sockets are also unrestricted: a tested process can contact a local service that performs +network access on its behalf, so the policy does not prevent indirect Internet access through such services. It is not a +complete network isolation boundary or a sandbox for hostile commits. The owner must qualify WebKit's actual network behavior +and, where strict host-wide egress isolation is required, provision that isolation separately on the dedicated Mac or network. +Do not expose a public-network proxy on loopback. Full acceptance of #346's no-public-network criterion remains pending this +qualification; direct-socket regression tests alone do not establish it for XPC services. `sandbox-exec` is deprecated and may +be unavailable on future macOS releases; such hosts fail rather than running unrestricted. + +The SSH coordinator passes one absolute host-monotonic deadline to the agent, which enforces it alongside a cancellation +marker. After expiry, the coordinator allows five seconds for the agent to flush its log and publish code 124 before stopping +it. A named 15-second startup warning threshold is capped by the lane timeout; it warns without aborting a slow bootstrap +before the shared deadline. Preparation bounds its local bundle clone to 300 seconds. Launchd owns its process group (`AbandonProcessGroup=false`); finishing, +timeout, interruption and SSH recovery boot out the service with `launchctl bootout --wait` under a bounded subprocess timeout. +The host must support that option. Stop failures preserve files and fail the run. A per-run cross-process lock serializes +start/finalization, recovery stop, artifact streaming and cleanup; late channels cannot recreate deleted runs. Logs (including +sandbox/launch failures), JUnit, CTest and CMake diagnostics are archived before checkout removal. `--keep` retains the run after +stopping it. Native process groups do not contain deliberately detached processes or system XPC services; only trusted commits +are supported. Real disconnect and descendant cleanup behavior still needs qualification on the dedicated host. + +Prepare the same CPM/stdnet/stdexec/Catch2, bootstrap and registry exports as Windows, omitting WebView2SDK and all Docker/CEF +files. Use `"platform": "macos", "images": {}` with provenance for every top-level entry. The Windows preload example above +is portable after removing its WebView2SDK line. Extraction uses the portable Windows filename subset to reject case collisions +on default APFS volumes. No filesystem case-sensitivity assumption is needed. + +```bash +python3 cmake/local-ci/run pack --dependencies /kits/macos-prepared --output /kits/macos.tgz +python3 cmake/local-ci/run run --machines Mac --commit HEAD \ + --macos-kit /kits/macos.tgz --macos-kit-sha256 --jobs 4 --require-all +``` + +`--macos-kit` and `--macos-kit-sha256` must be supplied together. A full invocation supplies all three kit/hash pairs (`--kit`, +`--windows-kit`, `--macos-kit`) and omits `--machines`/`--lanes`. Each host receives its own kit; no host needs GitHub access. + +`LocalCiMacOS` covers command generation, LaunchAgent configuration, login/lock checks, version reporting, kit integrity, +cache propagation, failure/timeout/cancellation, skipped sessions, cleanup retention and the full bundle/artifact protocol with +a native-session stand-in. On macOS it also exercises the real inherited socket policy, loopback and a child process. It does +not provision an account or register an actual LaunchAgent. Qualification still requires real SSH/Aqua/WKWebView execution, +XPC network checks, disconnect recovery, cold/warm cache measurements, all eleven lanes across three hosts and comparison +against GitHub on the same commit. The development Mac used for implementation has Command Line Tools rather than selected +full Xcode, so it cannot qualify the advertised Xcode lane. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 48d1cb1d..41634a04 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -623,5 +623,8 @@ artifact collection, bounded execution and explicit incomplete/failure statuses. stand-ins. Native Windows execution now launches a limited interactive scheduled task, initializes MSVC, checks WebView2 and the owner-prepared public egress firewall policy, caps compilation at four jobs, owns descendants through a Windows Job Object, and collects diagnostics before cleanup. Offline Windows regressions include real PowerShell binary transport and Job cleanup. -Real Linux image/host and Windows account/task qualification, native macOS sessions and comparison with GitHub timings remain open; +Native macOS execution now uses a temporary Aqua LaunchAgent, reports selected Xcode/AppleClang and OS versions, runs the +WKWebView lane with a verified Mac kit and inherited process network restriction, and reports missing sessions as skipped. +System WebKit XPC services are outside that process restriction. Real Linux/Windows/macOS host qualification, XPC egress +isolation, the complete eleven-lane run and comparison with GitHub timings remain open; this is not yet a qualified replacement for running any of the GitHub jobs. See [LOCAL_CI](LOCAL_CI.md). diff --git a/test/cmake/TestLocalCi.py b/test/cmake/TestLocalCi.py index acf6f177..8eef0c99 100644 --- a/test/cmake/TestLocalCi.py +++ b/test/cmake/TestLocalCi.py @@ -361,6 +361,9 @@ def test_orchestrator_transport_failure_and_unreachable_machine(self): root = pathlib.Path(os.environ["WF_TEST_REMOTE"]) if args[:2] == ["python3", "-c"]: args[2] = args[2].replace("pathlib.Path.home()", "pathlib.Path(" + repr(str(root)) + ")") +if len(args) > 1 and args[1].endswith('/worker.py'): + # This fixture emulates RyzenLinux even when hosted on macOS. + args = [sys.executable, '-c', "import sys,pathlib;sys.argv=sys.argv[1:];sys.path.insert(0,str(pathlib.Path(sys.argv[0]).resolve().parent));import worker;raise SystemExit(worker.main(hostPlatform='linux'))", *args[1:]] raise SystemExit(subprocess.run(args, cwd=root).returncode) ''') (binaries / "docker").write_text("#!" + sys.executable + "\n" + r''' diff --git a/test/cmake/TestLocalCiMacOS.py b/test/cmake/TestLocalCiMacOS.py new file mode 100644 index 00000000..b3d1ae35 --- /dev/null +++ b/test/cmake/TestLocalCiMacOS.py @@ -0,0 +1,438 @@ +"""Offline macOS driver regressions; no real account/LaunchAgent changes.""" +import argparse +import ctypes +import errno +import io +import json +import os +from pathlib import Path +import plistlib +import shutil +import socket +import subprocess +import sys +import tarfile +import tempfile +import threading +import time +import unittest +from unittest.mock import MagicMock, patch + +sys.dont_write_bytecode = True +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'cmake/local-ci')) +import orchestrator as ci +import macos_worker as mac + + +class MacCiTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix='wf-mac-test-') + self.root = Path(self.temporary.name) / '.webfront-local-ci/runs/run' + self.root.mkdir(parents=True) + self.matrix = json.loads((ci.HERE / 'lanes.json').read_text()) + self.lane = next(row for row in self.matrix['lanes'] if row['machine'] == 'Mac') + self.args = argparse.Namespace(lane=self.lane['id'], sha='a' * 40, jobs=12, timeout=1, keep=False) + ci.STOP.clear() + self.uid = patch.object(mac.os, 'getuid', return_value=501, create=True) + self.uid.start() + + def tearDown(self): + ci.STOP.clear() + self.uid.stop() + self.temporary.cleanup() + + def kit(self, platform='macos'): + dependencies = self.root / 'input' + dependencies.mkdir() + (dependencies / 'preload.cmake').write_text('# fixture') + (dependencies / 'provision.json').write_text(json.dumps({'platform': platform, 'sources': { + 'preload.cmake': {'origin': 'fixture', 'integrity': 'reviewed'}}})) + archive = self.root / 'kit.tgz' + ci.pack(argparse.Namespace(dependencies=dependencies, output=archive)) + return archive + + def test_plan_uses_native_compiler_and_complete_ctest_metadata(self): + configure, build, test = mac.buildCommands(self.lane, 12, '/CI user/work', '/CI user/deps', '/CI/cache') + for option in self.lane['common_options'] + self.lane['options']: + self.assertIn(option, configure) + for option in ('-DCMAKE_CXX_COMPILER=/usr/bin/clang++', '-DCMAKE_CXX_COMPILER_LAUNCHER=ccache', + '-DFETCHCONTENT_FULLY_DISCONNECTED=ON', '-DWEBFRONT_BOOTSTRAP_DIR=/CI user/deps/bootstrap'): + self.assertIn(option, configure) + self.assertEqual(build[-1], '4') + self.assertIn('--no-tests=error', test) + self.assertIn('--output-junit', test) + self.assertEqual(test[test.index('-C') + 1], 'Release') + + def test_launchagent_runs_in_aqua_without_privilege_or_persistent_install(self): + self.args.deadline = 123.25 + with patch.object(mac, 'checkConsole'), patch.object(mac, 'command') as run: + mac.startTask(self.root, self.args) + config = plistlib.loads((self.root / (self.args.lane + '.plist')).read_bytes()) + self.assertEqual(config['LimitLoadToSessionType'], 'Aqua') + self.assertFalse(config['AbandonProcessGroup']) + self.assertFalse(config['KeepAlive']) + self.assertNotIn('UserName', config) + self.assertEqual(config['ProgramArguments'][:2], ['/usr/bin/sandbox-exec', '-f']) + self.assertEqual(config['ProgramArguments'][-2:], ['--deadline', '123.25']) + self.assertEqual(set(config['EnvironmentVariables']), {'PATH', 'HOME', 'LANG'}) + self.assertEqual(run.call_args.args[0][1:3], ['bootstrap', mac.guiDomain()]) + self.assertEqual(Path(run.call_args.args[0][-1]).parent, self.root) + + def test_kit_integrity_and_platform(self): + archive = self.kit() + with patch.object(mac, 'command') as run: + mac.prepare(self.root, ci.digest(archive)) + self.assertEqual(run.call_args.args[0][:3], ['git', 'clone', '--mirror']) + self.assertEqual(run.call_args.kwargs['timeout'], mac.PREPARE_CLONE_TIMEOUT_SECONDS) + (self.root / 'dependencies/preload.cmake').write_text('tampered') + with self.assertRaises(ValueError): + ci.verifyKit(self.root / 'dependencies') + + def test_wrong_platform_is_rejected(self): + archive = self.kit('windows') + with patch.object(mac, 'command') as run: + with self.assertRaisesRegex(ValueError, 'platform=macos'): + mac.prepare(self.root, ci.digest(archive)) + run.assert_not_called() + + def test_bad_transfer_rejected_before_extraction(self): + (self.root / 'kit.tgz').write_bytes(b'tampered') + with self.assertRaisesRegex(ValueError, 'SHA-256'): + mac.prepare(self.root, 'bad') + self.assertFalse((self.root / 'dependencies').exists()) + + def test_console_requires_own_uid_and_gui_domain(self): + with patch.object(mac.os, 'getuid', return_value=501), \ + patch.object(mac.Path, 'stat', return_value=argparse.Namespace(st_uid=502)): + with self.assertRaises(mac.NoDesktop): + mac.checkConsole() + with patch.object(mac.os, 'getuid', return_value=501), \ + patch.object(mac.Path, 'stat', return_value=argparse.Namespace(st_uid=501)), \ + patch.object(mac.subprocess, 'run', return_value=subprocess.CompletedProcess([], 1)): + with self.assertRaises(mac.NoDesktop): + mac.checkConsole() + + def test_locked_disconnected_and_incomplete_sessions_are_skipped(self): + valid = {'kCGSSessionUserIDKey': os.getuid(), 'kCGSSessionOnConsoleKey': True, + 'kCGSessionLoginDoneKey': True, 'kCGSSessionAuditIDKey': 123} + for change in ({'CGSSessionScreenIsLocked': True}, {'kCGSSessionOnConsoleKey': False}, + {'kCGSessionLoginDoneKey': False}, {'kCGSSessionUserIDKey': -1}): + with patch.object(mac, 'checkConsole'), patch.object(mac, 'sessionInfo', return_value=valid | change), \ + patch.object(mac, 'consoleUsers', return_value=[valid | {'CGSSessionScreenIsLocked': False}]): + with self.assertRaises(mac.NoDesktop): + mac.checkDesktop() + with patch.object(mac, 'checkConsole'), patch.object(mac, 'sessionInfo', return_value=valid), \ + patch.object(mac, 'consoleUsers', return_value=[valid | {'CGSSessionScreenIsLocked': False}]): + mac.checkDesktop() + # IORegistry may omit the lock key for an unlocked session. + with patch.object(mac, 'checkConsole'), patch.object(mac, 'sessionInfo', return_value=valid), \ + patch.object(mac, 'consoleUsers', return_value=[valid]): + mac.checkDesktop() + for users in ([], [valid | {'CGSSessionScreenIsLocked': True}], + [valid | {'CGSSessionScreenIsLocked': False, 'kCGSSessionAuditIDKey': 999}]): + with patch.object(mac, 'checkConsole'), patch.object(mac, 'sessionInfo', return_value=valid), \ + patch.object(mac, 'consoleUsers', return_value=users): + with self.assertRaises(mac.NoDesktop): + mac.checkDesktop() + + def test_missing_desktop_returns_125_and_never_builds(self): + with patch.object(mac, 'checkDesktop', side_effect=mac.NoDesktop('locked')), \ + patch.object(mac, 'reportToolchain') as report: + self.assertEqual(mac.session(self.root, self.args, self.lane), 125) + report.assert_not_called() + self.assertEqual(json.loads((self.root / (self.args.lane + '.result.json')).read_text())['code'], 125) + + def test_network_precondition_fails_closed(self): + with patch.object(mac.socket, 'socket') as factory: + probe = factory.return_value.__enter__.return_value + probe.connect_ex.return_value = errno.EPERM + mac.checkNetwork() + self.assertEqual(probe.connect_ex.call_count, 2) + for code in (0, errno.ETIMEDOUT, errno.ENETUNREACH): + probe.connect_ex.return_value = code + with self.assertRaisesRegex(ValueError, 'network restriction'): + mac.checkNetwork() + + @unittest.skipUnless(sys.platform == 'darwin', 'macOS inherited network policy') + def test_real_policy_blocks_ipv4_ipv6_and_allows_loopback_and_child(self): + script = '''import socket,errno,subprocess,sys +for family,address in ((socket.AF_INET,('192.0.2.1',443)),(socket.AF_INET6,('2001:db8::1',443))): + with socket.socket(family,socket.SOCK_STREAM) as s: + s.settimeout(.2) + assert s.connect_ex(address) in (errno.EPERM,errno.EACCES) +with socket.socket() as server: + server.bind(('127.0.0.1',0));server.listen() + with socket.create_connection(server.getsockname()): + child,_=server.accept();child.close() +if len(sys.argv)==1: + subprocess.run([sys.executable,'-c',__import__('os').environ['WF_PROBE'],'child'],check=True) +''' + result = subprocess.run(['/usr/bin/sandbox-exec', '-p', mac.NETWORK_POLICY, sys.executable, '-c', script], + env=dict(os.environ, WF_PROBE=script), capture_output=True, text=True, timeout=5) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_selected_xcode_and_versions_are_reported(self): + with patch.object(mac, 'command', return_value=subprocess.CompletedProcess([], 0, + 'cmake version ' + self.lane['cmake_version'])) as run, \ + patch('sys.stdout', new_callable=io.StringIO) as output: + mac.reportToolchain(self.lane, io.StringIO()) + invocations = [call.args[0] for call in run.call_args_list] + self.assertIn(['/usr/bin/xcodebuild', '-version'], invocations) + self.assertIn(['/usr/bin/xcode-select', '-p'], invocations) + self.assertIn('No automatic parity', output.getvalue()) + with patch.object(mac, 'command', return_value=subprocess.CompletedProcess([], 0, 'cmake version 1')): + with self.assertRaisesRegex(ValueError, 'CMake version'): + mac.reportToolchain(self.lane, io.StringIO()) + + def test_session_exports_offline_cache_and_preserves_nonzero_test(self): + def execute(invocation, log, timeout): + self.assertEqual(os.environ['CPM_SOURCE_CACHE'], str(self.root.parent.parent / 'cache/cpm')) + raise subprocess.CalledProcessError(7, invocation) + with patch.object(mac, 'checkDesktop'), patch.object(mac, 'checkNetwork'), \ + patch.object(mac, 'reportToolchain'), patch.object(mac, 'command'), \ + patch.object(mac, 'runProcess', side_effect=execute), patch.dict(os.environ): + self.assertEqual(mac.session(self.root, self.args, self.lane), 1) + self.assertIn('returned non-zero exit status 7', (self.root / (self.args.lane + '.session.log')).read_text()) + + def test_failed_lane_preserves_artifacts_and_error_when_stop_fails(self): + workspace = self.root / self.args.lane + workspace.mkdir() + (workspace / 'test-results.xml').write_text('') + (self.root / (self.args.lane + '.launch.log')).write_text('launch fixture') + (self.root / (self.args.lane + '.result.json')).write_text('{"code":7}') + with patch.object(mac, 'startTask'), patch.object(mac, 'stopTask', side_effect=ValueError('stop failed')), \ + patch('sys.stdout', new_callable=io.StringIO), patch('sys.stderr', new_callable=io.StringIO): + with self.assertRaises(subprocess.CalledProcessError) as error: + mac.runLane(self.root, self.args) + self.assertEqual(error.exception.returncode, 7) + self.assertTrue(workspace.exists()) + with tarfile.open(self.root / (self.args.lane + '-artifacts.tar')) as archive: + self.assertIn('test-results.xml', archive.getnames()) + self.assertIn(self.args.lane + '.launch.log', archive.getnames()) + + def test_success_cleanup_and_keep(self): + for keep in (True, False): + workspace = self.root / self.args.lane + workspace.mkdir(exist_ok=True) + (self.root / (self.args.lane + '.result.json')).write_text('{"code":0}') + self.args.keep = keep + with patch.object(mac, 'startTask'), patch.object(mac, 'stopTask'): + self.assertEqual(mac.runLane(self.root, self.args), 0) + self.assertEqual(workspace.exists(), keep) + + def test_no_graphical_domain_is_skipped_without_launch(self): + with patch.object(mac, 'startTask', side_effect=mac.NoDesktop('no login')), \ + patch.object(mac, 'stopTask'), patch('sys.stdout', new_callable=io.StringIO): + self.assertEqual(mac.runLane(self.root, self.args), 125) + + def test_timeout_and_cancellation_are_not_success(self): + with patch.object(mac, 'startTask'), patch.object(mac, 'stopTask'), \ + patch.object(mac, 'SESSION_FINISH_GRACE_SECONDS', .01): + ci.STOP.set() + with self.assertRaises(InterruptedError): + mac.runLane(self.root, self.args) + ci.STOP.clear() + self.args.timeout = .01 + with self.assertRaises(TimeoutError): + mac.runLane(self.root, self.args) + + def test_session_uses_inherited_deadline_and_publishes_complete_timeout_log(self): + self.args.timeout = 30 + self.args.deadline = time.monotonic() + .05 + def expire(*_): + time.sleep(max(0, self.args.deadline - time.monotonic()) + .01) + print('final timeout diagnostic', flush=True) + raise TimeoutError('shared deadline') + with patch.object(mac, 'checkDesktop'), patch.object(mac, 'checkNetwork'), \ + patch.object(mac, 'reportToolchain'), patch.object(mac, 'command'), \ + patch.object(mac, 'runProcess', side_effect=expire), patch.dict(os.environ): + self.assertEqual(mac.session(self.root, self.args, self.lane), 124) + result = self.root / (self.args.lane + '.result.json') + self.assertEqual(json.loads(result.read_text())['code'], 124) + self.assertIn('final timeout diagnostic', (self.root / (self.args.lane + '.session.log')).read_text()) + + def test_lane_allows_session_to_finalize_after_shared_deadline(self): + self.args.timeout = .02 + def launch(root, args): + def finish(): + time.sleep(max(0, args.deadline - time.monotonic()) + .03) + (root / (args.lane + '.session.log')).write_text('complete timeout diagnostic') + (root / (args.lane + '.result.json')).write_text('{"code":124}') + writer = threading.Thread(target=finish) + writer.start() + writers.append(writer) + writers = [] + try: + with patch.object(mac, 'startTask', side_effect=launch), patch.object(mac, 'stopTask'), \ + patch.object(mac, 'SESSION_FINISH_GRACE_SECONDS', .3), \ + patch('sys.stdout', new_callable=io.StringIO) as output: + with self.assertRaisesRegex(TimeoutError, 'session deadline'): + mac.runLane(self.root, self.args) + self.assertIn('complete timeout diagnostic', output.getvalue()) + with tarfile.open(self.root / (self.args.lane + '-artifacts.tar')) as archive: + self.assertEqual(archive.extractfile(self.args.lane + '.session.log').read(), + b'complete timeout diagnostic') + finally: + for writer in writers: + writer.join(timeout=2) + + def test_slow_start_warns_without_failing_before_lane_deadline(self): + self.args.timeout = 1 + writers = [] + def launch(root, args): + def finish(): + time.sleep(.15) + (root / (args.lane + '.session.log')).write_text('slow successful startup') + (root / (args.lane + '.result.json')).write_text('{"code":0}') + writer = threading.Thread(target=finish) + writer.start() + writers.append(writer) + try: + with patch.object(mac, 'startTask', side_effect=launch), patch.object(mac, 'stopTask'), \ + patch.object(mac, 'STARTUP_WARNING_SECONDS', .01), \ + patch('sys.stdout', new_callable=io.StringIO) as output: + self.assertEqual(mac.runLane(self.root, self.args), 0) + self.assertIn('waiting until the shared deadline', output.getvalue()) + finally: + for writer in writers: + writer.join(timeout=2) + + def test_corefoundation_serialization_error_is_reported_and_released(self): + cg, cf = MagicMock(), MagicMock() + cg.CGSessionCopyCurrentDictionary.return_value = 1 + cf.CFErrorGetCode.return_value = -99 + def serialize(*arguments): + ctypes.cast(arguments[-1], ctypes.POINTER(ctypes.c_void_p)).contents.value = 3 + return None + cf.CFPropertyListCreateData.side_effect = serialize + with patch.object(mac.ctypes, 'CDLL', side_effect=[cg, cf]): + with self.assertRaisesRegex(mac.NoDesktop, 'CoreFoundation error -99'): + mac.sessionInfo() + self.assertEqual(cf.CFRelease.call_count, 2) + self.assertEqual(cf.CFRelease.call_args_list[-1].args[0], 1) + self.assertEqual(cf.CFRelease.call_args_list[0].args[0].value, 3) + + def test_ioreg_supports_dictionary_and_array_roots(self): + users = [{'kCGSSessionUserIDKey': 501}] + for root in ({'IOConsoleUsers': users}, [{'IOConsoleUsers': users}]): + with patch.object(mac, 'command', return_value=subprocess.CompletedProcess([], 0, plistlib.dumps(root))): + self.assertEqual(mac.consoleUsers(), users) + + def test_cleanup_retains_run_if_stop_or_collection_fails(self): + self.args.action = 'cleanup' + self.args.lane = None + with patch.object(mac, 'stopTask', side_effect=ValueError('unconfirmed')), \ + patch.object(mac, 'cleanTree') as clean, patch('sys.stdout', new_callable=io.StringIO): + with self.assertRaises(ValueError): + mac.dispatch(self.args, self.matrix, self.root) + clean.assert_not_called() + self.assertTrue(self.root.exists()) + + def test_stop_is_idempotent_only_for_confirmed_missing_service(self): + (self.root / (self.args.lane + '.plist')).touch() + for diagnosis in ('Could not find service "fixture" in domain', 'permission denied'): + with patch.object(mac.subprocess, 'run', side_effect=[subprocess.CompletedProcess([], 3, '', 'bootout failed'), + subprocess.CompletedProcess([], 113, '', diagnosis)]): + if diagnosis.startswith('Could not find service'): + mac.stopTask(self.root, self.args.lane) + else: + with self.assertRaisesRegex(ValueError, 'not confirmed'): + mac.stopTask(self.root, self.args.lane) + + def test_dispatch_rejects_other_machine_lanes(self): + self.args.action = 'lane' + self.args.lane = 'desktop-windows-msvc-webview2' + with self.assertRaisesRegex(ValueError, 'only Mac'): + mac.dispatch(self.args, self.matrix, self.root) + + def test_macos_cli_requires_kit_hash_pair(self): + with patch('sys.stderr', new_callable=io.StringIO) as output: + self.assertEqual(ci.main(['run', '--macos-kit', 'missing.tgz']), 1) + self.assertIn('supplied together', output.getvalue()) + + def test_full_macos_transport_with_native_session_standin(self): + repository = Path(self.temporary.name) / "repository" + scripts = repository / "cmake/local-ci" + shutil.copytree(ci.HERE, scripts) + (repository / ".gitignore").write_text("build*/\n__pycache__/\n") + (repository / "unpublished.txt").write_text("local commit") + subprocess.run(["git", "init", str(repository)], check=True, capture_output=True) + for invocation in [["git", "add", "."], ["git", "-c", "user.name=Test", "-c", + "user.email=test@example.org", "commit", "-m", "local fixture"]]: + subprocess.run(invocation, cwd=repository, check=True, capture_output=True) + dependencies = Path(self.temporary.name) / "prepared" + dependencies.mkdir() + (dependencies / "preload.cmake").write_text("# fixture") + (dependencies / "provision.json").write_text(json.dumps({"platform": "macos", "sources": { + "preload.cmake": {"origin": "fixture", "integrity": "reviewed"}}})) + archive = Path(self.temporary.name) / "kit.tgz" + ci.pack(argparse.Namespace(dependencies=dependencies, output=archive)) + remoteRoot = Path(self.temporary.name) / "remote account" + remoteRoot.mkdir() + shim = Path(self.temporary.name) / "ssh.py" + shim.write_text('''import pathlib,sys,runpy,json,subprocess +sys.dont_write_bytecode=True +root=pathlib.Path(sys.argv[1]) +args=sys.argv[2:] +if args[1]=='-c': + pathlib.Path.home=classmethod(lambda cls: root) + sys.argv=['-c']+args[3:] + exec(args[2]) +else: + worker=root/args[1] + sys.path.insert(0,str(worker.parent)) + import macos_worker as w + w.checkNetwork=lambda: None + w.os.getuid=lambda: 501 + def launch(root,args): + workspace=root/args.lane + subprocess.run(['git','clone',str(root/'repo.git'),str(workspace)],check=True) + subprocess.run(['git','-C',str(workspace),'checkout','--detach',args.sha],check=True) + assert (workspace/'unpublished.txt').read_text()=='local commit' + (workspace/'test-results.xml').write_text('') + (root/(args.lane+'.session.log')).write_text('native session fixture') + (root/(args.lane+'.result.json')).write_text(json.dumps({'code':int(__import__('os').environ['WF_TEST_CODE'])})) + w.startTask=launch + w.stopTask=lambda *args: None + sys.argv=[str(worker)]+args[2:] + # Exercise the native dispatch on POSIX too, without changing os.name globally. + import worker as shared,argparse + p=argparse.ArgumentParser() + p.add_argument('action') + for option in ['lane','sha','kit-sha256']: p.add_argument('--'+option) + for option in ['jobs','timeout']: p.add_argument('--'+option,type=int) + p.add_argument('--keep',action='store_true') + parsed=p.parse_args(args[2:]) + try: code=w.dispatch(parsed,json.loads((worker.parent/'lanes.json').read_text()),worker.parent) + except (ValueError,OSError,subprocess.SubprocessError): code=1 + raise SystemExit(code) +''', encoding="utf-8") + def remote(machine, arguments, **kwargs): + self.assertEqual(machine, "Mac") + return [sys.executable, str(shim), str(remoteRoot), *arguments] + args = argparse.Namespace(allow_dirty=False, commit="HEAD", machines="Mac", lanes=None, + kit=None, kit_sha256=None, macos_kit=archive, macos_kit_sha256=ci.digest(archive), + jobs=4, timeout=20, transfer_timeout=20, parallel_lanes=1, keep=False, require_all=True) + previous = Path.cwd() + try: + os.chdir(repository) + for code in (0, 7, 125): + with patch.object(ci, "remote", side_effect=remote), \ + patch.object(ci, "ssh", return_value=[sys.executable, "-c", "print('reachable')"]), \ + patch.dict(os.environ, WF_TEST_CODE=str(code)), patch("sys.stdout", new_callable=io.StringIO): + actual = ci.execute(args) + logs = "\n".join(path.read_text(errors="replace") for path in repository.glob("build-local-ci/*/*/*.log")) + self.assertEqual(actual, int(bool(code)), logs) + results = [json.loads(path.read_text()) for path in repository.glob("build-local-ci/*/*/results.json")] + self.assertEqual({row["results"][0]["status"] for row in results}, {"passed", "failed", "skipped (no interactive session)"}) + for artifact in repository.glob("build-local-ci/*/*/*-artifacts.tar"): + with tarfile.open(artifact) as stream: + self.assertIn("test-results.xml", stream.getnames()) + self.assertEqual(list((remoteRoot / ".webfront-local-ci/runs").iterdir()), []) + finally: + os.chdir(previous) + + +if __name__ == '__main__': + unittest.main() diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index e6e90b5b..a8088823 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -105,6 +105,9 @@ if(Python3_Interpreter_FOUND) add_test(NAME LocalCiWindows COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/cmake/TestLocalCiWindows.py") set_tests_properties(LocalCiWindows PROPERTIES TIMEOUT 60) + add_test(NAME LocalCiMacOS + COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/cmake/TestLocalCiMacOS.py") + set_tests_properties(LocalCiMacOS PROPERTIES TIMEOUT 60) else() message(STATUS "Skipping LocalCiOrchestrator: Python 3.10+ was not found") endif()