Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-20 09:34:02

0001 #!/usr/bin/env python3
0002 """Bounded checks of an already-built LFHCal stack. Never installs or submits jobs."""
0003 import argparse
0004 import math
0005 import os
0006 from pathlib import Path
0007 import shutil
0008 import signal
0009 import subprocess
0010 import sys
0011 import tempfile
0012 
0013 HERE = Path(__file__).resolve().parent
0014 
0015 STANDARD_EXECUTABLES = (
0016     "Convert",
0017     "DataPrep",
0018     "CalibrateData",
0019     "DataAna",
0020     "Display",
0021     "CompareCalib",
0022     "CompareAna",
0023     "CompareInjection",
0024     "HGCROCStudy",
0025     "CompareWaveform",
0026 )
0027 
0028 DECODER_EXECUTABLES = (
0029     ("HGCROC_Conversion", Path("HGCROC_Conversion")),
0030     ("ParseCalibSamples", Path("ParseCalibSamples")),
0031     ("CompareHGCROCCalib", Path("CompareHGCROCCalib")),
0032     ("EvaluateRecoEffi", Path("EvaluateRecoEffi")),
0033     ("h2g_run", Path("h2g_decode") / "h2g_run"),
0034 )
0035 
0036 
0037 class SmokeFailure(RuntimeError):
0038     pass
0039 
0040 
0041 def executable(value):
0042     path = shutil.which(str(value))
0043     if path is None:
0044         raise SmokeFailure(f"Executable not found or not executable: {value}")
0045     return str(Path(path).resolve())
0046 
0047 
0048 def run_check(label, command, *, cwd, timeout, env=None, marker=None):
0049     print(f"CHECK {label}", flush=True)
0050     try:
0051         with subprocess.Popen(command, cwd=cwd, env=env, text=True,
0052                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
0053                               start_new_session=(os.name == "posix")) as process:
0054             try:
0055                 output, _ = process.communicate(timeout=timeout)
0056             except subprocess.TimeoutExpired as error:
0057                 # ROOT launches root.exe as a child. Kill the entire isolated
0058                 # group so a timeout cannot leave that workload running.
0059                 if os.name == "posix":
0060                     try:
0061                         os.killpg(process.pid, signal.SIGKILL)
0062                     except ProcessLookupError:
0063                         pass
0064                 else:
0065                     process.kill()
0066                 process.communicate()
0067                 raise SmokeFailure(f"{label}: timed out after {timeout:g} seconds") from error
0068             returncode = process.returncode
0069     except OSError as error:
0070         raise SmokeFailure(f"{label}: {error}") from error
0071     if returncode != 0 or (marker and marker not in output):
0072         detail = output[-8000:]
0073         raise SmokeFailure(f"{label}: exit {returncode}; expected marker {marker!r}\n{detail}")
0074     print(f"PASS  {label}", flush=True)
0075     return output
0076 
0077 
0078 def positive_timeout(value):
0079     number = float(value)
0080     if not math.isfinite(number) or number <= 0:
0081         raise argparse.ArgumentTypeError("timeout must be finite and positive")
0082     return number
0083 
0084 
0085 def parse_args(argv=None):
0086     parser = argparse.ArgumentParser(description=__doc__)
0087     layout = parser.add_mutually_exclusive_group(required=True)
0088     layout.add_argument("--build-dir", type=Path,
0089                         help="CMake output directory containing the required programs and libLFHCAL")
0090     layout.add_argument("--bin-dir", type=Path,
0091                         help="explicit binary directory for a copied/deployed layout; requires --library")
0092     parser.add_argument("--library", type=Path,
0093                         help="exact libLFHCAL shared library (required with --bin-dir)")
0094     parser.add_argument("--root", default="root", help="ROOT executable, default: PATH root")
0095     parser.add_argument("--root-config", default="root-config", help="matching ROOT configuration executable")
0096     parser.add_argument("--decoder", action="store_true",
0097                         help="also require and start decoder-enabled programs and h2g_decode/h2g_run")
0098     parser.add_argument("--yall", metavar="EXECUTABLE",
0099                         help="optional readiness check only: run this yall-run executable with --version")
0100     parser.add_argument("--timeout", type=positive_timeout, default=30,
0101                         help="seconds per command (default: 30); timeouts fail the suite")
0102     args = parser.parse_args(argv)
0103     if args.bin_dir and not args.library:
0104         parser.error("--bin-dir requires --library; the runner does not guess an installation layout")
0105     return args
0106 
0107 
0108 def main(argv=None):
0109     args = parse_args(argv)
0110     try:
0111         binaries = (args.build_dir or args.bin_dir).resolve()
0112         if args.library:
0113             library = args.library.resolve()
0114         else:
0115             candidates = [binaries / name for name in ("libLFHCAL.so", "libLFHCAL.dylib")]
0116             present = [path for path in candidates if path.is_file()]
0117             if len(present) != 1:
0118                 raise SmokeFailure(f"Expected exactly one libLFHCAL.so/.dylib in {binaries}")
0119             library = present[0]
0120         for path in (library, library.parent / "libLFHCAL_rdict.pcm",
0121                      library.parent / "libLFHCAL.rootmap"):
0122             if not path.is_file() or path.stat().st_size == 0:
0123                 raise SmokeFailure(f"Missing or empty library/dictionary artifact: {path}")
0124         commands = [(name, executable(binaries / name)) for name in STANDARD_EXECUTABLES]
0125         if args.decoder:
0126             commands.extend((name, executable(binaries / relative))
0127                             for name, relative in DECODER_EXECUTABLES)
0128         root = executable(args.root)
0129         root_config = executable(args.root_config)
0130         yall = executable(args.yall) if args.yall else None
0131         print(f"Artifacts: {binaries}\nLibrary:   {library}\nROOT:      {root}", flush=True)
0132         # A clean working directory avoids source/build-tree ROOT autoload and
0133         # ensures every fixture is temporary. No LD_LIBRARY_PATH is injected.
0134         with tempfile.TemporaryDirectory(prefix="lfhcal-smoke-") as directory:
0135             work = Path(directory)
0136             version = run_check("ROOT dependency", [root_config, "--version"],
0137                                 cwd=work, timeout=args.timeout).strip()
0138             if not version:
0139                 raise SmokeFailure("root-config --version returned empty output")
0140             print(f"ROOT version: {version}", flush=True)
0141             for name, command in commands:
0142                 run_check(f"{name} startup", [command, "-h"], cwd=work,
0143                           timeout=args.timeout, marker="Usage:")
0144             if not args.decoder:
0145                 print("NOT REQUESTED: decoder-enabled startup checks (use --decoder)", flush=True)
0146             env = dict(os.environ, LFHCAL_SMOKE_LIBRARY=str(library),
0147                        LFHCAL_SMOKE_PAYLOAD=str(HERE / "payload.C"),
0148                        LFHCAL_SMOKE_FILE=str(work / "fixture.root"))
0149             for mode in ("write", "read"):
0150                 env["LFHCAL_SMOKE_MODE"] = mode
0151                 run_check(f"ROOT {mode} / calibration", [root, "-n", "-l", "-b", "-q",
0152                           str(HERE / "driver.C")], cwd=work, env=env,
0153                           timeout=args.timeout, marker=f"LFHCAL_SMOKE_OK: {mode}")
0154             if yall:
0155                 version = run_check("Yall readiness only", [yall, "--version"],
0156                                     cwd=work, timeout=args.timeout).strip()
0157                 if not version:
0158                     raise SmokeFailure("yall-run --version returned empty output")
0159                 print(f"Yall version: {version}", flush=True)
0160             else:
0161                 print("NOT REQUESTED: Yall readiness (use --yall /path/to/yall-run)", flush=True)
0162         print("PASS: baseline LFHCal smoke checks. No campaigns or batch jobs were run.")
0163         return 0
0164     except (SmokeFailure, OSError) as error:
0165         print(f"FAIL: {error}", file=sys.stderr)
0166         return 1
0167 
0168 
0169 if __name__ == "__main__":
0170     sys.exit(main())