Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ currently provides the following executors:
* ``local``: run jobs locally
* ``lsf``: `IBM Spectrum LSF <https://www.ibm.com/docs/en/spectrum-lsf>`_
* ``pbs``: `Altair's PBS-Professional <https://www.altair.com/pbs-professional>`_ and variations, such as OpenPBS.
* ``sge``: `Son of Grid Engine <https://arc.liv.ac.uk/trac/SGE>`_ and compatible Grid Engine variants
* ``slurm``: `Slurm Scheduling System <https://slurm.schedmd.com/>`_


Expand Down
1 change: 1 addition & 0 deletions scripts/psijcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"flux",
"lsf",
"rp",
"sge",
"slurm"
],
)
Expand Down
7 changes: 7 additions & 0 deletions src/psij-descriptors/sge_descriptor.py
Original file line number Diff line number Diff line change
@@ -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')]
322 changes: 322 additions & 0 deletions src/psij/executors/batch/sge.py
Original file line number Diff line number Diff line change
@@ -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> <slots>``). 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 <https://arc.liv.ac.uk/trac/SGE>`_ 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.<name>`` 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 <pe>``) 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 <id>.<range> 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')
Loading
Loading