From d70b0cbc5c76298ef6fd885cc9b945490cc59b53 Mon Sep 17 00:00:00 2001 From: WenyXu Date: Wed, 28 Oct 2026 07:27:13 +0000 Subject: [PATCH] feat(ci): support optional Docker targets for query regression Signed-off-by: WenyXu --- .../ecs-image/bootstrap-runner-host.sh | 1 + .../ecs-image/build-ecs-image.py | 1 + .github/scripts/query-regression-run.py | 149 +++++++++++++++++- .github/workflows/query-regression.yml | 43 ++++- tests/perf/README.md | 54 ++++++- ...ery_regression_runner_compaction_toctou.py | 131 ++++++++++++++- 6 files changed, 365 insertions(+), 14 deletions(-) diff --git a/.github/runner-scale-sets/query-regression/ecs-image/bootstrap-runner-host.sh b/.github/runner-scale-sets/query-regression/ecs-image/bootstrap-runner-host.sh index 883bbede092..9299e51bb1f 100644 --- a/.github/runner-scale-sets/query-regression/ecs-image/bootstrap-runner-host.sh +++ b/.github/runner-scale-sets/query-regression/ecs-image/bootstrap-runner-host.sh @@ -161,6 +161,7 @@ apt-get install -y --no-install-recommends \ step "Create runner user (${RUNNER_UID}:${RUNNER_GID}) and environment" getent group "${RUNNER_GID}" > /dev/null || groupadd -g "${RUNNER_GID}" runner id -u runner > /dev/null 2>&1 || useradd -u "${RUNNER_UID}" -g "${RUNNER_GID}" -d /home/runner -s /bin/bash runner +usermod -aG docker runner chown -R "${RUNNER_UID}:${RUNNER_GID}" "${DATA_ROOT}/runner" echo 'PATH=/opt/cargo/bin:/usr/local/bin:/usr/bin:/bin' > "${DATA_ROOT}/runner/.env" chown "${RUNNER_UID}:${RUNNER_GID}" "${DATA_ROOT}/runner/.env" diff --git a/.github/runner-scale-sets/query-regression/ecs-image/build-ecs-image.py b/.github/runner-scale-sets/query-regression/ecs-image/build-ecs-image.py index f9ecb6b2333..2845612ebcd 100644 --- a/.github/runner-scale-sets/query-regression/ecs-image/build-ecs-image.py +++ b/.github/runner-scale-sets/query-regression/ecs-image/build-ecs-image.py @@ -137,6 +137,7 @@ docker cp "${{container}}:/home/runner" /home/runner # Runner identity mirrors the container image (UID/GID 1001). groupadd --gid 1001 runner 2>/dev/null || true useradd --uid 1001 --gid 1001 --home-dir /home/runner --shell /bin/bash runner 2>/dev/null || true +usermod -aG docker runner chown -R 1001:1001 /home/runner mkdir -p /opt/ephemeral-github-runner diff --git a/.github/scripts/query-regression-run.py b/.github/scripts/query-regression-run.py index d488cee1594..e59dcdfb709 100644 --- a/.github/scripts/query-regression-run.py +++ b/.github/scripts/query-regression-run.py @@ -21,10 +21,13 @@ import argparse import json import os import re +import shlex import signal import socket import subprocess +import sys import time +import uuid import urllib.request from dataclasses import dataclass from pathlib import Path @@ -130,6 +133,7 @@ class RunTarget: datanode_http_port: int datanode_data_dir: Path frontend_config: Path | None = None + containerized: bool = False def allocate_ports(n: int) -> list[int]: @@ -151,6 +155,7 @@ def make_target( root: Path, ports: list[int], frontend_config: Path | None = None, + containerized: bool = False, ) -> RunTarget: work_dir = root / name return RunTarget( @@ -167,6 +172,7 @@ def make_target( datanode_http_port=ports[3], datanode_data_dir=work_dir / "datanode-0" / "data", frontend_config=frontend_config, + containerized=containerized, ) @@ -258,7 +264,11 @@ def stop_component( procs: dict[tuple[str, str], subprocess.Popen[bytes]], ) -> None: proc = procs.pop((target.name, name), None) - if proc is None or proc.poll() is not None: + if proc is None: + return + if proc.poll() is not None: + if target.containerized and proc.returncode != 0: + raise RuntimeError(f"Docker target {target.name}/{name} exited with {proc.returncode}") return try: os.killpg(proc.pid, signal.SIGTERM) @@ -272,6 +282,8 @@ def stop_component( except ProcessLookupError: return proc.wait(timeout=20) + if target.containerized and proc.returncode not in (0, 128 + signal.SIGTERM): + raise RuntimeError(f"Docker target {target.name}/{name} cleanup failed: {proc.returncode}") def restart_component( @@ -284,9 +296,15 @@ def restart_component( def stop_all(targets: list[RunTarget], procs: dict[tuple[str, str], subprocess.Popen[bytes]]) -> None: + errors = [] for target in reversed(targets): for name in ("frontend", "datanode", "metasrv"): - stop_component(target, name, procs) + try: + stop_component(target, name, procs) + except Exception as err: + errors.append(err) + if errors: + raise RuntimeError(f"component cleanup failed: {errors}") from errors[0] def load_plan(fixture_generator: Path, case_path: Path) -> dict[str, Any]: @@ -313,8 +331,8 @@ def run_direct_case( ) -> int: ports = allocate_ports(16) targets = [ - make_target("base", base_bin, work_dir, ports[:8]), - make_target("candidate", candidate_bin, work_dir, ports[8:]), + make_target("base", base_bin, work_dir, ports[:8], containerized=bool(getattr(args, "base_image", ""))), + make_target("candidate", candidate_bin, work_dir, ports[8:], containerized=bool(getattr(args, "candidate_image", ""))), ] for target in targets: if target.work_dir.exists() and any(target.work_dir.iterdir()): @@ -407,6 +425,7 @@ def run_remote_case( work_dir, ports[:8], work_dir / "base" / "frontend-prom-store.toml", + containerized=bool(getattr(args, "base_image", "")), ), make_target( "candidate", @@ -414,6 +433,7 @@ def run_remote_case( work_dir, ports[8:], work_dir / "candidate" / "frontend-prom-store.toml", + containerized=bool(getattr(args, "candidate_image", "")), ), ] for target in targets: @@ -495,8 +515,8 @@ def run_otlp_case( raise ValueError("--otelgen-bin is required for otlp_trace_load") ports = allocate_ports(16) targets = [ - make_target("base", base_bin, work_dir, ports[:8]), - make_target("candidate", candidate_bin, work_dir, ports[8:]), + make_target("base", base_bin, work_dir, ports[:8], containerized=bool(getattr(args, "base_image", ""))), + make_target("candidate", candidate_bin, work_dir, ports[8:], containerized=bool(getattr(args, "candidate_image", ""))), ] for target in targets: if target.work_dir.exists() and any(target.work_dir.iterdir()): @@ -634,6 +654,106 @@ def write_failed_report(work_dir: Path, case_path: Path, error: Exception) -> No ) +def docker_target(image: str, root: Path, command: list[str]) -> int: + """Expose an image as a binary, including read-bench subcommands. + + The caller terminates a process group. Keep Docker clients in separate + sessions so cleanup can stop the container before SST inspection starts. + """ + name = f"query-regression-{uuid.uuid4().hex}" + + def interrupted(signum, _frame): + raise SystemExit(128 + signum) + + previous = {sig: signal.signal(sig, interrupted) for sig in (signal.SIGTERM, signal.SIGINT)} + try: + subprocess.run([ + "docker", "create", "--name", name, "--network", "host", + "--user", f"{os.getuid()}:{os.getgid()}", + "--volume", f"{root}:{root}", "--workdir", str(root), + "--entrypoint", "/greptime/bin/greptime", image, *command, + ], check=True, stdout=subprocess.DEVNULL, start_new_session=True) + attached = subprocess.run( + ["docker", "start", "--attach", name], check=False, start_new_session=True, + ) + if attached.returncode != 0: + return attached.returncode + # docker start's status is not the contract for the container's exit code. + result = subprocess.run( + ["docker", "inspect", "--format", "{{.State.ExitCode}}", name], + check=True, capture_output=True, text=True, start_new_session=True, + ) + return int(result.stdout.strip()) + finally: + for sig in previous: + signal.signal(sig, signal.SIG_IGN) + try: + subprocess.run( + ["docker", "stop", "--time", "5", name], check=False, + stdout=subprocess.DEVNULL, timeout=8, start_new_session=True, + ) + except subprocess.TimeoutExpired: + # Force-removal below still waits for the container to stop. + pass + finally: + try: + subprocess.run( + ["docker", "rm", "--force", "--volumes", name], check=True, + stdout=subprocess.DEVNULL, timeout=5, start_new_session=True, + ) + finally: + for sig, handler in previous.items(): + signal.signal(sig, handler) + + +def prepare_targets(args: argparse.Namespace) -> dict[str, Any]: + """Resolve images once and create binary-compatible launchers for all cases.""" + metadata = {} + images = {} + for name in ("base", "candidate"): + image = getattr(args, f"{name}_image") + ref = getattr(args, f"{name}_ref") + if not image: + metadata[name] = {"kind": "source", "ref": os.environ.get(f"VERIFIED_{name.upper()}_SHA") or ref} + continue + if sys.platform != "linux": + raise ValueError("Docker targets require Linux host networking and a local Docker daemon") + if image.startswith("-") or any(c.isspace() for c in image): + raise ValueError(f"invalid {name} image reference: {image!r}") + if image not in images: + result = subprocess.run( + ["docker", "image", "inspect", image], check=False, capture_output=True, text=True, + ) + if result.returncode != 0: + subprocess.run(["docker", "pull", image], check=True) + result = subprocess.run( + ["docker", "image", "inspect", image], check=True, capture_output=True, text=True, + ) + images[image] = json.loads(result.stdout)[0] + info = images[image] + image_id = info["Id"] + if not re.fullmatch(r"sha256:[0-9a-f]{64}", image_id): + raise ValueError(f"invalid Docker image ID: {image_id!r}") + args.work_dir = args.work_dir.resolve() + if ":" in str(args.work_dir): + raise ValueError("Docker target work directory cannot contain ':'") + launchers = args.work_dir / ".targets" + launchers.mkdir(parents=True, exist_ok=True) + launcher = launchers / name + command = [sys.executable, str(Path(__file__).resolve()), + "docker-target", image_id, str(args.work_dir)] + launcher.write_text("#!/bin/sh\nexec " + shlex.join(command) + ' "$@"\n', encoding="utf-8") + launcher.chmod(0o755) + setattr(args, f"{name}_bin", launcher) + setattr(args, f"{name}_ref", f"{image} ({image_id})") + metadata[name] = { + "kind": "docker", "image": image, "image_id": image_id, + "repo_digests": info.get("RepoDigests", []), + "network": "host", "user": f"{os.getuid()}:{os.getgid()}", + } + return metadata + + def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--cases", action="append", help="'all', 'heavy', or comma/space separated case paths") @@ -663,6 +783,8 @@ def main() -> int: parser.add_argument("--base-ref", default=os.environ.get("BASE_REF", "")) parser.add_argument("--candidate-ref", default=os.environ.get("CANDIDATE_REF", "")) parser.add_argument("--github-output", default=os.environ.get("GITHUB_OUTPUT")) + parser.add_argument("--base-image", default=os.environ.get("BASE_IMAGE", "")) + parser.add_argument("--candidate-image", default=os.environ.get("CANDIDATE_IMAGE", "")) args = parser.parse_args() try: cases = split_cases(args.cases or [os.environ.get("CASE_PATHS", "all")]) @@ -671,6 +793,12 @@ def main() -> int: append_github_output(args.github_output, 1) return 0 + preparation_error = None + metadata = {} + try: + metadata = prepare_targets(args) + except Exception as err: + preparation_error = err reports: list[Path] = [] status = 0 for case in cases: @@ -678,11 +806,18 @@ def main() -> int: work_dir = args.work_dir / case_slug(case_path) reports.append(work_dir / "query-regression-report.json") try: + if preparation_error is not None: + raise preparation_error case_status = run_case(args, case_path, work_dir) except Exception as err: # noqa: BLE001 - preserve an aggregate report for the summary step print(f"error: query regression case {case_path}: {err}", flush=True) write_failed_report(work_dir, case_path, err) case_status = 1 + report_path = reports[-1] + if (args.base_image or args.candidate_image) and report_path.exists(): + report = json.loads(report_path.read_text(encoding="utf-8")) + report["execution_targets"] = metadata + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") if case_status != 0: status = case_status or 1 @@ -695,4 +830,6 @@ def main() -> int: if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] == "docker-target": + raise SystemExit(docker_target(sys.argv[2], Path(sys.argv[3]), sys.argv[4:])) raise SystemExit(main()) diff --git a/.github/workflows/query-regression.yml b/.github/workflows/query-regression.yml index 6543281409d..cc182d896b4 100644 --- a/.github/workflows/query-regression.yml +++ b/.github/workflows/query-regression.yml @@ -26,6 +26,16 @@ on: description: Candidate ref/sha to build; reusable release calls must provide an immutable full SHA required: true type: string + base_image: + description: Base Docker image tag/digest (empty builds base_ref from source) + required: false + type: string + default: "" + candidate_image: + description: Candidate Docker image tag/digest (empty builds candidate_ref from source) + required: false + type: string + default: "" cargo_profile: description: Cargo profile to build base and candidate binaries with required: false @@ -80,6 +90,16 @@ on: description: Runner HTTP timeout seconds required: true default: "300" + base_image: + description: Base Docker image tag/digest (empty builds base_ref from source) + required: false + type: string + default: "" + candidate_image: + description: Candidate Docker image tag/digest (empty builds candidate_ref from source) + required: false + type: string + default: "" cargo_profile: description: Cargo profile to build base and candidate binaries with required: true @@ -214,6 +234,8 @@ jobs: PR_NUMBER: ${{ inputs.pr_number }} HEAD_REPO: ${{ inputs.head_repo }} BASE_REPO: ${{ inputs.base_repo }} + BASE_IMAGE: ${{ inputs.base_image }} + CANDIDATE_IMAGE: ${{ inputs.candidate_image }} BASE_REF: ${{ inputs.base_ref }} CANDIDATE_REF: ${{ inputs.candidate_ref || github.ref }} EVENT_MERGE_SHA: ${{ inputs.pr_number != '' && inputs.candidate_ref || '' }} @@ -224,6 +246,16 @@ jobs: EXPECTED_RUNNER_UID: ${{ vars.QUERY_REGRESSION_RUNNER_UID || '1001' }} EXPECTED_RUNNER_GID: ${{ vars.QUERY_REGRESSION_RUNNER_GID || '1001' }} steps: + - name: Validate image target admission + run: | + if [[ "${PR_ADMISSION}" == "true" && ( -n "${BASE_IMAGE}" || -n "${CANDIDATE_IMAGE}" ) ]]; then + echo "PR admission requires source targets for verified commit attribution." >&2 + exit 1 + fi + if [[ -n "${BASE_IMAGE}" || -n "${CANDIDATE_IMAGE}" ]]; then + docker info >/dev/null + fi + - name: Report provisioned ECS runner if: ${{ needs.provision.outputs.instance_id != '' }} shell: bash @@ -694,6 +726,7 @@ jobs: sccache --show-stats - name: Build base greptime + if: ${{ inputs.base_image == '' }} working-directory: src run: | set -euo pipefail @@ -733,7 +766,9 @@ jobs: run: | set -euo pipefail SECONDS=0 - cargo build --profile "${CARGO_PROFILE}" -p cmd --bin greptime + if [[ -z "${CANDIDATE_IMAGE}" ]]; then + cargo build --profile "${CARGO_PROFILE}" -p cmd --bin greptime + fi cargo build --profile "${CARGO_PROFILE}" -p cmd --bin query_perf_fixture --features dev-tools cargo build --profile "${CARGO_PROFILE}" -p cmd --bin query_regression_runner --features dev-tools candidate_build_elapsed="${SECONDS}" @@ -745,8 +780,10 @@ jobs: target_dir="debug" fi mkdir -p "${GITHUB_WORKSPACE}/query-regression-bins/candidate" - cp "${CARGO_TARGET_DIR}/${target_dir}/greptime" \ - "${GITHUB_WORKSPACE}/query-regression-bins/candidate/greptime" + if [[ -z "${CANDIDATE_IMAGE}" ]]; then + cp "${CARGO_TARGET_DIR}/${target_dir}/greptime" \ + "${GITHUB_WORKSPACE}/query-regression-bins/candidate/greptime" + fi cp "${CARGO_TARGET_DIR}/${target_dir}/query_perf_fixture" \ "${GITHUB_WORKSPACE}/query-regression-bins/candidate/query_perf_fixture" cp "${CARGO_TARGET_DIR}/${target_dir}/query_regression_runner" \ diff --git a/tests/perf/README.md b/tests/perf/README.md index 0361f598a3b..5a38f2f9156 100644 --- a/tests/perf/README.md +++ b/tests/perf/README.md @@ -495,18 +495,66 @@ query_regression_runner measure --case --fixture-generator ## GitHub Actions `.github/workflows/query-regression.yml` provides an opt-in CI entrypoint for -query regression runs. It builds its own binaries for now: +query regression runs. By default, it builds its own binaries: - base `greptime` from the PR base commit, or `workflow_dispatch` `base_ref` - candidate `greptime`, `query_perf_fixture`, and `query_regression_runner` from the PR merge ref/current candidate checkout - outer driver and summary formatter from the candidate checkout -The workflow builds base and candidate `greptime` as normal release-equivalent -binaries. Candidate `query_perf_fixture` and `query_regression_runner` are the +For source targets, the workflow builds `greptime` as a normal release-equivalent +binary. Candidate `query_perf_fixture` and `query_regression_runner` are the extra head-side helpers; `finalize-remote` uses candidate `greptime datanode parquetbench/scanbench` as the read-bench tool against each target's data directory. +### Docker image targets + +`base_image` and `candidate_image` are independent optional inputs to manual +and reusable query-regression workflows. Leave an input empty to build that +side from source, or set it to a GreptimeDB image tag/digest to skip its server +build. All four source/image combinations are supported. PR slash-command runs +continue to use verified source revisions; image overrides are rejected for PR +admission so reports cannot attribute an image to a different commit. + +The candidate checkout still supplies cases and builds `query_perf_fixture` +and `query_regression_runner`, even with two image targets. `base_ref` and +`candidate_ref` remain required for reusable calls. Remote-write read-bench +commands use the candidate target, including its image when configured. + +The local driver accepts `--base-image` / `--candidate-image` (or `BASE_IMAGE` / +`CANDIDATE_IMAGE`). An image overrides that side's `--*-bin`. For example: + +```bash +python3 .github/scripts/query-regression-run.py \ + --candidate-src . \ + --base-image greptime/greptimedb:v1.3.0 \ + --candidate-bin /absolute/path/to/candidate/greptime \ + --fixture-generator /absolute/path/to/query_perf_fixture \ + --runner /absolute/path/to/query_regression_runner \ + --cases tests/perf/query_cases/smoke_direct_sst/case.toml \ + --summary-script .github/scripts/query-regression-summary.py +``` + +Image targets require Linux and a local Docker daemon accessible to the runner +user; the workflow checks access before building. The ECS image builder and +manual host bootstrap add the runner to the Docker group. Existing hosts need +an administrator to provision this access and restart the runner service, or +a rebuilt ECS image, before selecting image targets. +Images must expose the GreptimeDB binary at `/greptime/bin/greptime` and support +the commands and data formats used by the selected cases. Images are pulled +when absent locally, then pinned to their inspected image ID for the entire +run; use a registry digest for repeatability across hosts. Reports include +requested images, resolved IDs and repository digests alongside source commit +identities. + +Containers use host networking and the runner's UID/GID. The run work directory +is bind-mounted at the same absolute path, preserving generated configuration, +SST materialization, logs and post-stop storage inspection. No additional CPU +or memory limits are imposed. Keep host resources and workloads comparable; +container execution and image build options can still affect timing. Use a +fresh work directory for each run. Container cleanup completes before the +lifecycle proceeds to storage inspection or a component restart. + The workflow runs when an allowlisted repository admin comments `/query-regression` on a non-draft PR. It does not rerun on pushes, ready-for-review, or reopen events. `/query-regression` runs the nine routine diff --git a/tests/perf/test_query_regression_runner_compaction_toctou.py b/tests/perf/test_query_regression_runner_compaction_toctou.py index 58f7f31b7fa..120e74d22f4 100644 --- a/tests/perf/test_query_regression_runner_compaction_toctou.py +++ b/tests/perf/test_query_regression_runner_compaction_toctou.py @@ -13,15 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Regression coverage for the outer remote-write lifecycle.""" +"""Regression coverage for remote-write and Docker target lifecycles.""" import importlib.util import json import sys +import signal +import subprocess import tempfile import unittest from pathlib import Path -from unittest.mock import patch +from types import SimpleNamespace +from unittest.mock import Mock, patch RUNNER_PATH = Path(__file__).resolve().parents[2] / ".github/scripts/query-regression-run.py" @@ -110,5 +113,129 @@ class RemoteWriteLifecycleTest(unittest.TestCase): self.assertIn("stop:candidate:frontend", events) +class DockerTargetTest(unittest.TestCase): + image_id = "sha256:" + "a" * 64 + + def test_independent_target_selection_and_image_identity(self) -> None: + for base_image, candidate_image in (("", ""), ("image:v1", ""), ("", "image:v1"), ("image:v1", "image:v1")): + with self.subTest(base=base_image, candidate=candidate_image), tempfile.TemporaryDirectory() as tmp: + args = SimpleNamespace( + base_image=base_image, candidate_image=candidate_image, + base_bin=Path("base"), candidate_bin=Path("candidate"), + base_ref="base-sha", candidate_ref="candidate-sha", work_dir=Path(tmp), + ) + result = SimpleNamespace(returncode=0, stdout=json.dumps([ + {"Id": self.image_id, "RepoDigests": ["image@sha256:abc"]}, + ])) + with patch.object(runner.subprocess, "run", return_value=result) as run: + metadata = runner.prepare_targets(args) + self.assertEqual(run.call_count, int(bool(base_image or candidate_image))) + for name, image in (("base", base_image), ("candidate", candidate_image)): + if image: + launcher = getattr(args, f"{name}_bin") + self.assertTrue(launcher.stat().st_mode & 0o111) + self.assertIn(self.image_id, launcher.read_text()) + self.assertIn('"$@"', launcher.read_text()) + self.assertEqual(metadata[name]["image"], image) + self.assertEqual(metadata[name]["image_id"], self.image_id) + else: + self.assertEqual(getattr(args, f"{name}_bin"), Path(name)) + self.assertEqual(metadata[name], {"kind": "source", "ref": f"{name}-sha"}) + + def test_default_source_run_preserves_report_and_refs(self) -> None: + payload = '{"status":"ok","targets":[],"thresholds":[]}\n' + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + def run_case(args, _case_path, work_dir): + self.assertEqual((args.base_image, args.candidate_image), ("", "")) + self.assertEqual((args.base_ref, args.candidate_ref), ("main", "feature")) + self.assertEqual(args.cargo_profile, "nightly") + work_dir.mkdir(parents=True) + (work_dir / "query-regression-report.json").write_text(payload) + return 0 + argv = ["runner", "--cases", "case.toml", "--work-dir", str(root), + "--base-ref", "main", "--candidate-ref", "feature"] + with (patch.dict(runner.os.environ, {}, clear=True), + patch.object(sys, "argv", argv), + patch.object(runner, "run_case", side_effect=run_case), + patch.object(runner, "write_summary", return_value=0), + patch.object(runner.subprocess, "run") as subprocess_run): + self.assertEqual(runner.main(), 0) + subprocess_run.assert_not_called() + reports = list(root.rglob("query-regression-report.json")) + self.assertEqual(len(reports), 1) + self.assertEqual(reports[0].read_bytes(), payload.encode()) + + def test_missing_image_is_pulled_and_inspected(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + args = SimpleNamespace(base_image="image:v1", candidate_image="", base_ref="", candidate_ref="", work_dir=Path(tmp)) + results = [SimpleNamespace(returncode=1), SimpleNamespace(returncode=0), + SimpleNamespace(stdout=json.dumps([{"Id": self.image_id}]))] + with patch.object(runner.subprocess, "run", side_effect=results) as run: + runner.prepare_targets(args) + self.assertEqual([call.args[0][:2] for call in run.call_args_list], + [["docker", "image"], ["docker", "pull"], ["docker", "image"]]) + + def test_container_exit_code_and_cleanup(self) -> None: + commands = [] + def run(command, **kwargs): + commands.append(command) + self.assertTrue(kwargs["start_new_session"]) + return SimpleNamespace(returncode=0, stdout="42\n") + with patch.object(runner.subprocess, "run", side_effect=run): + status = runner.docker_target(self.image_id, Path("/tmp/work space"), ["datanode", "scanbench", "--help"]) + self.assertEqual(status, 42) + create = commands[0] + self.assertIn("/tmp/work space:/tmp/work space", create) + self.assertEqual(create[-4:], [self.image_id, "datanode", "scanbench", "--help"]) + self.assertEqual([cmd[1] for cmd in commands], ["create", "start", "inspect", "stop", "rm"]) + self.assertEqual(commands[-1][-1], create[3]) + + def test_signal_and_failed_start_both_remove_container(self) -> None: + for interruption in (True, False): + commands = [] + def run(command, **kwargs): + commands.append(command) + if command[1] == "start": + if interruption: + signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) + raise subprocess.CalledProcessError(1, command) + return SimpleNamespace(returncode=0) + previous = signal.getsignal(signal.SIGTERM) + with self.subTest(interruption=interruption), patch.object(runner.subprocess, "run", side_effect=run): + with self.assertRaises(SystemExit if interruption else subprocess.CalledProcessError): + runner.docker_target(self.image_id, Path("/tmp/work"), ["metasrv", "start"]) + self.assertEqual([cmd[1] for cmd in commands], ["create", "start", "stop", "rm"]) + self.assertEqual(signal.getsignal(signal.SIGTERM), previous) + + + def test_stop_timeout_still_force_removes(self) -> None: + commands = [] + def run(command, **kwargs): + commands.append(command) + if command[1] == "stop": + raise subprocess.TimeoutExpired(command, 8) + return SimpleNamespace(returncode=0, stdout="0") + with patch.object(runner.subprocess, "run", side_effect=run): + self.assertEqual(runner.docker_target(self.image_id, Path("/tmp/work"), ["--version"]), 0) + self.assertEqual(commands[-1][1], "rm") + + def test_failed_container_cleanup_is_not_ignored(self) -> None: + target = runner.make_target("base", Path("launcher"), Path("/tmp/work"), list(range(8)), containerized=True) + proc = Mock() + proc.poll.return_value = None + proc.returncode = 1 + with patch.object(runner.os, "killpg"): + with self.assertRaisesRegex(RuntimeError, "cleanup failed"): + runner.stop_component(target, "datanode", {("base", "datanode"): proc}) + + def test_cleanup_failure_does_not_skip_other_components(self) -> None: + target = runner.make_target("base", Path("launcher"), Path("/tmp/work"), list(range(8)), containerized=True) + with patch.object(runner, "stop_component", side_effect=[RuntimeError("failed"), None, None]) as stop: + with self.assertRaisesRegex(RuntimeError, "component cleanup failed"): + runner.stop_all([target], {}) + self.assertEqual([call.args[1] for call in stop.call_args_list], ["frontend", "datanode", "metasrv"]) + + if __name__ == "__main__": unittest.main()