From 326e938d0239ef07d35c8b64675c048a8804d92d Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Sun, 25 Oct 2026 17:31:20 +0100 Subject: [PATCH] Remove local SSH CI infrastructure [#346] --- cmake/local-ci/lanes.json | 211 ----------- cmake/local-ci/linux.Dockerfile | 33 -- cmake/local-ci/macos_worker.py | 394 -------------------- cmake/local-ci/native_worker.py | 89 ----- cmake/local-ci/orchestrator.py | 444 ---------------------- cmake/local-ci/run | 11 - cmake/local-ci/windows_worker.py | 426 --------------------- cmake/local-ci/worker.py | 296 --------------- docs/CHANGELOG.md | 5 +- docs/LOCAL_CI.md | 469 ----------------------- docs/PROJECT_STATUS.md | 14 - test/cmake/CheckLocalCi.cmake | 352 ------------------ test/cmake/CheckLocalCiNegative.cmake | 149 -------- test/cmake/LocalCiCommands.cmake | 361 ------------------ test/cmake/TestLocalCi.py | 452 ---------------------- test/cmake/TestLocalCiMacOS.py | 438 ---------------------- test/cmake/TestLocalCiWindows.py | 514 -------------------------- test/unit/CMakeLists.txt | 21 -- 18 files changed, 3 insertions(+), 4676 deletions(-) delete mode 100644 cmake/local-ci/lanes.json delete mode 100644 cmake/local-ci/linux.Dockerfile delete mode 100644 cmake/local-ci/macos_worker.py delete mode 100644 cmake/local-ci/native_worker.py delete mode 100644 cmake/local-ci/orchestrator.py delete mode 100644 cmake/local-ci/run delete mode 100644 cmake/local-ci/windows_worker.py delete mode 100644 cmake/local-ci/worker.py delete mode 100644 docs/LOCAL_CI.md delete mode 100644 test/cmake/CheckLocalCi.cmake delete mode 100644 test/cmake/CheckLocalCiNegative.cmake delete mode 100644 test/cmake/LocalCiCommands.cmake delete mode 100644 test/cmake/TestLocalCi.py delete mode 100644 test/cmake/TestLocalCiMacOS.py delete mode 100644 test/cmake/TestLocalCiWindows.py diff --git a/cmake/local-ci/lanes.json b/cmake/local-ci/lanes.json deleted file mode 100644 index ae42dd88..00000000 --- a/cmake/local-ci/lanes.json +++ /dev/null @@ -1,211 +0,0 @@ -{ - "schema": 1, - "comment": "The local CI matrix (#346): one entry per lane the GitHub workflows expand to. test/cmake/CheckLocalCi.cmake fails when it drifts from .github/workflows.", - "mddlog": { - "repository": "ambroise-leclerc/mddlog", - "ref": "5b43265664d83c3b7135d328f611e685792a1b02", - "cmake_window": "4.0 to 4.3" - }, - "workflows": { - "BuildAndTest.yml": { - "jobs": ["desktop", "performance-linux", "sanitizers", "web-integration"], - "matrices": { - "desktop": {"key": "platform", "values": ["linux-gcc-webkitgtk", "windows-msvc-webview2", "macos-clang-wkwebview"]}, - "sanitizers": {"key": "sanitizer", "values": ["address-undefined", "thread"]}, - "web-integration": {"key": "compiler", "values": ["gcc", "clang"]} - } - }, - "MddlogIntegration.yml": { - "jobs": ["clang", "sanitizers"], - "matrices": { - "sanitizers": {"key": "name", "values": ["address-undefined", "thread"]} - } - } - }, - "local_differences": { - "parallelism": "GitHub builds with --parallel 2; local lanes use the jobs limit of the machine (4 compilations on Windows).", - "cache": "GitHub restores actions/cache and sccache; local lanes keep persistent CPM_SOURCE_CACHE and ccache volumes.", - "toolchain": "GitHub installs toolchains per run; local machines are prepared once (docs/LOCAL_CI.md).", - "runner_images": "ubuntu-26.04, ubuntu-24.04, windows-2025 and macos-26 runner images are replaced by pinned containers and the host systems.", - "github_only_steps": [ - "actions/upload-artifact (logs are collected by the orchestrator)", - "mozilla-actions/sccache-action (ccache replaces sccache)", - "actions/cache", - "Collect coverage upload (no Codecov step exists in the workflows; coverage.info and lcov --list stay local)", - "Cut the public network: applied to the lane container instead of the host firewall" - ] - }, - "lanes": [ - { - "id": "performance-linux-gcc-webkitgtk", - "workflow": "BuildAndTest.yml", "job": "performance-linux", "matrix": "", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu26", - "compiler": {"family": "gcc", "version": "16", "marker": "gcc-16"}, - "cmake_version": "4.4.4", "build_type": "Release", - "options": ["-DWEBFRONT_EMBED_WEBKITGTK=ON", "-DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK", "-DWEBFRONT_BUILD_EXAMPLES=OFF"], - "common_options": ["-DWEBFRONT_EMBED_CEF=OFF", "-DENABLE_TESTING=ON", "-DCMAKE_CXX_SCAN_FOR_MODULES=OFF"], - "workflow_options": ["-DENABLE_CACHE=OFF", "-DCMAKE_CXX_COMPILER_LAUNCHER=sccache"], - "targets": ["webkitgtk_transport_benchmark"], - "ctest": {"labels": ["performance"], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure", "--repeat", "until-fail:3"], "workflow_args": ["--output-junit", "@workspace@/build-performance/test-results.xml"]}, - "env": {"WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS": "1"}, - "extra_steps": ["measurement-environment", "performance-artifact"], - "evidence": ["Record measurement environment", "Retain performance report and diagnostics", "libwebkitgtk-6.0-dev"] - }, - { - "id": "desktop-linux-gcc-webkitgtk", - "workflow": "BuildAndTest.yml", "job": "desktop", "matrix": "linux-gcc-webkitgtk", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu26", - "compiler": {"family": "gcc", "version": "16", "marker": "gcc-16"}, - "cmake_version": "4.4.4", "build_type": "Debug", - "options": ["-DWEBFRONT_EMBED_WEBKITGTK=ON", "-DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK", "-DENABLE_COVERAGE=ON"], - "common_options": ["-DWEBFRONT_EMBED_CEF=OFF", "-DENABLE_TESTING=ON", "-DCMAKE_CXX_SCAN_FOR_MODULES=OFF"], - "workflow_options": ["-DENABLE_CACHE=OFF", "-DCMAKE_CXX_COMPILER_LAUNCHER=sccache"], - "targets": [], - "ctest": {"labels": [], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure", "--parallel", "4"], "workflow_args": ["--repeat", "until-fail:${{github.event_name=='workflow_dispatch'&&inputs.repeat_desktop_tests&&'3'||'1'}}", "--output-junit", "@workspace@/build/test-results.xml"]}, - "env": {"WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS": "1"}, - "extra_steps": ["lcov-coverage"], - "evidence": ["libwebkitgtk-6.0-dev", "lcov --list coverage.info", "--gcov-tool gcov-16", "--no-tests=error"] - }, - { - "id": "desktop-windows-msvc-webview2", - "workflow": "BuildAndTest.yml", "job": "desktop", "matrix": "windows-msvc-webview2", - "machine": "CurmudgeonWindows", "runtime": "native:msvc", - "compiler": {"family": "msvc", "version": "latest", "marker": "msvc-dev-cmd"}, - "cmake_version": "4.4.4", "build_type": "Release", - "options": ["-DWEBFRONT_EMBED_WEBVIEW2=ON", "-DWEBFRONT_WEBTEST_FRONTEND=WebView2"], - "common_options": ["-DWEBFRONT_EMBED_CEF=OFF", "-DENABLE_TESTING=ON", "-DCMAKE_CXX_SCAN_FOR_MODULES=OFF"], - "workflow_options": ["-DENABLE_CACHE=OFF", "-DCMAKE_CXX_COMPILER_LAUNCHER=sccache"], - "targets": [], - "ctest": {"labels": [], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure", "--parallel", "4"], "workflow_args": ["--repeat", "until-fail:${{github.event_name=='workflow_dispatch'&&inputs.repeat_desktop_tests&&'3'||'1'}}", "--output-junit", "@workspace@/build/test-results.xml"]}, - "env": {}, - "interactive_session": "required", - "extra_steps": ["webview2-runtime-check"], - "evidence": ["Ensure WebView2 Evergreen runtime", "--no-tests=error"] - }, - { - "id": "desktop-macos-clang-wkwebview", - "workflow": "BuildAndTest.yml", "job": "desktop", "matrix": "macos-clang-wkwebview", - "machine": "Mac", "runtime": "native:appleclang", - "compiler": {"family": "appleclang", "version": "xcode-latest", "marker": "xcode-version: latest"}, - "cmake_version": "4.4.4", "build_type": "Release", - "options": ["-DWEBFRONT_EMBED_WKWEBVIEW=ON", "-DWEBFRONT_WEBTEST_FRONTEND=WKWebView"], - "common_options": ["-DWEBFRONT_EMBED_CEF=OFF", "-DENABLE_TESTING=ON", "-DCMAKE_CXX_SCAN_FOR_MODULES=OFF"], - "workflow_options": ["-DENABLE_CACHE=OFF", "-DCMAKE_CXX_COMPILER_LAUNCHER=sccache"], - "targets": [], - "ctest": {"labels": [], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure", "--parallel", "4"], "workflow_args": ["--repeat", "until-fail:${{github.event_name=='workflow_dispatch'&&inputs.repeat_desktop_tests&&'3'||'1'}}", "--output-junit", "@workspace@/build/test-results.xml"]}, - "env": {}, - "interactive_session": "required", - "report": ["xcode-version"], - "evidence": ["--no-tests=error"] - }, - { - "id": "sanitizers-address-undefined", - "workflow": "BuildAndTest.yml", "job": "sanitizers", "matrix": "address-undefined", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu24-clang23", - "compiler": {"family": "clang", "version": "23", "marker": "clang-23"}, - "cmake_version": "4.4.4", "build_type": "RelWithDebInfo", - "options": ["-DENABLE_SANITIZER_ADDRESS=ON", "-DENABLE_SANITIZER_UNDEFINED_BEHAVIOR=ON", "-DENABLE_FUZZING=ON"], - "common_options": ["-DWEBFRONT_EMBED_CEF=OFF", "-DWEBFRONT_BUILD_EXAMPLES=OFF", "-DENABLE_TESTING=ON", "-DENABLE_CACHE=OFF"], - "targets": [], - "ctest": {"labels": [], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure", "--parallel", "4"], "workflow_args": ["--output-junit", "@workspace@/build-sanitizers/test-results.xml"]}, - "env": {"ASAN_OPTIONS": "detect_leaks=1:abort_on_error=1", "UBSAN_OPTIONS": "print_stacktrace=1:halt_on_error=1"}, - "fuzz_decoders": ["messages", "http", "websocket", "gzip"], - "fuzz_seconds": 30, - "evidence": ["for decoder in messages http websocket gzip", "-max_total_time=30", "libclang-rt-23-dev"] - }, - { - "id": "sanitizers-thread", - "workflow": "BuildAndTest.yml", "job": "sanitizers", "matrix": "thread", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu24-clang23", - "compiler": {"family": "clang", "version": "23", "marker": "clang-23"}, - "cmake_version": "4.4.4", "build_type": "RelWithDebInfo", - "options": ["-DCMAKE_CXX_FLAGS=-stdlib=libc++", "-DENABLE_SANITIZER_THREAD=ON"], - "common_options": ["-DWEBFRONT_EMBED_CEF=OFF", "-DWEBFRONT_BUILD_EXAMPLES=OFF", "-DENABLE_TESTING=ON", "-DENABLE_CACHE=OFF"], - "targets": [], - "ctest": {"labels": [], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure", "--parallel", "4"], "workflow_args": ["--output-junit", "@workspace@/build-sanitizers/test-results.xml"]}, - "env": {"TSAN_OPTIONS": "halt_on_error=1:second_deadlock_stack=1"}, - "host_requirements": {"sysctl": {"vm.mmap_rnd_bits": "28"}}, - "evidence": ["vm.mmap_rnd_bits=28", "libc++-23-dev"] - }, - { - "id": "web-integration-gcc", - "workflow": "BuildAndTest.yml", "job": "web-integration", "matrix": "gcc", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu24-clang23", - "compiler": {"family": "gcc", "version": "ubuntu-24.04-default", "marker": ""}, - "cmake_version": "4.4.4", "build_type": "Release", - "options": ["-DWEBFRONT_EMBED_CEF=ON"], - "common_options": ["-DWEBFRONT_BUILD_EXAMPLES=OFF", "-DENABLE_TESTING=ON"], - "targets": ["webtest", "developer_integration", "webfront-wf"], - "ctest": {"labels": ["web-integration"], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure", "--parallel", "4"], "workflow_args": ["--output-junit", "@workspace@/build-cef/test-results.xml"]}, - "env": {}, - "container": {"shm_size": "1g", "network_after_provisioning": "none"}, - "report": ["effective-compiler"], - "evidence": ["--target webtest developer_integration webfront-wf", "-L web-integration", "iptables -A OUTPUT ! -o lo -j REJECT"] - }, - { - "id": "web-integration-clang", - "workflow": "BuildAndTest.yml", "job": "web-integration", "matrix": "clang", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu24-clang23", - "compiler": {"family": "clang", "version": "23", "marker": "clang-23"}, - "cmake_version": "4.4.4", "build_type": "Release", - "options": ["-DWEBFRONT_EMBED_CEF=ON"], - "common_options": ["-DWEBFRONT_BUILD_EXAMPLES=OFF", "-DENABLE_TESTING=ON"], - "targets": ["webtest", "developer_integration", "webfront-wf"], - "ctest": {"labels": ["web-integration"], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure", "--parallel", "4"], "workflow_args": ["--output-junit", "@workspace@/build-cef/test-results.xml"]}, - "env": {"CC": "clang-23", "CXX": "clang++-23"}, - "container": {"shm_size": "1g", "network_after_provisioning": "none"}, - "evidence": ["--target webtest developer_integration webfront-wf", "-L web-integration", "lld-23"] - }, - { - "id": "mddlog-clang-source-install", - "workflow": "MddlogIntegration.yml", "job": "clang", "matrix": "", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu-clang21-libcxx", - "compiler": {"family": "clang", "version": "21", "marker": "clang-21"}, - "cmake_version": "4.3.1", "build_type": "Release", - "options": ["-DWEBFRONT_USE_MDDLOG=ON", "-DWEBFRONT_BUILD_EXAMPLES=OFF", "-DENABLE_TESTING=ON", "-DENABLE_CACHE=OFF"], - "common_options": [], - "targets": [], - "ctest": {"labels": [], "exclude_labels": [], "args": ["--no-tests=error", "--output-on-failure"]}, - "env": {}, - "modes": ["source", "installed"], - "configure_variants": [["-DWEBFRONT_MDDLOG_SOURCE_DIR=@workspace@/dependencies/mddlog"], ["-DCMAKE_PREFIX_PATH=@workspace@/mddlog-install"]], - "toolchain_file": "dependencies/mddlog/cmake/toolchains/linux-clang21-libcxx.cmake", - "evidence": ["-DWEBFRONT_MDDLOG_SOURCE_DIR=", "-DCMAKE_PREFIX_PATH=", "cmake --install build-mddlog-source/mddlog", "linux-clang21-libcxx.cmake"] - }, - { - "id": "mddlog-sanitizers-address-undefined", - "workflow": "MddlogIntegration.yml", "job": "sanitizers", "matrix": "address-undefined", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu-clang21-libcxx", - "compiler": {"family": "clang", "version": "21", "marker": "clang-21"}, - "cmake_version": "4.3.1", "build_type": "RelWithDebInfo", - "options": ["-DWEBFRONT_USE_MDDLOG=ON", "-DWEBFRONT_BUILD_EXAMPLES=OFF", "-DENABLE_TESTING=ON", "-DENABLE_CACHE=OFF"], - "common_options": [], - "toolchain_file": "dependencies/mddlog/cmake/toolchains/linux-clang21-libcxx.cmake", - "configure_variants": [["-DWEBFRONT_MDDLOG_SOURCE_DIR=@workspace@/dependencies/mddlog", "-DCMAKE_CXX_FLAGS=-stdlib=libc++ -fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer", "-DCMAKE_EXE_LINKER_FLAGS=-fsanitize=address,undefined -fno-sanitize-recover=undefined"]], - "targets": ["tests"], - "ctest": {"labels": [], "exclude_labels": [], "args": []}, - "catch2_direct": [["[transport],[weblink]", "--order", "rand", "x5"], ["--order", "rand"]], - "env": {"ASAN_OPTIONS": "detect_leaks=1:abort_on_error=1", "UBSAN_OPTIONS": "print_stacktrace=1:halt_on_error=1"}, - "sanitizer_flags": "-fsanitize=address,undefined -fno-sanitize-recover=undefined", - "evidence": ["for iteration in 1 2 3 4 5", "--target tests", "[transport],[weblink]"] - }, - { - "id": "mddlog-sanitizers-thread", - "workflow": "MddlogIntegration.yml", "job": "sanitizers", "matrix": "thread", - "machine": "RyzenLinux", "runtime": "container:linux-ubuntu-clang21-libcxx", - "compiler": {"family": "clang", "version": "21", "marker": "clang-21"}, - "cmake_version": "4.3.1", "build_type": "RelWithDebInfo", - "options": ["-DWEBFRONT_USE_MDDLOG=ON", "-DWEBFRONT_BUILD_EXAMPLES=OFF", "-DENABLE_TESTING=ON", "-DENABLE_CACHE=OFF"], - "common_options": [], - "toolchain_file": "dependencies/mddlog/cmake/toolchains/linux-clang21-libcxx.cmake", - "configure_variants": [["-DWEBFRONT_MDDLOG_SOURCE_DIR=@workspace@/dependencies/mddlog", "-DCMAKE_CXX_FLAGS=-stdlib=libc++ -fsanitize=thread -fno-omit-frame-pointer", "-DCMAKE_EXE_LINKER_FLAGS=-fsanitize=thread"]], - "targets": ["tests"], - "ctest": {"labels": [], "exclude_labels": [], "args": []}, - "catch2_direct": [["[transport],[weblink]", "--order", "rand", "x5"], ["--order", "rand"]], - "env": {"TSAN_OPTIONS": "halt_on_error=1:second_deadlock_stack=1"}, - "sanitizer_flags": "-fsanitize=thread", - "host_requirements": {"sysctl": {"vm.mmap_rnd_bits": "28"}}, - "evidence": ["vm.mmap_rnd_bits=28", "--target tests"] - } - ] -} diff --git a/cmake/local-ci/linux.Dockerfile b/cmake/local-ci/linux.Dockerfile deleted file mode 100644 index 04d934b3..00000000 --- a/cmake/local-ci/linux.Dockerfile +++ /dev/null @@ -1,33 +0,0 @@ -# Build on the development/provisioning workstation, never on the SSH test host. -# noble is the CEF/sanitizer baseline. For desktop, override BASE_IMAGE with an -# Ubuntu 26.04 digest and GCC_VERSION=16. The packer transports docker save output. -ARG BASE_IMAGE=ubuntu@sha256:008173c23f95b170204355c12626cb5a965d779a7e1283b09e9cffbb1bf33ca3 -FROM ${BASE_IMAGE} -SHELL ["/bin/bash", "-o", "pipefail", "-c"] -ARG GCC_VERSION=13 -ARG LLVM_VERSION=23 -ARG CMAKE_VERSION=4.4.4 -# Supply verified CMake release contents in the build context; no mutable installer. -COPY cmake/ /opt/cmake/ -ENV PATH="/opt/cmake/bin:${PATH}" -RUN test "$(cmake --version | head -1)" = "cmake version ${CMAKE_VERSION}" -RUN apt-get update && apt-get install -y --no-install-recommends \ - ca-certificates curl gnupg git python3 ninja-build ccache lcov xvfb xauth \ - pkg-config gcc g++ gcc-${GCC_VERSION} g++-${GCC_VERSION} \ - libwebkitgtk-6.0-dev libgtk-3-dev libnss3 libasound2t64 \ - libgbm-dev libxss1 libxcomposite1 libxdamage1 libxrandr2 \ - libatk-bridge2.0-0 libdrm2 libxkbcommon0 && rm -rf /var/lib/apt/lists/* -RUN gcc --version && g++ --version && gcc-${GCC_VERSION} --version && g++-${GCC_VERSION} --version -RUN curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key -o /tmp/llvm.asc \ - && gpg --show-keys --with-colons --fingerprint /tmp/llvm.asc \ - | grep -q 'fpr:::::::::6084F3CF814B57C1CF12EFD515CF4D18AF4F7421:' \ - && gpg --dearmor < /tmp/llvm.asc > /usr/share/keyrings/llvm.gpg \ - && . /etc/os-release \ - && echo "deb [signed-by=/usr/share/keyrings/llvm.gpg] https://apt.llvm.org/${VERSION_CODENAME}/ llvm-toolchain-${VERSION_CODENAME}-${LLVM_VERSION} main" > /etc/apt/sources.list.d/llvm.list \ - && apt-get update \ - && apt-get install -y --no-install-recommends clang-${LLVM_VERSION} clang-tidy-${LLVM_VERSION} lld-${LLVM_VERSION} \ - libclang-rt-${LLVM_VERSION}-dev libc++-${LLVM_VERSION}-dev libc++abi-${LLVM_VERSION}-dev \ - && rm -rf /var/lib/apt/lists/* /tmp/llvm.asc -# Host UID/GID override this default in docker run; no privileged runtime is used. -USER 1000:1000 -WORKDIR /workspace diff --git a/cmake/local-ci/macos_worker.py b/cmake/local-ci/macos_worker.py deleted file mode 100644 index 34f0cb27..00000000 --- a/cmake/local-ci/macos_worker.py +++ /dev/null @@ -1,394 +0,0 @@ -"""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 deleted file mode 100644 index 38555057..00000000 --- a/cmake/local-ci/native_worker.py +++ /dev/null @@ -1,89 +0,0 @@ -"""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 deleted file mode 100644 index 83dd7253..00000000 --- a/cmake/local-ci/orchestrator.py +++ /dev/null @@ -1,444 +0,0 @@ -"""Transfer a commit and verified offline kits, then run Linux/Windows/macOS lanes over SSH.""" -import argparse -import base64 -import concurrent.futures -import hashlib -import json -import os -from pathlib import Path, PurePosixPath, PureWindowsPath -import re -import shlex -import signal -import subprocess -import tarfile -import tempfile -import threading -import time -import uuid - -HERE = Path(__file__).resolve().parent -STOP = threading.Event() -MACHINES = {"RyzenLinux", "CurmudgeonWindows", "Mac"} -LANE_ID = re.compile(r"[a-z0-9][a-z0-9-]{0,63}") - - -def command(args, **kwargs): - return subprocess.run(args, check=True, **kwargs) - - -def digest(path): - result = hashlib.sha256() - with open(path, "rb") as stream: - for block in iter(lambda: stream.read(1024 * 1024), b""): - result.update(block) - return result.hexdigest() - - -def safeName(name, windows=False): - path = PurePosixPath(name) - reserved = {"CON", "PRN", "AUX", "NUL"} | {f"{p}{i}" for p in ("COM", "LPT") for i in range(1, 10)} - if (path.is_absolute() or ".." in path.parts or "\\" in name or not path.parts - or PureWindowsPath(name).drive - or (windows and any(":" in part or part.endswith((".", " ")) or - part.split(".")[0].upper() in reserved for part in path.parts))): - raise ValueError(f"Unsafe archive path: {name}") - return path - - -def extract(archive, destination, windows=False): - # No links, devices or duplicate paths: never let an archive write outside its run directory. - windows = windows or os.name == "nt" - with tarfile.open(archive) as source: - names = set() - for member in source: - name = safeName(member.name, windows=windows).as_posix() - identity = name.casefold() if windows else name - if identity in names or not (member.isfile() or member.isdir()): - raise ValueError(f"Unsupported archive member: {member.name}") - names.add(identity) - target = destination / name - if member.isdir(): - target.mkdir(parents=True, exist_ok=True) - else: - target.parent.mkdir(parents=True, exist_ok=True) - with source.extractfile(member) as src, open(target, "xb") as dst: - import shutil - shutil.copyfileobj(src, dst) - target.chmod(member.mode & 0o777) - - -def inventory(root): - result = {} - for path in sorted(root.rglob("*")): - if path.is_symlink(): - raise ValueError(f"Dereference dependency symlinks before packing: {path}") - if ".git" in path.relative_to(root).parts: - raise ValueError(f"Export source trees without Git metadata: {path}") - if path.is_file(): - result[path.relative_to(root).as_posix()] = digest(path) - elif not path.is_dir(): - raise ValueError(f"Unsupported dependency file: {path}") - return result - - -def verifyKit(root): - manifest = json.loads((root / "kit.json").read_text()) - actual = inventory(root) - del actual["kit.json"] - if actual != manifest["files"]: - raise ValueError("Offline kit integrity mismatch (missing, changed or extra files)") - if not (root / "preload.cmake").is_file(): - raise ValueError("Offline kit needs preload.cmake") - for name, image in manifest["images"].items(): - if not re.fullmatch(r"sha256:[0-9a-f]{64}", image["id"]): - raise ValueError(f"Image {name} needs an immutable Docker image ID") - safeName(image["archive"]) - if image["archive"] not in actual: - raise ValueError(f"Image archive missing: {name}") - return manifest - - -def pack(args): - root = args.dependencies.resolve() - 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") 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(): - if path.name not in {"provision.json", "kit.json"} and path.name not in config["sources"]: - raise ValueError(f"Missing source URL/revision/integrity for {path.name}") - for name, origin in config["sources"].items(): - if not isinstance(origin, dict) or not origin.get("origin") or not origin.get("integrity"): - raise ValueError(f"Incomplete source provenance: {name}") - files = inventory(root) - files.pop("kit.json", None) - manifest = dict(config, files=files, schema=1) - # Generate metadata in the archive without modifying the prepared dependency directory. - import io - with tarfile.open(args.output, "w:gz") as archive: - for name in files: - archive.add(root / name, arcname=name, recursive=False) - data = json.dumps(manifest, indent=2).encode() - info = tarfile.TarInfo("kit.json") - info.size = len(data) - archive.addfile(info, io.BytesIO(data)) - print(f"{digest(args.output)} {args.output}") - return 0 - - -def validateMatrix(matrix): - ids = set() - for lane in matrix["lanes"]: - machine, laneId = lane.get("machine"), lane.get("id") - if (not isinstance(machine, str) or machine not in MACHINES or not isinstance(laneId, str) - or not LANE_ID.fullmatch(laneId) or laneId in ids): - raise ValueError(f"Unsupported or duplicate lane metadata: {laneId!r}") - safeName(laneId, windows=True) - ids.add(laneId) - - -def selectedLanes(matrix, machines, lanes): - validateMatrix(matrix) - def names(value): - return set(value.split(",")) if value else set() - machineNames, laneNames = names(machines), names(lanes) - knownMachines = {lane["machine"] for lane in matrix["lanes"]} - knownLanes = {lane["id"] for lane in matrix["lanes"]} - if machineNames - knownMachines or laneNames - knownLanes: - raise ValueError("Unknown machine or lane selection") - result = [lane for lane in matrix["lanes"] if - (not machineNames or lane["machine"] in machineNames) and - (not laneNames or lane["id"] in laneNames)] - if not result: - raise ValueError("No lanes selected") - return result - - -def exitCode(results, requireAll): - if not any(row["status"] == "passed" for row in results): - return 1 - if any(row["status"] in {"failed", "interrupted", "timeout"} for row in results): - return 1 - return int(requireAll and any(row["status"] != "passed" for row in results)) - - -def ssh(machine, script): - if machine not in MACHINES: - raise ValueError(f"Unsupported SSH machine: {machine!r}") - return ["ssh", "-oBatchMode=yes", "-oConnectTimeout=5", "-oServerAliveInterval=10", - "-oServerAliveCountMax=2", "--", machine, script] - - -def remote(machine, args, forward_stdin=False): - if machine == "CurmudgeonWindows": - # Pass an explicit Windows command line through .NET, avoiding PowerShell - # 5.1's additional native-argument rewriting. list2cmdline handles runs of - # backslashes before quotes and at the end of quoted arguments. - inputCopy = "[Console]::OpenStandardInput().CopyTo($process.StandardInput.BaseStream); " if forward_stdin else "" - script = ("$ErrorActionPreference='Stop'; " - "[Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false); " - "[Console]::SetOut([System.IO.StreamWriter]::new([Console]::OpenStandardOutput(), " - "[System.Text.UTF8Encoding]::new($false))); " - "$start = New-Object System.Diagnostics.ProcessStartInfo; " - f"$start.FileName = {psQuote(args[0])}; " - f"$start.Arguments = {psQuote(subprocess.list2cmdline([str(arg) for arg in args[1:]]))}; " - "$start.WorkingDirectory = $HOME; $start.UseShellExecute = $false; $start.CreateNoWindow = $true; " - "$start.RedirectStandardInput = $true; " - "$process = [System.Diagnostics.Process]::Start($start); " - + inputCopy + "$process.StandardInput.Close(); " - "$process.WaitForExit(); exit $process.ExitCode") - return ssh(machine, powershell(script)) - # All values are shell quoted once, at the SSH command-string boundary. - return ssh(machine, shlex.join(args)) - - -def psQuote(value): - return "'" + str(value).replace("'", "''") + "'" - - -def powershell(script): - encoded = base64.b64encode(script.encode("utf-16-le")).decode("ascii") - return "powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand " + encoded - - -def runProcess(args, log, timeout, stdin=None): - started = time.monotonic() - process = subprocess.Popen(args, stdin=stdin or subprocess.DEVNULL, stdout=log, - stderr=subprocess.STDOUT) - try: - while process.poll() is None: - if STOP.wait(0.1): - raise InterruptedError("Interrupted") - if time.monotonic() - started > timeout: - raise TimeoutError(f"Timeout after {timeout}s") - if process.returncode: - raise subprocess.CalledProcessError(process.returncode, args) - finally: - if process.poll() is None: - if os.name == "nt": - subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10) - else: - process.terminate() - try: - process.wait(timeout=5) - except subprocess.TimeoutExpired: - process.kill() - process.wait() - - -# Bootstraps only into a unique directory under the dedicated account's CI root. -# The worker and its safe extractor are transmitted independently of the tested commit. -BOOTSTRAP = '''import pathlib,sys,tarfile -root=pathlib.Path.home()/".webfront-local-ci"/"runs"/sys.argv[1] -root.mkdir(parents=True,exist_ok=False) -with tarfile.open(fileobj=sys.stdin.buffer,mode="r|*") as archive: - for item in archive: - p=pathlib.PurePosixPath(item.name) - if p.is_absolute() or ".." in p.parts or "\\\\" in item.name or ":" in item.name or not item.isfile(): raise ValueError("Unsafe payload") - target=root/p - target.parent.mkdir(parents=True,exist_ok=True) - with archive.extractfile(item) as src,open(target,"xb") as dst: - import shutil - shutil.copyfileobj(src,dst) -print(root) -''' - - -def execute(args): - STOP.clear() - repository = Path(command(["git", "rev-parse", "--show-toplevel"], capture_output=True, - text=True).stdout.strip()) - if not args.allow_dirty and command(["git", "status", "--porcelain"], cwd=repository, - capture_output=True, text=True).stdout: - raise ValueError("Working tree is modified; commit changes or use --allow-dirty (tests the commit only)") - sha = command(["git", "rev-parse", "--verify", args.commit + "^{commit}"], cwd=repository, - capture_output=True, text=True).stdout.strip() - matrix = json.loads(command(["git", "show", sha + ":cmake/local-ci/lanes.json"], cwd=repository, - capture_output=True, text=True).stdout) - lanes = selectedLanes(matrix, args.machines, args.lanes) - runId = sha[:12] + "-" + uuid.uuid4().hex[:12] - output = repository / "build-local-ci" / sha / runId - output.mkdir(parents=True) - rows = [] - previous = signal.signal(signal.SIGINT, lambda *_: STOP.set()) - try: - with tempfile.TemporaryDirectory(prefix="webfront-local-ci-") as scratch: - scratch = Path(scratch) - kits = {} - if args.kit: - if digest(args.kit) != args.kit_sha256: - raise ValueError("Offline kit SHA-256 mismatch") - kits["RyzenLinux"] = (args.kit.resolve(), args.kit_sha256) - windowsKit = getattr(args, "windows_kit", None) - if windowsKit: - 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 - command(["git", "update-ref", ref, sha], cwd=repository) - try: - command(["git", "bundle", "create", str(bundle), ref], cwd=repository) - finally: - command(["git", "update-ref", "-d", ref], cwd=repository) - selectedMatrix = scratch / "lanes.json" - selectedMatrix.write_text(json.dumps(matrix)) - machines = {lane["machine"] for lane in lanes} - payloads = {} - for machine in machines & kits.keys(): - payload = scratch / (machine + ".tar") - 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) - payloads[machine] = payload - def workerCommand(machine, *arguments): - python = "python.exe" if machine == "CurmudgeonWindows" else "python3" - return remote(machine, [python, f".webfront-local-ci/runs/{runId}/worker.py", *arguments]) - ready = {} - def prepare(machine): - with open(output / (machine + "-prepare.log"), "wb") as log: - try: - runProcess(ssh(machine, "echo webfront-local-ci"), log, 10) - except InterruptedError: - return "interrupted" - except (subprocess.SubprocessError, TimeoutError, OSError): - return "unreachable" - if machine not in kits: - log.write(b"Missing offline kit and SHA-256 for this machine.\n") - return "failed" - try: - python = "python.exe" if machine == "CurmudgeonWindows" else "python3" - bootstrap = BOOTSTRAP if machine == "RyzenLinux" else ( - "import base64;exec(base64.b64decode(" + repr(base64.b64encode(BOOTSTRAP.encode()).decode()) + "))") - with open(payloads[machine], "rb") as stream: - runProcess(remote(machine, [python, "-c", bootstrap, runId], forward_stdin=True), log, - args.transfer_timeout, stream) - runProcess(workerCommand(machine, "prepare", "--kit-sha256", kits[machine][1]), log, - args.transfer_timeout) - return "ready" - except InterruptedError: - return "interrupted" - except TimeoutError: - return "timeout" - except (subprocess.SubprocessError, OSError): - return "failed" - with concurrent.futures.ThreadPoolExecutor(max_workers=len(machines)) as pool: - pending = {pool.submit(prepare, machine): machine for machine in machines} - for task in concurrent.futures.as_completed(pending): - ready[pending[task]] = task.result() - def laneTask(lane): - start = time.monotonic() - machine, laneId = lane["machine"], lane["id"] - status = ready[machine] - with open(output / (laneId + ".log"), "wb") as log: - if status == "ready": - try: - runProcess(workerCommand(machine, *([ - "lane", "--lane", laneId, "--sha", sha, "--jobs", str(args.jobs), - "--timeout", str(args.timeout)] + (["--keep"] if args.keep else []))), - log, args.timeout + 60) - status = "passed" - except InterruptedError: - status = "interrupted" - except TimeoutError: - status = "timeout" - except subprocess.CalledProcessError as error: - 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 in {"CurmudgeonWindows", "Mac"} else 15) - except (subprocess.SubprocessError, OSError): - 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 in {"CurmudgeonWindows", "Mac"} else 60) - except (subprocess.SubprocessError, OSError): - log.write(b"Artifact collection failed.\n") - if status == "passed": - status = "failed" - else: - log.write((status + "; see machine preparation log\n").encode()) - row = {"lane": laneId, "machine": machine, "status": status, - "seconds": round(time.monotonic() - start, 1)} - print(f"{laneId:44} {status:58} {row['seconds']:7.1f}s {machine}", flush=True) - return row - with concurrent.futures.ThreadPoolExecutor(max_workers=args.parallel_lanes) as pool: - rows = list(pool.map(laneTask, lanes)) - # Retain only explicit --keep runs; caches are outside the per-run directory. - if not args.keep: - for machine, status in ready.items(): - if machine in payloads and status != "unreachable": - with open(output / (machine + "-cleanup.log"), "wb") as log: - try: - command(workerCommand(machine, "cleanup"), stdout=log, stderr=subprocess.STDOUT, - timeout=90 if machine in {"CurmudgeonWindows", "Mac"} else 30) - except (subprocess.SubprocessError, OSError): - print(f"Cleanup not confirmed on {machine}; run {runId} retained") - finally: - signal.signal(signal.SIGINT, previous) - (output / "results.json").write_text(json.dumps({"sha": sha, "run": runId, "results": rows}, indent=2)) - complete = len(rows) == len(matrix["lanes"]) and all(r["status"] == "passed" for r in rows) - print(f"{'Complete' if complete else 'INCOMPLETE'} matrix. Logs: {output}") - return exitCode(rows, args.require_all) if not STOP.is_set() else 130 - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__) - sub = parser.add_subparsers(dest="action", required=True) - packParser = sub.add_parser("pack", help="Seal a prepared offline dependency/image directory") - packParser.add_argument("--dependencies", type=Path, required=True) - packParser.add_argument("--output", type=Path, required=True) - run = sub.add_parser("run", help="Test a commit (default: all lanes in the selected commit)") - run.add_argument("--commit", default="HEAD") - run.add_argument("--allow-dirty", action="store_true") - run.add_argument("--machines") - run.add_argument("--lanes") - run.add_argument("--require-all", action="store_true") - run.add_argument("--keep", action="store_true") - run.add_argument("--kit", type=Path) - 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) - run.add_argument("--transfer-timeout", type=int, default=1800) - args = parser.parse_args(argv) - try: - if args.action == "pack": - return pack(args) - if min(args.parallel_lanes, args.jobs, args.timeout, args.transfer_timeout) < 1: - raise ValueError("Concurrency and timeout values must be positive") - if bool(args.kit) != bool(args.kit_sha256): - 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) - return 1 diff --git a/cmake/local-ci/run b/cmake/local-ci/run deleted file mode 100644 index 513aea53..00000000 --- a/cmake/local-ci/run +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python3 -"""Local CI entry point; Python 3.10+ and its standard library only.""" -from pathlib import Path -import sys - -sys.dont_write_bytecode = True -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from orchestrator import main - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/cmake/local-ci/windows_worker.py b/cmake/local-ci/windows_worker.py deleted file mode 100644 index fc24c6a0..00000000 --- a/cmake/local-ci/windows_worker.py +++ /dev/null @@ -1,426 +0,0 @@ -"""Native Windows lane, launched in the dedicated account's interactive session. - -Provisioning (including host firewall policy) is always separate from execution. -""" -import base64 -import contextlib -import ctypes -from ctypes import wintypes -import ipaddress -import json -import os -from pathlib import Path, PureWindowsPath -import shutil -import socket -import subprocess -import sys -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): - encoded = base64.b64encode(("$ErrorActionPreference='Stop'; " + script).encode("utf-16-le")).decode() - try: - return command(["powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", - "-EncodedCommand", encoded], **kwargs) - except subprocess.CalledProcessError as error: - # Probes capture output for parsing; preserve their actual diagnosis in the lane log. - for output in (error.stdout, error.stderr): - if output: - print(output, file=sys.stderr, flush=True) - raise - - -def publicNetworks(): - # LAN SSH remains available. This is intentionally weaker than Linux network=none. - networks = [ipaddress.ip_network("0.0.0.0/0"), ipaddress.ip_network("::/0")] - for allowed in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8", - "169.254.0.0/16", "::1/128", "fc00::/7", "fe80::/10"): - subnet = ipaddress.ip_network(allowed) - networks = [part for network in networks for part in - (list(network.address_exclude(subnet)) if network.version == subnet.version - and subnet.subnet_of(network) else [network])] - return sorted(str(network) for network in networks) - - -def firewallSetup(): - addresses = ",".join(psQuote(address) for address in publicNetworks()) - return ("# Dedicated CI host only; run once as administrator, after reviewing LAN access.\n" - "Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled True\n" - "New-NetFirewallRule -Name WebFrontLocalCI-BlockPublic -DisplayName 'WebFront CI public egress block' " - "-Direction Outbound -Action Block -Enabled True -Profile Any -Protocol Any " - "-RemoteAddress " + addresses + "\n") - - -def checkNetwork(): - # Inspect effective policy, not a user-provided marker. Explicit block rules override allows. - result = ps(""" -if (@(Get-NetFirewallProfile -PolicyStore ActiveStore | Where-Object { -not $_.Enabled }).Count) { - throw 'All firewall profiles must be enabled' -} -$rule = Get-NetFirewallRule -PolicyStore ActiveStore -Name WebFrontLocalCI-BlockPublic -if ($rule.Enabled -ne 'True' -or $rule.Direction -ne 'Outbound' -or $rule.Action -ne 'Block' -or - $rule.Profile -ne 'Any') { throw 'Public egress block rule is missing or ineffective' } -$address = $rule | Get-NetFirewallAddressFilter -$port = $rule | Get-NetFirewallPortFilter -$app = $rule | Get-NetFirewallApplicationFilter -$service = $rule | Get-NetFirewallServiceFilter -$interface = $rule | Get-NetFirewallInterfaceFilter -$interfaceType = $rule | Get-NetFirewallInterfaceTypeFilter -if ($address.LocalAddress -ne 'Any' -or $port.Protocol -ne 'Any' -or - $app.Program -ne 'Any' -or $app.Package -ne 'Any' -or $service.Service -ne 'Any' -or - $interface.InterfaceAlias -ne 'Any' -or $interfaceType.InterfaceType -ne 'Any') { - throw 'Public egress block rule must cover every application, protocol and interface' -} -ConvertTo-Json -Compress -InputObject @($address.RemoteAddress) -""", capture_output=True, text=True, timeout=30) - actual = json.loads(result.stdout) - def normalized(addresses): - networks = [] - for value in addresses: - if "-" in value: - first, last = value.split("-", 1) - networks.extend(ipaddress.summarize_address_range(ipaddress.ip_address(first), - ipaddress.ip_address(last))) - else: - networks.append(ipaddress.ip_network(value, strict=False)) - return {str(net) for version in (4, 6) for net in - ipaddress.collapse_addresses(n for n in networks if n.version == version)} - if normalized(actual) != normalized(publicNetworks()): - raise ValueError("Public egress block does not cover the required IPv4/IPv6 ranges") - - -def checkDesktop(): - session = wintypes.DWORD() - kernel = ctypes.WinDLL("kernel32", use_last_error=True) - if not kernel.ProcessIdToSessionId(os.getpid(), ctypes.byref(session)) or not session.value: - raise ValueError("Windows lane needs an interactive session; SSH/session 0 is insufficient") - wts = ctypes.WinDLL("wtsapi32", use_last_error=True) - data, size = ctypes.c_void_p(), wintypes.DWORD() - if not wts.WTSQuerySessionInformationW(None, session.value, 8, ctypes.byref(data), ctypes.byref(size)): - raise ctypes.WinError(ctypes.get_last_error()) - try: - if ctypes.cast(data, ctypes.POINTER(wintypes.DWORD)).contents.value != 0: # WTSActive - raise ValueError("The Windows graphical session is disconnected") - finally: - wts.WTSFreeMemory(data) - user = ctypes.WinDLL("user32", use_last_error=True) - user.OpenInputDesktop.restype = wintypes.HANDLE - desktop = user.OpenInputDesktop(0, False, 0x0100) # DESKTOP_SWITCHDESKTOP - if not desktop: - raise ValueError("The Windows input desktop is unavailable; unlock the dedicated session") - user.CloseDesktop.argtypes = [wintypes.HANDLE] - user.CloseDesktop(desktop) - - -def ownProcessTree(): - """Keep the Job handle alive: killing the scheduled worker also kills all descendants.""" - class BasicLimits(ctypes.Structure): - _fields_ = [("ProcessTime", ctypes.c_int64), ("JobTime", ctypes.c_int64), - ("LimitFlags", wintypes.DWORD), ("MinWorkingSet", ctypes.c_size_t), - ("MaxWorkingSet", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD), - ("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD), - ("SchedulingClass", wintypes.DWORD)] - class IoCounters(ctypes.Structure): - _fields_ = [(name, ctypes.c_uint64) for name in - ("ReadOps", "WriteOps", "OtherOps", "ReadBytes", "WriteBytes", "OtherBytes")] - class ExtendedLimits(ctypes.Structure): - _fields_ = [("Basic", BasicLimits), ("Io", IoCounters), - ("ProcessMemory", ctypes.c_size_t), ("JobMemory", ctypes.c_size_t), - ("PeakProcessMemory", ctypes.c_size_t), ("PeakJobMemory", ctypes.c_size_t)] - kernel = ctypes.WinDLL("kernel32", use_last_error=True) - kernel.CreateJobObjectW.restype = wintypes.HANDLE - kernel.GetCurrentProcess.restype = wintypes.HANDLE - kernel.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD] - kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE] - handle = kernel.CreateJobObjectW(None, None) - limits = ExtendedLimits() - limits.Basic.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE - if (not handle or not kernel.SetInformationJobObject(handle, 9, ctypes.byref(limits), ctypes.sizeof(limits)) - or not kernel.AssignProcessToJobObject(handle, kernel.GetCurrentProcess())): - raise ctypes.WinError(ctypes.get_last_error()) - # Never close this handle while the worker is alive (the worker itself belongs to the Job). - return handle - - -def msvcEnvironment(): - vswhere = Path(os.environ.get("ProgramFiles(x86)", "C:/Program Files (x86)")) / \ - "Microsoft Visual Studio/Installer/vswhere.exe" - installation = command([str(vswhere), "-latest", "-products", "*", "-requires", - "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"], - capture_output=True, text=True, timeout=30).stdout.strip() - devcmd = Path(installation) / "Common7/Tools/VsDevCmd.bat" - if not installation or not devcmd.is_file(): - raise ValueError("Install Visual Studio MSVC x64 C++ tools and a Windows SDK") - # devcmd comes from vswhere, not from the commit/kit. Only this fixed shell sequence is evaluated. - # cmd's /s quoting is not CommandLineToArgvW: list2cmdline would escape these - # inner quotes and break every installation under Program Files. - result = command('cmd.exe /d /s /c ""' + str(devcmd) + - '" -no_logo -arch=x64 -host_arch=x64 >nul && set"', - capture_output=True, text=True, timeout=60) - return dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line and not line.startswith("=")) - - -def checkRuntime(): - result = ps(""" -$roots = @("${env:ProgramFiles(x86)}/Microsoft/EdgeWebView/Application", - "$env:ProgramFiles/Microsoft/EdgeWebView/Application", - "$env:LOCALAPPDATA/Microsoft/EdgeWebView/Application") -$runtime = @($roots | Where-Object { Test-Path -LiteralPath $_ } | ForEach-Object { - Get-ChildItem -LiteralPath $_ -Filter msedgewebview2.exe -Recurse -}) -if (-not $runtime.Count) { throw 'Provision WebView2 Evergreen before running offline' } -$runtime | ForEach-Object { - if (-not $_.VersionInfo.FileVersion) { throw 'WebView2 runtime has no version' } - Write-Output "WebView2 $($_.VersionInfo.FileVersion) at $($_.FullName)" -} -""", capture_output=True, text=True, timeout=30) - print(result.stdout, flush=True) - - -def buildCommands(lane, jobs, workspace, dependencies, cache): - workspace, dependencies, cache = map(PureWindowsPath, (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=cl", "-DCMAKE_CXX_COMPILER_LAUNCHER=sccache", - "-DCPM_SOURCE_CACHE=" + cache.as_posix() + "/cpm", "-DFETCHCONTENT_FULLY_DISCONNECTED=ON", - "-DWEBFRONT_BOOTSTRAP_DIR=" + (dependencies / "bootstrap").as_posix(), - "-DWEBFRONT_REGISTRY_DIR=" + (dependencies / "registry").as_posix()] - buildArgs = ["cmake", "--build", str(build), "--config", lane["build_type"], - "--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 digest(root / "kit.tgz") != expected: - raise ValueError("Transferred Windows kit SHA-256 mismatch") - dependencies = root / "dependencies" - dependencies.mkdir() - extract(root / "kit.tgz", dependencies, windows=True) - manifest = verifyKit(dependencies) - if manifest.get("platform") != "windows" or manifest["images"]: - raise ValueError("Windows needs a platform=windows kit without Docker images") - checkNetwork() - 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")]) - - -def taskName(root, lane): - return "WebFrontCI-" + root.name + "-" + lane - - -def startTask(root, args): - arguments = subprocess.list2cmdline(["-u", str(root / "worker.py"), "session", "--lane", args.lane, - "--sha", args.sha, "--jobs", str(min(args.jobs, 4)), - "--timeout", str(args.timeout)]) - name = psQuote(taskName(root, args.lane)) - ps(f""" -$action = New-ScheduledTaskAction -Execute {psQuote(sys.executable)} -Argument {psQuote(arguments)} -WorkingDirectory {psQuote(root)} -$principal = New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited -$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Seconds {args.timeout + 30}) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Register-ScheduledTask -TaskName {name} -Action $action -Principal $principal -Settings $settings | Out-Null -Start-ScheduledTask -TaskName {name} -""", timeout=30) - - -def stopTask(root, lane): - (root / (lane + ".cancel")).touch() - name = psQuote(taskName(root, lane)) - ps(f""" -$task = Get-ScheduledTask -TaskName {name} -ErrorAction SilentlyContinue -if ($task) {{ - Stop-ScheduledTask -TaskName {name} - $deadline = (Get-Date).AddSeconds(10) - while ((Get-ScheduledTask -TaskName {name}).State -eq 'Running') {{ - if ((Get-Date) -gt $deadline) {{ throw 'Scheduled task cancellation was not confirmed' }} - Start-Sleep -Milliseconds 100 - }} - Unregister-ScheduledTask -TaskName {name} -Confirm:$false -}} -""", timeout=15) - - -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 = 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: - job = ownProcessTree() - checkDesktop() - checkNetwork() - os.environ.update(msvcEnvironment()) - os.environ.update(lane.get("env", {})) - cache = root.parent.parent / "cache" - (cache / "sccache").mkdir(parents=True, exist_ok=True) - # CTest's independent CMake projects do not inherit configure's -D entries. - os.environ["CPM_SOURCE_CACHE"] = (cache / "cpm").as_posix() - os.environ["SCCACHE_DIR"] = str(cache / "sccache") - # A lane owns its server so cancel/timeout cannot kill another run's cache server. - with socket.socket() as listener: - listener.bind(("127.0.0.1", 0)) - os.environ["SCCACHE_SERVER_PORT"] = str(listener.getsockname()[1]) - os.environ["SCCACHE_IDLE_TIMEOUT"] = "0" - version = command(["cmake", "--version"], capture_output=True, text=True).stdout - print(version, flush=True) - if version.splitlines()[0] != "cmake version " + lane["cmake_version"]: - raise ValueError("CMake version does not match the Windows lane") - command(["cl"], stdout=log, stderr=log) # compiler banner and effective toolset - command(["sccache", "--version"], stdout=log, stderr=log) - checkRuntime() - workspace = root / args.lane - command(["git", "clone", "--no-hardlinks", str(root / "repo.git"), str(workspace)], stdout=log, stderr=log) - command(["git", "-C", str(workspace), "checkout", "--detach", args.sha], stdout=log, stderr=log) - 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())) - code = 0 - except (ValueError, OSError, subprocess.SubprocessError, InterruptedError, TimeoutError) as error: - code = 124 if time.monotonic() >= deadline else 1 - print(f"Windows lane: {error}", flush=True) - finally: - done.set() - watcher.join() - temporary = result.with_suffix(".tmp") - temporary.write_text(json.dumps({"code": code}), encoding="utf-8") - temporary.replace(result) - return code - - -def finishLane(root, args): - """Return secondary errors; always try both diagnostic paths, never delete a live checkout.""" - errors = [] - stopped = False - try: - stopTask(root, args.lane) - stopped = True - except Exception as error: - errors.append(("Task stop", error)) - try: - collect(root, args.lane) - except Exception as error: - errors.append(("Artifact collection", error)) - try: - log = root / (args.lane + ".session.log") - if log.exists(): - print(log.read_text(encoding="utf-8", errors="replace"), flush=True) - except Exception as error: - errors.append(("Session log", error)) - # If collecting diagnostics failed, retain the source files for manual recovery too. - 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 runLane(root, args): - try: - with runLock(root): - if not root.exists() or (root / (args.lane + ".cancel")).exists(): - raise InterruptedError("Windows run was already stopped or removed") - startTask(root, args) - deadline = time.monotonic() + args.timeout - result = root / (args.lane + ".result.json") - while not result.exists(): - if STOP.wait(0.1) or (root / (args.lane + ".cancel")).exists() or not root.exists(): - raise InterruptedError("Windows lane interrupted") - if time.monotonic() >= deadline: - raise TimeoutError("Windows lane deadline expired (check the interactive account/session)") - if (time.monotonic() > deadline - args.timeout + 15 - and not (root / (args.lane + ".session.log")).exists()): - raise ValueError("Interactive task did not start; log on and unlock the dedicated Windows account") - code = json.loads(result.read_text(encoding="utf-8"))["code"] - if code == 124: - raise TimeoutError("Windows session deadline expired") - if code: - raise subprocess.CalledProcessError(code, "Windows graphical session") - finally: - original = sys.exc_info()[1] - try: - with runLock(root): - # A recovery channel may have collected/removed the run already. - 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["runtime"] != "native:msvc": - raise ValueError("Windows worker accepts only native:msvc lanes") - if args.action == "prepare": - prepare(root, args.kit_sha256) - elif args.action == "lane": - runLane(root, args) - elif args.action == "session": - return session(root, args, lane) - elif args.action == "stop": - with runLock(root): - if root.exists(): - # Recover artifacts before a late execution channel can finalize/remove its checkout. - args.keep = True - errors = finishLane(root, args) - for stage, error in errors: - print(f"{stage} failed: {error}", file=sys.stderr, flush=True) - if errors: - raise errors[0][1] - elif args.action == "artifacts": - # Windows text-mode stdout translates LF bytes; the SSH artifact stream must be binary. - if os.name == "nt": - import msvcrt - msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) - with runLock(root): - with open(root / (args.lane + "-artifacts.tar"), "rb") as source: - shutil.copyfileobj(source, sys.stdout.buffer) - elif args.action == "cleanup": - if root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci": - raise ValueError("Refusing cleanup outside a local CI run") - with runLock(root): - if root.exists(): - # A failed cancellation must never turn cleanup into deletion of a live task's files. - for row in matrix["lanes"]: - if row["runtime"] == "native:msvc": - stopTask(root, row["id"]) - cleanTree(root, root) - else: - raise ValueError("Unsupported Windows action") - return 0 - - -if __name__ == "__main__": - if sys.argv[1:] == ["--print-firewall-setup"]: - print(firewallSetup()) - else: - raise SystemExit("Use worker.py, or --print-firewall-setup during host provisioning") diff --git a/cmake/local-ci/worker.py b/cmake/local-ci/worker.py deleted file mode 100644 index b0c109f6..00000000 --- a/cmake/local-ci/worker.py +++ /dev/null @@ -1,296 +0,0 @@ -"""Remote Linux worker and in-container lane executor. Never downloads dependencies.""" -import argparse -import json -import os -from pathlib import Path, PurePosixPath -import shutil -import signal -import subprocess -import sys -import tarfile - -sys.dont_write_bytecode = True -from orchestrator import command, digest, extract, verifyKit, runProcess, STOP, validateMatrix - -ROOT = Path(__file__).resolve().parent - -CLEAN_WORKSPACE = """from pathlib import Path -import shutil -for child in Path('/workspace').iterdir(): - if child.is_dir() and not child.is_symlink(): - shutil.rmtree(child) - else: - child.unlink() -""" - - -def cleanWorkspace(workspace, image, laneId): - # Browser profiles can be 0700, owned by the container's mapped UID rather - # than the host account. Reuse the test UID to remove them without extra caps. - name = containerName(laneId) + "-cleanup" - try: - command(["docker", "run", "--rm", "--pull=never", "--network=none", "--name", name, - "--user", f"{os.getuid()}:{os.getgid()}", "--group-add=0", "--cap-drop=ALL", - "--security-opt=no-new-privileges", - "--mount", f"type=bind,src={workspace},dst=/workspace", - image, "python3", "-c", CLEAN_WORKSPACE], timeout=60) - finally: - subprocess.run(["docker", "rm", "-f", name], stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, timeout=15) - workspace.rmdir() - - -def shareDirectory(path): - # In rootless Docker, container group 0 maps to the dedicated host account's group. - # Setgid + group writes let the non-root container and host collect/clean the same tree. - for directory, _, files in os.walk(path): - target = Path(directory) - target.chmod(target.stat().st_mode | 0o2070) - for name in files: - target = Path(directory) / name - if not target.is_symlink(): - target.chmod(target.stat().st_mode | 0o060) - - -def containerName(lane): - return "wf-" + ROOT.name + "-" + lane - - -def prepare(expected): - if os.getuid() == 0: - raise ValueError("Use a dedicated non-root SSH account and rootless Docker") - security = command(["docker", "info", "--format", "{{json .SecurityOptions}}"], - capture_output=True, text=True).stdout - if "name=rootless" not in json.loads(security): - raise ValueError("The dedicated account must use rootless Docker") - if digest(ROOT / "kit.tgz") != expected: - raise ValueError("Transferred kit SHA-256 mismatch") - dependencies = ROOT / "dependencies" - dependencies.mkdir() - extract(ROOT / "kit.tgz", dependencies) - manifest = verifyKit(dependencies) - 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) - for image in manifest["images"].values(): - command(["docker", "load", "--input", str(dependencies / image["archive"])]) - command(["docker", "image", "inspect", image["id"]], stdout=subprocess.DEVNULL) - # --mirror preserves refs/local-ci/*, including a detached commit with no branch. - command(["git", "clone", "--mirror", str(ROOT / "commit.bundle"), str(ROOT / "repo.git")]) - - -def ctestCommand(lane, build): - ctest = lane["ctest"] - args = ["ctest", "--test-dir", str(build)] + ctest["args"] - for label in ctest["labels"]: - args += ["-L", label] - for label in ctest["exclude_labels"]: - args += ["-LE", label] - return args - - -def buildCommands(lane, jobs, workspace="/workspace"): - """The same lane data used by the drift checker supplies every build/test command.""" - # Commands run in a Linux container even when planned/tested on Windows. - workspace = PurePosixPath(workspace) - commands = [] - variants = lane.get("configure_variants", [[]]) - for index, variant in enumerate(variants): - build = workspace / f"build-local-{index}" - options = lane["common_options"] + lane["options"] + variant - options = [option.replace("@workspace@", str(workspace)) for option in options] - configure = ["cmake", "-S", str(workspace), "-B", str(build), "-G", "Ninja", - "-C", "/deps/preload.cmake", "-DCMAKE_BUILD_TYPE=" + lane["build_type"]] - if lane.get("toolchain_file"): - configure += ["-DCMAKE_TOOLCHAIN_FILE=" + str(workspace / lane["toolchain_file"])] - configure += options - if "-DWEBFRONT_EMBED_CEF=ON" in options: - configure += ["-DFETCHCONTENT_SOURCE_DIR_CEF_BINARIES=" + str(build / "_deps/cef_binaries-src")] - # Local differences are intentional: CPM/ccache persistence, local JUnit paths. - configure += ["-DCPM_SOURCE_CACHE=/cache/cpm", "-DFETCHCONTENT_FULLY_DISCONNECTED=ON", - "-DWEBFRONT_BOOTSTRAP_DIR=/deps/bootstrap", "-DWEBFRONT_REGISTRY_DIR=/deps/registry", - "-DCMAKE_CXX_COMPILER_LAUNCHER=ccache"] - commands.append(configure) - buildArgs = ["cmake", "--build", str(build), "--parallel", str(jobs)] - if lane["targets"]: - buildArgs += ["--target"] + lane["targets"] - commands.append(buildArgs) - if lane.get("catch2_direct"): - for invocation in lane["catch2_direct"]: - repeat = int(invocation[-1][1:]) if invocation[-1].startswith("x") else 1 - arguments = invocation[:-1] if repeat != 1 else invocation - for _ in range(repeat): - commands.append([str(build / "test/unit/tests")] + arguments) - else: - commands.append(ctestCommand(lane, build) + ["--output-junit", str(build / "test-results.xml")]) - if lane.get("modes") and index == 0: - commands.append(["cmake", "--install", str(build / "mddlog"), "--prefix", - str(workspace / "mddlog-install")]) - build = workspace / "build-local-0" - for decoder in lane.get("fuzz_decoders", []): - commands.append([str(build / f"test/fuzz/fuzz_{decoder}"), - str(build / f"test/fuzz/corpus/{decoder}"), - f"-max_total_time={lane['fuzz_seconds']}", "-timeout=5", "-max_len=65536", - "-rss_limit_mb=1024", f"-artifact_prefix={build}/test/fuzz/artifacts/{decoder}-"]) - if "lcov-coverage" in lane.get("extra_steps", []): - coverage = str(build / "coverage.info") - commands += [ - ["lcov", "--ignore-errors", "inconsistent,inconsistent", "--gcov-tool", "gcov-16", "--capture", - "--directory", str(build), "--output-file", coverage], - ["lcov", "--ignore-errors", "inconsistent,inconsistent", "--remove", coverage, - "/usr/*", "*/examples/*", "--output-file", coverage], - ["lcov", "--list", coverage]] - return commands - - -def executeInside(lane, jobs): - os.umask(0o002) - cmakeVersion = command(["cmake", "--version"], capture_output=True, text=True).stdout - print(cmakeVersion, flush=True) - if cmakeVersion.splitlines()[0] != "cmake version " + lane["cmake_version"]: - raise ValueError("CMake version does not match the lane") - family, version = lane["compiler"]["family"], lane["compiler"]["version"] - if family == "clang": - os.environ.update(CC="clang-" + version, CXX="clang++-" + version) - elif version == "16": - os.environ.update(CC="gcc-16", CXX="g++-16") - else: - os.environ.update(CC="gcc", CXX="g++") - command([os.environ["CXX"], "--version"]) - command(["ccache", "--version"]) - if family == "clang" or version == "16": - actual = command([os.environ["CXX"], "-dumpversion"], capture_output=True, text=True).stdout.strip() - if actual.split(".")[0] != version: - raise ValueError("Compiler major version does not match the lane") - # Apply the WebKit sandbox exception only to test commands, as in the workflow. - env = lane.get("env", {}) - os.environ.update({key: value for key, value in env.items() if key != "WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS"}) - # CTest subconfigurations must reuse the prepared CPM module too. - os.environ.update(CPM_SOURCE_CACHE="/cache/cpm", CCACHE_DIR="/cache/ccache", CCACHE_BASEDIR="/workspace") - if "-DWEBFRONT_EMBED_CEF=ON" in lane["options"]: - # CEFSupport copies runtime resources into this SDK tree during the build. - # Keep that writable tree private to the lane, at the path CEFSupport uses. - shutil.copytree("/deps/cef-binaries", "/workspace/build-local-0/_deps/cef_binaries-src") - shareDirectory(Path("/workspace/build-local-0/_deps/cef_binaries-src")) - for invocation in buildCommands(lane, jobs): - if lane.get("fuzz_decoders"): - Path("/workspace/build-local-0/test/fuzz/artifacts").mkdir(parents=True, exist_ok=True) - print("+", repr(invocation), flush=True) - testEnv = dict(os.environ) - if invocation[0] == "ctest": - testEnv.update(env) - command(invocation, cwd="/workspace", env=testEnv) - command(["ccache", "--show-stats"]) - - -def runLane(args, matrix): - lane = next(row for row in matrix["lanes"] if row["id"] == args.lane) - if not lane["runtime"].startswith("container:"): - raise ValueError("Native lanes are not implemented in delivery step 2") - for key, expected in lane.get("host_requirements", {}).get("sysctl", {}).items(): - actual = command(["sysctl", "-n", key], capture_output=True, text=True).stdout.strip() - if actual != expected: - raise ValueError(f"Host requires {key}={expected}; found {actual}. Ask its owner to configure it.") - manifest = json.loads((ROOT / "dependencies/kit.json").read_text()) - image = manifest["images"][lane["runtime"].split(":", 1)[1]]["id"] - workspace = ROOT / lane["id"] - # A standalone .git works at /workspace in the container; linked worktrees - # would retain absolute host paths in their .git files and object alternates. - workspace.mkdir() - command(["git", "clone", "--mirror", "--no-hardlinks", str(ROOT / "repo.git"), str(workspace / ".git")]) - command(["git", "-C", str(workspace), "config", "core.bare", "false"]) - command(["git", "-C", str(workspace), "checkout", "--detach", args.sha]) - if lane["workflow"] == "MddlogIntegration.yml": - if manifest.get("mddlog_ref") != matrix["mddlog"]["ref"]: - raise ValueError("Offline kit mddlog revision does not match lanes.json") - shutil.copytree(ROOT / "dependencies/mddlog", workspace / "dependencies/mddlog") - cache = ROOT.parent.parent / "cache" - (cache / "cpm").mkdir(parents=True, exist_ok=True) - (cache / "ccache").mkdir(parents=True, exist_ok=True) - shareDirectory(workspace) - # Do not traverse shared caches while another lane is writing them. - for directory in (cache, cache / "cpm", cache / "ccache"): - directory.chmod(directory.stat().st_mode | 0o2070) - invocation = ["docker", "run", "--rm", "--pull=never", "--name", containerName(args.lane), - "--network=none", "--shm-size=" + lane.get("container", {}).get("shm_size", "1g"), - "--user", f"{os.getuid()}:{os.getgid()}", "--group-add=0", "--cap-drop=ALL", - "--security-opt=no-new-privileges", "--init", - "--mount", f"type=bind,src={workspace},dst=/workspace", - "--mount", f"type=bind,src={ROOT / 'dependencies'},dst=/deps,readonly", - "--mount", f"type=bind,src={ROOT},dst=/runner,readonly", - "--mount", f"type=bind,src={cache},dst=/cache", - "--env", "GIT_CONFIG_COUNT=1", "--env", "GIT_CONFIG_KEY_0=safe.directory", - "--env", "GIT_CONFIG_VALUE_0=/workspace", - "--env", "HOME=/tmp", "--workdir", "/workspace", image, - "python3", "/runner/worker.py", "inside", "--lane", args.lane, "--jobs", str(args.jobs)] - try: - runProcess(invocation, sys.stdout, args.timeout) - finally: - # Stop is idempotent; a timeout or disconnected SSH must not leave a running container. - subprocess.run(["docker", "rm", "-f", containerName(args.lane)], stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, timeout=15) - # Save diagnostics before removing the worktree, including failed configurations. - with tarfile.open(ROOT / (args.lane + "-artifacts.tar"), "w") as archive: - for pattern in ("**/coverage.info", "**/test-results.xml", "**/LastTest.log", - "**/CMakeConfigureLog.yaml", "**/artifacts/*"): - 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) - if not args.keep: - cleanWorkspace(workspace, image, args.lane) - - -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") - parser.add_argument("--lane") - 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()) - if hasattr(signal, "SIGHUP"): - signal.signal(signal.SIGHUP, lambda *_: STOP.set()) - matrix = json.loads((ROOT / "lanes.json").read_text()) - try: - 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) - if args.action == "prepare": - prepare(args.kit_sha256) - elif args.action == "lane": - runLane(args, matrix) - elif args.action == "inside": - executeInside(next(row for row in matrix["lanes"] if row["id"] == args.lane), args.jobs) - elif args.action == "stop": - command(["docker", "rm", "-f", containerName(args.lane)]) - elif args.action == "artifacts": - with open(ROOT / (args.lane + "-artifacts.tar"), "rb") as source: - shutil.copyfileobj(source, sys.stdout.buffer) - elif args.action == "cleanup": - if ROOT.parent.name != "runs" or ROOT.parent.parent.name != ".webfront-local-ci": - raise ValueError("Refusing cleanup outside a local CI run") - shutil.rmtree(ROOT) - return 0 - except TimeoutError as error: - print(f"local-ci worker: {error}", file=sys.stderr, flush=True) - return 124 - except (ValueError, KeyError, OSError, subprocess.SubprocessError, InterruptedError) as error: - print(f"local-ci worker: {error}", file=sys.stderr, flush=True) - return 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index af2a5f0e..a412a95b 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- Remove the local SSH CI orchestrator, container definitions, native session workers and matrix drift checks. + The GitHub-hosted workflows remain the CI execution path. + - The allocation-counting regression is omitted from ThreadSanitizer builds, whose C++ runtime defines the same global `new`/`delete` operators; ordinary and ASan/UBSan builds retain it. macOS adds `WKWebViewTransportBenchmark` (HTML bridge, native strings, `callAsyncJavaScript` and base64 bytes) and separate native @@ -23,8 +26,6 @@ `Messages.hpp` wrote to the standard output for every encoded parameter, and `Frame::addBuffer` formatted a hex dump of every buffer before the log level was tested. -- Local CI matrix, step 1 of 3 (#346): `cmake/local-ci/lanes.json` describes the ten lanes of `BuildAndTest.yml` and `MddlogIntegration.yml` (machine, toolchain, CMake, options, targets, CTest labels), `docs/LOCAL_CI.md` documents them and their differences with GitHub, and the offline CTest cases `LocalCiLanesMatchWorkflows` and `LocalCiLanesRejectDrift` fail when the lanes and the workflows diverge. Command options are compared in both directions for each matrix variant; extra matrix axes and exclusions are rejected explicitly. The orchestrator, the Linux containers and the Windows and macOS sessions follow in steps 2 and 3. - - The README animation draws the C++ application inside the image, beside the WebFront window (#359): it is no longer cropped by the table column on narrow screens and in the GitHub app, and weighs 0.4 MB instead of 1.2 MB. The code stays in the README as text, in a collapsed block; `docs/tools/render-life-bootstrap.py` reads it from there. - The manifest and the lock of the repository move to `js/developer/` (#354): the driver and the CI select them with `--manifest-dir js/developer`, and the closed list of the root loses two entries (9 left). diff --git a/docs/LOCAL_CI.md b/docs/LOCAL_CI.md deleted file mode 100644 index c3d4f638..00000000 --- a/docs/LOCAL_CI.md +++ /dev/null @@ -1,469 +0,0 @@ -# Local CI matrix - -Story #346: run the whole CI matrix of WebFront from a development machine, over SSH, on three machines of the local network -(`RyzenLinux`, `CurmudgeonWindows`, `Mac`), to validate a commit before pushing it. The machines stay under the sole control of -their owner: no self-hosted GitHub runner, no inbound connection from GitHub, no GitHub secret on the machines. GitHub CI remains the -reference for pull requests. - -## State of the delivery - -The story is delivered in three verifiable steps; a partial step does not close it. - -| Step | Content | State | -| --- | --- | --- | -| 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 and macOS implementations delivered; real-host qualification and timings pending | - -## The lanes - -`BuildAndTest.yml` expands to eight lanes and `MddlogIntegration.yml` to three. The workflows' trigger conditions (push, schedule, -manual dispatch) do not exempt the local matrix from the extended lanes: a full run selects all eleven. - -| Lane | GitHub job | Machine | Toolchain | CMake | -| --- | --- | --- | --- | --- | -| `performance-linux-gcc-webkitgtk` | `performance-linux` | `RyzenLinux` (container) | GCC 16, Release, WebKitGTK, three performance runs | 4.4.4 | -| `desktop-linux-gcc-webkitgtk` | `desktop` / `linux-gcc-webkitgtk` | `RyzenLinux` (container) | GCC 16, Debug, coverage, WebKitGTK | 4.4.4 | -| `desktop-windows-msvc-webview2` | `desktop` / `windows-msvc-webview2` | `CurmudgeonWindows` (native) | MSVC, Release, WebView2 | 4.4.4 | -| `desktop-macos-clang-wkwebview` | `desktop` / `macos-clang-wkwebview` | `Mac` (native) | AppleClang (latest Xcode), Release, WKWebView | 4.4.4 | -| `sanitizers-address-undefined` | `sanitizers` / `address-undefined` | `RyzenLinux` (container) | Clang 23, ASan+UBSan, fuzzing of four decoders | 4.4.4 | -| `sanitizers-thread` | `sanitizers` / `thread` | `RyzenLinux` (container) | Clang 23, TSan, libc++, `vm.mmap_rnd_bits=28` on the host | 4.4.4 | -| `web-integration-gcc` | `web-integration` / `gcc` | `RyzenLinux` (container) | GCC of Ubuntu 24.04 (effective version reported, not GCC 16), CEF | 4.4.4 | -| `web-integration-clang` | `web-integration` / `clang` | `RyzenLinux` (container) | Clang 23, CEF | 4.4.4 | -| `mddlog-clang-source-install` | `clang` | `RyzenLinux` (container) | Clang 21, libc++, source then installed mddlog | 4.3.1 | -| `mddlog-sanitizers-address-undefined` | `sanitizers` / `address-undefined` | `RyzenLinux` (container) | Clang 21, libc++, ASan+UBSan, Catch2 run directly | 4.3.1 | -| `mddlog-sanitizers-thread` | `sanitizers` / `thread` | `RyzenLinux` (container) | Clang 21, libc++, TSan, Catch2 run directly | 4.3.1 | - -mddlog lanes use the revision pinned in `MddlogIntegration.yml`; CMake 4.3.1 stays in the qualified 4.0 to 4.3 window. - -## Drift check - -`cmake/local-ci/lanes.json` is the single source. The CTest case `LocalCiLanesMatchWorkflows` runs -`test/cmake/CheckLocalCi.cmake` offline on the workflows as text and fails when: - -- a workflow job or matrix value has no lane, or a lane matches no job or matrix value; duplicate values, additional matrix axes, - exclusions and unsupported matrix syntax are rejected explicitly; -- the build type, an option, a target, a CTest label or argument, a sanitizer flag, an environment variable, a sysctl, the fuzzed - decoders or their duration, the compiler or the pinned CMake version of a lane differs from its job; -- the mddlog revision or repository of a lane differs from the workflow; -- this document does not name a lane; -- the declaration of the local differences below is removed. - -Configure options, build targets and CTest arguments are compared in both directions, after substituting the selected matrix row -and the sanitizer's string conditional. An additional option or test filter is drift too. Each switch keeps its operand during -comparison. Every configuration must have a build and, for CTest lanes, a test invocation on the same build directory. The mddlog -source and installed modes are checked separately; direct Catch2 arguments and repeat counts are checked as well. - -The reader supports the workflows' current block mappings, a single inline matrix axis with optional `include` rows, or an -`include`-only matrix. It reads scalar, folded and literal `run` scripts and direct `cmake`, `ctest` and Catch2 command lines. -It is not a general YAML or shell interpreter: a new matrix shape or unresolved matrix expression in a checked command must be -supported explicitly before the check can pass. Other evidence (compiler setup, environment and provisioning steps) remains a -textual check. - -`LocalCiLanesRejectDrift` mutates copies of the workflows and of the lanes, checking additions, removals, swapped sanitizer rows, -new axes and lost test invocations. It also checks that harmless argument and matrix-row reordering passes. -Workflows with CRLF line endings exercise both the mutation reader and the checker; CMake's `file(READ)` already normalizes them. - -The command metadata in `lanes.json` uses these fields: - -- `options` and `common_options` are the configuration's CMake definitions; `build_type` supplies `CMAKE_BUILD_TYPE`. -- `workflow_options` records the GitHub-specific cache definitions, checked exactly despite the declared local cache difference. -- `toolchain_file` supplies `CMAKE_TOOLCHAIN_FILE`. `configure_variants` adds each configure invocation's definitions in workflow - order (one variant by default), including source versus installed mddlog paths and sanitizer flags. -- `ctest.workflow_args` records GitHub's JUnit output and optional desktop repetition, in addition to `ctest.args` and the labels. -- `@workspace@` normalizes `github.workspace` paths. Other GitHub expressions are compared literally with whitespace removed; - the checker does not evaluate event-dependent desktop repetition. - -## Known differences with GitHub - -- Parallelism: GitHub builds with `--parallel 2`; local lanes use the jobs limit of their machine (4 simultaneous compilations on - Windows). -- Cache: GitHub restores `actions/cache` and sccache; local lanes keep persistent CPM and ccache volumes. The gain is to be measured, - not assumed. The desktop's `ENABLE_CACHE=OFF` and explicit sccache launcher are recorded in `workflow_options`. -- Reports and repetition: GitHub's JUnit paths and the desktop's event-dependent `--repeat` are recorded in `ctest.workflow_args`; - local result collection and stability-run selection belong to the orchestrator delivered in the later steps. -- Toolchains: GitHub installs them per run; local machines are prepared once. -- Runner images: `ubuntu-26.04`, `ubuntu-24.04`, `windows-2025` and `macos-26` are replaced by pinned containers and by the host - systems. The effective compiler and, on macOS, the selected Xcode are reported and compared with the `latest` of the runner. -- Steps with no local equivalent: artifact uploads (the orchestrator collects the logs), `sccache-action`, `actions/cache`, and the - isolation of the public network, which applies to the lane container instead of the host firewall. The workflows contain no Codecov, - Gist or badge step; coverage stays local as `coverage.info` and `lcov --list`. - -## SSH/Linux execution (delivery step 2) - -The Python 3.10+ driver uses the standard library only. The invoking workstation needs Git, OpenSSH (`ssh`) and Python; -Docker and the toolchains are needed only when preparing the images/dependencies and on the Linux execution host. There is -no `uv`, JavaScript runtime or package manager dependency. Run from the checkout to test: - -```sh -python3 cmake/local-ci/run pack --dependencies /path/to/prepared-kit --output /path/to/kit.tgz -# pack prints the SHA-256 of kit.tgz; use that exact value below. -python3 cmake/local-ci/run run --commit HEAD --machines RyzenLinux \ - --kit /path/to/kit.tgz --kit-sha256 --parallel-lanes 2 --jobs 4 --require-all -``` - -`--machines` and `--lanes` take comma-separated names; both filters apply when both are present. Without filters, all lanes in the selected commit -are selected. `--require-all` requires every **selected** lane to pass; a filtered run still reports `INCOMPLETE` for the full -matrix. `--keep` retains remote worktrees and builds. `--timeout` bounds each lane (default 3600 seconds), and -`--transfer-timeout` bounds preparation (default 1800 seconds). Limits must be positive. SSH probes have a five-second connection -timeout and a ten-second overall deadline. An unknown name or an empty selection is an error. - -The driver refuses tracked or untracked changes. `--allow-dirty` explicitly permits them, but tests the named **commit only**, -without sending the changes. Lane metadata comes from that commit, not from dirty files. The driver sends a self-contained Git -bundle using a temporary private reference, so detached or unpushed commits work. It removes the reference afterwards; neither -side pushes or fetches a remote repository. The remote clone mirrors the private reference before creating independent detached checkouts. Their standalone `.git` -metadata remains usable at `/workspace` inside a container, without absolute paths into the host clone. -The orchestration code itself comes from the driver's installation. -Before any SSH probe or result-file creation, all lane machines must be one of `RyzenLinux`, `CurmudgeonWindows` or `Mac`, -and lane IDs must be unique lowercase alphanumeric/hyphen names of at most 64 characters, beginning with a letter or digit. -Workers validate the same metadata and reject unknown requested lanes before using them in paths. SSH also ends its option -list explicitly before the machine name. - -Each run has a unique ID. Logs, `results.json` and per-lane artifact tar files land under -`build-local-ci///`, which the existing `build*/` ignore covers. Artifacts include CTest JUnit files, -`LastTest.log`, CMake configure diagnostics, fuzz findings and `coverage.info`, when produced. The coverage summary is also in the -lane's log. A failed test, timeout, interruption or artifact-collection failure returns nonzero. No executed lane also returns -nonzero. Without `--require-all`, unreachable/skipped lanes permit a successful partial result only when another lane passes; -the printed matrix is still explicitly incomplete. Ctrl+C requests remote container removal, joins the worker threads and writes -results; inability to confirm remote cancellation is recorded in the lane log. An SSH outage can prevent confirming cancellation: -the remote worker also enforces its own deadline and handles SIGHUP/SIGTERM. - -### Preparing the Linux account - -Create a dedicated unprivileged account, with key-only SSH authentication and no access to the primary account's data or -credentials. Use **rootless Docker** for this account; membership in a rootful Docker group grants host administrator access -and does not satisfy this account boundary. Install Git, Python 3.10+, `cp`, `sysctl` and rootless Docker. Do not copy GitHub, -Codecov or Gist tokens, SSH agent sockets or Docker credentials. The worker rejects UID 0. The account owns only its working -root (`~/.webfront-local-ci/runs/`), its persistent cache (`~/.webfront-local-ci/cache/`) and its rootless Docker image store. -No host firewall, sysctl or system package setting is changed by a run. Unless `--keep` is given, the driver removes its own -unique run directory after collection; images and caches remain for reuse. - -Configure the workstation's existing SSH client, accepting/verifying host keys during setup: - -```sshconfig -Host RyzenLinux - HostName - User webfront-ci - IdentityFile ~/.ssh/webfront-ci - IdentitiesOnly yes -Host CurmudgeonWindows - HostName - User webfront-ci - IdentityFile ~/.ssh/webfront-ci - IdentitiesOnly yes -Host Mac - HostName - User webfront-ci - IdentityFile ~/.ssh/webfront-ci - IdentitiesOnly yes -``` - -For both TSan lanes the **owner** must provision `vm.mmap_rnd_bits=28` on RyzenLinux. The worker checks `sysctl -n` before any -container starts and fails with the actual value and required setting when they differ. This is a host setting, not a Docker -namespace setting. The orchestrator never changes it. - -### Preparing the offline kit on the workstation - -Provision separately from execution. Use the pinned dependency versions of the **commit under test**, including transitive -ones. The initial version seals and checks a **prepared** dependency directory; it does not automatically download or resolve -it. Verify upstream archive checksums and Git revisions while preparing it. The kit's generated per-file SHA-256 inventory and -the separately supplied archive SHA-256 detect subsequent alteration/transfer errors; they do not authenticate an upstream URL. -`provision.json` records the provenance so it can be audited. No dependency source tree may contain `.git` metadata, links, -credentials or device files. Export Git sources with `git archive ` and dereference internal source links before -packing. The packer rejects links and Git metadata rather than copying local repository credentials. - -Use this directory layout (unneeded toolchains may be omitted for a filtered run): - -```text -prepared-kit/ - provision.json - preload.cmake - cpm/CPM_0.43.2.cmake - sources/stdnet/ # 8005774eabcba7e73188c02d2eeca2ff43c4ee3a - sources/stdexec/ # stdnet's STDNET_STDEXEC_TAG, currently 7df6de8eeec667c8adce66fa5a3e17cfd6849e48 - sources/Catch2/ # v3.15.2 - sources/CEF/ # v154.0.34 wrapper package - cef-binaries/ # unpacked SDK selected by that CEF package, Linux architecture of the host - bootstrap/environment.tgz - registry/ # every archive in test/web/registry-packages.json, using WebFrontRegistry's scoped names - mddlog/ # sources at lanes.json's mddlog.ref, without .git - images/ # docker save archives, not credentials or registry configuration -``` - -The bootstrap URL and SHA-512 are in `cmake/WebFrontBootstrap.cmake`; registry URLs and SHA-512 values are in -`test/web/registry-packages.json`. CMake verifies both again during each lane. CPM's own version is pinned in `cmake/CPM.cmake`; -its module is seeded into the persistent CPM cache during preparation. stdnet/Catch2 and CEF references are in the root, -`test/unit/` and `cmake/CEFIntegration.cmake` respectively. Include any additional sources required by mddlog's pinned revision -and its toolchain, overriding their fetches in the preload. Missing transitive dependencies fail offline. No warm workstation -cache is implicitly available to the remote container. - -A minimal `preload.cmake` for the WebFront dependencies is: - -```cmake -set(CPM_stdnet_SOURCE /deps/sources/stdnet CACHE PATH "") -set(CPM_Catch2_SOURCE /deps/sources/Catch2 CACHE PATH "") -set(CPM_CEF_SOURCE /deps/sources/CEF CACHE PATH "") -set(FETCHCONTENT_SOURCE_DIR_STDEXEC /deps/sources/stdexec CACHE PATH "") -``` - -Do not set `WEBFRONT_MDDLOG_SOURCE_DIR` globally in the preload: the installed-mddlog variant must use its installed package. -The worker supplies the source path only for the source variant. It also supplies the bootstrap/registry directories, ccache, -CPM cache and `FETCHCONTENT_FULLY_DISCONNECTED=ON`. It also exports `CPM_SOURCE_CACHE=/cache/cpm` so independent CMake -configurations launched by CTest, including `AddSubdirectoryConsumer`, reuse the prepared CPM module without downloading it. -For CEF it copies `cef-binaries` to the lane's private -`build-local-0/_deps/cef_binaries-src` and sets the matching FetchContent override. This preserves the paths used by -`CEFSupport.cmake` and lets its resource-copy rules write into a private SDK instead of a shared or read-only source tree. - -`provision.json` maps each runtime key in `lanes.json` to an immutable Docker image **ID** (the `sha256:...` returned by -`docker image inspect`, not a mutable tag). Archive paths are relative to the kit. For example: - -```json -{ - "images": { - "linux-ubuntu24-clang23": {"id": "sha256:<64 hexadecimal digits>", "archive": "images/noble.tar"}, - "linux-ubuntu26": {"id": "sha256:<64 hexadecimal digits>", "archive": "images/desktop.tar"}, - "linux-ubuntu-clang21-libcxx": {"id": "sha256:<64 hexadecimal digits>", "archive": "images/mddlog.tar"} - }, - "mddlog_ref": "5b43265664d83c3b7135d328f611e685792a1b02", - "sources": { - "preload.cmake": {"origin": "local reviewed fetch overrides", "integrity": ""}, - "cpm": {"origin": "CPM.cmake release URL", "integrity": ""}, - "sources": {"origin": "", "integrity": ""}, - "cef-binaries": {"origin": "", "integrity": ""}, - "bootstrap": {"origin": "", "integrity": ""}, - "registry": {"origin": "test/web/registry-packages.json at ", "integrity": ""}, - "mddlog": {"origin": "ambroise-leclerc/mddlog at ", "integrity": ""}, - "images": {"origin": "linux.Dockerfile and pinned base digests, build arguments and CMake release URLs", "integrity": ""} - } -} -``` - -Every top-level entry requires provenance. `pack` adds `kit.json`, containing a SHA-256 for every file, to the archive without -modifying the input directory. The remote worker checks the outer archive hash before extracting, rejects paths escaping the -run directory and checks every extracted file (including missing and unexpected files) before loading images. Docker loads the -supplied archives, verifies the declared image IDs exist, then uses `--pull=never`. -Windows extraction additionally rejects reserved device names (such as `aux.h` and `nul.c`), alternate data streams, -trailing dots/spaces and case-insensitive path collisions. Linux workers retain case-sensitive POSIX names, so `Foo`/`foo` -and ordinary files named `aux.h` remain valid in Linux kits. Absolute paths, drive paths, parent traversal, backslash paths, -links and exact duplicate archive entries remain forbidden for every target. Extraction onto a Windows filesystem always -applies the stricter Windows rules, regardless of the kit's target. - -### Linux images and execution - -`cmake/local-ci/linux.Dockerfile` defaults to a digest-pinned Ubuntu 24.04 base, GCC 13, LLVM 23 and CMake 4.4.4. Build on the -provisioning workstation. Its context must contain the unpacked, checksum-verified CMake release under `cmake/`. Build a second -image with `LLVM_VERSION=21 CMAKE_VERSION=4.3.1` and the matching CMake archive for mddlog, and a desktop image with -`BASE_IMAGE=ubuntu@sha256: GCC_VERSION=16` and CMake 4.4.4. Pin any overridden base **by digest**, never a tag. -Both the default `gcc`/`g++` metapackages and the requested versioned compiler packages are installed and probed during image -construction. The LLVM archive key fingerprint is checked before enabling the apt repository. Package repositories are used only at image -build time; the saved image ID seals the resulting toolchain. Record each image's base, arguments and CMake archive checksum in -`provision.json`. Save the images on the workstation with `docker save --output /images/.tar `. - -Each Linux lane uses a disposable container with the invoking account's UID/GID, dropped capabilities, `no-new-privileges`, -Docker's default seccomp profile and a private 1 GiB `/dev/shm`. The worker checks that Docker reports rootless mode. -A supplementary container group 0 maps to the dedicated host account's group; setgid build/cache directories and umask 002 -let the non-root container write shared build and cache files. Private browser profiles may still be mode 0700; -a final offline container reuses the test UID/GID to remove workspace contents before the host removes the empty directory. -This cleanup mounts only that workspace, drops all capabilities, and is omitted with `--keep`. Git's safe-directory exception is limited to `/workspace`. No privileged mode, Docker socket, host network or host IPC is -mounted. Existing CEF test policy disables Chromium's internal sandbox; isolation is provided by the unprivileged, disposable -container. There is no additional `seccomp=unconfined` exception. WebKit's workflow sandbox exception applies only to its trusted -CTest fixtures. Xvfb is installed in the image; the existing CTest commands start it where needed. - -All phases, including **configure and build**, use `--network=none`. SSH runs on the host and remains reachable; only container -loopback is available to browser fixtures. This also prevents a CMake fallback downloader from contacting GitHub. Source and -installed mddlog modes, six direct Catch2 runs for each mddlog sanitizer, all four fuzzers, native WebKitGTK and coverage use the -commands generated from the lane metadata. The container reports and checks the effective CMake/compiler major versions; -the CEF GCC lane reports Ubuntu's default compiler rather than claiming GCC 16. Builds run concurrently up to `--parallel-lanes`, -with `--jobs` compiler jobs each. Persistent CPM/ccache directories are mounted under `/cache`; the kit source overrides remain -in the per-run read-only dependency tree. There are no cache-speed or memory-use claims until measured on RyzenLinux. - -### Qualification still required - -`test/cmake/TestLocalCi.py` runs offline with Python 3.10+ and is registered as `LocalCiOrchestrator` when that interpreter is -available (Python remains optional for normal C++ consumers). It tests the command plans, tar safety/integrity, unpushed bundle -transport, failing tests, unreachable machines, dirty trees, timeouts, interruption, TSan preconditions and container isolation -arguments. Its protocol test substitutes local SSH/Docker executables; it does **not** qualify actual toolchain images or GUI -sessions. `LocalCiLanesMatchWorkflows` and its negative suite still check the workflows independently. - -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. 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 - -The Windows lane uses the same commit bundle, verified kit inventory, command metadata and result collection as Linux. -It runs natively, with Ninja and the latest installed x64 MSVC toolset selected by `vswhere`, in the dedicated account's -graphical session. It prints the effective compiler banner, CMake and WebView2 versions. CMake must match the lane's pinned -version exactly; `latest` MSVC is reported, without claiming equality with the current GitHub runner image. -MSVC deliberately follows the latest installed x64 toolset and WebView2 follows the installed Evergreen runtime, matching the -workflow's unpinned toolset/runtime policy. Unlike CMake, their versions are recorded rather than compared with an expected -version: divergence from GitHub requires reviewing those logs. Runtime discovery establishes that a versioned executable -exists; the browser tests establish actual compatibility. No automatic toolset or Evergreen-version parity is claimed. -Compilation is capped at four jobs, even when `--jobs` requests more. CTest retains the metadata's full test selection, -Release configuration, parallelism and `--no-tests=error`, and writes JUnit output. - -Prepare a dedicated **standard**, non-administrator Windows account with Git, Python 3.10+ (`python.exe` on its SSH PATH, -not the Store alias), Ninja, sccache, the pinned CMake, Visual Studio C++ x64 tools/Windows SDK and `vswhere` installed. -Install WebView2 Evergreen separately while provisioning. Execution never installs or updates the runtime. -Enable key-only OpenSSH access and verify its host key. Log that same account on locally (or in an active RDP session), -and keep its desktop unlocked during tests. A service/SSH session or a disconnected graphical session is insufficient. - -For each run the SSH worker registers a uniquely named `WebFrontCI--` task for the current account with -`LogonType Interactive`, `RunLevel Limited`, no password, no elevation and an execution deadline. It starts that task on demand. -The task checks its active session/input desktop before configuring; failure is a failed lane, never a pass. If no session -worker starts within 15 seconds, execution fails with an account/session diagnostic. The task obtains its MSVC environment -from `VsDevCmd.bat`, uses a private checkout and writes a session log plus an atomic result file. A Windows Job Object with -`KILL_ON_JOB_CLOSE` owns the task process and descendants. A timeout, Ctrl+C or failed SSH run requests task stop through a -second SSH channel; the native worker also enforces its deadline and the scheduled task has a backup time limit. -Task stop is confirmed before unregistering and deleting the run. Cancellation failure preserves files for inspection. -Normal completion unregisters the task, collects the session log, JUnit, `LastTest.log` and CMake diagnostics, then removes -the checkout (including read-only Git objects). `--keep` preserves files after stopping the task. -If stop fails, the worker still attempts an artifact snapshot and prints the session log, retains the checkout, and reports -the stop failure without replacing the original execution error. A collection failure also retains the source diagnostics. -Snapshots taken while stop is unconfirmed may be incomplete because the task could still be writing files. - -Task start/finalization, recovery stop, artifact streaming and run cleanup use a shared per-run cross-process lock. Recovery -stop collects diagnostics too. A late execution channel cannot overwrite an already collected archive after checkout removal, -or recreate a run removed by cleanup. Lock files live outside the removable run under `.webfront-local-ci/locks/`; the small -files are deliberately retained so late channels always lock the same file. Recovery SSH commands allow 90 seconds for -serialization and cancellation. Actual OpenSSH-for-Windows process behavior on a lost channel remains a host qualification -item; correctness of collection/cleanup does not depend on receiving SIGTERM at disconnect. - -Windows needs its own kit: use `"platform": "windows"`, `"images": {}` in `provision.json`, the same provenance mapping, -CPM module, exported stdnet/stdexec/Catch2, bootstrap/registry archives, and the pinned WebView2 SDK exported as -`sources/WebView2SDK`. Its URL, version and SHA-256 are in `cmake/WebView2Support.cmake`. Neither Docker nor Linux SDKs -are needed. A portable preload uses paths relative to itself: - -```cmake -set(CPM_stdnet_SOURCE "${CMAKE_CURRENT_LIST_DIR}/sources/stdnet" CACHE PATH "") -set(CPM_Catch2_SOURCE "${CMAKE_CURRENT_LIST_DIR}/sources/Catch2" CACHE PATH "") -set(CPM_WebView2SDK_SOURCE "${CMAKE_CURRENT_LIST_DIR}/sources/WebView2SDK" CACHE PATH "") -set(FETCHCONTENT_SOURCE_DIR_STDEXEC "${CMAKE_CURRENT_LIST_DIR}/sources/stdexec" CACHE PATH "") -``` - -CPM's module and the sccache data persist under the dedicated account's `.webfront-local-ci/cache/`. -The worker exports `CPM_SOURCE_CACHE` to the graphical session, so independent configurations launched by CTest reuse the -verified module as well; supplying only the top-level `-DCPM_SOURCE_CACHE` would let those configurations attempt a download. -Each lane uses a separate sccache server port; stopping its Job does not stop a concurrent run's server. -The verified dependency sources remain private to the run. FetchContent is disconnected; missing CPM/transitive dependencies -also fail under the public egress policy rather than downloading. The packer seals prepared files; it does not resolve them. - -Windows network policy must be prepared by the owner on a **dedicated CI host or VM**. The worker never changes firewall -rules. It requires all Windows Firewall profiles enabled and the effective outbound block rule `WebFrontLocalCI-BlockPublic` -covering every program, protocol and interface and the complete public IPv4/IPv6 address space. To review the setup commands: - -```powershell -python.exe cmake/local-ci/windows_worker.py --print-firewall-setup -``` - -Apply those commands once as administrator on the dedicated host, after reviewing them. They affect all host users/programs. -The block deliberately exempts RFC1918 IPv4, loopback, link-local and IPv6 unique-local addresses, preserving private-LAN SSH -and browser loopback. Consequently **LAN access remains possible**; this is weaker isolation than Linux `--network=none`. -The complement also deliberately blocks IPv4 multicast (`224.0.0.0/4`), limited broadcast (`255.255.255.255`) and IPv6 -multicast (`ff00::/8`). This may affect DHCP renewal, mDNS, LLMNR and IPv6 neighbor discovery. Qualify those services and SSH -reachability across lease renewal on the dedicated host before enabling the policy; no multicast/broadcast exception has -been validated or added. Existing allowance of `fc00::/7` does not imply multicast traffic is allowed. -Do not expose a public-network proxy on the permitted LAN or loopback. The worker checks the active policy during preparation -and again in the interactive task, before configure/build/tests. Rule absence, disabled profiles or narrower coverage fails. -The policy must remain enforced by the owner throughout the run; this native account is not a sandbox for hostile commits. - -Seal the kit on a prepared workstation and run the Windows lane from any supported orchestrator host: - -```powershell -python.exe cmake/local-ci/run pack --dependencies C:/kits/windows-prepared --output C:/kits/windows.tgz -python.exe cmake/local-ci/run run --machines CurmudgeonWindows --commit HEAD ` - --windows-kit C:/kits/windows.tgz --windows-kit-sha256 --jobs 4 --require-all -``` - -`--windows-kit` and `--windows-kit-sha256` must be supplied together. They are independent of Linux's `--kit` and -`--kit-sha256`, so one invocation can select both machines and send the appropriate kit to each. The SSH transport uses -encoded PowerShell commands and preserves spaces, apostrophes and binary streams with either cmd.exe or PowerShell as the -OpenSSH default shell. No account, scheduled task or firewall needs to be changed on the orchestrator host. - -`LocalCiWindows` adds offline regressions for native command generation, task policy, kit integrity, network preconditions, -failed/successful sessions, missing desktops, deadlines, cancellation, artifact retention and cleanup. Its full protocol test -uses an SSH/native-session stand-in with real bundles/checkouts and artifacts. On Windows it also exercises real PowerShell -binary transport and a real Job Object's child-process termination. These tests do not register real tasks or change firewall -policy. Running the whole lane over SSH with the dedicated graphical account, cold/warm caches and comparison against GitHub -remain qualification work; implementation tests are not evidence that the remote host has been provisioned correctly. -In particular, verify from the actual **non-elevated SSH account** that `Get-NetFirewallProfile` and -`Get-NetFirewallRule -PolicyStore ActiveStore`, plus every `Get-NetFirewall*Filter` used by `checkNetwork`, can read the -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 056b6bf1..4445c2a9 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -620,17 +620,3 @@ Local verification on 2026-07-19 completed successfully: the CEF-off build passe - `NativeDebugFS` exposes development files and is not a production packaging format. - CEF is a large optional dependency. Only the focused Linux integration job should download it for the minimal baseline. - React/Babel assets remain examples rather than the core demonstration. Modern Node/Vite integration, overlays, and packaged filesystems require separate product decisions. WebView2 fixed-version runtime packaging remains out of scope. - -## Local CI over SSH (#346) - -The eleven-lane description and workflow drift checks now have a Python standard-library orchestrator, commit bundles, verified -offline dependency/image kits, per-lane Linux containers without network access, persistent CPM/ccache directories, log and -artifact collection, bounded execution and explicit incomplete/failure statuses. The offline protocol regression uses SSH/Docker -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. -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/CheckLocalCi.cmake b/test/cmake/CheckLocalCi.cmake deleted file mode 100644 index 42fde5c5..00000000 --- a/test/cmake/CheckLocalCi.cmake +++ /dev/null @@ -1,352 +0,0 @@ -# The local CI matrix (cmake/local-ci/lanes.json, #346) has to describe every lane the GitHub workflows expand to: it fails on a job -# without lane, a lane without job, a different matrix, CMake version, compiler, option, target, CTest label, test step or mddlog -# revision. The local differences (cache, parallelism, toolchain, runner images, GitHub-only steps) are declared in the file and -# documented in docs/LOCAL_CI.md, which has to name every lane. Offline: the workflows are read as text. -# cmake -DROOT= [-DWORKFLOWS_DIR=] [-DLANES_FILE=] [-DDOC_FILE=] -P test/cmake/CheckLocalCi.cmake -cmake_minimum_required(VERSION 3.31) -include("${CMAKE_CURRENT_LIST_DIR}/LocalCiCommands.cmake") - -if(NOT ROOT) - message(FATAL_ERROR "ROOT is required") -endif() -if(NOT WORKFLOWS_DIR) - set(WORKFLOWS_DIR "${ROOT}/.github/workflows") -endif() -if(NOT LANES_FILE) - set(LANES_FILE "${ROOT}/cmake/local-ci/lanes.json") -endif() -if(NOT DOC_FILE) - set(DOC_FILE "${ROOT}/docs/LOCAL_CI.md") -endif() - -# A global property, so that checks made inside helper functions are not lost with their scope. -set_property(GLOBAL PROPERTY local_ci_problems "") -function(report message) - set_property(GLOBAL APPEND_STRING PROPERTY local_ci_problems "\n - ${message}") -endfunction() - -if(NOT EXISTS "${LANES_FILE}") - message(FATAL_ERROR "Missing ${LANES_FILE}") -endif() -file(READ "${LANES_FILE}" lanes_json) -string(JSON schema GET "${lanes_json}" schema) -if(NOT schema EQUAL 1) - message(FATAL_ERROR "Unsupported lanes.json schema: ${schema}") -endif() - -# The mandatory declaration of the local differences. -foreach(difference parallelism cache toolchain runner_images) - string(JSON text ERROR_VARIABLE err GET "${lanes_json}" local_differences ${difference}) - if(err OR text STREQUAL "") - report("local_differences.${difference} is not declared") - endif() -endforeach() -string(JSON github_only ERROR_VARIABLE err LENGTH "${lanes_json}" local_differences github_only_steps) -if(err OR github_only EQUAL 0) - report("local_differences.github_only_steps is not declared") -endif() - -# Splits the jobs: section of a workflow into one text per job (written to _), and returns the job names. -function(read_jobs workflow out_names prefix) - file(READ "${WORKFLOWS_DIR}/${workflow}" text) - string(FIND "${text}" "\njobs:\n" start) - if(start EQUAL -1) - message(FATAL_ERROR "${workflow} has no jobs: section") - endif() - string(SUBSTRING "${text}" ${start} -1 jobs_text) - string(REGEX MATCHALL "\n [A-Za-z][A-Za-z0-9_-]*:\n" headers "${jobs_text}") - set(names "") - set(positions "") - foreach(header IN LISTS headers) - string(FIND "${jobs_text}" "${header}" position) - string(STRIP "${header}" stripped) - string(REGEX REPLACE ":$" "" job "${stripped}") - list(APPEND names "${job}") - list(APPEND positions ${position}) - endforeach() - list(LENGTH names count) - set(index 0) - foreach(job IN LISTS names) - list(GET positions ${index} begin) - math(EXPR next "${index} + 1") - if(next LESS count) - list(GET positions ${next} finish) - else() - string(LENGTH "${jobs_text}" finish) - endif() - math(EXPR size "${finish} - ${begin}") - string(SUBSTRING "${jobs_text}" ${begin} ${size} block) - set(${prefix}_${job} "${block}" PARENT_SCOPE) - math(EXPR index "${index} + 1") - endforeach() - set(${out_names} "${names}" PARENT_SCOPE) -endfunction() - -# The values of a matrix: an inline list `key: [a, b]` or the `- key: value` entries of an include list. -function(matrix_values block key out) - set(values "") - if(block MATCHES "[ \n]${key}: \\[([^]\n]*)\\]") - string(REPLACE "," ";" values "${CMAKE_MATCH_1}") - else() - # Only the strategy: step names are `- name:` entries too. - string(FIND "${block}" "matrix:" from) - string(FIND "${block}" "\n steps:" to) - set(strategy "") - if(from GREATER -1 AND to GREATER from) - math(EXPR size "${to} - ${from}") - string(SUBSTRING "${block}" ${from} ${size} strategy) - endif() - string(REGEX MATCHALL "- ${key}: [A-Za-z0-9_-]+" entries "${strategy}") - foreach(entry IN LISTS entries) - string(REGEX REPLACE "^- ${key}: " "" value "${entry}") - list(APPEND values "${value}") - endforeach() - endif() - set(cleaned "") - foreach(value IN LISTS values) - string(STRIP "${value}" value) - list(APPEND cleaned "${value}") - endforeach() - set(${out} "${cleaned}" PARENT_SCOPE) -endfunction() - -function(require_text block lane what text) - string(FIND "${block}" "${text}" found) - if(found EQUAL -1) - report("lane ${lane}: ${what} '${text}' is not in the workflow job") - endif() -endfunction() - -function(json_strings json out) - string(JSON count ERROR_VARIABLE err LENGTH "${json}") - set(items "") - if(NOT err AND count GREATER 0) - math(EXPR last "${count} - 1") - foreach(i RANGE ${last}) - string(JSON item GET "${json}" ${i}) - list(APPEND items "${item}") - endforeach() - endif() - set(${out} "${items}" PARENT_SCOPE) -endfunction() - -# Jobs and matrices of every workflow against the declaration. -string(JSON lane_count LENGTH "${lanes_json}" lanes) -math(EXPR lane_last "${lane_count} - 1") -string(JSON workflow_count LENGTH "${lanes_json}" workflows) -math(EXPR workflow_last "${workflow_count} - 1") -set(lane_ids "") -set(lane_keys "") -foreach(i RANGE ${lane_last}) - string(JSON id GET "${lanes_json}" lanes ${i} id) - string(JSON workflow GET "${lanes_json}" lanes ${i} workflow) - string(JSON job GET "${lanes_json}" lanes ${i} job) - string(JSON matrix GET "${lanes_json}" lanes ${i} matrix) - list(APPEND lane_ids "${id}") - list(APPEND lane_keys "${workflow}|${job}|${matrix}") -endforeach() -list(LENGTH lane_ids id_count) -list(REMOVE_DUPLICATES lane_ids) -list(LENGTH lane_ids unique_ids) -if(NOT id_count EQUAL unique_ids) - report("lane ids are not unique") -endif() - -set(expected_keys "") -foreach(w RANGE ${workflow_last}) - string(JSON workflow MEMBER "${lanes_json}" workflows ${w}) - if(NOT EXISTS "${WORKFLOWS_DIR}/${workflow}") - report("workflow ${workflow} is declared but missing") - continue() - endif() - read_jobs("${workflow}" actual_jobs "job_${w}") - string(JSON declared_json GET "${lanes_json}" workflows "${workflow}" jobs) - json_strings("${declared_json}" declared_jobs) - foreach(job IN LISTS actual_jobs) - if(NOT job IN_LIST declared_jobs) - report("${workflow}: job '${job}' has no lane declaration") - endif() - endforeach() - foreach(job IN LISTS declared_jobs) - if(NOT job IN_LIST actual_jobs) - report("${workflow}: declared job '${job}' does not exist") - continue() - endif() - string(JSON matrix_json ERROR_VARIABLE err GET "${lanes_json}" workflows "${workflow}" matrices "${job}") - if(err OR matrix_json STREQUAL "" OR matrix_json MATCHES "NOTFOUND") - list(APPEND expected_keys "${workflow}|${job}|") - if("${job_${w}_${job}}" MATCHES "matrix:") - report("${workflow}: job '${job}' has a matrix that is not declared") - endif() - continue() - endif() - string(JSON key GET "${matrix_json}" key) - string(JSON values_json GET "${matrix_json}" values) - json_strings("${values_json}" declared_values) - lane_matrix("${job_${w}_${job}}" "${key}" "" unused_entry unused_block) - matrix_values("${job_${w}_${job}}" "${key}" actual_values) - list(LENGTH actual_values actual_count) - set(unique_values "${actual_values}") - list(REMOVE_DUPLICATES unique_values) - list(LENGTH unique_values unique_count) - if(NOT actual_count EQUAL unique_count) - report("${workflow}: ${job} matrix has duplicate values") - endif() - foreach(value IN LISTS actual_values) - if(NOT value IN_LIST declared_values) - report("${workflow}: ${job} matrix value '${value}' has no lane declaration") - endif() - endforeach() - foreach(value IN LISTS declared_values) - if(NOT value IN_LIST actual_values) - report("${workflow}: declared ${job} matrix value '${value}' does not exist") - endif() - list(APPEND expected_keys "${workflow}|${job}|${value}") - endforeach() - endforeach() -endforeach() -foreach(key IN LISTS expected_keys) - list(FIND lane_keys "${key}" first) - if(first EQUAL -1) - report("no lane for ${key}") - endif() -endforeach() -foreach(key IN LISTS lane_keys) - if(NOT key IN_LIST expected_keys) - report("lane ${key} matches no job or matrix value") - endif() -endforeach() -list(LENGTH lane_keys key_count) -list(REMOVE_DUPLICATES lane_keys) -list(LENGTH lane_keys unique_keys) -if(NOT key_count EQUAL unique_keys) - report("two lanes describe the same job and matrix value") -endif() - -# Every lane against the text of its job. -foreach(i RANGE ${lane_last}) - string(JSON id GET "${lanes_json}" lanes ${i} id) - string(JSON workflow GET "${lanes_json}" lanes ${i} workflow) - string(JSON job GET "${lanes_json}" lanes ${i} job) - string(JSON matrix GET "${lanes_json}" lanes ${i} matrix) - string(JSON build_type GET "${lanes_json}" lanes ${i} build_type) - string(JSON cmake_version GET "${lanes_json}" lanes ${i} cmake_version) - string(JSON marker GET "${lanes_json}" lanes ${i} compiler marker) - string(JSON machine GET "${lanes_json}" lanes ${i} machine) - if(NOT machine MATCHES "^(RyzenLinux|CurmudgeonWindows|Mac)$") - report("lane ${id}: unknown machine '${machine}'") - endif() - set(block "") - foreach(w RANGE ${workflow_last}) - string(JSON name MEMBER "${lanes_json}" workflows ${w}) - if(name STREQUAL workflow AND DEFINED job_${w}_${job}) - set(block "${job_${w}_${job}}") - set(workflow_index ${w}) - endif() - endforeach() - if(block STREQUAL "") - continue() - endif() - - set(entry "${block}") - if(NOT matrix STREQUAL "") - string(JSON key GET "${lanes_json}" workflows "${workflow}" matrices "${job}" key) - lane_matrix("${block}" "${key}" "${matrix}" entry block) - endif() - string(JSON lane GET "${lanes_json}" lanes ${i}) - check_lane_commands("${block}" "${lane}") - - if(entry MATCHES "build_type: ([A-Za-z]+)") - if(NOT CMAKE_MATCH_1 STREQUAL build_type) - report("lane ${id}: build type ${build_type}, workflow has ${CMAKE_MATCH_1}") - endif() - else() - require_text("${block}" "${id}" "build type" "-DCMAKE_BUILD_TYPE=${build_type}") - endif() - - # CMake versions: every setup-cmake of the job. - string(REGEX MATCHALL "[ ]version: '[0-9.]+'" versions "${block}") - if(NOT versions) - report("lane ${id}: the job installs no pinned CMake") - endif() - foreach(version IN LISTS versions) - if(NOT version MATCHES "'${cmake_version}'") - report("lane ${id}: CMake ${cmake_version}, workflow has ${version}") - endif() - endforeach() - - if(NOT marker STREQUAL "") - require_text("${block}" "${id}" "compiler" "${marker}") - endif() - - string(JSON env_json GET "${lanes_json}" lanes ${i} env) - string(JSON env_count LENGTH "${env_json}") - if(env_count GREATER 0) - math(EXPR env_last "${env_count} - 1") - foreach(e RANGE ${env_last}) - string(JSON env_key MEMBER "${env_json}" ${e}) - string(JSON env_value GET "${env_json}" "${env_key}") - require_text("${block}" "${id}" "environment variable" "${env_key}") - require_text("${block}" "${id}" "environment value" "${env_value}") - endforeach() - endif() - - string(JSON flags ERROR_VARIABLE err GET "${lanes_json}" lanes ${i} sanitizer_flags) - if(NOT err) - require_text("${block}" "${id}" "sanitizer flags" "${flags}") - endif() - string(JSON sysctl_json ERROR_VARIABLE err GET "${lanes_json}" lanes ${i} host_requirements sysctl) - if(NOT err) - string(JSON sysctl_key MEMBER "${sysctl_json}" 0) - string(JSON sysctl_value GET "${sysctl_json}" "${sysctl_key}") - require_text("${block}" "${id}" "sysctl" "${sysctl_key}=${sysctl_value}") - endif() - - string(JSON fuzz_json ERROR_VARIABLE err GET "${lanes_json}" lanes ${i} fuzz_decoders) - if(NOT err) - json_strings("${fuzz_json}" decoders) - string(REPLACE ";" " " decoder_text "${decoders}") - require_text("${block}" "${id}" "fuzzed decoders" "for decoder in ${decoder_text}") - string(JSON fuzz_seconds GET "${lanes_json}" lanes ${i} fuzz_seconds) - require_text("${block}" "${id}" "fuzz duration" "-max_total_time=${fuzz_seconds}") - endif() - - string(JSON evidence_json GET "${lanes_json}" lanes ${i} evidence) - json_strings("${evidence_json}" evidence) - foreach(text IN LISTS evidence) - require_text("${block}" "${id}" "step" "${text}") - endforeach() - - # The pinned mddlog revision of the Mddlog workflow. - if(workflow STREQUAL "MddlogIntegration.yml") - string(JSON mddlog_ref GET "${lanes_json}" mddlog ref) - string(JSON mddlog_repository GET "${lanes_json}" mddlog repository) - require_text("${block}" "${id}" "mddlog revision" "ref: ${mddlog_ref}") - require_text("${block}" "${id}" "mddlog repository" "repository: ${mddlog_repository}") - string(REGEX MATCHALL "ref: [0-9a-f]+" refs "${block}") - foreach(ref IN LISTS refs) - if(NOT ref STREQUAL "ref: ${mddlog_ref}") - report("lane ${id}: workflow pins ${ref}, lanes.json pins ${mddlog_ref}") - endif() - endforeach() - endif() -endforeach() - -# The documentation names every lane. -if(EXISTS "${DOC_FILE}") - file(READ "${DOC_FILE}" doc) - foreach(id IN LISTS lane_ids) - string(FIND "${doc}" "`${id}`" found) - if(found EQUAL -1) - report("${DOC_FILE} does not document lane ${id}") - endif() - endforeach() -else() - report("missing ${DOC_FILE}") -endif() - -get_property(problems GLOBAL PROPERTY local_ci_problems) -if(problems) - message(FATAL_ERROR "cmake/local-ci/lanes.json drifted from the workflows:${problems}") -endif() -message(STATUS "${lane_count} local CI lanes match ${WORKFLOWS_DIR}") diff --git a/test/cmake/CheckLocalCiNegative.cmake b/test/cmake/CheckLocalCiNegative.cmake deleted file mode 100644 index c0ed2765..00000000 --- a/test/cmake/CheckLocalCiNegative.cmake +++ /dev/null @@ -1,149 +0,0 @@ -# Proves that CheckLocalCi.cmake rejects drift and accepts equivalent command/matrix layouts. -# cmake -DROOT= -DWORK_DIR= -P test/cmake/CheckLocalCiNegative.cmake -cmake_minimum_required(VERSION 3.31) - -if(NOT ROOT OR NOT WORK_DIR) - message(FATAL_ERROR "ROOT and WORK_DIR are required") -endif() - -function(crlf_workflows dir) - foreach(workflow BuildAndTest.yml MddlogIntegration.yml) - file(READ "${dir}/workflows/${workflow}" text) - string(REPLACE "\n" "\r\n" text "${text}") - file(WRITE "${dir}/workflows/${workflow}" "${text}") - endforeach() -endfunction() - -# Mutate copies by replacing `from` with `to`. A nonempty `expect` requires failure -# with that diagnostic; an empty one requires success. An optional CRLF argument -# exercises both the mutation reader and the checker with Windows line endings. -function(check_mutation name file from to expect) - set(dir "${WORK_DIR}/${name}") - file(REMOVE_RECURSE "${dir}") - file(MAKE_DIRECTORY "${dir}/workflows") - file(COPY "${ROOT}/.github/workflows/BuildAndTest.yml" "${ROOT}/.github/workflows/MddlogIntegration.yml" DESTINATION "${dir}/workflows") - file(COPY "${ROOT}/cmake/local-ci/lanes.json" DESTINATION "${dir}") - file(COPY "${ROOT}/docs/LOCAL_CI.md" DESTINATION "${dir}") - if(file STREQUAL "lanes.json" OR file STREQUAL "LOCAL_CI.md") - set(target "${dir}/${file}") - else() - set(target "${dir}/workflows/${file}") - endif() - if(ARGV5 STREQUAL "CRLF") - crlf_workflows("${dir}") - endif() - # file(READ) already normalizes CRLF, including in the minimum CMake 3.31. - file(READ "${target}" text) - string(FIND "${text}" "${from}" found) - if(found EQUAL -1) - message(FATAL_ERROR "${name}: '${from}' is not in ${file}, the mutation proves nothing") - endif() - string(REPLACE "${from}" "${to}" text "${text}") - file(WRITE "${target}" "${text}") - if(ARGV5 STREQUAL "CRLF") - crlf_workflows("${dir}") - endif() - execute_process(COMMAND "${CMAKE_COMMAND}" -DROOT=${ROOT} -DWORKFLOWS_DIR=${dir}/workflows - -DLANES_FILE=${dir}/lanes.json -DDOC_FILE=${dir}/LOCAL_CI.md -P "${CMAKE_CURRENT_LIST_DIR}/CheckLocalCi.cmake" - RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) - if(expect STREQUAL "") - if(NOT result EQUAL 0) - message(FATAL_ERROR "${name}: equivalent workflow was rejected:\n${out}${err}") - endif() - return() - endif() - if(result EQUAL 0) - message(FATAL_ERROR "${name}: the drift was not rejected") - endif() - string(FIND "${out}${err}" "${expect}" reported) - if(reported EQUAL -1) - message(FATAL_ERROR "${name}: expected '${expect}' in:\n${out}${err}") - endif() -endfunction() - -check_mutation(new-job BuildAndTest.yml "\n web-integration:\n" "\n extra-job:\n runs-on: x\n steps: []\n\n web-integration:\n" "extra-job") -check_mutation(matrix-value BuildAndTest.yml "sanitizer: [address-undefined, thread]" "sanitizer: [address-undefined, thread, memory]" "memory") -check_mutation(cmake-version BuildAndTest.yml "version: '4.4.4'" "version: '4.4.3'" "4.4.3") -check_mutation(mddlog-ref MddlogIntegration.yml "ref: 5b43265664d83c3b7135d328f611e685792a1b02" "ref: 0000000000000000000000000000000000000000" "mddlog") -check_mutation(compiler BuildAndTest.yml "clang-23" "clang-24" "clang-23") -check_mutation(option BuildAndTest.yml "-DENABLE_COVERAGE=ON" "-DENABLE_COVERAGE=OFF" "-DENABLE_COVERAGE=ON") -check_mutation(ctest-label BuildAndTest.yml "-L web-integration" "-L web" "-L web-integration") -check_mutation(lane-removed lanes.json - "\"job\": \"web-integration\", \"matrix\": \"gcc\"" - "\"job\": \"web-integration\", \"matrix\": \"gcc-old\"" - "no lane for BuildAndTest.yml|web-integration|gcc") -check_mutation(undocumented-lane LOCAL_CI.md "`sanitizers-thread`" "`sanitizers-tsan`" "sanitizers-thread") - -# Compare both directions: additions and removal from either side are drift too. -check_mutation(extra-option BuildAndTest.yml "-DENABLE_COVERAGE=ON" "-DENABLE_COVERAGE=ON -DENABLE_SANITIZER_ADDRESS=ON" "configure options") -check_mutation(extra-ctest-filter BuildAndTest.yml "ctest --test-dir build -C" "ctest --test-dir build -L web-integration -C" "CTest arguments") -check_mutation(extra-ctest-exclude BuildAndTest.yml "ctest --test-dir build -C" "ctest --test-dir build -LE web-integration -C" "CTest arguments") -check_mutation(extra-ctest-regex BuildAndTest.yml "ctest --test-dir build -C" "ctest --test-dir build -R transport -C" "CTest arguments") -check_mutation(ctest-parallel-operand BuildAndTest.yml "--no-tests=error --parallel 4" "--no-tests=error --parallel 3" "CTest arguments") -check_mutation(extra-target BuildAndTest.yml "--target webtest developer_integration webfront-wf" "--target webtest developer_integration webfront-wf tests" "build targets") -check_mutation(removed-declared-option lanes.json "\"-DENABLE_COVERAGE=ON\"" "\"-DENABLE_COVERAGE=OFF\"" "configure options") - -# The flags still occur in the job, but belong to the wrong matrix rows. -check_mutation(swapped-sanitizers MddlogIntegration.yml - "- name: address-undefined\n flags: -fsanitize=address,undefined -fno-sanitize-recover=undefined\n - name: thread\n flags: -fsanitize=thread" - "- name: address-undefined\n flags: -fsanitize=thread\n - name: thread\n flags: -fsanitize=address,undefined -fno-sanitize-recover=undefined" - "configure options") -check_mutation(swapped-sanitizer-branches BuildAndTest.yml - "matrix.sanitizer == 'thread' &&" "matrix.sanitizer == 'address-undefined' &&" "configure options") -check_mutation(unresolved-matrix-command BuildAndTest.yml - "matrix.options }}" "matrix.unknown_options }}" "unsupported command expression") - -# Additional axes and exclusions need explicit support, not a partial expansion. -check_mutation(extra-inline-axis BuildAndTest.yml - "compiler: [gcc, clang]" "compiler: [gcc, clang]\n optimization: [O1, O2]" "unsupported matrix field 'optimization'") -check_mutation(extra-block-axis BuildAndTest.yml - "compiler: [gcc, clang]" "compiler: [gcc, clang]\n optimization:\n - O1\n - O2" "unsupported matrix field 'optimization'") -check_mutation(matrix-exclusion BuildAndTest.yml - "compiler: [gcc, clang]" "compiler: [gcc, clang]\n exclude:\n - compiler: clang" "unsupported matrix field 'exclude'") - -# Every execution mode must keep its own commands, not merely evidence elsewhere. -check_mutation(installed-tests-removed MddlogIntegration.yml - "run: ctest --test-dir build-mddlog-install --output-on-failure --no-tests=error" - "run: echo tests skipped" "ctests count") -check_mutation(installed-option-changed MddlogIntegration.yml - [[-DCMAKE_PREFIX_PATH=${{ github.workspace }}/mddlog-install]] - [[-DCMAKE_PREFIX_PATH=${{ github.workspace }}/wrong-install]] "configure options") -check_mutation(catch-order-changed MddlogIntegration.yml - "--order rand" "--order lex" "Catch2 arguments") -check_mutation(catch-full-suite-removed MddlogIntegration.yml - "run: ./build-sanitized/test/unit/tests --order rand" "run: echo tests skipped" "catch_calls count") -check_mutation(catch-repeat-changed MddlogIntegration.yml - "for iteration in 1 2 3 4 5; do" "for iteration in 1 2 3; do" "Catch2 arguments") - -check_mutation(extra-target-equals BuildAndTest.yml - "cmake --build build --config" "cmake --build build --target=tests --config" "build targets") -check_mutation(installed-tests-wrong-directory MddlogIntegration.yml - "ctest --test-dir build-mddlog-install" "ctest --test-dir build-mddlog-source" "configured and tested directories") -check_mutation(duplicate-matrix-value BuildAndTest.yml - "compiler: [gcc, clang]" "compiler: [gcc, clang, clang]" "matrix has duplicate values") -check_mutation(ctest-repeat-changed BuildAndTest.yml - "until-fail:" "until-pass:" "CTest arguments") -check_mutation(comment-cannot-replace-option BuildAndTest.yml - "options: -DWEBFRONT_EMBED_WEBVIEW2=ON -DWEBFRONT_WEBTEST_FRONTEND=WebView2" - "# -DWEBFRONT_EMBED_WEBVIEW2=ON\n options: -DWEBFRONT_WEBTEST_FRONTEND=WebView2" "configure options") - -# Equivalent layouts must stay valid: ordering and shell quoting are not drift. -check_mutation(reordered-ctest-options BuildAndTest.yml - "--output-on-failure --no-tests=error" "--no-tests=error --output-on-failure" "") -check_mutation(quoted-cmake-option BuildAndTest.yml - "-DENABLE_COVERAGE=ON" "'-DENABLE_COVERAGE=ON'" "") -check_mutation(reordered-matrix-rows MddlogIntegration.yml - "- name: address-undefined\n flags: -fsanitize=address,undefined -fno-sanitize-recover=undefined\n - name: thread\n flags: -fsanitize=thread" - "- name: thread\n flags: -fsanitize=thread\n - name: address-undefined\n flags: -fsanitize=address,undefined -fno-sanitize-recover=undefined" "") -check_mutation(crlf-workflows BuildAndTest.yml - "matrix:\n compiler: [gcc, clang]" "matrix:\n compiler: [gcc, clang]" "" CRLF) - -# The dedicated Linux performance lane must stay optimized, exercise the benchmark and repeat it. -check_mutation(performance-release BuildAndTest.yml - "build-performance -G Ninja -DCMAKE_BUILD_TYPE=Release" "build-performance -G Ninja -DCMAKE_BUILD_TYPE=Debug" "configure options") -check_mutation(performance-target BuildAndTest.yml - "--target webkitgtk_transport_benchmark" "--target webkitgtk_lifecycle" "build targets") -check_mutation(performance-label BuildAndTest.yml - "-C Release -L performance" "-C Release -L web-integration" "CTest arguments") -check_mutation(performance-repeat BuildAndTest.yml - "--repeat until-fail:3" "--repeat until-fail:1" "CTest arguments") diff --git a/test/cmake/LocalCiCommands.cmake b/test/cmake/LocalCiCommands.cmake deleted file mode 100644 index c59c5a6c..00000000 --- a/test/cmake/LocalCiCommands.cmake +++ /dev/null @@ -1,361 +0,0 @@ -# Deliberately bounded readers for the workflow syntax used by the local CI lanes. -# They never evaluate shell code or GitHub expressions. New matrix shapes must be -# taught to the checker rather than silently reducing the number of checked lanes. -function(lane_matrix block key value out_entry out_block) - string(REPLACE ";" "\\;" lines "${block}") - string(REPLACE "\n" ";" lines "${lines}") - set(in_matrix FALSE) - set(selected FALSE) - set(entry "") - set(matrix_text "") - foreach(line IN LISTS lines) - if(line STREQUAL " matrix:") - set(in_matrix TRUE) - string(APPEND matrix_text "${line}\n") - continue() - endif() - if(NOT in_matrix) - continue() - endif() - if(line MATCHES "^ *[^ #]" AND NOT line MATCHES "^ ") - set(in_matrix FALSE) - continue() - endif() - string(APPEND matrix_text "${line}\n") - if(line MATCHES "^ ([A-Za-z_][A-Za-z0-9_-]*): *(.*)$") - set(field "${CMAKE_MATCH_1}") - set(contents "${CMAKE_MATCH_2}") - if(NOT field STREQUAL key AND NOT field STREQUAL "include") - report("unsupported matrix field '${field}': declare and support every matrix axis") - elseif(field STREQUAL key AND NOT contents MATCHES "^\\[[^]]+\\]$") - report("unsupported matrix axis '${key}': expected an inline list") - elseif(field STREQUAL "include" AND NOT contents STREQUAL "") - report("unsupported matrix include: expected a block list") - endif() - elseif(line MATCHES "^ *- ([A-Za-z_][A-Za-z0-9_-]*): *([A-Za-z0-9_-]+)$") - if(NOT CMAKE_MATCH_1 STREQUAL key) - report("unsupported matrix include key '${CMAKE_MATCH_1}', expected '${key}'") - endif() - if(CMAKE_MATCH_2 STREQUAL value) - set(selected TRUE) - else() - set(selected FALSE) - endif() - elseif(NOT line MATCHES "^ *(#.*)?$" AND NOT line MATCHES "^ +[A-Za-z_][A-Za-z0-9_-]*: .+$") - report("unsupported matrix syntax: ${line}") - endif() - if(selected) - string(APPEND entry "${line}\n") - endif() - endforeach() - if(matrix_text STREQUAL "") - report("unsupported or missing matrix block") - endif() - string(REPLACE "${matrix_text}" "" resolved "${block}") - - # Resolve only the selected row and the simple string-valued conditional used - # by the sanitizer configure command. Other expressions fail in command_tokens. - set(conditional "\\$\\{\\{ *matrix\\.([A-Za-z_-]+) == '([^']*)' && '([^']*)' \\|\\| '([^']*)' *\\}\\}") - while(resolved MATCHES "${conditional}") - set(expression "${CMAKE_MATCH_0}") - if(NOT CMAKE_MATCH_1 STREQUAL key) - report("unsupported matrix condition: ${expression}") - break() - endif() - if(CMAKE_MATCH_2 STREQUAL value) - set(replacement "${CMAKE_MATCH_3}") - else() - set(replacement "${CMAKE_MATCH_4}") - endif() - string(REPLACE "${expression}" "${replacement}" resolved "${resolved}") - endwhile() - string(REGEX MATCHALL "\\$\\{\\{ *matrix\\.[A-Za-z_-]+ *\\}\\}" expressions "${resolved}") - foreach(expression IN LISTS expressions) - string(REGEX MATCH "matrix\\.([A-Za-z_-]+)" unused "${expression}") - set(field "${CMAKE_MATCH_1}") - if(field STREQUAL key) - set(replacement "${value}") - elseif(entry MATCHES "\n *${field}: ([^\n]*)") - set(replacement "${CMAKE_MATCH_1}") - else() - continue() - endif() - string(REPLACE "${expression}" "${replacement}" resolved "${resolved}") - endforeach() - set(${out_entry} "${entry}" PARENT_SCOPE) - set(${out_block} "${resolved}" PARENT_SCOPE) -endfunction() - -function(json_quote value out) - string(REPLACE "\\" "\\\\" value "${value}") - string(REPLACE "\"" "\\\"" value "${value}") - string(REPLACE "\n" "\\n" value "${value}") - string(REPLACE "\r" "\\r" value "${value}") - string(REPLACE "\t" "\\t" value "${value}") - set(${out} "\"${value}\"" PARENT_SCOPE) -endfunction() - -# Collect run scalars, folding >- and preserving literal | scripts. YAML keys and -# comments cannot masquerade as executed command arguments. -function(workflow_scripts block out) - string(REPLACE ";" "\\;" lines "${block}\nEND") - string(REPLACE "\n" ";" lines "${lines}") - set(scripts "[]") - set(active FALSE) - foreach(line IN LISTS lines) - if(active) - string(REGEX MATCH "^ *" indent "${line}") - string(LENGTH "${indent}" width) - if(line MATCHES "^ *$" OR width GREATER run_indent) - string(STRIP "${line}" content) - string(APPEND script "${content}${separator}") - continue() - endif() - json_quote("${script}" quoted) - string(JSON count LENGTH "${scripts}") - string(JSON scripts SET "${scripts}" ${count} "${quoted}") - set(active FALSE) - endif() - if(line MATCHES "^( *)run: *(.*)$") - string(LENGTH "${CMAKE_MATCH_1}" run_indent) - set(script "${CMAKE_MATCH_2}") - if(script MATCHES "^[>|][-+]?$") - if(script MATCHES "^>") - set(separator " ") - else() - set(separator "\n") - endif() - set(script "") - set(active TRUE) - else() - json_quote("${script}" quoted) - string(JSON count LENGTH "${scripts}") - string(JSON scripts SET "${scripts}" ${count} "${quoted}") - endif() - endif() - endforeach() - set(${out} "${scripts}" PARENT_SCOPE) -endfunction() - -function(command_tokens command lane out) - # Workspace paths vary locally. Compact the remaining expressions to keep - # them single tokens; their exact contents are still compared to lanes.json. - string(REGEX REPLACE "\\$\\{\\{ *github\\.workspace *\\}\\}" "@workspace@" command "${command}") - string(REGEX MATCHALL "\\$\\{\\{[^}]*\\}\\}" expressions "${command}") - set(index 0) - foreach(expression IN LISTS expressions) - if(expression MATCHES "matrix\\.") - report("lane ${lane}: unsupported command expression ${expression}") - endif() - string(REPLACE " " "" expression_${index} "${expression}") - string(REPLACE "${expression}" "@expression${index}@" command "${command}") - math(EXPR index "${index} + 1") - endforeach() - separate_arguments(tokens UNIX_COMMAND "${command}") - while(index GREATER 0) - math(EXPR index "${index} - 1") - string(REPLACE "@expression${index}@" "${expression_${index}}" tokens "${tokens}") - endwhile() - set(${out} "${tokens}" PARENT_SCOPE) -endfunction() - -function(compare_arguments lane what expected actual) - # Argument order is irrelevant for these option lists, but duplicates and - # values are significant (including the operand of a CTest filter). - list(SORT expected) - list(SORT actual) - if(NOT "${expected}" STREQUAL "${actual}") - report("lane ${lane}: ${what} differ: expected [${expected}], workflow [${actual}]") - endif() -endfunction() - -# Keep each CTest switch attached to its operand before comparing option sets. -function(option_pairs tokens out) - set(pairs "") - while(tokens) - list(POP_FRONT tokens token) - if(token MATCHES "^-" AND NOT token MATCHES "=" AND tokens) - list(GET tokens 0 next) - if(NOT next MATCHES "^-") - list(POP_FRONT tokens next) - string(APPEND token "=${next}") - endif() - endif() - list(APPEND pairs "${token}") - endwhile() - set(${out} "${pairs}" PARENT_SCOPE) -endfunction() - -function(check_lane_commands block lane) - string(JSON id GET "${lane}" id) - string(JSON build_type GET "${lane}" build_type) - set(expected_options "-DCMAKE_BUILD_TYPE=${build_type}") - foreach(field options common_options workflow_options) - string(JSON array ERROR_VARIABLE err GET "${lane}" ${field}) - if(NOT err) - json_strings("${array}" items) - list(APPEND expected_options ${items}) - endif() - endforeach() - string(JSON toolchain ERROR_VARIABLE err GET "${lane}" toolchain_file) - if(NOT err) - list(APPEND expected_options "-DCMAKE_TOOLCHAIN_FILE=@workspace@/${toolchain}") - endif() - string(JSON variants ERROR_VARIABLE err GET "${lane}" configure_variants) - if(err) - set(variants "[[]]") - endif() - string(JSON configure_count LENGTH "${variants}") - string(JSON array GET "${lane}" targets) - json_strings("${array}" expected_targets) - string(JSON array GET "${lane}" ctest args) - json_strings("${array}" expected_ctest) - if(expected_ctest) - set(ctest_count ${configure_count}) - else() - set(ctest_count 0) - endif() - foreach(field labels exclude_labels workflow_args) - string(JSON array ERROR_VARIABLE err GET "${lane}" ctest ${field}) - if(NOT err) - json_strings("${array}" items) - foreach(item IN LISTS items) - if(field STREQUAL "labels") - list(APPEND expected_ctest "-L" "${item}") - elseif(field STREQUAL "exclude_labels") - list(APPEND expected_ctest "-LE" "${item}") - else() - list(APPEND expected_ctest "${item}") - endif() - endforeach() - endif() - endforeach() - option_pairs("${expected_ctest}" expected_ctest) - set(configures 0) - set(builds 0) - set(ctests 0) - set(catch_calls 0) - set(configure_dirs "") - set(build_dirs "") - set(ctest_dirs "") - workflow_scripts("${block}" scripts) - string(JSON count LENGTH "${scripts}") - if(count EQUAL 0) - report("lane ${id}: no run commands") - return() - endif() - math(EXPR last "${count} - 1") - foreach(i RANGE ${last}) - string(JSON script GET "${scripts}" ${i}) - string(REPLACE "\\\n" " " script "${script}") - string(REPLACE ";" "\\;" lines "${script}") - string(REPLACE "\n" ";" lines "${lines}") - foreach(line IN LISTS lines) - string(STRIP "${line}" line) - if(NOT line MATCHES "^(cmake |ctest |\\./[^ ]+/test/unit/tests )") - continue() - endif() - command_tokens("${line}" "${id}" tokens) - list(POP_FRONT tokens program) - if(program STREQUAL "cmake" AND NOT line MATCHES "^cmake --") - set(actual_options "") - set(was_build_dir FALSE) - foreach(token IN LISTS tokens) - if(was_build_dir) - list(APPEND configure_dirs "${token}") - endif() - if(token STREQUAL "-B") - set(was_build_dir TRUE) - else() - set(was_build_dir FALSE) - endif() - if(token MATCHES "^-D") - list(APPEND actual_options "${token}") - endif() - endforeach() - set(expected "${expected_options}") - if(configures LESS configure_count) - string(JSON array GET "${variants}" ${configures}) - json_strings("${array}" items) - list(APPEND expected ${items}) - endif() - compare_arguments("${id}" "configure options" "${expected}" "${actual_options}") - math(EXPR configures "${configures} + 1") - elseif(program STREQUAL "cmake" AND line MATCHES "^cmake --build ") - list(GET tokens 1 directory) - list(APPEND build_dirs "${directory}") - set(targets "") - set(in_targets FALSE) - foreach(token IN LISTS tokens) - if(token STREQUAL "--target") - set(in_targets TRUE) - elseif(token MATCHES "^--target=(.+)$") - list(APPEND targets "${CMAKE_MATCH_1}") - set(in_targets TRUE) - elseif(token MATCHES "^-") - set(in_targets FALSE) - elseif(in_targets) - list(APPEND targets "${token}") - endif() - endforeach() - compare_arguments("${id}" "build targets" "${expected_targets}" "${targets}") - math(EXPR builds "${builds} + 1") - elseif(program STREQUAL "ctest") - set(actual "") - while(tokens) - list(POP_FRONT tokens token) - if(token STREQUAL "--test-dir" OR token STREQUAL "-C") - if(NOT tokens) - report("lane ${id}: CTest ${token} has no operand") - break() - endif() - list(POP_FRONT tokens operand) - if(token STREQUAL "--test-dir") - list(APPEND ctest_dirs "${operand}") - endif() - if(token STREQUAL "-C" AND NOT operand STREQUAL build_type) - report("lane ${id}: CTest configuration ${operand}, expected ${build_type}") - endif() - else() - list(APPEND actual "${token}") - endif() - endwhile() - option_pairs("${actual}" actual) - compare_arguments("${id}" "CTest arguments" "${expected_ctest}" "${actual}") - math(EXPR ctests "${ctests} + 1") - elseif(program MATCHES "/test/unit/tests$") - string(JSON array ERROR_VARIABLE err GET "${lane}" catch2_direct ${catch_calls}) - if(err) - report("lane ${id}: undeclared Catch2 command") - else() - json_strings("${array}" expected) - if(script MATCHES "for iteration in ([0-9 ]+); do") - separate_arguments(iterations UNIX_COMMAND "${CMAKE_MATCH_1}") - list(LENGTH iterations repeats) - list(APPEND tokens "x${repeats}") - endif() - option_pairs("${expected}" expected) - option_pairs("${tokens}" actual) - compare_arguments("${id}" "Catch2 arguments" "${expected}" "${actual}") - endif() - math(EXPR catch_calls "${catch_calls} + 1") - endif() - endforeach() - endforeach() - compare_arguments("${id}" "configured and built directories" "${configure_dirs}" "${build_dirs}") - if(ctest_count GREATER 0) - compare_arguments("${id}" "configured and tested directories" "${configure_dirs}" "${ctest_dirs}") - endif() - string(JSON catch_count ERROR_VARIABLE err LENGTH "${lane}" catch2_direct) - if(err) - set(catch_count 0) - endif() - foreach(pair "configures|${configure_count}" "builds|${configure_count}" "ctests|${ctest_count}" "catch_calls|${catch_count}") - string(REPLACE "|" ";" pair "${pair}") - list(GET pair 0 field) - list(GET pair 1 expected) - if(NOT ${field} EQUAL expected) - report("lane ${id}: ${field} count ${${field}}, expected ${expected}") - endif() - endforeach() -endfunction() diff --git a/test/cmake/TestLocalCi.py b/test/cmake/TestLocalCi.py deleted file mode 100644 index 8eef0c99..00000000 --- a/test/cmake/TestLocalCi.py +++ /dev/null @@ -1,452 +0,0 @@ -"""Offline regression tests for local CI transport, command plans and failure reporting.""" -import argparse -import io -import json -import os -from pathlib import Path, PureWindowsPath -import shutil -import subprocess -import sys -import tarfile -import tempfile -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[2] -sys.dont_write_bytecode = True -sys.path.insert(0, str(ROOT / "cmake/local-ci")) -import orchestrator as ci -import worker - - -class LocalCiTests(unittest.TestCase): - def setUp(self): - self.matrix = json.loads((ci.HERE / "lanes.json").read_text()) - self.temporary = tempfile.TemporaryDirectory(prefix="wf-ci-test-") - self.root = Path(self.temporary.name) - ci.STOP.clear() - - def tearDown(self): - self.temporary.cleanup() - ci.STOP.clear() - - def lane(self, name): - return next(lane for lane in self.matrix["lanes"] if lane["id"] == name) - - def test_selection_and_partial_exit_status(self): - self.assertEqual(len(ci.selectedLanes(self.matrix, None, None)), 11) - self.assertEqual(len(ci.selectedLanes(self.matrix, "RyzenLinux", None)), 9) - for machines, lanes in [("Typo", None), (None, "typo"), ("Mac", "web-integration-gcc")]: - with self.assertRaises(ValueError): - ci.selectedLanes(self.matrix, machines, lanes) - passed = {"status": "passed"} - for status in ["unreachable", "skipped (no interactive session)"]: - rows = [passed, {"status": status}] - self.assertEqual(ci.exitCode(rows, False), 0) - self.assertEqual(ci.exitCode(rows, True), 1) - for status in ["failed", "timeout", "interrupted"]: - self.assertEqual(ci.exitCode([passed, {"status": status}], False), 1) - self.assertEqual(ci.exitCode([], False), 1) - self.assertEqual(ci.exitCode([{"status": "unreachable"}], False), 1) - - def test_bundle_contains_unpushed_commit(self): - source, target = self.root / "source", self.root / "target" - subprocess.run(["git", "init", str(source)], check=True, capture_output=True) - (source / "test.txt").write_text("unpushed contents") - for command in [["git", "add", "test.txt"], - ["git", "-c", "user.name=Test", "-c", "user.email=test@example.org", "commit", "-m", "local"], - ["git", "bundle", "create", str(self.root / "commit.bundle"), "HEAD"]]: - subprocess.run(command, cwd=source, check=True, capture_output=True) - subprocess.run(["git", "clone", str(self.root / "commit.bundle"), str(target)], - check=True, capture_output=True) - self.assertEqual((target / "test.txt").read_text(), "unpushed contents") - self.assertFalse((source / ".git/config").read_text().find("github") >= 0) - - def test_archive_rejects_escape_links_and_duplicate_files(self): - for name, kind in [("../escape", tarfile.REGTYPE), ("/escape", tarfile.REGTYPE), - ("link", tarfile.SYMTYPE), ("device", tarfile.CHRTYPE), - ("a\\b", tarfile.REGTYPE), ("duplicate", tarfile.REGTYPE), - ("C:/escape", tarfile.REGTYPE), ("file:stream", tarfile.REGTYPE), - ("NUL.txt", tarfile.REGTYPE), ("alias.", tarfile.REGTYPE)]: - with self.subTest(name=name): - archive = self.root / "bad.tar" - with tarfile.open(archive, "w") as stream: - member = tarfile.TarInfo(name) - member.type = kind - stream.addfile(member) - if name == "duplicate": - stream.addfile(member) - with self.assertRaises(ValueError): - ci.extract(archive, self.root / "out", windows=True) - - def test_metadata_rejects_ssh_options_path_traversal_and_duplicate_ids(self): - import copy - for field, value in [("machine", "-oProxyCommand=bad"), ("machine", "user@host"), - ("id", "../escape"), ("id", "C:/escape"), ("id", "-option"), - ("id", "bad name"), ("id", "con"), ("id", "x" * 65)]: - with self.subTest(field=field, value=value): - matrix = copy.deepcopy(self.matrix) - matrix["lanes"][0][field] = value - with self.assertRaises(ValueError): - ci.selectedLanes(matrix, "CurmudgeonWindows", None) - duplicate = dict(self.matrix, lanes=[self.matrix["lanes"][0]] * 2) - with self.assertRaises(ValueError): - ci.selectedLanes(duplicate, None, None) - with self.assertRaises(ValueError): - ci.ssh("-oProxyCommand=bad", "echo test") - command = ci.ssh("RyzenLinux", "echo test") - self.assertEqual(command[command.index("--") + 1], "RyzenLinux") - - def test_worker_rejects_unknown_lane_before_external_actions(self): - result = subprocess.run([sys.executable, str(ci.HERE / "worker.py"), "stop", "--lane", "../escape"], - capture_output=True, text=True, timeout=10) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("Unknown lane", result.stderr) - - def test_project_status_is_valid_utf8(self): - self.assertNotIn("\ufffd", (ROOT / "docs/PROJECT_STATUS.md").read_text(encoding="utf-8")) - - def test_linux_names_do_not_inherit_windows_alias_restrictions(self): - for name in ("aux.h", "nul.c", "con.txt", "ending.", "ending ", "Foo", "foo"): - self.assertEqual(ci.safeName(name).as_posix(), name) - for name in ("aux.h", "nul.c", "con.txt", "ending.", "ending "): - with self.assertRaises(ValueError): - ci.safeName(name, windows=True) - archive = self.root / "case.tar" - with tarfile.open(archive, "w") as stream: - for name in ("Foo", "foo"): - stream.addfile(tarfile.TarInfo(name)) - with self.assertRaises(ValueError): - ci.extract(archive, self.root / "windows-case", windows=True) - if sys.platform == "linux": - ci.extract(archive, self.root / "linux-case") - self.assertEqual({path.name for path in (self.root / "linux-case").iterdir()}, {"Foo", "foo"}) - - def makeKit(self): - dependencies = self.root / "deps" - dependencies.mkdir() - (dependencies / "preload.cmake").write_text("# offline overrides\n") - (dependencies / "image.tar").write_bytes(b"image fixture") - provision = { - "images": {"linux-ubuntu24-clang23": {"id": "sha256:" + "a" * 64, "archive": "image.tar"}}, - "sources": {"preload.cmake": {"origin": "local overrides", "integrity": "reviewed"}, - "image.tar": {"origin": "docker save", "integrity": "sha256:" + "a" * 64}}} - (dependencies / "provision.json").write_text(json.dumps(provision)) - archive = self.root / "kit.tgz" - ci.pack(argparse.Namespace(dependencies=dependencies, output=archive)) - extracted = self.root / "extracted" - ci.extract(archive, extracted) - return archive, extracted - - def test_kit_integrity_and_extra_missing_modified_files(self): - archive, extracted = self.makeKit() - self.assertEqual(len(ci.verifyKit(extracted)["images"]), 1) - target = extracted / "preload.cmake" - old = target.read_bytes() - for change in ["extra", "missing", "modified"]: - with self.subTest(change=change): - if change == "extra": - (extracted / "unexpected").write_text("extra") - elif change == "missing": - target.unlink() - else: - target.write_text("tampered") - with self.assertRaises(ValueError): - ci.verifyKit(extracted) - (extracted / "unexpected").unlink(missing_ok=True) - target.write_bytes(old) - - def test_kit_refuses_mutable_image_ids_and_git_metadata(self): - _, extracted = self.makeKit() - manifest = json.loads((extracted / "kit.json").read_text()) - manifest["images"]["linux-ubuntu24-clang23"]["id"] = "ubuntu:latest" - (extracted / "kit.json").write_text(json.dumps(manifest)) - with self.assertRaises(ValueError): - ci.verifyKit(extracted) - (extracted / ".git").mkdir() - (extracted / ".git/config").write_text("metadata") - with self.assertRaises(ValueError): - ci.inventory(extracted) - - def test_all_linux_command_plans_keep_tests_and_filters(self): - for lane in ci.selectedLanes(self.matrix, "RyzenLinux", None): - with self.subTest(lane=lane["id"]): - plan = worker.buildCommands(lane, 3) - configurations = [cmd for cmd in plan if "-S" in cmd] - self.assertEqual(len(configurations), len(lane.get("configure_variants", [[]]))) - for cmd in configurations: - self.assertIn("-DFETCHCONTENT_FULLY_DISCONNECTED=ON", cmd) - self.assertIn("-DWEBFRONT_BOOTSTRAP_DIR=/deps/bootstrap", cmd) - self.assertFalse(any("@workspace@" in arg for arg in cmd)) - for cmd in [cmd for cmd in plan if "--build" in cmd]: - self.assertEqual(cmd[cmd.index("--parallel") + 1], "3") - if lane.get("catch2_direct"): - tests = [cmd for cmd in plan if cmd[0].endswith("test/unit/tests")] - self.assertEqual(len(tests), 6) - self.assertEqual(sum("[transport],[weblink]" in cmd for cmd in tests), 5) - else: - tests = [cmd for cmd in plan if cmd[0] == "ctest"] - self.assertEqual(len(tests), len(configurations)) - for cmd in tests: - self.assertIn("--no-tests=error", cmd) - self.assertIn("--output-on-failure", cmd) - for label in lane["ctest"]["labels"]: - self.assertEqual(cmd[cmd.index("-L") + 1], label) - cef = worker.buildCommands(self.lane("web-integration-gcc"), 4) - build = next(cmd for cmd in cef if "--build" in cmd) - self.assertEqual(build[build.index("--target") + 1:], ["webtest", "developer_integration", "webfront-wf"]) - fuzz = worker.buildCommands(self.lane("sanitizers-address-undefined"), 4) - self.assertEqual(sum("-max_total_time=30" in cmd for cmd in fuzz), 4) - installed = worker.buildCommands(self.lane("mddlog-clang-source-install"), 4) - self.assertTrue(any("--install" in cmd for cmd in installed)) - self.assertTrue(any("-DCMAKE_PREFIX_PATH=/workspace/mddlog-install" in cmd for cmd in installed)) - - def test_linux_command_plans_are_independent_of_host_paths(self): - for lane in ci.selectedLanes(self.matrix, "RyzenLinux", None): - with self.subTest(lane=lane["id"]): - expected = worker.buildCommands(lane, 3) - # Model Windows path semantics on every CI host. Paths in these - # commands belong to the Linux container, never to the caller. - with patch.object(worker, "Path", PureWindowsPath): - actual = worker.buildCommands(lane, 3) - self.assertEqual(actual, expected) - self.assertFalse(any("\\" in arg for cmd in actual for arg in cmd)) - - @unittest.skipUnless(shutil.which("cmake") and shutil.which("ctest"), "CMake and CTest required") - def test_ctest_subconfiguration_reuses_offline_cpm_module(self): - cache = self.root / "cache/cpm" - cache.mkdir(parents=True) - version = (ROOT / "cmake/CPM.cmake").read_text().split("set(CPM_DOWNLOAD_VERSION ", 1)[1].split(")", 1)[0] - (cache / f"CPM_{version}.cmake").write_text("set(WF_CPM_LOADED TRUE)\n") - child = self.root / "child.cmake" - child.write_text('''# A download attempt is a failure, without ever accessing the network. -macro(file operation) - if("${operation}" STREQUAL "DOWNLOAD") - message(FATAL_ERROR "CPM download attempted in an offline subconfiguration") - endif() - _file(${ARGV}) -endmacro() -''' + f'''include("{(ROOT / 'cmake/CPM.cmake').as_posix()}") -if(NOT WF_CPM_LOADED) - message(FATAL_ERROR "The prepared CPM module was not loaded") -endif() -''') - build = self.root / "build" - build.mkdir() - # A script-only CTest directory needs no generator discovery. On Windows, - # selecting Visual Studio can run slow host/SDK probes even with project(NONE). - cmake = Path(shutil.which("cmake")).as_posix() - (build / "CTestTestfile.cmake").write_text( - f'add_test(ChildConfiguration "{cmake}" "-P" "{child.as_posix()}")\n') - lane = dict(self.lane("web-integration-gcc"), options=["-DWEBFRONT_EMBED_CEF=OFF"]) - - def execute(invocation, **kwargs): - if invocation[0] == "ctest": - env = dict(kwargs["env"]) - # Map the container mount to this test's prepared host cache. - if env.get("CPM_SOURCE_CACHE") == "/cache/cpm": - env["CPM_SOURCE_CACHE"] = str(cache.parent) - result = subprocess.run(invocation, env=env, capture_output=True, text=True, timeout=20) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - return result - return subprocess.CompletedProcess(invocation, 0, "cmake version " + lane["cmake_version"]) - - plan = [["ctest", "--test-dir", str(build), "-C", "Release", "--output-on-failure", "--no-tests=error"]] - with patch.dict(os.environ), patch.object(worker.os, "umask"), \ - patch.object(worker, "command", side_effect=execute), \ - patch.object(worker, "buildCommands", return_value=plan): - os.environ.pop("CPM_SOURCE_CACHE", None) - worker.executeInside(lane, 1) - - @unittest.skipUnless(os.name == "posix", "Linux container worker") - def test_linux_container_is_offline_unprivileged_and_stopped(self): - lane = self.lane("web-integration-gcc") - self.root = self.root / ".webfront-local-ci/runs/run" - self.root.mkdir(parents=True) - (self.root / "dependencies").mkdir() - (self.root / "dependencies/kit.json").write_text(json.dumps({"images": { - "linux-ubuntu24-clang23": {"id": "sha256:" + "a" * 64}}})) - workspace = self.root / lane["id"] - args = argparse.Namespace(lane=lane["id"], sha="b" * 40, jobs=2, timeout=10, keep=False) - with patch.object(worker, "ROOT", self.root), patch.object(worker, "command") as commands, \ - patch.object(worker, "runProcess", side_effect=subprocess.CalledProcessError(1, "test")) as run, \ - patch.object(worker.subprocess, "run") as stop: - with self.assertRaises(subprocess.CalledProcessError): - worker.runLane(args, self.matrix) - invocation = run.call_args.args[0] - for flag in ["--network=none", "--pull=never", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--user"]: - self.assertIn(flag, invocation) - self.assertNotIn("--privileged", invocation) - self.assertEqual(stop.call_count, 2) - self.assertTrue((self.root / (lane["id"] + "-artifacts.tar")).is_file()) - self.assertFalse(workspace.exists()) - args.keep = True - with patch.object(worker, "ROOT", self.root), patch.object(worker, "command"), \ - patch.object(worker, "runProcess", side_effect=subprocess.CalledProcessError(1, "test")), \ - patch.object(worker.subprocess, "run") as stop: - with self.assertRaises(subprocess.CalledProcessError): - worker.runLane(args, self.matrix) - stop.assert_called_once() - self.assertTrue(workspace.exists()) - - @unittest.skipUnless(os.name == "posix", "Linux container permissions") - def test_cleanup_uses_test_identity_for_private_profiles(self): - workspace = self.root / "workspace" - profile = workspace / "profile" - profile.mkdir(parents=True, mode=0o700) - (profile / "data").write_text("private browser data") - outside = self.root / "outside" - outside.write_text("untouched") - (workspace / "link").symlink_to(outside) - originalRun = subprocess.run - - def clean(invocation, **kwargs): - for flag in ("--network=none", "--pull=never", "--cap-drop=ALL", "--group-add=0"): - self.assertIn(flag, invocation) - self.assertEqual(invocation[invocation.index("--user") + 1], f"{os.getuid()}:{os.getgid()}") - self.assertEqual(invocation.count("--mount"), 1) - script = invocation[-1].replace("Path('/workspace')", "Path(" + repr(str(workspace)) + ")") - return originalRun([sys.executable, "-c", script], check=True, timeout=kwargs["timeout"]) - - with patch.object(worker, "command", side_effect=clean), \ - patch.object(worker.subprocess, "run") as stop, \ - patch.object(worker.shutil, "rmtree", side_effect=PermissionError("host cannot read private profile")): - worker.cleanWorkspace(workspace, "sha256:" + "a" * 64, "fixture") - stop.assert_called_once() - self.assertFalse(workspace.exists()) - self.assertEqual(outside.read_text(), "untouched") - - def test_tsan_host_requirement_stops_before_docker(self): - lane = self.lane("sanitizers-thread") - args = argparse.Namespace(lane=lane["id"]) - with patch.object(worker, "command", return_value=subprocess.CompletedProcess([], 0, "32\n")) as cmd: - with self.assertRaisesRegex(ValueError, r"vm.mmap_rnd_bits=28"): - worker.runLane(args, self.matrix) - cmd.assert_called_once_with(["sysctl", "-n", "vm.mmap_rnd_bits"], capture_output=True, text=True) - - def test_failure_timeout_and_interruption_are_nonzero(self): - with tempfile.TemporaryFile() as log: - with self.assertRaises(subprocess.CalledProcessError): - ci.runProcess([sys.executable, "-c", "raise SystemExit(7)"], log, 2) - with self.assertRaises(TimeoutError): - ci.runProcess([sys.executable, "-c", "import time; time.sleep(30)"], log, 0.1) - ci.STOP.set() - with self.assertRaises(InterruptedError): - ci.runProcess([sys.executable, "-c", "import time; time.sleep(30)"], log, 2) - - @unittest.skipUnless(os.name == "posix" and os.getuid() != 0, "Dedicated non-root POSIX worker") - def test_orchestrator_transport_failure_and_unreachable_machine(self): - import shutil - repository = self.root / "repository" - repository.mkdir() - scripts = repository / "cmake/local-ci" - shutil.copytree(ci.HERE, scripts) - subprocess.run(["git", "init", str(repository)], check=True, capture_output=True) - (repository / ".gitignore").write_text("build*/\n") - for invocation in [["git", "add", "."], - ["git", "-c", "user.name=Test", "-c", "user.email=test@example.org", - "commit", "-m", "fixture"]]: - subprocess.run(invocation, cwd=repository, check=True, capture_output=True) - archive, _ = self.makeKit() - binaries = self.root / "bin" - binaries.mkdir() - remoteRoot = self.root / "remote" - remoteRoot.mkdir() - # Exercise the real tar/bundle/worker protocol with local SSH and Docker stand-ins. - (binaries / "ssh").write_text("#!" + sys.executable + "\n" + r''' -import os, pathlib, shlex, subprocess, sys -if os.environ.get("WF_TEST_UNREACHABLE"): - raise SystemExit(255) -args = shlex.split(sys.argv[-1]) -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''' -import os, subprocess, sys -with open(os.environ["WF_TEST_DOCKER_LOG"], "a") as log: - log.write(repr(sys.argv[1:]) + "\n") -if sys.argv[1] == "run": - workspace = next(arg.split("src=", 1)[1].split(",dst=", 1)[0] for arg in sys.argv - if arg.startswith("type=bind,src=") and arg.endswith("dst=/workspace")) - if sys.argv[-2] == "-c": - # Cleanup has a single mount and executes a fixed script on that mount. - script = sys.argv[-1].replace("Path('/workspace')", "Path(" + repr(workspace) + ")") - exec(script) - raise SystemExit(0) - assert os.path.isdir(os.path.join(workspace, ".git")) - assert subprocess.check_output(["git", "-C", workspace, "ls-files"]).strip() - if os.environ.get("WF_TEST_DOCKER_SUCCESS"): - print("simulated successful container", flush=True) - raise SystemExit(0) - print("intentionally broken test", flush=True) - raise SystemExit(7) -if sys.argv[1] == "info": - print('["name=rootless"]') -''') - for path in binaries.iterdir(): - path.chmod(0o755) - dockerLog = self.root / "docker.log" - env = dict(os.environ, PATH=str(binaries) + os.pathsep + os.environ["PATH"], - WF_TEST_REMOTE=str(remoteRoot), WF_TEST_DOCKER_LOG=str(dockerLog)) - invocation = [sys.executable, str(scripts / "run"), "run", "--lanes", "web-integration-gcc", - "--kit", str(archive), "--kit-sha256", ci.digest(archive), "--require-all"] - failed = subprocess.run(invocation, cwd=repository, env=env, capture_output=True, text=True, timeout=20) - self.assertEqual(failed.returncode, 1, failed.stdout + failed.stderr) - results = list(repository.glob("build-local-ci/*/*/results.json")) - self.assertEqual(len(results), 1) - row = json.loads(results[0].read_text())["results"][0] - self.assertEqual(row["status"], "failed") - self.assertIn("intentionally broken test", (results[0].parent / "web-integration-gcc.log").read_text()) - self.assertTrue((results[0].parent / "web-integration-gcc-artifacts.tar").exists()) - self.assertIn("--network=none", dockerLog.read_text()) - self.assertEqual(list((remoteRoot / ".webfront-local-ci/runs").iterdir()), []) - env["WF_TEST_DOCKER_SUCCESS"] = "1" - succeeded = subprocess.run(invocation, cwd=repository, env=env, capture_output=True, text=True, timeout=20) - self.assertEqual(succeeded.returncode, 0, succeeded.stdout + succeeded.stderr) - self.assertIn("passed", succeeded.stdout) - self.assertIn("INCOMPLETE", succeeded.stdout) - # Two independent Linux checkouts can run concurrently and keep separate results. - parallel = list(invocation) - parallel[parallel.index("--lanes") + 1] = "web-integration-gcc,web-integration-clang" - concurrent = subprocess.run(parallel, cwd=repository, env=env, capture_output=True, text=True, timeout=20) - self.assertEqual(concurrent.returncode, 0, concurrent.stdout + concurrent.stderr) - self.assertEqual(concurrent.stdout.count("passed"), 2) - env["WF_TEST_UNREACHABLE"] = "1" - missing = subprocess.run(invocation, cwd=repository, env=env, capture_output=True, text=True, timeout=20) - self.assertEqual(missing.returncode, 1, missing.stdout + missing.stderr) - self.assertIn("unreachable", missing.stdout) - # A modified tree is rejected before SSH and --allow-dirty still tests only the commit. - (repository / "untracked.txt").write_text("local change") - (scripts / "lanes.json").write_text("dirty, invalid metadata must not be sent") - dirty = subprocess.run(invocation, cwd=repository, env=env, capture_output=True, text=True, timeout=20) - self.assertNotEqual(dirty.returncode, 0) - self.assertIn("Working tree is modified", dirty.stderr) - allowed = subprocess.run(invocation + ["--allow-dirty"], cwd=repository, env=env, - capture_output=True, text=True, timeout=20) - self.assertIn("unreachable", allowed.stdout) - - def test_bootstrap_refuses_to_overwrite_existing_run(self): - # The actual bootstrap protocol is a tar stream, independent of a remote GitHub clone. - script = ci.BOOTSTRAP.replace('pathlib.Path.home()', repr(str(self.root))) - script = script.replace(repr(str(self.root)) + '/".webfront-local-ci"', - 'pathlib.Path(' + repr(str(self.root)) + ')/".webfront-local-ci"') - payload = io.BytesIO() - with tarfile.open(fileobj=payload, mode="w") as archive: - data = b"worker fixture" - info = tarfile.TarInfo("worker.py") - info.size = len(data) - archive.addfile(info, io.BytesIO(data)) - first = subprocess.run([sys.executable, "-c", script, "run-id"], input=payload.getvalue(), capture_output=True) - self.assertEqual(first.returncode, 0, first.stderr) - second = subprocess.run([sys.executable, "-c", script, "run-id"], input=payload.getvalue(), capture_output=True) - self.assertNotEqual(second.returncode, 0) - self.assertEqual((self.root / ".webfront-local-ci/runs/run-id/worker.py").read_bytes(), data) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/cmake/TestLocalCiMacOS.py b/test/cmake/TestLocalCiMacOS.py deleted file mode 100644 index b3d1ae35..00000000 --- a/test/cmake/TestLocalCiMacOS.py +++ /dev/null @@ -1,438 +0,0 @@ -"""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/cmake/TestLocalCiWindows.py b/test/cmake/TestLocalCiWindows.py deleted file mode 100644 index 5441da9e..00000000 --- a/test/cmake/TestLocalCiWindows.py +++ /dev/null @@ -1,514 +0,0 @@ -"""Offline Windows orchestration regressions; no account/firewall/task changes.""" -import argparse -import base64 -import io -import json -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tarfile -import tempfile -import unittest -from unittest.mock import 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 windows_worker as windows - - -class WindowsCiTests(unittest.TestCase): - def setUp(self): - self.temporary = tempfile.TemporaryDirectory(prefix="wf-native-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["runtime"] == "native:msvc") - self.args = argparse.Namespace(lane=self.lane["id"], sha="a" * 40, jobs=12, timeout=1, keep=False) - ci.STOP.clear() - - def tearDown(self): - ci.STOP.clear() - self.temporary.cleanup() - - def test_windows_transport_uses_encoded_powershell_literals(self): - values = ["python.exe", "path with spaces/worker.py", "O'Brien;$HOME&|%", "\"quoted\""] - invocation = ci.remote("CurmudgeonWindows", values) - encoded = invocation[-1].split()[-1] - script = base64.b64decode(encoded).decode("utf-16-le") - self.assertIn("$start.FileName = 'python.exe'", script) - self.assertIn("O''Brien;$HOME&|%", script) - self.assertTrue(script.endswith("exit $process.ExitCode")) - self.assertIn("-EncodedCommand", invocation[-1]) - - def test_windows_plan_preserves_metadata_and_caps_compilations(self): - plan = windows.buildCommands(self.lane, 12, "C:/CI user/work", "C:/CI user/deps", "C:/CI user/cache") - configure, build, test = plan - for option in self.lane["common_options"] + self.lane["options"]: - self.assertIn(option, configure) - self.assertIn("-DCMAKE_CXX_COMPILER=cl", configure) - self.assertIn("-DCMAKE_CXX_COMPILER_LAUNCHER=sccache", configure) - self.assertIn("-DFETCHCONTENT_FULLY_DISCONNECTED=ON", configure) - self.assertIn("-DWEBFRONT_BOOTSTRAP_DIR=C:/CI user/deps/bootstrap", configure) - self.assertEqual(build[build.index("--parallel") + 1], "4") - self.assertEqual(test[test.index("-C") + 1], "Release") - self.assertIn("--no-tests=error", test) - self.assertIn("--output-junit", test) - self.assertEqual(windows.buildCommands(self.lane, 2, "C:/w", "C:/d", "C:/c")[1][-1], "2") - - def test_task_uses_interactive_limited_principal_and_bounded_lifetime(self): - with patch.object(windows, "ps") as run: - windows.startTask(self.root, self.args) - script = run.call_args.args[0] - self.assertIn("-LogonType Interactive -RunLevel Limited", script) - self.assertIn("-ExecutionTimeLimit", script) - self.assertIn("Start-ScheduledTask", script) - self.assertNotIn("-Password", script) - self.assertNotIn("-Force", script) - self.assertIn("--jobs 4", script) - - def test_windows_kit_needs_no_docker_but_keeps_integrity(self): - dependencies = self.root / "input" - dependencies.mkdir() - (dependencies / "preload.cmake").write_text("# overrides") - (dependencies / "provision.json").write_text(json.dumps({"platform": "windows", "sources": { - "preload.cmake": {"origin": "fixture", "integrity": "reviewed"}}})) - archive = self.root / "kit.tgz" - ci.pack(argparse.Namespace(dependencies=dependencies, output=archive)) - with patch.object(windows, "checkNetwork"), patch.object(windows, "command") as run: - windows.prepare(self.root, ci.digest(archive)) - self.assertEqual(run.call_args.args[0][:3], ["git", "clone", "--mirror"]) - self.assertEqual(ci.verifyKit(self.root / "dependencies")["platform"], "windows") - (self.root / "dependencies/preload.cmake").write_text("tampered") - with self.assertRaises(ValueError): - ci.verifyKit(self.root / "dependencies") - - def test_bad_transfer_fails_before_extraction_or_policy_probe(self): - (self.root / "kit.tgz").write_bytes(b"tampered") - with patch.object(windows, "checkNetwork") as probe: - with self.assertRaisesRegex(ValueError, "SHA-256"): - windows.prepare(self.root, "bad") - probe.assert_not_called() - self.assertFalse((self.root / "dependencies").exists()) - - def test_public_network_check_requires_effective_complete_policy(self): - valid = subprocess.CompletedProcess([], 0, json.dumps(windows.publicNetworks())) - with patch.object(windows, "ps", return_value=valid) as run: - windows.checkNetwork() - script = run.call_args.args[0] - self.assertIn("-PolicyStore ActiveStore", script) - self.assertIn("Get-NetFirewallApplicationFilter", script) - self.assertIn("Get-NetFirewallInterfaceFilter", script) - for addresses in [["0.0.0.0/1"], ["0.0.0.0/0"], ["::/0"], []]: - with patch.object(windows, "ps", return_value=subprocess.CompletedProcess([], 0, json.dumps(addresses))): - with self.assertRaises(ValueError): - windows.checkNetwork() - with patch.object(windows, "ps", side_effect=subprocess.CalledProcessError(1, "firewall")): - with self.assertRaises(subprocess.CalledProcessError): - windows.checkNetwork() - - def test_network_policy_deliberately_blocks_multicast_and_broadcast(self): - import ipaddress - networks = [ipaddress.ip_network(value) for value in windows.publicNetworks()] - for address in ("224.0.0.251", "224.0.0.252", "255.255.255.255", "ff02::1", "ff02::fb"): - address = ipaddress.ip_address(address) - self.assertTrue(any(address.version == net.version and address in net for net in networks)) - for address in ("127.0.0.1", "192.168.1.1", "::1", "fc00::1", "fe80::1"): - address = ipaddress.ip_address(address) - self.assertFalse(any(address.version == net.version and address in net for net in networks)) - - def test_failed_session_collects_diagnostics_and_removes_task(self): - workspace = self.root / self.args.lane - workspace.mkdir() - (workspace / "test-results.xml").write_text("") - (self.root / (self.args.lane + ".session.log")).write_text("broken test") - def launch(*_): - (self.root / (self.args.lane + ".result.json")).write_text('{"code":7}') - with patch.object(windows, "startTask", side_effect=launch), patch.object(windows, "stopTask") as stop, \ - patch("sys.stdout", new_callable=io.StringIO): - with self.assertRaises(subprocess.CalledProcessError): - windows.runLane(self.root, self.args) - stop.assert_called_once_with(self.root, self.args.lane) - with tarfile.open(self.root / (self.args.lane + "-artifacts.tar")) as archive: - self.assertIn("test-results.xml", archive.getnames()) - self.assertIn(self.args.lane + ".session.log", archive.getnames()) - self.assertFalse(workspace.exists()) - - def test_success_and_keep(self): - workspace = self.root / self.args.lane - workspace.mkdir() - self.args.keep = True - (self.root / (self.args.lane + ".result.json")).write_text('{"code":0}') - with patch.object(windows, "startTask"), patch.object(windows, "stopTask") as stop: - windows.runLane(self.root, self.args) - stop.assert_called_once() - self.assertTrue(workspace.exists()) - - def test_stop_failure_preserves_original_error_and_collects_diagnostics(self): - workspace = self.root / self.args.lane - workspace.mkdir() - (workspace / "test-results.xml").write_text("") - (self.root / (self.args.lane + ".session.log")).write_text("original test failure") - failure = subprocess.CalledProcessError(7, "build") - with patch.object(windows, "startTask", side_effect=failure), \ - patch.object(windows, "stopTask", side_effect=ValueError("Scheduled task cancellation was not confirmed")), \ - patch.object(windows, "cleanTree") as clean, patch("sys.stdout", new_callable=io.StringIO) as log, \ - patch("sys.stderr", new_callable=io.StringIO) as errors: - with self.assertRaises(subprocess.CalledProcessError) as raised: - windows.runLane(self.root, self.args) - self.assertIs(raised.exception, failure) - self.assertIn("original test failure", log.getvalue()) - self.assertIn("cancellation was not confirmed", errors.getvalue()) - clean.assert_not_called() - with tarfile.open(self.root / (self.args.lane + "-artifacts.tar")) as archive: - self.assertIn("test-results.xml", archive.getnames()) - - def test_stop_failure_after_success_is_nonzero_and_keeps_checkout(self): - (self.root / self.args.lane).mkdir() - (self.root / (self.args.lane + ".result.json")).write_text('{"code":0}') - with patch.object(windows, "startTask"), \ - patch.object(windows, "stopTask", side_effect=ValueError("stop not confirmed")), \ - patch("sys.stderr", new_callable=io.StringIO): - with self.assertRaisesRegex(ValueError, "stop not confirmed"): - windows.runLane(self.root, self.args) - self.assertTrue((self.root / self.args.lane).exists()) - self.assertTrue((self.root / (self.args.lane + "-artifacts.tar")).exists()) - - def test_collection_failure_still_prints_log_and_preserves_execution_error(self): - (self.root / (self.args.lane + ".session.log")).write_text("diagnosis survives collection") - failure = TimeoutError("execution expired") - with patch.object(windows, "startTask", side_effect=failure), patch.object(windows, "stopTask"), \ - patch.object(windows, "collect", side_effect=OSError("archive full")), \ - patch("sys.stdout", new_callable=io.StringIO) as log, patch("sys.stderr", new_callable=io.StringIO) as errors: - with self.assertRaises(TimeoutError) as raised: - windows.runLane(self.root, self.args) - self.assertIs(raised.exception, failure) - self.assertIn("diagnosis survives collection", log.getvalue()) - self.assertIn("archive full", errors.getvalue()) - - def test_late_lane_does_not_recreate_a_removed_run(self): - with patch.object(windows, "startTask") as start, patch.object(windows, "stopTask") as stop, \ - patch.object(windows, "collect") as collect: - windows.cleanTree(self.root, self.root) - with self.assertRaises(InterruptedError): - windows.runLane(self.root, self.args) - start.assert_not_called() - stop.assert_not_called() - collect.assert_not_called() - self.assertFalse(self.root.exists()) - - def test_late_stop_preserves_archive_after_checkout_was_cleaned(self): - workspace = self.root / self.args.lane - workspace.mkdir() - (workspace / "test-results.xml").write_text("") - windows.collect(self.root, self.args.lane) - archive = self.root / (self.args.lane + "-artifacts.tar") - before = archive.read_bytes() - windows.cleanTree(self.root, workspace) - self.args.action = "stop" - with patch.object(windows, "stopTask"): - windows.dispatch(self.args, self.matrix, self.root) - self.assertEqual(archive.read_bytes(), before) - - def test_recovery_cleanup_waits_for_another_channels_lock(self): - # A separate process models the old SSH worker still reading/collecting artifacts. - script = ("import sys,time;sys.dont_write_bytecode=True;sys.path.insert(0," + repr(str(ci.HERE)) + ");" - "import windows_worker as w;from pathlib import Path; " - "lock=w.runLock(Path(sys.argv[1]));lock.__enter__();print('locked',flush=True);" - "sys.stdin.readline();lock.__exit__(None,None,None)") - holder = subprocess.Popen([sys.executable, "-c", script, str(self.root)], - stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) - try: - self.assertEqual(holder.stdout.readline().strip(), "locked") - self.args.action = "cleanup" - self.args.lane = None - lock = windows.runLock - with patch.object(windows, "runLock", side_effect=lambda root: lock(root, timeout=0.01)), \ - patch.object(windows, "stopTask") as stop: - with self.assertRaises(TimeoutError): - windows.dispatch(self.args, self.matrix, self.root) - stop.assert_not_called() - self.assertTrue(self.root.exists()) - holder.communicate("release\n", timeout=10) - self.assertEqual(holder.returncode, 0) - with patch.object(windows, "stopTask"): - windows.dispatch(self.args, self.matrix, self.root) - self.assertFalse(self.root.exists()) - finally: - if holder.poll() is None: - holder.kill() - holder.communicate(timeout=10) - - def test_cleanup_failure_keeps_run_for_inspection(self): - self.args.action = "cleanup" - self.args.lane = None - with patch.object(windows, "stopTask", side_effect=ValueError("not stopped")), \ - patch.object(windows, "cleanTree") as clean: - with self.assertRaises(ValueError): - windows.dispatch(self.args, self.matrix, self.root) - clean.assert_not_called() - - def test_rmtree_uses_onexc_on_modern_python(self): - with patch.object(sys, "version_info", (3, 12)), patch.object(windows.shutil, "rmtree") as remove: - windows.cleanTree(self.root, self.root) - self.assertIn("onexc", remove.call_args.kwargs) - self.assertNotIn("onerror", remove.call_args.kwargs) - - def test_timeout_interruption_and_missing_session_stop_the_task(self): - for interrupted in (False, True): - with self.subTest(interrupted=interrupted): - self.args.timeout = 0.02 - ci.STOP.clear() - if interrupted: - ci.STOP.set() - with patch.object(windows, "startTask"), patch.object(windows, "stopTask") as stop: - with self.assertRaises(InterruptedError if interrupted else TimeoutError): - windows.runLane(self.root, self.args) - stop.assert_called_once() - - def test_cancellation_signals_and_unregisters_exact_task(self): - with patch.object(windows, "ps") as run: - windows.stopTask(self.root, self.args.lane) - self.assertTrue((self.root / (self.args.lane + ".cancel")).exists()) - self.assertIn(windows.taskName(self.root, self.args.lane), run.call_args.args[0]) - self.assertIn("Unregister-ScheduledTask", run.call_args.args[0]) - self.assertNotIn("-Force", run.call_args.args[0]) - - def test_cleanup_refuses_unrelated_directory(self): - self.args.action = "cleanup" - self.args.lane = None - with self.assertRaisesRegex(ValueError, "Refusing cleanup"): - windows.dispatch(self.args, self.matrix, Path(self.temporary.name)) - self.assertTrue(self.root.exists()) - - def test_session_rejects_unavailable_desktop_before_configure(self): - with patch.object(windows, "ownProcessTree"), \ - patch.object(windows, "checkDesktop", side_effect=ValueError("locked desktop")), \ - patch.object(windows, "command") as run, patch.object(sys, "stdout"), patch.object(sys, "stderr"): - self.assertEqual(windows.session(self.root, self.args, self.lane), 1) - run.assert_not_called() - result = self.root / (self.args.lane + ".result.json") - self.assertEqual(json.loads(result.read_text())["code"], 1) - self.assertIn("locked desktop", (self.root / (self.args.lane + ".session.log")).read_text()) - - def test_native_session_runs_planned_commands_and_propagates_build_failure(self): - def command(invocation, **kwargs): - return subprocess.CompletedProcess(invocation, 0, "cmake version " + self.lane["cmake_version"] + "\n") - for failed in (False, True): - with self.subTest(failed=failed), patch.object(windows, "ownProcessTree"), \ - patch.object(windows, "checkDesktop"), patch.object(windows, "checkNetwork"), \ - patch.object(windows, "checkRuntime"), patch.object(windows, "msvcEnvironment", return_value={}), \ - patch.object(windows, "command", side_effect=command), patch.dict(os.environ), \ - patch.object(sys, "stdout"), patch.object(sys, "stderr"), \ - patch.object(windows, "runProcess", side_effect=( - [None, subprocess.CalledProcessError(7, "build")] if failed else None)) as run: - self.assertEqual(windows.session(self.root, self.args, self.lane), int(failed)) - calls = [call.args[0] for call in run.call_args_list] - self.assertEqual(len(calls), 2 if failed else 3) - self.assertIn("--build", calls[1]) - if not failed: - self.assertEqual(calls[2][0], "ctest") - result = json.loads((self.root / (self.args.lane + ".result.json")).read_text()) - self.assertEqual(result["code"], int(failed)) - - @unittest.skipUnless(shutil.which("cmake") and shutil.which("ctest"), "CMake and CTest required") - def test_native_ctest_subconfiguration_reuses_offline_cpm(self): - cache = self.root.parent.parent / "cache/cpm/cpm" - cache.mkdir(parents=True) - version = (ROOT / "cmake/CPM.cmake").read_text().split("set(CPM_DOWNLOAD_VERSION ", 1)[1].split(")", 1)[0] - (cache / f"CPM_{version}.cmake").write_text("set(WF_CPM_LOADED TRUE)\n") - fixture = self.root / "fixture" - fixture.mkdir() - child = fixture / "child.cmake" - child.write_text('''macro(file operation) - if("${operation}" STREQUAL "DOWNLOAD") - message(FATAL_ERROR "Native CTest subconfiguration attempted a CPM download") - endif() - _file(${ARGV}) -endmacro() -''' + f'''include("{(ROOT / 'cmake/CPM.cmake').as_posix()}") -if(NOT WF_CPM_LOADED) - message(FATAL_ERROR "Prepared CPM module was not loaded") -endif() -''') - build = fixture / "build" - build.mkdir() - cmake = Path(shutil.which("cmake")).as_posix() - (build / "CTestTestfile.cmake").write_text( - f'add_test(ChildConfiguration "{cmake}" "-P" "{child.as_posix()}")\n') - def invoke(arguments, log, timeout): - if arguments[0] == "ctest": - result = subprocess.run(["ctest", "--test-dir", str(build), "-C", "Release", "--no-tests=error", - "--output-on-failure"], capture_output=True, text=True, timeout=20) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - with patch.object(windows, "ownProcessTree"), patch.object(windows, "checkDesktop"), \ - patch.object(windows, "checkNetwork"), patch.object(windows, "checkRuntime"), \ - patch.object(windows, "msvcEnvironment", return_value={}), patch.dict(os.environ), \ - patch.object(windows, "command", return_value=subprocess.CompletedProcess([], 0, - "cmake version " + self.lane["cmake_version"])), \ - patch.object(windows, "runProcess", side_effect=invoke): - os.environ.pop("CPM_SOURCE_CACHE", None) - self.args.timeout = 30 - self.assertEqual(windows.session(self.root, self.args, self.lane), 0) - - @unittest.skipUnless(os.name == "nt", "Native Windows transport") - def test_real_powershell_preserves_binary_stdin_stdout_and_arguments(self): - invocation = ci.remote("CurmudgeonWindows", [sys.executable, "-c", - "import sys;sys.stdout.buffer.write(sys.stdin.buffer.read());" - "assert sys.argv[1] == \"O'Brien & space\"", "O'Brien & space"], forward_stdin=True) - encoded = invocation[-1].split()[-1] - script = base64.b64decode(encoded).decode("utf-16-le") - for prefix in ("", "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ", - "[Console]::InputEncoding = [System.Text.Encoding]::UTF8; "): - with self.subTest(prefix=prefix): - encoded = base64.b64encode((prefix + script).encode("utf-16-le")).decode() - result = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], - input=bytes(range(256)), capture_output=True, timeout=20) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(result.stdout, bytes(range(256))) - - @unittest.skipUnless(os.name == "nt", "Native Windows argument parsing") - def test_real_powershell_roundtrips_backslashes_quotes_and_empty_arguments(self): - values = ["", "plain", "a b", 'backslash\\"quote', 'two\\\\"quotes', 'trailing space \\', - 'C:\\path with spaces\\', "'apostrophe'", '"', "&|%$", "caf\u00e9"] - args = [sys.executable, "-c", "import json,sys;print(json.dumps(sys.argv[1:]))", *values] - invocation = ci.remote("CurmudgeonWindows", args) - result = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand", - invocation[-1].split()[-1]], capture_output=True, timeout=20) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(json.loads(result.stdout), values) - - @unittest.skipUnless(os.name == "nt", "Native Windows stdin lifecycle") - def test_remote_command_does_not_wait_for_unused_open_stdin(self): - invocation = ci.remote("CurmudgeonWindows", [sys.executable, "-c", "print('done')"]) - child = subprocess.Popen(["powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand", - invocation[-1].split()[-1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - try: - child.wait(timeout=10) # Keep stdin open, as an interactive SSH client would. - self.assertEqual(child.returncode, 0, child.stderr.read()) - self.assertEqual(child.stdout.read().strip(), b"done") - finally: - child.stdin.close() - if child.poll() is None: - child.kill() - child.wait(timeout=10) - child.stdout.close() - child.stderr.close() - - def test_full_windows_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": "windows", "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 windows_worker as w - w.checkNetwork=lambda: None - 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, "CurmudgeonWindows") - return [sys.executable, str(shim), str(remoteRoot), *arguments] - args = argparse.Namespace(allow_dirty=False, commit="HEAD", machines="CurmudgeonWindows", lanes=None, - kit=None, kit_sha256=None, windows_kit=archive, windows_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): - 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"}) - 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) - - @unittest.skipUnless(os.name == "nt", "Windows Job Object") - def test_killing_worker_also_kills_child_process(self): - script = ("import sys,subprocess,time; sys.path.insert(0," + repr(str(ci.HERE)) + "); " - "import windows_worker as w; job=w.ownProcessTree(); " - "p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']); " - "print(p.pid,flush=True); time.sleep(60)") - parent = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE, text=True) - import ctypes - from ctypes import wintypes - kernel = ctypes.WinDLL("kernel32", use_last_error=True) - kernel.OpenProcess.restype = wintypes.HANDLE - kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] - kernel.CloseHandle.argtypes = [wintypes.HANDLE] - handle = None - try: - child = int(parent.stdout.readline()) - handle = kernel.OpenProcess(0x100000, False, child) - self.assertTrue(handle) - parent.terminate() - parent.wait(timeout=10) - self.assertEqual(kernel.WaitForSingleObject(handle, 10000), 0) - finally: - if parent.poll() is None: - parent.kill() - parent.wait(timeout=10) - parent.stdout.close() - if handle: - kernel.CloseHandle(handle) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 6b26efac..f8922d16 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -90,27 +90,6 @@ add_test(NAME RepositoryLayoutRejectsVendoredSources COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DGIT_EXECUTABLE=${GIT_EXECUTABLE} -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/layout-negative -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckRepositoryLayoutNegative.cmake) -# The local CI matrix (#346) has to keep describing the lanes of the GitHub workflows. -add_test(NAME LocalCiLanesMatchWorkflows - COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckLocalCi.cmake) -add_test(NAME LocalCiLanesRejectDrift - COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/local-ci-negative - -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckLocalCiNegative.cmake) -# Python is a local-CI driver dependency, not a library/build dependency. -find_package(Python3 3.10 QUIET COMPONENTS Interpreter) -if(Python3_Interpreter_FOUND) - add_test(NAME LocalCiOrchestrator - COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/cmake/TestLocalCi.py") - set_tests_properties(LocalCiOrchestrator PROPERTIES TIMEOUT 60) - 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() add_test(NAME NewcomerDocsMatchExamples COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckNewcomerDocs.cmake) add_test(NAME FrontendSelection