diff --git a/cmake/local-ci/linux.Dockerfile b/cmake/local-ci/linux.Dockerfile new file mode 100644 index 00000000..04d934b3 --- /dev/null +++ b/cmake/local-ci/linux.Dockerfile @@ -0,0 +1,33 @@ +# 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/orchestrator.py b/cmake/local-ci/orchestrator.py new file mode 100644 index 00000000..e61a8ba8 --- /dev/null +++ b/cmake/local-ci/orchestrator.py @@ -0,0 +1,434 @@ +"""Transfer a commit and verified offline kits, then run Linux/Windows 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") == "windows"): + raise ValueError("provision.json must describe images or platform=windows, 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) + 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 / "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 {"RyzenLinux", "CurmudgeonWindows"}: + return "skipped (native session support pending step 3)" + if machine not in kits: + log.write(b"Missing offline kit and SHA-256 for this machine.\n") + return "failed" + 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 "failed" + except (subprocess.SubprocessError, OSError): + status = "failed" + if status in {"interrupted", "timeout", "failed"}: + # A second SSH channel stops the container even if the execution channel was lost. + try: + command(workerCommand(machine, "stop", "--lane", laneId), stdout=log, + stderr=subprocess.STDOUT, timeout=90 if machine == "CurmudgeonWindows" else 15) + except (subprocess.SubprocessError, OSError): + log.write(b"Remote cancellation could not be confirmed; inspect the container.\n") + try: + with open(output / (laneId + "-artifacts.tar"), "wb") as artifacts: + command(workerCommand(machine, "artifacts", "--lane", laneId), stdout=artifacts, + stderr=log, timeout=90 if machine == "CurmudgeonWindows" else 60) + 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 == "CurmudgeonWindows" 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("--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") + 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 new file mode 100644 index 00000000..513aea53 --- /dev/null +++ b/cmake/local-ci/run @@ -0,0 +1,11 @@ +#!/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 new file mode 100644 index 00000000..547134f6 --- /dev/null +++ b/cmake/local-ci/windows_worker.py @@ -0,0 +1,504 @@ +"""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 stat +import subprocess +import sys +import tarfile +import threading +import time + +from orchestrator import command, digest, extract, verifyKit, psQuote, STOP, runProcess, validateMatrix +from worker import ctestCommand + + +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 collect(root, lane): + workspace = root / lane + destination = root / (lane + "-artifacts.tar") + # A recovery stop may arrive after the original channel archived and removed + # its checkout. Preserve that complete archive rather than replacing it with just a log. + if destination.exists() and not workspace.exists(): + return + temporary = destination.with_suffix(".tmp") + with tarfile.open(temporary, "w") as archive: + log = root / (lane + ".session.log") + if log.is_file(): + archive.add(log, arcname=log.name) + for pattern in ("**/test-results.xml", "**/LastTest.log", "**/CMakeConfigureLog.yaml"): + for path in workspace.glob(pattern): + if path.is_file() and not path.is_symlink(): + archive.add(path, arcname=path.relative_to(workspace), recursive=False) + temporary.replace(destination) + + +def cleanTree(root, target): + root, target = root.resolve(), target.resolve() + if (root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci" + or not target.is_relative_to(root)): + raise ValueError("Refusing cleanup outside a local CI run") + def readonly(function, path, error): + # Git object files are read-only on Windows, even in an owned disposable clone. + if not Path(path).resolve().is_relative_to(target): + raise ValueError("Cleanup path escaped the local CI run") + if not os.stat(path).st_mode & stat.S_IWRITE: + os.chmod(path, stat.S_IWRITE) + function(path) + else: + raise error + if sys.version_info >= (3, 12): + shutil.rmtree(target, onexc=readonly) + else: + shutil.rmtree(target, onerror=lambda function, path, error: readonly(function, path, error[1])) + + +@contextlib.contextmanager +def runLock(root, timeout=60): + """Serialize finalization and recovery SSH channels, including run-directory removal.""" + root = root.resolve() + if root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci": + raise ValueError("Refusing lock outside a local CI run") + # Outside the removable run: every channel must keep opening the same lock file. + locks = root.parent.parent / "locks" + locks.mkdir(exist_ok=True) + with open(locks / (root.name + ".lock"), "a+b") as lock: + if lock.tell() == 0: + lock.write(b"\0") + lock.flush() + deadline = time.monotonic() + timeout + while True: + try: + lock.seek(0) + if os.name == "nt": + import msvcrt + msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except OSError: + if time.monotonic() >= deadline: + raise TimeoutError("Another Windows CI channel is still finalizing this run") + time.sleep(0.1) + try: + yield + finally: + lock.seek(0) + if os.name == "nt": + msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(lock.fileno(), fcntl.LOCK_UN) + + +def finishLane(root, args): + """Return secondary errors; always try both diagnostic paths, never delete a live checkout.""" + errors = [] + 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 new file mode 100644 index 00000000..468468fd --- /dev/null +++ b/cmake/local-ci/worker.py @@ -0,0 +1,292 @@ +"""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(): + 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("--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 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/LOCAL_CI.md b/docs/LOCAL_CI.md index 9b5c5fe1..5ee5b87d 100644 --- a/docs/LOCAL_CI.md +++ b/docs/LOCAL_CI.md @@ -12,8 +12,8 @@ The story is delivered in three verifiable steps; a partial step does not close | Step | Content | State | | --- | --- | --- | | 1 | The eleven lanes in `cmake/local-ci/lanes.json` and the offline drift check `LocalCiLanesMatchWorkflows` | delivered | -| 2 | Commit transport, provisioning without GitHub access, Linux containers and the orchestrator | not started | -| 3 | Native Windows and macOS sessions, result collection, full qualification and timings | not started | +| 2 | Commit transport, offline-kit verification, Linux containers and the orchestrator | implemented; real-host/image qualification pending | +| 3 | Native Windows and macOS sessions, result collection, full qualification and timings | Windows implementation delivered; host qualification and macOS pending | ## The lanes @@ -88,3 +88,308 @@ The command metadata in `lanes.json` uses these fields: - 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. Delivery step 3 also needs the macOS graphical session and Xcode reporting, and the eleven-lane run. +A reachable Mac reports `skipped (native session support pending step 3)`; an unreachable machine reports `unreachable`. +Neither counts as passed, and `--require-all` fails when either is selected. The story remains open. + +### 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. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 8ce41a01..48d1cb1d 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -614,3 +614,14 @@ 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. +Real Linux image/host and Windows account/task qualification, native macOS sessions and comparison with GitHub timings remain open; +this is not yet a qualified replacement for running any of the GitHub jobs. See [LOCAL_CI](LOCAL_CI.md). diff --git a/test/cmake/TestLocalCi.py b/test/cmake/TestLocalCi.py new file mode 100644 index 00000000..acf6f177 --- /dev/null +++ b/test/cmake/TestLocalCi.py @@ -0,0 +1,449 @@ +"""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)) + ")") +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/TestLocalCiWindows.py b/test/cmake/TestLocalCiWindows.py new file mode 100644 index 00000000..5441da9e --- /dev/null +++ b/test/cmake/TestLocalCiWindows.py @@ -0,0 +1,514 @@ +"""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 22d63527..e6e90b5b 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -96,6 +96,18 @@ add_test(NAME LocalCiLanesMatchWorkflows 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) +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