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..fb6a438f --- /dev/null +++ b/cmake/local-ci/orchestrator.py @@ -0,0 +1,365 @@ +"""Transfer a chosen commit and an offline dependency kit, then run Linux lanes over SSH.""" +import argparse +import concurrent.futures +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +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() + + +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): + path = PurePosixPath(name) + if path.is_absolute() or ".." in path.parts or "\\" in name or not path.parts: + raise ValueError(f"Unsafe archive path: {name}") + return path + + +def extract(archive, destination): + # No links, devices or duplicate paths: never let an archive write outside its run directory. + with tarfile.open(archive) as source: + names = set() + for member in source: + name = safeName(member.name).as_posix() + if name in names or not (member.isfile() or member.isdir()): + raise ValueError(f"Unsupported archive member: {member.name}") + names.add(name) + 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"): + raise ValueError("provision.json must describe images and source provenance") + # 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 selectedLanes(matrix, machines, lanes): + 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): + return ["ssh", "-oBatchMode=yes", "-oConnectTimeout=5", "-oServerAliveInterval=10", + "-oServerAliveCountMax=2", machine, script] + + +def remote(machine, args): + # All values are shell quoted once, at the SSH command-string boundary. + return ssh(machine, shlex.join(args)) + + +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: + 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 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) + kit = None + if args.kit: + if digest(args.kit) != args.kit_sha256: + raise ValueError("Offline kit SHA-256 mismatch") + kit = args.kit.resolve() + 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) + payload = scratch / "payload.tar" + selectedMatrix = scratch / "lanes.json" + selectedMatrix.write_text(json.dumps(matrix)) + with tarfile.open(payload, "w") as archive: + for path, name in [(bundle, "commit.bundle"), (HERE / "worker.py", "worker.py"), + (HERE / "orchestrator.py", "orchestrator.py"), + (selectedMatrix, "lanes.json")]: + archive.add(path, arcname=name) + if kit: + archive.add(kit, arcname="kit.tgz") + machines = {lane["machine"] for lane in lanes} + 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 != "RyzenLinux": + return "skipped (native session support pending step 3)" + if not kit: + log.write(b"Linux lanes require --kit and --kit-sha256; prepare an offline kit first.\n") + return "failed" + try: + with open(payload, "rb") as stream: + runProcess(remote(machine, ["python3", "-c", BOOTSTRAP, runId]), log, + args.transfer_timeout, stream) + runProcess(remote(machine, ["python3", f".webfront-local-ci/runs/{runId}/worker.py", + "prepare", "--kit-sha256", args.kit_sha256]), 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(remote(machine, ["python3", f".webfront-local-ci/runs/{runId}/worker.py", + "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(remote(machine, ["python3", f".webfront-local-ci/runs/{runId}/worker.py", + "stop", "--lane", laneId]), stdout=log, + stderr=subprocess.STDOUT, timeout=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(remote(machine, ["python3", f".webfront-local-ci/runs/{runId}/worker.py", + "artifacts", "--lane", laneId]), stdout=artifacts, + stderr=log, timeout=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 == "RyzenLinux" and status != "unreachable": + with open(output / (machine + "-cleanup.log"), "wb") as log: + try: + command(remote(machine, ["python3", f".webfront-local-ci/runs/{runId}/worker.py", + "cleanup"]), stdout=log, stderr=subprocess.STDOUT, timeout=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("--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") + 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/worker.py b/cmake/local-ci/worker.py new file mode 100644 index 00000000..e2078dd1 --- /dev/null +++ b/cmake/local-ci/worker.py @@ -0,0 +1,285 @@ +"""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 + +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 launches independent CMake configurations, which do not inherit -D cache entries. + 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"]) + 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()) + signal.signal(signal.SIGHUP, lambda *_: STOP.set()) + matrix = json.loads((ROOT / "lanes.json").read_text()) + try: + 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..75359535 100644 --- a/docs/LOCAL_CI.md +++ b/docs/LOCAL_CI.md @@ -12,7 +12,7 @@ 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 | +| 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 | not started | ## The lanes @@ -88,3 +88,196 @@ 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 eleven lanes +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. + +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`. + +### 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. Delivery step 3 still needs the Windows interactive scheduled task (MSVC environment, at most four +compilations and WebView2 runtime), the macOS graphical session and Xcode reporting, and the eleven-lane run. For now a reachable +Windows/Mac machine reports `skipped (native session support pending step 3)`; an unreachable one reports `unreachable`. +Neither counts as passed, and `--require-all` fails when either is selected. The story remains open. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 8ce41a01..c33ffe64 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -614,3 +614,11 @@ 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. Real Linux image/host qualification, native Windows/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..eed83d7a --- /dev/null +++ b/test/cmake/TestLocalCi.py @@ -0,0 +1,404 @@ +"""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)]: + 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") + + 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/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 22d63527..6b86f1c9 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -96,6 +96,15 @@ 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) +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