| 1 |
from pathlib import Path |
| 2 |
import shutil |
| 3 |
import tempfile |
| 4 |
from typing import Optional, Union |
| 5 |
import os |
| 6 |
from sluurp.utils import SubProcessCommand |
| 7 |
from .utils import has_scancel_available, has_scontrol_available |
| 8 |
import time |
| 9 |
import logging |
| 10 |
from uuid import uuid4 |
| 11 |
from packaging import version |
| 12 |
from platform import python_version |
| 13 |
|
| 14 |
_logger = logging.getLogger(__name__) |
| 15 |
|
| 16 |
|
| 17 |
class Job: |
| 18 |
def __init__(self, working_directory) -> None: |
| 19 |
""" |
| 20 |
:param script: script to be launched |
| 21 |
""" |
| 22 |
self._working_directory = working_directory |
| 23 |
self._dry_run = False |
| 24 |
self._result = "not run yet" |
| 25 |
|
| 26 |
@property |
| 27 |
def working_directory(self) -> Optional[str]: |
| 28 |
return self._working_directory |
| 29 |
|
| 30 |
@property |
| 31 |
def result(self): |
| 32 |
return self._result |
| 33 |
|
| 34 |
@property |
| 35 |
def dry_run(self): |
| 36 |
return self._dry_run |
| 37 |
|
| 38 |
@dry_run.setter |
| 39 |
def dry_run(self, dry_run: bool): |
| 40 |
self._dry_run = dry_run |
| 41 |
|
| 42 |
def run(self): |
| 43 |
raise NotImplementedError("Base class") |
| 44 |
|
| 45 |
|
| 46 |
class ScriptJob(Job): |
| 47 |
def __init__( |
| 48 |
self, |
| 49 |
script: tuple, |
| 50 |
working_directory: Optional[Path] = None, |
| 51 |
script_path: Optional[Path] = None, |
| 52 |
clean_script: bool = True, |
| 53 |
clean_job_artefacts: bool = True, |
| 54 |
) -> None: |
| 55 |
""" |
| 56 |
:param tuple script: script with a tuple of str (one per line to write) |
| 57 |
""" |
| 58 |
if not isinstance(script, tuple): |
| 59 |
raise TypeError( |
| 60 |
f"script is expected to be a tuple. {type(script)} provided" |
| 61 |
) |
| 62 |
super().__init__(working_directory) |
| 63 |
self._clean_script = clean_script |
| 64 |
self._script_path = script_path |
| 65 |
self._script = list(script) |
| 66 |
self._overwrite = False |
| 67 |
self._file_extension = "sh" |
| 68 |
self._clean_job_artefacts = clean_job_artefacts |
| 69 |
|
| 70 |
@property |
| 71 |
def script(self) -> tuple: |
| 72 |
return tuple(self._script) |
| 73 |
|
| 74 |
@property |
| 75 |
def file_extension(self): |
| 76 |
return self._file_extension |
| 77 |
|
| 78 |
@file_extension.setter |
| 79 |
def file_extension(self, file_extension: str): |
| 80 |
self._file_extension = file_extension.lsplit(".") |
| 81 |
|
| 82 |
@property |
| 83 |
def overwrite(self) -> bool: |
| 84 |
return self._overwrite |
| 85 |
|
| 86 |
@overwrite.setter |
| 87 |
def overwrite(self, overwrite: bool): |
| 88 |
self._overwrite = overwrite |
| 89 |
|
| 90 |
@property |
| 91 |
def script_path(self) -> Optional[Path]: |
| 92 |
return self._script_path |
| 93 |
|
| 94 |
@property |
| 95 |
def clean_script(self): |
| 96 |
return self._clean_script |
| 97 |
|
| 98 |
@clean_script.setter |
| 99 |
def clean_script(self, clean_script: bool): |
| 100 |
self._clean_script = clean_script |
| 101 |
|
| 102 |
@property |
| 103 |
def clean_job_artefacts(self) -> bool: |
| 104 |
return self._clean_job_artefacts |
| 105 |
|
| 106 |
@clean_job_artefacts.setter |
| 107 |
def clean_job_artefacts(self, clean: bool): |
| 108 |
return self._clean_job_artefacts |
| 109 |
|
| 110 |
def _save_script(self) -> Path: |
| 111 |
if self.script_path is not None: |
| 112 |
if os.path.exists(self.script_path) and not os.path.isfile( |
| 113 |
self.script_path |
| 114 |
): |
| 115 |
raise ValueError( |
| 116 |
f"script_path is expected to be a file path ({self.script_path})" |
| 117 |
) |
| 118 |
else: |
| 119 |
self._script_path = ".".join( |
| 120 |
[tempfile.NamedTemporaryFile().name, self.file_extension] |
| 121 |
) |
| 122 |
os.makedirs(os.path.dirname(self.script_path), exist_ok=True) |
| 123 |
|
| 124 |
|
| 125 |
if not self.overwrite and os.path.exists(self.script_path): |
| 126 |
raise OSError(f"{self.script_path} already exists. Won't overwrite it") |
| 127 |
|
| 128 |
with open(self.script_path, mode="w") as file_object: |
| 129 |
self._specify_shell_command(file_object) |
| 130 |
self._write_script_preprocessing_lines(file_object) |
| 131 |
self._write_script_lines(file_object) |
| 132 |
self._write_script_postprocessing_lines(file_object) |
| 133 |
return self.script_path |
| 134 |
|
| 135 |
def _specify_shell_command(self, file_object): |
| 136 |
file_object.write("#!/bin/bash -l\n") |
| 137 |
|
| 138 |
def _write_script_lines(self, file_object): |
| 139 |
for line in self.script: |
| 140 |
file_object.write(line + "\n") |
| 141 |
|
| 142 |
def _write_script_preprocessing_lines(self, file_object): |
| 143 |
if self._working_directory is not None: |
| 144 |
file_object.write(f"#SBATCH --chdir={self.working_directory}\n") |
| 145 |
|
| 146 |
def _write_script_postprocessing_lines(self, file_object): |
| 147 |
pass |
| 148 |
|
| 149 |
def _do_script_cleaning(self): |
| 150 |
if self.script_path is not None and os.path.isfile(self.script_path): |
| 151 |
os.remove(self.script_path) |
| 152 |
|
| 153 |
def _do_job_artefacts_cleaning(self): |
| 154 |
pass |
| 155 |
|
| 156 |
|
| 157 |
class SBatchScriptJob(ScriptJob): |
| 158 |
def __init__(self, slurm_config: Optional[dict] = None, *args, **kwargs) -> None: |
| 159 |
super().__init__(*args, **kwargs) |
| 160 |
assert isinstance(slurm_config, (dict, type(None))) |
| 161 |
|
| 162 |
self._job_id = None |
| 163 |
self._status = "Under submission" |
| 164 |
self._slurm_config = slurm_config if slurm_config is not None else {} |
| 165 |
self._sbatch_extra_params = self._slurm_config.pop("sbatch_extra_params", {}) |
| 166 |
|
| 167 |
self._pycuda_cache_dir = os.path.join( |
| 168 |
os.path.dirname(self.script_path), f".pycuda_cache_dir_{uuid4()}" |
| 169 |
) |
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
self._script.insert(0, f"mkdir -p {self._pycuda_cache_dir}") |
| 175 |
self._script.insert(1, f"export PYCUDA_CACHE_DIR={self._pycuda_cache_dir}") |
| 176 |
|
| 177 |
def set_status(self, status): |
| 178 |
self._status = status |
| 179 |
|
| 180 |
@property |
| 181 |
def job_id(self): |
| 182 |
return self._job_id |
| 183 |
|
| 184 |
@job_id.setter |
| 185 |
def job_id(self, job_id: int): |
| 186 |
self._job_id = job_id |
| 187 |
|
| 188 |
@property |
| 189 |
def status(self): |
| 190 |
return self._status |
| 191 |
|
| 192 |
def get_status(self): |
| 193 |
return self._status |
| 194 |
|
| 195 |
def run(self): |
| 196 |
""" |
| 197 |
run the sbatch command with the script created. |
| 198 |
""" |
| 199 |
self._status = "Running" |
| 200 |
script_path = self._save_script() |
| 201 |
export = self._sbatch_extra_params.get("export", "NONE") |
| 202 |
if not os.path.exists(script_path): |
| 203 |
raise OSError( |
| 204 |
f"{script_path} doesn't exists. Unable to write script file. Can be write rights error." |
| 205 |
) |
| 206 |
if self.dry_run is False: |
| 207 |
job_id = SubProcessCommand( |
| 208 |
command=f"sbatch --export={export} {script_path}" |
| 209 |
).run() |
| 210 |
else: |
| 211 |
job_id = "-1" |
| 212 |
self._result = self._get_job_id_or_raise_error(job_id) |
| 213 |
if self.clean_script: |
| 214 |
self._do_script_cleaning() |
| 215 |
if self.clean_job_artefacts: |
| 216 |
self._do_job_artefacts_cleaning() |
| 217 |
return self._result |
| 218 |
|
| 219 |
def _get_job_id_or_raise_error(self, text: Union[str, SubProcessCommand]) -> int: |
| 220 |
try: |
| 221 |
|
| 222 |
return int(text.replace("\n", "").split(" ")[-1]) |
| 223 |
except Exception as e: |
| 224 |
raise ValueError( |
| 225 |
f"Fail to get job id from submission. Submission failed. Most likely the slurm configuration is invalid. Please run 'sbatch {self._get_output_file_path()}' to get more information" |
| 226 |
) from e |
| 227 |
|
| 228 |
def _specify_shell_command(self, file_object): |
| 229 |
file_object.write("#!/bin/bash -l\n") |
| 230 |
|
| 231 |
def _get_output_file_path(self): |
| 232 |
return str(self.script_path)[: -(len(self.file_extension) + 1)] + ".out" |
| 233 |
|
| 234 |
def _write_script_preprocessing_lines(self, file_object): |
| 235 |
super()._write_script_preprocessing_lines(file_object=file_object) |
| 236 |
|
| 237 |
slurm_lines, pre_processing_lines = self.interpret_slurm_config( |
| 238 |
self._slurm_config, |
| 239 |
self._sbatch_extra_params, |
| 240 |
) |
| 241 |
|
| 242 |
output_file_path = self._get_output_file_path() |
| 243 |
file_object.write(f"#SBATCH --output={output_file_path}\n") |
| 244 |
|
| 245 |
for slurm_line in slurm_lines: |
| 246 |
file_object.write(slurm_line + "\n") |
| 247 |
for pre_processing_line in pre_processing_lines: |
| 248 |
file_object.write(pre_processing_line + "\n") |
| 249 |
|
| 250 |
def _do_job_artefacts_cleaning(self): |
| 251 |
if os.path.exists(self._pycuda_cache_dir): |
| 252 |
shutil.rmtree(self._pycuda_cache_dir, ignore_errors=True) |
| 253 |
|
| 254 |
def collect_logs(self): |
| 255 |
try: |
| 256 |
with open(self._get_output_file_path()) as f: |
| 257 |
return f.readlines() |
| 258 |
except OSError as e: |
| 259 |
_logger.info( |
| 260 |
f"Failed to collect log from {self._get_output_file_path}. Error is {e}" |
| 261 |
) |
| 262 |
return None |
| 263 |
|
| 264 |
@staticmethod |
| 265 |
def strip_gpu_card_name(gpu_name: str): |
| 266 |
""" |
| 267 |
today the name of the gpu return by sinfo are rejected when we are using the -C option. |
| 268 |
Looks like they are prefixed and postfix. For now we strip the extra information but more coherence |
| 269 |
is needed. |
| 270 |
""" |
| 271 |
if version.parse(python_version()) >= version.parse("3.9"): |
| 272 |
gpu_name = gpu_name.removeprefix("nvidia_") |
| 273 |
gpu_name = gpu_name.removeprefix("tesla_") |
| 274 |
gpu_name = gpu_name.removesuffix("-sxm2-32gb") |
| 275 |
gpu_name = gpu_name.removesuffix("-pcie-32gb") |
| 276 |
else: |
| 277 |
gpu_name = gpu_name.replace("nvidia_", "") |
| 278 |
gpu_name = gpu_name.replace("tesla_", "") |
| 279 |
gpu_name = gpu_name.replace("-sxm2-32gb", "") |
| 280 |
gpu_name = gpu_name.replace("-pcie-32gb", "") |
| 281 |
|
| 282 |
return gpu_name |
| 283 |
|
| 284 |
@staticmethod |
| 285 |
def interpret_slurm_config( |
| 286 |
slurm_config: dict, sbatch_extra_params: Optional[dict] = None |
| 287 |
) -> tuple: |
| 288 |
""" |
| 289 |
convert a slurm configuration dictory to a tuple of two tuples. |
| 290 |
The first tuple will provide the lines to add to the shell script for sbtach (ressources specification) |
| 291 |
The second line will provide some command to run before the 'processing command' like sourcing a python virtual environment |
| 292 |
|
| 293 |
:param dict slurm_config: slurm configuration to be interpreted |
| 294 |
""" |
| 295 |
if not isinstance(slurm_config, dict): |
| 296 |
raise TypeError( |
| 297 |
f"slurm_config is expected to be a dict. {type(slurm_config)} provided" |
| 298 |
) |
| 299 |
if sbatch_extra_params is None: |
| 300 |
sbatch_extra_params = {} |
| 301 |
slurm_ressources = [] |
| 302 |
preprocessing = [] |
| 303 |
for key, value in slurm_config.items(): |
| 304 |
if value is None: |
| 305 |
continue |
| 306 |
if key == "cpu-per-task": |
| 307 |
slurm_ressources.append(f"#SBATCH --cpus-per-task={value}") |
| 308 |
elif key == "n_tasks": |
| 309 |
slurm_ressources.append(f"#SBATCH --ntasks={value}") |
| 310 |
elif key == "memory": |
| 311 |
slurm_ressources.append(f"#SBATCH --mem={value}GB") |
| 312 |
elif key == "partition": |
| 313 |
slurm_ressources.append(f"#SBATCH -p {value}") |
| 314 |
elif key == "n_gpus": |
| 315 |
gpu_line = f"#SBATCH --gres=gpu:{value}" |
| 316 |
gpu_card = sbatch_extra_params.get("gpu_card", None) |
| 317 |
if gpu_card is not None: |
| 318 |
gpu_card = SBatchScriptJob.strip_gpu_card_name(gpu_card) |
| 319 |
gpu_line += f" -C {gpu_card}" |
| 320 |
slurm_ressources.append(gpu_line) |
| 321 |
elif key == "job_name": |
| 322 |
slurm_ressources.append(f"#SBATCH -J '{value}'") |
| 323 |
elif key == "walltime": |
| 324 |
slurm_ressources.append(f"#SBATCH -t {value}") |
| 325 |
elif key == "python_venv": |
| 326 |
preprocessing.append(f"source {value}") |
| 327 |
elif key == "modules": |
| 328 |
if isinstance(value, (tuple, list)): |
| 329 |
[preprocessing.append(f"module load {v}") for v in value] |
| 330 |
else: |
| 331 |
preprocessing.append(f"module load {value}") |
| 332 |
else: |
| 333 |
_logger.info(f"Unknow slurm configuration key: {key}") |
| 334 |
return tuple(slurm_ressources), tuple(preprocessing) |
| 335 |
|
| 336 |
|
| 337 |
def get_job_status(job_id): |
| 338 |
if job_id is None: |
| 339 |
return "error" |
| 340 |
elif not has_scontrol_available(): |
| 341 |
raise RuntimeError("squeue not available") |
| 342 |
else: |
| 343 |
res = SControlShowJobCommand(job_id=job_id).run() |
| 344 |
job_state = res.get("JobState", "FAILED") |
| 345 |
if job_state.lower() in ( |
| 346 |
"out_of_memory", |
| 347 |
"suspended", |
| 348 |
"timeout", |
| 349 |
"nodefail", |
| 350 |
"preempted", |
| 351 |
"boot_fail", |
| 352 |
"deadline", |
| 353 |
" resv_del_hold", |
| 354 |
"revoked", |
| 355 |
): |
| 356 |
_logger.warning(f"slurm job {job_id} failed with state {job_state}") |
| 357 |
job_state = "FAILED" |
| 358 |
return job_state.lower() |
| 359 |
|
| 360 |
|
| 361 |
def get_job_infos(job_id): |
| 362 |
if not has_scontrol_available(): |
| 363 |
raise RuntimeError("squeue not available") |
| 364 |
else: |
| 365 |
return SControlShowJobCommand(job_id=job_id).run() |
| 366 |
|
| 367 |
|
| 368 |
def submit_sbatch_job(job): |
| 369 |
job_id = job.run() |
| 370 |
if not isinstance(job_id, int): |
| 371 |
return |
| 372 |
job.job_id = job_id |
| 373 |
while True: |
| 374 |
job_status = get_job_status(job_id) |
| 375 |
job.set_status(job_status) |
| 376 |
if job_status.lower() in ("completed", "failed", "cancelled", "finished"): |
| 377 |
infos = get_job_infos(job_id) |
| 378 |
job.infos = infos |
| 379 |
return job_status.lower() |
| 380 |
else: |
| 381 |
time.sleep(1) |
| 382 |
|
| 383 |
|
| 384 |
def get_my_jobs(): |
| 385 |
res = SubProcessCommand('squeue --me --format="%i"').run().split("\n") |
| 386 |
jobs_ids = [] |
| 387 |
for result_line in res: |
| 388 |
try: |
| 389 |
job_id = int(result_line) |
| 390 |
jobs_ids.append(job_id) |
| 391 |
except ValueError: |
| 392 |
continue |
| 393 |
return jobs_ids |
| 394 |
|
| 395 |
|
| 396 |
def cancel_slurm_job(job_id): |
| 397 |
if not has_scancel_available(): |
| 398 |
raise RuntimeError("slurm command 'scancel' not available from this computer") |
| 399 |
else: |
| 400 |
return SubProcessCommand(command=f"scancel {job_id}").run() |
| 401 |
|
| 402 |
|
| 403 |
class SControlShowJobCommand(SubProcessCommand): |
| 404 |
def __init__(self, job_id, platform="Linux"): |
| 405 |
super().__init__(f"scontrol show job {job_id}", platform) |
| 406 |
|
| 407 |
def interpret_result(self, stdout, stderr): |
| 408 |
return self.stdout_to_dict(stdout=stdout) |
| 409 |
|
| 410 |
@staticmethod |
| 411 |
def stdout_to_dict(stdout): |
| 412 |
res = {} |
| 413 |
res_splitted = " ".join(stdout.split("\n")) |
| 414 |
res_splitted = res_splitted.split(" ") |
| 415 |
for elements in res_splitted: |
| 416 |
if elements == "": |
| 417 |
continue |
| 418 |
elements_splitted = elements.split("=", maxsplit=1) |
| 419 |
if len(elements_splitted) < 2: |
| 420 |
continue |
| 421 |
|
| 422 |
key, value = elements_splitted[0], elements_splitted[1] |
| 423 |
res[key] = value |
| 424 |
return res |