File size: 7,888 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
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:]}"
    )