toil.batchSystems.abstractGridEngineBatchSystem

Attributes

DEFAULT_DELAYS

logger

JobTuple

Exceptions

CalledProcessErrorStderr

Version of CalledProcessError that include stderr in the error message if it is set

Classes

BatchJobExitReason

Enum where members are also (and must be) ints

UpdatedBatchJobInfo

BatchSystemCleanupSupport

Adds cleanup support when the last running job leaves a node, for batch

ExternalBatchIdMessage

Produced when using a batch system, links toil assigned batch ID to

AcceleratorRequirement

Requirement for one or more computational accelerators, like a GPU or FPGA.

AbstractGridEngineBatchSystem

A partial implementation of BatchSystemSupport for batch systems run on a

Functions

get_job_kind(names)

Return an identifying string for the job.

old_retry([delays, timeout, predicate])

Deprecated.

Module Contents

class toil.batchSystems.abstractGridEngineBatchSystem.BatchJobExitReason[source]

Bases: enum.IntEnum

Enum where members are also (and must be) ints

FINISHED: int = 1

Successfully finished.

FAILED: int = 2

Job finished, but failed.

LOST: int = 3

Preemptable failure (job’s executing host went away).

KILLED: int = 4

Job killed before finishing.

ERROR: int = 5

Internal error.

MEMLIMIT: int = 6

Job hit batch system imposed memory limit.

MISSING: int = 7

Job disappeared from the scheduler without actually stopping, so Toil killed it.

MAXJOBDURATION: int = 8

Job ran longer than –maxJobDuration, so Toil killed it.

PARTITION: int = 9

Job was not able to talk to the leader via the job store, so Toil declared it failed.

classmethod to_string(value)[source]

Convert to human-readable string.

Given an int that may be or may be equal to a value from the enum, produce the string value of its matching enum entry, or a stringified int.

Parameters:

value (int)

Return type:

str

class toil.batchSystems.abstractGridEngineBatchSystem.UpdatedBatchJobInfo[source]

Bases: NamedTuple

jobID: int
exitStatus: int

The exit status (integer value) of the job. 0 implies successful.

EXIT_STATUS_UNAVAILABLE_VALUE is used when the exit status is not available (e.g. job is lost, or otherwise died but actual exit code was not reported).

exitReason: BatchJobExitReason | None
wallTime: float | int | None
class toil.batchSystems.abstractGridEngineBatchSystem.BatchSystemCleanupSupport(config, maxCores, maxMemory, maxDisk)[source]

Bases: toil.batchSystems.local_support.BatchSystemLocalSupport

Adds cleanup support when the last running job leaves a node, for batch systems that can’t provide it using the backing scheduler.

Parameters:
classmethod supportsWorkerCleanup()[source]

Whether this batch system supports worker cleanup.

Indicates whether this batch system invokes BatchSystemSupport.workerCleanup() after the last job for a particular workflow invocation finishes. Note that the term worker refers to an entire node, not just a worker process. A worker process may run more than one job sequentially, and more than one concurrent worker process may exist on a worker node, for the same workflow. The batch system is said to shut down after the last worker process terminates.

Return type:

bool

getWorkerContexts()[source]

Get a list of picklable context manager objects to wrap worker work in, in order.

Can be used to ask the Toil worker to do things in-process (such as configuring environment variables, hot-deploying user scripts, or cleaning up a node) that would otherwise require a wrapping “executor” process.

Return type:

List[ContextManager[Any]]

class toil.batchSystems.abstractGridEngineBatchSystem.ExternalBatchIdMessage[source]

Bases: NamedTuple

Produced when using a batch system, links toil assigned batch ID to Batch system ID (Whatever’s returned by local implementation, PID, batch ID, etc)

toil_batch_id: int
external_batch_id: str
batch_system: str
toil.batchSystems.abstractGridEngineBatchSystem.get_job_kind(names)[source]

Return an identifying string for the job.

The result may contain spaces.

Returns: Either the unit name, job name, or display name, which identifies

the kind of job it is to toil. Otherwise “Unknown Job” in case no identifier is available

Parameters:

names (Names)

Return type:

str

class toil.batchSystems.abstractGridEngineBatchSystem.AcceleratorRequirement[source]

Bases: TypedDict

Requirement for one or more computational accelerators, like a GPU or FPGA.

count: int

How many of the accelerator are needed to run the job.

kind: str

What kind of accelerator is required. Can be “gpu”. Other kinds defined in the future might be “fpga”, etc.

model: typing_extensions.NotRequired[str]

What model of accelerator is needed. The exact set of values available depends on what the backing scheduler calls its accelerators; strings like “nvidia-tesla-k80” might be expected to work. If a specific model of accelerator is not required, this should be absent.

brand: typing_extensions.NotRequired[str]

What brand or manufacturer of accelerator is required. The exact set of values available depends on what the backing scheduler calls the brands of its accleerators; strings like “nvidia” or “amd” might be expected to work. If a specific brand of accelerator is not required (for example, because the job can use multiple brands of accelerator that support a given API) this should be absent.

api: typing_extensions.NotRequired[str]

What API is to be used to communicate with the accelerator. This can be “cuda”. Other APIs supported in the future might be “rocm”, “opencl”, “metal”, etc. If the job does not need a particular API to talk to the accelerator, this should be absent.

exception toil.batchSystems.abstractGridEngineBatchSystem.CalledProcessErrorStderr(returncode, cmd, output=None, stderr=None)[source]

Bases: subprocess.CalledProcessError

Version of CalledProcessError that include stderr in the error message if it is set

__str__()[source]

Return str(self).

Return type:

str

toil.batchSystems.abstractGridEngineBatchSystem.old_retry(delays=DEFAULT_DELAYS, timeout=DEFAULT_TIMEOUT, predicate=lambda e: ...)[source]

Deprecated.

Retry an operation while the failure matches a given predicate and until a given timeout expires, waiting a given amount of time in between attempts. This function is a generator that yields contextmanagers. See doctests below for example usage.

Parameters:
  • delays (Iterable[float]) – an interable yielding the time in seconds to wait before each retried attempt, the last element of the iterable will be repeated.

  • timeout (float) – a overall timeout that should not be exceeded for all attempts together. This is a best-effort mechanism only and it won’t abort an ongoing attempt, even if the timeout expires during that attempt.

  • predicate (Callable[[Exception],bool]) – a unary callable returning True if another attempt should be made to recover from the given exception. The default value for this parameter will prevent any retries!

Returns:

a generator yielding context managers, one per attempt

Return type:

Iterator

Retry for a limited amount of time:

>>> true = lambda _:True
>>> false = lambda _:False
>>> i = 0
>>> for attempt in old_retry( delays=[0], timeout=.1, predicate=true ):
...     with attempt:
...         i += 1
...         raise RuntimeError('foo')
Traceback (most recent call last):
...
RuntimeError: foo
>>> i > 1
True

If timeout is 0, do exactly one attempt:

>>> i = 0
>>> for attempt in old_retry( timeout=0 ):
...     with attempt:
...         i += 1
...         raise RuntimeError( 'foo' )
Traceback (most recent call last):
...
RuntimeError: foo
>>> i
1

Don’t retry on success:

>>> i = 0
>>> for attempt in old_retry( delays=[0], timeout=.1, predicate=true ):
...     with attempt:
...         i += 1
>>> i
1

Don’t retry on unless predicate returns True:

>>> i = 0
>>> for attempt in old_retry( delays=[0], timeout=.1, predicate=false):
...     with attempt:
...         i += 1
...         raise RuntimeError( 'foo' )
Traceback (most recent call last):
...
RuntimeError: foo
>>> i
1
toil.batchSystems.abstractGridEngineBatchSystem.DEFAULT_DELAYS = (0, 1, 1, 4, 16, 64)
toil.batchSystems.abstractGridEngineBatchSystem.logger
toil.batchSystems.abstractGridEngineBatchSystem.JobTuple
class toil.batchSystems.abstractGridEngineBatchSystem.AbstractGridEngineBatchSystem(config, maxCores, maxMemory, maxDisk)[source]

Bases: toil.batchSystems.cleanup_support.BatchSystemCleanupSupport

A partial implementation of BatchSystemSupport for batch systems run on a standard HPC cluster. By default auto-deployment is not implemented.

exception GridEngineThreadException[source]

Bases: Exception

Common base class for all non-exit exceptions.

class GridEngineThread(newJobsQueue, updatedJobsQueue, killQueue, killedJobsQueue, boss)[source]

Bases: threading.Thread

A class that represents a thread of control.

This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass.

Parameters:
getBatchSystemID(jobID)[source]

Get batch system-specific job ID

Note: for the moment this is the only consistent way to cleanly get the batch system job ID

Parameters:

jobID (int) – Toil BatchSystem numerical job ID

Return type:

str

forgetJob(jobID)[source]

Remove jobID passed

Parameters:

jobID (int) – toil job ID

Return type:

None

createJobs(newJob)[source]

Create a new job with the given attributes.

Implementation-specific; called by GridEngineThread.run()

Parameters:

newJob (JobTuple)

Return type:

bool

killJobs()[source]

Kill any running jobs within thread

checkOnJobs()[source]

Check and update status of all running jobs.

Respects statePollingWait and will return cached results if not within time period to talk with the scheduler.

run()[source]

Run any new jobs

abstract coalesce_job_exit_codes(batch_job_id_list)[source]

Returns exit codes and possibly exit reasons for a list of jobs, or None if they are running.

Called by GridEngineThread.checkOnJobs().

This is an optional part of the interface. It should raise NotImplementedError if not actually implemented for a particular scheduler.

Parameters:

batch_job_id_list (string) – List of batch system job ID

Return type:

List[Union[int, Tuple[int, Optional[toil.batchSystems.abstractBatchSystem.BatchJobExitReason]], None]]

abstract prepareSubmission(cpu, memory, jobID, command, jobName, job_environment=None, gpus=None)[source]

Preparation in putting together a command-line string for submitting to batch system (via submitJob().)

Param:

int cpu

Param:

int memory

Param:

int jobID: Toil job ID

Param:

string subLine: the command line string to be called

Param:

string jobName: the name of the Toil job, to provide metadata to batch systems if desired

Param:

dict job_environment: the environment variables to be set on the worker

Return type:

List[str]

Parameters:
  • cpu (int)

  • memory (int)

  • jobID (int)

  • command (str)

  • jobName (str)

  • job_environment (Optional[Dict[str, str]])

  • gpus (Optional[int])

abstract submitJob(subLine)[source]

Wrapper routine for submitting the actual command-line call, then processing the output to get the batch system job ID

Param:

string subLine: the literal command line string to be called

Return type:

string: batch system job ID, which will be stored internally

abstract getRunningJobIDs()[source]

Get a list of running job IDs. Implementation-specific; called by boss AbstractGridEngineBatchSystem implementation via AbstractGridEngineBatchSystem.getRunningBatchJobIDs()

Return type:

list

abstract killJob(jobID)[source]

Kill specific job with the Toil job ID. Implementation-specific; called by GridEngineThread.killJobs()

Parameters:

jobID (string) – Toil job ID

abstract getJobExitCode(batchJobID)[source]

Returns job exit code and possibly an instance of abstractBatchSystem.BatchJobExitReason.

Returns None if the job is still running.

If the job is not running but the exit code is not available, it will be EXIT_STATUS_UNAVAILABLE_VALUE. Implementation-specific; called by GridEngineThread.checkOnJobs().

The exit code will only be 0 if the job affirmatively succeeded.

Parameters:

batchjobID (string) – batch system job ID

Return type:

Union[int, Tuple[int, Optional[toil.batchSystems.abstractBatchSystem.BatchJobExitReason]], None]

classmethod supportsAutoDeployment()[source]

Whether this batch system supports auto-deployment of the user script itself.

If it does, the setUserScript() can be invoked to set the resource object representing the user script.

Note to implementors: If your implementation returns True here, it should also override

issueBatchJob(command, jobDesc, job_environment=None)[source]

Issues a job with the specified command to the batch system and returns a unique job ID number.

Parameters:
  • command (str) – the command to execute somewhere to run the Toil worker process

  • job_desc – the JobDescription for the job being run

  • job_environment (Optional[Dict[str, str]]) – a collection of job-specific environment variables to be set on the worker.

Returns:

a unique job ID number that can be used to reference the newly issued job

killBatchJobs(jobIDs)[source]

Kills the given jobs, represented as Job ids, then checks they are dead by checking they are not in the list of issued jobs.

getIssuedBatchJobIDs()[source]

Gets the list of issued jobs

getRunningBatchJobIDs()[source]

Retrieve running job IDs from local and batch scheduler.

Respects statePollingWait and will return cached results if not within time period to talk with the scheduler.

getUpdatedBatchJob(maxWait)[source]

Returns information about job that has updated its status (i.e. ceased running, either successfully or with an error). Each such job will be returned exactly once.

Does not return info for jobs killed by killBatchJobs, although they may cause None to be returned earlier than maxWait.

Parameters:

maxWait – the number of seconds to block, waiting for a result

Returns:

If a result is available, returns UpdatedBatchJobInfo. Otherwise it returns None. wallTime is the number of seconds (a strictly positive float) in wall-clock time the job ran for, or None if this batch system does not support tracking wall time.

shutdown()[source]

Signals thread to shutdown (via sentinel) then cleanly joins the thread

Return type:

None

setEnv(name, value=None)[source]

Set an environment variable for the worker process before it is launched. The worker process will typically inherit the environment of the machine it is running on but this method makes it possible to override specific variables in that inherited environment before the worker is launched. Note that this mechanism is different to the one used by the worker internally to set up the environment of a job. A call to this method affects all jobs issued after this method returns. Note to implementors: This means that you would typically need to copy the variables before enqueuing a job.

If no value is provided it will be looked up from the current environment.

Parameters:
  • name – the environment variable to be set on the worker.

  • value – if given, the environment variable given by name will be set to this value. If None, the variable’s current value will be used as the value on the worker

Raises:

RuntimeError – if value is None and the name cannot be found in the environment

classmethod getWaitDuration()[source]
sleepSeconds(sleeptime=1)[source]

Helper function to drop on all state-querying functions to avoid over-querying.

with_retries(operation, *args, **kwargs)[source]

Call operation with args and kwargs. If one of the calls to a command fails, sleep and try again.