toil.fileStores.cachingFileStore¶
Attributes¶
Exceptions¶
Error Raised if the user attempts to add a non-local file to cache |
|
Raised if file store can't free enough space for caching |
|
Error raised if the caching code discovers a file that represents a |
|
Error raised if the user attempts to add a non-local file to cache |
Classes¶
A small wrapper around Python's builtin string class. |
|
Interface used to allow user code run by Toil to read and write files. |
|
Class represents a unit of work in toil. |
|
Stores all the information that the Toil Leader ever needs to know about a Job. |
|
Represents the physical storage for the jobs and files in a Toil workflow. |
|
A wrapper describing an error condition. |
|
A cache-enabled file store. |
Functions¶
|
|
|
Return the free space, and total size of the file system hosting dirPath. |
|
|
|
Copy a file using posix atomic creations semantics. |
|
Copy an open file using posix atomic creations semantics. |
|
Make a publicly-accessible directory in the given directory. |
|
Make a temporary directory like tempfile.mkdtemp, but with relaxed permissions. |
|
Robustly tries to delete paths. |
|
Retry a function if it fails with any Exception defined in "errors". |
|
Return the name of the current process. Like a PID but visible between |
|
Return true if the process named by the given name (from process_name) exists, and false otherwise. |
Module Contents¶
- toil.fileStores.cachingFileStore.getFileSystemSize(dirPath)[source]¶
Return the free space, and total size of the file system hosting dirPath.
- class toil.fileStores.cachingFileStore.FileID(fileStoreID, size, executable=False)[source]¶
Bases:
strA small wrapper around Python’s builtin string class.
It is used to represent a file’s ID in the file store, and has a size attribute that is the file’s size in bytes. This object is returned by importFile and writeGlobalFile.
Calls into the file store can use bare strings; size will be queried from the job store if unavailable in the ID.
- pack()[source]¶
Pack the FileID into a string so it can be passed through external code.
- Return type:
- class toil.fileStores.cachingFileStore.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.fileStores.cachingFileStore.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.fileStores.cachingFileStore.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.fileStores.cachingFileStore.AbstractJobStore(locator)[source]¶
Bases:
abc.ABCRepresents the physical storage for the jobs and files in a Toil workflow.
JobStores are responsible for storing
toil.job.JobDescription(which relate jobs to each other) and files.Actual
toil.job.Jobobjects are stored in files, referenced by JobDescriptions. All the non-file CRUD methods the JobStore provides deal in JobDescriptions and not full, executable Jobs.To actually get ahold of a
toil.job.Job, usetoil.job.Job.loadJob()with a JobStore and the relevant JobDescription.- Parameters:
locator (str)
- initialize(config)[source]¶
Initialize this job store.
Create the physical storage for this job store, allocate a workflow ID and persist the given Toil configuration to the store.
- Parameters:
config (toil.common.Config) – the Toil configuration to initialize this job store with. The given configuration will be updated with the newly allocated workflow ID.
- Raises:
JobStoreExistsException – if the physical storage for this job store already exists
- Return type:
None
- write_config()[source]¶
Persists the value of the
AbstractJobStore.configattribute to the job store, so that it can be retrieved later by other instances of this class.- Return type:
None
- resume()[source]¶
Connect this instance to the physical storage it represents and load the Toil configuration into the
AbstractJobStore.configattribute.- Raises:
NoSuchJobStoreException – if the physical storage for this job store doesn’t exist
- Return type:
None
- property config: toil.common.Config¶
Return the Toil configuration associated with this job store.
- Return type:
- property locator: str¶
Get the locator that defines the job store, which can be used to connect to it.
- Return type:
- rootJobStoreIDFileName = 'rootJobStoreID'¶
- setRootJob(rootJobStoreID)[source]¶
Set the root job of the workflow backed by this job store.
- Parameters:
rootJobStoreID (toil.fileStores.FileID)
- Return type:
None
- set_root_job(job_id)[source]¶
Set the root job of the workflow backed by this job store.
- Parameters:
job_id (toil.fileStores.FileID) – The ID of the job to set as root
- Return type:
None
- load_root_job()[source]¶
Loads the JobDescription for the root job in the current job store.
- Raises:
toil.job.JobException – If no root job is set or if the root job doesn’t exist in this job store
- Returns:
The root job.
- Return type:
- createRootJob(desc)[source]¶
- Parameters:
desc (toil.job.JobDescription)
- Return type:
- create_root_job(job_description)[source]¶
Create the given JobDescription and set it as the root job in this job store.
- Parameters:
job_description (toil.job.JobDescription) – JobDescription to save and make the root job.
- Return type:
- get_root_job_return_value()[source]¶
Parse the return value from the root job.
Raises an exception if the root job hasn’t fulfilled its promise yet.
- Return type:
Any
- importFile(srcUrl: str, sharedFileName: str, hardlink: bool = False, symlink: bool = True) None[source]¶
- importFile(srcUrl: str, sharedFileName: None = None, hardlink: bool = False, symlink: bool = True) toil.fileStores.FileID
- import_file(src_uri: str, shared_file_name: str, hardlink: bool = False, symlink: bool = True) None[source]¶
- import_file(src_uri: str, shared_file_name: None = None, hardlink: bool = False, symlink: bool = True) toil.fileStores.FileID
Imports the file at the given URL into job store. The ID of the newly imported file is returned. If the name of a shared file name is provided, the file will be imported as such and None is returned. If an executable file on the local filesystem is uploaded, its executability will be preserved when it is downloaded.
Currently supported schemes are:
- ‘s3’ for objects in Amazon S3
e.g. s3://bucket/key
- ‘file’ for local files
- ‘http’
- ‘gs’
e.g. gs://bucket/file
Raises FileNotFoundError if the file does not exist.
- Parameters:
- Returns:
The jobStoreFileID of the imported file or None if shared_file_name was given
- Return type:
toil.fileStores.FileID or None
- exportFile(jobStoreFileID, dstUrl)[source]¶
- Parameters:
jobStoreFileID (toil.fileStores.FileID)
dstUrl (str)
- Return type:
None
- export_file(file_id, dst_uri)[source]¶
Exports file to destination pointed at by the destination URL. The exported file will be executable if and only if it was originally uploaded from an executable file on the local filesystem.
Refer to
AbstractJobStore.import_file()documentation for currently supported URL schemes.Note that the helper method _exportFile is used to read from the source and write to destination. To implement any optimizations that circumvent this, the _exportFile method should be overridden by subclasses of AbstractJobStore.
- classmethod url_exists(src_uri)[source]¶
Return True if the file at the given URI exists, and False otherwise.
- classmethod get_size(src_uri)[source]¶
Get the size in bytes of the file at the given URL, or None if it cannot be obtained.
- classmethod get_is_directory(src_uri)[source]¶
Return True if the thing at the given URL is a directory, and False if it is a file. The URL may or may not end in ‘/’.
- classmethod list_url(src_uri)[source]¶
List the directory at the given URL. Returned path components can be joined with ‘/’ onto the passed URL to form new URLs. Those that end in ‘/’ correspond to directories. The provided URL may or may not end with ‘/’.
Currently supported schemes are:
- ‘s3’ for objects in Amazon S3
e.g. s3://bucket/prefix/
- ‘file’ for local files
- classmethod read_from_url(src_uri, writable)[source]¶
Read the given URL and write its content into the given writable stream.
Raises FileNotFoundError if the URL doesn’t exist.
- classmethod open_url(src_uri)[source]¶
Read from the given URI.
Raises FileNotFoundError if the URL doesn’t exist.
Has a readable stream interface, unlike
read_from_url()which takes a writable stream.
- abstract destroy()[source]¶
The inverse of
initialize(), this method deletes the physical storage represented by this instance. While not being atomic, this method is at least idempotent, as a means to counteract potential issues with eventual consistency exhibited by the underlying storage mechanisms. This means that if the method fails (raises an exception), it may (and should be) invoked again. If the underlying storage mechanism is eventually consistent, even a successful invocation is not an ironclad guarantee that the physical storage vanished completely and immediately. A successful invocation only guarantees that the deletion will eventually happen. It is therefore recommended to not immediately reuse the same job store location for a new Toil workflow.- Return type:
None
- get_env()[source]¶
Returns a dictionary of environment variables that this job store requires to be set in order to function properly on a worker.
- clean(jobCache=None)[source]¶
Function to cleanup the state of a job store after a restart.
Fixes jobs that might have been partially updated. Resets the try counts and removes jobs that are not successors of the current root job.
- Parameters:
jobCache (Optional[Dict[Union[str, toil.job.TemporaryID], toil.job.JobDescription]]) – if a value it must be a dict from job ID keys to JobDescription object values. Jobs will be loaded from the cache (which can be downloaded from the job store in a batch) instead of piecemeal when recursed into.
- Return type:
- assignID(jobDescription)[source]¶
- Parameters:
jobDescription (toil.job.JobDescription)
- Return type:
None
- abstract assign_job_id(job_description)[source]¶
Get a new jobStoreID to be used by the described job, and assigns it to the JobDescription.
Files associated with the assigned ID will be accepted even if the JobDescription has never been created or updated.
- Parameters:
job_description (toil.job.JobDescription) – The JobDescription to give an ID to
- Return type:
None
- batch()[source]¶
If supported by the batch system, calls to create() with this context manager active will be performed in a batch after the context manager is released.
- Return type:
Iterator[None]
- create(jobDescription)[source]¶
- Parameters:
jobDescription (toil.job.JobDescription)
- Return type:
- abstract create_job(job_description)[source]¶
Writes the given JobDescription to the job store. The job must have an ID assigned already.
Must call jobDescription.pre_update_hook()
- Returns:
The JobDescription passed.
- Return type:
- Parameters:
job_description (toil.job.JobDescription)
- abstract job_exists(job_id)[source]¶
Indicates whether a description of the job with the specified jobStoreID exists in the job store
- publicUrlExpiration¶
- abstract get_public_url(file_name)[source]¶
Returns a publicly accessible URL to the given file in the job store. The returned URL may expire as early as 1h after its been returned. Throw an exception if the file does not exist.
- Parameters:
file_name (str) – the jobStoreFileID of the file to generate a URL for
- Raises:
NoSuchFileException – if the specified file does not exist in this job store
- Return type:
Differs from
getPublicUrl()in that this method is for generating URLs for shared files written bywriteSharedFileStream().Returns a publicly accessible URL to the given file in the job store. The returned URL starts with ‘http:’, ‘https:’ or ‘file:’. The returned URL may expire as early as 1h after its been returned. Throw an exception if the file does not exist.
- Parameters:
shared_file_name (str) – The name of the shared file to generate a publically accessible url for.
- Raises:
NoSuchFileException – raised if the specified file does not exist in the store
- Return type:
- abstract load_job(job_id)[source]¶
Loads the description of the job referenced by the given ID, assigns it the job store’s config, and returns it.
May declare the job to have failed (see
toil.job.JobDescription.setupJobAfterFailure()) if there is evidence of a failed update attempt.- Parameters:
job_id (str) – the ID of the job to load
- Raises:
NoSuchJobException – if there is no job with the given ID
- Return type:
- update(jobDescription)[source]¶
- Parameters:
jobDescription (toil.job.JobDescription)
- Return type:
None
- abstract update_job(job_description)[source]¶
Persists changes to the state of the given JobDescription in this store atomically.
Must call jobDescription.pre_update_hook()
- Parameters:
job (toil.job.JobDescription) – the job to write to this job store
job_description (toil.job.JobDescription)
- Return type:
None
- abstract delete_job(job_id)[source]¶
Removes the JobDescription from the store atomically. You may not then subsequently call load(), write(), update(), etc. with the same jobStoreID or any JobDescription bearing it.
This operation is idempotent, i.e. deleting a job twice or deleting a non-existent job will succeed silently.
- Parameters:
job_id (str) – the ID of the job to delete from this job store
- Return type:
None
- abstract jobs()[source]¶
Best effort attempt to return iterator on JobDescriptions for all jobs in the store. The iterator may not return all jobs and may also contain orphaned jobs that have already finished successfully and should not be rerun. To guarantee you get any and all jobs that can be run instead construct a more expensive ToilState object
- Returns:
Returns iterator on jobs in the store. The iterator may or may not contain all jobs and may contain invalid jobs
- Return type:
Iterator[toil.job.jobDescription]
- abstract write_file(local_path, job_id=None, cleanup=False)[source]¶
Takes a file (as a path) and places it in this job store. Returns an ID that can be used to retrieve the file at a later time. The file is written in a atomic manner. It will not appear in the jobStore until the write has successfully completed.
- Parameters:
local_path (str) – the path to the local file that will be uploaded to the job store. The last path component (basename of the file) will remain associated with the file in the file store, if supported, so that the file can be searched for by name or name glob.
job_id (str) – the id of a job, or None. If specified, the may be associated with that job in a job-store-specific way. This may influence the returned ID.
cleanup (bool) – Whether to attempt to delete the file when the job whose jobStoreID was given as jobStoreID is deleted with jobStore.delete(job). If jobStoreID was not given, does nothing.
- Raises:
ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method
NoSuchJobException – if the job specified via jobStoreID does not exist
- Return type:
FIXME: some implementations may not raise this
- abstract write_file_stream(job_id=None, cleanup=False, basename=None, encoding=None, errors=None)[source]¶
Similar to writeFile, but returns a context manager yielding a tuple of 1) a file handle which can be written to and 2) the ID of the resulting file in the job store. The yielded file handle does not need to and should not be closed explicitly. The file is written in a atomic manner. It will not appear in the jobStore until the write has successfully completed.
- Parameters:
job_id (str) – the id of a job, or None. If specified, the may be associated with that job in a job-store-specific way. This may influence the returned ID.
cleanup (bool) – Whether to attempt to delete the file when the job whose jobStoreID was given as jobStoreID is deleted with jobStore.delete(job). If jobStoreID was not given, does nothing.
basename (str) – If supported by the implementation, use the given file basename so that when searching the job store with a query matching that basename, the file will be detected.
encoding (str) – the name of the encoding used to encode the file. Encodings are the same as for encode(). Defaults to None which represents binary mode.
errors (str) – 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.
- Raises:
ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method
NoSuchJobException – if the job specified via jobStoreID does not exist
- Return type:
FIXME: some implementations may not raise this
- Returns:
a context manager yielding a file handle which can be written to and an ID that references the newly created file and can be used to read the file in the future.
- Return type:
- Parameters:
- abstract get_empty_file_store_id(job_id=None, cleanup=False, basename=None)[source]¶
Creates an empty file in the job store and returns its ID. Call to fileExists(getEmptyFileStoreID(jobStoreID)) will return True.
- Parameters:
job_id (str) – the id of a job, or None. If specified, the may be associated with that job in a job-store-specific way. This may influence the returned ID.
cleanup (bool) – Whether to attempt to delete the file when the job whose jobStoreID was given as jobStoreID is deleted with jobStore.delete(job). If jobStoreID was not given, does nothing.
basename (str) – If supported by the implementation, 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 jobStoreFileID that references the newly created file and can be used to reference the file in the future.
- Return type:
- abstract read_file(file_id, local_path, symlink=False)[source]¶
Copies or hard links the file referenced by jobStoreFileID to the given local file path. The version will be consistent with the last copy of the file written/updated. If the file in the job store is later modified via updateFile or updateFileStream, it is implementation-defined whether those writes will be visible at localFilePath. The file is copied in an atomic manner. It will not appear in the local file system until the copy has completed.
The file at the given local path may not be modified after this method returns!
Note! Implementations of readFile need to respect/provide the executable attribute on FileIDs.
- Parameters:
file_id (str) – ID of the file to be copied
local_path (str) – the local path indicating where to place the contents of the given file in the job store
symlink (bool) – whether the reader can tolerate a symlink. If set to true, the job store may create a symlink instead of a full copy of the file or a hard link.
- Return type:
None
- read_file_stream(file_id: toil.fileStores.FileID | str, encoding: Literal[None] = None, errors: str | None = None) ContextManager[IO[bytes]][source]¶
- read_file_stream(file_id: toil.fileStores.FileID | str, encoding: str, errors: str | None = None) ContextManager[IO[str]]
Similar to readFile, but returns a context manager yielding a file handle which can be read from. The yielded file handle does not need to and should not be closed explicitly.
- Parameters:
file_id (str) – ID of the file to get a readable file handle for
encoding (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 (str) – 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.
- Returns:
a context manager yielding a file handle which can be read from
- Return type:
- abstract delete_file(file_id)[source]¶
Deletes the file with the given ID from this job store. This operation is idempotent, i.e. deleting a file twice or deleting a non-existent file will succeed silently.
- Parameters:
file_id (str) – ID of the file to delete
- Return type:
None
- abstract get_file_size(file_id)[source]¶
Get the size of the given file in bytes, or 0 if it does not exist when queried.
Note that job stores which encrypt files might return overestimates of file sizes, since the encrypted file may have been padded to the nearest block, augmented with an initialization vector, etc.
- updateFile(jobStoreFileID, localFilePath)[source]¶
Replaces the existing version of a file in the job store.
- abstract update_file(file_id, local_path)[source]¶
Replaces the existing version of a file in the job store.
Throws an exception if the file does not exist.
- Parameters:
- Raises:
ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method
NoSuchFileException – if the specified file does not exist
- Return type:
None
- abstract update_file_stream(file_id, encoding=None, errors=None)[source]¶
Replaces the existing version of a file in the job store. Similar to writeFile, but returns a context manager yielding a file handle which can be written to. The yielded file handle does not need to and should not be closed explicitly.
- Parameters:
file_id (str) – the ID of the file in the job store to be updated
encoding (str) – the name of the encoding used to encode the file. Encodings are the same as for encode(). Defaults to None which represents binary mode.
errors (str) – 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.
- Raises:
ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method
NoSuchFileException – if the specified file does not exist
- Return type:
Iterator[IO[Any]]
Returns a context manager yielding a writable file handle to the global file referenced by the given name. File will be created in an atomic manner.
- Parameters:
shared_file_name (str) – A file name matching AbstractJobStore.fileNameRegex, unique within this job store
encrypted (bool) – True if the file must be encrypted, None if it may be encrypted or False if it must be stored in the clear.
encoding (str) – the name of the encoding used to encode the file. Encodings are the same as for encode(). Defaults to None which represents binary mode.
errors (str) – 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.
- Raises:
ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method
- Returns:
a context manager yielding a writable file handle
- Return type:
Iterator[IO[bytes]]
Returns a context manager yielding a readable file handle to the global file referenced by the given name.
- Parameters:
shared_file_name (str) – A file name matching AbstractJobStore.fileNameRegex, unique within this job store
encoding (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 (str) – 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.
- Returns:
a context manager yielding a readable file handle
- Return type:
Iterator[IO[bytes]]
- writeStatsAndLogging(statsAndLoggingString)[source]¶
- Parameters:
statsAndLoggingString (str)
- Return type:
None
- abstract write_logs(msg)[source]¶
Stores a message as a log in the jobstore.
- Parameters:
msg (str) – the string to be written
- Raises:
ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method
- Return type:
None
- abstract read_logs(callback, read_all=False)[source]¶
Reads logs accumulated by the write_logs() method. For each log this method calls the given callback function with the message as an argument (rather than returning logs directly, this method must be supplied with a callback which will process log messages).
Only unread logs will be read unless the read_all parameter is set.
- Parameters:
callback (Callable) – a function to be applied to each of the stats file handles found
read_all (bool) – a boolean indicating whether to read the already processed stats files in addition to the unread stats files
- Raises:
ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method
- Returns:
the number of stats files processed
- Return type:
- write_leader_pid()[source]¶
Write the pid of this process to a file in the job store.
Overwriting the current contents of pid.log is a feature, not a bug of this method. Other methods will rely on always having the most current pid available. So far there is no reason to store any old pids.
- Return type:
None
- read_leader_pid()[source]¶
Read the pid of the leader process to a file in the job store.
- Raises:
NoSuchFileException – If the PID file doesn’t exist.
- Return type:
- write_leader_node_id()[source]¶
Write the leader node id to the job store. This should only be called by the leader.
- Return type:
None
- read_leader_node_id()[source]¶
Read the leader node id stored in the job store.
- Raises:
NoSuchFileException – If the node ID file doesn’t exist.
- Return type:
- write_kill_flag(kill=False)[source]¶
Write a file inside the job store that serves as a kill flag.
The initialized file contains the characters “NO”. This should only be changed when the user runs the “toil kill” command.
Changing this file to a “YES” triggers a kill of the leader process. The workers are expected to be cleaned up by the leader.
- Parameters:
kill (bool)
- Return type:
None
- read_kill_flag()[source]¶
Read the kill flag from the job store, and return True if the leader has been killed. False otherwise.
- Return type:
- default_caching()[source]¶
Jobstore’s preference as to whether it likes caching or doesn’t care about it. Some jobstores benefit from caching, however on some local configurations it can be flaky.
see https://github.com/DataBiosphere/toil/issues/4218
- Return type:
- toil.fileStores.cachingFileStore.deprecated(new_function_name)[source]¶
- Parameters:
new_function_name (str)
- Return type:
Callable[Ellipsis, Any]
- toil.fileStores.cachingFileStore.atomic_copy(src_path, dest_path, executable=None)[source]¶
Copy a file using posix atomic creations semantics.
- toil.fileStores.cachingFileStore.atomic_copyobj(src_fh, dest_path, length=16384, executable=False)[source]¶
Copy an open file using posix atomic creations semantics.
- Parameters:
src_fh (io.BytesIO)
dest_path (str)
length (int)
executable (bool)
- Return type:
None
- toil.fileStores.cachingFileStore.make_public_dir(in_directory, suggested_name=None)[source]¶
Make a publicly-accessible directory in the given directory.
- Parameters:
- Return type:
Try to make a random directory name with length 4 that doesn’t exist, with the given prefix. Otherwise, try length 5, length 6, etc, up to a max of 32 (len of uuid4 with dashes replaced). This function’s purpose is mostly to avoid having long file names when generating directories. If somehow this fails, which should be incredibly unlikely, default to a normal uuid4, which was our old default.
- toil.fileStores.cachingFileStore.mkdtemp(suffix=None, prefix=None, dir=None)[source]¶
Make a temporary directory like tempfile.mkdtemp, but with relaxed permissions.
The permissions on the directory will be 711 instead of 700, allowing the group and all other users to traverse the directory. This is necessary if the directory is on NFS and the Docker daemon would like to mount it or a file inside it into a container, because on NFS even the Docker daemon appears bound by the file permissions.
See <https://github.com/DataBiosphere/toil/issues/4644>, and <https://stackoverflow.com/a/67928880> which talks about a similar problem but in the context of user namespaces.
- toil.fileStores.cachingFileStore.robust_rmtree(path)[source]¶
Robustly tries to delete paths.
Continues silently if the path to be removed is already gone, or if it goes away while this function is executing.
May raise an error if a path changes between file and directory while the function is executing, or if a permission error is encountered.
- class toil.fileStores.cachingFileStore.ErrorCondition(error=None, error_codes=None, boto_error_codes=None, error_message_must_include=None, retry_on_this_condition=True)[source]¶
A wrapper describing an error condition.
ErrorCondition events may be used to define errors in more detail to determine whether to retry.
- toil.fileStores.cachingFileStore.retry(intervals=None, infinite_retries=False, errors=None, log_message=None, prepare=None)[source]¶
Retry a function if it fails with any Exception defined in “errors”.
Does so every x seconds, where x is defined by a list of numbers (ints or floats) in “intervals”. Also accepts ErrorCondition events for more detailed retry attempts.
- Parameters:
intervals (Optional[List]) – A list of times in seconds we keep retrying until returning failure. Defaults to retrying with the following exponential back-off before failing: 1s, 1s, 2s, 4s, 8s, 16s
infinite_retries (bool) – If this is True, reset the intervals when they run out. Defaults to: False.
errors (Optional[Sequence[Union[ErrorCondition, Type[Exception]]]]) –
A list of exceptions OR ErrorCondition objects to catch and retry on. ErrorCondition objects describe more detailed error event conditions than a plain error. An ErrorCondition specifies: - Exception (required) - Error codes that must match to be retried (optional; defaults to not checking) - A string that must be in the error message to be retried (optional; defaults to not checking) - A bool that can be set to False to always error on this condition.
If not specified, this will default to a generic Exception.
log_message (Optional[Tuple[Callable, str]]) – Optional tuple of (“log/print function()”, “message string”) that will precede each attempt.
prepare (Optional[List[Callable]]) – Optional list of functions to call, with the function’s arguments, between retries, to reset state.
- Returns:
The result of the wrapped function or raise.
- Return type:
Callable[[Callable[Ellipsis, RT]], Callable[Ellipsis, RT]]
- toil.fileStores.cachingFileStore.get_process_name(base_dir)[source]¶
Return the name of the current process. Like a PID but visible between containers on what to Toil appears to be a node.
- toil.fileStores.cachingFileStore.process_name_exists(base_dir, name)[source]¶
Return true if the process named by the given name (from process_name) exists, and false otherwise.
Can see across container boundaries using the given node workflow directory.
- toil.fileStores.cachingFileStore.logger¶
- toil.fileStores.cachingFileStore.SQLITE_TIMEOUT_SECS = 60.0¶
- exception toil.fileStores.cachingFileStore.CacheError(message)[source]¶
Bases:
ExceptionError Raised if the user attempts to add a non-local file to cache
- exception toil.fileStores.cachingFileStore.CacheUnbalancedError[source]¶
Bases:
CacheErrorRaised if file store can’t free enough space for caching
- message = 'Unable unable to free enough space for caching. This error frequently arises due to jobs using...¶
- exception toil.fileStores.cachingFileStore.IllegalDeletionCacheError(deletedFile)[source]¶
Bases:
CacheErrorError raised if the caching code discovers a file that represents a reference to a cached file to have gone missing.
This can be a big problem if a hard link is moved, because then the cache will be unable to evict the file it links to.
Remember that files read with readGlobalFile may not be deleted by the user and need to be deleted with deleteLocalFile.
- exception toil.fileStores.cachingFileStore.InvalidSourceCacheError(message)[source]¶
Bases:
CacheErrorError raised if the user attempts to add a non-local file to cache
- class toil.fileStores.cachingFileStore.CachingFileStore(jobStore, jobDesc, file_store_dir, waitForPreviousCommit)[source]¶
Bases:
toil.fileStores.abstractFileStore.AbstractFileStoreA cache-enabled file store.
Provides files that are read out as symlinks or hard links into a cache directory for the node, if permitted by the workflow.
Also attempts to write files back to the backing JobStore asynchronously, after quickly taking them into the cache. Writes are only required to finish when the job’s actual state after running is committed back to the job store.
Internaly, manages caching using a database. Each node has its own database, shared between all the workers on the node. The database contains several tables:
files contains one entry for each file in the cache. Each entry knows the path to its data on disk. It also knows its global file ID, its state, and its owning worker PID. If the owning worker dies, another worker will pick it up. It also knows its size.
File states are:
“cached”: happily stored in the cache. Reads can happen immediately. Owner is null. May be adopted and moved to state “deleting” by anyone, if it has no outstanding immutable references.
“downloading”: in the process of being saved to the cache by a non-null owner. Reads must wait for the state to become “cached”. If the worker dies, goes to state “deleting”, because we don’t know if it was fully downloaded or if anyone still needs it. No references can be created to a “downloading” file except by the worker responsible for downloading it.
“uploadable”: stored in the cache and ready to be written to the job store by a non-null owner. Transitions to “uploading” when a (thread of) the owning worker process picks it up and begins uploading it, to free cache space or to commit a completed job. If the worker dies, goes to state “cached”, because it may have outstanding immutable references from the dead-but-not-cleaned-up job that was going to write it.
“uploading”: stored in the cache and being written to the job store by a non-null owner. Transitions to “cached” when successfully uploaded. If the worker dies, goes to state “cached”, because it may have outstanding immutable references from the dead-but-not-cleaned-up job that was writing it.
“deleting”: in the process of being removed from the cache by a non-null owner. Will eventually be removed from the database.
refs contains one entry for each outstanding reference to a cached file (hard link, symlink, or full copy). The table name is refs instead of references because references is an SQL reserved word. It remembers what job ID has the reference, and the path the reference is at. References have three states:
“immutable”: represents a hardlink or symlink to a file in the cache. Dedicates the file’s size in bytes of the job’s disk requirement to the cache, to be used to cache this file or to keep around other files without references. May be upgraded to “copying” if the link can’t actually be created.
“copying”: records that a file in the cache is in the process of being copied to a path. Will be upgraded to a mutable reference eventually.
“mutable”: records that a file from the cache was copied to a certain path. Exist only to support deleteLocalFile’s API. Only files with only mutable references (or no references) are eligible for eviction.
jobs contains one entry for each job currently running. It keeps track of the job’s ID, the worker that is supposed to be running the job, the job’s disk requirement, and the job’s local temp dir path that will need to be cleaned up. When workers check for jobs whose workers have died, they null out the old worker, and grab ownership of and clean up jobs and their references until the null-worker jobs are gone.
properties contains key, value pairs for tracking total space available, and whether caching is free for this run.
- Parameters:
jobDesc (toil.job.JobDescription)
file_store_dir (str)
waitForPreviousCommit (Callable[[], Any])
- as_process()[source]¶
Assume the process’s identity to act on the caching database.
Yields the process’s name in the caching database, and holds onto a lock while your thread has it.
- Return type:
Generator[str, None, None]
- property con: sqlite3.Connection¶
Get the database connection to be used for the current thread.
- Return type:
- property cur: sqlite3.Cursor¶
Get the main cursor to be used for the current thread.
- Return type:
- getCacheLimit()[source]¶
Return the total number of bytes to which the cache is limited.
If no limit is available, raises an error.
- getCacheUsed()[source]¶
Return the total number of bytes used in the cache.
If no value is available, raises an error.
- getCacheExtraJobSpace()[source]¶
Return the total number of bytes of disk space requested by jobs running against this cache but not yet used.
We can get into a situation where the jobs on the node take up all its space, but then they want to write to or read from the cache. So when that happens, we need to debit space from them somehow…
If no value is available, raises an error.
- getCacheAvailable()[source]¶
Return the total number of free bytes available for caching, or, if negative, the total number of bytes of cached files that need to be evicted to free up enough space for all the currently scheduled jobs.
If no value is available, raises an error.
- getSpaceUsableForJobs()[source]¶
Return the total number of bytes that are not taken up by job requirements, ignoring files and file usage. We can’t ever run more jobs than we actually have room for, even with caching.
If not retrievable, raises an error.
- getCacheUnusedJobRequirement()[source]¶
Return the total number of bytes of disk space requested by the current job and not used by files the job is using in the cache.
Mutable references don’t count, but immutable/uploading ones do.
If no value is available, raises an error.
- adjustCacheLimit(newTotalBytes)[source]¶
Adjust the total cache size limit to the given number of bytes.
- fileIsCached(fileID)[source]¶
Return true if the given file is currently cached, and false otherwise.
Note that this can’t really be relied upon because a file may go cached -> deleting after you look at it. If you need to do something with the file you need to do it in a transaction.
- getFileReaderCount(fileID)[source]¶
Return the number of current outstanding reads of the given file.
Counts mutable references too.
- cachingIsFree()[source]¶
Return true if files can be cached for free, without taking up space. Return false otherwise.
This will be true when working with certain job stores in certain configurations, most notably the FileJobStore.
- open(job)[source]¶
This context manager decorated method allows cache-specific operations to be conducted before and after the execution of a job in worker.py
- Parameters:
job (toil.job.Job)
- Return type:
Generator[None, None, None]
- writeGlobalFile(localFileName, cleanup=False, executable=False)[source]¶
Creates a file in the jobstore and returns a FileID reference.
- 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 – job store id for the file
userPath – a path to the name of file to which the global file will be copied or hard-linked (see below).
cache – Described in
toil.fileStores.CachingFileStore.readGlobalFile()mutable – Described in
toil.fileStores.CachingFileStore.readGlobalFile()symlink – 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.
- readGlobalFileStream(fileStoreID, encoding=None, errors=None)[source]¶
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.
- 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 – File Store ID of the file to be deleted.
- 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 – the File Store ID of the file to be deleted.
- exportFile(jobStoreFileID, dstUrl)[source]¶
- Parameters:
jobStoreFileID (toil.fileStores.FileID)
dstUrl (str)
- Return type:
None
- export_file(file_id, dst_uri)[source]¶
- Parameters:
file_id (toil.fileStores.FileID)
dst_uri (str)
- Return type:
None
- 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:
- 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 – If True, commit the state of the FileStore’s job, and file deletes. Otherwise, commit only file creates/updates.
- startCommitThread(state_to_commit)[source]¶
Run in a thread to actually commit the current job.
- Parameters:
state_to_commit (Optional[toil.job.JobDescription])
- classmethod shutdown(shutdown_info)[source]¶
- Parameters:
shutdown_info (Tuple[str, str]) – Tuple of the coordination directory (where the cache database is) and the cache directory (where the cached data is).
- Return type:
None
Job local temp directories will be removed due to their appearance in the database.