from __future__ import annotations import hashlib import json import os import shutil import subprocess from dataclasses import asdict, dataclass from datetime import UTC, datetime from pathlib import Path from typing import Sequence class RDockPipelineError(RuntimeError): """Raised for actionable pipeline failures.""" def _candidate_rbt_roots( preferred: str | Path | None = None, executable: str | None = None, env: dict[str, str] | None = None, ) -> list[Path]: merged_env = os.environ if env is None else env candidates: list[Path] = [] def _push(path: str | Path | None) -> None: if not path: return p = Path(path) if p not in candidates: candidates.append(p) _push(preferred) _push(merged_env.get("RBT_ROOT")) rdock_root = merged_env.get("RDOCK_ROOT") if rdock_root: _push(rdock_root) _push(Path(rdock_root) / "share") _push(Path(rdock_root) / "share" / "rdock") conda_prefix = merged_env.get("CONDA_PREFIX") if conda_prefix: _push(Path(conda_prefix) / "share" / "rdock") _push(Path(conda_prefix) / "share") _push(conda_prefix) resolved_executable = executable if executable and not os.path.sep in executable: resolved_executable = shutil.which(executable) or executable if resolved_executable: prefix = Path(resolved_executable).resolve().parent.parent _push(prefix / "share" / "rdock") _push(prefix / "share") _push(prefix) for candidate in ( Path("/opt/homebrew/opt/rdock/share"), Path("/usr/local/opt/rdock/share"), Path("/usr/share/rdock"), Path("/usr/local/share/rdock"), ): _push(candidate) cellar = Path("/opt/homebrew/Cellar/rdock") if cellar.exists(): for candidate in sorted(cellar.glob("*/share"), reverse=True): _push(candidate) return candidates def _is_valid_rbt_root(path: Path) -> bool: return (path / "data" / "RbtElements.dat").exists() def resolve_rbt_root( preferred: str | Path | None = None, executable: str | None = None, env: dict[str, str] | None = None, ) -> str | None: for candidate in _candidate_rbt_roots(preferred=preferred, executable=executable, env=env): if _is_valid_rbt_root(candidate): return str(candidate.resolve()) return None def resolve_dock_prm_path( preferred_rbt_root: str | Path | None = None, executable: str | None = None, env: dict[str, str] | None = None, ) -> Path | None: root = resolve_rbt_root(preferred=preferred_rbt_root, executable=executable, env=env) candidates: list[Path] = [] if root: root_path = Path(root) candidates.extend([root_path / "data" / "scripts" / "dock.prm", root_path / "data" / "dock.prm"]) candidates.append(Path("dock.prm")) for candidate in candidates: if candidate.exists() and candidate.is_file() and candidate.stat().st_size > 0: return candidate.resolve() return None def sha256_file(path: str | Path) -> str: source = Path(path) h = hashlib.sha256() with source.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): h.update(chunk) return h.hexdigest() def require_file(path: str | Path, label: str) -> Path: p = Path(path) if not p.exists(): raise RDockPipelineError(f"Missing {label}: {p}") if p.is_file() and p.stat().st_size == 0: raise RDockPipelineError(f"Empty {label}: {p}") return p def require_executable(name: str) -> str: resolved = shutil.which(name) if not resolved: raise RDockPipelineError( f"Required executable `{name}` was not found on PATH. Install rDock/OpenBabel " "and ensure RBT_ROOT/RBT_HOME/library paths are configured before running." ) return resolved def probe_version(executable: str) -> str: for args in ([executable, "--version"], [executable, "-version"], [executable, "-h"]): try: proc = subprocess.run(args, check=False, capture_output=True, text=True, timeout=10) except Exception: continue text = "\n".join([proc.stdout or "", proc.stderr or ""]).strip() if text: for line in text.splitlines(): probe = line.strip() if probe and set(probe) != {"*"}: return probe[:240] return text.splitlines()[0][:240] return "unavailable" @dataclass class CommandRecord: stage: str command: list[str] cwd: str start_time: str end_time: str exit_code: int stdout_log: str stderr_log: str def to_dict(self) -> dict[str, object]: return asdict(self) class CommandRunner: def __init__(self, command_log: str | Path) -> None: self.command_log = Path(command_log) self.command_log.parent.mkdir(parents=True, exist_ok=True) self.records: list[CommandRecord] = [] def run( self, stage: str, command: Sequence[str], cwd: str | Path, stdout_log: str | Path, stderr_log: str | Path, timeout: int | None = None, env: dict[str, str] | None = None, ) -> CommandRecord: cwd_path = Path(cwd) stdout_path = Path(stdout_log) stderr_path = Path(stderr_log) stdout_path.parent.mkdir(parents=True, exist_ok=True) stderr_path.parent.mkdir(parents=True, exist_ok=True) start = datetime.now(UTC).isoformat() merged_env = os.environ.copy() if env: merged_env.update(env) try: proc = subprocess.run( list(command), cwd=str(cwd_path), check=False, capture_output=True, text=True, timeout=timeout, env=merged_env, ) stdout = proc.stdout or "" stderr = proc.stderr or "" rc = int(proc.returncode) except subprocess.TimeoutExpired as exc: stdout = exc.stdout if isinstance(exc.stdout, str) else "" stderr = (exc.stderr if isinstance(exc.stderr, str) else "") + f"\nTIMEOUT after {timeout}s" rc = 124 end = datetime.now(UTC).isoformat() stdout_path.write_text(stdout, encoding="utf-8") stderr_path.write_text(stderr, encoding="utf-8") rec = CommandRecord( stage=stage, command=list(command), cwd=str(cwd_path), start_time=start, end_time=end, exit_code=rc, stdout_log=str(stdout_path), stderr_log=str(stderr_path), ) self.records.append(rec) with self.command_log.open("a", encoding="utf-8") as handle: handle.write(json.dumps(rec.to_dict(), sort_keys=True) + "\n") return rec def fail_if_bad_command(record: CommandRecord, expected: str) -> None: stdout = Path(record.stdout_log).read_text(encoding="utf-8", errors="ignore") if record.stdout_log else "" stderr = Path(record.stderr_log).read_text(encoding="utf-8", errors="ignore") if record.stderr_log else "" text = f"{stdout}\n{stderr}" error_markers = ( "RBT_FILE_READ_ERROR", "RBT_ERROR", "BAD_RECEPTOR_FILE", "Error opening", "Segmentation fault", "Fatal", ) if record.exit_code == 0 and not any(marker.lower() in text.lower() for marker in error_markers): return raise RDockPipelineError( f"{expected} failed with exit code {record.exit_code}. Command: {' '.join(record.command)}. " f"See stdout log: {record.stdout_log}; stderr log: {record.stderr_log}. " f"Last diagnostic: {text.strip()[-1200:]}" )