Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
394 changes: 394 additions & 0 deletions cmake/local-ci/macos_worker.py

Large diffs are not rendered by default.

89 changes: 89 additions & 0 deletions cmake/local-ci/native_worker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""Shared diagnostic collection, cleanup and cross-channel locking for native lanes."""
import contextlib
import os
from pathlib import Path
import shutil
import stat
import sys
import tarfile
import time


def collect(root, lane):
workspace = root / lane
destination = root / (lane + "-artifacts.tar")
# A recovery stop may arrive after the original channel archived and removed
# its checkout. Preserve that complete archive rather than replacing it with just a log.
if destination.exists() and not workspace.exists():
return
temporary = destination.with_suffix(".tmp")
with tarfile.open(temporary, "w") as archive:
for suffix in (".session.log", ".launch.log"):
log = root / (lane + suffix)
if log.is_file():
archive.add(log, arcname=log.name)
for pattern in ("**/test-results.xml", "**/LastTest.log", "**/CMakeConfigureLog.yaml"):
for path in workspace.glob(pattern):
if path.is_file() and not path.is_symlink():
archive.add(path, arcname=path.relative_to(workspace), recursive=False)
temporary.replace(destination)


def cleanTree(root, target):
root, target = root.resolve(), target.resolve()
if (root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci"
or not target.is_relative_to(root)):
raise ValueError("Refusing cleanup outside a local CI run")
def readonly(function, path, error):
# Git object files are read-only on Windows, even in an owned disposable clone.
if not Path(path).resolve().is_relative_to(target):
raise ValueError("Cleanup path escaped the local CI run")
if not os.stat(path).st_mode & stat.S_IWRITE:
os.chmod(path, stat.S_IWRITE)
function(path)
else:
raise error
if sys.version_info >= (3, 12):
shutil.rmtree(target, onexc=readonly)
else:
shutil.rmtree(target, onerror=lambda function, path, error: readonly(function, path, error[1]))


@contextlib.contextmanager
def runLock(root, timeout=60):
"""Serialize finalization and recovery SSH channels, including run-directory removal."""
root = root.resolve()
if root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci":
raise ValueError("Refusing lock outside a local CI run")
# Outside the removable run: every channel must keep opening the same lock file.
locks = root.parent.parent / "locks"
locks.mkdir(exist_ok=True)
with open(locks / (root.name + ".lock"), "a+b") as lock:
if lock.tell() == 0:
lock.write(b"\0")
lock.flush()
deadline = time.monotonic() + timeout
while True:
try:
lock.seek(0)
if os.name == "nt":
import msvcrt
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except OSError:
if time.monotonic() >= deadline:
raise TimeoutError("Another native CI channel is still finalizing this run")
time.sleep(0.1)
try:
yield
finally:
lock.seek(0)
if os.name == "nt":
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(lock.fileno(), fcntl.LOCK_UN)


30 changes: 20 additions & 10 deletions cmake/local-ci/orchestrator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Transfer a commit and verified offline kits, then run Linux/Windows lanes over SSH."""
"""Transfer a commit and verified offline kits, then run Linux/Windows/macOS lanes over SSH."""
import argparse
import base64
import concurrent.futures
Expand Down Expand Up @@ -103,8 +103,8 @@ def pack(args):
if args.output.resolve().is_relative_to(root):
raise ValueError("The output archive must be outside the dependency directory")
config = json.loads((root / "provision.json").read_text())
if not config.get("sources") or not (config.get("images") or config.get("platform") == "windows"):
raise ValueError("provision.json must describe images or platform=windows, and source provenance")
if not config.get("sources") or not (config.get("images") or config.get("platform") in {"windows", "macos"}):
raise ValueError("provision.json must describe images or platform=windows/macos, and source provenance")
config.setdefault("images", {})
# Require provenance for every top-level tree (archives retain their upstream checksums).
for path in root.iterdir():
Expand Down Expand Up @@ -278,6 +278,11 @@ def execute(args):
if digest(windowsKit) != args.windows_kit_sha256:
raise ValueError("Windows offline kit SHA-256 mismatch")
kits["CurmudgeonWindows"] = (windowsKit.resolve(), args.windows_kit_sha256)
macosKit = getattr(args, "macos_kit", None)
if macosKit:
if digest(macosKit) != args.macos_kit_sha256:
raise ValueError("macOS offline kit SHA-256 mismatch")
kits["Mac"] = (macosKit.resolve(), args.macos_kit_sha256)
bundle = scratch / "commit.bundle"
# A temporary private ref lets git bundle include detached and unpushed commits.
ref = "refs/local-ci/" + runId
Expand All @@ -295,6 +300,8 @@ def execute(args):
with tarfile.open(payload, "w") as archive:
for path, name in [(bundle, "commit.bundle"), (HERE / "worker.py", "worker.py"),
(HERE / "windows_worker.py", "windows_worker.py"),
(HERE / "macos_worker.py", "macos_worker.py"),
(HERE / "native_worker.py", "native_worker.py"),
(HERE / "orchestrator.py", "orchestrator.py"),
(selectedMatrix, "lanes.json"), (kits[machine][0], "kit.tgz")]:
archive.add(path, arcname=name)
Expand All @@ -311,8 +318,6 @@ def prepare(machine):
return "interrupted"
except (subprocess.SubprocessError, TimeoutError, OSError):
return "unreachable"
if machine not in {"RyzenLinux", "CurmudgeonWindows"}:
return "skipped (native session support pending step 3)"
if machine not in kits:
log.write(b"Missing offline kit and SHA-256 for this machine.\n")
return "failed"
Expand Down Expand Up @@ -353,20 +358,21 @@ def laneTask(lane):
except TimeoutError:
status = "timeout"
except subprocess.CalledProcessError as error:
status = "timeout" if error.returncode == 124 else "failed"
status = ("timeout" if error.returncode == 124 else
"skipped (no interactive session)" if machine == "Mac" and error.returncode == 125 else "failed")
except (subprocess.SubprocessError, OSError):
status = "failed"
if status in {"interrupted", "timeout", "failed"}:
# A second SSH channel stops the container even if the execution channel was lost.
try:
command(workerCommand(machine, "stop", "--lane", laneId), stdout=log,
stderr=subprocess.STDOUT, timeout=90 if machine == "CurmudgeonWindows" else 15)
stderr=subprocess.STDOUT, timeout=90 if machine in {"CurmudgeonWindows", "Mac"} else 15)
except (subprocess.SubprocessError, OSError):
log.write(b"Remote cancellation could not be confirmed; inspect the container.\n")
log.write(b"Remote cancellation could not be confirmed; inspect the remote run.\n")
try:
with open(output / (laneId + "-artifacts.tar"), "wb") as artifacts:
command(workerCommand(machine, "artifacts", "--lane", laneId), stdout=artifacts,
stderr=log, timeout=90 if machine == "CurmudgeonWindows" else 60)
stderr=log, timeout=90 if machine in {"CurmudgeonWindows", "Mac"} else 60)
except (subprocess.SubprocessError, OSError):
log.write(b"Artifact collection failed.\n")
if status == "passed":
Expand All @@ -386,7 +392,7 @@ def laneTask(lane):
with open(output / (machine + "-cleanup.log"), "wb") as log:
try:
command(workerCommand(machine, "cleanup"), stdout=log, stderr=subprocess.STDOUT,
timeout=90 if machine == "CurmudgeonWindows" else 30)
timeout=90 if machine in {"CurmudgeonWindows", "Mac"} else 30)
except (subprocess.SubprocessError, OSError):
print(f"Cleanup not confirmed on {machine}; run {runId} retained")
finally:
Expand Down Expand Up @@ -414,6 +420,8 @@ def main(argv=None):
run.add_argument("--kit-sha256")
run.add_argument("--windows-kit", type=Path)
run.add_argument("--windows-kit-sha256")
run.add_argument("--macos-kit", type=Path)
run.add_argument("--macos-kit-sha256")
run.add_argument("--parallel-lanes", type=int, default=2)
run.add_argument("--jobs", type=int, default=4)
run.add_argument("--timeout", type=int, default=3600)
Expand All @@ -428,6 +436,8 @@ def main(argv=None):
raise ValueError("--kit and --kit-sha256 must be supplied together")
if bool(args.windows_kit) != bool(args.windows_kit_sha256):
raise ValueError("--windows-kit and --windows-kit-sha256 must be supplied together")
if bool(args.macos_kit) != bool(args.macos_kit_sha256):
raise ValueError("--macos-kit and --macos-kit-sha256 must be supplied together")
return execute(args)
except (ValueError, OSError, subprocess.SubprocessError) as error:
print(f"local-ci: {error}", file=__import__('sys').stderr)
Expand Down
80 changes: 1 addition & 79 deletions cmake/local-ci/windows_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,14 @@
from pathlib import Path, PureWindowsPath
import shutil
import socket
import stat
import subprocess
import sys
import tarfile
import threading
import time

from orchestrator import command, digest, extract, verifyKit, psQuote, STOP, runProcess, validateMatrix
from worker import ctestCommand
from native_worker import collect, cleanTree, runLock


def ps(script, **kwargs):
Expand Down Expand Up @@ -311,83 +310,6 @@ def watch():
return code


def collect(root, lane):
workspace = root / lane
destination = root / (lane + "-artifacts.tar")
# A recovery stop may arrive after the original channel archived and removed
# its checkout. Preserve that complete archive rather than replacing it with just a log.
if destination.exists() and not workspace.exists():
return
temporary = destination.with_suffix(".tmp")
with tarfile.open(temporary, "w") as archive:
log = root / (lane + ".session.log")
if log.is_file():
archive.add(log, arcname=log.name)
for pattern in ("**/test-results.xml", "**/LastTest.log", "**/CMakeConfigureLog.yaml"):
for path in workspace.glob(pattern):
if path.is_file() and not path.is_symlink():
archive.add(path, arcname=path.relative_to(workspace), recursive=False)
temporary.replace(destination)


def cleanTree(root, target):
root, target = root.resolve(), target.resolve()
if (root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci"
or not target.is_relative_to(root)):
raise ValueError("Refusing cleanup outside a local CI run")
def readonly(function, path, error):
# Git object files are read-only on Windows, even in an owned disposable clone.
if not Path(path).resolve().is_relative_to(target):
raise ValueError("Cleanup path escaped the local CI run")
if not os.stat(path).st_mode & stat.S_IWRITE:
os.chmod(path, stat.S_IWRITE)
function(path)
else:
raise error
if sys.version_info >= (3, 12):
shutil.rmtree(target, onexc=readonly)
else:
shutil.rmtree(target, onerror=lambda function, path, error: readonly(function, path, error[1]))


@contextlib.contextmanager
def runLock(root, timeout=60):
"""Serialize finalization and recovery SSH channels, including run-directory removal."""
root = root.resolve()
if root.parent.name != "runs" or root.parent.parent.name != ".webfront-local-ci":
raise ValueError("Refusing lock outside a local CI run")
# Outside the removable run: every channel must keep opening the same lock file.
locks = root.parent.parent / "locks"
locks.mkdir(exist_ok=True)
with open(locks / (root.name + ".lock"), "a+b") as lock:
if lock.tell() == 0:
lock.write(b"\0")
lock.flush()
deadline = time.monotonic() + timeout
while True:
try:
lock.seek(0)
if os.name == "nt":
import msvcrt
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except OSError:
if time.monotonic() >= deadline:
raise TimeoutError("Another Windows CI channel is still finalizing this run")
time.sleep(0.1)
try:
yield
finally:
lock.seek(0)
if os.name == "nt":
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(lock.fileno(), fcntl.LOCK_UN)


def finishLane(root, args):
"""Return secondary errors; always try both diagnostic paths, never delete a live checkout."""
errors = []
Expand Down
6 changes: 5 additions & 1 deletion cmake/local-ci/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,14 +243,15 @@ def runLane(args, matrix):
cleanWorkspace(workspace, image, args.lane)


def main():
def main(hostPlatform=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "lane", "inside", "stop", "cleanup", "artifacts", "session"])
parser.add_argument("--kit-sha256")
parser.add_argument("--lane")
parser.add_argument("--sha")
parser.add_argument("--jobs", type=int, default=4)
parser.add_argument("--timeout", type=int, default=3600)
parser.add_argument("--deadline", type=float)
parser.add_argument("--keep", action="store_true")
args = parser.parse_args()
signal.signal(signal.SIGTERM, lambda *_: STOP.set())
Expand All @@ -261,6 +262,9 @@ def main():
validateMatrix(matrix)
if args.lane and not any(row["id"] == args.lane for row in matrix["lanes"]):
raise ValueError("Unknown lane")
if (hostPlatform or sys.platform) == "darwin":
import macos_worker
return macos_worker.dispatch(args, matrix, ROOT)
if os.name == "nt":
import windows_worker
return windows_worker.dispatch(args, matrix, ROOT)
Expand Down
Loading
Loading