toil.batchSystems.abstractBatchSystem¶
Attributes¶
Memoize a function result based on its parameters using this decorator. |
|
Exceptions¶
Common base class for all non-exit exceptions. |
|
To be raised when a resource request times out. |
Classes¶
Protocol for the setOption function we get to let us set up CLI options for |
|
Holds messages that should cause jobs to change their scheduling states. |
|
A connection to a message bus that lets us publish messages. |
|
Class to represent configuration operations for a toil workflow run. |
|
A context manager that represents a Toil workflow. |
|
Implements a deferred function system. Each Toil worker will have an |
|
Interface used to allow user code run by Toil to read and write files. |
|
Stores all the information that the Toil Leader ever needs to know about a Job. |
|
Base class implementing the storage and presentation of requirements. |
|
Represents a file or directory that will be deployed to each node before any jobs in the user script are invoked. |
|
Enum where members are also (and must be) ints |
|
An abstract base class to represent the interface the batch system must provide to Toil. |
|
Partial implementation of AbstractBatchSystem, support methods. |
|
The coresUsed attribute is a floating point value between 0 (all cores idle) and 1 (all cores |
|
A batch system that supports a variable number of worker nodes. |
|
Represents an integral amount of a resource (such as memory bytes). |
|
Represents a collection of distinct resources (such as accelerators). |
Functions¶
|
|
Module Contents¶
- class toil.batchSystems.abstractBatchSystem.OptionSetter[source]¶
Bases:
ProtocolProtocol for the setOption function we get to let us set up CLI options for each batch system.
Actual functionality is defined in the Config class.
- OptionType¶
- class toil.batchSystems.abstractBatchSystem.MessageBus[source]¶
Holds messages that should cause jobs to change their scheduling states. Messages are put in and buffered, and can be taken out and handled as batches when convenient.
All messages are NamedTuple objects of various subtypes.
Message order is guaranteed to be preserved within a type.
- publish(message)[source]¶
Put a message onto the bus. Can be called from any thread.
- Parameters:
message (Any)
- Return type:
None
- check()[source]¶
If we are in the owning thread, deliver any messages that are in the queue for us. Must be called every once in a while in the main thread, possibly through inbox objects.
- Return type:
None
- MessageType¶
- subscribe(message_type, handler)[source]¶
Register the given callable to be called when messages of the given type are sent. It will be called with messages sent after the subscription is created. Returns a subscription object; when the subscription object is GC’d the subscription will end.
- Parameters:
message_type (Type[MessageType])
handler (Callable[[MessageType], Any])
- Return type:
pubsub.core.listener.Listener
- connect(wanted_types)[source]¶
Get a connection object that serves as an inbox for messages of the given types. Messages of those types will accumulate in the inbox until it is destroyed. You can check for them at any time.
- Parameters:
wanted_types (List[type])
- Return type:
- connect_output_file(file_path)[source]¶
Send copies of all messages to the given output file.
Returns connection data which must be kept alive for the connection to persist. That data is opaque: the user is not supposed to look at it or touch it or do anything with it other than store it somewhere or delete it.
- Parameters:
file_path (str)
- Return type:
Any
- class toil.batchSystems.abstractBatchSystem.MessageOutbox[source]¶
Bases:
MessageBusClientA connection to a message bus that lets us publish messages.
- class toil.batchSystems.abstractBatchSystem.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.batchSystems.abstractBatchSystem.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.batchSystems.abstractBatchSystem.DeferredFunctionManager(stateDirBase)[source]¶
Implements a deferred function system. Each Toil worker will have an instance of this class. When a job is executed, it will happen inside a context manager from this class. If the job registers any “deferred” functions, they will be executed when the context manager is exited.
If the Python process terminates before properly exiting the context manager and running the deferred functions, and some other worker process enters or exits the per-job context manager of this class at a later time, or when the DeferredFunctionManager is shut down on the worker, the earlier job’s deferred functions will be picked up and run.
Note that deferred function cleanup is on a best-effort basis, and deferred functions may end up getting executed multiple times.
Internally, deferred functions are serialized into files in the given directory, which are locked by the owning process.
If that process dies, other processes can detect that the files are able to be locked, and will take them over.
- Parameters:
stateDirBase (str)
- STATE_DIR_STEM = 'deferred'¶
- PREFIX = 'func'¶
- WIP_SUFFIX = '.tmp'¶
- __del__()[source]¶
Clean up our state on disk. We assume that the deferred functions we manage have all been executed, and none are currently recorded.
- class toil.batchSystems.abstractBatchSystem.AbstractFileStore(jobStore, jobDesc, file_store_dir, waitForPreviousCommit)[source]¶
Bases:
abc.ABCInterface used to allow user code run by Toil to read and write files.
Also provides the interface to other Toil facilities used by user code, including:
normal (non-real-time) logging
finding the correct temporary directory for scratch work
importing and exporting files into and out of the workflow
Stores user files in the jobStore, but keeps them separate from actual jobs.
May implement caching.
Passed as argument to the
toil.job.Job.run()method.Access to files is only permitted inside the context manager provided by
toil.fileStores.abstractFileStore.AbstractFileStore.open().Also responsible for committing completed jobs back to the job store with an update operation, and allowing that commit operation to be waited for.
- Parameters:
jobDesc (toil.job.JobDescription)
file_store_dir (str)
waitForPreviousCommit (Callable[[], Any])
- static createFileStore(jobStore, jobDesc, file_store_dir, waitForPreviousCommit, caching)[source]¶
Create a concreate FileStore.
- Parameters:
jobDesc (toil.job.JobDescription)
file_store_dir (str)
waitForPreviousCommit (Callable[[], Any])
caching (Optional[bool])
- Return type:
Union[toil.fileStores.nonCachingFileStore.NonCachingFileStore, toil.fileStores.cachingFileStore.CachingFileStore]
- static shutdownFileStore(workflowID, config_work_dir, config_coordination_dir)[source]¶
Carry out any necessary filestore-specific cleanup.
This is a destructive operation and it is important to ensure that there are no other running processes on the system that are modifying or using the file store for this workflow.
This is the intended to be the last call to the file store in a Toil run, called by the batch system cleanup function upon batch system shutdown.
- open(job)[source]¶
Create the context manager around tasks prior and after a job has been run.
File operations are only permitted inside the context manager.
Implementations must only yield from within with super().open(job):.
- Parameters:
job (toil.job.Job) – The job instance of the toil job to run.
- Return type:
Generator[None, None, None]
- get_disk_usage()[source]¶
Get the number of bytes of disk used by the last job run under open().
Disk usage is measured at the end of the job. TODO: Sample periodically and record peak usage.
- Return type:
Optional[int]
- getLocalTempDir()[source]¶
Get a new local temporary directory in which to write files.
The directory will only persist for the duration of the job.
- Returns:
The absolute path to a new local temporary directory. This directory will exist for the duration of the job only, and is guaranteed to be deleted once the job terminates, removing all files it contains recursively.
- Return type:
- getLocalTempFile(suffix=None, prefix=None)[source]¶
Get a new local temporary file that will persist for the duration of the job.
- Parameters:
- Returns:
The absolute path to a local temporary file. This file will exist for the duration of the job only, and is guaranteed to be deleted once the job terminates.
- Return type:
- getLocalTempFileName(suffix=None, prefix=None)[source]¶
Get a valid name for a new local file. Don’t actually create a file at the path.
- Parameters:
- Returns:
Path to valid file
- Return type:
- abstract writeGlobalFile(localFileName, cleanup=False)[source]¶
Upload a file (as a path) to the job store.
If the file is in a FileStore-managed temporary directory (i.e. from
toil.fileStores.abstractFileStore.AbstractFileStore.getLocalTempDir()), it will become a local copy of the file, eligible for deletion bytoil.fileStores.abstractFileStore.AbstractFileStore.deleteLocalFile().If an executable file on the local filesystem is uploaded, its executability will be preserved when it is downloaded again.
- Parameters:
localFileName (str) – The path to the local file to upload. The last path component (basename of the file) will remain associated with the file in the file store, if supported by the backing JobStore, so that the file can be searched for by name or name glob.
cleanup (bool) – if True then the copy of the global file will be deleted once the job and all its successors have completed running. If not the global file must be deleted manually.
- Returns:
an ID that can be used to retrieve the file.
- Return type:
- writeGlobalFileStream(cleanup=False, basename=None, encoding=None, errors=None)[source]¶
Similar to writeGlobalFile, but allows the writing of a stream to the job store. The yielded file handle does not need to and should not be closed explicitly.
- Parameters:
encoding (Optional[str]) – The name of the encoding used to decode the file. Encodings are the same as for decode(). Defaults to None which represents binary mode.
errors (Optional[str]) – Specifies how encoding errors are to be handled. Errors are the same as for open(). Defaults to ‘strict’ when an encoding is specified.
cleanup (bool) – is as in
toil.fileStores.abstractFileStore.AbstractFileStore.writeGlobalFile().basename (Optional[str]) – If supported by the backing JobStore, use the given file basename so that when searching the job store with a query matching that basename, the file will be detected.
- Returns:
A context manager yielding a tuple of 1) a file handle which can be written to and 2) the toil.fileStores.FileID of the resulting file in the job store.
- Return type:
Iterator[Tuple[toil.lib.io.WriteWatchingStream, toil.fileStores.FileID]]
- logAccess(fileStoreID, destination=None)[source]¶
Record that the given file was read by the job.
(to be announced if the job fails)
If destination is not None, it gives the path that the file was downloaded to. Otherwise, assumes that the file was streamed.
Must be called by
readGlobalFile()andreadGlobalFileStream()implementations.- Parameters:
fileStoreID (Union[toil.fileStores.FileID, str])
destination (Union[str, None])
- Return type:
None
- abstract readGlobalFile(fileStoreID, userPath=None, cache=True, mutable=False, symlink=False)[source]¶
Make the file associated with fileStoreID available locally.
If mutable is True, then a copy of the file will be created locally so that the original is not modified and does not change the file for other jobs. If mutable is False, then a link can be created to the file, saving disk resources. The file that is downloaded will be executable if and only if it was originally uploaded from an executable file on the local filesystem.
If a user path is specified, it is used as the destination. If a user path isn’t specified, the file is stored in the local temp directory with an encoded name.
The destination file must not be deleted by the user; it can only be deleted through deleteLocalFile.
Implementations must call
logAccess()to report the download.- Parameters:
fileStoreID (str) – job store id for the file
userPath (Optional[str]) – a path to the name of file to which the global file will be copied or hard-linked (see below).
cache (bool) – Described in
toil.fileStores.CachingFileStore.readGlobalFile()mutable (bool) – Described in
toil.fileStores.CachingFileStore.readGlobalFile()symlink (bool) – True if caller can accept symlink, False if caller can only accept a normal file or hardlink
- Returns:
An absolute path to a local, temporary copy of the file keyed by fileStoreID.
- Return type:
- readGlobalFileStream(fileStoreID: str, encoding: Literal[None] = None, errors: str | None = None) ContextManager[IO[bytes]][source]¶
- readGlobalFileStream(fileStoreID: str, encoding: str, errors: str | None = None) ContextManager[IO[str]]
Read a stream from the job store; similar to readGlobalFile.
The yielded file handle does not need to and should not be closed explicitly.
- Parameters:
encoding – the name of the encoding used to decode the file. Encodings are the same as for decode(). Defaults to None which represents binary mode.
errors – an optional string that specifies how encoding errors are to be handled. Errors are the same as for open(). Defaults to ‘strict’ when an encoding is specified.
Implementations must call
logAccess()to report the download.- Returns:
a context manager yielding a file handle which can be read from.
- getGlobalFileSize(fileStoreID)[source]¶
Get the size of the file pointed to by the given ID, in bytes.
If a FileID or something else with a non-None ‘size’ field, gets that.
Otherwise, asks the job store to poll the file’s size.
Note that the job store may overestimate the file’s size, for example if it is encrypted and had to be augmented with an IV or other encryption framing.
- Parameters:
fileStoreID (Union[toil.fileStores.FileID, str]) – File ID for the file
- Returns:
File’s size in bytes, as stored in the job store
- Return type:
- abstract deleteLocalFile(fileStoreID)[source]¶
Delete local copies of files associated with the provided job store ID.
Raises an OSError with an errno of errno.ENOENT if no such local copies exist. Thus, cannot be called multiple times in succession.
The files deleted are all those previously read from this file ID via readGlobalFile by the current job into the job’s file-store-provided temp directory, plus the file that was written to create the given file ID, if it was written by the current job from the job’s file-store-provided temp directory.
- Parameters:
fileStoreID (Union[toil.fileStores.FileID, str]) – File Store ID of the file to be deleted.
- Return type:
None
- abstract deleteGlobalFile(fileStoreID)[source]¶
Delete local files and then permanently deletes them from the job store.
To ensure that the job can be restarted if necessary, the delete will not happen until after the job’s run method has completed.
- Parameters:
fileStoreID (Union[toil.fileStores.FileID, str]) – the File Store ID of the file to be deleted.
- Return type:
None
- importFile(srcUrl, sharedFileName=None)[source]¶
- Parameters:
- Return type:
Optional[toil.fileStores.FileID]
- import_file(src_uri, shared_file_name=None)[source]¶
- Parameters:
- Return type:
Optional[toil.fileStores.FileID]
- exportFile(jobStoreFileID, dstUrl)[source]¶
- Parameters:
jobStoreFileID (toil.fileStores.FileID)
dstUrl (str)
- Return type:
None
- abstract export_file(file_id, dst_uri)[source]¶
- Parameters:
file_id (toil.fileStores.FileID)
dst_uri (str)
- Return type:
None
- log_to_leader(text, level=logging.INFO)[source]¶
Send a logging message to the leader. The message will also be logged by the worker at the same level.
- log_user_stream(name, stream)[source]¶
Send a stream of UTF-8 text to the leader as a named log stream.
Useful for things like the error logs of Docker containers. The leader will show it to the user or organize it appropriately for user-level log information.
- abstract startCommit(jobState=False)[source]¶
Update the status of the job on the disk.
May bump the version number of the job.
May start an asynchronous process. Call waitForCommit() to wait on that process. You must waitForCommit() before committing any further updates to the job. During the asynchronous process, it is safe to modify the job; modifications after this call will not be committed until the next call.
- Parameters:
jobState (bool) – If True, commit the state of the FileStore’s job, and file deletes. Otherwise, commit only file creates/updates.
- Return type:
None
- abstract waitForCommit()[source]¶
Blocks while startCommit is running.
This function is called by this job’s successor to ensure that it does not begin modifying the job store until after this job has finished doing so.
Might be called when startCommit is never called on a particular instance, in which case it does not block.
- Returns:
Always returns True
- Return type:
- classmethod shutdown(shutdown_info)[source]¶
- Abstractmethod:
- Parameters:
shutdown_info (Any)
- Return type:
None
Shutdown the filestore on this node.
This is intended to be called on batch system shutdown.
- Parameters:
shutdown_info (Any) – The implementation-specific shutdown information, for shutting down the file store and removing all its state and all job local temp directories from the node.
- Return type:
None
- class toil.batchSystems.abstractBatchSystem.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:
- toil.batchSystems.abstractBatchSystem.ParsedRequirement¶
- class toil.batchSystems.abstractBatchSystem.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.batchSystems.abstractBatchSystem.memoize¶
Memoize a function result based on its parameters using this decorator.
For example, this can be used in place of lazy initialization. If the decorating function is invoked by multiple threads, the decorated function may be called more than once with the same arguments.
- class toil.batchSystems.abstractBatchSystem.Resource[source]¶
Bases:
namedtuple('Resource', ('name','pathHash','url','contentHash'))Represents a file or directory that will be deployed to each node before any jobs in the user script are invoked.
Each instance is a namedtuple with the following elements:
The pathHash element contains the MD5 (in hexdigest form) of the path to the resource on the leader node. The path, and therefore its hash is unique within a job store.
The url element is a “file:” or “http:” URL at which the resource can be obtained.
The contentHash element is an MD5 checksum of the resource, allowing for validation and caching of resources.
If the resource is a regular file, the type attribute will be ‘file’.
If the resource is a directory, the type attribute will be ‘dir’ and the URL will point at a ZIP archive of that directory.
- resourceEnvNamePrefix = 'JTRES_'¶
- rootDirPathEnvName¶
- classmethod create(jobStore, leaderPath)[source]¶
Saves the content of the file or directory at the given path to the given job store and returns a resource object representing that content for the purpose of obtaining it again at a generic, public URL. This method should be invoked on the leader node.
- Parameters:
leaderPath (str)
- Return type:
- classmethod prepareSystem()[source]¶
Prepares this system for the downloading and lookup of resources. This method should only be invoked on a worker node. It is idempotent but not thread-safe.
- Return type:
None
- register()[source]¶
Register this resource for later retrieval via lookup(), possibly in a child process.
- Return type:
None
- classmethod lookup(leaderPath)[source]¶
Return a resource object representing a resource created from a file or directory at the given path on the leader.
This method should be invoked on the worker. The given path does not need to refer to an existing file or directory on the worker, it only identifies the resource within an instance of toil. This method returns None if no resource for the given path exists.
- download(callback=None)[source]¶
Download this resource from its URL to a file on the local system.
This method should only be invoked on a worker node after the node was setup for accessing resources via prepareSystem().
- Parameters:
callback (Optional[Callable[[str], None]])
- Return type:
None
- property localPath: str¶
- Abstractmethod:
- Return type:
Get the path to resource on the worker.
The file or directory at the returned path may or may not yet exist. Invoking download() will ensure that it does.
- toil.batchSystems.abstractBatchSystem.logger¶
- toil.batchSystems.abstractBatchSystem.EXIT_STATUS_UNAVAILABLE_VALUE = 255¶
- class toil.batchSystems.abstractBatchSystem.BatchJobExitReason[source]¶
Bases:
enum.IntEnumEnum where members are also (and must be) ints
- class toil.batchSystems.abstractBatchSystem.UpdatedBatchJobInfo[source]¶
Bases:
NamedTuple- exitStatus: int¶
The exit status (integer value) of the job. 0 implies successful.
EXIT_STATUS_UNAVAILABLE_VALUE is used when the exit status is not available (e.g. job is lost, or otherwise died but actual exit code was not reported).
- exitReason: BatchJobExitReason | None¶
- class toil.batchSystems.abstractBatchSystem.WorkerCleanupInfo[source]¶
Bases:
NamedTuple
- class toil.batchSystems.abstractBatchSystem.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.batchSystems.abstractBatchSystem.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
- class toil.batchSystems.abstractBatchSystem.NodeInfo(coresUsed, memoryUsed, coresTotal, memoryTotal, requestedCores, requestedMemory, workers)[source]¶
The coresUsed attribute is a floating point value between 0 (all cores idle) and 1 (all cores busy), reflecting the CPU load of the node.
The memoryUsed attribute is a floating point value between 0 (no memory used) and 1 (all memory used), reflecting the memory pressure on the node.
The coresTotal and memoryTotal attributes are the node’s resources, not just the used resources
The requestedCores and requestedMemory attributes are all the resources that Toil Jobs have reserved on the node, regardless of whether the resources are actually being used by the Jobs.
The workers attribute is an integer reflecting the number of workers currently active workers on the node.
- class toil.batchSystems.abstractBatchSystem.AbstractScalableBatchSystem[source]¶
Bases:
AbstractBatchSystemA batch system that supports a variable number of worker nodes.
Used by
toil.provisioners.clusterScaler.ClusterScalerto scale the number of worker nodes in the cluster up or down depending on overall load.- abstract getNodes(preemptible=None, timeout=600)[source]¶
Returns a dictionary mapping node identifiers of preemptible or non-preemptible nodes to NodeInfo objects, one for each node.
- abstract nodeInUse(nodeIP)[source]¶
Can be used to determine if a worker node is running any tasks. If the node is doesn’t exist, this function should simply return False.
- abstract ignoreNode(nodeAddress)[source]¶
Stop sending jobs to this node. Used in autoscaling when the autoscaler is ready to terminate a node, but jobs are still running. This allows the node to be terminated after the current jobs have finished.
- Parameters:
nodeAddress (str) – IP address of node to ignore.
- Return type:
None
- exception toil.batchSystems.abstractBatchSystem.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])
- exception toil.batchSystems.abstractBatchSystem.AcquisitionTimeoutException(resource, requested, available)[source]¶
Bases:
ExceptionTo be raised when a resource request times out.
- class toil.batchSystems.abstractBatchSystem.ResourcePool(initial_value, resource_type, timeout=5)[source]¶
Represents an integral amount of a resource (such as memory bytes). Amounts can be acquired immediately or with a timeout, and released. Provides a context manager to do something with an amount of resource acquired.
- acquireNow(amount)[source]¶
Reserve the given amount of the given resource. Returns True if successful and False if this is not possible immediately.
- class toil.batchSystems.abstractBatchSystem.ResourceSet(initial_value, resource_type, timeout=5)[source]¶
Represents a collection of distinct resources (such as accelerators). Subsets can be acquired immediately or with a timeout, and released. Provides a context manager to do something with a set of of resources acquired.
- acquireNow(subset)[source]¶
Reserve the given amount of the given resource. Returns True if successful and False if this is not possible immediately.
- acquire(subset)[source]¶
Reserve the given amount of the given resource. Raises AcquisitionTimeoutException if this is not possible in under self.timeout time.
- Parameters:
subset (Set[int])
- Return type:
None