| 1 |
|
| 2 |
"""Fleet CI harness for rsync. |
| 3 |
|
| 4 |
Builds the committed HEAD of an rsync checkout on a fleet of remote machines |
| 5 |
(over ssh), runs the test suite under both transports (default stdio-pipe and |
| 6 |
--use-tcp) in parallel, and prints one report of only the UNEXPECTED results -- |
| 7 |
a fast local pre-flight for the GitHub CI matrix. |
| 8 |
|
| 9 |
Each target maps 1:1 to a .github/workflows/*.yml job: the per-target configure |
| 10 |
flags mirror that workflow, and the pipe-run RSYNC_EXPECT_SKIPPED list is PARSED |
| 11 |
from the workflow (not hardcoded). The --use-tcp run never sets an expected-skip |
| 12 |
list (matching the workflows), so only test FAILs matter there. |
| 13 |
|
| 14 |
The tcp pass runs only the tests that can reach the daemon transport, because it |
| 15 |
follows a full pipe pass over the very same build: --use-tcp is observable only |
| 16 |
through rsyncfns' start_test_daemon(), so a test that never calls it produces |
| 17 |
the same result twice. Pass --full-tcp to run the whole suite there anyway. |
| 18 |
|
| 19 |
A target may also list older "protocols" (e.g. [30, 29]) in the fleet config: |
| 20 |
each runs as an extra stdio-pipe pass with runtests --protocol=N (the fleet |
| 21 |
analogue of a workflow's check30/check29 steps), using that step's own parsed |
| 22 |
skip list, and shows up as a protoNN column in the report. |
| 23 |
|
| 24 |
The fleet -- which machines, how to reach and build each -- is read from a JSON |
| 25 |
config: ~/.fleettest.json if present, else fleettest.json next to this script, |
| 26 |
or --fleet PATH. Copy the bundled fleettest.json.example to either location (or |
| 27 |
symlink it) and edit for your own hosts; see testsuite/README.md and the |
| 28 |
comments in fleettest.json.example. |
| 29 |
|
| 30 |
Source = `git archive HEAD` of the rsync tree (the current directory, or --repo |
| 31 |
PATH) -- source-only, no .o/binaries are ever pushed. |
| 32 |
|
| 33 |
Every run uses its own randomly-named build directory on each target |
| 34 |
(<builddir>-<run_id>-<target>), so two or three fleettest runs can share the same |
| 35 |
fleet without interfering: each pushes, builds and tests in isolation. The run dir |
| 36 |
is removed when the run ends -- on success or failure, and best-effort on |
| 37 |
Ctrl-C/kill (pass --keep to retain it for inspection). |
| 38 |
|
| 39 |
--keep-on-fail is the cheaper half of --keep: only the targets that came back |
| 40 |
with something unexpected keep their run dir, and their full build/test output |
| 41 |
is also written locally under fleettest-logs/<run_id>/<target>/. A fleet run |
| 42 |
costs a full build on every machine, so re-running just to see why one test |
| 43 |
failed is expensive -- and a race test may not fail the same way twice. |
| 44 |
|
| 45 |
A run that is hard-killed |
| 46 |
(SIGKILL), or signalled mid-push, or whose ssh dies during cleanup can leave a |
| 47 |
stray <builddir>-<id>-<target> behind -- plus an orphaned path-flipper or test |
| 48 |
rsyncd on platforms without a parent-death backstop; sweep all of those |
| 49 |
(root-owned files included, via sudo -n) with `fleettest.py --cleanup` (optionally |
| 50 |
scoped with --targets). Run --cleanup between runs, not during one: its process |
| 51 |
kills are host-global and would also catch a concurrent run's flipper/daemon. |
| 52 |
Because each run starts from a fresh dir, every build is a full configure + build. |
| 53 |
|
| 54 |
Targets run concurrently, EXCEPT that targets naming the same machine run one |
| 55 |
after another. More than one target may point at a single host -- a variant that |
| 56 |
tests the same build on a different filesystem does -- and those cannot overlap: |
| 57 |
they would fight over the fixed ports the daemon tests claim, and over any other |
| 58 |
host-global state. |
| 59 |
|
| 60 |
PROVISIONING: each target must have the build toolchain its workflow's prepare |
| 61 |
step installs -- the target regenerates its own configure/proto.h/man pages, so |
| 62 |
it needs autoconf+automake, perl, a python3 markdown lib (cmarkgfm or commonmark) |
| 63 |
unless its flags pass --disable-md2man, and the dev libraries for whatever its |
| 64 |
configure flags enable (e.g. --with-rrsync needs openssl/xxhash/zstd/lz4 headers). |
| 65 |
A missing piece shows up as BUILD-FAIL with configure's own "you need X" hint. |
| 66 |
|
| 67 |
Per-target "privilege" (set in the JSON) controls how the suite runs: "root" |
| 68 |
(already root -- run directly), "sudo" (build unprivileged, run the suite via |
| 69 |
sudo to match a CI runner), or "user" (run directly as a plain non-root user). A |
| 70 |
target with "nonroot": true additionally reruns -- as the (non-root) ssh user, |
| 71 |
after the sudo runs -- every test that declares `fleet_nonroot = True` at module |
| 72 |
level, so privilege-sensitive tests opt in from the test file itself with no |
| 73 |
fleet-config edit when new ones are added. |
| 74 |
|
| 75 |
Usage (run from inside an rsync checkout, or pass --repo): |
| 76 |
python3 testsuite/fleettest.py # whole fleet, both transports |
| 77 |
python3 testsuite/fleettest.py --targets cygwin,freebsd |
| 78 |
python3 testsuite/fleettest.py --transport pipe |
| 79 |
python3 testsuite/fleettest.py --keep # keep run dirs for inspection |
| 80 |
python3 testsuite/fleettest.py --keep-on-fail # ...but only where it broke |
| 81 |
python3 testsuite/fleettest.py --timing # per-target AND per-test times |
| 82 |
python3 testsuite/fleettest.py --cleanup # sweep stray run dirs, exit |
| 83 |
python3 testsuite/fleettest.py --fleet my-fleet.json --list |
| 84 |
|
| 85 |
Exit 0 iff every selected (target x transport) cell is OK. |
| 86 |
""" |
| 87 |
|
| 88 |
from __future__ import annotations |
| 89 |
|
| 90 |
import argparse |
| 91 |
import atexit |
| 92 |
import concurrent.futures |
| 93 |
import dataclasses |
| 94 |
import fnmatch |
| 95 |
import json |
| 96 |
import os |
| 97 |
import shlex |
| 98 |
import re |
| 99 |
import secrets |
| 100 |
import signal |
| 101 |
import subprocess |
| 102 |
import sys |
| 103 |
import tempfile |
| 104 |
import threading |
| 105 |
import time |
| 106 |
from pathlib import Path |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
SKIP_CSV = "" |
| 113 |
|
| 114 |
BACKPORT_EXCLUDE: list[str] = [] |
| 115 |
XFAIL_GLOBS: list[str] = [] |
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
TIMING = False |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
FULL_TCP = False |
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
TRANSPORTS: list[str] = [] |
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
REPO = Path.cwd() |
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
TESTSUITE_REPO = REPO |
| 138 |
WORKFLOWS = TESTSUITE_REPO / ".github" / "workflows" |
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
HOME_CONFIG = Path.home() / ".fleettest.json" |
| 144 |
SCRIPT_CONFIG = Path(__file__).resolve().parent / "fleettest.json" |
| 145 |
DEFAULT_CONFIGS = [HOME_CONFIG, SCRIPT_CONFIG] |
| 146 |
EXAMPLE_CONFIG = SCRIPT_CONFIG.with_name(SCRIPT_CONFIG.name + ".example") |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
PUSH_EXCLUDES = [ |
| 156 |
".git", "config.h", "config.status", "config.log", "Makefile", "shconfig", |
| 157 |
"configure.sh", "config.h.in", "aclocal.m4", "proto.h", "git-version.h", |
| 158 |
"/rsync.1", "/rsync-ssl.1", "/rsyncd.conf.5", "/rrsync.1", |
| 159 |
"*.o", "*.exe", "__pycache__", "*.pyc", "/testtmp", |
| 160 |
"/rsync", "/tls", "/getgroups", "/getfsdev", "/trimslash", "/wildtest", |
| 161 |
"/testrun", "/simdtest", "/t_unsafe", "/t_chmod_secure", "/t_rename_secure", |
| 162 |
"/t_symlink_secure", "/t_secure_relpath", |
| 163 |
] |
| 164 |
|
| 165 |
|
| 166 |
@dataclasses.dataclass |
| 167 |
class Target: |
| 168 |
name: str |
| 169 |
ssh_host: str | None |
| 170 |
workflow: str |
| 171 |
configure_flags: list[str] |
| 172 |
make: str = "make" |
| 173 |
env_prefix: str = "" |
| 174 |
scratchbase: str = "" |
| 175 |
configure_pre: str = "" |
| 176 |
python: str = "python3" |
| 177 |
rsync_bin: str = "rsync" |
| 178 |
privilege: str = "root" |
| 179 |
pipe_jobs: int = 8 |
| 180 |
tcp_jobs: int = 8 |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
builddir: str = "rsync-citest" |
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
nonroot: bool = False |
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
protocols: list[int] = dataclasses.field(default_factory=list) |
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
max_retry: int = 0 |
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
expect_skip_extra: list[str] = dataclasses.field(default_factory=list) |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
expect_skip_omit: list[str] = dataclasses.field(default_factory=list) |
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
exclude: list[str] = dataclasses.field(default_factory=list) |
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
xfail: list[str] = dataclasses.field(default_factory=list) |
| 220 |
|
| 221 |
|
| 222 |
def load_fleet(path: Path) -> list[Target]: |
| 223 |
"""Load the fleet from a JSON file of the shape {"targets": [ {...}, ... ]}. |
| 224 |
|
| 225 |
Each entry's keys are Target fields; keys starting with "_" are treated as |
| 226 |
comments and ignored (both at top level and per target). Validation errors |
| 227 |
name the offending target so a typo is easy to find.""" |
| 228 |
try: |
| 229 |
data = json.loads(path.read_text()) |
| 230 |
except OSError as e: |
| 231 |
sys.exit(f"cannot read fleet config {path}: {e}") |
| 232 |
except json.JSONDecodeError as e: |
| 233 |
sys.exit(f"invalid JSON in {path}: {e}") |
| 234 |
if not isinstance(data, dict) or not isinstance(data.get("targets"), list): |
| 235 |
sys.exit(f'{path}: expected a JSON object with a "targets" array') |
| 236 |
fields = {f.name for f in dataclasses.fields(Target)} |
| 237 |
fleet: list[Target] = [] |
| 238 |
for i, entry in enumerate(data["targets"]): |
| 239 |
if not isinstance(entry, dict): |
| 240 |
sys.exit(f"{path}: targets[{i}] is not an object") |
| 241 |
entry = {k: v for k, v in entry.items() if not k.startswith("_")} |
| 242 |
who = entry.get("name", f"targets[{i}]") |
| 243 |
bad = set(entry) - fields |
| 244 |
if bad: |
| 245 |
sys.exit(f"{path}: target {who!r} has unknown key(s): " |
| 246 |
f"{', '.join(sorted(bad))}") |
| 247 |
try: |
| 248 |
fleet.append(Target(**entry)) |
| 249 |
except TypeError as e: |
| 250 |
sys.exit(f"{path}: target {who!r}: {e}") |
| 251 |
if not fleet: |
| 252 |
sys.exit(f"{path}: no targets defined") |
| 253 |
return fleet |
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
@dataclasses.dataclass |
| 262 |
class CmdResult: |
| 263 |
rc: int |
| 264 |
out: str |
| 265 |
timed_out: bool = False |
| 266 |
|
| 267 |
|
| 268 |
def run_on(target: Target, script: str, timeout: int) -> CmdResult: |
| 269 |
"""Run a /bin/sh script on the target. Remote via ssh, else local.""" |
| 270 |
if target.ssh_host: |
| 271 |
argv = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", |
| 272 |
target.ssh_host, script] |
| 273 |
else: |
| 274 |
argv = ["/bin/sh", "-c", script] |
| 275 |
try: |
| 276 |
p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout) |
| 277 |
return CmdResult(p.returncode, (p.stdout or "") + (p.stderr or "")) |
| 278 |
except subprocess.TimeoutExpired as e: |
| 279 |
out = (e.stdout or b"") + (e.stderr or b"") |
| 280 |
if isinstance(out, bytes): |
| 281 |
out = out.decode(errors="replace") |
| 282 |
return CmdResult(124, out, timed_out=True) |
| 283 |
except FileNotFoundError as e: |
| 284 |
return CmdResult(127, str(e)) |
| 285 |
|
| 286 |
|
| 287 |
def push_argv(target: Target, staging: str) -> list[str]: |
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
args = ["rsync", "-rlpgoD", "--checksum", "--delete"] |
| 295 |
for ex in PUSH_EXCLUDES: |
| 296 |
args.append(f"--exclude={ex}") |
| 297 |
dst = f"{target.ssh_host}:{target.builddir}/" if target.ssh_host \ |
| 298 |
else f"{target.builddir}/" |
| 299 |
args += [f"{staging}/", dst] |
| 300 |
return args |
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
def parse_workflow_skip(workflow: str, make_target: str = "check") -> str | None: |
| 308 |
"""Return the literal RSYNC_EXPECT_SKIPPED spec for the given `make <target>` |
| 309 |
step (check / check30 / check29), or None if that step leaves it unset. The |
| 310 |
protocol passes have their own check30/check29 lines (e.g. an xattr/ACL test |
| 311 |
that runs at proto 30 but skips at 29), so they must be parsed separately from |
| 312 |
the plain pipe `make check`. The trailing '? tolerates a `bash -c '... make |
| 313 |
check'` wrapper (e.g. Cygwin). |
| 314 |
|
| 315 |
The spec is passed through to the remote runtests.py verbatim; @FILE entries |
| 316 |
(testsuite/skiplist/*.txt) are expanded there, against the staged tree, so |
| 317 |
the list always matches the tests that shipped with it.""" |
| 318 |
path = WORKFLOWS / workflow |
| 319 |
try: |
| 320 |
text = path.read_text() |
| 321 |
except OSError: |
| 322 |
return None |
| 323 |
rx = re.compile(r"RSYNC_EXPECT_SKIPPED=(\S+)\s+make\s+" |
| 324 |
+ re.escape(make_target) + r"'?\s*$", re.M) |
| 325 |
m = rx.search(text) |
| 326 |
return m.group(1) if m else None |
| 327 |
|
| 328 |
|
| 329 |
def _expand_spec_names(spec: str) -> set[str]: |
| 330 |
"""The test names a workflow's RSYNC_EXPECT_SKIPPED spec resolves to, by |
| 331 |
reading its @FILE references out of the suite tree. Only used to decide |
| 332 |
which backport exclusions are actually IN the expected-skip set: runtests |
| 333 |
rejects a '-name' that removes a name nothing added, so a removal may only |
| 334 |
be emitted for a name the spec really contains.""" |
| 335 |
names: set[str] = set() |
| 336 |
for tok in spec.split(","): |
| 337 |
tok = tok.strip() |
| 338 |
if not tok or tok.startswith("-"): |
| 339 |
continue |
| 340 |
if tok.startswith("@"): |
| 341 |
f = TESTSUITE_REPO / tok[1:] |
| 342 |
try: |
| 343 |
for ln in f.read_text().splitlines(): |
| 344 |
ln = ln.split("#", 1)[0].strip() |
| 345 |
if ln: |
| 346 |
names.add(ln) |
| 347 |
except OSError: |
| 348 |
pass |
| 349 |
else: |
| 350 |
names.add(tok) |
| 351 |
return names |
| 352 |
|
| 353 |
|
| 354 |
def workflow_skip_for(t: "Target", make_target: str = "check") -> str | None: |
| 355 |
"""The target's expected-skip csv for a `make <target>` pass: its workflow's |
| 356 |
RSYNC_EXPECT_SKIPPED, plus any per-target expect_skip_extra (old-box-only |
| 357 |
skips the workflow omits) and minus any expect_skip_omit (tests the workflow |
| 358 |
expects to skip which this target can actually run). |
| 359 |
|
| 360 |
The workflow spec is now mostly @FILE references, which are expanded on the |
| 361 |
target rather than here, so an omission cannot be done by set subtraction: |
| 362 |
the name to drop lives inside a file we deliberately do not read. It is |
| 363 |
emitted as a '-name' token instead, which runtests.py applies after every |
| 364 |
addition. |
| 365 |
|
| 366 |
None (no oracle) when the workflow has no such step -- e.g. a protocols=[29] |
| 367 |
target whose workflow has no check29 line. The extras alone would be a |
| 368 |
near-empty expected set and so a guaranteed mismatch; a lane the workflow |
| 369 |
does not pin is simply not pinned here either.""" |
| 370 |
base = parse_workflow_skip(t.workflow, make_target) |
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
in_spec = _expand_spec_names(base) if (base and BACKPORT_EXCLUDE) else set() |
| 376 |
omit = set(t.expect_skip_omit) | (set(BACKPORT_EXCLUDE) & in_spec) |
| 377 |
if base is None or not (t.expect_skip_extra or omit): |
| 378 |
return base |
| 379 |
items = sorted(set(t.expect_skip_extra) | ({base} if base else set())) |
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
items += [f"-{n}" for n in sorted(omit)] |
| 385 |
return ",".join(items) |
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
_NONROOT_RE = re.compile(r"^[ \t]*fleet_nonroot[ \t]*=[ \t]*True\b", re.M) |
| 397 |
|
| 398 |
|
| 399 |
def discover_nonroot_tests(testsuite_dir: Path) -> list[str]: |
| 400 |
"""Return the names (without the _test.py suffix) of the tests under |
| 401 |
testsuite_dir that declare `fleet_nonroot = True`.""" |
| 402 |
names = [] |
| 403 |
for p in sorted(testsuite_dir.glob("*_test.py")): |
| 404 |
try: |
| 405 |
if _NONROOT_RE.search(p.read_text(errors="replace")): |
| 406 |
names.append(p.name[: -len("_test.py")]) |
| 407 |
except OSError: |
| 408 |
continue |
| 409 |
return names |
| 410 |
|
| 411 |
|
| 412 |
def _exclude_csv(t: "Target") -> str: |
| 413 |
"""RSYNC_EXCLUDE csv for a target: the global --skip globs plus this target's |
| 414 |
per-box `exclude` list (tests it never runs, e.g. the openbsd kernel-bug |
| 415 |
daemon+flipper races).""" |
| 416 |
parts = [p for p in ([SKIP_CSV] + list(t.exclude)) if p] |
| 417 |
return ",".join(parts) |
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
def build_script(t: Target) -> str: |
| 426 |
flags = " ".join(t.configure_flags) |
| 427 |
|
| 428 |
|
| 429 |
pre = f'{t.env_prefix}\n' if t.env_prefix else '' |
| 430 |
return ( |
| 431 |
f'cd {t.builddir} || exit 3\n' |
| 432 |
f'{pre}' |
| 433 |
f'if [ ! -f Makefile ]; then {t.configure_pre} ./configure {flags} || exit 4; fi\n' |
| 434 |
f'{t.make} -j{t.pipe_jobs} check-progs || exit 5\n' |
| 435 |
) |
| 436 |
|
| 437 |
|
| 438 |
def test_script(t: Target, transport: str, skip_csv: str | None, jobs: int, |
| 439 |
protocol: int | None = None, only: list[str] | None = None) -> str: |
| 440 |
rb = f'--rsync-bin="$PWD/{t.rsync_bin}"' |
| 441 |
tcp = " --use-tcp" if transport == "tcp" else "" |
| 442 |
|
| 443 |
proto = f" --protocol={protocol}" if protocol is not None else "" |
| 444 |
|
| 445 |
|
| 446 |
env = "PYTHONDONTWRITEBYTECODE=1 " |
| 447 |
if t.scratchbase: |
| 448 |
|
| 449 |
|
| 450 |
env += f"scratchbase={shlex.quote(t.scratchbase)} " |
| 451 |
excl = _exclude_csv(t) |
| 452 |
if excl: |
| 453 |
env += f"RSYNC_EXCLUDE={excl} " |
| 454 |
|
| 455 |
|
| 456 |
names = "" |
| 457 |
if only: |
| 458 |
names = " " + " ".join(only) |
| 459 |
elif skip_csv: |
| 460 |
env += f"RSYNC_EXPECT_SKIPPED={skip_csv} " |
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
timing = " --timing" if TIMING and not only else "" |
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
narrow_tcp = (transport == "tcp" and not FULL_TCP and not only |
| 473 |
and "pipe" in TRANSPORTS) |
| 474 |
only_daemon = " --daemon-tests-only" if narrow_tcp else "" |
| 475 |
runtests = (f'{t.python} runtests.py {rb}{tcp}{proto} ' |
| 476 |
f'-j {jobs}{timing}{only_daemon}{names}') |
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
pre = f'{t.env_prefix}; ' if t.env_prefix else '' |
| 481 |
if t.privilege == "sudo": |
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
path_pass = 'PATH="$PATH" ' if t.env_prefix else '' |
| 486 |
cmd = f"{pre}sudo -n env {path_pass}{env}{runtests}" |
| 487 |
else: |
| 488 |
cmd = pre + env + runtests |
| 489 |
return f'cd {t.builddir} || exit 3\n{cmd}\n' |
| 490 |
|
| 491 |
|
| 492 |
def nonroot_test_script(t: Target, names: list[str]) -> str: |
| 493 |
"""Run the given tests as the (non-root) ssh user -- the fleet analogue of a |
| 494 |
workflow's non-root check step. Explicit test names make runtests.py |
| 495 |
full_run False, so no RSYNC_EXPECT_SKIPPED is involved; only FAILs matter. |
| 496 |
The prior sudo pipe/tcp runs left testtmp root-owned, so clear it (via sudo) |
| 497 |
before the non-root run recreates it.""" |
| 498 |
pre = f'{t.env_prefix}; ' if t.env_prefix else '' |
| 499 |
_e = _exclude_csv(t) |
| 500 |
excl = f'RSYNC_EXCLUDE={_e} ' if _e else '' |
| 501 |
sb = f'scratchbase={shlex.quote(t.scratchbase)} ' if t.scratchbase else '' |
| 502 |
runtests = (f'PYTHONDONTWRITEBYTECODE=1 {sb}{excl}{t.python} runtests.py ' |
| 503 |
f'--rsync-bin="$PWD/{t.rsync_bin}" {" ".join(names)}') |
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
extra_rm = (f'sudo -n rm -rf {shlex.quote(t.scratchbase + "/testtmp")}\n' |
| 508 |
if t.scratchbase else '') |
| 509 |
return (f'cd {t.builddir} || exit 3\n' |
| 510 |
f'sudo -n rm -rf testtmp\n' |
| 511 |
f'{extra_rm}' |
| 512 |
f'{pre}{runtests}\n') |
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
RE_RESULT = re.compile(r"^(PASS|FAIL|ERROR|XFAIL|SKIP)\s+(\S+)", re.M) |
| 520 |
RE_COUNT = re.compile(r"^\s+(\d+)\s+(passed|failed|xfailed|skipped)\b", re.M) |
| 521 |
RE_SKIP_HDR = re.compile(r"^----- skipped results:", re.M) |
| 522 |
RE_SKIP_EXP = re.compile(r"^\s+expected:\s*(.*)$", re.M) |
| 523 |
RE_SKIP_GOT = re.compile(r"^\s+got:\s*(.*)$", re.M) |
| 524 |
|
| 525 |
|
| 526 |
def _csv_set(s: str) -> set[str]: |
| 527 |
return {x for x in s.strip().split(",") if x} |
| 528 |
|
| 529 |
|
| 530 |
@dataclasses.dataclass |
| 531 |
class TransportResult: |
| 532 |
transport: str |
| 533 |
exit_code: int |
| 534 |
timed_out: bool |
| 535 |
counts: dict[str, int] |
| 536 |
failed: list[str] |
| 537 |
skip_checked: bool |
| 538 |
skip_expected: set[str] |
| 539 |
skip_got: set[str] |
| 540 |
raw: str |
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
recovered: list[str] = dataclasses.field(default_factory=list) |
| 545 |
|
| 546 |
|
| 547 |
xfailed_req: list[str] = dataclasses.field(default_factory=list) |
| 548 |
|
| 549 |
@property |
| 550 |
def skip_mismatch(self) -> bool: |
| 551 |
return self.skip_checked and self.skip_expected != self.skip_got |
| 552 |
|
| 553 |
@property |
| 554 |
def ok(self) -> bool: |
| 555 |
return (not self.timed_out and self.exit_code == 0 |
| 556 |
and not self.failed and not self.skip_mismatch) |
| 557 |
|
| 558 |
|
| 559 |
def parse_transport(transport: str, r: CmdResult, skip_checked: bool, |
| 560 |
xfail_extra: list[str] = ()) -> TransportResult: |
| 561 |
counts = {"passed": 0, "failed": 0, "xfailed": 0, "skipped": 0} |
| 562 |
for m in RE_COUNT.finditer(r.out): |
| 563 |
counts[m.group(2)] = int(m.group(1)) |
| 564 |
failed = [m.group(2) for m in RE_RESULT.finditer(r.out) |
| 565 |
if m.group(1) in ("FAIL", "ERROR")] |
| 566 |
|
| 567 |
|
| 568 |
xfail_globs = [*XFAIL_GLOBS, *xfail_extra] |
| 569 |
xfailed_req = [f for f in failed |
| 570 |
if any(fnmatch.fnmatch(f, g) for g in xfail_globs)] |
| 571 |
failed = [f for f in failed if f not in xfailed_req] |
| 572 |
exp = got = set() |
| 573 |
if skip_checked and RE_SKIP_HDR.search(r.out): |
| 574 |
em = RE_SKIP_EXP.search(r.out) |
| 575 |
gm = RE_SKIP_GOT.search(r.out) |
| 576 |
exp = _csv_set(em.group(1)) if em else set() |
| 577 |
got = _csv_set(gm.group(1)) if gm else set() |
| 578 |
rc = r.rc |
| 579 |
|
| 580 |
|
| 581 |
if xfailed_req and not failed and rc != 0: |
| 582 |
rc = 0 |
| 583 |
return TransportResult(transport, rc, r.timed_out, counts, failed, |
| 584 |
skip_checked, exp, got, r.out, xfailed_req=xfailed_req) |
| 585 |
|
| 586 |
|
| 587 |
def retry_failed(t: Target, label: str, tr: TransportResult, rerun) -> None: |
| 588 |
"""Honour the target's max_retry budget: re-run each failed test on its own |
| 589 |
(serially) up to max_retry more times; drop any that pass and record them in |
| 590 |
tr.recovered. `rerun(names)` runs the given tests and returns a CmdResult. |
| 591 |
A no-op when max_retry is 0 or there were no failures.""" |
| 592 |
if not t.max_retry or not tr.failed: |
| 593 |
return |
| 594 |
remaining = list(tr.failed) |
| 595 |
for attempt in range(1, t.max_retry + 1): |
| 596 |
r = rerun(remaining) |
| 597 |
still = [m.group(2) for m in RE_RESULT.finditer(r.out) |
| 598 |
if m.group(1) in ("FAIL", "ERROR")] |
| 599 |
recovered = [n for n in remaining if n not in still] |
| 600 |
if recovered: |
| 601 |
tr.recovered.extend(recovered) |
| 602 |
log(f"[{t.name}] {label} retry {attempt}/{t.max_retry}: " |
| 603 |
f"recovered {','.join(recovered)}" |
| 604 |
+ (f"; still failing {','.join(still)}" if still else "")) |
| 605 |
remaining = [n for n in remaining if n in still] |
| 606 |
if not remaining: |
| 607 |
break |
| 608 |
tr.failed = remaining |
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
if not remaining and tr.recovered and tr.exit_code != 0: |
| 613 |
tr.exit_code = 0 |
| 614 |
|
| 615 |
|
| 616 |
@dataclasses.dataclass |
| 617 |
class TargetResult: |
| 618 |
target: str |
| 619 |
reachable: bool = True |
| 620 |
pushed: bool = True |
| 621 |
build_ok: bool = True |
| 622 |
error: str = "" |
| 623 |
build_log: str = "" |
| 624 |
transports: dict[str, TransportResult] = dataclasses.field(default_factory=dict) |
| 625 |
|
| 626 |
|
| 627 |
timings: dict[str, float] = dataclasses.field(default_factory=dict) |
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
|
| 634 |
_print_lock = threading.Lock() |
| 635 |
|
| 636 |
|
| 637 |
def log(msg: str) -> None: |
| 638 |
with _print_lock: |
| 639 |
print(msg, flush=True) |
| 640 |
|
| 641 |
|
| 642 |
def run_target(t: Target, args, staging: str) -> TargetResult: |
| 643 |
res = TargetResult(t.name) |
| 644 |
log(f"[{t.name}] start") |
| 645 |
started = time.monotonic() |
| 646 |
|
| 647 |
if t.ssh_host: |
| 648 |
ping = run_on(t, "echo ok", timeout=25) |
| 649 |
if ping.rc != 0: |
| 650 |
res.reachable = False |
| 651 |
res.error = f"ssh unreachable (rc={ping.rc}): {ping.out.strip()[:200]}" |
| 652 |
log(f"[{t.name}] UNREACHABLE") |
| 653 |
return res |
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
t0 = time.monotonic() |
| 658 |
push = subprocess.run(push_argv(t, staging), |
| 659 |
capture_output=True, text=True, timeout=600) |
| 660 |
res.timings["push"] = time.monotonic() - t0 |
| 661 |
if push.returncode != 0: |
| 662 |
res.pushed = False |
| 663 |
res.error = f"push failed (rc={push.returncode}): {push.stderr.strip()[:300]}" |
| 664 |
log(f"[{t.name}] PUSH-FAIL") |
| 665 |
return res |
| 666 |
|
| 667 |
t0 = time.monotonic() |
| 668 |
b = run_on(t, build_script(t), timeout=1200) |
| 669 |
res.timings["build"] = time.monotonic() - t0 |
| 670 |
res.build_ok = b.rc == 0 |
| 671 |
res.build_log = b.out |
| 672 |
if not res.build_ok: |
| 673 |
log(f"[{t.name}] BUILD-FAIL") |
| 674 |
return res |
| 675 |
|
| 676 |
for transport in args.transports: |
| 677 |
skip_csv = workflow_skip_for(t) if transport == "pipe" else None |
| 678 |
jobs = (args.jobs if args.jobs else |
| 679 |
(t.tcp_jobs if transport == "tcp" else t.pipe_jobs)) |
| 680 |
cmd = test_script(t, transport, skip_csv, jobs) |
| 681 |
t0 = time.monotonic() |
| 682 |
r = run_on(t, cmd, timeout=2400) |
| 683 |
res.timings[transport] = time.monotonic() - t0 |
| 684 |
tr = parse_transport(transport, r, skip_csv is not None, t.xfail) |
| 685 |
retry_failed(t, transport, tr, lambda names, tp=transport: run_on( |
| 686 |
t, test_script(t, tp, None, 1, only=names), timeout=1200)) |
| 687 |
res.transports[transport] = tr |
| 688 |
log(f"[{t.name}] {transport} done " |
| 689 |
f"({'ok' if tr.ok else 'ISSUE'})") |
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
if t.protocols and "pipe" in args.transports: |
| 697 |
jobs = args.jobs if args.jobs else t.pipe_jobs |
| 698 |
for proto in t.protocols: |
| 699 |
label = f"proto{proto}" |
| 700 |
skip_csv = workflow_skip_for(t, f"check{proto}") |
| 701 |
cmd = test_script(t, "pipe", skip_csv, jobs, protocol=proto) |
| 702 |
t0 = time.monotonic() |
| 703 |
r = run_on(t, cmd, timeout=2400) |
| 704 |
res.timings[label] = time.monotonic() - t0 |
| 705 |
tr = parse_transport(label, r, skip_csv is not None, t.xfail) |
| 706 |
retry_failed(t, label, tr, lambda names, pr=proto: run_on( |
| 707 |
t, test_script(t, "pipe", None, 1, protocol=pr, only=names), |
| 708 |
timeout=1200)) |
| 709 |
res.transports[label] = tr |
| 710 |
log(f"[{t.name}] {label} done " |
| 711 |
f"({'ok' if tr.ok else 'ISSUE'})") |
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
if t.nonroot and args.nonroot_tests: |
| 716 |
t0 = time.monotonic() |
| 717 |
r = run_on(t, nonroot_test_script(t, args.nonroot_tests), timeout=2400) |
| 718 |
res.timings["nonroot"] = time.monotonic() - t0 |
| 719 |
tr = parse_transport("nonroot", r, skip_checked=False, xfail_extra=t.xfail) |
| 720 |
retry_failed(t, "nonroot", tr, lambda names: run_on( |
| 721 |
t, nonroot_test_script(t, names), timeout=1200)) |
| 722 |
res.transports["nonroot"] = tr |
| 723 |
log(f"[{t.name}] nonroot done " |
| 724 |
f"({'ok' if tr.ok else 'ISSUE'})") |
| 725 |
res.timings["total"] = time.monotonic() - started |
| 726 |
return res |
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
def cell_status(res: TargetResult, transport: str) -> str: |
| 735 |
if not res.reachable: |
| 736 |
return "UNREACHABLE" |
| 737 |
if not res.pushed: |
| 738 |
return "PUSH-FAIL" |
| 739 |
if not res.build_ok: |
| 740 |
return "BUILD-FAIL" |
| 741 |
tr = res.transports.get(transport) |
| 742 |
if tr is None: |
| 743 |
return "-" |
| 744 |
if tr.timed_out: |
| 745 |
return "TIMEOUT" |
| 746 |
if tr.failed: |
| 747 |
return f"FAIL({len(tr.failed)})" |
| 748 |
if tr.skip_mismatch: |
| 749 |
return "SKIP-MISMATCH" |
| 750 |
if tr.exit_code != 0: |
| 751 |
return f"EXIT({tr.exit_code})" |
| 752 |
return "OK" |
| 753 |
|
| 754 |
|
| 755 |
def print_report(results: list[TargetResult], args, fleet: list[Target]) -> bool: |
| 756 |
by_name = {t.name: t for t in fleet} |
| 757 |
order = {t.name: i for i, t in enumerate(fleet)} |
| 758 |
results.sort(key=lambda r: order.get(r.target, 99)) |
| 759 |
|
| 760 |
|
| 761 |
|
| 762 |
transports = list(args.transports) |
| 763 |
protos = {k for r in results for k in r.transports if k.startswith("proto")} |
| 764 |
|
| 765 |
transports += sorted(protos, key=lambda c: int(c[len("proto"):]), reverse=True) |
| 766 |
if any("nonroot" in r.transports for r in results): |
| 767 |
transports.append("nonroot") |
| 768 |
ts = time.strftime("%Y-%m-%d %H:%M") |
| 769 |
print("\n" + "=" * 64) |
| 770 |
print(f"rsync fleet CI — branch {current_branch()} — {ts}") |
| 771 |
print(f"source: HEAD run: {args.run_id} " |
| 772 |
f"transports: {','.join(args.transports)}") |
| 773 |
print("(A target's pipe skip-set is only enforced when its workflow sets " |
| 774 |
"RSYNC_EXPECT_SKIPPED; otherwise only FAILs matter. The 'nonroot' " |
| 775 |
"column runs the privilege-sensitive tests as the unprivileged user; " |
| 776 |
"'-' = N/A.)") |
| 777 |
print("=" * 64) |
| 778 |
|
| 779 |
width = max(len(t) for t in order) + 2 |
| 780 |
header = "TARGET".ljust(width) + "".join(tr.upper().ljust(16) for tr in transports) |
| 781 |
print(header) |
| 782 |
all_ok = True |
| 783 |
for res in results: |
| 784 |
row = res.target.ljust(width) |
| 785 |
for transport in transports: |
| 786 |
st = cell_status(res, transport) |
| 787 |
if st not in ("OK", "-"): |
| 788 |
all_ok = False |
| 789 |
row += st.ljust(16) |
| 790 |
|
| 791 |
t = by_name.get(res.target) |
| 792 |
notes = [] |
| 793 |
if t is not None: |
| 794 |
if t.ssh_host is None: |
| 795 |
notes.append("(local)") |
| 796 |
if "tcp" in transports and t.tcp_jobs != t.pipe_jobs: |
| 797 |
notes.append(f"(tcp -j{t.tcp_jobs})") |
| 798 |
print(row + " ".join(notes)) |
| 799 |
|
| 800 |
|
| 801 |
details: list[str] = [] |
| 802 |
for res in results: |
| 803 |
if not res.reachable: |
| 804 |
details.append(f"{res.target} — UNREACHABLE: {res.error}") |
| 805 |
continue |
| 806 |
if not res.pushed: |
| 807 |
details.append(f"{res.target} — PUSH-FAIL: {res.error}") |
| 808 |
continue |
| 809 |
if not res.build_ok: |
| 810 |
tail = "\n ".join(res.build_log.strip().splitlines()[-20:]) |
| 811 |
details.append(f"{res.target} — BUILD-FAIL:\n {tail}") |
| 812 |
continue |
| 813 |
for transport in transports: |
| 814 |
tr = res.transports.get(transport) |
| 815 |
if tr is None or tr.ok: |
| 816 |
continue |
| 817 |
if tr.timed_out: |
| 818 |
details.append(f"{res.target} / {transport} — TIMEOUT") |
| 819 |
if tr.failed: |
| 820 |
details.append(f"{res.target} / {transport} — {len(tr.failed)} failed:\n " |
| 821 |
+ " ".join(tr.failed)) |
| 822 |
if tr.skip_mismatch: |
| 823 |
extra = tr.skip_got - tr.skip_expected |
| 824 |
missing = tr.skip_expected - tr.skip_got |
| 825 |
diff = [] |
| 826 |
if extra: |
| 827 |
diff.append(f"unexpected skips: {','.join(sorted(extra))}") |
| 828 |
if missing: |
| 829 |
diff.append(f"expected-but-ran: {','.join(sorted(missing))}") |
| 830 |
details.append(f"{res.target} / {transport} — skip mismatch (" |
| 831 |
+ "; ".join(diff) + ")\n" |
| 832 |
f" expected: {','.join(sorted(tr.skip_expected))}\n" |
| 833 |
f" got: {','.join(sorted(tr.skip_got))}") |
| 834 |
elif not tr.failed and not tr.timed_out and tr.exit_code != 0: |
| 835 |
details.append(f"{res.target} / {transport} — runtests exit {tr.exit_code}") |
| 836 |
|
| 837 |
|
| 838 |
|
| 839 |
statuses = [cell_status(res, transport) |
| 840 |
for res in results for transport in transports] |
| 841 |
cells = sum(1 for s in statuses if s != "-") |
| 842 |
ok_cells = sum(1 for s in statuses if s == "OK") |
| 843 |
print("=" * 64) |
| 844 |
if details: |
| 845 |
print("==== UNEXPECTED RESULTS ====") |
| 846 |
for d in details: |
| 847 |
print(d) |
| 848 |
print("=" * 64) |
| 849 |
|
| 850 |
|
| 851 |
|
| 852 |
recovered = [f"{res.target} / {transport}: {','.join(tr.recovered)}" |
| 853 |
for res in results for transport in transports |
| 854 |
if (tr := res.transports.get(transport)) and tr.recovered] |
| 855 |
if recovered: |
| 856 |
print("==== RECOVERED (flaky -- failed, then passed on retry) ====") |
| 857 |
for r in recovered: |
| 858 |
print(f" {r}") |
| 859 |
print("=" * 64) |
| 860 |
xfreq = [f"{res.target} / {transport}: {','.join(tr.xfailed_req)}" |
| 861 |
for res in results for transport in transports |
| 862 |
if (tr := res.transports.get(transport)) and tr.xfailed_req] |
| 863 |
if xfreq: |
| 864 |
print("==== XFAILED BY REQUEST (--xfail; failure tolerated, cell still OK) ====") |
| 865 |
for r in xfreq: |
| 866 |
print(f" {r}") |
| 867 |
print("=" * 64) |
| 868 |
print(f"{len(results)} targets x {len(transports)} transports = {cells} cells: " |
| 869 |
f"{ok_cells} OK, {cells - ok_cells} not OK") |
| 870 |
return all_ok |
| 871 |
|
| 872 |
|
| 873 |
def target_ok(res: TargetResult) -> bool: |
| 874 |
"""True if this target produced no unexpected result at all -- reachable, |
| 875 |
pushed, built, and every pass it ran was OK.""" |
| 876 |
if not (res.reachable and res.pushed and res.build_ok): |
| 877 |
return False |
| 878 |
return all(tr.ok for tr in res.transports.values()) |
| 879 |
|
| 880 |
|
| 881 |
def keep_on_fail(results: list[TargetResult], args, |
| 882 |
chosen: list[Target]) -> list[str]: |
| 883 |
"""--keep-on-fail: for every target that did NOT come back clean, save its |
| 884 |
full output locally and mark its remote run dir to survive the exit sweep. |
| 885 |
|
| 886 |
A fleet run is expensive (a full configure + build on ten machines), and the |
| 887 |
report only prints the names of failing tests -- so re-running was the only |
| 888 |
way to see WHY one failed, at the cost of another full run, on a race test |
| 889 |
that may not fail the same way twice. Saving the raw output at the moment of |
| 890 |
failure, and keeping the tree that produced it, makes that re-run |
| 891 |
unnecessary. Clean targets are untouched: they are still swept as usual. |
| 892 |
|
| 893 |
Returns human-readable lines describing what was kept, for the report.""" |
| 894 |
failed = [r for r in results if not target_ok(r)] |
| 895 |
if not failed: |
| 896 |
return [] |
| 897 |
root = Path(args.keep_on_fail).expanduser() / args.run_id |
| 898 |
notes: list[str] = [] |
| 899 |
for res in failed: |
| 900 |
_retain_targets.add(res.target) |
| 901 |
d = root / _dirsafe(res.target) |
| 902 |
try: |
| 903 |
d.mkdir(parents=True, exist_ok=True) |
| 904 |
if res.error: |
| 905 |
(d / "error.txt").write_text(res.error + "\n") |
| 906 |
if res.build_log: |
| 907 |
(d / "build.log").write_text(res.build_log) |
| 908 |
for name, tr in res.transports.items(): |
| 909 |
(d / f"{name}.log").write_text(tr.raw) |
| 910 |
saved = str(d) |
| 911 |
except OSError as e: |
| 912 |
saved = f"(could not write logs: {e})" |
| 913 |
notes.append(f"{res.target}: logs {saved}") |
| 914 |
|
| 915 |
|
| 916 |
if res.reachable and res.pushed: |
| 917 |
t = next((x for x in chosen if x.name == res.target), None) |
| 918 |
if t is not None: |
| 919 |
where = f"{t.ssh_host}:{t.builddir}" if t.ssh_host else t.builddir |
| 920 |
notes.append(f"{res.target}: run dir kept at {where}") |
| 921 |
return notes |
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
_TIMING_PHASES = ("push", "build", "pipe", "tcp", "nonroot") |
| 926 |
|
| 927 |
|
| 928 |
def _fmt_dur(s: float) -> str: |
| 929 |
if s < 60: |
| 930 |
return f"{s:.0f}s" |
| 931 |
m, sec = divmod(int(round(s)), 60) |
| 932 |
return f"{m}m{sec:02d}s" |
| 933 |
|
| 934 |
|
| 935 |
def print_timing(results: list[TargetResult]) -> None: |
| 936 |
"""Per-target wall-clock breakdown, slowest first. Targets run in parallel, |
| 937 |
so the whole run is gated by the slowest one -- that's the hold-up; the |
| 938 |
phase columns show whether it's push, build or the test passes.""" |
| 939 |
timed = [r for r in results if r.timings] |
| 940 |
if not timed: |
| 941 |
return |
| 942 |
|
| 943 |
protos = sorted({k for r in timed for k in r.timings if k.startswith("proto")}, |
| 944 |
key=lambda c: int(c[len("proto"):]), reverse=True) |
| 945 |
order = [p for p in _TIMING_PHASES if p != "nonroot"] + protos + ["nonroot"] |
| 946 |
phases = [p for p in order if any(p in r.timings for r in timed)] |
| 947 |
|
| 948 |
def total(r: TargetResult) -> float: |
| 949 |
|
| 950 |
return r.timings.get("total") or sum(r.timings.get(p, 0.0) for p in phases) |
| 951 |
|
| 952 |
timed.sort(key=total, reverse=True) |
| 953 |
width = max([len("TARGET")] + [len(r.target) for r in timed]) + 2 |
| 954 |
print("\n==== TIMING (slowest target first) ====") |
| 955 |
print("TARGET".ljust(width) + "TOTAL".ljust(9) |
| 956 |
+ "".join(p.upper().ljust(9) for p in phases)) |
| 957 |
for r in timed: |
| 958 |
row = r.target.ljust(width) + _fmt_dur(total(r)).ljust(9) |
| 959 |
for p in phases: |
| 960 |
v = r.timings.get(p) |
| 961 |
row += (_fmt_dur(v) if v is not None else "-").ljust(9) |
| 962 |
print(row) |
| 963 |
slow = timed[0] |
| 964 |
print(f"hold-up: {slow.target} at {_fmt_dur(total(slow))} gates the run " |
| 965 |
"(targets run in parallel)") |
| 966 |
|
| 967 |
|
| 968 |
def current_branch() -> str: |
| 969 |
try: |
| 970 |
return subprocess.run(["git", "-C", str(REPO), "rev-parse", |
| 971 |
"--abbrev-ref", "HEAD"], |
| 972 |
capture_output=True, text=True).stdout.strip() or "?" |
| 973 |
except Exception: |
| 974 |
return "?" |
| 975 |
|
| 976 |
|
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
|
| 982 |
|
| 983 |
_cleanup_targets: list[Target] = [] |
| 984 |
_cleanup_lock = threading.Lock() |
| 985 |
_cleanup_done = False |
| 986 |
|
| 987 |
|
| 988 |
_retain_targets: set[str] = set() |
| 989 |
|
| 990 |
|
| 991 |
def _dirsafe(name: str) -> str: |
| 992 |
"""A target name reduced to what is safe in a remote path we later rm -rf. |
| 993 |
Anything outside [A-Za-z0-9._-] becomes '_', so a name cannot introduce a |
| 994 |
path separator, a shell metacharacter, or a leading dash.""" |
| 995 |
return re.sub(r'[^A-Za-z0-9._-]', '_', name).lstrip('-') or 'target' |
| 996 |
|
| 997 |
|
| 998 |
def _unsafe_builddir(path: str) -> bool: |
| 999 |
"""True if `path` is too broad to feed to `rm -rf` -- empty, root, $HOME, or |
| 1000 |
an absolute path sitting directly under / (e.g. /tmp). A real run dir is |
| 1001 |
always nested deeper, so this rejects an obvious builddir misconfiguration |
| 1002 |
before any destructive command is built.""" |
| 1003 |
p = (path or "").rstrip("/") |
| 1004 |
if p in ("", "/", "~") or os.path.expanduser(p) == os.path.expanduser("~"): |
| 1005 |
return True |
| 1006 |
return os.path.isabs(p) and os.path.dirname(p) == "/" |
| 1007 |
|
| 1008 |
|
| 1009 |
def cleanup_run() -> None: |
| 1010 |
"""Best-effort `rm -rf` of this run's dir on every chosen target. Idempotent |
| 1011 |
(atexit + a signal handler may both call it). Each target removes only its |
| 1012 |
own <base>-<run_id> dir, so a concurrent run's dir is never touched. |
| 1013 |
|
| 1014 |
Targets listed in _retain_targets are left alone -- that is --keep-on-fail |
| 1015 |
holding a failed target's tree (build output plus the scratch trees the |
| 1016 |
failing tests left) for a post-mortem.""" |
| 1017 |
global _cleanup_done |
| 1018 |
with _cleanup_lock: |
| 1019 |
if _cleanup_done or not _cleanup_targets: |
| 1020 |
return |
| 1021 |
_cleanup_done = True |
| 1022 |
targets = [t for t in _cleanup_targets if t.name not in _retain_targets] |
| 1023 |
for t in targets: |
| 1024 |
if _unsafe_builddir(t.builddir): |
| 1025 |
continue |
| 1026 |
run_on(t, f'rm -rf -- {t.builddir}', timeout=60) |
| 1027 |
|
| 1028 |
|
| 1029 |
def _on_signal(signum, frame): |
| 1030 |
cleanup_run() |
| 1031 |
|
| 1032 |
|
| 1033 |
|
| 1034 |
os._exit(130 if signum == signal.SIGINT else 143) |
| 1035 |
|
| 1036 |
|
| 1037 |
|
| 1038 |
|
| 1039 |
|
| 1040 |
|
| 1041 |
|
| 1042 |
|
| 1043 |
|
| 1044 |
|
| 1045 |
|
| 1046 |
|
| 1047 |
_CLEANUP_SCRIPT = r'''fail=0 |
| 1048 |
# Cygwin signals are cooperative, so a process stuck in a Windows call ignores |
| 1049 |
# even SIGKILL and pkill cannot touch it -- exactly how an orphaned test rsyncd |
| 1050 |
# ends up squatting its port forever. Where taskkill exists, finish the job |
| 1051 |
# through Windows using the winpid (4th column of `ps -W`). |
| 1052 |
win_force() { |
| 1053 |
command -v taskkill >/dev/null 2>&1 || return 0 |
| 1054 |
command -v ps >/dev/null 2>&1 || return 0 |
| 1055 |
for p in $(pgrep -f "$1" 2>/dev/null); do |
| 1056 |
w=$(ps -W 2>/dev/null | awk -v x="$p" '$1==x {print $4}') |
| 1057 |
[ -n "$w" ] && taskkill /F /PID "$w" >/dev/null 2>&1 |
| 1058 |
done |
| 1059 |
} |
| 1060 |
sweep() { |
| 1061 |
command -v pgrep >/dev/null 2>&1 || return 0 |
| 1062 |
before=$(pgrep -f "$2" 2>/dev/null | wc -l | tr -d ' ') |
| 1063 |
[ "$before" -gt 0 ] 2>/dev/null || return 0 |
| 1064 |
pkill -f "$2" 2>/dev/null |
| 1065 |
sudo -n pkill -f "$2" 2>/dev/null |
| 1066 |
sleep 1 |
| 1067 |
if [ "$(pgrep -f "$2" 2>/dev/null | wc -l | tr -d ' ')" -gt 0 ] 2>/dev/null; then |
| 1068 |
win_force "$2" |
| 1069 |
sleep 1 |
| 1070 |
fi |
| 1071 |
after=$(pgrep -f "$2" 2>/dev/null | wc -l | tr -d ' ') |
| 1072 |
killed=$((before - after)) |
| 1073 |
[ "$killed" -gt 0 ] 2>/dev/null && echo "KILLED $killed stray $1(s)" |
| 1074 |
if [ "$after" -gt 0 ] 2>/dev/null; then |
| 1075 |
echo "SURVIVED $after stray $1(s)" |
| 1076 |
fail=1 |
| 1077 |
fi |
| 1078 |
} |
| 1079 |
sweep flipper 'r[e]name.*r[e]name.*r[e]name' |
| 1080 |
sweep daemon 'det[a]ch --address=127.0.0.1' |
| 1081 |
sweep client 'rsync://[l]ocalhost' |
| 1082 |
for d in @BASE@-*; do |
| 1083 |
[ -e "$d" ] || continue |
| 1084 |
if rm -rf -- "$d" 2>/dev/null || sudo -n rm -rf -- "$d" 2>/dev/null; then |
| 1085 |
echo "REMOVED $d" |
| 1086 |
else |
| 1087 |
echo "FAILED $d" |
| 1088 |
fail=1 |
| 1089 |
fi |
| 1090 |
done |
| 1091 |
exit $fail |
| 1092 |
''' |
| 1093 |
|
| 1094 |
|
| 1095 |
def cleanup_remnants(targets: list[Target]) -> int: |
| 1096 |
"""--cleanup mode: on each target, kill the stray processes a killed run can |
| 1097 |
leave behind, then remove every <base>-* run dir, reporting what went. |
| 1098 |
Returns a process exit code. Only suffixed run dirs are swept -- a bare |
| 1099 |
<base> is left alone. |
| 1100 |
|
| 1101 |
A run that is SIGKILLed (or whose ssh drops) can strand two kinds of process |
| 1102 |
on platforms without a parent-death backstop: the TOCTOU path-flipper (a |
| 1103 |
busy `python -c` rename loop that pins a CPU) and an orphaned test rsyncd |
| 1104 |
(`--no-detach --address=127.0.0.1`, which then squats its fixed port -- the |
| 1105 |
very wedge claim_ports()' bind-probe now reports). Both are killed best |
| 1106 |
effort (sudo -n retry for root-owned ones); a kill is verified by re-counting |
| 1107 |
afterwards, and a process that survives is reported and fails the run. |
| 1108 |
|
| 1109 |
CAVEAT: the kill patterns are host-global, not scoped to a particular run, so |
| 1110 |
--cleanup assumes no *other* fleettest run is active on the target -- it |
| 1111 |
would also kill a concurrent run's flipper/daemon (and any manual `rsync |
| 1112 |
--daemon --no-detach --address=127.0.0.1`). Run it between runs, not during |
| 1113 |
one. Run dirs whose contents a root test owns are removed via a `sudo -n rm` |
| 1114 |
fallback; only a dir that survives even that is a failure.""" |
| 1115 |
rc = 0 |
| 1116 |
for t in targets: |
| 1117 |
base = t.builddir |
| 1118 |
if _unsafe_builddir(base): |
| 1119 |
log(f"[{t.name}] skipped (unsafe builddir {base!r})") |
| 1120 |
continue |
| 1121 |
|
| 1122 |
|
| 1123 |
r = run_on(t, _CLEANUP_SCRIPT.replace("@BASE@", base), timeout=120) |
| 1124 |
lines = r.out.splitlines() |
| 1125 |
removed = [ln.split(" ", 1)[1] for ln in lines if ln.startswith("REMOVED ")] |
| 1126 |
failed = [ln.split(" ", 1)[1] for ln in lines if ln.startswith("FAILED ")] |
| 1127 |
killed = [ln.replace("KILLED ", "killed ", 1) |
| 1128 |
for ln in lines if ln.startswith("KILLED ")] |
| 1129 |
survived = [ln.replace("SURVIVED ", "still alive: ", 1) |
| 1130 |
for ln in lines if ln.startswith("SURVIVED ")] |
| 1131 |
msgs = killed[:] |
| 1132 |
if removed: |
| 1133 |
msgs.append("removed: " + " ".join(removed)) |
| 1134 |
if survived: |
| 1135 |
rc = 1 |
| 1136 |
msgs += survived |
| 1137 |
if failed: |
| 1138 |
rc = 1 |
| 1139 |
msgs.append("could not remove (even with sudo): " + " ".join(failed)) |
| 1140 |
if r.rc not in (0, 1): |
| 1141 |
rc = 1 |
| 1142 |
msgs.append(f"cleanup error rc={r.rc}: {r.out.strip()[:160]}") |
| 1143 |
log(f"[{t.name}] " + ("; ".join(msgs) if msgs else "nothing to remove")) |
| 1144 |
return rc |
| 1145 |
|
| 1146 |
|
| 1147 |
|
| 1148 |
|
| 1149 |
|
| 1150 |
|
| 1151 |
|
| 1152 |
def main() -> int: |
| 1153 |
ap = argparse.ArgumentParser(description="Fleet CI harness for rsync.") |
| 1154 |
ap.add_argument("--targets", help="comma-separated subset (default: all)") |
| 1155 |
ap.add_argument("--transport", choices=["pipe", "tcp", "both"], default="both") |
| 1156 |
ap.add_argument("--keep", action="store_true", |
| 1157 |
help="keep each run's build dir (default: remove it at exit)") |
| 1158 |
ap.add_argument("--keep-on-fail", nargs="?", const="fleettest-logs", |
| 1159 |
metavar="DIR", |
| 1160 |
help="for targets that came back with anything unexpected, " |
| 1161 |
"save the full build/test output under DIR/<run-id>/<target>/ " |
| 1162 |
"and keep that target's remote run dir (clean targets are " |
| 1163 |
"swept as usual). Makes a failure inspectable without " |
| 1164 |
"repeating the run. DIR defaults to ./fleettest-logs") |
| 1165 |
ap.add_argument("--cleanup", action="store_true", |
| 1166 |
help="kill stray flippers/test daemons and remove stray " |
| 1167 |
"<builddir>-* run dirs (root-owned via sudo -n) on the " |
| 1168 |
"targets, then exit; run between runs, not during one " |
| 1169 |
"(kills are host-global)") |
| 1170 |
ap.add_argument("--jobs", type=int, help="override -j for both transports") |
| 1171 |
ap.add_argument("--full-tcp", action="store_true", |
| 1172 |
help="run the whole suite in the tcp pass. By default that " |
| 1173 |
"pass runs only the tests that can reach the daemon " |
| 1174 |
"transport, since the rest just repeat the pipe pass over " |
| 1175 |
"the same build") |
| 1176 |
ap.add_argument("--timing", action="store_true", |
| 1177 |
help="report per-target wall-clock (push/build/test) to find " |
| 1178 |
"the slowest target") |
| 1179 |
ap.add_argument("--repo", help="rsync source tree to build (default: cwd)") |
| 1180 |
ap.add_argument("--testsuite-repo", |
| 1181 |
help="rsync tree to take runtests.py + testsuite/ from " |
| 1182 |
"(default: --repo). Build one tree and run another's test " |
| 1183 |
"suite against it, e.g. --repo ../rsync-v3.4 --testsuite-repo .") |
| 1184 |
ap.add_argument("--fleet", help="fleet config JSON (default: ~/.fleettest.json, " |
| 1185 |
"else fleettest.json next to this script)") |
| 1186 |
ap.add_argument("--skip", metavar="LIST", |
| 1187 |
help="comma-separated test-name globs to exclude from every " |
| 1188 |
"run on every target (passed to runtests as RSYNC_EXCLUDE; " |
| 1189 |
"the tests are not run). E.g. --skip 'chmod-option,prealloc*'") |
| 1190 |
ap.add_argument("--xfail", metavar="LIST", |
| 1191 |
help="comma-separated test-name globs whose FAILURE is " |
| 1192 |
"tolerated: a matching fail is listed but does not make a " |
| 1193 |
"cell 'not OK'. For known stable-gap tests you still want to " |
| 1194 |
"run. E.g. --xfail 'chmod-option,preallocate,crtimes'") |
| 1195 |
ap.add_argument("--list", action="store_true", help="list targets and exit") |
| 1196 |
args = ap.parse_args() |
| 1197 |
|
| 1198 |
global SKIP_CSV, XFAIL_GLOBS, TIMING, FULL_TCP, BACKPORT_EXCLUDE |
| 1199 |
SKIP_CSV = ",".join(s.strip() for s in (args.skip or "").split(",") if s.strip()) |
| 1200 |
XFAIL_GLOBS = [s.strip() for s in (args.xfail or "").split(",") if s.strip()] |
| 1201 |
TIMING = args.timing |
| 1202 |
FULL_TCP = args.full_tcp |
| 1203 |
|
| 1204 |
global REPO, WORKFLOWS, TESTSUITE_REPO |
| 1205 |
REPO = Path(args.repo).resolve() if args.repo else Path.cwd() |
| 1206 |
TESTSUITE_REPO = Path(args.testsuite_repo).resolve() if args.testsuite_repo else REPO |
| 1207 |
|
| 1208 |
|
| 1209 |
WORKFLOWS = TESTSUITE_REPO / ".github" / "workflows" |
| 1210 |
|
| 1211 |
|
| 1212 |
|
| 1213 |
|
| 1214 |
|
| 1215 |
|
| 1216 |
|
| 1217 |
|
| 1218 |
|
| 1219 |
bp = REPO / "testsuite" / "skiplist" / "backport.txt" |
| 1220 |
if bp.is_file(): |
| 1221 |
names = [ln.split("#", 1)[0].strip() for ln in bp.read_text().splitlines()] |
| 1222 |
names = [x for x in names if x] |
| 1223 |
if names: |
| 1224 |
SKIP_CSV = ",".join(x for x in ([SKIP_CSV] + names) if x) |
| 1225 |
BACKPORT_EXCLUDE[:] = names |
| 1226 |
print(f"[backport] excluding {len(names)} test(s) declared in " |
| 1227 |
f"{bp.relative_to(REPO)}") |
| 1228 |
if not args.cleanup: |
| 1229 |
|
| 1230 |
|
| 1231 |
|
| 1232 |
|
| 1233 |
if not (TESTSUITE_REPO / "runtests.py").is_file(): |
| 1234 |
print(f"{TESTSUITE_REPO} has no runtests.py; run from inside a " |
| 1235 |
f"checkout or pass --testsuite-repo a tree with the Python " |
| 1236 |
f"test suite", file=sys.stderr) |
| 1237 |
return 2 |
| 1238 |
if not (REPO / "rsync.h").is_file(): |
| 1239 |
print(f"{REPO} is not an rsync source tree (no rsync.h); " |
| 1240 |
f"run from inside a checkout or pass --repo", file=sys.stderr) |
| 1241 |
return 2 |
| 1242 |
|
| 1243 |
if args.fleet: |
| 1244 |
config_path = Path(args.fleet).resolve() |
| 1245 |
if not config_path.exists(): |
| 1246 |
print(f"no fleet config at {config_path}", file=sys.stderr) |
| 1247 |
return 2 |
| 1248 |
else: |
| 1249 |
config_path = next((p for p in DEFAULT_CONFIGS if p.exists()), None) |
| 1250 |
if config_path is None: |
| 1251 |
tried = " or ".join(str(p) for p in DEFAULT_CONFIGS) |
| 1252 |
print(f"no fleet config found (looked for {tried})\n" |
| 1253 |
f"copy {EXAMPLE_CONFIG} to {SCRIPT_CONFIG} or {HOME_CONFIG} " |
| 1254 |
f"(or pass --fleet PATH)", file=sys.stderr) |
| 1255 |
return 2 |
| 1256 |
fleet = load_fleet(config_path) |
| 1257 |
|
| 1258 |
if args.list: |
| 1259 |
for t in fleet: |
| 1260 |
host = t.ssh_host or "(local)" |
| 1261 |
skip = parse_workflow_skip(t.workflow) |
| 1262 |
proto = (",".join(f"proto{p}" for p in t.protocols) |
| 1263 |
if t.protocols else "none") |
| 1264 |
print(f"{t.name:12} {host:18} {t.make:6} " |
| 1265 |
f"pipe-skip={'set' if skip else 'unset'} protocols={proto}") |
| 1266 |
return 0 |
| 1267 |
|
| 1268 |
chosen = fleet |
| 1269 |
if args.targets: |
| 1270 |
want = [s.strip() for s in args.targets.split(",") if s.strip()] |
| 1271 |
by_name = {t.name: t for t in fleet} |
| 1272 |
bad = [w for w in want if w not in by_name] |
| 1273 |
if bad: |
| 1274 |
print(f"unknown target(s): {', '.join(bad)}", file=sys.stderr) |
| 1275 |
print(f"known: {', '.join(by_name)}", file=sys.stderr) |
| 1276 |
return 2 |
| 1277 |
chosen = [by_name[w] for w in want] |
| 1278 |
|
| 1279 |
if args.cleanup: |
| 1280 |
|
| 1281 |
|
| 1282 |
|
| 1283 |
|
| 1284 |
return cleanup_remnants(chosen) |
| 1285 |
|
| 1286 |
args.transports = ["pipe", "tcp"] if args.transport == "both" else [args.transport] |
| 1287 |
global TRANSPORTS |
| 1288 |
TRANSPORTS = args.transports |
| 1289 |
if "tcp" in args.transports and "pipe" not in args.transports and not FULL_TCP: |
| 1290 |
log("note: --transport tcp is the only pass, so it runs the WHOLE suite " |
| 1291 |
"(the daemon-only narrowing needs a pipe pass to cover the rest)") |
| 1292 |
|
| 1293 |
|
| 1294 |
|
| 1295 |
|
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
args.run_id = secrets.token_hex(3) |
| 1300 |
for t in chosen: |
| 1301 |
t.builddir = f"{t.builddir}-{args.run_id}-{_dirsafe(t.name)}" |
| 1302 |
log(f"run {args.run_id}: build dir <target>:{chosen[0].builddir.rsplit('-', 1)[0]}-<target> " |
| 1303 |
f"(removed at exit; --keep to retain)") |
| 1304 |
|
| 1305 |
|
| 1306 |
|
| 1307 |
|
| 1308 |
if not args.keep: |
| 1309 |
_cleanup_targets.extend(chosen) |
| 1310 |
atexit.register(cleanup_run) |
| 1311 |
signal.signal(signal.SIGINT, _on_signal) |
| 1312 |
signal.signal(signal.SIGTERM, _on_signal) |
| 1313 |
|
| 1314 |
|
| 1315 |
|
| 1316 |
|
| 1317 |
|
| 1318 |
|
| 1319 |
|
| 1320 |
|
| 1321 |
staging = tempfile.mkdtemp(prefix="rsync-fleettest-stage.") |
| 1322 |
try: |
| 1323 |
ar = subprocess.run(f"git -C {REPO} archive HEAD | tar -x -C {staging}", |
| 1324 |
shell=True, capture_output=True, text=True) |
| 1325 |
if ar.returncode != 0: |
| 1326 |
print(f"git archive failed: {ar.stderr}", file=sys.stderr) |
| 1327 |
return 2 |
| 1328 |
|
| 1329 |
|
| 1330 |
|
| 1331 |
|
| 1332 |
|
| 1333 |
if TESTSUITE_REPO != REPO: |
| 1334 |
ov = subprocess.run( |
| 1335 |
f"git -C {TESTSUITE_REPO} archive HEAD -- runtests.py testsuite " |
| 1336 |
f"| tar -x -C {staging}", |
| 1337 |
shell=True, capture_output=True, text=True) |
| 1338 |
if ov.returncode != 0: |
| 1339 |
print(f"testsuite overlay archive failed: {ov.stderr}", file=sys.stderr) |
| 1340 |
return 2 |
| 1341 |
|
| 1342 |
|
| 1343 |
args.nonroot_tests = discover_nonroot_tests(Path(staging) / "testsuite") |
| 1344 |
|
| 1345 |
|
| 1346 |
|
| 1347 |
|
| 1348 |
|
| 1349 |
|
| 1350 |
|
| 1351 |
groups: dict[str, list[Target]] = {} |
| 1352 |
for t in chosen: |
| 1353 |
groups.setdefault(t.ssh_host or "<local>", []).append(t) |
| 1354 |
for host, ts in groups.items(): |
| 1355 |
if len(ts) > 1: |
| 1356 |
log(f"[{host}] {len(ts)} targets on one machine, run in " |
| 1357 |
f"sequence: {', '.join(x.name for x in ts)}") |
| 1358 |
|
| 1359 |
def run_group(ts: 'list[Target]') -> 'list[TargetResult]': |
| 1360 |
out = [] |
| 1361 |
for t in ts: |
| 1362 |
try: |
| 1363 |
out.append(run_target(t, args, staging)) |
| 1364 |
except Exception as e: |
| 1365 |
r = TargetResult(t.name) |
| 1366 |
r.reachable = False |
| 1367 |
r.error = f"harness exception: {e!r}" |
| 1368 |
out.append(r) |
| 1369 |
return out |
| 1370 |
|
| 1371 |
results: list[TargetResult] = [] |
| 1372 |
with concurrent.futures.ThreadPoolExecutor(max_workers=len(groups)) as ex: |
| 1373 |
futs = {ex.submit(run_group, ts): ts for ts in groups.values()} |
| 1374 |
for fut in concurrent.futures.as_completed(futs): |
| 1375 |
ts = futs[fut] |
| 1376 |
try: |
| 1377 |
results.extend(fut.result()) |
| 1378 |
except Exception as e: |
| 1379 |
for t in ts: |
| 1380 |
r = TargetResult(t.name) |
| 1381 |
r.reachable = False |
| 1382 |
r.error = f"harness exception: {e!r}" |
| 1383 |
results.append(r) |
| 1384 |
finally: |
| 1385 |
subprocess.run(["rm", "-rf", staging]) |
| 1386 |
|
| 1387 |
|
| 1388 |
|
| 1389 |
kept = keep_on_fail(results, args, chosen) if args.keep_on_fail else [] |
| 1390 |
|
| 1391 |
all_ok = print_report(results, args, fleet) |
| 1392 |
if kept: |
| 1393 |
print("==== KEPT FOR POST-MORTEM (--keep-on-fail) ====") |
| 1394 |
for k in kept: |
| 1395 |
print(f" {k}") |
| 1396 |
print("=" * 64) |
| 1397 |
if args.timing: |
| 1398 |
print_timing(results) |
| 1399 |
return 0 if all_ok else 1 |
| 1400 |
|
| 1401 |
|
| 1402 |
if __name__ == "__main__": |
| 1403 |
sys.exit(main()) |