toil.test.batchSystems.batchSystemTest¶
Attributes¶
Exceptions¶
Common base class for all non-exit exceptions. |
Classes¶
An abstract base class to represent the interface the batch system must provide to Toil. |
|
Partial implementation of AbstractBatchSystem, support methods. |
|
Mixin for test cases that need a running Mesos master and agent on the local host. |
|
The interface for running jobs on a single machine, runs all the jobs you |
|
Class to represent configuration operations for a toil workflow run. |
|
A context manager that represents a Toil workflow. |
|
Class represents a unit of work in toil. |
|
Stores all the information that the Toil Leader ever needs to know about a Job. |
|
Base class implementing the storage and presentation of requirements. |
|
A common base class for Toil tests. |
|
Class for testing batch system plugin functionality. |
|
Hide abstract base class from unittest's test case loader |
|
Tests against the Kubernetes batch system |
|
Kubernetes batch system unit tests that don't need to actually talk to a cluster. |
|
Tests against the AWS Batch batch system |
|
Tests against the Mesos batch system |
|
Tests against the single-machine batch system |
|
This test ensures that single machine batch system doesn't exceed the configured number |
|
Abstract class used to define the interface to a service. |
|
Tests against the GridEngine batch system |
|
Tests against the Slurm batch system |
|
Tests against the LSF batch system |
|
Tests against the Torque batch system |
|
Tests against the HTCondor batch system |
|
Tests Toil workflow against the SingleMachine batch system |
|
Tests Toil workflow against the Mesos batch system |
Functions¶
|
Adds a batch system to the registry for workflow or plugin-supplied batch systems. |
|
Get a batch system class by name. |
Get the names of all the availsble batch systems. |
|
|
Restore the batch system registry state to a snapshot from |
Return a snapshot of the plugin registry that can be restored to remove |
|
Get the rounded-up integer number of whole CPUs available. |
|
|
Use as a decorator before test classes or methods to run only if AWS Batch |
|
Use as a decorator before test classes or methods to run only if AWS S3 is usable. |
|
Use as a decorator before test classes or methods to only run them if |
|
Use as a decorator before test classes or methods to run only if GridEngine is installed. |
|
Use a decorator before test classes or methods to run only if the HTCondor is installed. |
|
Use as a decorator before test classes or methods to run only if Kubernetes is installed and configured. |
|
Use as a decorator before test classes or methods to run only if Kubernetes is installed. |
|
Use as a decorator before test classes or methods to only run them if LSF is installed. |
|
Use as a decorator before test classes or methods to run only if Mesos is installed. |
|
Use as a decorator before test classes or methods to run only if Slurm is installed. |
|
Use as a decorator before test classes or methods to run only if PBS/Torque is installed. |
|
Use this decorator to identify tests that are slow and not critical. |
|
Dump a string into a temp file and return its path. |
|
|
|
|
|
|
|
|
|
Run in parallel to determine the number of concurrent tasks. |
|
Increments counter file and returns the max number of times the file |
|
|
|
|
Module Contents¶
- class toil.test.batchSystems.batchSystemTest.AbstractBatchSystem[source]¶
Bases:
abc.ABCAn abstract base class to represent the interface the batch system must provide to Toil.
- classmethod supportsAutoDeployment()[source]¶
- Abstractmethod:
- Return type:
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:
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:
- 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.
- 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.
- 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:
AbstractBatchSystemPartial implementation of AbstractBatchSystem, support methods.
- Parameters:
config (toil.common.Config)
maxCores (float)
maxMemory (int)
maxDisk (int)
- 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:
- 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:
- 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:
- 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.
- 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:
ExceptionCommon 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])
- class toil.test.batchSystems.batchSystemTest.MesosTestSupport[source]¶
Mixin for test cases that need a running Mesos master and agent on the local host.
- class MesosThread(numCores)[source]¶
Bases:
toil.lib.threading.ExceptionalThreadA 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¶
- class MesosMasterThread(numCores)[source]¶
Bases:
MesosThreadA 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
- class MesosAgentThread(numCores)[source]¶
Bases:
MesosThreadA 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
- 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:
class_factory (Callable[[], Type[toil.batchSystems.abstractBatchSystem.AbstractBatchSystem]]) – A function that returns a batch system class (NOT an instance), which implements
toil.batchSystems.abstractBatchSystem.AbstractBatchSystem.key (str)
- 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.BatchSystemSupportThe 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:
config (toil.common.Config)
maxCores (float)
maxMemory (int)
maxDisk (int)
max_jobs (Optional[int])
- 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:
command (str)
job_desc (toil.job.JobDescription)
- Return type:
- 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.
- 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.
- 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.
- 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.
- defaultAccelerators: List[toil.job.AcceleratorRequirement]¶
- 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
- 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)
- __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:
- __exit__(exc_type, exc_val, exc_tb)[source]¶
Clean up after a workflow invocation.
Depending on the configuration, delete the job store.
- Parameters:
exc_type (Optional[Type[BaseException]])
exc_val (Optional[BaseException])
exc_tb (Optional[types.TracebackType])
- 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:
- 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:
- 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:
jobStoreFileID (toil.fileStores.FileID)
dstUrl (str)
- 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:
file_id (toil.fileStores.FileID)
dst_uri (str)
- Return type:
None
- static normalize_uri(uri, check_existence=False)[source]¶
Given a URI, if it has no scheme, prepend “file:”.
- 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.
- 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:
- 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:
- 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.
- classmethod getLocalWorkflowDir(workflowID, configWorkDir=None)[source]¶
Return the directory where worker directories and the cache will be located for this workflow on this machine.
- 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:
- Returns:
Path to the local workflow coordination directory on this machine.
- Return type:
- 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:
- property memory¶
- The maximum number of bytes of memory the job will require to run.
- property accelerators: List[AcceleratorRequirement]¶
Any accelerators, such as GPUs, that are needed.
- Return type:
List[AcceleratorRequirement]
- 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.
- addFollowOn(followOnJob)[source]¶
Add a follow-on job.
Follow-on jobs will be run after the child jobs and their successors have been run.
- 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’stoil.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:
- 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:
- hasService(service)[source]¶
Return True if the given Service is a service of this job, and False otherwise.
- addChildFn(fn, *args, **kwargs)[source]¶
Add a function as a child job.
- Parameters:
fn (Callable) – Function to be run as a child job with
*argsand**kwargsas 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:
- 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
*argsand**kwargsas 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:
- addChildJobFn(fn, *args, **kwargs)[source]¶
Add a job function as a child job.
See
toil.job.JobFunctionWrappingJobfor a definition of a job function.- Parameters:
fn (Callable) – Job function to be run as a child job with
*argsand**kwargsas 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:
- addFollowOnJobFn(fn, *args, **kwargs)[source]¶
Add a follow-on job function.
See
toil.job.JobFunctionWrappingJobfor a definition of a job function.- Parameters:
fn (Callable) – Job function to be run as a follow-on job with
*argsand**kwargsas 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:
- 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:
- 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
*argsand**kwargsas arguments. See toil.job.JobFunctionWrappingJob for reserved keyword arguments used to specify resource requirements.- Returns:
The new function that wraps fn.
- Return type:
- 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
*argsand**kwargsas arguments. See toil.job.JobFunctionWrappingJob for reserved keyword arguments used to specify resource requirements.- Returns:
The new job function that wraps fn.
- Return type:
- encapsulate(name=None)[source]¶
Encapsulates the job, see
toil.job.EncapsulatedJob. Convenience function for constructor oftoil.job.EncapsulatedJob.- Parameters:
name (Optional[str]) – Human-readable name for the encapsulated job.
- Returns:
an encapsulated version of this job.
- Return type:
- 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:
- 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:
- 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()andtoil.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 isO(|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.
- 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:
- static getDefaultOptions(jobStore=None, jobstore_as_flag=False)[source]¶
Get default options for a toil workflow.
- Parameters:
- Returns:
The options used by a toil workflow.
- Return type:
- static addToilOptions(parser, jobstore_as_flag=False)[source]¶
Adds the default toil options to an
optparseorargparseparser object.- Parameters:
parser (Union[optparse.OptionParser, argparse.ArgumentParser]) – Options object to add toil options to.
jobstore_as_flag (bool) – make the job store option a –jobStore flag instead of a required jobStore positional argument.
- 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:
RequirerAbstract 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:
- 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:
- Return type:
- classmethod loadJob(job_store, job_description)[source]¶
Retrieves a
toil.job.Jobinstance from a JobStore- Parameters:
job_store (toil.jobStores.abstractJobStore.AbstractJobStore) – The job store.
job_description (JobDescription) – the JobDescription of the job to retrieve.
- Returns:
The job referenced by the JobDescription.
- Return type:
- set_debug_flag(flag)[source]¶
Enable the given debug option on the job.
- Parameters:
flag (str)
- Return type:
None
- 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.
- class toil.test.batchSystems.batchSystemTest.JobDescription(requirements, jobName, unitName='', displayName='', local=None)[source]¶
Bases:
RequirerStores 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:
- 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.
- 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:
- 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:
file_store_id (str)
user_script (toil.resource.ModuleDescriptor)
- 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.
- 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.
- 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
- 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:
- 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:
- 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.
- hasFollowOn(followOnID)[source]¶
Test if the job with the given ID is a follow-on of the described job.
- hasServiceHostJob(serviceID)[source]¶
Test if the ServiceHostJob is a service of the described job.
- Return type:
- 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:
exit_status (Optional[int]) – The exit code from the job.
exit_reason (Optional[toil.batchSystems.abstractBatchSystem.BatchJobExitReason]) – The reason the job stopped, if available from the batch system.
- 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:
- 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]
- __deepcopy__(memo)[source]¶
Return a semantically-deep copy of the object, for
copy.deepcopy().- Parameters:
memo (Any)
- Return type:
- property requirements: RequirementsDict¶
Get dict containing all non-None, non-defaulted requirements.
- Return type:
- property preemptible: bool¶
Whether a preemptible node is permitted, or a nonpreemptible one is required.
- Return type:
- property accelerators: List[AcceleratorRequirement]¶
Any accelerators, such as GPUs, that are needed.
- Return type:
List[AcceleratorRequirement]
- 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:
- class toil.test.batchSystems.batchSystemTest.ToilTest(methodName='runTest')[source]¶
Bases:
unittest.TestCaseA 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.
- 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
- 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.ToilTestClass for testing batch system plugin functionality.
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
Bases:
toil.test.ToilTestA 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.
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:
Hook method for setting up class fixture before running tests in the class.
Hook method for setting up the test fixture before exercising it.
Hook method for deconstructing the test fixture after testing it.
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:
Test the mechanism for setting per-job environment variables to batch system jobs.
Bases:
toil.test.ToilTestAn abstract base class for batch system tests that use a full Toil workflow rather than using the batch system directly.
- Return type:
Configures options for Toil workflow and makes job store. :param str tempDir: path to test directory :return: Toil options object
Hook method for setting up the test fixture before exercising it.
Hook method for deconstructing the test fixture after testing it.
Tests that the batch system is allocating core resources properly for concurrent tasks.
Test if the OMP_NUM_THREADS env var is set correctly based on jobs.cores.
Bases:
AbstractBatchSystemTestAn abstract class to reduce redundancy between Grid Engine, Slurm, and other similar batch systems
- class toil.test.batchSystems.batchSystemTest.KubernetesBatchSystemTest(methodName='runTest')[source]¶
Bases:
hiddenTests against the Kubernetes batch system
- class toil.test.batchSystems.batchSystemTest.KubernetesBatchSystemBenchTest(methodName='runTest')[source]¶
Bases:
toil.test.ToilTestKubernetes batch system unit tests that don’t need to actually talk to a cluster.
- class toil.test.batchSystems.batchSystemTest.AWSBatchBatchSystemTest(methodName='runTest')[source]¶
Bases:
hiddenTests against the AWS Batch batch system
- class toil.test.batchSystems.batchSystemTest.MesosBatchSystemTest(methodName='runTest')[source]¶
Bases:
hidden,toil.batchSystems.mesos.test.MesosTestSupportTests against the Mesos batch system
- toil.test.batchSystems.batchSystemTest.write_temp_file(s, temp_dir)[source]¶
Dump a string into a temp file and return its path.
- class toil.test.batchSystems.batchSystemTest.SingleMachineBatchSystemTest(methodName='runTest')[source]¶
Bases:
hiddenTests against the single-machine batch system
- class toil.test.batchSystems.batchSystemTest.MaxCoresSingleMachineBatchSystemTest(methodName='runTest')[source]¶
Bases:
toil.test.ToilTestThis 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
- class toil.test.batchSystems.batchSystemTest.Service(cmd)[source]¶
Bases:
toil.job.Job.ServiceAbstract 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!
- class toil.test.batchSystems.batchSystemTest.GridEngineBatchSystemTest(methodName='runTest')[source]¶
Bases:
hiddenTests against the GridEngine batch system
- class toil.test.batchSystems.batchSystemTest.SlurmBatchSystemTest(methodName='runTest')[source]¶
Bases:
hiddenTests against the Slurm batch system
- class toil.test.batchSystems.batchSystemTest.LSFBatchSystemTest(methodName='runTest')[source]¶
Bases:
hiddenTests against the LSF batch system
- class toil.test.batchSystems.batchSystemTest.TorqueBatchSystemTest(methodName='runTest')[source]¶
Bases:
hiddenTests against the Torque batch system
- class toil.test.batchSystems.batchSystemTest.HTCondorBatchSystemTest(methodName='runTest')[source]¶
Bases:
hiddenTests against the HTCondor batch system
- class toil.test.batchSystems.batchSystemTest.SingleMachineBatchSystemJobTest(methodName='runTest')[source]¶
Bases:
hiddenTests Toil workflow against the SingleMachine batch system
- class toil.test.batchSystems.batchSystemTest.MesosBatchSystemJobTest(methodName='runTest')[source]¶
Bases:
hidden,toil.batchSystems.mesos.test.MesosTestSupportTests 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
- 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: