"""Utils for slurm bridge.Copyright 2021, Bill & Melinda Gates Foundation. All rights reserved."""importjsonimportosfromosimportPathLikefrompathlibimportPathfromtypingimportDictfromloggingimportgetLogger,DEBUGfromidmtools_slurm_utils.bashimportcommand_bashfromidmtools_slurm_utils.sbatchimportcommand_sbatchfromidmtools_slurm_utils.scancelimportcommand_scancelfromidmtools_slurm_utils.verifyimportcommand_verifyERROR_INVALID_COMMAND="No command specified. You must specify either bash, scancel, or verify"logger=getLogger()VALID_COMMANDS=['bash','sbatch','scancel','verify']
[docs]defprocess_job(job_path,result_dir,cleanup_job:bool=True):""" Process a job. Args: job_path: Path to the job result_dir: Result directory cleanup_job: Cleanup job when done(true), false leave it in place. """try:result_dir=Path(result_dir)ifnotresult_dir.exists():result_dir.mkdir(parents=True,exist_ok=True)result_name=result_dir.joinpath(f'{os.path.basename(Path(job_path))}.result')result=get_job_result(job_path)write_result(result,result_name)ifcleanup_job:os.unlink(job_path)exceptExceptionase:logger.exception(e)pass
[docs]defget_job_result(job_path:PathLike)->Dict:""" Read a job file in from path and return a result. Args: job_path: Path Returns: Result """withopen(job_path,"r")asjin:info=json.load(jin)if"command"notininfoorinfo['command'].lower()notinVALID_COMMANDS:result=dict(status="error",output=ERROR_INVALID_COMMAND)else:command=info['command'].lower()ifcommand=="sbatch":result=command_sbatch(info)elifcommand=="bash":result=command_bash(info)elifcommand=="verify":result=command_verify(info)elifcommand=="scancel":result=command_scancel(info)else:result=dict(status="error",output=ERROR_INVALID_COMMAND)iflogger.isEnabledFor(DEBUG):logger.debug(f'Result for {job_path}: {json.dumps(result,indent=4,sort_keys=True)}')returnresult
[docs]defwrite_result(result:Dict,result_name:Path):""" Write the result of a job to a directory. Args: result: Result to write result_name: Path to write result to. """withopen(result_name,"w")asrout:json.dump(result,rout)