import glob
import os
import re
import shutil
import subprocess
import tempfile
import time
import uuid
import zipfile
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Optional, Tuple, Union
from haddock import log
from haddock.core.defaults import cns_exec_linux as CNS_EXEC
from haddock.libs.libsubprocess import CNSJob
from haddock.libs.libutil import parse_ncores
# =====================================================================#
# EXPLANATION #
# =====================================================================#
# `JOB_TYPE` is an environment variable that can be set to specify the
# type of job associated with a given VO. This is usually important for
# accounting purposes, as different job types may have different resources
# associated with it.
# There is an explanation about this in the user manual.
# =====================================================================#
JOB_TYPE = os.getenv("HADDOCK3_GRID_JOB_TYPE", "WeNMR")
MAX_RETRIES = 10
# Seconds to wait before retrying a failed submission, doubled after each
# retry up to SUBMIT_RETRY_MAX_DELAY (10 retries then cover ~37 minutes)
SUBMIT_RETRY_DELAY = 30
SUBMIT_RETRY_MAX_DELAY = 300
# Seconds between two status checks of the submitted jobs
POLL_INTERVAL = 30
# Number of models (CNS jobs) packed into one grid job, per module.
# Chosen from grid tests on the protein-protein docking example (#1768):
# smaller jobs return results faster, as the waiting time dominates.
MODELS_PER_JOB = {
"topoaa": 2,
"topocg": 2,
"rigidbody": 10,
"flexref": 2,
"emref": 2,
"emscoring": 2,
"mdref": 2,
"mdscoring": 2,
"cgtoaa": 2,
}
# Important patterns to adjust the paths in the `.inp` file
OUTPUT_PATTERN = r'\$output_\w+\s*=\s*"([^"]+)"|\$output_\w+\s*=\s*([^\s;]+)'
VAR_PATTERN = r"\(\$\s*[^=]*=(?!.?\$)(.*)\)" # https://regex101.com/r/dYqlZP/1
AT_PATTERN = r"@@(?!\$)(.*)"
[docs]
def ping_dirac() -> bool:
"""Ping the Dirac server to check if it's reachable."""
if not validate_dirac():
return False
result = subprocess.run(["dirac-proxy-info"], capture_output=True)
if result.returncode != 0:
log.error(f"Dirac proxy info failed: {result.stderr.decode().strip()}")
return False
return True
[docs]
def validate_dirac() -> bool:
"""Check if the DIRAC client is valid and configured."""
expected_cmds = [
"dirac-proxy-info",
"dirac-wms-job-submit",
"dirac-wms-job-status",
"dirac-wms-job-get-output",
]
for cmd in expected_cmds:
# Expect the commands to be in the PATH
which_cmd = shutil.which(cmd)
if not which_cmd:
log.error(f"Command '{cmd}' not found in PATH.")
return False
return True
[docs]
class JobStatus(Enum):
WAITING = "Waiting"
RUNNING = "Running"
UNKNOWN = "Unknown"
DONE = "Done"
MATCHED = "Matched"
COMPLETING = "Completing"
FAILED = "Failed"
STAGED = "Staged"
[docs]
@classmethod
def from_string(cls, value):
"""Convert string to JobStatus enum."""
value = value.strip().lower()
# Stalled, killed or deleted jobs will not finish, handle them as
# failed so they are resubmitted
if value in ("stalled", "killed", "deleted"):
return cls.FAILED
for status in cls:
if status.value.lower() == value:
return status
return cls.UNKNOWN
[docs]
class GridInterface(ABC):
def __init__(
self,
input: Union[Path, str, list[str]],
toppar_path: Path,
module_path: Path,
) -> None:
# Common attributes for all grid jobs can be defined here
# Unique name for the job
self.name = str(uuid.uuid4())
# Create a temporary directory for the job
self.loc = Path(tempfile.mkdtemp(prefix="haddock_grid_"))
# working directory where the GridJob was created, this is important
# so we know where to put the files coming from the grid
self.wd = Path.cwd()
# `id` is given by DIRAC
self.id = None
# Site where the job is running
self.site = None
# Script that will be executed in the grid
self.job_script = self.loc / "job.sh"
# JDL file that describes the job to DIRAC
self.jdl = self.loc / "job.jdl"
# Internal status of the job
self.status = JobStatus.STAGED
# `expected_outputs` is what will be produced by this `.inp` file
self.expected_outputs = []
# Output and error files generated by the job.sh execution
self.stdout_f = None
self.stderr_f = None
# List of files to be included in the payload
self.payload_fnames = []
# Counter for retries
self.retries = 0
# Tracker for timings
self.timings: dict[JobStatus, datetime] = {}
# `input_str` is the content of the `.inp` file
self.input_str = ""
# `input_str_list` is a list of separate recipes`
self.input_str_list = [] # Initialize the list to store separate recipes
# `module_path` is the path to the CNS module files
self.module_path = module_path
# `toppar_path` is the path to the TOPPAR files`
self.toppar_path = toppar_path
# Indicator if this job has been packaged
self.packaged = False
# `parse_input` is an abstract compatibility method that will handle
# different types of input. It can be either a string, a path or
# a list of paths/strings
self.parse_input(input)
[docs]
def package(self) -> None:
# We need to process the input file first to adjust paths and identify outputs
self.process_input_f()
# CREATE JOB FILE
self.create_job_script()
# CREATE THE JDL
self.create_jdl()
# CREATE PAYLOAD
self.prepare_payload(
cns_script_path=Path(self.module_path),
toppar_path=Path(self.toppar_path),
)
self.packaged = True
[docs]
@abstractmethod
def create_job_script(self) -> None:
"""Create the job script that will be executed in the grid."""
pass
[docs]
def create_jdl(self) -> None:
"""Create the JDL file that describes the job to DIRAC."""
output_sandbox = ["job.out", "job.err"]
output_sandbox.extend(self.expected_outputs)
output_sandbox_str = ", ".join(f'"{fname}"' for fname in output_sandbox)
jdl_lines = [
f'JobName = "{self.name}";',
'Executable = "job.sh";',
'Arguments = "";',
'StdOutput = "job.out";',
'StdError = "job.err";',
f'JobType = "{JOB_TYPE}";',
'InputSandbox = {"job.sh", "payload.zip"};',
"OutputSandbox = {" + f"{output_sandbox_str}" + "};",
]
jdl_string = "[\n " + "\n ".join(jdl_lines) + "\n]\n"
# log.debug(f"JDL for job {self.name}:\n{jdl_string}")
with open(self.jdl, "w") as f:
f.write(jdl_string)
[docs]
def update_status(self) -> None:
"""Update the status of the job by querying DIRAC."""
try:
result = subprocess.run(
["dirac-wms-job-status", str(self.id)],
shell=False,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as e:
log.error(
f"Updating the status failed: {e}\nStdout: {e.stdout}\nStderr: {e.stderr}"
)
raise
self.set_status(self.parse_output(result.stdout))
[docs]
def set_status(self, output_dict: dict[str, str]) -> None:
"""Set the status of the job from the parsed DIRAC status output."""
self.status = JobStatus.from_string(output_dict["Status"])
self.site = output_dict.get("Site", "Unknown")
log.debug(self)
if self.status == JobStatus.RUNNING and JobStatus.RUNNING not in self.timings:
# job is running and we have not tracket it yet, save the time
self.timings[JobStatus.RUNNING] = datetime.now()
elif self.status == JobStatus.DONE and JobStatus.DONE not in self.timings:
# job is done and we have not tracked it yet, save the time
self.timings[JobStatus.DONE] = datetime.now()
[docs]
def prepare_payload(self, cns_script_path: Path, toppar_path: Path) -> None:
"""Prepare the payload.zip file containing all necessary files."""
# Find the CNS scripts that should be inside the payload
for f in cns_script_path.glob("*"):
self.payload_fnames.append(Path(f))
# Find the TOPPAR files that should be inside the payload
for f in toppar_path.rglob("*"):
if f.is_file(): # Only add files, not directories
self.payload_fnames.append(f)
# Create the payload.zip
with zipfile.ZipFile(f"{self.loc}/payload.zip", "w") as z:
# It must contain the CNS executable and the input file,
# z.write(self.input_f, arcname=f"{self.input_f.name}")
z.write(CNS_EXEC, arcname="cns")
arcnames = {"cns"}
for f in set(self.payload_fnames):
# NOTE: Preserve the relative path structure from `toppar_path`!
# This is important because some CNS scripts have relative paths
# hardcoded in it
if f.is_relative_to(toppar_path):
arcname = str(f.relative_to(toppar_path))
else:
arcname = Path(f).name
# A toppar file the `.inp` refers to is also copied next to it,
# add it only once or `unzip` asks whether to overwrite it
if arcname in arcnames:
continue
arcnames.add(arcname)
z.write(f, arcname=arcname)
[docs]
def submit(self) -> None:
"""Interface to submit the job to DIRAC."""
# If this is a re-submission the timings will already be set,
# make sure it is clean
self.clean_timings()
if not self.packaged:
self.package()
self.timings[JobStatus.WAITING] = datetime.now()
# Submissions can fail when DIRAC is briefly unavailable, retry them
# and count them towards the same MAX_RETRIES as failed jobs
while True:
try:
# The SUBMIT_CMD returns the job ID in stdout
result = subprocess.run(
["dirac-wms-job-submit", f"{self.loc}/job.jdl"],
shell=False,
capture_output=True,
text=True,
cwd=self.loc,
check=True,
)
break
except subprocess.CalledProcessError as e:
if self.retries >= MAX_RETRIES:
log.error(
f"Job submission failed: {e}\nStdout: {e.stdout}\nStderr: {e.stderr}"
)
# Giving up on this job, remove its temporary folder
self.clean()
raise
self.retries += 1
delay = min(
SUBMIT_RETRY_DELAY * 2 ** (self.retries - 1), SUBMIT_RETRY_MAX_DELAY
)
log.warning(
f"> Submission of job {self.name} failed ({e.stdout.strip()}), retrying in {delay}s - {self.retries}/{MAX_RETRIES} <"
)
time.sleep(delay)
# Add the ID to the object
self.id = int(result.stdout.split()[-1])
# Update the status
self.update_status()
[docs]
def retrieve_output(self) -> None:
"""Retrieve the output files from DIRAC.
The `dirac-wms-job-get-output` command downloads the output sandbox, this means that
anything that was specified in the `OutputSandbox` section of the JDL file will be
put in the current working directory following the pattern: `working_dir/job_id/`
"""
try:
subprocess.run(
["dirac-wms-job-get-output", str(self.id)],
shell=False,
capture_output=True,
text=True,
cwd=self.loc,
)
except subprocess.CalledProcessError as e:
log.error(
f"Retrieving output failed: {e}\nStdout: {e.stdout}\nStderr: {e.stderr}"
)
raise
# NOTE: This is the output of the `job.sh`
self.stdout_f = Path(f"{self.loc}/{self.id}/job.out")
self.stderr_f = Path(f"{self.loc}/{self.id}/job.err")
# If the job failed for some reason, save the output
if self.stderr_f.exists():
dst = Path(self.wd / f"{self.id}_dirac.err")
shutil.copy(self.stderr_f, dst)
log.debug(f"ID stderr: {self.stderr_f.read_text()}")
ls = glob.glob(f"{self.loc}/{self.id}/*")
log.debug(f"Files in the output sandbox: {ls}")
log.debug(f"Expected outputs: {self.expected_outputs}")
# Copy the output to the expected location; the CNS `.out` logs are
# only in the sandbox if CNS failed, as `job.sh` removes them otherwise
for output_f in self.expected_outputs:
src = Path(f"{self.loc}/{self.id}/{output_f}")
if not src.exists():
continue
dst = Path(self.wd / f"{output_f}")
shutil.copy(src, dst)
[docs]
def clean_timings(self) -> None:
"""Clean the timings dictionary."""
self.timings = {}
[docs]
def clean(self) -> None:
"""Clean up the temporary directory where the job lives."""
shutil.rmtree(self.loc)
[docs]
@staticmethod
def parse_output(output_str: str) -> dict[str, str]:
"""Parse the output string from DIRAC commands into a dictionary."""
items = output_str.replace(";", "")
status_dict = {}
for item in items.split(" "):
if "=" in item:
key, value = item.split("=", 1)
status_dict[key.strip()] = value.strip()
return status_dict
@staticmethod
def _process_line(line: str) -> Tuple[str, Optional[str]]:
"""Process a line to identify and adjust paths."""
match_var = re.findall(VAR_PATTERN, line)
match_at = re.findall(AT_PATTERN, line)
# NOTE: In CNS it cannot match both patterns at the same time
if match_at:
item = match_at[0].strip('"').strip("'")
elif match_var:
item = match_var[0].strip('"').strip("'")
else:
# no match
return line, None
if Path(item).exists():
# This is a path
return line.replace(item, Path(item).name), item
else:
# This is not a path
return line, None
@staticmethod
def _find_output(line) -> Optional[str]:
"""Parse the line and identify if this contains an output file declaration."""
match = re.search(OUTPUT_PATTERN, line)
if match:
return match.group(1) if match.group(1) else match.group(2)
return None
def __repr__(self) -> str:
return f"ID: {self.id} Name: {self.name} Output: {self.expected_outputs} Status: {self.status.value} Site: {self.site}"
[docs]
class GridJob(GridInterface):
"""GridJob is a class tha represents a job to be run on the GRID via DIRAC."""
def __init__(
self,
input: Union[Path, str],
toppar_path: Path,
module_path: Path,
) -> None:
super().__init__(
input=input,
toppar_path=toppar_path,
module_path=module_path,
) # initialize the base class
[docs]
def create_job_script(self) -> None:
"""Create the job script that will be executed in the grid."""
# NOTE: We use `\n` instead of `os.linesep` because this will
# be executed in a Linux environment inside the grid
inp_name = f"{self.name}.inp"
cns_out_name = f"{self.name}.out"
self.expected_outputs.append(cns_out_name)
instructions = "#!/bin/bash\n"
instructions += "export MODULE=./\n"
instructions += "export TOPPAR=./\n"
instructions += "unzip payload.zip\n"
instructions += f"./cns < {inp_name} > {cns_out_name}\n"
# Remove `cns.log` if there is no error
instructions += f"[ $? -eq 0 ] && rm {cns_out_name} || exit 1\n"
with open(self.job_script, "w") as f:
f.write(instructions)
[docs]
class CompositeGridJob(GridInterface):
def __init__(
self,
input: list[str],
toppar_path: Path,
module_path: Path,
) -> None:
super().__init__(
input=input,
toppar_path=toppar_path,
module_path=module_path,
) # initialize the base class
[docs]
def create_job_script(self) -> None:
"""Create the job script that will be executed in the grid."""
# NOTE: We use `\n` instead of `os.linesep` because this will
# be executed in a Linux environment inside the grid
instructions = "#!/bin/bash\n"
instructions += "export MODULE=./\n"
instructions += "export TOPPAR=./\n"
instructions += "unzip payload.zip\n"
for idx, _ in enumerate(self.input_str_list):
inp_name = f"{idx}_{self.name}.inp"
cns_out_name = f"{idx}_{self.name}.out"
self.expected_outputs.append(cns_out_name)
instructions += f"./cns < {inp_name} > {cns_out_name}\n"
instructions += f"[ $? -eq 0 ] && rm {cns_out_name} || exit 1\n"
with open(self.job_script, "w") as f:
f.write(instructions)
[docs]
class GRIDScheduler:
"""Scheduler to manage and run jobs on the GRID via DIRAC."""
def __init__(self, tasks: list[CNSJob], params: dict) -> None:
self.ncores = parse_ncores(params["ncores"])
self.tasks = tasks
self.workload: list[CompositeGridJob] = []
# Modules run inside their step folder, named `<step>_<module>`
module = Path.cwd().name.split("_", 1)[-1]
self.batch_size = MODELS_PER_JOB.get(module, 1)
[docs]
def run(self) -> None:
"""Execute the tasks."""
log.info("#" * 42)
log.info("=== Running tasks with GRID Scheduler ===")
self.create_batches()
self.submit_jobs()
self.wait_for_completion()
log.info("#" * 42)
[docs]
def create_batches(self) -> None:
"""Create batches of jobs to be submitted together."""
toppar_path = self.tasks[0].envvars["TOPPAR"]
module_path = self.tasks[0].envvars["MODULE"]
# `input_file` is either the path to the `.inp` file or its content
inputs = [
t.input_file.read_text() if isinstance(t.input_file, Path) else t.input_file
for t in self.tasks
]
self.workload = [
CompositeGridJob(
input=inputs[i : i + self.batch_size],
toppar_path=toppar_path,
module_path=module_path,
)
for i in range(0, len(inputs), self.batch_size)
]
log.info(
f"++ Created {len(self.workload)} payload(s) with up to {self.batch_size} job(s) each"
)
[docs]
def wait_for_completion(self) -> None:
"""Wait for jobs with status WAITING or RUNNING to complete."""
log.info("++ Waiting...")
while True:
jobs_to_check = [
job
for job in self.workload
if job.status
not in {JobStatus.STAGED, JobStatus.DONE, JobStatus.FAILED}
]
if not jobs_to_check:
break
time.sleep(POLL_INTERVAL)
log.debug(f"+ Checking status of {len(jobs_to_check)} payload(s)...")
self.update_statuses(jobs_to_check)
with ThreadPoolExecutor(max_workers=self.ncores) as executor:
executor.map(self.process_job, jobs_to_check)
[docs]
@staticmethod
def update_statuses(jobs: list[CompositeGridJob]) -> None:
"""Update the status of all jobs with a single DIRAC call."""
result = subprocess.run(
["dirac-wms-job-status", *[str(job.id) for job in jobs]],
shell=False,
capture_output=True,
text=True,
)
if result.returncode != 0:
log.warning(f"> Checking the job status failed: {result.stdout.strip()} <")
# DIRAC prints one line per job; jobs it does not report keep their status
# and are checked again in the next round
statuses = {}
for line in result.stdout.splitlines():
output_dict = GridInterface.parse_output(line)
if "JobID" in output_dict and "Status" in output_dict:
statuses[output_dict["JobID"]] = output_dict
for job in jobs:
if str(job.id) in statuses:
job.set_status(statuses[str(job.id)])
[docs]
def submit_jobs(self) -> None:
"""Submit jobs to the GRID in parallel."""
log.info(f"++ Submitting {len(self.workload)} payloads to the grid...")
with ThreadPoolExecutor(max_workers=self.ncores) as executor:
executor.map(lambda job: job.package(), self.workload)
with ThreadPoolExecutor(max_workers=self.ncores) as executor:
executor.map(lambda job: job.submit(), self.workload)
[docs]
@staticmethod
def process_job(job: GridJob) -> None:
"""Process a single job: retrieve output if done, handle retries if failed.
NOTE: This function is parallelized, that is why things like cleaning, download, retry
are here. If you are adding new functionality, consider if it should be here or in the
sequential part of the code.
"""
if job.status == JobStatus.FAILED:
# Jobs on the grid can fail for many reasons outside our control
# So if the job is failed, resubmit it up to MAX_RETRIES times
if job.retries < MAX_RETRIES:
expected_output_str = ",".join(job.expected_outputs)
job.retries += 1
log.warning(
f"> Job {job.name} ({expected_output_str}) failed on {job.site}, re-submitting - {job.retries}/{MAX_RETRIES} <"
)
log.debug(f"job {job.name} at {job.loc}")
job.submit()
else:
# TODO: Add some sort of fallback mechanism here
log.error(f"> Job {job.name} failed {MAX_RETRIES} times, giving up <")
job.clean()
if job.status == JobStatus.DONE:
log.debug(f"Job {job.name} is done, retrieving output...")
job.retrieve_output()
log.debug(f"job {job.name} at {job.loc}")
job.clean()