| 1 |
#!/usr/bin/python3 -cimport os, sys; os.execv(os.path.dirname(sys.argv[1]) + "/pywrap", sys.argv) |
| 2 |
|
| 3 |
import binascii |
| 4 |
import errno |
| 5 |
import glob |
| 6 |
import importlib.machinery |
| 7 |
import importlib.util |
| 8 |
import logging |
| 9 |
import os |
| 10 |
import socket |
| 11 |
import string |
| 12 |
import subprocess |
| 13 |
import sys |
| 14 |
import tempfile |
| 15 |
import time |
| 16 |
import unittest |
| 17 |
from collections.abc import Collection, Sequence |
| 18 |
from dataclasses import dataclass |
| 19 |
from typing import IO |
| 20 |
|
| 21 |
import testlib |
| 22 |
from lcov import create_coverage_report, prepare_for_code_coverage |
| 23 |
from lib.constants import DEFAULT_MACHINE_MEMORY_MB |
| 24 |
from machine import testvm |
| 25 |
|
| 26 |
os.environ["PYTHONUNBUFFERED"] = "1" |
| 27 |
|
| 28 |
# Amount of times a test is re-run to find flakes / race conditions |
| 29 |
AMPLIFY_TEST_COUNT = 10 |
| 30 |
|
| 31 |
# Memory usage constants; measured 2026-01 on Fedora 43 x86_64 with Chromium 143 and Firefox 146 |
| 32 |
BROWSER_MEMORY_MB = 550 # Incremental per process (Firefox: 470 MB, Chromium: 319 MB; + margin) |
| 33 |
# browser code/libs shared memory (285 MB measured), and leave some breathing room for OS/buffers |
| 34 |
SYSTEM_RESERVE_GB = 1.0 |
| 35 |
|
| 36 |
|
| 37 |
def get_available_memory_gb() -> float: |
| 38 |
# Format: "MemAvailable: 12345678 kB" |
| 39 |
with open('/proc/meminfo', 'r') as f: |
| 40 |
for line in f: |
| 41 |
if line.startswith('MemAvailable:'): |
| 42 |
return int(line.split()[1]) / (1024 * 1024) |
| 43 |
raise RuntimeError("MemAvailable not found in /proc/meminfo") |
| 44 |
|
| 45 |
|
| 46 |
@dataclass |
| 47 |
class CliOpts(testlib.TestlibArgs): |
| 48 |
amplify: str | None |
| 49 |
base: str |
| 50 |
browser: str | None |
| 51 |
debug: bool |
| 52 |
exclude: Sequence[str] |
| 53 |
machine: str | None |
| 54 |
no_retry_fail: bool |
| 55 |
nondestructive: bool |
| 56 |
nondestructive_cpus: int |
| 57 |
nondestructive_memory_mb: int |
| 58 |
capacity_factor: float |
| 59 |
test_dir: str |
| 60 |
test_glob: str |
| 61 |
thorough: bool |
| 62 |
track_naughties: bool |
| 63 |
|
| 64 |
|
| 65 |
def flush_stdout() -> None: |
| 66 |
while True: |
| 67 |
try: |
| 68 |
sys.stdout.flush() |
| 69 |
break |
| 70 |
except BlockingIOError: |
| 71 |
time.sleep(0.1) |
| 72 |
|
| 73 |
|
| 74 |
class Test: |
| 75 |
def __init__( |
| 76 |
self, |
| 77 |
test_id: int, |
| 78 |
*, |
| 79 |
command: Sequence[str], |
| 80 |
timeout: float, |
| 81 |
nondestructive: bool, |
| 82 |
retry_when_affected: bool, |
| 83 |
todo: str | None, |
| 84 |
ram_gb: float, |
| 85 |
) -> None: |
| 86 |
self.process: subprocess.Popen[bytes] | None = None |
| 87 |
self.retries = 0 |
| 88 |
self.test_id = test_id |
| 89 |
self.command = list(command) |
| 90 |
self.timeout = timeout |
| 91 |
self.nondestructive = nondestructive |
| 92 |
self.machine_id: int | None = None |
| 93 |
self.retry_when_affected = retry_when_affected |
| 94 |
self.todo = todo |
| 95 |
self.ram_gb = ram_gb |
| 96 |
self.returncode: int | None = None |
| 97 |
|
| 98 |
def assign_machine(self, machine_id: int, ssh_address: str, web_address: str) -> None: |
| 99 |
assert self.nondestructive, "assigning a machine only works for nondestructive test" |
| 100 |
self.machine_id = machine_id |
| 101 |
self.command.insert(-2, "--machine") |
| 102 |
self.command.insert(-2, ssh_address) |
| 103 |
self.command.insert(-2, "--browser") |
| 104 |
self.command.insert(-2, web_address) |
| 105 |
|
| 106 |
def start(self) -> None: |
| 107 |
if self.nondestructive: |
| 108 |
assert self.machine_id is not None, ( |
| 109 |
f"need to assign nondestructive test {self} {self.command} to a machine" |
| 110 |
) |
| 111 |
self.outfile: IO[bytes] | None = tempfile.TemporaryFile() |
| 112 |
self.process = subprocess.Popen( |
| 113 |
["timeout", "-v", str(self.timeout), *self.command], stdout=self.outfile, stderr=subprocess.STDOUT |
| 114 |
) |
| 115 |
|
| 116 |
def poll(self) -> int | None: |
| 117 |
assert self.process is not None |
| 118 |
|
| 119 |
poll_result = self.process.poll() |
| 120 |
if poll_result is not None: |
| 121 |
assert self.outfile is not None |
| 122 |
|
| 123 |
self.outfile.flush() |
| 124 |
self.outfile.seek(0) |
| 125 |
self.output = self.outfile.read() |
| 126 |
self.outfile.close() |
| 127 |
self.outfile = None |
| 128 |
self.returncode = self.process.returncode |
| 129 |
|
| 130 |
return poll_result |
| 131 |
|
| 132 |
def finish(self, affected_tests: list[str], opts: CliOpts) -> tuple[str | None, int]: |
| 133 |
"""Returns if a test should retry or not |
| 134 |
|
| 135 |
Call test-failure-policy on the test's output, print if needed. |
| 136 |
|
| 137 |
Return (retry_reason, exit_code). retry_reason can be None or a string. |
| 138 |
""" |
| 139 |
|
| 140 |
print_tap = not opts.list |
| 141 |
affected = any(self.command[0].endswith(t) for t in affected_tests) |
| 142 |
retry_reason = "" |
| 143 |
|
| 144 |
# Try affected tests 3 times |
| 145 |
if self.returncode == 0 and affected and self.retry_when_affected and self.retries < 2: |
| 146 |
retry_reason = "test affected tests 3 times" |
| 147 |
self.retries += 1 |
| 148 |
self._print_test(print_tap=print_tap, retry_reason=f"# RETRY {self.retries} ({retry_reason})") |
| 149 |
return retry_reason, 0 |
| 150 |
|
| 151 |
# If test is being skipped pick up the reason |
| 152 |
if self.returncode == 77: |
| 153 |
lines = self.output.splitlines() |
| 154 |
skip_reason = lines[-1].strip().decode() |
| 155 |
self.output = b"\n".join(lines[:-1]) |
| 156 |
self._print_test(print_tap=print_tap, skip_reason=skip_reason) |
| 157 |
return None, 0 |
| 158 |
|
| 159 |
# If the test was marked with @todo then... |
| 160 |
if self.todo is not None: |
| 161 |
if self.returncode == 0: |
| 162 |
# The test passed, but it shouldn't have. |
| 163 |
self.returncode = 1 # that's a fail |
| 164 |
self._print_test(print_tap=print_tap, todo_reason=f"# expected failure: {self.todo}") |
| 165 |
return None, 1 |
| 166 |
else: |
| 167 |
# The test failed as expected |
| 168 |
# Outputs 'not ok 1 test # TODO ...' |
| 169 |
self._print_test(print_tap=print_tap, todo_reason=f"# TODO {self.todo}") |
| 170 |
return None, 0 |
| 171 |
|
| 172 |
if self.returncode == 0: |
| 173 |
self._print_test(print_tap=print_tap) |
| 174 |
return None, 0 |
| 175 |
|
| 176 |
if not opts.thorough: |
| 177 |
cmd = ["test-failure-policy", "--all"] |
| 178 |
if not opts.track_naughties: |
| 179 |
cmd.append("--offline") |
| 180 |
cmd.append(testvm.DEFAULT_IMAGE) |
| 181 |
try: |
| 182 |
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
| 183 |
reason = proc.communicate(self.output + ("not ok " + str(self)).encode())[0].strip() |
| 184 |
|
| 185 |
if proc.returncode == 77: |
| 186 |
self.returncode = proc.returncode |
| 187 |
self._print_test(skip_reason=f"# SKIP {reason.decode()}") |
| 188 |
return None, 0 |
| 189 |
|
| 190 |
if proc.returncode == 78: |
| 191 |
self.returncode = proc.returncode |
| 192 |
self._print_test(skip_reason=f"# NOTE {reason.decode()}") |
| 193 |
return None, 1 |
| 194 |
|
| 195 |
if proc.returncode == 1: |
| 196 |
retry_reason = reason.decode() |
| 197 |
|
| 198 |
except OSError as ex: |
| 199 |
if ex.errno != errno.ENOENT: |
| 200 |
sys.stderr.write(f"\nCouldn't run test-failure-policy: {ex!s}\n") |
| 201 |
|
| 202 |
# Always retry test harness failures |
| 203 |
if retry_reason and "test harness" in retry_reason: |
| 204 |
self.retries += 1 |
| 205 |
self._print_test(retry_reason=f"# RETRY {self.retries} ({retry_reason})") |
| 206 |
return retry_reason, 0 |
| 207 |
|
| 208 |
# HACK: many tests are unstable, always retry them 3 times unless affected |
| 209 |
if not affected and not retry_reason and not opts.no_retry_fail: |
| 210 |
retry_reason = "be robust against unstable tests" |
| 211 |
|
| 212 |
has_unexpected_message = testlib.UNEXPECTED_MESSAGE.encode() in self.output |
| 213 |
has_pixel_test_message = testlib.PIXEL_TEST_MESSAGE.encode() in self.output |
| 214 |
if self.retries < 2 and not (has_unexpected_message or has_pixel_test_message) and retry_reason: |
| 215 |
self.retries += 1 |
| 216 |
self._print_test(retry_reason=f"# RETRY {self.retries} ({retry_reason})") |
| 217 |
return retry_reason, 0 |
| 218 |
|
| 219 |
self.output += b"\n" |
| 220 |
self._print_test() |
| 221 |
self.machine_id = None |
| 222 |
return None, 1 |
| 223 |
|
| 224 |
# internal methods |
| 225 |
|
| 226 |
def __str__(self) -> str: |
| 227 |
ram = "" if self.nondestructive else f" ({self.ram_gb:.1f}GB)" |
| 228 |
nd = f" [ND@{self.machine_id}]" if self.nondestructive else "" |
| 229 |
return f"{self.test_id} {self.command[0]} {self.command[-1]}{ram}{nd}" |
| 230 |
|
| 231 |
def _print_test( |
| 232 |
self, *, print_tap: bool = True, retry_reason: str = "", skip_reason: str = "", todo_reason: str = "" |
| 233 |
) -> None: |
| 234 |
def write_line(line: bytes) -> None: |
| 235 |
while line: |
| 236 |
try: |
| 237 |
sys.stdout.buffer.write(line) |
| 238 |
break |
| 239 |
except BlockingIOError as e: |
| 240 |
line = line[e.characters_written :] |
| 241 |
time.sleep(0.1) |
| 242 |
|
| 243 |
# be quiet in TAP mode for successful tests |
| 244 |
lines = self.output.strip().splitlines(keepends=True) |
| 245 |
if print_tap and self.returncode == 0 and len(lines) > 0: |
| 246 |
for line in lines[:-1]: |
| 247 |
if line.startswith(b"WARNING:"): |
| 248 |
write_line(line) |
| 249 |
write_line(lines[-1]) |
| 250 |
else: |
| 251 |
for line in lines: |
| 252 |
write_line(line) |
| 253 |
|
| 254 |
if retry_reason: |
| 255 |
retry_reason = " " + retry_reason |
| 256 |
if skip_reason: |
| 257 |
skip_reason = " " + skip_reason |
| 258 |
if todo_reason: |
| 259 |
todo_reason = " " + todo_reason |
| 260 |
|
| 261 |
if not print_tap: |
| 262 |
print(retry_reason + skip_reason + todo_reason) |
| 263 |
flush_stdout() |
| 264 |
return |
| 265 |
|
| 266 |
print() # Tap needs to start on a separate line |
| 267 |
status = "ok" if self.returncode in [0, 77] else "not ok" |
| 268 |
print(f"{status} {self}{retry_reason}{skip_reason}{todo_reason}") |
| 269 |
flush_stdout() |
| 270 |
|
| 271 |
|
| 272 |
class GlobalMachine: |
| 273 |
def __init__( |
| 274 |
self, |
| 275 |
*, |
| 276 |
restrict: bool = True, |
| 277 |
cpus: int | None = None, |
| 278 |
memory_mb: int, |
| 279 |
machine_class: type[testvm.VirtMachine] = testvm.VirtMachine, |
| 280 |
): |
| 281 |
self.image = testvm.DEFAULT_IMAGE |
| 282 |
self.network = testvm.VirtNetwork(image=self.image) |
| 283 |
self.networking = self.network.host(restrict=restrict) |
| 284 |
self.machine: testvm.VirtMachine | None = machine_class( |
| 285 |
verbose=True, networking=self.networking, image=self.image, cpus=cpus, memory_mb=memory_mb |
| 286 |
) |
| 287 |
self.machine_class = machine_class |
| 288 |
if not os.path.exists(self.machine.image_file): |
| 289 |
self.machine.pull(self.machine.image_file) |
| 290 |
self.machine.start() |
| 291 |
self.start_time = time.time() |
| 292 |
self.duration: int | None = None |
| 293 |
self.ssh_address: str | None = f"{self.machine.ssh_address}:{self.machine.ssh_port}" |
| 294 |
self.web_address: str | None = f"{self.machine.web_address}:{self.machine.web_port}" |
| 295 |
self.running_test: Test | None = None |
| 296 |
|
| 297 |
def reset(self) -> None: |
| 298 |
# It is important to re-use self.networking here, so that the |
| 299 |
# machine keeps its browser and control port. |
| 300 |
assert self.machine is not None |
| 301 |
self.machine.kill() |
| 302 |
self.machine = self.machine_class(verbose=True, networking=self.networking, image=self.image) |
| 303 |
self.machine.start() |
| 304 |
|
| 305 |
def kill(self) -> None: |
| 306 |
assert self.running_test is None, "can't kill global machine with running test" |
| 307 |
assert self.machine is not None |
| 308 |
self.machine.kill() |
| 309 |
self.network.kill() |
| 310 |
self.duration = round(time.time() - self.start_time) |
| 311 |
self.machine = None |
| 312 |
self.ssh_address = None |
| 313 |
self.web_address = None |
| 314 |
|
| 315 |
def is_available(self) -> bool: |
| 316 |
return self.machine is not None and self.running_test is None |
| 317 |
|
| 318 |
|
| 319 |
def check_valid(filename: str) -> str | None: |
| 320 |
name = os.path.basename(filename) |
| 321 |
allowed = string.ascii_letters + string.digits + "-_" |
| 322 |
if not all(c in allowed for c in name): |
| 323 |
return None |
| 324 |
return name.replace("-", "_") |
| 325 |
|
| 326 |
|
| 327 |
def build_command(filename: str, test: str, opts: CliOpts) -> Sequence[str]: |
| 328 |
cmd = [filename] |
| 329 |
if opts.trace: |
| 330 |
cmd.append("-t") |
| 331 |
if opts.verbosity: |
| 332 |
cmd.append("-v") |
| 333 |
if not opts.fetch: |
| 334 |
cmd.append("--nonet") |
| 335 |
if opts.list: |
| 336 |
cmd.append("-l") |
| 337 |
if opts.coverage: |
| 338 |
cmd.append("--coverage") |
| 339 |
cmd.append(test) |
| 340 |
return cmd |
| 341 |
|
| 342 |
|
| 343 |
def get_affected_tests(test_dir: str, base_branch: str, test_files: Collection[str]) -> list[str]: |
| 344 |
if not base_branch: |
| 345 |
return [] |
| 346 |
|
| 347 |
changed_tests = [] |
| 348 |
|
| 349 |
# Detect affected tests from changed test files |
| 350 |
diff_out = subprocess.check_output(["git", "diff", "--name-only", "origin/" + base_branch, test_dir]) |
| 351 |
# Never consider 'test/verify/check-example' to be affected - our tests for tests count on that |
| 352 |
# This file provides only examples, there is no place for it being flaky, no need to retry |
| 353 |
changed_tests = [test.decode() for test in diff_out.strip().splitlines() if not test.endswith(b"check-example")] |
| 354 |
|
| 355 |
# If more than 3 test files were changed don't consider any of them as affected |
| 356 |
# as it might be a PR that changes more unrelated things. |
| 357 |
if len(changed_tests) > 3: |
| 358 |
# If 'test/verify/check-testlib' is affected, keep just that one - our tests for tests count on that |
| 359 |
if "test/verify/check-testlib" in changed_tests: |
| 360 |
changed_tests = ["test/verify/check-testlib"] |
| 361 |
else: |
| 362 |
changed_tests = [] |
| 363 |
|
| 364 |
# Detect affected tests from changed pkg/* subdirectories in cockpit |
| 365 |
# If affected tests get detected from pkg/* changes, don't apply the |
| 366 |
# "only do this for max. 3 check-* changes" (even if the PR also changes ≥ 3 check-*) |
| 367 |
# (this does not apply to other projects) |
| 368 |
diff_out = subprocess.check_output(["git", "diff", "--name-only", "origin/" + base_branch, "--", "pkg/"]) |
| 369 |
|
| 370 |
# Drop changes in css files - this does not affect tests thus no reason to retry |
| 371 |
files = [f.decode() for f in diff_out.strip().splitlines() if not f.endswith(b"css")] |
| 372 |
|
| 373 |
changed_pkgs = {"check-" + pkg.split("/")[1] for pkg in files} |
| 374 |
changed_tests.extend([test for test in test_files if any(pkg in test for pkg in changed_pkgs)]) |
| 375 |
|
| 376 |
return changed_tests |
| 377 |
|
| 378 |
|
| 379 |
def detect_tests( |
| 380 |
test_files: Collection[str], image: str, opts: CliOpts |
| 381 |
) -> tuple[list[Test], list[Test], type[testvm.VirtMachine] | None]: |
| 382 |
"""Detect tests to be run |
| 383 |
|
| 384 |
Builds the list of tests we'll run in separate machines (destructive tests) |
| 385 |
and the ones we can run on the same machine (nondestructive) |
| 386 |
""" |
| 387 |
|
| 388 |
destructive_tests: list[Test] = [] |
| 389 |
nondestructive_tests: list[Test] = [] |
| 390 |
seen_classes: dict[str, str] = {} |
| 391 |
machine_class = None |
| 392 |
test_id = 1 |
| 393 |
|
| 394 |
for filename in test_files: |
| 395 |
name = check_valid(filename) |
| 396 |
if not name or not os.path.isfile(filename): |
| 397 |
continue |
| 398 |
loader = importlib.machinery.SourceFileLoader(name, filename) |
| 399 |
spec = importlib.util.spec_from_loader(loader.name, loader) |
| 400 |
assert spec is not None |
| 401 |
module = importlib.util.module_from_spec(spec) |
| 402 |
loader.exec_module(module) |
| 403 |
for test_suite in unittest.TestLoader().loadTestsFromModule(module): |
| 404 |
assert isinstance(test_suite, unittest.TestSuite) |
| 405 |
for test in test_suite: |
| 406 |
assert isinstance(test, unittest.TestCase) |
| 407 |
if isinstance(test, testlib.MachineCase) and test.machine_class is not None: |
| 408 |
if machine_class is not None and machine_class != test.machine_class: |
| 409 |
raise ValueError( |
| 410 |
f"only one unique machine_class can be used per project, provided with {machine_class} and {test.machine_class}" |
| 411 |
) |
| 412 |
|
| 413 |
machine_class = test.machine_class |
| 414 |
|
| 415 |
# ensure that test classes are unique, so that they can be selected properly |
| 416 |
cls = test.__class__.__name__ |
| 417 |
if seen_classes.get(cls) not in [None, filename]: |
| 418 |
raise ValueError("test class %s in %s already defined in %s" % (cls, filename, seen_classes[cls])) |
| 419 |
seen_classes[cls] = filename |
| 420 |
|
| 421 |
test_method = getattr(test.__class__, test._testMethodName) |
| 422 |
test_str = f"{cls}.{test._testMethodName}" |
| 423 |
# most tests should take much less than 10mins, so default to that; |
| 424 |
# longer tests can be annotated with @timeout(seconds) |
| 425 |
# check the test function first, fall back to the class'es timeout |
| 426 |
if opts.tests and not any(t in test_str for t in opts.tests): |
| 427 |
continue |
| 428 |
if test_str in opts.exclude: |
| 429 |
continue |
| 430 |
test_timeout = testlib.get_decorator(test_method, test, "timeout", 600) |
| 431 |
nd = testlib.get_decorator(test_method, test, "nondestructive") |
| 432 |
rwa = not testlib.get_decorator(test_method, test, "no_retry_when_changed") |
| 433 |
todo = testlib.get_decorator(test_method, test, "todo") |
| 434 |
|
| 435 |
# Calculate test's RAM requirement (VM memory + browser) |
| 436 |
if nd: |
| 437 |
total_vm_memory_mb = opts.nondestructive_memory_mb |
| 438 |
else: |
| 439 |
provision = getattr(test.__class__, "provision", None) or {"machine": {}} |
| 440 |
total_vm_memory_mb = sum( |
| 441 |
config.get("memory_mb") or DEFAULT_MACHINE_MEMORY_MB |
| 442 |
for config in provision.values() |
| 443 |
) |
| 444 |
ram_gb = (total_vm_memory_mb + BROWSER_MEMORY_MB) / 1024.0 |
| 445 |
|
| 446 |
tst = Test( |
| 447 |
test_id, |
| 448 |
command=build_command(filename, test_str, opts), |
| 449 |
timeout=test_timeout, |
| 450 |
nondestructive=nd, |
| 451 |
retry_when_affected=rwa, |
| 452 |
todo=todo, |
| 453 |
ram_gb=ram_gb, |
| 454 |
) |
| 455 |
if nd: |
| 456 |
for _ in range(AMPLIFY_TEST_COUNT if opts.amplify == test_str else 1): |
| 457 |
nondestructive_tests.append(tst) |
| 458 |
else: |
| 459 |
if not opts.nondestructive: |
| 460 |
for _ in range(AMPLIFY_TEST_COUNT if opts.amplify == test_str else 1): |
| 461 |
destructive_tests.append(tst) |
| 462 |
test_id += 1 |
| 463 |
|
| 464 |
# sort non destructive tests by class/test name, to avoid spurious errors where failures depend on the order of |
| 465 |
# execution but let's make sure we always test them both ways around; hash the image name, which is |
| 466 |
# robust, reproducible, and provides an even distribution of both directions |
| 467 |
nondestructive_tests.sort(key=lambda t: t.command[-1], reverse=bool(binascii.crc32(image.encode()) & 1)) |
| 468 |
|
| 469 |
return (nondestructive_tests, destructive_tests, machine_class) |
| 470 |
|
| 471 |
|
| 472 |
def list_tests(opts: CliOpts) -> None: |
| 473 |
test_files = glob.glob(os.path.join(opts.test_dir, opts.test_glob)) |
| 474 |
nondestructive_tests, destructive_tests, _ = detect_tests(test_files, "dummy", opts) |
| 475 |
names = {t.command[-1] for t in nondestructive_tests + destructive_tests} |
| 476 |
for n in sorted(names): |
| 477 |
print(n) |
| 478 |
|
| 479 |
|
| 480 |
def run(opts: CliOpts, image: str) -> int: |
| 481 |
fail_count = 0 |
| 482 |
start_time = time.time() |
| 483 |
|
| 484 |
if opts.coverage: |
| 485 |
prepare_for_code_coverage() |
| 486 |
|
| 487 |
test_files = glob.glob(os.path.join(opts.test_dir, opts.test_glob)) |
| 488 |
changed_tests = get_affected_tests(opts.test_dir, opts.base, test_files) |
| 489 |
nondestructive_tests, destructive_tests, machine_class = detect_tests(test_files, image, opts) |
| 490 |
nondestructive_tests_len = len(nondestructive_tests) |
| 491 |
destructive_tests_len = len(destructive_tests) |
| 492 |
|
| 493 |
if opts.machine: |
| 494 |
assert not destructive_tests |
| 495 |
|
| 496 |
print(f"1..{nondestructive_tests_len + destructive_tests_len}") |
| 497 |
flush_stdout() |
| 498 |
|
| 499 |
running_tests: list[Test] = [] |
| 500 |
global_machines: list[GlobalMachine] = [] |
| 501 |
test_slots: int = 0 # how many tests can we run in parallel |
| 502 |
|
| 503 |
if not opts.machine: |
| 504 |
# Create appropriate number of nondestructive machines; prioritize the nondestructive tests, to get |
| 505 |
# them out of the way as fast as possible, then let the destructive ones start as soon as |
| 506 |
# a given nondestructive runner is done. Limit by available RAM and CPU. |
| 507 |
available_ram_gb = get_available_memory_gb() - SYSTEM_RESERVE_GB |
| 508 |
global_machine_ram_gb = (opts.nondestructive_memory_mb + BROWSER_MEMORY_MB) / 1024.0 |
| 509 |
max_global_by_ram = int(available_ram_gb / global_machine_ram_gb) |
| 510 |
if max_global_by_ram == 0: |
| 511 |
sys.exit(f"Need {global_machine_ram_gb:.1f} GB per test, but only {available_ram_gb:.1f} GB available") |
| 512 |
|
| 513 |
max_global_by_cpu = max((os.cpu_count() or 0) // 2, 1) |
| 514 |
test_slots = int(min(max_global_by_ram, max_global_by_cpu) * opts.capacity_factor) |
| 515 |
|
| 516 |
num_global = min(nondestructive_tests_len, test_slots) |
| 517 |
logging.debug("ND capacity: %.1f GB available, %.1f GB/slot, " |
| 518 |
"max %d by RAM, max %d by CPU, factor %f, %d tests → starting %d slots", |
| 519 |
available_ram_gb, global_machine_ram_gb, |
| 520 |
max_global_by_ram, max_global_by_cpu, opts.capacity_factor, |
| 521 |
nondestructive_tests_len, num_global) |
| 522 |
|
| 523 |
for _ in range(num_global): |
| 524 |
global_machines.append( |
| 525 |
GlobalMachine( |
| 526 |
restrict=not opts.enable_network, |
| 527 |
cpus=opts.nondestructive_cpus, |
| 528 |
memory_mb=opts.nondestructive_memory_mb, |
| 529 |
machine_class=machine_class or testvm.VirtMachine, |
| 530 |
) |
| 531 |
) |
| 532 |
|
| 533 |
# test scheduling loop |
| 534 |
while True: |
| 535 |
made_progress = False |
| 536 |
|
| 537 |
# mop up finished tests |
| 538 |
logging.debug("test loop: %d running tests", len(running_tests)) |
| 539 |
for test in running_tests.copy(): |
| 540 |
poll_result = test.poll() |
| 541 |
if poll_result is not None: |
| 542 |
made_progress = True |
| 543 |
running_tests.remove(test) |
| 544 |
test_machine = test.machine_id # test_finish() resets it |
| 545 |
retry_reason, test_result = test.finish(changed_tests, opts) |
| 546 |
fail_count += test_result |
| 547 |
logging.debug("test %s finished; result %s retry reason %s", test, test_result, retry_reason) |
| 548 |
|
| 549 |
if test_machine is not None and not opts.machine: |
| 550 |
# unassign from global machine |
| 551 |
global_machines[test_machine].running_test = None |
| 552 |
|
| 553 |
# sometimes our global machine gets messed up; also, tests that time out don't run cleanup handlers |
| 554 |
# restart it to avoid an unbounded number of test retries and follow-up errors |
| 555 |
if poll_result == 124 or (retry_reason and "test harness" in retry_reason): |
| 556 |
# try hard to keep the test output consistent |
| 557 |
sys.stderr.write("\nRestarting global machine %s\n" % test_machine) |
| 558 |
sys.stderr.flush() |
| 559 |
global_machines[test_machine].reset() |
| 560 |
|
| 561 |
# run again if needed |
| 562 |
if retry_reason: |
| 563 |
if test.nondestructive: |
| 564 |
nondestructive_tests.insert(0, test) |
| 565 |
else: |
| 566 |
destructive_tests.insert(0, test) |
| 567 |
|
| 568 |
if opts.machine and opts.browser: |
| 569 |
if not running_tests and nondestructive_tests: |
| 570 |
test = nondestructive_tests.pop(0) |
| 571 |
logging.debug("Static machine is free, assigning next test %s", test) |
| 572 |
test.assign_machine(-1, opts.machine, opts.browser) |
| 573 |
test.start() |
| 574 |
running_tests.append(test) |
| 575 |
made_progress = True |
| 576 |
else: |
| 577 |
# find free global machines, and either assign a new non destructive test, or kill them to free resources |
| 578 |
for idx, machine in enumerate(global_machines): |
| 579 |
if machine.is_available(): |
| 580 |
if nondestructive_tests: |
| 581 |
test = nondestructive_tests.pop(0) |
| 582 |
logging.debug("Global machine %s is free, assigning next test %s", idx, test) |
| 583 |
machine.running_test = test |
| 584 |
assert machine.ssh_address is not None |
| 585 |
assert machine.web_address is not None |
| 586 |
test.assign_machine(idx, machine.ssh_address, machine.web_address) |
| 587 |
test.start() |
| 588 |
running_tests.append(test) |
| 589 |
else: |
| 590 |
logging.debug("Global machine %s is free, and no more non destructive tests; killing", idx) |
| 591 |
machine.kill() |
| 592 |
|
| 593 |
made_progress = True |
| 594 |
|
| 595 |
# Schedule destructive tests if we have enough RAM, and also don't exceed the parallelism capacity |
| 596 |
running_destructive_tests = len([t for t in running_tests if not t.nondestructive]) |
| 597 |
available_ram_gb = get_available_memory_gb() - SYSTEM_RESERVE_GB |
| 598 |
|
| 599 |
# Start destructive tests one at a time to avoid VM boot storms |
| 600 |
if destructive_tests: |
| 601 |
next_test = destructive_tests[0] |
| 602 |
|
| 603 |
# Check if we have a free slot |
| 604 |
running_global_machines = len([m for m in global_machines if m.machine is not None]) |
| 605 |
assert test_slots |
| 606 |
max_destructive = test_slots - running_global_machines |
| 607 |
if running_destructive_tests >= max_destructive: |
| 608 |
logging.debug("NOT starting %s: no free slots (max %d), already running %d destructive and %d global ND machines", |
| 609 |
next_test, max_destructive, running_destructive_tests, running_global_machines) |
| 610 |
# Check available RAM |
| 611 |
elif next_test.ram_gb > available_ram_gb: |
| 612 |
logging.debug("NOT starting %s: insufficient RAM (needs %.1f GB, only %.1f GB available)", |
| 613 |
next_test, next_test.ram_gb, available_ram_gb) |
| 614 |
else: |
| 615 |
test = destructive_tests.pop(0) |
| 616 |
logging.debug("starting %s", test) |
| 617 |
test.start() |
| 618 |
running_tests.append(test) |
| 619 |
made_progress = True |
| 620 |
# Avoid VM boot storms; unreliable especially with nested KVM. This should be enough time to let VMs boot |
| 621 |
time.sleep(15) |
| 622 |
|
| 623 |
# are we done? |
| 624 |
if not running_tests: |
| 625 |
assert not nondestructive_tests, ( |
| 626 |
f"nondestructive_tests should be empty: {[str(t) for t in nondestructive_tests]}" |
| 627 |
) |
| 628 |
assert not destructive_tests, f"destructive_tests should be empty: {[str(t) for t in destructive_tests]}" |
| 629 |
break |
| 630 |
|
| 631 |
# Sleep if we didn't make progress, give running tests some breathing room |
| 632 |
if not made_progress: |
| 633 |
time.sleep(5) |
| 634 |
|
| 635 |
# Create coverage report |
| 636 |
if opts.coverage: |
| 637 |
create_coverage_report() |
| 638 |
|
| 639 |
# print summary |
| 640 |
duration = int(time.time() - start_time) |
| 641 |
hostname = socket.gethostname().split(".")[0] |
| 642 |
|
| 643 |
nondestructive_details: list[str] = [] |
| 644 |
if not opts.machine: |
| 645 |
for idx, machine in enumerate(global_machines): |
| 646 |
nondestructive_details.append(f"{idx}: {machine.duration}s") |
| 647 |
|
| 648 |
details = f"[{duration}s on {hostname}, {destructive_tests_len} destructive tests, {nondestructive_tests_len} nondestructive tests: {', '.join(nondestructive_details)}]" |
| 649 |
print() |
| 650 |
if fail_count > 0: |
| 651 |
print(f"# {fail_count} TESTS FAILED {details}") |
| 652 |
else: |
| 653 |
print(f"# TESTS PASSED {details}") |
| 654 |
flush_stdout() |
| 655 |
|
| 656 |
return fail_count |
| 657 |
|
| 658 |
|
| 659 |
def main() -> int: |
| 660 |
parser = testlib.arg_parser(enable_sit=False) |
| 661 |
parser.add_argument("--debug", action="store_true", help="Enable verbose debug logging") |
| 662 |
parser.add_argument("--thorough", action="store_true", help="Thorough mode, no skipping known issues") |
| 663 |
parser.add_argument("-n", "--nondestructive", action="store_true", help="Only consider @nondestructive tests") |
| 664 |
parser.add_argument( |
| 665 |
"--machine", |
| 666 |
metavar="hostname[:port]", |
| 667 |
default=None, |
| 668 |
help="Run tests against an already running machine; implies --nondestructive", |
| 669 |
) |
| 670 |
parser.add_argument( |
| 671 |
"--browser", |
| 672 |
metavar="hostname[:port]", |
| 673 |
default=None, |
| 674 |
help="When using --machine, use this cockpit web address", |
| 675 |
) |
| 676 |
parser.add_argument( |
| 677 |
"--test-dir", |
| 678 |
default=os.environ.get("TEST_DIR", testvm.TEST_DIR), |
| 679 |
help="Directory in which to glob for test files; default: %(default)s", |
| 680 |
) |
| 681 |
parser.add_argument( |
| 682 |
"--test-glob", |
| 683 |
default="check-*", |
| 684 |
help="Pattern with which to glob in the test directory; default: %(default)s", |
| 685 |
) |
| 686 |
parser.add_argument( |
| 687 |
"--exclude", |
| 688 |
action="append", |
| 689 |
default=[], |
| 690 |
metavar="TestClass.testName", |
| 691 |
help="Exclude test (exact match only); can be specified multiple times", |
| 692 |
) |
| 693 |
parser.add_argument( |
| 694 |
"--nondestructive-cpus", type=int, default=None, help="Number of CPUs for nondestructive test global machines" |
| 695 |
) |
| 696 |
parser.add_argument( |
| 697 |
"--nondestructive-memory-mb", type=int, default=DEFAULT_MACHINE_MEMORY_MB, |
| 698 |
help="RAM size for nondestructive test global machines (default: %(default)s MB)", |
| 699 |
) |
| 700 |
parser.add_argument( |
| 701 |
"--capacity-factor", type=float, default=1.0, |
| 702 |
help="Multiply the detected capacity for running tests in parallel with this number (default: %(default)s)", |
| 703 |
) |
| 704 |
parser.add_argument( |
| 705 |
"--base", |
| 706 |
default=os.environ.get("BASE_BRANCH"), |
| 707 |
help="Retry affected tests compared to given base branch; default: %(default)s", |
| 708 |
) |
| 709 |
parser.add_argument( |
| 710 |
"--track-naughties", action="store_true", help="Update the occurrence of naughties on cockpit-project/bots" |
| 711 |
) |
| 712 |
parser.add_argument("--no-retry-fail", action="store_true", help="Don't retry failed tests") |
| 713 |
parser.add_argument("--amplify", type=str, default=None, help="Run the given tests multiple times in a row") |
| 714 |
opts = CliOpts(**vars(parser.parse_args())) |
| 715 |
|
| 716 |
# Set up logging |
| 717 |
if opts.debug: |
| 718 |
logging.basicConfig(level=logging.DEBUG, format='%(levelname)s:run-tests:%(message)s') |
| 719 |
|
| 720 |
if opts.machine: |
| 721 |
if not opts.browser: |
| 722 |
parser.error("--browser must be specified together with --machine") |
| 723 |
opts.nondestructive = True |
| 724 |
|
| 725 |
# Tell any subprocesses what we are testing |
| 726 |
if "TEST_REVISION" not in os.environ: |
| 727 |
r = subprocess.run(["git", "rev-parse", "HEAD"], universal_newlines=True, check=False, stdout=subprocess.PIPE) |
| 728 |
if r.returncode == 0: |
| 729 |
os.environ["TEST_REVISION"] = r.stdout.strip() |
| 730 |
|
| 731 |
os.environ["TEST_BROWSER"] = os.environ.get("TEST_BROWSER", "chromium") |
| 732 |
|
| 733 |
image = testvm.DEFAULT_IMAGE |
| 734 |
testvm.DEFAULT_IMAGE = image |
| 735 |
os.environ["TEST_OS"] = image |
| 736 |
|
| 737 |
# on RHEL 8, provide enough RAM for cryptsetup's PBKDF (https://issues.redhat.com/browse/RHEL-8258) |
| 738 |
# On any newer OS, cryptsetup gets along with less RAM |
| 739 |
if image.startswith("rhel-8") and opts.nondestructive_memory_mb == DEFAULT_MACHINE_MEMORY_MB: |
| 740 |
opts.nondestructive_memory_mb = 1400 |
| 741 |
|
| 742 |
# Make sure tests can make relative imports |
| 743 |
sys.path.append(os.path.realpath(opts.test_dir)) |
| 744 |
|
| 745 |
if opts.list: |
| 746 |
list_tests(opts) |
| 747 |
return 0 |
| 748 |
|
| 749 |
return run(opts, image) |
| 750 |
|
| 751 |
|
| 752 |
if __name__ == "__main__": |
| 753 |
sys.exit(main()) |