Debian Codegraph @

testsuite/fleettest.py

raw symbols SCIP
1 #!/usr/bin/env python3
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 # Set from --skip / --xfail in main(). SKIP_CSV is passed to runtests as
109 # RSYNC_EXCLUDE (tests dropped before running); XFAIL_GLOBS are tolerated
110 # failures (a matching FAIL does not make a cell "not OK"). Both are
111 # comma-separated test-name globs (fnmatch), applied across every target.
112 SKIP_CSV = ""
113 # Names from a backport tree's testsuite/skiplist/backport.txt (see main()).
114 BACKPORT_EXCLUDE: list[str] = []
115 XFAIL_GLOBS: list[str] = []
116
117 # Set from --timing in main(). Also asks each target's runtests.py for its own
118 # per-test wall-clock table, so a slow cell can be attributed to actual tests.
119 TIMING = False
120
121 # Set from --full-tcp in main(): run the WHOLE suite in the tcp pass rather than
122 # only the tests that can observe the transport. The narrow pass is the default
123 # because the tcp run follows a full pipe run over the very same build.
124 FULL_TCP = False
125
126 # The transports this run will execute (from --transport), needed in test_script
127 # to tell "tcp after a pipe pass" from "tcp is the only pass".
128 TRANSPORTS: list[str] = []
129
130 # Set from --repo in main() (default: cwd). The harness builds whatever rsync
131 # source tree these point at, so it must be run from inside an rsync checkout
132 # or given --repo PATH.
133 REPO = Path.cwd()
134 # Source tree providing the test suite (runtests.py + testsuite/). Defaults to
135 # REPO; --testsuite-repo decouples it so one tree is built and another's suite is
136 # run against the result.
137 TESTSUITE_REPO = REPO
138 WORKFLOWS = TESTSUITE_REPO / ".github" / "workflows"
139
140 # Fleet config (overridable with --fleet): ~/.fleettest.json is tried first, then
141 # fleettest.json next to this script. The example template sits next to the
142 # script too.
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 # The pushed tree is source-only (git archive). Each target regenerates its own
149 # build files, so --delete must NOT prune them: we exclude everything `make`
150 # produces (autotools output, proto.h, man pages, config.h/Makefile, *.o, the
151 # binaries) plus test artifacts a prior sudo run left root-owned (testtmp,
152 # __pycache__, *.pyc -- which a non-root --delete can't unlink). Excluded paths
153 # are protected from --delete, so each target keeps its native build state for
154 # incremental rebuilds. `configure` itself is committed, so it is NOT excluded.
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 # null in JSON => run locally
170 workflow: str # filename under .github/workflows
171 configure_flags: list[str]
172 make: str = "make" # e.g. "gmake" on the BSDs/Solaris
173 env_prefix: str = "" # exported before configure AND make (e.g. PATH)
174 scratchbase: str = "" # run the tests' scratch trees here (e.g. another filesystem)
175 configure_pre: str = "" # shell run before ./configure (env exports, brew)
176 python: str = "python3"
177 rsync_bin: str = "rsync" # "rsync.exe" on Cygwin
178 privilege: str = "root" # "root" (already root) | "sudo" | "user" (plain, no sudo)
179 pipe_jobs: int = 8
180 tcp_jobs: int = 8
181 # Base build-dir name (relative to remote $HOME; absolute for local). A
182 # per-run random suffix is appended (-> <builddir>-<run_id>) so concurrent
183 # fleettest runs don't share a tree; --cleanup sweeps leftover <builddir>-*.
184 builddir: str = "rsync-citest"
185 # When true, after the sudo runs, additionally run -- as the (non-root) ssh
186 # user -- every test that declares `fleet_nonroot = True` (see
187 # discover_nonroot_tests). Mirrors a workflow's non-root check step.
188 nonroot: bool = False
189 # Older protocol versions to additionally exercise, each as a separate
190 # stdio-pipe pass with runtests --protocol=N (the fleet analogue of a
191 # workflow's check30/check29 steps). e.g. [30, 29]. Empty => proto pass off.
192 protocols: list[int] = dataclasses.field(default_factory=list)
193 # Per-target retry budget for FLAKY tests: after a run, each failed test is
194 # re-run on its own up to max_retry more times, and any that then pass are
195 # dropped from the failure list (and reported as "recovered", never hidden).
196 # Use on a slow/loaded box where concurrency-sensitive tests occasionally
197 # flake, instead of dropping the whole target to a lower -j. 0 => no retry.
198 max_retry: int = 0
199 # Test names this specific box skips beyond what its workflow lists -- e.g. an
200 # old-kernel fleet box (no openat2/RESOLVE_BENEATH) skips the RB-conditional
201 # symlink-race tests that the workflow's newer CI runner actually runs. Merged
202 # into RSYNC_EXPECT_SKIPPED for each pipe/protocol pass the workflow itself
203 # pins -- a pass with no matching workflow step stays unpinned (see
204 # workflow_skip_for).
205 expect_skip_extra: list[str] = dataclasses.field(default_factory=list)
206 # ...and the mirror: entries the workflow expects to skip which this target
207 # actually RUNS (a relocated scratch can satisfy a condition the
208 # workflow's host cannot, e.g. a cross-device copy).
209 expect_skip_omit: list[str] = dataclasses.field(default_factory=list)
210 # Test-name globs this box never runs (passed to runtests as RSYNC_EXCLUDE),
211 # for tests unreliable on this platform for a non-rsync reason -- e.g. the
212 # daemon+flipper symlink-race tests on openbsd, which the platform's kernel
213 # connect()-under-rename-load bug hangs (see dev-notes). Merged with --skip.
214 exclude: list[str] = dataclasses.field(default_factory=list)
215 # Test-name globs whose failure is tolerated on THIS box (merged with the
216 # global --xfail), for a known platform/version-specific failure that should
217 # not fail the cell -- e.g. crtimes on macOS for an older binary. The test
218 # still runs; if it passes, the entry is simply a no-op.
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 # command execution (ssh for remote, local shell when ssh_host is null)
258 # ---------------------------------------------------------------------------
259
260
261 @dataclasses.dataclass
262 class CmdResult:
263 rc: int
264 out: str # combined stdout + stderr
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 # -rlpgoD = -a without -t: do NOT preserve mtimes. The host clock can be
289 # hours AHEAD of a target, so preserved (commit-time) mtimes land "in the
290 # future" there and rsync's `Makefile: Makefile.in config.status` rule
291 # triggers a config.status/autoconf regeneration storm. Letting files take
292 # the target's own clock avoids that. --checksum keeps the transfer
293 # incremental despite the unstable mtimes (decide by content, not size+time).
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 # workflow skip-list parsing
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 # A backport-excluded test never runs, so it cannot skip either: drop it
372 # from the expected-skip set as well, or the oracle waits for a skip that
373 # can no longer happen. Only for names the spec actually contains --
374 # runtests rejects a '-name' that removes a name nothing added.
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 # A backport-excluded test cannot skip, because it never runs -- so it must
381 # also come OUT of the expected-skip set, or the oracle waits for a skip
382 # that can no longer happen. The name usually lives inside an @FILE, so it
383 # is dropped with a '-name' token that runtests applies after expansion.
384 items += [f"-{n}" for n in sorted(omit)]
385 return ",".join(items)
386
387
388 # ---------------------------------------------------------------------------
389 # non-root test discovery
390 # ---------------------------------------------------------------------------
391
392 # A test opts into the fleet's extra non-root pass by setting a module-level
393 # `fleet_nonroot = True`. We read it with a text scan rather than importing the
394 # module (test files execute their body on import), so a new privilege-sensitive
395 # test joins the pass just by carrying the marker -- no fleet-config edit needed.
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 # remote script builders
422 # ---------------------------------------------------------------------------
423
424
425 def build_script(t: Target) -> str:
426 flags = " ".join(t.configure_flags)
427 # configure only when not yet configured (keeps incremental builds fast);
428 # --clean wipes the builddir beforehand so Makefile is absent -> reconfigure.
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 # protocol forces an older wire version (mirrors `make check30`/`check29`).
443 proto = f" --protocol={protocol}" if protocol is not None else ""
444 # PYTHONDONTWRITEBYTECODE: don't drop root-owned __pycache__/*.pyc into the
445 # tree (a sudo run would, breaking the next non-root push --delete).
446 env = "PYTHONDONTWRITEBYTECODE=1 "
447 if t.scratchbase:
448 # Must travel in `env`, not env_prefix: the sudo branch below runs
449 # `sudo -n env ...`, which drops whatever the outer shell exported.
450 env += f"scratchbase={shlex.quote(t.scratchbase)} "
451 excl = _exclude_csv(t)
452 if excl:
453 env += f"RSYNC_EXCLUDE={excl} "
454 # Named tests (a max_retry re-run) make runtests full_run False, so the
455 # expected-skip list does not apply -- only the named tests' pass/fail matter.
456 names = ""
457 if only:
458 names = " " + " ".join(only)
459 elif skip_csv:
460 env += f"RSYNC_EXPECT_SKIPPED={skip_csv} "
461 # --timing makes the remote runtests print its own per-test wall-clock table,
462 # which lands in the captured output: that is where a "this target is slow"
463 # cell turns into "these tests are slow on this target".
464 timing = " --timing" if TIMING and not only else ""
465 # --use-tcp is observable only through start_test_daemon(), so when the tcp
466 # pass follows a full pipe pass over the same build, the tests that never
467 # reach it would just produce the same result twice: narrow it to the ones
468 # that can tell the difference. That reasoning depends ENTIRELY on the pipe
469 # pass having run -- under --transport tcp it is the only pass there is, and
470 # narrowing it would silently drop the other 186 tests from the run
471 # altogether. --full-tcp forces the full sweep either way.
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 # env_prefix (e.g. a brew PATH) must reach the test too: some tests build a
478 # helper binary on the fly (a test may invoke `make`, which needs gawk etc.),
479 # so the build tools must be on PATH at test time.
480 pre = f'{t.env_prefix}; ' if t.env_prefix else ''
481 if t.privilege == "sudo":
482 # -n: never prompt (capture_output has no TTY -- a prompt would hang
483 # the whole timeout). Targets need passwordless sudo or a fresh
484 # `sudo -v`. env keeps the vars (and PATH) across the sudo boundary.
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 # A relocated scratch lives outside builddir, so clearing ./testtmp alone
505 # leaves the prior sudo run's root-owned tree in place and the non-root
506 # pass cannot create anything under it.
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 # runtests.py output parsing
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 # Tests that failed the initial run but passed on a max_retry re-run, so they
542 # were dropped from `failed`. Surfaced in the report (a recovered flake is
543 # noted, never silently hidden).
544 recovered: list[str] = dataclasses.field(default_factory=list)
545 # Tests whose failure was tolerated via --xfail: dropped from `failed` (so the
546 # cell can still be OK) but surfaced in the report, never silently hidden.
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 # --xfail (global) plus this box's per-target xfail: drop tolerated failures
567 # from `failed` so they don't fail the cell.
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 # runtests exits non-zero per failing test; if the only failures were
580 # tolerated, clear the stale code so the cell reads OK (cf. retry_failed).
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 # The initial run's non-zero exit was the now-recovered failures; once they
610 # all pass on retry the cell is OK, so clear the stale exit code (only the
611 # failed tests can make runtests exit non-zero on a no-skip-list re-run).
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 # Wall-clock seconds per phase (push/build/pipe/tcp/nonroot) plus "total";
626 # populated for --timing. Phases run sequentially, so they sum to the total.
627 timings: dict[str, float] = dataclasses.field(default_factory=dict)
628
629
630 # ---------------------------------------------------------------------------
631 # per-target worker
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 # Always push: the run dir is freshly named per run, so there is no prior
656 # tree to reuse -- every run is a full configure + build.
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 # Extra older-protocol passes (mirroring the workflow's check30/check29
692 # steps): same stdio-pipe transport, but each protocol uses its own
693 # check30/check29 skip list (a feature like xattrs/ACLs runs at proto 30 yet
694 # skips at 29). Only targets that list `protocols` opt in; skipped under
695 # --transport tcp (these are pipe runs).
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 # Extra non-root pass (after the sudo runs) for targets that opt in, running
714 # the tests that declare `fleet_nonroot = True` (discovered in main()).
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 # reporting
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 # protoNN columns appear only when some target ran that older-protocol pass;
760 # the 'nonroot' column only when some target ran a non-root pass. Targets
761 # without a given pass show "-" there (a neutral N/A, not a failure).
762 transports = list(args.transports)
763 protos = {k for r in results for k in r.transports if k.startswith("proto")}
764 # highest protocol first (proto30 before proto29), matching check30/check29.
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", "-"): # "-" = N/A (e.g. no nonroot pass)
788 all_ok = False
789 row += st.ljust(16)
790 # data-driven row notes: local target, or a target with a distinct tcp -j
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 # detail section: only the unexpected cells
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 # Exclude N/A ("-") cells (e.g. the nonroot column for targets that don't
838 # run a non-root pass) from the OK/not-OK tally.
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 # Recovered flakes: tests that failed but passed within the target's
850 # max_retry budget. The cell counts as OK, but list them so a flaky test is
851 # never silently swallowed.
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 # The remote tree is only meaningful if the run got far enough to make
915 # one; an unreachable or un-pushed target has nothing to keep.
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 # Phase columns for --timing, in execution order (push -> build -> tests).
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 # Insert any protoNN phases (highest first) just before nonroot, in run order.
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 # Failed-early targets have no "total"; sum the phases they did reach.
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 # run-dir cleanup
979 # ---------------------------------------------------------------------------
980
981 # Targets whose per-run dir (t.builddir, already suffixed with the run_id) this
982 # process must remove on exit. Populated in main() once the run_id is applied.
983 _cleanup_targets: list[Target] = []
984 _cleanup_lock = threading.Lock()
985 _cleanup_done = False
986 # Names of targets whose run dir must survive the exit sweep (--keep-on-fail,
987 # populated once results are in). Everything else is removed as usual.
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 # Skip atexit/thread-join: worker threads' ssh calls can't be cancelled and
1032 # would otherwise block exit until they return. The remote build/test simply
1033 # errors out now that its dir is gone.
1034 os._exit(130 if signum == signal.SIGINT else 143)
1035
1036
1037 # sweep() counts a pattern, kills it (best effort; sudo -n retry for processes a
1038 # root-running test left), then RE-counts after a settle so we report what
1039 # actually died (KILLED = before-after) and flag any survivor (SURVIVED, sets
1040 # fail) instead of claiming success when pkill couldn't reach it. The patterns
1041 # use the pgrep self-exclusion trick -- 'r[e]name'/'det[a]ch'/'[l]ocalhost' match a
1042 # real process's "rename"/"detach"/"localhost" but not the bracketed literal in this
1043 # script's own argv (run_on passes the whole script as the remote argv), so we never
1044 # signal ourselves. The client sweep catches an orphaned `rsync rsync://localhost:N/`
1045 # left blocked on a read when its test was killed (no I/O timeout). @BASE@ is
1046 # substituted with the target's run-dir prefix.
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 # Structured markers (KILLED/SURVIVED/REMOVED/FAILED) keep the report
1122 # clean even though run_on() folds stderr into stdout.
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 # main
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 # The expected-skip lists travel with the suite, so read workflows from the
1208 # tree that provides the tests.
1209 WORKFLOWS = TESTSUITE_REPO / ".github" / "workflows"
1210
1211 # A tree that is OLDER than the suite being run against it -- a backport
1212 # branch under --testsuite-repo -- cannot pass tests for fixes and features
1213 # it does not carry, and cannot build the suite's newer unit-test helpers.
1214 # It declares those in its own testsuite/skiplist/backport.txt, which is
1215 # read from the BUILT tree, not the suite tree, because only the built tree
1216 # knows what it lacks. The names are excluded outright (RSYNC_EXCLUDE)
1217 # rather than declared as expected skips: some of them fail rather than
1218 # skip, and an expected-skip list cannot describe a failure.
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 # The Python test suite (runtests.py + testsuite/) comes from
1230 # TESTSUITE_REPO, so that is where runtests.py must live. The build tree
1231 # (REPO) only has to be a buildable rsync source -- it may be an older
1232 # release whose runtests.py predates the Python suite, or lacks it.
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 # Sweep every <builddir>-* run dir on the selected targets. NB: this
1281 # also removes dirs belonging to runs that are still in progress, so
1282 # only run it when no other fleettest runs are active (or scope with
1283 # --targets).
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 # Give this run its own build dir on every target so concurrent runs don't
1294 # collide, and name it after the target too, because two targets can share
1295 # one machine: <builddir>-<run_id>-<target>. Without the target part they
1296 # would push into the same tree, and the second would inherit the first's
1297 # config.h/Makefile and never reconfigure with its own flags. The base name
1298 # is still the prefix --cleanup globs.
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 # Remove each run dir when we exit -- success or failure, and best-effort on
1306 # Ctrl-C/kill (a signal mid-push may still leave a remnant). SIGKILL can't be
1307 # caught; `fleettest.py --cleanup` sweeps any such remnant.
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 # Stage committed HEAD (source-only). Each target regenerates its own
1315 # build files with its own toolchain -- exactly like the CI jobs, which
1316 # install autotools / python-markdown / dev-libs in their prepare step.
1317 # (Pushing locally-generated files instead fights rsync's Makefile
1318 # maintainer rules: a target with a different autoconf version sees
1319 # "configure.sh has CHANGED" and errors.) So each target must be
1320 # provisioned like its workflow -- see the module docstring.
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 # --testsuite-repo: overlay another tree's runtests.py + testsuite/ onto
1330 # the built source (merge, no delete). Build REPO's rsync, but run
1331 # TESTSUITE_REPO's suite against it. The leftover .test files from REPO
1332 # are ignored by a Python runtests.py (it globs *_test.py).
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 # Tests that opt into the non-root pass (same for every target).
1343 args.nonroot_tests = discover_nonroot_tests(Path(staging) / "testsuite")
1344
1345 # Targets are grouped by machine, and a machine's targets run one after
1346 # another. Two targets CAN name the same host -- an alternate-filesystem
1347 # variant of another target does exactly that -- and running those at
1348 # the same time breaks both: they would fight over the fixed ports the
1349 # daemon tests claim, and over any other host-global state. Different
1350 # machines still run concurrently, which is where the parallelism was.
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: # never let one target kill the run
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: # a whole group died: account for each
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 # Before the exit sweep runs: mark failed targets' run dirs to survive and
1388 # write their output locally, so the report can point at both.
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())