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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
#!/usr/bin/env python3
# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause

"""Unified runner for Isaac Lab installation CI tests.

Modes

``docker``
    Build a clean-room Docker container and execute pytest inside it.
``native``
    Run pytest directly on the host (no Docker).

Examples

.. code-block:: bash

    # Run all tests inside Docker (Ubuntu 24.04)
    tools/run_install_ci.py docker

    # Run only pip tests with a custom base image
    tools/run_install_ci.py docker --base-image ubuntu:22.04 -- -vs -k "testname"

    # Run with GPU support (passes --gpus all to Docker)
    tools/run_install_ci.py docker --gpu

    # Filter by marker (e.g. only uv tests, only slow tests)
    tools/run_install_ci.py docker -- -m uv
    tools/run_install_ci.py docker --gpu -- -m "slow and gpu"

    # Filter by bug ID (dashes become underscores)
    tools/run_install_ci.py docker --gpu -- -m <bug-id>

    # Drop into a shell for debugging
    tools/run_install_ci.py docker --shell

    # Run natively (no Docker)
    tools/run_install_ci.py native -- -vs

    # Pass a pre-built wheel
    tools/run_install_ci.py docker --wheel /tmp/isaaclab-3.0.0-py3-none-any.whl
"""

from __future__ import annotations

import argparse
import os
import shutil
import subprocess
import sys
import time
import uuid
from pathlib import Path

_DIM = "\033[2m"
_MAGENTA = "\033[95m"
_RESET = "\033[0m"

# Controls whether run_cmd() streams output by default.
stream_output: bool = False


def run_cmd(
    args: list[str],
    *,
    cwd: str | Path | None = None,
    env: dict[str, str] | None = None,
    timeout: int = 600,
    check: bool = True,
    stream: bool | None = None,
) -> subprocess.CompletedProcess:
    """Run a command, merging *env* into the current environment.

    Args:
        args: Command and arguments to run.
        cwd: Working directory for the subprocess.
        env: Extra environment variables merged into the current environment.
        timeout: Timeout in seconds.
        check: Raise CalledProcessError on non-zero exit.
        stream: When True, stream stdout/stderr to the console in
            real time instead of capturing them.

    Returns:
        The CompletedProcess; raises CalledProcessError when *check* is
        True and return code != 0.
    """
    if stream is None:
        stream = stream_output
    merged_env = {**os.environ, **(env or {})}
    cmd_str = " ".join(str(a) for a in args)
    if stream:
        sys.stdout.write(f"{_MAGENTA}[COMMAND] {cmd_str}{_RESET}\n")
        sys.stdout.flush()
        t0 = time.monotonic()
        proc = subprocess.Popen(
            [str(a) for a in args],
            cwd=str(cwd) if cwd else None,
            env=merged_env,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
        )
        lines: list[str] = []
        try:
            for line in proc.stdout:
                lines.append(line)
                sys.stdout.write(f"{_DIM}{line}{_RESET}")
                sys.stdout.flush()
        except Exception:
            proc.kill()
            raise
        try:
            proc.wait(timeout=timeout)
        except subprocess.TimeoutExpired:
            proc.kill()
            proc.wait()
            raise
        elapsed = time.monotonic() - t0
        sys.stdout.write(f"{_MAGENTA}[{elapsed:.1f}s]{_RESET}\n")
        sys.stdout.flush()
        result = subprocess.CompletedProcess(
            args=proc.args,
            returncode=proc.returncode,
            stdout="".join(lines),
            stderr="",
        )
        if check and result.returncode != 0:
            raise subprocess.CalledProcessError(result.returncode, result.args, result.stdout, result.stderr)
        return result
    return subprocess.run(
        [str(a) for a in args],
        cwd=str(cwd) if cwd else None,
        env=merged_env,
        capture_output=True,
        text=True,
        timeout=timeout,
        check=check,
    )


def _find_repo_root() -> Path:
    """Walk up from CWD or this file to find the repo root."""
    for anchor in [Path.cwd(), Path(__file__).resolve().parent]:
        for parent in [anchor] + list(anchor.parents):
            if (parent / "isaaclab.sh").exists():
                return parent
    raise FileNotFoundError("Could not locate IsaacLab repository root")


# Docker mode


def _build_image(
    repo_root: Path,
    dockerfile: Path,
    image_tag: str,
    build_args: dict[str, str],
    no_cache: bool,
) -> int:
    """Build a Docker image, returning the exit code."""
    build_cmd = ["docker", "build", "--progress=plain"]
    for key, value in build_args.items():
        build_cmd.extend(["--build-arg", f"{key}={value}"])
    build_cmd.extend(["-f", str(dockerfile), "-t", image_tag])
    if no_cache:
        build_cmd.append("--no-cache")
    build_cmd.append(str(repo_root))
    result = run_cmd(build_cmd, check=False, stream=True)
    return result.returncode


def _prepare_results_dir(results_dir: str) -> Path:
    """Prepare a host directory for Docker-copied test results.

    Args:
        results_dir: Host directory where the JUnit XML file should be copied.

    Returns:
        Path to the expected host JUnit XML file.
    """
    results_abs = Path(results_dir).resolve()
    results_abs.mkdir(parents=True, exist_ok=True)

    # Keep the directory writable across repeated self-hosted runner jobs. The
    # actual XML is copied out with ``docker cp`` after the container exits, so
    # pytest never has to open a bind-mounted host file from inside Docker.
    try:
        results_abs.chmod(0o777)
    except OSError as exc:
        print(f"Warning: could not chmod results directory {results_abs}: {exc}", file=sys.stderr)

    results_xml = results_abs / "results.xml"
    if results_xml.exists() or results_xml.is_symlink():
        try:
            if results_xml.is_dir():
                shutil.rmtree(results_xml)
            else:
                results_xml.unlink()
        except OSError as exc:
            print(f"Warning: could not remove stale results file {results_xml}: {exc}", file=sys.stderr)

    return results_xml


def _copy_junit_xml(container_name: str, container_results_xml: str, host_results_xml: Path) -> None:
    """Copy JUnit XML from a completed Docker container to the host.

    Args:
        container_name: Name of the Docker container to copy from.
        container_results_xml: Path to the JUnit XML file inside the container.
        host_results_xml: Host path where the JUnit XML file should be stored.
    """
    copy_cmd = ["docker", "cp", f"{container_name}:{container_results_xml}", str(host_results_xml)]
    copy_result = run_cmd(copy_cmd, check=False, stream=True)
    if copy_result.returncode != 0:
        print(
            f"Warning: could not copy JUnit XML from {container_name}:{container_results_xml} to {host_results_xml}.",
            file=sys.stderr,
        )
        return

    try:
        host_results_xml.chmod(0o666)
    except OSError as exc:
        print(f"Warning: could not chmod results file {host_results_xml}: {exc}", file=sys.stderr)


def _cmd_docker(args: argparse.Namespace) -> int:
    """Build the Docker image and run tests inside the container based on *args*."""

    repo_root = _find_repo_root()

    _install_ci_dir = repo_root / "source" / "isaaclab" / "test" / "install_ci"
    dockerfile = _install_ci_dir / "Dockerfile.installci"
    image_tag = f"isaaclab-installci:{args.base_image.replace(':', '-').replace('/', '-')}"

    rc = _build_image(
        repo_root,
        dockerfile,
        image_tag,
        {"BASE_IMAGE": args.base_image},
        args.no_cache,
    )
    if rc != 0:
        print(f"Docker build failed (exit {rc})")
        return rc
    print(f"Docker image built: {image_tag}")

    host_results_xml: Path | None = None
    container_name: str | None = None
    container_results_xml = "/tmp/isaaclab-installci-results.xml"
    if args.results_dir:
        host_results_xml = _prepare_results_dir(args.results_dir)
        if not args.shell:
            container_name = f"isaaclab-installci-{os.getpid()}-{uuid.uuid4().hex[:8]}"

    # Run
    docker_run_cmd: list[str] = ["docker", "run"]
    if container_name:
        docker_run_cmd.extend(["--name", container_name])
    else:
        docker_run_cmd.append("--rm")
    docker_run_cmd.append("--network=host")

    if args.gpu:
        docker_run_cmd.extend(["--gpus", "all"])

    # Persist pip and uv caches across runs via named Docker volumes.
    # The container runs as the non-root 'isaaclab' user (uid 1000), so caches
    # must live under /home/isaaclab rather than /root.
    if not args.no_pip_cache:
        docker_run_cmd.extend(["-v", "isaaclab-install-ci-pip-cache:/home/isaaclab/.cache/pip"])
    if not args.no_uv_cache:
        docker_run_cmd.extend(["-v", "isaaclab-install-ci-uv-cache:/home/isaaclab/.cache/uv"])

    # Pass environment variables
    docker_run_cmd.extend(["-e", "OMNI_KIT_ACCEPT_EULA=Y"])
    docker_run_cmd.extend(["-e", "ACCEPT_EULA=Y"])

    if args.results_dir and args.shell and host_results_xml is not None:
        docker_run_cmd.extend(["-v", f"{host_results_xml.parent}:/tmp/results"])

    if args.wheel:
        wheel_abs = Path(args.wheel).resolve()
        container_wheel = f"/tmp/wheels/{wheel_abs.name}"
        docker_run_cmd.extend(["-v", f"{wheel_abs}:{container_wheel}:ro"])
        docker_run_cmd.extend(["-e", f"ISAACLAB_WHEEL={container_wheel}"])

    if args.shell:
        # Interactive debugging mode
        docker_run_cmd.extend(["-it", "--entrypoint", "bash", image_tag])
    else:
        # Test execution mode
        pytest_args = args.pytest_args or ["--tb=short"]
        if args.results_dir:
            pytest_args = [f"--junitxml={container_results_xml}"] + pytest_args
        docker_run_cmd.extend([image_tag] + pytest_args)

    print(f"{_MAGENTA}[COMMAND] {' '.join(docker_run_cmd)}{_RESET}")

    t0 = time.monotonic()
    try:
        ret = subprocess.call(docker_run_cmd, timeout=5400)
    except subprocess.TimeoutExpired:
        print("Docker run timed out after 90 minutes", file=sys.stderr)
        if container_name:
            run_cmd(["docker", "kill", container_name], check=False, stream=True)
        ret = 124
    finally:
        if container_name:
            if host_results_xml is not None:
                _copy_junit_xml(container_name, container_results_xml, host_results_xml)
            run_cmd(["docker", "rm", "-f", container_name], check=False, stream=True)
    elapsed = time.monotonic() - t0
    print(f"{_MAGENTA}[{elapsed:.1f}s]{_RESET}")
    return ret


# Native mode


def _cmd_native(args: argparse.Namespace) -> int:
    """Run tests directly on the host OS."""

    repo_root = _find_repo_root()
    test_dir = repo_root / "source" / "isaaclab" / "test" / "install_ci"

    env = os.environ.copy()
    if args.wheel:
        env["ISAACLAB_WHEEL"] = str(Path(args.wheel).resolve())

    pytest_args = args.pytest_args or ["--tb=short"]
    cmd = [sys.executable, "-m", "pytest"] + pytest_args

    print(f"{_MAGENTA}[COMMAND] {' '.join(cmd)}{_RESET}")

    t0 = time.monotonic()
    ret = subprocess.call(cmd, cwd=str(test_dir), env=env)
    elapsed = time.monotonic() - t0
    print(f"{_MAGENTA}[{elapsed:.1f}s]{_RESET}")
    return ret


# CLI


def main() -> int:
    """Parse CLI arguments and dispatch to the docker or native test runner.

    Returns:
        Exit code: 0 on success, non-zero on failure.
    """
    parser = argparse.ArgumentParser(
        description="Isaac Lab Installation CI test runner",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""\
docker options:
  --base-image IMAGE   Docker base image (default: ubuntu:24.04)
  --gpu                Pass --gpus all to docker run
  --shell              Drop into interactive bash instead of running tests
  --no-cache           Build Docker image without layer cache
  --no-pip-cache       Disable persistent pip cache volume
  --no-uv-cache        Disable persistent uv cache volume
  --results-dir DIR    Host directory for test results (auto-adds --junitxml)
  --wheel PATH         Path to pre-built isaaclab wheel file

native options:
  --wheel PATH         Path to pre-built isaaclab wheel file

pytest arguments:
  Pass pytest options after '--'. Without '--', defaults to '-sv --tb=short'.

  examples:
    %(prog)s docker                                          # run all tests in Docker
    %(prog)s docker --base-image ubuntu:22.04 -- -vs -k "testname"  # custom base image
    %(prog)s docker --gpu                                    # GPU support (--gpus all)
    %(prog)s docker --gpu -- -m uv                           # uv tests only
    %(prog)s docker --gpu -- -m conda                        # conda tests only
    %(prog)s docker --gpu -- -m "slow and gpu"               # combine markers with GPU
    %(prog)s docker --gpu -- -k <bug-id>                     # filter by bug ID
    %(prog)s docker --shell                                  # drop into shell for debugging
    %(prog)s native -- -vs                                   # run natively (no Docker)
    %(prog)s docker --wheel /tmp/isaaclab.whl                # pass a pre-built wheel
    %(prog)s docker -- --collect-only                        # list tests without running
""",
    )
    sub = parser.add_subparsers(dest="mode")

    # docker subcommand
    docker_p = sub.add_parser("docker", help="Build container and run tests inside Docker")
    docker_p.add_argument(
        "--base-image",
        default="ubuntu:24.04",
        help="Docker base image (default: ubuntu:24.04)",
    )
    docker_p.add_argument("--gpu", action="store_true", help="Pass --gpus all to docker run")
    docker_p.add_argument(
        "--shell", action="store_true", help="Drop into an interactive bash shell instead of running tests"
    )
    docker_p.add_argument("--no-cache", action="store_true", help="Build Docker image without cache")
    docker_p.add_argument("--no-pip-cache", action="store_true", help="Disable persistent pip cache volume")
    docker_p.add_argument("--no-uv-cache", action="store_true", help="Disable persistent uv cache volume")
    docker_p.add_argument(
        "--results-dir", type=str, default=None, help="Host directory for test results (auto-adds --junitxml)"
    )
    docker_p.add_argument("--wheel", type=str, default=None, help="Path to pre-built isaaclab wheel file")
    docker_p.add_argument("pytest_args", nargs="*", help="Arguments forwarded to pytest (use -- to separate)")

    # native subcommand
    native_p = sub.add_parser("native", help="Run tests directly on the host OS")
    native_p.add_argument("--wheel", type=str, default=None, help="Path to pre-built isaaclab wheel file")
    native_p.add_argument("pytest_args", nargs="*", help="Arguments forwarded to pytest (use -- to separate)")

    # If '--' is in sys.argv, split there so pytest args are captured correctly
    argv = sys.argv[1:]
    if "--" in argv:
        split_idx = argv.index("--")
        our_args = argv[:split_idx]
        pytest_extra = argv[split_idx + 1 :]
    else:
        our_args = argv
        pytest_extra = []

    args = parser.parse_args(our_args)

    # Merge any args after '--' into pytest_args
    if pytest_extra:
        args.pytest_args = (args.pytest_args or []) + pytest_extra

    if args.mode == "docker":
        if not shutil.which("docker"):
            print("Error: docker is not available on PATH", file=sys.stderr)
            return 1
        return _cmd_docker(args)
    elif args.mode == "native":
        return _cmd_native(args)
    else:
        parser.print_help()
        return 1


if __name__ == "__main__":
    raise SystemExit(main())