Alien-libhisto

 view release on metacpan or  search on metacpan

bundled/tools/scripts/test_container.py  view on Meta::CPAN

        f"ctest --test-dir {build_dir_name} -j{effective_jobs} --output-on-failure",
    ]

    if full:
        test_commands.append(
            "if command -v python3 >/dev/null 2>&1 && python3 -c 'import setuptools' >/dev/null 2>&1 && [ -f bindings/python/setup.py ]; then "
            "  echo '==> Running Python bindings test in container...' && "
            "  (cd bindings/python && rm -rf build histo/*.so && python3 setup.py build_ext --inplace && PYTHONPATH=. python3 -m unittest discover -s tests -v) && "
            "  (rm -rf bindings/python/build bindings/python/histo/*.so 2>/dev/null || true); "
            "fi"
        )
        test_commands.append(
            "if command -v perl >/dev/null 2>&1 && perl -MAlien::Build::MM -e 1 >/dev/null 2>&1 && perl -MAlien::cmake3 -e 1 >/dev/null 2>&1 && [ -f bindings/perl/Alien-libhisto/Makefile.PL ]; then "
            "  echo '==> Running Perl bindings test in container...' && "
            "  (cd bindings/perl/Alien-libhisto && perl Makefile.PL && make && make test && (make realclean 2>/dev/null || true)) && "
            "  (cd bindings/perl/Math-Histo && perl Makefile.PL && make && make test && (make realclean 2>/dev/null || true)); "
            "fi"
        )

    # Post-clean and restore ownership to host user so zero root-owned artifacts remain
    post_chown_cmd = f"chown -R {os.getuid()}:{os.getgid()} /workspace 2>/dev/null || true"
    test_commands.append(pre_clean_cmd)
    test_commands.append(post_chown_cmd)

    container_script = " && ".join(test_commands)

    docker_cmd = [
        engine,
        "run",
        "--rm",
        "--ulimit", "core=-1",
        "-e", "DEBIAN_FRONTEND=noninteractive",
    ]
    if config.get("platform"):
        docker_cmd.extend(["--platform", config["platform"]])
    docker_cmd.extend([
        "-v", f"{repo_root}:/workspace",
        "-w", "/workspace",
        image,
        "sh", "-c", container_script,
    ])

    log(f"Starting target '{target_name}' [{config['description']}] using {engine} ({image})...")
    t0 = time.time()
    try:
        exec_container_cmd(docker_cmd, check=True)
    except subprocess.CalledProcessError as err:
        elapsed = time.time() - t0
        log_error(f"Target '{target_name}' FAILED with exit code {err.returncode} after {elapsed:.2f}s.")

        if err.returncode in [139, 134, 132, 136, 2, 1]:
            sig_name = {139: "SIGSEGV (Segmentation Fault)", 134: "SIGABRT (Abort)", 132: "SIGILL (Illegal Instruction)", 136: "SIGFPE (Floating Point Exception)"}.get(err.returncode, f"Error {err.returncode}")
            print("\n" + "=" * 75)
            log_error(f"AUTOMATED CRASH INSPECTION & POST-MORTEM DIAGNOSTICS: {sig_name}")
            print("=" * 75)
            print(f"Target Architecture : {config.get('arch')} ({config.get('bits', 64)}-bit {config.get('endian', 'little')}-endian)")
            print(f"Container Image     : {image} ({config.get('platform', 'native')})")
            print(f"Build Directory     : {build_dir_name}")
            print("=" * 75)

            debug_script = (
                "echo '--- Active System & Core Pattern ---' && "
                "uname -a && "
                "cat /proc/sys/kernel/core_pattern 2>/dev/null || true && "
                "echo '--- Core Dump Search & GDB Backtrace ---' && "
                "CORE_FILE=$(find /tmp /var/crash \"" + build_dir_name + "\" -name 'core*' -o -name '*.core' 2>/dev/null | head -n 1) && "
                "if [ -n \"$CORE_FILE\" ]; then "
                "  echo \"Found Core Dump: $CORE_FILE\" && "
                "  BIN_FILE=$(find " + build_dir_name + " -type f -executable -not -name '*.sh' 2>/dev/null | head -n 1) && "
                "  if command -v gdb >/dev/null 2>&1 && [ -n \"$BIN_FILE\" ]; then "
                "    echo \"Inspecting with GDB against binary: $BIN_FILE...\" && "
                "    gdb --batch -ex 'set pagination off' -ex 'bt full' -ex 'thread apply all bt full' \"$BIN_FILE\" \"$CORE_FILE\" 2>/dev/null || true; "
                "  fi; "
                "else "
                "  echo 'Note: No local core file saved in container volume (host kernel may handle core dumps via systemd-coredump or kernel pipe).'; "
                "fi && "
                "if [ \"" + str(err.returncode) + "\" = \"139\" ] && [ \"" + str(is_foreign_arch(config.get("arch", ""))) + "\" = \"True\" ]; then "
                "  echo '--- QEMU Emulation Note ---' && "
                "  echo 'A SIGSEGV during multi-threaded build under QEMU user-mode emulation is typically caused by QEMU binfmt thread limit exhaustion.' && "
                "  echo 'Remedy: Retry with lower concurrency (e.g. -j 2 or -j 1) or upgrade host qemu-user-static.'; "
                "fi"
            )
            inspect_cmd = [engine, "run", "--rm", "-e", "DEBIAN_FRONTEND=noninteractive"]
            if config.get("platform"):
                inspect_cmd.extend(["--platform", config["platform"]])
            inspect_cmd.extend([
                "-v", f"{repo_root}:/workspace",
                "-w", "/workspace",
                image,
                "sh", "-c", debug_script
            ])
            try:
                exec_container_cmd(inspect_cmd, timeout=30)
            except Exception:
                pass
            print("=" * 75 + "\n")
        raise err
    finally:
        try:
            exec_container_cmd([engine, "run", "--rm", "-v", f"{repo_root}:/workspace", "alpine:latest", "sh", "-c", post_chown_cmd], timeout=15)
        except Exception:
            pass

    elapsed = time.time() - t0
    log_success(f"Target '{target_name}' PASSED in {elapsed:.2f}s")
    return True


def main():
    parser = argparse.ArgumentParser(
        description="libhisto Multi-Architecture & Portability Test Runner"
    )
    parser.add_argument(
        "-t", "--target",
        default="musl",
        help="Target profile name, alias, 'all', or 'matrix' (default: musl)"
    )
    parser.add_argument(
        "--engine",
        choices=["auto", "docker", "podman"],
        default="auto",
        help="Container runtime engine (default: auto-detect)"
    )
    parser.add_argument(
        "--full",
        action="store_true",
        help="Run full test suite (Core C + Python & Perl bindings) inside the target"
    )
    parser.add_argument(
        "-j", "--jobs",
        type=int,
        default=os.cpu_count() or 4,
        help="Number of parallel compilation jobs"
    )
    parser.add_argument(
        "--build-type",
        default="Release",
        choices=["Release", "Debug"],
        help="CMake build type (default: Release)"
    )
    parser.add_argument(
        "--list",
        action="store_true",
        help="List available target architectures and profiles"
    )
    parser.add_argument(
        "--clean",
        action="store_true",
        help="Clean up container build directories"
    )



( run in 0.750 second using v1.01-cache-2.11-cpan-c32d3c3b8f1 )