toil.test.batchSystems.batchSystemTest

Attributes

retry_flaky_test

logger

numCores

preemptible

defaultRequirements

Exceptions

InsufficientSystemResources

Common base class for all non-exit exceptions.

Classes

AbstractBatchSystem

An abstract base class to represent the interface the batch system must provide to Toil.

BatchSystemSupport

Partial implementation of AbstractBatchSystem, support methods.

MesosTestSupport

Mixin for test cases that need a running Mesos master and agent on the local host.

SingleMachineBatchSystem

The interface for running jobs on a single machine, runs all the jobs you

Config

Class to represent configuration operations for a toil workflow run.

Toil

A context manager that represents a Toil workflow.

Job

Class represents a unit of work in toil.

JobDescription

Stores all the information that the Toil Leader ever needs to know about a Job.

Requirer

Base class implementing the storage and presentation of requirements.

ToilTest

A common base class for Toil tests.

BatchSystemPluginTest

Class for testing batch system plugin functionality.

hidden

Hide abstract base class from unittest's test case loader

KubernetesBatchSystemTest

Tests against the Kubernetes batch system

KubernetesBatchSystemBenchTest

Kubernetes batch system unit tests that don't need to actually talk to a cluster.

AWSBatchBatchSystemTest

Tests against the AWS Batch batch system

MesosBatchSystemTest

Tests against the Mesos batch system

SingleMachineBatchSystemTest

Tests against the single-machine batch system

MaxCoresSingleMachineBatchSystemTest

This test ensures that single machine batch system doesn't exceed the configured number

Service

Abstract class used to define the interface to a service.

GridEngineBatchSystemTest

Tests against the GridEngine batch system

SlurmBatchSystemTest

Tests against the Slurm batch system

LSFBatchSystemTest

Tests against the LSF batch system

TorqueBatchSystemTest

Tests against the Torque batch system

HTCondorBatchSystemTest

Tests against the HTCondor batch system

SingleMachineBatchSystemJobTest

Tests Toil workflow against the SingleMachine batch system

MesosBatchSystemJobTest

Tests Toil workflow against the Mesos batch system

Functions

add_batch_system_factory(key, class_factory)

Adds a batch system to the registry for workflow or plugin-supplied batch systems.

get_batch_system(key)

Get a batch system class by name.

get_batch_systems()

Get the names of all the availsble batch systems.

restore_batch_system_plugin_state(snapshot)

Restore the batch system registry state to a snapshot from

save_batch_system_plugin_state()

Return a snapshot of the plugin registry that can be restored to remove

cpu_count()

Get the rounded-up integer number of whole CPUs available.

needs_aws_batch(test_item)

Use as a decorator before test classes or methods to run only if AWS Batch

needs_aws_s3(test_item)

Use as a decorator before test classes or methods to run only if AWS S3 is usable.

needs_fetchable_appliance(test_item)

Use as a decorator before test classes or methods to only run them if

needs_gridengine(test_item)

Use as a decorator before test classes or methods to run only if GridEngine is installed.

needs_htcondor(test_item)

Use a decorator before test classes or methods to run only if the HTCondor is installed.

needs_kubernetes(test_item)

Use as a decorator before test classes or methods to run only if Kubernetes is installed and configured.

needs_kubernetes_installed(test_item)

Use as a decorator before test classes or methods to run only if Kubernetes is installed.

needs_lsf(test_item)

Use as a decorator before test classes or methods to only run them if LSF is installed.

needs_mesos(test_item)

Use as a decorator before test classes or methods to run only if Mesos is installed.

needs_slurm(test_item)

Use as a decorator before test classes or methods to run only if Slurm is installed.

needs_torque(test_item)

Use as a decorator before test classes or methods to run only if PBS/Torque is installed.

slow(test_item)

Use this decorator to identify tests that are slow and not critical.

write_temp_file(s, temp_dir)

Dump a string into a temp file and return its path.

parentJob(job, cmd)

childJob(job, cmd)

grandChildJob(job, cmd)

greatGrandChild(cmd)

measureConcurrency(filepath[, sleep_time])

Run in parallel to determine the number of concurrent tasks.

count(delta, file_path)

Increments counter file and returns the max number of times the file

getCounters(path)

resetCounters(path)

get_omp_threads()

Module Contents

class toil.test.batchSystems.batchSystemTest.AbstractBatchSystem[source]

Bases: abc.ABC

An abstract base class to represent the interface the batch system must provide to Toil.

classmethod supportsAutoDeployment()[source]
Abstractmethod:

Return type:

bool

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

classmethod supportsWorkerCleanup()[source]
Abstractmethod:

Return type:

bool

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.

abstract setUserScript(userScript)[source]

Set the user script for this workflow.

This method must be called before the first job is issued to this batch system, and only if supportsAutoDeployment() returns True, otherwise it will raise an exception.

Parameters:

userScript (toil.resource.Resource) – the resource object representing the user script or module and the modules it depends on.

Return type:

None

set_message_bus(message_bus)[source]

Give the batch system an opportunity to connect directly to the message bus, so that it can send informational messages about the jobs it is running to other Toil components.

Parameters:

message_bus (toil.bus.MessageBus)

Return type:

None

abstract issueBatchJob(command, job_desc, 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 (toil.job.JobDescription) – 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

Return type:

int

abstract killBatchJobs(jobIDs)[source]

Kills the given job IDs. After returning, the killed jobs will not appear in the results of getRunningBatchJobIDs. The killed job will not be returned from getUpdatedBatchJob.

Parameters:

jobIDs (List[int]) – list of IDs of jobs to kill

Return type:

None

abstract getIssuedBatchJobIDs()[source]

Gets all currently issued jobs

Returns:

A list of jobs (as job ID numbers) currently issued (may be running, or may be waiting to be run). Despite the result being a list, the ordering should not be depended upon.

Return type:

List[int]

abstract getRunningBatchJobIDs()[source]

Gets a map of jobs as job ID numbers that are currently running (not just waiting) and how long they have been running, in seconds.

Returns:

dictionary with currently running job ID number keys and how many seconds they have been running as the value

Return type:

Dict[int, float]

abstract 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 (int) – 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.

Return type:

Optional[UpdatedBatchJobInfo]

getSchedulingStatusMessage()[source]

Get a log message fragment for the user about anything that might be going wrong in the batch system, if available.

If no useful message is available, return None.

This can be used to report what resource is the limiting factor when scheduling jobs, for example. If the leader thinks the workflow is stuck, the message can be displayed to the user to help them diagnose why it might be stuck.

Returns:

User-directed message about scheduling state.

Return type:

Optional[str]

abstract shutdown()[source]

Called at the completion of a toil invocation. Should cleanly terminate all worker threads.

Return type:

None

abstract 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 (str)

  • value (Optional[str])

Return type:

None

classmethod add_options(parser)[source]

If this batch system provides any command line options, add them to the given parser.

Parameters:

parser (Union[argparse.ArgumentParser, argparse._ArgumentGroup])

Return type:

None

classmethod setOptions(setOption)[source]

Process command line or configuration options relevant to this batch system.

Parameters:

setOption (toil.batchSystems.options.OptionSetter) – A function with signature setOption(option_name, parsing_function=None, check_function=None, default=None, env=None) returning nothing, used to update run configuration as a side effect.

Return type:

None

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.test.batchSystems.batchSystemTest.BatchSystemSupport(config, maxCores, maxMemory, maxDisk)[source]

Bases: AbstractBatchSystem

Partial implementation of AbstractBatchSystem, support methods.

Parameters:
check_resource_request(requirer)[source]

Check resource request is not greater than that available or allowed.

Parameters:
  • requirer (toil.job.Requirer) – Object whose requirements are being checked

  • job_name (str) – Name of the job being checked, for generating a useful error report.

  • detail (str) – Batch-system-specific message to include in the error.

Raises:

InsufficientSystemResources – raised when a resource is requested in an amount greater than allowed

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 (str) – the environment variable to be set on the worker.

  • value (Optional[str]) – 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

Return type:

None

set_message_bus(message_bus)[source]

Give the batch system an opportunity to connect directly to the message bus, so that it can send informational messages about the jobs it is running to other Toil components.

Parameters:

message_bus (toil.bus.MessageBus)

Return type:

None

get_batch_logs_dir()[source]

Get the directory where the backing batch system should save its logs.

Only really makes sense if the backing batch system actually saves logs to a filesystem; Kubernetes for example does not. Ought to be a directory shared between the leader and the workers, if the backing batch system writes logs onto the worker’s view of the filesystem, like many HPC schedulers do.

Return type:

str

format_std_out_err_path(toil_job_id, cluster_job_id, std)[source]

Format path for batch system standard output/error and other files generated by the batch system itself.

Files will be written to the batch logs directory (–batchLogsDir, defaulting to the Toil work directory) with names containing both the Toil and batch system job IDs, for ease of debugging job failures.

Param:

int toil_job_id : The unique id that Toil gives a job.

Param:

cluster_job_id : What the cluster, for example, GridEngine, uses as its internal job id.

Param:

string std : The provenance of the stream (for example: ‘err’ for ‘stderr’ or ‘out’ for ‘stdout’)

Return type:

string : Formatted filename; however if self.config.noStdOutErr is true, returns ‘/dev/null’ or equivalent.

Parameters:
  • toil_job_id (int)

  • cluster_job_id (str)

  • std (str)

format_std_out_err_glob(toil_job_id)[source]

Get a glob string that will match all file paths generated by format_std_out_err_path for a job.

Parameters:

toil_job_id (int)

Return type:

str

static workerCleanup(info)[source]

Cleans up the worker node on batch system shutdown.

Also see supportsWorkerCleanup().

Parameters:

info (WorkerCleanupInfo) – A named tuple consisting of all the relevant information for cleaning up the worker.

Return type:

None

exception toil.test.batchSystems.batchSystemTest.InsufficientSystemResources(requirer, resource, available=None, batch_system=None, source=None, details=[])[source]

Bases: Exception

Common base class for all non-exit exceptions.

Parameters:
  • requirer (toil.job.Requirer)

  • resource (str)

  • available (Optional[toil.job.ParsedRequirement])

  • batch_system (Optional[str])

  • source (Optional[str])

  • details (List[str])

__str__()[source]

Explain the exception.

Return type:

str

class toil.test.batchSystems.batchSystemTest.MesosTestSupport[source]

Mixin for test cases that need a running Mesos master and agent on the local host.

wait_for_master()[source]
class MesosThread(numCores)[source]

Bases: toil.lib.threading.ExceptionalThread

A thread whose join() method re-raises exceptions raised during run(). While join() is idempotent, the exception is only during the first invocation of join() that successfully joined the thread. If join() times out, no exception will be re reraised even though an exception might already have occurred in run().

When subclassing this thread, override tryRun() instead of run().

>>> def f():
...     assert 0
>>> t = ExceptionalThread(target=f)
>>> t.start()
>>> t.join()
Traceback (most recent call last):
...
AssertionError
>>> class MyThread(ExceptionalThread):
...     def tryRun( self ):
...         assert 0
>>> t = MyThread()
>>> t.start()
>>> t.join()
Traceback (most recent call last):
...
AssertionError
lock
abstract mesosCommand()[source]
tryRun()[source]
findMesosBinary(names)[source]
class MesosMasterThread(numCores)[source]

Bases: MesosThread

A thread whose join() method re-raises exceptions raised during run(). While join() is idempotent, the exception is only during the first invocation of join() that successfully joined the thread. If join() times out, no exception will be re reraised even though an exception might already have occurred in run().

When subclassing this thread, override tryRun() instead of run().

>>> def f():
...     assert 0
>>> t = ExceptionalThread(target=f)
>>> t.start()
>>> t.join()
Traceback (most recent call last):
...
AssertionError
>>> class MyThread(ExceptionalThread):
...     def tryRun( self ):
...         assert 0
>>> t = MyThread()
>>> t.start()
>>> t.join()
Traceback (most recent call last):
...
AssertionError
mesosCommand()[source]
class MesosAgentThread(numCores)[source]

Bases: MesosThread

A thread whose join() method re-raises exceptions raised during run(). While join() is idempotent, the exception is only during the first invocation of join() that successfully joined the thread. If join() times out, no exception will be re reraised even though an exception might already have occurred in run().

When subclassing this thread, override tryRun() instead of run().

>>> def f():
...     assert 0
>>> t = ExceptionalThread(target=f)
>>> t.start()
>>> t.join()
Traceback (most recent call last):
...
AssertionError
>>> class MyThread(ExceptionalThread):
...     def tryRun( self ):
...         assert 0
>>> t = MyThread()
>>> t.start()
>>> t.join()
Traceback (most recent call last):
...
AssertionError
mesosCommand()[source]
toil.test.batchSystems.batchSystemTest.add_batch_system_factory(key, class_factory)[source]

Adds a batch system to the registry for workflow or plugin-supplied batch systems.

Parameters:
toil.test.batchSystems.batchSystemTest.get_batch_system(key)[source]

Get a batch system class by name.

Raises:

KeyError if the key is not the name of a batch system, and ImportError if the batch system’s class cannot be loaded.

Parameters:

key (str)

Return type:

Type[toil.batchSystems.abstractBatchSystem.AbstractBatchSystem]

toil.test.batchSystems.batchSystemTest.get_batch_systems()[source]

Get the names of all the availsble batch systems.

Return type:

Sequence[str]

toil.test.batchSystems.batchSystemTest.restore_batch_system_plugin_state(snapshot)[source]

Restore the batch system registry state to a snapshot from save_batch_system_plugin_state().

Parameters:

snapshot (Tuple[List[str], Dict[str, Callable[[], Type[toil.batchSystems.abstractBatchSystem.AbstractBatchSystem]]]])

toil.test.batchSystems.batchSystemTest.save_batch_system_plugin_state()[source]

Return a snapshot of the plugin registry that can be restored to remove added plugins. Useful for testing the plugin system in-process with other tests.

Return type:

Tuple[List[str], Dict[str, Callable[[], Type[toil.batchSystems.abstractBatchSystem.AbstractBatchSystem]]]]

class toil.test.batchSystems.batchSystemTest.SingleMachineBatchSystem(config, maxCores, maxMemory, maxDisk, max_jobs=None)[source]

Bases: toil.batchSystems.abstractBatchSystem.BatchSystemSupport

The interface for running jobs on a single machine, runs all the jobs you give it as they come in, but in parallel.

Uses a single “daddy” thread to manage a fleet of child processes.

Communication with the daddy thread happens via two queues: one queue of jobs waiting to be run (the input queue), and one queue of jobs that are finished/stopped and need to be returned by getUpdatedBatchJob (the output queue).

When the batch system is shut down, the daddy thread is stopped.

If running in debug-worker mode, jobs are run immediately as they are sent to the batch system, in the sending thread, and the daddy thread is not run. But the queues are still used.

Parameters:
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

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.

numCores
minCores = 0.1

The minimal fractional CPU. Tasks with a smaller core requirement will be rounded up to this value.

physicalMemory
daddy()[source]

Be the “daddy” thread.

Our job is to look at jobs from the input queue.

If a job fits in the available resources, we allocate resources for it and kick off a child process.

We also check on our children.

When a child finishes, we reap it, release its resources, and put its information in the output queue.

getSchedulingStatusMessage()[source]

Get a log message fragment for the user about anything that might be going wrong in the batch system, if available.

If no useful message is available, return None.

This can be used to report what resource is the limiting factor when scheduling jobs, for example. If the leader thinks the workflow is stuck, the message can be displayed to the user to help them diagnose why it might be stuck.

Returns:

User-directed message about scheduling state.

check_resource_request(requirer)[source]

Check resource request is not greater than that available or allowed.

Parameters:
  • requirer (toil.job.Requirer) – Object whose requirements are being checked

  • job_name (str) – Name of the job being checked, for generating a useful error report.

  • detail (str) – Batch-system-specific message to include in the error.

Raises:

InsufficientSystemResources – raised when a resource is requested in an amount greater than allowed

Return type:

None

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

Adds the command and resources to a queue to be run.

Parameters:
Return type:

int

killBatchJobs(jobIDs)[source]

Kills jobs by ID.

Parameters:

jobIDs (List[int])

Return type:

None

getIssuedBatchJobIDs()[source]

Just returns all the jobs that have been run, but not yet returned as updated.

Return type:

List[int]

getRunningBatchJobIDs()[source]

Gets a map of jobs as job ID numbers that are currently running (not just waiting) and how long they have been running, in seconds.

Returns:

dictionary with currently running job ID number keys and how many seconds they have been running as the value

Return type:

Dict[int, float]

shutdown()[source]

Terminate cleanly and join daddy thread.

Return type:

None

getUpdatedBatchJob(maxWait)[source]

Returns a tuple of a no-longer-running job, the return value of its process, and its runtime, or None.

Parameters:

maxWait (int)

Return type:

Optional[toil.batchSystems.abstractBatchSystem.UpdatedBatchJobInfo]

classmethod add_options(parser)[source]

If this batch system provides any command line options, add them to the given parser.

Parameters:

parser (Union[argparse.ArgumentParser, argparse._ArgumentGroup])

Return type:

None

classmethod setOptions(setOption)[source]

Process command line or configuration options relevant to this batch system.

Parameters:

setOption (toil.batchSystems.options.OptionSetter) – A function with signature setOption(option_name, parsing_function=None, check_function=None, default=None, env=None) returning nothing, used to update run configuration as a side effect.

class toil.test.batchSystems.batchSystemTest.Config[source]

Class to represent configuration operations for a toil workflow run.

logFile: str | None
logRotating: bool
cleanWorkDir: str
max_jobs: int
max_local_jobs: int
manualMemArgs: bool
run_local_jobs_on_workers: bool
coalesceStatusCalls: bool
mesos_endpoint: str | None
mesos_framework_id: str | None
mesos_role: str | None
mesos_name: str
kubernetes_host_path: str | None
kubernetes_owner: str | None
kubernetes_service_account: str | None
kubernetes_pod_timeout: float
kubernetes_privileged: bool
tes_endpoint: str
tes_user: str
tes_password: str
tes_bearer_token: str
aws_batch_region: str | None
aws_batch_queue: str | None
aws_batch_job_role_arn: str | None
scale: float
batchSystem: str
batch_logs_dir: str | None

The backing scheduler will be instructed, if possible, to save logs to this directory, where the leader can read them.

statePollingWait: int
state_polling_timeout: int
disableAutoDeployment: bool
workflowID: str | None

This attribute uniquely identifies the job store and therefore the workflow. It is necessary in order to distinguish between two consecutive workflows for which self.jobStore is the same, e.g. when a job store name is reused after a previous run has finished successfully and its job store has been clean up.

workflowAttemptNumber: int
jobStore: str
logLevel: str
colored_logs: bool
workDir: str | None
coordination_dir: str | None
noStdOutErr: bool
stats: bool
clean: str | None
clusterStats: str
restart: bool
caching: bool | None
symlinkImports: bool
moveOutputs: bool
provisioner: str | None
nodeTypes: List[Tuple[Set[str], float | None]]
minNodes: List[int]
maxNodes: List[int]
targetTime: float
betaInertia: float
scaleInterval: int
preemptibleCompensation: float
nodeStorage: int
nodeStorageOverrides: List[str]
metrics: bool
assume_zero_overhead: bool
maxPreemptibleServiceJobs: int
maxServiceJobs: int
deadlockWait: float | int
deadlockCheckInterval: float | int
defaultMemory: int
defaultCores: float | int
defaultDisk: int
defaultPreemptible: bool
defaultAccelerators: List[toil.job.AcceleratorRequirement]
maxCores: int
maxMemory: int
maxDisk: int
retryCount: int
enableUnlimitedPreemptibleRetries: bool
doubleMem: bool
maxJobDuration: int
rescueJobsFrequency: int
job_store_timeout: float
maxLogFileSize: int
writeLogs: str
writeLogsGzip: str
writeLogsFromAllJobs: bool
write_messages: str | None
realTimeLogging: bool
environment: Dict[str, str]
disableChaining: bool
disableJobStoreChecksumVerification: bool
sseKey: str | None
servicePollingInterval: int
useAsync: bool
forceDockerAppliance: bool
statusWait: int
disableProgress: bool
readGlobalFileMutableByDefault: bool
debugWorker: bool
disableWorkerOutputCapture: bool
badWorker: float
badWorkerFailInterval: float
kill_polling_interval: int
cwl: bool
set_from_default_config()[source]
Return type:

None

prepare_start()[source]

After options are set, prepare for initial start of workflow.

Return type:

None

prepare_restart()[source]

Before restart options are set, prepare for a restart of a workflow. Set up any execution-specific parameters and clear out any stale ones.

Return type:

None

setOptions(options)[source]

Creates a config object from the options object.

Parameters:

options (argparse.Namespace)

Return type:

None

check_configuration_consistency()[source]

Old checks that cannot be fit into an action class for argparse

Return type:

None

__eq__(other)[source]

Return self==value.

Parameters:

other (object)

Return type:

bool

__hash__()[source]

Return hash(self).

Return type:

int

class toil.test.batchSystems.batchSystemTest.Toil(options)[source]

Bases: ContextManager[Toil]

A context manager that represents a Toil workflow.

Specifically the batch system, job store, and its configuration.

Parameters:

options (argparse.Namespace)

config: Config
__enter__()[source]

Derive configuration from the command line options.

Then load the job store and, on restart, consolidate the derived configuration with the one from the previous invocation of the workflow.

Return type:

Toil

__exit__(exc_type, exc_val, exc_tb)[source]

Clean up after a workflow invocation.

Depending on the configuration, delete the job store.

Parameters:
Return type:

Literal[False]

start(rootJob)[source]

Invoke a Toil workflow with the given job as the root for an initial run.

This method must be called in the body of a with Toil(...) as toil: statement. This method should not be called more than once for a workflow that has not finished.

Parameters:

rootJob (toil.job.Job) – The root job of the workflow

Returns:

The root job’s return value

Return type:

Any

restart()[source]

Restarts a workflow that has been interrupted.

Returns:

The root job’s return value

Return type:

Any

classmethod getJobStore(locator)[source]

Create an instance of the concrete job store implementation that matches the given locator.

Parameters:

locator (str) – The location of the job store to be represent by the instance

Returns:

an instance of a concrete subclass of AbstractJobStore

Return type:

toil.jobStores.abstractJobStore.AbstractJobStore

static parseLocator(locator)[source]
Parameters:

locator (str)

Return type:

Tuple[str, str]

static buildLocator(name, rest)[source]
Parameters:
Return type:

str

classmethod resumeJobStore(locator)[source]
Parameters:

locator (str)

Return type:

toil.jobStores.abstractJobStore.AbstractJobStore

static createBatchSystem(config)[source]

Create an instance of the batch system specified in the given config.

Parameters:

config (Config) – the current configuration

Returns:

an instance of a concrete subclass of AbstractBatchSystem

Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

importFile(srcUrl: str, sharedFileName: str, symlink: bool = True) None[source]
importFile(srcUrl: str, sharedFileName: None = None, symlink: bool = True) toil.fileStores.FileID
import_file(src_uri: str, shared_file_name: str, symlink: bool = True, check_existence: bool = True) None[source]
import_file(src_uri: str, shared_file_name: None = None, symlink: bool = True, check_existence: bool = True) toil.fileStores.FileID

Import the file at the given URL into the job store.

By default, returns None if the file does not exist.

Parameters:

check_existence – If true, raise FileNotFoundError if the file does not exist. If false, return None when the file does not exist.

See toil.jobStores.abstractJobStore.AbstractJobStore.importFile() for a full description

exportFile(jobStoreFileID, dstUrl)[source]
Parameters:
Return type:

None

export_file(file_id, dst_uri)[source]

Export file to destination pointed at by the destination URL.

See toil.jobStores.abstractJobStore.AbstractJobStore.exportFile() for a full description

Parameters:
Return type:

None

static normalize_uri(uri, check_existence=False)[source]

Given a URI, if it has no scheme, prepend “file:”.

Parameters:
  • check_existence (bool) – If set, raise FileNotFoundError if a URI points to a local file that does not exist.

  • uri (str)

Return type:

str

static getToilWorkDir(configWorkDir=None)[source]

Return a path to a writable directory under which per-workflow directories exist.

This directory is always required to exist on a machine, even if the Toil worker has not run yet. If your workers and leader have different temp directories, you may need to set TOIL_WORKDIR.

Parameters:

configWorkDir (Optional[str]) – Value passed to the program using the –workDir flag

Returns:

Path to the Toil work directory, constant across all machines

Return type:

str

classmethod get_toil_coordination_dir(config_work_dir, config_coordination_dir)[source]

Return a path to a writable directory, which will be in memory if convenient. Ought to be used for file locking and coordination.

Parameters:
  • config_work_dir (Optional[str]) – Value passed to the program using the –workDir flag

  • config_coordination_dir (Optional[str]) – Value passed to the program using the –coordinationDir flag

  • workflow_id – Used if a tmpdir_prefix exists to create full directory paths unique per workflow

Returns:

Path to the Toil coordination directory. Ought to be on a POSIX filesystem that allows directories containing open files to be deleted.

Return type:

str

static get_workflow_path_component(workflow_id)[source]

Get a safe filesystem path component for a workflow.

Will be consistent for all processes on a given machine, and different for all processes on different machines.

Parameters:

workflow_id (str) – The ID of the current Toil workflow.

Return type:

str

classmethod getLocalWorkflowDir(workflowID, configWorkDir=None)[source]

Return the directory where worker directories and the cache will be located for this workflow on this machine.

Parameters:
  • configWorkDir (Optional[str]) – Value passed to the program using the –workDir flag

  • workflowID (str)

Returns:

Path to the local workflow directory on this machine

Return type:

str

classmethod get_local_workflow_coordination_dir(workflow_id, config_work_dir, config_coordination_dir)[source]

Return the directory where coordination files should be located for this workflow on this machine. These include internal Toil databases and lock files for the machine.

If an in-memory filesystem is available, it is used. Otherwise, the local workflow directory, which may be on a shared network filesystem, is used.

Parameters:
  • workflow_id (str) – Unique ID of the current workflow.

  • config_work_dir (Optional[str]) – Value used for the work directory in the current Toil Config.

  • config_coordination_dir (Optional[str]) – Value used for the coordination directory in the current Toil Config.

Returns:

Path to the local workflow coordination directory on this machine.

Return type:

str

class toil.test.batchSystems.batchSystemTest.Job(memory=None, cores=None, disk=None, accelerators=None, preemptible=None, preemptable=None, unitName='', checkpoint=False, displayName='', descriptionClass=None, local=None)[source]

Class represents a unit of work in toil.

Parameters:
  • memory (Optional[ParseableIndivisibleResource])

  • cores (Optional[ParseableDivisibleResource])

  • disk (Optional[ParseableIndivisibleResource])

  • accelerators (Optional[ParseableAcceleratorRequirement])

  • preemptible (Optional[ParseableFlag])

  • preemptable (Optional[ParseableFlag])

  • unitName (Optional[str])

  • checkpoint (Optional[bool])

  • displayName (Optional[str])

  • descriptionClass (Optional[type])

  • local (Optional[bool])

__str__()[source]

Produce a useful logging string to identify this Job and distinguish it from its JobDescription.

check_initialized()[source]

Ensure that Job.__init__() has been called by any subclass __init__().

This uses the fact that the self._description instance variable should always be set after __init__().

If __init__() has not been called, raise an error.

Return type:

None

property jobStoreID: str | TemporaryID

Get the ID of this Job.

Return type:

Union[str, TemporaryID]

property description: JobDescription

Expose the JobDescription that describes this job.

Return type:

JobDescription

property disk: int

The maximum number of bytes of disk the job will require to run.

Return type:

int

property memory
The maximum number of bytes of memory the job will require to run.
property cores: int | float

The number of CPU cores required.

Return type:

Union[int, float]

property accelerators: List[AcceleratorRequirement]

Any accelerators, such as GPUs, that are needed.

Return type:

List[AcceleratorRequirement]

property preemptible: bool

Whether the job can be run on a preemptible node.

Return type:

bool

preemptable()[source]
property checkpoint: bool

Determine if the job is a checkpoint job or not.

Return type:

bool

assignConfig(config)[source]

Assign the given config object.

It will be used by various actions implemented inside the Job class.

Parameters:

config (toil.common.Config) – Config object to query

Return type:

None

run(fileStore)[source]

Override this function to perform work and dynamically create successor jobs.

Parameters:

fileStore (toil.fileStores.abstractFileStore.AbstractFileStore) – Used to create local and globally sharable temporary files and to send log messages to the leader process.

Returns:

The return value of the function can be passed to other jobs by means of toil.job.Job.rv().

Return type:

Any

addChild(childJob)[source]

Add a childJob to be run as child of this job.

Child jobs will be run directly after this job’s toil.job.Job.run() method has completed.

Returns:

childJob: for call chaining

Parameters:

childJob (Job)

Return type:

Job

hasChild(childJob)[source]

Check if childJob is already a child of this job.

Returns:

True if childJob is a child of the job, else False.

Parameters:

childJob (Job)

Return type:

bool

addFollowOn(followOnJob)[source]

Add a follow-on job.

Follow-on jobs will be run after the child jobs and their successors have been run.

Returns:

followOnJob for call chaining

Parameters:

followOnJob (Job)

Return type:

Job

hasPredecessor(job)[source]

Check if a given job is already a predecessor of this job.

Parameters:

job (Job)

Return type:

bool

hasFollowOn(followOnJob)[source]

Check if given job is already a follow-on of this job.

Returns:

True if the followOnJob is a follow-on of this job, else False.

Parameters:

followOnJob (Job)

Return type:

bool

addService(service, parentService=None)[source]

Add a service.

The toil.job.Job.Service.start() method of the service will be called after the run method has completed but before any successors are run. The service’s toil.job.Job.Service.stop() method will be called once the successors of the job have been run.

Services allow things like databases and servers to be started and accessed by jobs in a workflow.

Raises:

toil.job.JobException – If service has already been made the child of a job or another service.

Parameters:
  • service (Job) – Service to add.

  • parentService (Optional[Job]) – Service that will be started before ‘service’ is started. Allows trees of services to be established. parentService must be a service of this job.

Returns:

a promise that will be replaced with the return value from toil.job.Job.Service.start() of service in any successor of the job.

Return type:

Promise

hasService(service)[source]

Return True if the given Service is a service of this job, and False otherwise.

Parameters:

service (Job)

Return type:

bool

addChildFn(fn, *args, **kwargs)[source]

Add a function as a child job.

Parameters:

fn (Callable) – Function to be run as a child job with *args and **kwargs as arguments to this function. See toil.job.FunctionWrappingJob for reserved keyword arguments used to specify resource requirements.

Returns:

The new child job that wraps fn.

Return type:

FunctionWrappingJob

addFollowOnFn(fn, *args, **kwargs)[source]

Add a function as a follow-on job.

Parameters:

fn (Callable) – Function to be run as a follow-on job with *args and **kwargs as arguments to this function. See toil.job.FunctionWrappingJob for reserved keyword arguments used to specify resource requirements.

Returns:

The new follow-on job that wraps fn.

Return type:

FunctionWrappingJob

addChildJobFn(fn, *args, **kwargs)[source]

Add a job function as a child job.

See toil.job.JobFunctionWrappingJob for a definition of a job function.

Parameters:

fn (Callable) – Job function to be run as a child job with *args and **kwargs as arguments to this function. See toil.job.JobFunctionWrappingJob for reserved keyword arguments used to specify resource requirements.

Returns:

The new child job that wraps fn.

Return type:

FunctionWrappingJob

addFollowOnJobFn(fn, *args, **kwargs)[source]

Add a follow-on job function.

See toil.job.JobFunctionWrappingJob for a definition of a job function.

Parameters:

fn (Callable) – Job function to be run as a follow-on job with *args and **kwargs as arguments to this function. See toil.job.JobFunctionWrappingJob for reserved keyword arguments used to specify resource requirements.

Returns:

The new follow-on job that wraps fn.

Return type:

FunctionWrappingJob

property tempDir: str

Shortcut to calling job.fileStore.getLocalTempDir().

Temp dir is created on first call and will be returned for first and future calls :return: Path to tempDir. See job.fileStore.getLocalTempDir

Return type:

str

log(text, level=logging.INFO)[source]

Log using fileStore.log_to_leader().

Parameters:

text (str)

Return type:

None

static wrapFn(fn, *args, **kwargs)[source]

Makes a Job out of a function.

Convenience function for constructor of toil.job.FunctionWrappingJob.

Parameters:

fn – Function to be run with *args and **kwargs as arguments. See toil.job.JobFunctionWrappingJob for reserved keyword arguments used to specify resource requirements.

Returns:

The new function that wraps fn.

Return type:

FunctionWrappingJob

static wrapJobFn(fn, *args, **kwargs)[source]

Makes a Job out of a job function.

Convenience function for constructor of toil.job.JobFunctionWrappingJob.

Parameters:

fn – Job function to be run with *args and **kwargs as arguments. See toil.job.JobFunctionWrappingJob for reserved keyword arguments used to specify resource requirements.

Returns:

The new job function that wraps fn.

Return type:

JobFunctionWrappingJob

encapsulate(name=None)[source]

Encapsulates the job, see toil.job.EncapsulatedJob. Convenience function for constructor of toil.job.EncapsulatedJob.

Parameters:

name (Optional[str]) – Human-readable name for the encapsulated job.

Returns:

an encapsulated version of this job.

Return type:

EncapsulatedJob

rv(*path)[source]

Create a promise (toil.job.Promise).

The “promise” representing a return value of the job’s run method, or, in case of a function-wrapping job, the wrapped function’s return value.

Parameters:

path ((Any)) – Optional path for selecting a component of the promised return value. If absent or empty, the entire return value will be used. Otherwise, the first element of the path is used to select an individual item of the return value. For that to work, the return value must be a list, dictionary or of any other type implementing the __getitem__() magic method. If the selected item is yet another composite value, the second element of the path can be used to select an item from it, and so on. For example, if the return value is [6,{‘a’:42}], .rv(0) would select 6 , rv(1) would select {‘a’:3} while rv(1,’a’) would select 3. To select a slice from a return value that is slicable, e.g. tuple or list, the path element should be a slice object. For example, assuming that the return value is [6, 7, 8, 9] then .rv(slice(1, 3)) would select [7, 8]. Note that slicing really only makes sense at the end of path.

Returns:

A promise representing the return value of this jobs toil.job.Job.run() method.

Return type:

Promise

registerPromise(path)[source]
prepareForPromiseRegistration(jobStore)[source]

Set up to allow this job’s promises to register themselves.

Prepare this job (the promisor) so that its promises can register themselves with it, when the jobs they are promised to (promisees) are serialized.

The promissee holds the reference to the promise (usually as part of the job arguments) and when it is being pickled, so will the promises it refers to. Pickling a promise triggers it to be registered with the promissor.

Parameters:

jobStore (toil.jobStores.abstractJobStore.AbstractJobStore)

Return type:

None

checkJobGraphForDeadlocks()[source]

Ensures that a graph of Jobs (that hasn’t yet been saved to the JobStore) doesn’t contain any pathological relationships between jobs that would result in deadlocks if we tried to run the jobs.

See toil.job.Job.checkJobGraphConnected(), toil.job.Job.checkJobGraphAcyclic() and toil.job.Job.checkNewCheckpointsAreLeafVertices() for more info.

Raises:

toil.job.JobGraphDeadlockException – if the job graph is cyclic, contains multiple roots or contains checkpoint jobs that are not leaf vertices when defined (see toil.job.Job.checkNewCheckpointsAreLeaves()).

getRootJobs()[source]

Return the set of root job objects that contain this job.

A root job is a job with no predecessors (i.e. which are not children, follow-ons, or services).

Only deals with jobs created here, rather than loaded from the job store.

Return type:

Set[Job]

checkJobGraphConnected()[source]
Raises:

toil.job.JobGraphDeadlockException – if toil.job.Job.getRootJobs() does not contain exactly one root job.

As execution always starts from one root job, having multiple root jobs will cause a deadlock to occur.

Only deals with jobs created here, rather than loaded from the job store.

checkJobGraphAcylic()[source]
Raises:

toil.job.JobGraphDeadlockException – if the connected component of jobs containing this job contains any cycles of child/followOn dependencies in the augmented job graph (see below). Such cycles are not allowed in valid job graphs.

A follow-on edge (A, B) between two jobs A and B is equivalent to adding a child edge to B from (1) A, (2) from each child of A, and (3) from the successors of each child of A. We call each such edge an edge an “implied” edge. The augmented job graph is a job graph including all the implied edges.

For a job graph G = (V, E) the algorithm is O(|V|^2). It is O(|V| + |E|) for a graph with no follow-ons. The former follow-on case could be improved!

Only deals with jobs created here, rather than loaded from the job store.

checkNewCheckpointsAreLeafVertices()[source]

A checkpoint job is a job that is restarted if either it fails, or if any of its successors completely fails, exhausting their retries.

A job is a leaf it is has no successors.

A checkpoint job must be a leaf when initially added to the job graph. When its run method is invoked it can then create direct successors. This restriction is made to simplify implementation.

Only works on connected components of jobs not yet added to the JobStore.

Raises:

toil.job.JobGraphDeadlockException – if there exists a job being added to the graph for which checkpoint=True and which is not a leaf.

Return type:

None

defer(function, *args, **kwargs)[source]

Register a deferred function, i.e. a callable that will be invoked after the current attempt at running this job concludes. A job attempt is said to conclude when the job function (or the toil.job.Job.run() method for class-based jobs) returns, raises an exception or after the process running it terminates abnormally. A deferred function will be called on the node that attempted to run the job, even if a subsequent attempt is made on another node. A deferred function should be idempotent because it may be called multiple times on the same node or even in the same process. More than one deferred function may be registered per job attempt by calling this method repeatedly with different arguments. If the same function is registered twice with the same or different arguments, it will be called twice per job attempt.

Examples for deferred functions are ones that handle cleanup of resources external to Toil, like Docker containers, files outside the work directory, etc.

Parameters:
  • function (callable) – The function to be called after this job concludes.

  • args (list) – The arguments to the function

  • kwargs (dict) – The keyword arguments to the function

Return type:

None

class Runner[source]

Used to setup and run Toil workflow.

static getDefaultArgumentParser(jobstore_as_flag=False)[source]

Get argument parser with added toil workflow options.

Parameters:

jobstore_as_flag (bool) – make the job store option a –jobStore flag instead of a required jobStore positional argument.

Returns:

The argument parser used by a toil workflow with added Toil options.

Return type:

argparse.ArgumentParser

static getDefaultOptions(jobStore=None, jobstore_as_flag=False)[source]

Get default options for a toil workflow.

Parameters:
  • jobStore (Optional[str]) – A string describing the jobStore for the workflow.

  • jobstore_as_flag (bool) – make the job store option a –jobStore flag instead of a required jobStore positional argument.

Returns:

The options used by a toil workflow.

Return type:

argparse.Namespace

static addToilOptions(parser, jobstore_as_flag=False)[source]

Adds the default toil options to an optparse or argparse parser object.

Parameters:
Return type:

None

static startToil(job, options)[source]

Run the toil workflow using the given options.

Deprecated by toil.common.Toil.start.

(see Job.Runner.getDefaultOptions and Job.Runner.addToilOptions) starting with this job. :param job: root job of the workflow :raises: toil.exceptions.FailedJobsException if at the end of function there remain failed jobs. :return: The return value of the root job’s run function.

Parameters:

job (Job)

Return type:

Any

class Service(memory=None, cores=None, disk=None, accelerators=None, preemptible=None, unitName=None)[source]

Bases: Requirer

Abstract class used to define the interface to a service.

Should be subclassed by the user to define services.

Is not executed as a job; runs within a ServiceHostJob.

abstract start(job)[source]

Start the service.

Parameters:

job (Job) – The underlying host job that the service is being run in. Can be used to register deferred functions, or to access the fileStore for creating temporary files.

Returns:

An object describing how to access the service. The object must be pickleable and will be used by jobs to access the service (see toil.job.Job.addService()).

Return type:

Any

abstract stop(job)[source]

Stops the service. Function can block until complete.

Parameters:

job (Job) – The underlying host job that the service is being run in. Can be used to register deferred functions, or to access the fileStore for creating temporary files.

Return type:

None

check()[source]

Checks the service is still running.

Raises:

exceptions.RuntimeError – If the service failed, this will cause the service job to be labeled failed.

Returns:

True if the service is still running, else False. If False then the service job will be terminated, and considered a success. Important point: if the service job exits due to a failure, it should raise a RuntimeError, not return False!

Return type:

bool

getUserScript()[source]
Return type:

toil.resource.ModuleDescriptor

getTopologicalOrderingOfJobs()[source]
Returns:

a list of jobs such that for all pairs of indices i, j for which i < j, the job at index i can be run before the job at index j.

Return type:

List[Job]

Only considers jobs in this job’s subgraph that are newly added, not loaded from the job store.

Ignores service jobs.

saveBody(jobStore)[source]

Save the execution data for just this job to the JobStore, and fill in the JobDescription with the information needed to retrieve it.

The Job’s JobDescription must have already had a real jobStoreID assigned to it.

Does not save the JobDescription.

Parameters:

jobStore (toil.jobStores.abstractJobStore.AbstractJobStore) – The job store to save the job body into.

Return type:

None

saveAsRootJob(jobStore)[source]

Save this job to the given jobStore as the root job of the workflow.

Returns:

the JobDescription describing this job.

Parameters:

jobStore (toil.jobStores.abstractJobStore.AbstractJobStore)

Return type:

JobDescription

classmethod loadJob(job_store, job_description)[source]

Retrieves a toil.job.Job instance from a JobStore

Parameters:
Returns:

The job referenced by the JobDescription.

Return type:

Job

set_debug_flag(flag)[source]

Enable the given debug option on the job.

Parameters:

flag (str)

Return type:

None

has_debug_flag(flag)[source]

Return true if the given debug flag is set.

Parameters:

flag (str)

Return type:

bool

files_downloaded_hook(host_and_job_paths=None)[source]

Function that subclasses can call when they have downloaded their input files.

Will abort the job if the “download_only” debug flag is set.

Can be hinted a list of file path pairs outside and inside the job container, in which case the container environment can be reconstructed.

Parameters:

host_and_job_paths (Optional[List[Tuple[str, str]]])

Return type:

None

class toil.test.batchSystems.batchSystemTest.JobDescription(requirements, jobName, unitName='', displayName='', local=None)[source]

Bases: Requirer

Stores all the information that the Toil Leader ever needs to know about a Job.

This includes:
  • Resource requirements.

  • Which jobs are children or follow-ons or predecessors of this job.

  • A reference to the Job object in the job store.

Can be obtained from an actual (i.e. executable) Job object, and can be used to obtain the Job object from the JobStore.

Never contains other Jobs or JobDescriptions: all reference is by ID.

Subclassed into variants for checkpoint jobs and service jobs that have their specific parameters.

Parameters:
  • requirements (Mapping[str, Union[int, str, bool]])

  • jobName (str)

  • unitName (Optional[str])

  • displayName (Optional[str])

  • local (Optional[bool])

get_names()[source]

Get the names and ID of this job as a named tuple.

Return type:

toil.bus.Names

get_chain()[source]

Get all the jobs that executed in this job’s chain, in order.

For each job, produces a named tuple with its various names and its original job store ID. The jobs in the chain are in execution order.

If the job hasn’t run yet or it didn’t chain, produces a one-item list.

Return type:

List[toil.bus.Names]

serviceHostIDsInBatches()[source]

Find all batches of service host job IDs that can be started at the same time.

(in the order they need to start in)

Return type:

Iterator[List[str]]

successorsAndServiceHosts()[source]

Get an iterator over all child, follow-on, and service job IDs.

Return type:

Iterator[str]

allSuccessors()[source]

Get an iterator over all child, follow-on, and chained, inherited successor job IDs.

Follow-ons will come before children.

Return type:

Iterator[str]

successors_by_phase()[source]

Get an iterator over all child/follow-on/chained inherited successor job IDs, along with their phase numbere on the stack.

Phases ececute higher numbers to lower numbers.

Return type:

Iterator[Tuple[int, str]]

property services
Get a collection of the IDs of service host jobs for this job, in arbitrary order.

Will be empty if the job has no unfinished services.

has_body()[source]

Returns True if we have a job body associated, and False otherwise.

Return type:

bool

attach_body(file_store_id, user_script)[source]

Attach a job body to this JobDescription.

Takes the file store ID that the body is stored at, and the required user script module.

The file store ID can also be “firstJob” for the root job, stored as a shared file instead.

Parameters:
Return type:

None

detach_body()[source]

Drop the body reference from a JobDescription.

Return type:

None

get_body()[source]

Get the information needed to load the job body.

Returns:

a file store ID (or magic shared file name “firstJob”) and a user script module.

Return type:

Tuple[str, toil.resource.ModuleDescriptor]

Fails if no body is attached; check has_body() first.

nextSuccessors()[source]

Return the collection of job IDs for the successors of this job that are ready to run.

If those jobs have multiple predecessor relationships, they may still be blocked on other jobs.

Returns None when at the final phase (all successors done), and an empty collection if there are more phases but they can’t be entered yet (e.g. because we are waiting for the job itself to run).

Return type:

Optional[Set[str]]

filterSuccessors(predicate)[source]

Keep only successor jobs for which the given predicate function approves.

The predicate function is called with the job’s ID.

Treats all other successors as complete and forgets them.

Parameters:

predicate (Callable[[str], bool])

Return type:

None

filterServiceHosts(predicate)[source]

Keep only services for which the given predicate approves.

The predicate function is called with the service host job’s ID.

Treats all other services as complete and forgets them.

Parameters:

predicate (Callable[[str], bool])

Return type:

None

clear_nonexistent_dependents(job_store)[source]

Remove all references to child, follow-on, and associated service jobs that do not exist.

That is to say, all those that have been completed and removed.

Parameters:

job_store (toil.jobStores.abstractJobStore.AbstractJobStore)

Return type:

None

clear_dependents()[source]

Remove all references to successor and service jobs.

Return type:

None

is_subtree_done()[source]

Check if the subtree is done.

Returns:

True if the job appears to be done, and all related child, follow-on, and service jobs appear to be finished and removed.

Return type:

bool

replace(other)[source]

Take on the ID of another JobDescription, retaining our own state and type.

When updated in the JobStore, we will save over the other JobDescription.

Useful for chaining jobs: the chained-to job can replace the parent job.

Merges cleanup state and successors other than this job from the job being replaced into this one.

Parameters:

other (JobDescription) – Job description to replace.

Return type:

None

assert_is_not_newer_than(other)[source]

Make sure this JobDescription is not newer than a prospective new version of the JobDescription.

Parameters:

other (JobDescription)

Return type:

None

is_updated_by(other)[source]

Return True if the passed JobDescription is a distinct, newer version of this one.

Parameters:

other (JobDescription)

Return type:

bool

addChild(childID)[source]

Make the job with the given ID a child of the described job.

Parameters:

childID (str)

Return type:

None

addFollowOn(followOnID)[source]

Make the job with the given ID a follow-on of the described job.

Parameters:

followOnID (str)

Return type:

None

addServiceHostJob(serviceID, parentServiceID=None)[source]

Make the ServiceHostJob with the given ID a service of the described job.

If a parent ServiceHostJob ID is given, that parent service will be started first, and must have already been added.

hasChild(childID)[source]

Return True if the job with the given ID is a child of the described job.

Parameters:

childID (str)

Return type:

bool

hasFollowOn(followOnID)[source]

Test if the job with the given ID is a follow-on of the described job.

Parameters:

followOnID (str)

Return type:

bool

hasServiceHostJob(serviceID)[source]

Test if the ServiceHostJob is a service of the described job.

Return type:

bool

renameReferences(renames)[source]

Apply the given dict of ID renames to all references to jobs.

Does not modify our own ID or those of finished predecessors. IDs not present in the renames dict are left as-is.

Parameters:

renames (Dict[TemporaryID, str]) – Rename operations to apply.

Return type:

None

addPredecessor()[source]

Notify the JobDescription that a predecessor has been added to its Job.

Return type:

None

onRegistration(jobStore)[source]

Perform setup work that requires the JobStore.

Called by the Job saving logic when this JobDescription meets the JobStore and has its ID assigned.

Overridden to perform setup work (like hooking up flag files for service jobs) that requires the JobStore.

Parameters:

jobStore (toil.jobStores.abstractJobStore.AbstractJobStore) – The job store we are being placed into

Return type:

None

setupJobAfterFailure(exit_status=None, exit_reason=None)[source]

Configure job after a failure.

Reduce the remainingTryCount if greater than zero and set the memory to be at least as big as the default memory (in case of exhaustion of memory, which is common).

Requires a configuration to have been assigned (see toil.job.Requirer.assignConfig()).

Parameters:
Return type:

None

getLogFileHandle(jobStore)[source]

Create a context manager that yields a file handle to the log file.

Assumes logJobStoreFileID is set.

property remainingTryCount
Get the number of tries remaining.

The try count set on the JobDescription, or the default based on the retry count from the config if none is set.

clearRemainingTryCount()[source]

Clear remainingTryCount and set it back to its default value.

Returns:

True if a modification to the JobDescription was made, and False otherwise.

Return type:

bool

__str__()[source]

Produce a useful logging string identifying this job.

Return type:

str

__repr__()[source]

Return repr(self).

reserve_versions(count)[source]

Reserve a job version number for later, for journaling asynchronously.

Parameters:

count (int)

Return type:

None

pre_update_hook()[source]

Run before pickling and saving a created or updated version of this job.

Called by the job store.

Return type:

None

class toil.test.batchSystems.batchSystemTest.Requirer(requirements)[source]

Base class implementing the storage and presentation of requirements.

Has cores, memory, disk, and preemptability as properties.

Parameters:

requirements (Mapping[str, ParseableRequirement])

assignConfig(config)[source]

Assign the given config object to be used to provide default values.

Must be called exactly once on a loaded JobDescription before any requirements are queried.

Parameters:

config (toil.common.Config) – Config object to query

Return type:

None

__getstate__()[source]

Return the dict to use as the instance’s __dict__ when pickling.

Return type:

Dict[str, Any]

__copy__()[source]

Return a semantically-shallow copy of the object, for copy.copy().

Return type:

Requirer

__deepcopy__(memo)[source]

Return a semantically-deep copy of the object, for copy.deepcopy().

Parameters:

memo (Any)

Return type:

Requirer

property requirements: RequirementsDict

Get dict containing all non-None, non-defaulted requirements.

Return type:

RequirementsDict

property disk: int

Get the maximum number of bytes of disk required.

Return type:

int

property memory: int

Get the maximum number of bytes of memory required.

Return type:

int

property cores: int | float

Get the number of CPU cores required.

Return type:

Union[int, float]

property preemptible: bool

Whether a preemptible node is permitted, or a nonpreemptible one is required.

Return type:

bool

preemptable(val)[source]
Parameters:

val (ParseableFlag)

Return type:

None

property accelerators: List[AcceleratorRequirement]

Any accelerators, such as GPUs, that are needed.

Return type:

List[AcceleratorRequirement]

scale(requirement, factor)[source]

Return a copy of this object with the given requirement scaled up or down.

Only works on requirements where that makes sense.

Parameters:
Return type:

Requirer

requirements_string()[source]

Get a nice human-readable string of our requirements.

Return type:

str

toil.test.batchSystems.batchSystemTest.retry_flaky_test
toil.test.batchSystems.batchSystemTest.cpu_count()[source]

Get the rounded-up integer number of whole CPUs available.

Counts hyperthreads as CPUs.

Uses the system’s actual CPU count, or the current v1 cgroup’s quota per period, if the quota is set.

Ignores the cgroup’s cpu shares value, because it’s extremely difficult to interpret. See https://github.com/kubernetes/kubernetes/issues/81021.

Caches result for efficiency.

Returns:

Integer count of available CPUs, minimum 1.

Return type:

int

class toil.test.batchSystems.batchSystemTest.ToilTest(methodName='runTest')[source]

Bases: unittest.TestCase

A common base class for Toil tests.

Please have every test case directly or indirectly inherit this one.

When running tests you may optionally set the TOIL_TEST_TEMP environment variable to the path of a directory where you want temporary test files be placed. The directory will be created if it doesn’t exist. The path may be relative in which case it will be assumed to be relative to the project root. If TOIL_TEST_TEMP is not defined, temporary files and directories will be created in the system’s default location for such files and any temporary files or directories left over from tests will be removed automatically removed during tear down. Otherwise, left-over files will not be removed.

setup_method(method)[source]
Parameters:

method (Any)

Return type:

None

classmethod setUpClass()[source]

Hook method for setting up class fixture before running tests in the class.

Return type:

None

classmethod tearDownClass()[source]

Hook method for deconstructing the class fixture after running all tests in the class.

Return type:

None

setUp()[source]

Hook method for setting up the test fixture before exercising it.

Return type:

None

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

Return type:

None

classmethod awsRegion()[source]

Pick an appropriate AWS region.

Use us-west-2 unless running on EC2, in which case use the region in which the instance is located

Return type:

str

toil.test.batchSystems.batchSystemTest.needs_aws_batch(test_item)[source]

Use as a decorator before test classes or methods to run only if AWS Batch is usable.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_aws_s3(test_item)[source]

Use as a decorator before test classes or methods to run only if AWS S3 is usable.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_fetchable_appliance(test_item)[source]

Use as a decorator before test classes or methods to only run them if the Toil appliance Docker image is able to be downloaded from the Internet.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_gridengine(test_item)[source]

Use as a decorator before test classes or methods to run only if GridEngine is installed.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_htcondor(test_item)[source]

Use a decorator before test classes or methods to run only if the HTCondor is installed.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_kubernetes(test_item)[source]

Use as a decorator before test classes or methods to run only if Kubernetes is installed and configured.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_kubernetes_installed(test_item)[source]

Use as a decorator before test classes or methods to run only if Kubernetes is installed.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_lsf(test_item)[source]

Use as a decorator before test classes or methods to only run them if LSF is installed.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_mesos(test_item)[source]

Use as a decorator before test classes or methods to run only if Mesos is installed.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_slurm(test_item)[source]

Use as a decorator before test classes or methods to run only if Slurm is installed.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.needs_torque(test_item)[source]

Use as a decorator before test classes or methods to run only if PBS/Torque is installed.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.slow(test_item)[source]

Use this decorator to identify tests that are slow and not critical. Skip if TOIL_TEST_QUICK is true.

Parameters:

test_item (MT)

Return type:

MT

toil.test.batchSystems.batchSystemTest.logger
toil.test.batchSystems.batchSystemTest.numCores = 2
toil.test.batchSystems.batchSystemTest.preemptible = False
toil.test.batchSystems.batchSystemTest.defaultRequirements
class toil.test.batchSystems.batchSystemTest.BatchSystemPluginTest(methodName='runTest')[source]

Bases: toil.test.ToilTest

Class for testing batch system plugin functionality.

setUp()[source]

Hook method for setting up the test fixture before exercising it.

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

test_add_batch_system_factory()[source]
class toil.test.batchSystems.batchSystemTest.hidden[source]

Hide abstract base class from unittest’s test case loader

http://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class#answer-25695512

class AbstractBatchSystemTest(methodName='runTest')[source]

Bases: toil.test.ToilTest

A base test case with generic tests that every batch system should pass.

Cannot assume that the batch system actually executes commands on the local machine/filesystem.

abstract createBatchSystem()[source]
Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

supportsWallTime()[source]
classmethod createConfig()[source]

Returns a dummy config for the batch system tests. We need a workflowID to be set up since we are running tests without setting up a jobstore. This is the class version to be used when an instance is not available.

Return type:

toil.common.Config

classmethod setUpClass()[source]

Hook method for setting up class fixture before running tests in the class.

setUp()[source]

Hook method for setting up the test fixture before exercising it.

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

get_max_startup_seconds()[source]

Get the number of seconds this test ought to wait for the first job to run. Some batch systems may need time to scale up.

Return type:

int

test_available_cores()[source]
test_run_jobs()[source]
test_set_env()[source]
test_set_job_env()[source]

Test the mechanism for setting per-job environment variables to batch system jobs.

testCheckResourceRequest()[source]
testScalableBatchSystem()[source]
class AbstractBatchSystemJobTest(methodName='runTest')[source]

Bases: toil.test.ToilTest

An abstract base class for batch system tests that use a full Toil workflow rather than using the batch system directly.

cpuCount
allocatedCores
sleepTime = 5
abstract getBatchSystemName()[source]
Return type:

(str, AbstractBatchSystem)

getOptions(tempDir)[source]

Configures options for Toil workflow and makes job store. :param str tempDir: path to test directory :return: Toil options object

setUp()[source]

Hook method for setting up the test fixture before exercising it.

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

testJobConcurrency()[source]

Tests that the batch system is allocating core resources properly for concurrent tasks.

test_omp_threads()[source]

Test if the OMP_NUM_THREADS env var is set correctly based on jobs.cores.

class AbstractGridEngineBatchSystemTest(methodName='runTest')[source]

Bases: AbstractBatchSystemTest

An abstract class to reduce redundancy between Grid Engine, Slurm, and other similar batch systems

class toil.test.batchSystems.batchSystemTest.KubernetesBatchSystemTest(methodName='runTest')[source]

Bases: hidden

Tests against the Kubernetes batch system

supportsWallTime()[source]
createBatchSystem()[source]
class toil.test.batchSystems.batchSystemTest.KubernetesBatchSystemBenchTest(methodName='runTest')[source]

Bases: toil.test.ToilTest

Kubernetes batch system unit tests that don’t need to actually talk to a cluster.

test_preemptability_constraints()[source]

Make sure we generate the right preemptability constraints.

test_label_constraints()[source]

Make sure we generate the right preemptability constraints.

class toil.test.batchSystems.batchSystemTest.AWSBatchBatchSystemTest(methodName='runTest')[source]

Bases: hidden

Tests against the AWS Batch batch system

supportsWallTime()[source]
createBatchSystem()[source]
get_max_startup_seconds()[source]

Get the number of seconds this test ought to wait for the first job to run. Some batch systems may need time to scale up.

Return type:

int

class toil.test.batchSystems.batchSystemTest.MesosBatchSystemTest(methodName='runTest')[source]

Bases: hidden, toil.batchSystems.mesos.test.MesosTestSupport

Tests against the Mesos batch system

classmethod createConfig()[source]

needs to set mesos_endpoint to localhost for testing since the default is now the private IP address

supportsWallTime()[source]
createBatchSystem()[source]
tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

testIgnoreNode()[source]
toil.test.batchSystems.batchSystemTest.write_temp_file(s, temp_dir)[source]

Dump a string into a temp file and return its path.

Parameters:
Return type:

str

class toil.test.batchSystems.batchSystemTest.SingleMachineBatchSystemTest(methodName='runTest')[source]

Bases: hidden

Tests against the single-machine batch system

supportsWallTime()[source]
Return type:

bool

createBatchSystem()[source]
Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

testProcessEscape(hide=False)[source]

Test to make sure that child processes and their descendants go away when the Toil workflow stops.

If hide is true, will try and hide the child processes to make them hard to stop.

Parameters:

hide (bool)

Return type:

None

testHidingProcessEscape()[source]

Test to make sure that child processes and their descendants go away when the Toil workflow stops, even if the job process stops and leaves children.

class toil.test.batchSystems.batchSystemTest.MaxCoresSingleMachineBatchSystemTest(methodName='runTest')[source]

Bases: toil.test.ToilTest

This test ensures that single machine batch system doesn’t exceed the configured number cores

classmethod setUpClass()[source]

Hook method for setting up class fixture before running tests in the class.

Return type:

None

setUp()[source]

Hook method for setting up the test fixture before exercising it.

Return type:

None

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

Return type:

None

scriptCommand()[source]
Return type:

str

test()[source]
testServices()[source]
toil.test.batchSystems.batchSystemTest.parentJob(job, cmd)[source]
toil.test.batchSystems.batchSystemTest.childJob(job, cmd)[source]
toil.test.batchSystems.batchSystemTest.grandChildJob(job, cmd)[source]
toil.test.batchSystems.batchSystemTest.greatGrandChild(cmd)[source]
class toil.test.batchSystems.batchSystemTest.Service(cmd)[source]

Bases: toil.job.Job.Service

Abstract class used to define the interface to a service.

Should be subclassed by the user to define services.

Is not executed as a job; runs within a ServiceHostJob.

start(fileStore)[source]

Start the service.

Parameters:

job – The underlying host job that the service is being run in. Can be used to register deferred functions, or to access the fileStore for creating temporary files.

Returns:

An object describing how to access the service. The object must be pickleable and will be used by jobs to access the service (see toil.job.Job.addService()).

check()[source]

Checks the service is still running.

Raises:

exceptions.RuntimeError – If the service failed, this will cause the service job to be labeled failed.

Returns:

True if the service is still running, else False. If False then the service job will be terminated, and considered a success. Important point: if the service job exits due to a failure, it should raise a RuntimeError, not return False!

stop(fileStore)[source]

Stops the service. Function can block until complete.

Parameters:

job – The underlying host job that the service is being run in. Can be used to register deferred functions, or to access the fileStore for creating temporary files.

class toil.test.batchSystems.batchSystemTest.GridEngineBatchSystemTest(methodName='runTest')[source]

Bases: hidden

Tests against the GridEngine batch system

createBatchSystem()[source]
Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

class toil.test.batchSystems.batchSystemTest.SlurmBatchSystemTest(methodName='runTest')[source]

Bases: hidden

Tests against the Slurm batch system

createBatchSystem()[source]
Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

class toil.test.batchSystems.batchSystemTest.LSFBatchSystemTest(methodName='runTest')[source]

Bases: hidden

Tests against the LSF batch system

createBatchSystem()[source]
Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

class toil.test.batchSystems.batchSystemTest.TorqueBatchSystemTest(methodName='runTest')[source]

Bases: hidden

Tests against the Torque batch system

createBatchSystem()[source]
Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

class toil.test.batchSystems.batchSystemTest.HTCondorBatchSystemTest(methodName='runTest')[source]

Bases: hidden

Tests against the HTCondor batch system

createBatchSystem()[source]
Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

class toil.test.batchSystems.batchSystemTest.SingleMachineBatchSystemJobTest(methodName='runTest')[source]

Bases: hidden

Tests Toil workflow against the SingleMachine batch system

getBatchSystemName()[source]
Return type:

(str, AbstractBatchSystem)

testConcurrencyWithDisk()[source]

Tests that the batch system is allocating disk resources properly

testNestedResourcesDoNotBlock()[source]

Resources are requested in the order Memory > Cpu > Disk. Test that unavailability of cpus for one job that is scheduled does not block another job that can run.

class toil.test.batchSystems.batchSystemTest.MesosBatchSystemJobTest(methodName='runTest')[source]

Bases: hidden, toil.batchSystems.mesos.test.MesosTestSupport

Tests Toil workflow against the Mesos batch system

getOptions(tempDir)[source]

Configures options for Toil workflow and makes job store. :param str tempDir: path to test directory :return: Toil options object

getBatchSystemName()[source]
Return type:

(str, AbstractBatchSystem)

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

toil.test.batchSystems.batchSystemTest.measureConcurrency(filepath, sleep_time=10)[source]

Run in parallel to determine the number of concurrent tasks. This code was copied from toil.batchSystemTestMaxCoresSingleMachineBatchSystemTest :param str filepath: path to counter file :param int sleep_time: number of seconds to sleep before counting down :return int max concurrency value:

toil.test.batchSystems.batchSystemTest.count(delta, file_path)[source]

Increments counter file and returns the max number of times the file has been modified. Counter data must be in the form: concurrent tasks, max concurrent tasks (counter should be initialized to 0,0)

Parameters:
  • delta (int) – increment value

  • file_path (str) – path to shared counter file

Return int max concurrent tasks:

toil.test.batchSystems.batchSystemTest.getCounters(path)[source]
toil.test.batchSystems.batchSystemTest.resetCounters(path)[source]
toil.test.batchSystems.batchSystemTest.get_omp_threads()[source]
Return type:

str