diff --git a/docs/user_guide.rst b/docs/user_guide.rst index b68cf6657..92fe6651a 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -75,6 +75,7 @@ currently provides the following executors: * ``local``: run jobs locally * ``lsf``: `IBM Spectrum LSF `_ * ``pbs``: `Altair's PBS-Professional `_ and variations, such as OpenPBS. + * ``sge``: `Son of Grid Engine `_ and compatible Grid Engine variants * ``slurm``: `Slurm Scheduling System `_ diff --git a/scripts/psijcli.py b/scripts/psijcli.py index e69bf179e..60b9f26d8 100644 --- a/scripts/psijcli.py +++ b/scripts/psijcli.py @@ -23,6 +23,7 @@ "flux", "lsf", "rp", + "sge", "slurm" ], ) diff --git a/src/psij-descriptors/sge_descriptor.py b/src/psij-descriptors/sge_descriptor.py new file mode 100644 index 000000000..5097cee07 --- /dev/null +++ b/src/psij-descriptors/sge_descriptor.py @@ -0,0 +1,7 @@ +from packaging.version import Version +from psij.descriptor import Descriptor + + +__PSI_J_EXECUTORS__ = [Descriptor(name='sge', nice_name='Son of Grid Engine', + aliases=['gridengine'], version=Version('0.0.1'), + cls='psij.executors.batch.sge.SGEJobExecutor')] diff --git a/src/psij/executors/batch/sge.py b/src/psij/executors/batch/sge.py new file mode 100644 index 000000000..374ddbe38 --- /dev/null +++ b/src/psij/executors/batch/sge.py @@ -0,0 +1,322 @@ +"""Defines the SGEJobExecutor class and its config class.""" +import logging +import os +import re +import xml.etree.ElementTree as ET +from pathlib import Path +from threading import RLock +from typing import Optional, Collection, List, Dict, IO, Set + +from psij import Job, JobStatus, JobState, SubmitException +from psij.executors.batch.batch_scheduler_executor import BatchSchedulerExecutor, \ + BatchSchedulerExecutorConfig, check_status_exit_code, InvalidJobStateError +from psij.executors.batch.script_generator import TemplatedScriptGenerator + + +logger = logging.getLogger(__name__) + +_QSUB_COMMAND = 'qsub' +_QSTAT_COMMAND = 'qstat' +_QDEL_COMMAND = 'qdel' + +_QDEL_FAILURE_REGEX = re.compile(r'(does not exist)|(has already been deleted)', re.IGNORECASE) + +_PE_ENV_VAR = 'PSIJ_SGE_PE' + +# characters SGE does not allow in job names (see qsub(1), -N); whitespace is also replaced +# since the name is rendered as a directive argument +_INVALID_NAME_CHARS = re.compile(r'[/:@\\*?\s]') + + +def _sanitize_job_name(name: Optional[str]) -> Optional[str]: + if not name: + return None + # the name defaults to the executable path, so use its last component + name = name.rstrip('/').rsplit('/', 1)[-1] + name = _INVALID_NAME_CHARS.sub('_', name) + return name or None + + +class SGEExecutorConfig(BatchSchedulerExecutorConfig): + """A configuration class for the Son of Grid Engine executor.""" + + def __init__(self, launcher_log_file: Optional[Path] = None, + work_directory: Optional[Path] = None, queue_polling_interval: int = 30, + initial_queue_polling_delay: int = 2, + queue_polling_error_threshold: int = 2, + keep_files: bool = False, + parallel_environment: Optional[str] = None, + memory_resource: str = 'h_vmem', + exclusive_resource: str = 'exclusive', + gpu_resource: Optional[str] = None, + gpu_per_slot: bool = False): + """ + Parameters + ---------- + launcher_log_file + See :class:`.BatchSchedulerExecutorConfig`. + work_directory + See :class:`.BatchSchedulerExecutorConfig`. + queue_polling_interval + See :class:`.BatchSchedulerExecutorConfig`. + initial_queue_polling_delay + See :class:`.BatchSchedulerExecutorConfig`. + queue_polling_error_threshold + See :class:`.BatchSchedulerExecutorConfig`. + keep_files + See :class:`.BatchSchedulerExecutorConfig`. + parallel_environment + The name of the Grid Engine parallel environment used to request multiple slots + (i.e., ``#$ -pe ``). Parallel environment names are + site-specific. If not specified, the value of the ``PSIJ_SGE_PE`` environment + variable is used. If neither is set, no parallel environment is requested and jobs + receive a single slot. + memory_resource + The name of the (per-slot) resource used to request memory. Defaults to ``h_vmem``. + exclusive_resource + The name of the boolean resource used to request exclusive node access. Defaults to + ``exclusive``. + gpu_resource + The name of the consumable resource used to request GPUs (e.g., ``gpu`` or + ``ngpus``). GPU resource names are site-specific, so this has no default; if it is + not set, GPU requests are not passed to the scheduler and a warning is logged. + gpu_per_slot + Whether the GPU resource is consumed per slot (``YES`` in the consumable column of + ``qconf -sc``) or per job (``JOB``, the default here). If per slot, the executor + divides the job's total GPU count by the number of slots, rounding up. The default + is per job because getting it wrong that way over-requests GPUs, which fails + visibly, whereas wrongly assuming per slot under-requests them silently. + """ + super().__init__(launcher_log_file, work_directory, queue_polling_interval, + initial_queue_polling_delay, queue_polling_error_threshold, keep_files) + if parallel_environment is None: + parallel_environment = os.environ.get(_PE_ENV_VAR) or None + self.parallel_environment = parallel_environment + self.memory_resource = memory_resource + self.exclusive_resource = exclusive_resource + self.gpu_resource = gpu_resource + self.gpu_per_slot = gpu_per_slot + + +class SGEJobExecutor(BatchSchedulerExecutor): + """A :class:`~psij.JobExecutor` for Son of Grid Engine and compatible schedulers. + + `Son of Grid Engine `_ is a community-maintained + descendant of Sun Grid Engine. + + Uses the ``qsub``, ``qstat``, and ``qdel`` commands, respectively, to submit, + monitor, and cancel jobs. + + Creates a batch script with ``#$`` directives when submitting a job. Multi-slot jobs + require a parallel environment, which can be specified using + the ``parallel_environment`` argument of :class:`SGEExecutorConfig` or the ``PSIJ_SGE_PE`` + environment variable. + + Renders all custom attributes of the form ``sge.`` into the corresponding + directive. For example, setting + ``job.spec.attributes.custom_attributes['sge.P'] = 'myproject'`` results in a + ``#$ -P myproject`` directive being placed in the submit script. The ``sge.pe`` custom + attribute is treated specially: it names the parallel environment to use for that job + (e.g., ``'orte'``), overriding the configured one, with the slot count still derived from + the job's resources. + + Slots correspond to CPU cores, so the executor requests + ``process_count * cpu_cores_per_process`` slots. Memory is requested per slot, using the + ``memory_resource`` configured in :class:`SGEExecutorConfig`. GPUs are requested only if + ``gpu_resource`` is configured, since GPU resource names vary between sites. + + Grid Engine has no direct way to request a number of nodes. The PE's ``allocation_rule`` + (see ``qconf -sp ``) decides how those slots are spread across hosts. For example, + ``$pe_slots`` places all slots on one host, and a fixed integer rule places exactly that + many slots on each host. ``node_count`` and ``processes_per_node`` are therefore only + honored if the chosen PE's allocation rule matches them. + """ + + def __init__(self, url: Optional[str] = None, config: Optional[SGEExecutorConfig] = None): + """ + Parameters + ---------- + url + Not used, but required by the spec for automatic initialization. + config + An optional configuration for this executor. + """ + if not config: + config = SGEExecutorConfig() + super().__init__(url=url, config=config) + self.generator = TemplatedScriptGenerator(config, Path(__file__).parent / 'sge' + / 'sge.mustache') + self._canceled: Set[str] = set() + self._canceled_lock = RLock() + + # Submit methods + + def generate_submit_script(self, job: Job, context: Dict[str, object], + submit_file: IO[str]) -> None: + """See :meth:`~.BatchSchedulerExecutor.generate_submit_script`.""" + self.generator.generate_submit_script(job, context, submit_file) + + def _create_script_context(self, job: Job) -> Dict[str, object]: + ctx = super()._create_script_context(job) + assert job.spec is not None + # Executor modules may be loaded more than once by the plugin system, so an + # SGEExecutorConfig passed by the user may not be an instance of this module's class. + # It may also be a generic config. Read the SGE-specific settings by duck typing. + config = self.config + pe = getattr(config, 'parallel_environment', None) or os.environ.get(_PE_ENV_VAR) or None + + sge: Dict[str, object] = { + 'job_name': _sanitize_job_name(job.spec.name), + 'memory_resource': getattr(config, 'memory_resource', 'h_vmem'), + 'exclusive_resource': getattr(config, 'exclusive_resource', 'exclusive'), + } + + # a per-job 'sge.pe' custom attribute names the parallel environment to use instead of + # the configured one; it is consumed here rather than rendered as a raw directive + custom = ctx['custom_attributes'] + assert isinstance(custom, dict) + sge_attrs = custom.get('sge') + if isinstance(sge_attrs, list): + for attr in [a for a in sge_attrs if str(a['key']).lower() == 'pe']: + pe = str(attr['value']) + sge_attrs.remove(attr) + + res = job.spec.resources + slots = 1 + if res is not None: + processes = getattr(res, 'computed_process_count', None) or 1 + # SGE slots are cores, so each process needs cpu_cores_per_process slots + cores_per_process = getattr(res, 'cpu_cores_per_process', None) or 1 + slots = processes * cores_per_process + if getattr(res, 'exclusive_node_use', False): + sge['exclusive'] = True + memory_kb = getattr(res, 'memory_kb', None) + if memory_kb: + # SGE memory requests are per slot + sge['memory_per_slot_kb'] = max(1, memory_kb // slots) + gpus_per_process = getattr(res, 'gpu_cores_per_process', None) + if gpus_per_process: + self._add_gpu_request(job, sge, processes * gpus_per_process, slots) + node_count = getattr(res, 'computed_node_count', None) + if node_count and node_count > 1: + logger.warning('Job %s: %s nodes requested, but SGE cannot enforce a node ' + 'count; node placement is determined by the allocation rule ' + 'of the parallel environment', job.id, node_count) + + if pe: + sge['pe'] = pe + sge['slots'] = slots + elif slots > 1: + logger.warning('Job %s: %s processes requested, but no SGE parallel environment ' + 'is configured; set SGEExecutorConfig.parallel_environment or the ' + '%s environment variable', job.id, slots, _PE_ENV_VAR) + + # not named 'sge', which would clash with the sge.* custom attributes in the template + ctx['sge_res'] = sge + return ctx + + def _add_gpu_request(self, job: Job, sge: Dict[str, object], total_gpus: int, + slots: int) -> None: + gpu_resource = getattr(self.config, 'gpu_resource', None) + if not gpu_resource: + logger.warning('Job %s: %s GPUs requested, but no SGE GPU resource is configured; ' + 'set SGEExecutorConfig.gpu_resource (e.g., to "gpu")', + job.id, total_gpus) + return + if getattr(self.config, 'gpu_per_slot', False): + # consumables are multiplied by the slot count, so request a per-slot share + count = -(-total_gpus // slots) + if count * slots != total_gpus: + logger.warning('Job %s: %s GPUs cannot be divided evenly over %s slots; ' + 'requesting %s per slot (%s total)', job.id, total_gpus, slots, + count, count * slots) + else: + count = total_gpus + sge['gpu_resource'] = gpu_resource + sge['gpu_count'] = count + + def get_submit_command(self, job: Job, submit_file_path: Path) -> List[str]: + """See :meth:`~.BatchSchedulerExecutor.get_submit_command`.""" + return [_QSUB_COMMAND, '-terse', str(submit_file_path.absolute())] + + def job_id_from_submit_output(self, out: str) -> str: + """See :meth:`~.BatchSchedulerExecutor.job_id_from_submit_output`.""" + # with -terse, qsub prints only the job id (or . for array jobs) + return out.strip().split()[0].split('.')[0] + + # Cancel methods + + def get_cancel_command(self, native_id: str) -> List[str]: + """See :meth:`~.BatchSchedulerExecutor.get_cancel_command`.""" + with self._canceled_lock: + self._canceled.add(native_id) + return [_QDEL_COMMAND, native_id] + + def process_cancel_command_output(self, exit_code: int, out: str) -> None: + """See :meth:`~.BatchSchedulerExecutor.process_cancel_command_output`.""" + if _QDEL_FAILURE_REGEX.search(out): + raise InvalidJobStateError() + raise SubmitException('Failed to cancel job: %s' % out) + + # Status methods + + def get_status_command(self, native_ids: Collection[str]) -> List[str]: + """See :meth:`~.BatchSchedulerExecutor.get_status_command`.""" + # SGE's qstat only lists pending/running jobs; finished jobs are absent and are + # reported as completed, with the exit code file deciding between COMPLETED and FAILED + return [_QSTAT_COMMAND, '-xml', '-u', self._current_user()] + + def parse_status_output(self, exit_code: int, out: str) -> Dict[str, JobStatus]: + """See :meth:`~.BatchSchedulerExecutor.parse_status_output`.""" + check_status_exit_code(_QSTAT_COMMAND, exit_code, out) + r: Dict[str, JobStatus] = {} + root = ET.fromstring(out) + for job_el in root.iter('job_list'): + native_id = (job_el.findtext('JB_job_number') or '').strip() + native_state = (job_el.findtext('state') or '').strip() + if not native_id: + continue + state = self._get_state(native_state) + msg = None + if state == JobState.FAILED: + msg = 'Job is in error state (%s); see "qstat -j %s" for details' % \ + (native_state, native_id) + r[native_id] = JobStatus(state, message=msg) + + # canceled jobs vanish from qstat; report them as CANCELED instead of COMPLETED + with self._canceled_lock: + for native_id in list(self._canceled): + if native_id not in r: + r[native_id] = JobStatus(JobState.CANCELED) + self._canceled.discard(native_id) + return r + + def _get_state(self, state: str) -> JobState: + if 'E' in state: + return JobState.FAILED + if 'd' in state: + return JobState.CANCELED + if any(c in state for c in 'rt'): + # running or transferring (also covers restarted "Rr" and suspended "s"/"S"/"T" + # running jobs, such as "Sr") + return JobState.ACTIVE + if any(c in state for c in 'qwh'): + # pending, held, or rescheduled-and-pending ("Rq") + return JobState.QUEUED + if any(c in state for c in 'RsST'): + return JobState.ACTIVE + logger.warning('Unknown SGE job state "%s"; assuming QUEUED', state) + return JobState.QUEUED + + def get_list_command(self) -> List[str]: + """See :meth:`~.BatchSchedulerExecutor.get_list_command`.""" + return [_QSTAT_COMMAND, '-u', self._current_user()] + + def parse_list_output(self, out: str) -> List[str]: + """See :meth:`~.BatchSchedulerExecutor.parse_list_output`.""" + # skip the header and the separator line + return [line.split()[0] for line in out.splitlines()[2:] if line.strip()] + + def _clean_submit_script(self, job: Job) -> None: + super()._clean_submit_script(job) + self._delete_aux_file(job, '.nodefile') diff --git a/src/psij/executors/batch/sge/sge.mustache b/src/psij/executors/batch/sge/sge.mustache new file mode 100644 index 000000000..1dae415fa --- /dev/null +++ b/src/psij/executors/batch/sge/sge.mustache @@ -0,0 +1,94 @@ +#!/bin/bash + +#$ -S /bin/bash + +{{#sge_res.job_name}} +#$ -N "{{.}}" +{{/sge_res.job_name}} + +{{#job.spec.directory}} +#$ -wd "{{.}}" +{{/job.spec.directory}} +{{^job.spec.directory}} +#$ -cwd +{{/job.spec.directory}} + +{{#job.spec.inherit_environment}} +#$ -V +{{/job.spec.inherit_environment}} + +{{#sge_res}} + {{#pe}} +#$ -pe {{pe}} {{slots}} + {{/pe}} + {{#exclusive}} +#$ -l {{exclusive_resource}}=true + {{/exclusive}} + {{#memory_per_slot_kb}} +#$ -l {{memory_resource}}={{.}}K + {{/memory_per_slot_kb}} + {{#gpu_count}} +#$ -l {{gpu_resource}}={{.}} + {{/gpu_count}} +{{/sge_res}} + +{{#formatted_job_duration}} +#$ -l h_rt={{.}} +{{/formatted_job_duration}} + +{{#job.spec.attributes}} + {{#queue_name}} +#$ -q {{.}} + {{/queue_name}} + {{#account}} +#$ -A {{.}} + {{/account}} + {{#reservation_id}} +#$ -ar {{.}} + {{/reservation_id}} +{{/job.spec.attributes}} + +{{#custom_attributes}} + {{#sge}} +#$ -{{key}} {{value}} + {{/sge}} +{{/custom_attributes}} + +{{!since we redirect the output manually, below, tell SGE not to do its own thing, since it +only results in empty files that are not cleaned up}} +#$ -o /dev/null +#$ -e /dev/null + +{{!JOB_ID is not available when the directives are evaluated, so redirect here}} +exec &>> "{{psij.script_dir}}/$JOB_ID.out" + +{{#env}} +export {{name}}={{value}} +{{/env}} + +{{> batch_lib}} + +{{!SGE lists each host once in PE_HOSTFILE, together with its slot count ("host slots queue +processors"); expand it to PBS-style form, with one line per slot}} +PSIJ_NODEFILE="{{psij.script_dir}}/$JOB_ID.nodefile" +if [ -n "$PE_HOSTFILE" ] && [ -f "$PE_HOSTFILE" ]; then + while read _PSIJ_HOST _PSIJ_SLOTS _PSIJ_REST; do + for _ in $(seq 1 1 $_PSIJ_SLOTS); do echo "$_PSIJ_HOST"; done + done < "$PE_HOSTFILE" > "$PSIJ_NODEFILE" +else + hostname > "$PSIJ_NODEFILE" +fi +export PSIJ_NODEFILE + +{{> stagein}} +_psij_update_status ACTIVE + +{{#psij.launch_command}}{{.}} {{/psij.launch_command}} +_PSIJ_JOB_EC=$? + +{{> stageout}} +{{> cleanup}} + +{{!we redirect to a file tied to the native ID so that we can reach the file with attach().}} +echo $_PSIJ_JOB_EC > "{{psij.script_dir}}/$JOB_ID.ec" +echo "_PSIJ_SCRIPT_DONE" diff --git a/tests/conftest.py b/tests/conftest.py index 943162515..dd3b86a79 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -147,6 +147,8 @@ def _translate_executor(config: Dict[str, str], executor: str) -> List[str]: if executor == 'auto_q': if config.option.environment.get('has_slurm'): return ['slurm'] + elif config.option.environment.get('has_sge'): + return ['sge'] elif config.option.environment.get('has_pbs'): return ['pbs'] elif config.option.environment.get('has_lsf'): @@ -165,7 +167,7 @@ def _translate_launcher(config: Dict[str, str], exec: str, launcher: str) -> str if launcher == 'auto_l': if exec == 'slurm': return 'srun' - elif exec == 'pbs': + elif exec == 'pbs' or exec == 'sge': return 'mpirun' elif exec == 'lsf': return 'ibrun' @@ -465,7 +467,9 @@ def _discover_environment(config): logger.warning('Cannot get git repository information.') try: env['has_slurm'] = shutil.which('sbatch') is not None - if not env['has_slurm']: + # both SGE and PBS provide qsub; SGE installations define SGE_ROOT + env['has_sge'] = 'SGE_ROOT' in os.environ and shutil.which('qsub') is not None + if not env['has_slurm'] and not env['has_sge']: env['has_pbs'] = shutil.which('qsub') is not None env['has_lsf'] = shutil.which('bsub') is not None env['has_cobalt'] = shutil.which('cqsub') is not None diff --git a/tests/test_resources.py b/tests/test_resources.py index 878d3677b..3ec108da2 100644 --- a/tests/test_resources.py +++ b/tests/test_resources.py @@ -62,6 +62,10 @@ def _check_ranks(s: str, expected_ranks: int, expected_nodes: int) -> None: def test_nodes(execparams: ExecutorTestParams) -> None: if not _supported(execparams): pytest.skip('Unsupported executor/launcher combination') + if execparams.executor == 'sge': + # SGE has no node count request; host placement is dependent on PE allocation_rule. + # 2 nodes x 2 processes cannot be guaranteed + pytest.skip('SGE cannot enforce node counts') _make_test_dir() @@ -90,7 +94,7 @@ def test_nodes(execparams: ExecutorTestParams) -> None: def _supported(ep: ExecutorTestParams) -> bool: if ep.executor == 'batch-test': return ep.launcher == 'batch-test' - if ep.executor in ['slurm', 'pbs', 'lsf']: + if ep.executor in ['slurm', 'pbs', 'lsf', 'sge']: return ep.launcher in ['mpirun', 'srun', 'ibrun'] return False diff --git a/tests/test_sge.py b/tests/test_sge.py new file mode 100644 index 000000000..6220ca893 --- /dev/null +++ b/tests/test_sge.py @@ -0,0 +1,236 @@ +from datetime import timedelta +from io import StringIO +from typing import Any, Dict, Optional, cast + +import pytest + +from psij import Job, JobExecutor, JobSpec, JobAttributes, ResourceSpecV1, JobState +from psij.executors.batch.sge import SGEJobExecutor, SGEExecutorConfig + + +_QSTAT_XML = """ + + + + 101 + 0.55500 + job1 + user + r + all.q@node1 + 4 + + + 105 + job5 + dr + 1 + + + + + 102 + job2 + qw + 1 + + + 103 + job3 + hqw + 1 + + + 104 + job4 + Eqw + 1 + + + +""" + + +def _executor(pe: Optional[str] = None, **kwargs: Any) -> SGEJobExecutor: + config = SGEExecutorConfig(parallel_environment=pe, **kwargs) + ex = JobExecutor.get_instance('sge', config=config) + # the plugin system loads its own copy of the executor module, so isinstance() against + # the class imported here would fail + assert type(ex).__name__ == 'SGEJobExecutor' + return cast(SGEJobExecutor, ex) + + +def _script(ex: SGEJobExecutor, job: Job) -> str: + f = StringIO() + ex.generate_submit_script(job, ex._create_script_context(job), f) + return f.getvalue() + + +def _job(resources: Optional[ResourceSpecV1] = None, + custom: Optional[Dict[str, object]] = None, + duration: Optional[timedelta] = None) -> Job: + attrs = JobAttributes(custom_attributes=custom) + if duration: + attrs.duration = duration + spec = JobSpec('/bin/date', resources=resources, attributes=attrs) + spec.launcher = 'single' + return Job(spec) + + +def test_parse_status_output() -> None: + ex = _executor() + r = ex.parse_status_output(0, _QSTAT_XML) + assert r['101'].state == JobState.ACTIVE + assert r['102'].state == JobState.QUEUED + assert r['103'].state == JobState.QUEUED + assert r['104'].state == JobState.FAILED + assert r['104'].message is not None and 'qstat -j 104' in r['104'].message + assert r['105'].state == JobState.CANCELED + + +@pytest.mark.parametrize('state,expected', [ + ('r', JobState.ACTIVE), ('t', JobState.ACTIVE), ('Rr', JobState.ACTIVE), + ('Rq', JobState.QUEUED), ('qw', JobState.QUEUED), ('hqw', JobState.QUEUED), + ('s', JobState.ACTIVE), ('Sr', JobState.ACTIVE), ('Eqw', JobState.FAILED), + ('dr', JobState.CANCELED), ('dt', JobState.CANCELED)]) +def test_states(state: str, expected: JobState) -> None: + assert _executor()._get_state(state) == expected + + +def test_parse_status_failure() -> None: + with pytest.raises(RuntimeError): + _executor().parse_status_output(1, 'error') + + +def test_canceled_job_missing_from_qstat() -> None: + ex = _executor() + assert ex.get_cancel_command('200') == ['qdel', '200'] + r = ex.parse_status_output(0, _QSTAT_XML) + assert r['200'].state == JobState.CANCELED + # reported only once + assert '200' not in ex.parse_status_output(0, _QSTAT_XML) + + +def test_job_id_from_submit_output() -> None: + ex = _executor() + assert ex.job_id_from_submit_output('12345\n') == '12345' + assert ex.job_id_from_submit_output('12345.1-10:1\n') == '12345' + + +def test_parse_list_output() -> None: + out = ('job-ID prior name user state submit/start at queue slots\n' + '-----------------------------------------------------------------------------\n' + ' 101 0.55500 job1 user r 01/01/2026 10:00:00 all.q@n1 4\n' + ' 102 0.00000 job2 user qw 01/01/2026 10:00:00 1\n') + assert _executor().parse_list_output(out) == ['101', '102'] + + +def test_script_pe_from_config() -> None: + s = _script(_executor('mpi'), _job(ResourceSpecV1(node_count=2, processes_per_node=4))) + assert '#$ -pe mpi 8' in s + + +def test_script_pe_from_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv('PSIJ_SGE_PE', 'smp') + s = _script(_executor(), _job(ResourceSpecV1(process_count=3))) + assert '#$ -pe smp 3' in s + + +def test_script_no_pe(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv('PSIJ_SGE_PE', raising=False) + s = _script(_executor(), _job(ResourceSpecV1())) + assert '-pe' not in s + + +def test_script_pe_override() -> None: + s = _script(_executor('mpi'), _job(ResourceSpecV1(process_count=4), + custom={'sge.pe': 'orte'})) + assert '#$ -pe orte 4' in s + assert s.count('-pe') == 1 + assert '#$ -pe mpi' not in s + + +def test_script_resources() -> None: + res = ResourceSpecV1(process_count=4, memory=4 * 1024 * 1024 * 1024, + exclusive_node_use=True) + s = _script(_executor('mpi'), _job(res, duration=timedelta(hours=1, minutes=30))) + # 4 GiB total over 4 slots -> 1 GiB per slot + assert '#$ -l h_vmem=1048576K' in s + assert '#$ -l exclusive=true' in s + assert '#$ -l h_rt=1:30:0' in s + + +def test_script_custom_attributes() -> None: + s = _script(_executor(), _job(custom={'sge.P': 'myproject'})) + assert '#$ -P myproject' in s + + +def test_script_name_and_directory() -> None: + job = _job() + assert job.spec is not None + job.spec.name = 'myjob' + job.spec.directory = '/tmp/wd' + s = _script(_executor(), job) + assert '#$ -N "myjob"' in s + assert '#$ -wd "/tmp/wd"' in s + assert '#$ -cwd' not in s + + +@pytest.mark.parametrize('name,expected', [ + (None, '#$ -N "date"'), # defaults to the executable, /bin/date + ('my job', '#$ -N "my_job"'), + ('a/b:c@d*e?f', '#$ -N "b_c_d_e_f"'), +]) +def test_script_job_name_sanitized(name: Optional[str], expected: str) -> None: + job = _job() + assert job.spec is not None + job.spec.name = name + s = _script(_executor(), job) + assert expected in s + + +def test_script_cpu_cores_per_process() -> None: + # 2 processes x 4 cores -> 8 slots; 8 GiB over 8 slots -> 1 GiB per slot + res = ResourceSpecV1(process_count=2, cpu_cores_per_process=4, + memory=8 * 1024 * 1024 * 1024) + s = _script(_executor('smp'), _job(res)) + assert '#$ -pe smp 8' in s + assert '#$ -l h_vmem=1048576K' in s + + +def test_script_threaded_single_process() -> None: + s = _script(_executor('smp'), _job(ResourceSpecV1(process_count=1, cpu_cores_per_process=5))) + assert '#$ -pe smp 5' in s + + +def test_script_gpus_per_slot() -> None: + # 2 processes x 2 GPUs = 4 GPUs over 4 slots (2 x 2 cores) -> 1 per slot + res = ResourceSpecV1(process_count=2, cpu_cores_per_process=2, gpu_cores_per_process=2) + s = _script(_executor('smp', gpu_resource='ngpus', gpu_per_slot=True), _job(res)) + assert '#$ -l ngpus=1' in s + + +def test_script_gpus_per_slot_rounds_up() -> None: + # 1 GPU over 4 slots -> rounded up to 1 per slot + res = ResourceSpecV1(process_count=1, cpu_cores_per_process=4, gpu_cores_per_process=1) + s = _script(_executor('smp', gpu_resource='ngpus', gpu_per_slot=True), _job(res)) + assert '#$ -l ngpus=1' in s + + +def test_script_gpus_per_job() -> None: + res = ResourceSpecV1(process_count=2, cpu_cores_per_process=4, gpu_cores_per_process=2) + s = _script(_executor('smp', gpu_resource='gpu'), _job(res)) + assert '#$ -l gpu=4' in s + + +def test_script_gpus_without_resource_name(caplog: pytest.LogCaptureFixture) -> None: + res = ResourceSpecV1(process_count=1, gpu_cores_per_process=1) + s = _script(_executor('smp'), _job(res)) + directives = [line for line in s.splitlines() if line.startswith('#$ -l')] + assert not any('gpu' in line for line in directives) + assert 'no SGE GPU resource is configured' in caplog.text + + +def test_node_count_warning(caplog: pytest.LogCaptureFixture) -> None: + _script(_executor('mpi'), _job(ResourceSpecV1(node_count=2, processes_per_node=2))) + assert 'SGE cannot enforce a node count' in caplog.text