| 1 | from asyncio import Future |
| 2 | from concurrent.futures import ThreadPoolExecutor |
| 3 | from typing import Callable |
| 4 | import time |
| 5 | from sluurp.job import SBatchScriptJob, submit_sbatch_job |
| 6 | |
| 7 | SUBMISSION_TIMEOUT = 10 |
| 8 | |
| 9 | _executor = None |
| 10 | |
| 11 | |
| 12 | class Executor(ThreadPoolExecutor): |
| 13 | def submit(self, fn: Callable, *args, **kwargs) -> Future: |
| 14 | future = super().submit(fn, *args, **kwargs) |
| 15 | return future |
| 16 | |
| 17 | |
| 18 | def submit(job: SBatchScriptJob, timeout=SUBMISSION_TIMEOUT): |
| 19 | """ |
| 20 | function to submit a job to slurm using SBATCH |
| 21 | |
| 22 | :param SBatchScriptJob job: job script to submit |
| 23 | """ |
| 24 | global _executor |
| 25 | if _executor is None: |
| 26 | _executor = Executor() |
| 27 | |
| 28 | if not isinstance(job, SBatchScriptJob): |
| 29 | raise TypeError( |
| 30 | f"job is expected to be an instance of {SBatchScriptJob}. {type(job)} provided" |
| 31 | ) |
| 32 | |
| 33 | future = _executor.submit(submit_sbatch_job, job) |
| 34 | wait_time = 0 |
| 35 | while job.job_id is None and wait_time < timeout: |
| 36 | time.sleep(0.1) |
| 37 | wait_time += 0.1 |
| 38 | future.job_id = job.job_id |
| 39 | future.collect_logs = job.collect_logs |
| 40 | if job.job_id is None: |
| 41 | future.set_exception("Unable to submit job within allocated time") |
| 42 | return future |