toil.cwl.cwltoil

Implemented support for Common Workflow Language (CWL) for Toil.

Attributes

DEFAULT_BATCH_SYSTEM

CWL_UNSUPPORTED_REQUIREMENT_EXCEPTION

CWL_UNSUPPORTED_REQUIREMENT_EXIT_CODE

Promised

DEFAULT_LOGLEVEL

logger

DEFAULT_TMPDIR

DEFAULT_TMPDIR_PREFIX

MISSING_FILE

DirectoryContents

ProcessType

usage_message

Exceptions

InsufficientSystemResources

Common base class for all non-exit exceptions.

JobTooBigError

Raised in the scaler thread when a job cannot fit in any available node

FailedJobsException

Common base class for all non-exit exceptions.

NoSuchFileException

Indicates that the specified file does not exist.

LocatorException

Base exception class for all locator exceptions.

InvalidImportExportUrlException

Common base class for all non-exit exceptions.

UnimplementedURLException

Unspecified run-time error.

JobStoreUnavailableException

Raised when a particular type of job store is requested but can't be used.

NoAvailableJobStoreException

Indicates that no job store name is available.

Classes

Toil

A context manager that represents a Toil workflow.

FileID

A small wrapper around Python's builtin string class.

AbstractFileStore

Interface used to allow user code run by Toil to read and write files.

AcceleratorRequirement

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

Job

Class represents a unit of work in toil.

Promise

References a return value from a method as a promise before the method itself is run.

AbstractJobStore

Represents the physical storage for the jobs and files in a Toil workflow.

FileJobStore

A job store that uses a directory on a locally attached file system. To be compatible with

ExceptionalThread

A thread whose join() method re-raises exceptions raised during run(). While join() is

UnresolvedDict

Tag to indicate a dict contains promises that must be resolved.

SkipNull

Internal sentinel object.

Conditional

Object holding conditional expression until we are ready to evaluate it.

ResolveSource

Apply linkMerge and pickValue operators to values coming into a port.

StepValueFrom

A workflow step input which has a valueFrom expression attached to it.

DefaultWithSource

A workflow step input that has both a source and a default value.

JustAValue

A simple value masquerading as a 'resolve'-able object.

ToilPathMapper

Keeps track of files in a Toil way.

ToilSingleJobExecutor

A SingleJobExecutor that does not assume it is at the top level of the workflow.

ToilTool

Mixin to hook Toil into a cwltool tool type.

ToilCommandLineTool

Subclass the cwltool command line tool to provide the custom ToilPathMapper.

ToilExpressionTool

Subclass the cwltool expression tool to provide the custom ToilPathMapper.

ToilFsAccess

Custom filesystem access class which handles toil filestore references.

CWLNamedJob

Base class for all CWL jobs that do user work, to give them useful names.

ResolveIndirect

Helper Job.

CWLJobWrapper

Wrap a CWL job that uses dynamic resources requirement.

CWLJob

Execute a CWL tool using cwltool.executors.SingleJobExecutor.

CWLScatter

Implement workflow scatter step.

CWLGather

Follows on to a scatter Job.

SelfJob

Fake job object to facilitate implementation of CWLWorkflow.run().

CWLWorkflow

Toil Job to convert a CWL workflow graph into a Toil job graph.

Functions

addOptions(parser[, jobstore_as_flag, cwl, wdl])

Add all Toil command line options to a parser.

check_cwltool_version()

Check if the installed cwltool version matches Toil's expected version.

download_structure(file_store, index, existing, ...)

Download nested dictionary from the Toil file store to a local path.

get_from_structure(dir_dict, path)

Given a relative path, follow it in the given directory structure.

visit_cwl_class_and_reduce(rec, classes, op_down, op_up)

Apply the given operations to all CWL objects with the given named CWL class.

unwrap(p)

Function for ensuring you actually have a promised value, and not just a promise.

generate_locator(job_store_type[, local_suggestion, ...])

Generate a random locator for a job store of the given type. Raises an

mkdtemp([suffix, prefix, dir])

Make a temporary directory like tempfile.mkdtemp, but with relaxed permissions.

cwltoil_was_removed()

Complain about deprecated entrypoint.

filter_skip_null(name, value)

Recursively filter out SkipNull objects from 'value'.

ensure_no_collisions(directory[, dir_description])

Make sure no items in the given CWL Directory have the same name.

resolve_dict_w_promises(dict_w_promises[, file_store])

Resolve a dictionary of promises evaluate expressions to produce the actual values.

simplify_list(maybe_list)

Turn a length one list loaded by cwltool into a scalar.

toil_make_tool(toolpath_object, loadingContext)

Emit custom ToilCommandLineTools.

check_directory_dict_invariants(contents)

Make sure a directory structure dict makes sense. Throws an error

decode_directory(dir_path)

Decode a directory from a "toildir:" path to a directory (or a file in it).

encode_directory(contents)

Encode a directory from a "toildir:" path to a directory (or a file in it).

toil_get_file(file_store, index, existing, uri[, ...])

Set up the given file or directory from the Toil jobstore at a file URI

write_file(writeFunc, index, existing, file_uri)

Write a file into the Toil jobstore.

path_to_loc(obj)

Make a path into a location.

import_files(import_function, fs_access, fileindex, ...)

Prepare all files and directories.

upload_directory(directory_metadata, directory_contents)

Upload a Directory object.

upload_file(uploadfunc, fileindex, existing, file_metadata)

Update a file object so that the file will be accessible from another machine.

writeGlobalFileWrapper(file_store, fileuri)

Wrap writeGlobalFile to accept file:// URIs.

remove_empty_listings(rec)

toilStageFiles(toil, cwljob, outdir[, destBucket, ...])

Copy input files out of the global file store and update location and path.

get_container_engine(runtime_context)

makeJob(tool, jobobj, runtime_context, parent_name, ...)

Create the correct Toil Job object for the CWL tool.

remove_pickle_problems(obj)

Doc_loader does not pickle correctly, causing Toil errors, remove from objects.

visitSteps(cmdline_tool, op)

Iterate over a CWL Process object, running the op on each tool description

rm_unprocessed_secondary_files(job_params)

filtered_secondary_files(unfiltered_secondary_files)

Remove unprocessed secondary files.

scan_for_unsupported_requirements(tool[, ...])

Scan the given CWL tool for any unsupported optional features.

determine_load_listing(tool)

Determine the directory.listing feature in CWL.

generate_default_job_store(batch_system_name, ...)

Choose a default job store appropriate to the requested batch system and

get_options(args)

Parse given args and properly add non-Toil arguments into the cwljob of the Namespace.

main([args, stdout])

Run the main loop for toil-cwl-runner.

find_default_container(args, builder)

Find the default constructor by consulting a Toil.options object.

Module Contents

exception toil.cwl.cwltoil.InsufficientSystemResources(requirer, resource, available=None, batch_system=None, source=None, details=[])

Bases: Exception

Common base class for all non-exit exceptions.

Parameters:
  • requirer (toil.job.Requirer)

  • resource (str)

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

  • batch_system (Optional[str])

  • source (Optional[str])

  • details (List[str])

__str__()

Explain the exception.

Return type:

str

toil.cwl.cwltoil.DEFAULT_BATCH_SYSTEM = 'single_machine'
class toil.cwl.cwltoil.Toil(options)

Bases: ContextManager[Toil]

A context manager that represents a Toil workflow.

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

Parameters:

options (argparse.Namespace)

config: Config
__enter__()

Derive configuration from the command line options.

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

Return type:

Toil

__exit__(exc_type, exc_val, exc_tb)

Clean up after a workflow invocation.

Depending on the configuration, delete the job store.

Parameters:
Return type:

Literal[False]

start(rootJob)

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

Restarts a workflow that has been interrupted.

Returns:

The root job’s return value

Return type:

Any

classmethod getJobStore(locator)

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

Parameters:

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

Returns:

an instance of a concrete subclass of AbstractJobStore

Return type:

toil.jobStores.abstractJobStore.AbstractJobStore

static parseLocator(locator)
Parameters:

locator (str)

Return type:

Tuple[str, str]

static buildLocator(name, rest)
Parameters:
Return type:

str

classmethod resumeJobStore(locator)
Parameters:

locator (str)

Return type:

toil.jobStores.abstractJobStore.AbstractJobStore

static createBatchSystem(config)

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

Parameters:

config (Config) – the current configuration

Returns:

an instance of a concrete subclass of AbstractBatchSystem

Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

importFile(srcUrl: str, sharedFileName: str, symlink: bool = True) None
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
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)
Parameters:
Return type:

None

export_file(file_id, dst_uri)

Export file to destination pointed at by the destination URL.

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

Parameters:
Return type:

None

static normalize_uri(uri, check_existence=False)

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

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

  • uri (str)

Return type:

str

static getToilWorkDir(configWorkDir=None)

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

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

Parameters:

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

Returns:

Path to the Toil work directory, constant across all machines

Return type:

str

classmethod get_toil_coordination_dir(config_work_dir, config_coordination_dir)

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

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

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

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

Returns:

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

Return type:

str

static get_workflow_path_component(workflow_id)

Get a safe filesystem path component for a workflow.

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

Parameters:

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

Return type:

str

classmethod getLocalWorkflowDir(workflowID, configWorkDir=None)

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

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

  • workflowID (str)

Returns:

Path to the local workflow directory on this machine

Return type:

str

classmethod get_local_workflow_coordination_dir(workflow_id, config_work_dir, config_coordination_dir)

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

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

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

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

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

Returns:

Path to the local workflow coordination directory on this machine.

Return type:

str

toil.cwl.cwltoil.addOptions(parser, jobstore_as_flag=False, cwl=False, wdl=False)

Add all Toil command line options to a parser.

Support for config files if using configargparse. This will also check and set up the default config file.

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

  • cwl (bool) – Whether CWL options are expected. If so, CWL options won’t be suppressed.

  • wdl (bool) – Whether WDL options are expected. If so, WDL options won’t be suppressed.

  • parser (argparse.ArgumentParser)

Return type:

None

toil.cwl.cwltoil.check_cwltool_version()

Check if the installed cwltool version matches Toil’s expected version.

A warning is printed to standard error if the versions differ. We do not assume that logging is set up already. Safe to call repeatedly; only one warning will be printed.

Return type:

None

exception toil.cwl.cwltoil.JobTooBigError(job=None, shape=None, constraints=None)

Bases: Exception

Raised in the scaler thread when a job cannot fit in any available node type and is likely to lock up the workflow.

Parameters:
__str__()

Stringify the exception, including the message.

Return type:

str

toil.cwl.cwltoil.CWL_UNSUPPORTED_REQUIREMENT_EXCEPTION: Type[cwltool.errors.UnsupportedRequirement] | Type[CWLUnsupportedException]
toil.cwl.cwltoil.CWL_UNSUPPORTED_REQUIREMENT_EXIT_CODE = 33
toil.cwl.cwltoil.download_structure(file_store, index, existing, dir_dict, into_dir)

Download nested dictionary from the Toil file store to a local path.

Guaranteed to fill the structure with real files, and not symlinks out of it to elsewhere. File URIs may be toilfile: URIs or any other URI that Toil’s job store system can read.

Parameters:
  • file_store (toil.fileStores.abstractFileStore.AbstractFileStore) – The Toil file store to download from.

  • index (Dict[str, str]) – Maps from downloaded file path back to input URI.

  • existing (Dict[str, str]) – Maps from file_store_id URI to downloaded file path.

  • dir_dict (DirectoryStructure) – a dict from string to string (for files) or dict (for subdirectories) describing a directory structure.

  • into_dir (str) – The directory to download the top-level dict’s files into.

Return type:

None

toil.cwl.cwltoil.get_from_structure(dir_dict, path)

Given a relative path, follow it in the given directory structure.

Return the string URI for files, the directory dict for subdirectories, or None for nonexistent things.

Parameters:
  • dir_dict (DirectoryStructure)

  • path (str)

Return type:

Union[str, DirectoryStructure, None]

toil.cwl.cwltoil.visit_cwl_class_and_reduce(rec, classes, op_down, op_up)

Apply the given operations to all CWL objects with the given named CWL class.

Applies the down operation top-down, and the up operation bottom-up, and passes the down operation’s result and a list of the up operation results for all child keys (flattening across lists and collapsing nodes of non-matching classes) to the up operation.

Returns:

The flattened list of up operation results from all calls.

Parameters:
  • rec (Any)

  • classes (Iterable[str])

  • op_down (Callable[[Any], DownReturnType])

  • op_up (Callable[[Any, DownReturnType, List[UpReturnType]], UpReturnType])

Return type:

List[UpReturnType]

exception toil.cwl.cwltoil.FailedJobsException(job_store, failed_jobs, exit_code=1)

Bases: Exception

Common base class for all non-exit exceptions.

Parameters:
__str__()

Stringify the exception, including the message.

Return type:

str

class toil.cwl.cwltoil.FileID(fileStoreID, size, executable=False)

Bases: str

A 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.

Parameters:
pack()

Pack the FileID into a string so it can be passed through external code.

Return type:

str

classmethod forPath(fileStoreID, filePath)
Parameters:
  • fileStoreID (str)

  • filePath (str)

Return type:

FileID

classmethod unpack(packedFileStoreID)

Unpack the result of pack() into a FileID object.

Parameters:

packedFileStoreID (str)

Return type:

FileID

class toil.cwl.cwltoil.AbstractFileStore(jobStore, jobDesc, file_store_dir, waitForPreviousCommit)

Bases: abc.ABC

Interface 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:
static createFileStore(jobStore, jobDesc, file_store_dir, waitForPreviousCommit, caching)

Create a concreate FileStore.

Parameters:
Return type:

Union[toil.fileStores.nonCachingFileStore.NonCachingFileStore, toil.fileStores.cachingFileStore.CachingFileStore]

static shutdownFileStore(workflowID, config_work_dir, config_coordination_dir)

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.

Parameters:
  • workflowID (str) – The workflow ID for this invocation of the workflow

  • config_work_dir (Optional[str]) – The path to the work directory in the Toil Config.

  • config_coordination_dir (Optional[str]) – The path to the coordination directory in the Toil Config.

Return type:

None

open(job)

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

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

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:

str

getLocalTempFile(suffix=None, prefix=None)

Get a new local temporary file that will persist for the duration of the job.

Parameters:
  • suffix (Optional[str]) – If not None, the file name will end with this string. Otherwise, default value “.tmp” will be used

  • prefix (Optional[str]) – If not None, the file name will start with this string. Otherwise, default value “tmp” will be used

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:

str

getLocalTempFileName(suffix=None, prefix=None)

Get a valid name for a new local file. Don’t actually create a file at the path.

Parameters:
  • suffix (Optional[str]) – If not None, the file name will end with this string. Otherwise, default value “.tmp” will be used

  • prefix (Optional[str]) – If not None, the file name will start with this string. Otherwise, default value “tmp” will be used

Returns:

Path to valid file

Return type:

str

abstract writeGlobalFile(localFileName, cleanup=False)

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 by toil.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:

toil.fileStores.FileID

writeGlobalFileStream(cleanup=False, basename=None, encoding=None, errors=None)

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)

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() and readGlobalFileStream() implementations.

Parameters:
Return type:

None

abstract readGlobalFile(fileStoreID, userPath=None, cache=True, mutable=False, symlink=False)

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:

str

readGlobalFileStream(fileStoreID: str, encoding: Literal[None] = None, errors: str | None = None) ContextManager[IO[bytes]]
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)

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:

int

abstract deleteLocalFile(fileStoreID)

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)

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)
Parameters:
  • srcUrl (str)

  • sharedFileName (Optional[str])

Return type:

Optional[toil.fileStores.FileID]

import_file(src_uri, shared_file_name=None)
Parameters:
  • src_uri (str)

  • shared_file_name (Optional[str])

Return type:

Optional[toil.fileStores.FileID]

exportFile(jobStoreFileID, dstUrl)
Parameters:
Return type:

None

abstract export_file(file_id, dst_uri)
Parameters:
Return type:

None

log_to_leader(text, level=logging.INFO)

Send a logging message to the leader. The message will also be logged by the worker at the same level.

Parameters:
  • text (str) – The string to log.

  • level (int) – The logging level.

Return type:

None

logToMaster(text, level=logging.INFO)
Parameters:
Return type:

None

log_user_stream(name, stream)

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.

Parameters:
  • name (str) – A hierarchical, .-delimited string.

  • stream (IO[bytes]) – A stream of encoded text. Encoding errors will be tolerated.

Return type:

None

abstract startCommit(jobState=False)

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

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:

bool

classmethod shutdown(shutdown_info)
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.cwl.cwltoil.AcceleratorRequirement

Bases: TypedDict

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

count: int

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

kind: str

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

model: typing_extensions.NotRequired[str]

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

brand: typing_extensions.NotRequired[str]

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

api: typing_extensions.NotRequired[str]

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

class toil.cwl.cwltoil.Job(memory=None, cores=None, disk=None, accelerators=None, preemptible=None, preemptable=None, unitName='', checkpoint=False, displayName='', descriptionClass=None, local=None)

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__()

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

check_initialized()

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

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

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

Return type:

None

property jobStoreID: str | TemporaryID

Get the ID of this Job.

Return type:

Union[str, TemporaryID]

property description: JobDescription

Expose the JobDescription that describes this job.

Return type:

JobDescription

property disk: int

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

Return type:

int

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

The number of CPU cores required.

Return type:

Union[int, float]

property accelerators: List[AcceleratorRequirement]

Any accelerators, such as GPUs, that are needed.

Return type:

List[AcceleratorRequirement]

property preemptible: bool

Whether the job can be run on a preemptible node.

Return type:

bool

preemptable()
property checkpoint: bool

Determine if the job is a checkpoint job or not.

Return type:

bool

assignConfig(config)

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)

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)

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

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

Returns:

childJob: for call chaining

Parameters:

childJob (Job)

Return type:

Job

hasChild(childJob)

Check if childJob is already a child of this job.

Returns:

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

Parameters:

childJob (Job)

Return type:

bool

addFollowOn(followOnJob)

Add a follow-on job.

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

Returns:

followOnJob for call chaining

Parameters:

followOnJob (Job)

Return type:

Job

hasPredecessor(job)

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

Parameters:

job (Job)

Return type:

bool

hasFollowOn(followOnJob)

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

Returns:

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

Parameters:

followOnJob (Job)

Return type:

bool

addService(service, parentService=None)

Add a service.

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

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

Raises:

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

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

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

Returns:

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

Return type:

Promise

hasService(service)

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

Parameters:

service (Job)

Return type:

bool

addChildFn(fn, *args, **kwargs)

Add a function as a child job.

Parameters:

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

Returns:

The new child job that wraps fn.

Return type:

FunctionWrappingJob

addFollowOnFn(fn, *args, **kwargs)

Add a function as a follow-on job.

Parameters:

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

Returns:

The new follow-on job that wraps fn.

Return type:

FunctionWrappingJob

addChildJobFn(fn, *args, **kwargs)

Add a job function as a child job.

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

Parameters:

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

Returns:

The new child job that wraps fn.

Return type:

FunctionWrappingJob

addFollowOnJobFn(fn, *args, **kwargs)

Add a follow-on job function.

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

Parameters:

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

Returns:

The new follow-on job that wraps fn.

Return type:

FunctionWrappingJob

property tempDir: str

Shortcut to calling job.fileStore.getLocalTempDir().

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

Return type:

str

log(text, level=logging.INFO)

Log using fileStore.log_to_leader().

Parameters:

text (str)

Return type:

None

static wrapFn(fn, *args, **kwargs)

Makes a Job out of a function.

Convenience function for constructor of toil.job.FunctionWrappingJob.

Parameters:

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

Returns:

The new function that wraps fn.

Return type:

FunctionWrappingJob

static wrapJobFn(fn, *args, **kwargs)

Makes a Job out of a job function.

Convenience function for constructor of toil.job.JobFunctionWrappingJob.

Parameters:

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

Returns:

The new job function that wraps fn.

Return type:

JobFunctionWrappingJob

encapsulate(name=None)

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

Parameters:

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

Returns:

an encapsulated version of this job.

Return type:

EncapsulatedJob

rv(*path)

Create a promise (toil.job.Promise).

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

Parameters:

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

Returns:

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

Return type:

Promise

registerPromise(path)
prepareForPromiseRegistration(jobStore)

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

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

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

Parameters:

jobStore (toil.jobStores.abstractJobStore.AbstractJobStore)

Return type:

None

checkJobGraphForDeadlocks()

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

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

Raises:

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

getRootJobs()

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()
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()
Raises:

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

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

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

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

checkNewCheckpointsAreLeafVertices()

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)

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

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

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

  • args (list) – The arguments to the function

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

Return type:

None

class Runner

Used to setup and run Toil workflow.

static getDefaultArgumentParser(jobstore_as_flag=False)

Get argument parser with added toil workflow options.

Parameters:

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

Returns:

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

Return type:

argparse.ArgumentParser

static getDefaultOptions(jobStore=None, jobstore_as_flag=False)

Get default options for a toil workflow.

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

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

Returns:

The options used by a toil workflow.

Return type:

argparse.Namespace

static addToilOptions(parser, jobstore_as_flag=False)

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

Parameters:
Return type:

None

static startToil(job, options)

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)

Bases: Requirer

Abstract class used to define the interface to a service.

Should be subclassed by the user to define services.

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

abstract start(job)

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)

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

Checks the service is still running.

Raises:

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

Returns:

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

Return type:

bool

getUserScript()
Return type:

toil.resource.ModuleDescriptor

getTopologicalOrderingOfJobs()
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)

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)

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

Returns:

the JobDescription describing this job.

Parameters:

jobStore (toil.jobStores.abstractJobStore.AbstractJobStore)

Return type:

JobDescription

classmethod loadJob(job_store, job_description)

Retrieves a toil.job.Job instance from a JobStore

Parameters:
Returns:

The job referenced by the JobDescription.

Return type:

Job

set_debug_flag(flag)

Enable the given debug option on the job.

Parameters:

flag (str)

Return type:

None

has_debug_flag(flag)

Return true if the given debug flag is set.

Parameters:

flag (str)

Return type:

bool

files_downloaded_hook(host_and_job_paths=None)

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

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

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

Parameters:

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

Return type:

None

class toil.cwl.cwltoil.Promise(job, path)

References a return value from a method as a promise before the method itself is run.

References a return value from a toil.job.Job.run() or toil.job.Job.Service.start() method as a promise before the method itself is run.

Let T be a job. Instances of Promise (termed a promise) are returned by T.rv(), which is used to reference the return value of T’s run function. When the promise is passed to the constructor (or as an argument to a wrapped function) of a different, successor job the promise will be replaced by the actual referenced return value. This mechanism allows a return values from one job’s run method to be input argument to job before the former job’s run function has been executed.

Parameters:
  • job (Job)

  • path (Any)

filesToDelete

A set of IDs of files containing promised values when we know we won’t need them anymore

__reduce__()

Return the Promise class and construction arguments.

Called during pickling when a promise (an instance of this class) is about to be be pickled. Returns the Promise class and construction arguments that will be evaluated during unpickling, namely the job store coordinates of a file that will hold the promised return value. By the time the promise is about to be unpickled, that file should be populated.

toil.cwl.cwltoil.Promised
toil.cwl.cwltoil.unwrap(p)

Function for ensuring you actually have a promised value, and not just a promise. Mostly useful for satisfying type-checking.

The “unwrap” terminology is borrowed from Rust.

Parameters:

p (Promised[T])

Return type:

T

class toil.cwl.cwltoil.AbstractJobStore(locator)

Bases: abc.ABC

Represents 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.Job objects 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, use toil.job.Job.loadJob() with a JobStore and the relevant JobDescription.

Parameters:

locator (str)

initialize(config)

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

writeConfig()
Return type:

None

write_config()

Persists the value of the AbstractJobStore.config attribute to the job store, so that it can be retrieved later by other instances of this class.

Return type:

None

resume()

Connect this instance to the physical storage it represents and load the Toil configuration into the AbstractJobStore.config attribute.

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:

toil.common.Config

property locator: str

Get the locator that defines the job store, which can be used to connect to it.

Return type:

str

rootJobStoreIDFileName = 'rootJobStoreID'
setRootJob(rootJobStoreID)

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)

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

loadRootJob()
Return type:

toil.job.JobDescription

load_root_job()

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:

toil.job.JobDescription

createRootJob(desc)
Parameters:

desc (toil.job.JobDescription)

Return type:

toil.job.JobDescription

create_root_job(job_description)

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:

toil.job.JobDescription

getRootJobReturnValue()
Return type:

Any

get_root_job_return_value()

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

Raises FileNotFoundError if the file does not exist.

Parameters:
  • src_uri (str) – URL that points to a file or object in the storage mechanism of a supported URL scheme e.g. a blob in an AWS s3 bucket. It must be a file, not a directory or prefix.

  • shared_file_name (str) – Optional name to assign to the imported file within the job store

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)
Parameters:
Return type:

None

export_file(file_id, dst_uri)

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.

Parameters:
  • file_id (str) – The id of the file in the job store that should be exported.

  • dst_uri (str) – URL that points to a file or object in the storage mechanism of a supported URL scheme e.g. a blob in an AWS s3 bucket.

Return type:

None

classmethod url_exists(src_uri)

Return True if the file at the given URI exists, and False otherwise.

Parameters:

src_uri (str) – URL that points to a file or object in the storage mechanism of a supported URL scheme e.g. a blob in an AWS s3 bucket.

Return type:

bool

classmethod get_size(src_uri)

Get the size in bytes of the file at the given URL, or None if it cannot be obtained.

Parameters:

src_uri (str) – URL that points to a file or object in the storage mechanism of a supported URL scheme e.g. a blob in an AWS s3 bucket.

Return type:

Optional[int]

classmethod get_is_directory(src_uri)

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 ‘/’.

Parameters:

src_uri (str)

Return type:

bool

classmethod list_url(src_uri)

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:

Parameters:

src_uri (str) – URL that points to a directory or prefix in the storage mechanism of a supported URL scheme e.g. a prefix in an AWS s3 bucket.

Returns:

A list of URL components in the given directory, already URL-encoded.

Return type:

List[str]

classmethod read_from_url(src_uri, writable)

Read the given URL and write its content into the given writable stream.

Raises FileNotFoundError if the URL doesn’t exist.

Returns:

The size of the file in bytes and whether the executable permission bit is set

Parameters:
Return type:

Tuple[int, bool]

classmethod open_url(src_uri)

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.

Parameters:

src_uri (str)

Return type:

IO[bytes]

abstract destroy()

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

getEnv()
Return type:

Dict[str, str]

get_env()

Returns a dictionary of environment variables that this job store requires to be set in order to function properly on a worker.

Return type:

dict[str,str]

clean(jobCache=None)

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:

toil.job.JobDescription

assignID(jobDescription)
Parameters:

jobDescription (toil.job.JobDescription)

Return type:

None

abstract assign_job_id(job_description)

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

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

jobDescription (toil.job.JobDescription)

Return type:

toil.job.JobDescription

abstract create_job(job_description)

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:

toil.job.JobDescription

Parameters:

job_description (toil.job.JobDescription)

exists(jobStoreID)
Parameters:

jobStoreID (str)

Return type:

bool

abstract job_exists(job_id)

Indicates whether a description of the job with the specified jobStoreID exists in the job store

Return type:

bool

Parameters:

job_id (str)

publicUrlExpiration
getPublicUrl(fileName)
Parameters:

fileName (str)

Return type:

str

abstract get_public_url(file_name)

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:

str

getSharedPublicUrl(sharedFileName)
Parameters:

sharedFileName (str)

Return type:

str

abstract get_shared_public_url(shared_file_name)

Differs from getPublicUrl() in that this method is for generating URLs for shared files written by writeSharedFileStream().

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:

str

load(jobStoreID)
Parameters:

jobStoreID (str)

Return type:

toil.job.JobDescription

abstract load_job(job_id)

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:

toil.job.JobDescription

update(jobDescription)
Parameters:

jobDescription (toil.job.JobDescription)

Return type:

None

abstract update_job(job_description)

Persists changes to the state of the given JobDescription in this store atomically.

Must call jobDescription.pre_update_hook()

Parameters:
Return type:

None

delete(jobStoreID)
Parameters:

jobStoreID (str)

Return type:

None

abstract delete_job(job_id)

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

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]

writeFile(localFilePath, jobStoreID=None, cleanup=False)
Parameters:
  • localFilePath (str)

  • jobStoreID (Optional[str])

  • cleanup (bool)

Return type:

str

abstract write_file(local_path, job_id=None, cleanup=False)

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:
Return type:

str

FIXME: some implementations may not raise this

Returns:

an ID referencing the newly created file and can be used to read the file in the future.

Return type:

str

Parameters:
  • local_path (str)

  • job_id (Optional[str])

  • cleanup (bool)

writeFileStream(jobStoreID=None, cleanup=False, basename=None, encoding=None, errors=None)
Parameters:
  • jobStoreID (Optional[str])

  • cleanup (bool)

  • basename (Optional[str])

  • encoding (Optional[str])

  • errors (Optional[str])

Return type:

ContextManager[Tuple[IO[bytes], str]]

abstract write_file_stream(job_id=None, cleanup=False, basename=None, encoding=None, errors=None)

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:
Return type:

Iterator[Tuple[IO[bytes], str]]

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:

Iterator[Tuple[IO[bytes], str]]

Parameters:
  • job_id (Optional[str])

  • cleanup (bool)

  • basename (Optional[str])

  • encoding (Optional[str])

  • errors (Optional[str])

getEmptyFileStoreID(jobStoreID=None, cleanup=False, basename=None)
Parameters:
  • jobStoreID (Optional[str])

  • cleanup (bool)

  • basename (Optional[str])

Return type:

str

abstract get_empty_file_store_id(job_id=None, cleanup=False, basename=None)

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:

str

readFile(jobStoreFileID, localFilePath, symlink=False)
Parameters:
  • jobStoreFileID (str)

  • localFilePath (str)

  • symlink (bool)

Return type:

None

abstract read_file(file_id, local_path, symlink=False)

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

readFileStream(jobStoreFileID, encoding=None, errors=None)
Parameters:
  • jobStoreFileID (str)

  • encoding (Optional[str])

  • errors (Optional[str])

Return type:

Union[ContextManager[IO[bytes]], ContextManager[IO[str]]]

read_file_stream(file_id: toil.fileStores.FileID | str, encoding: Literal[None] = None, errors: str | None = None) ContextManager[IO[bytes]]
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:

Iterator[Union[IO[bytes], IO[str]]]

deleteFile(jobStoreFileID)
Parameters:

jobStoreFileID (str)

Return type:

None

abstract delete_file(file_id)

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

fileExists(jobStoreFileID)

Determine whether a file exists in this job store.

Parameters:

jobStoreFileID (str)

Return type:

bool

abstract file_exists(file_id)

Determine whether a file exists in this job store.

Parameters:

file_id (str) – an ID referencing the file to be checked

Return type:

bool

getFileSize(jobStoreFileID)

Get the size of the given file in bytes.

Parameters:

jobStoreFileID (str)

Return type:

int

abstract get_file_size(file_id)

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.

Parameters:

file_id (str) – an ID referencing the file to be checked

Return type:

int

updateFile(jobStoreFileID, localFilePath)

Replaces the existing version of a file in the job store.

Parameters:
  • jobStoreFileID (str)

  • localFilePath (str)

Return type:

None

abstract update_file(file_id, local_path)

Replaces the existing version of a file in the job store.

Throws an exception if the file does not exist.

Parameters:
  • file_id (str) – the ID of the file in the job store to be updated

  • local_path (str) – the local path to a file that will overwrite the current version in the job store

Raises:
Return type:

None

updateFileStream(jobStoreFileID, encoding=None, errors=None)
Parameters:
  • jobStoreFileID (str)

  • encoding (Optional[str])

  • errors (Optional[str])

Return type:

ContextManager[IO[Any]]

abstract update_file_stream(file_id, encoding=None, errors=None)

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:
Return type:

Iterator[IO[Any]]

sharedFileNameRegex
writeSharedFileStream(sharedFileName, isProtected=None, encoding=None, errors=None)
Parameters:
  • sharedFileName (str)

  • isProtected (Optional[bool])

  • encoding (Optional[str])

  • errors (Optional[str])

Return type:

ContextManager[IO[bytes]]

abstract write_shared_file_stream(shared_file_name, encrypted=None, encoding=None, errors=None)

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]]

readSharedFileStream(sharedFileName, encoding=None, errors=None)
Parameters:
  • sharedFileName (str)

  • encoding (Optional[str])

  • errors (Optional[str])

Return type:

ContextManager[IO[bytes]]

abstract read_shared_file_stream(shared_file_name, encoding=None, errors=None)

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

statsAndLoggingString (str)

Return type:

None

abstract write_logs(msg)

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

readStatsAndLogging(callback, readAll=False)
Parameters:
  • callback (Callable[Ellipsis, Any])

  • readAll (bool)

Return type:

int

abstract read_logs(callback, read_all=False)

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:

int

write_leader_pid()

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

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:

int

write_leader_node_id()

Write the leader node id to the job store. This should only be called by the leader.

Return type:

None

read_leader_node_id()

Read the leader node id stored in the job store.

Raises:

NoSuchFileException – If the node ID file doesn’t exist.

Return type:

str

write_kill_flag(kill=False)

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

Read the kill flag from the job store, and return True if the leader has been killed. False otherwise.

Return type:

bool

default_caching()

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:

bool

exception toil.cwl.cwltoil.NoSuchFileException(jobStoreFileID, customName=None, *extra)

Bases: Exception

Indicates that the specified file does not exist.

Parameters:
exception toil.cwl.cwltoil.LocatorException(error_msg, locator, prefix=None)

Bases: Exception

Base exception class for all locator exceptions. For example, job store/aws bucket exceptions where they already exist

Parameters:
  • error_msg (str)

  • locator (str)

  • prefix (Optional[str])

exception toil.cwl.cwltoil.InvalidImportExportUrlException(url)

Bases: Exception

Common base class for all non-exit exceptions.

Parameters:

url (urllib.parse.ParseResult)

exception toil.cwl.cwltoil.UnimplementedURLException(url, operation)

Bases: RuntimeError

Unspecified run-time error.

Parameters:
class toil.cwl.cwltoil.FileJobStore(path, fanOut=1000)

Bases: toil.jobStores.abstractJobStore.AbstractJobStore

A job store that uses a directory on a locally attached file system. To be compatible with distributed batch systems, that file system must be shared by all worker nodes.

Parameters:
validDirs = 'abcdefghijklmnopqrstuvwxyz0123456789'
validDirsSet
JOB_DIR_PREFIX = 'instance-'
JOB_NAME_DIR_PREFIX = 'kind-'
BUFFER_SIZE = 10485760
default_caching()

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:

bool

__repr__()

Return repr(self).

initialize(config)

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 – 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

resume()

Connect this instance to the physical storage it represents and load the Toil configuration into the AbstractJobStore.config attribute.

Raises:

NoSuchJobStoreException – if the physical storage for this job store doesn’t exist

destroy()

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.

assign_job_id(job_description)

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

create_job(job_description)

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:

toil.job.JobDescription

batch()

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.

job_exists(job_id)

Indicates whether a description of the job with the specified jobStoreID exists in the job store

Return type:

bool

get_public_url(jobStoreFileID)

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:

str

get_shared_public_url(sharedFileName)

Differs from getPublicUrl() in that this method is for generating URLs for shared files written by writeSharedFileStream().

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:

str

load_job(job_id)

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 – the ID of the job to load

Raises:

NoSuchJobException – if there is no job with the given ID

update_job(job)

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

delete_job(job_id)

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

jobs()

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]

optional_hard_copy(hardlink)
write_file(local_path, job_id=None, cleanup=False)

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:

FIXME: some implementations may not raise this

Returns:

an ID referencing the newly created file and can be used to read the file in the future.

Return type:

str

write_file_stream(job_id=None, cleanup=False, basename=None, encoding=None, errors=None)

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:

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:

Iterator[Tuple[IO[bytes], str]]

get_empty_file_store_id(jobStoreID=None, cleanup=False, basename=None)

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:

str

update_file(file_id, local_path)

Replaces the existing version of a file in the job store.

Throws an exception if the file does not exist.

Parameters:
  • file_id – the ID of the file in the job store to be updated

  • local_path – the local path to a file that will overwrite the current version in the job store

Raises:
read_file(file_id, local_path, symlink=False)

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

delete_file(file_id)

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

file_exists(file_id)

Determine whether a file exists in this job store.

Parameters:

file_id – an ID referencing the file to be checked

get_file_size(file_id)

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.

Parameters:

file_id (str) – an ID referencing the file to be checked

Return type:

int

update_file_stream(file_id, encoding=None, errors=None)

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:
read_file_stream(file_id: str | toil.fileStores.FileID, encoding: Literal[None] = None, errors: str | None = None) Iterator[IO[bytes]]
read_file_stream(file_id: str | toil.fileStores.FileID, encoding: str, errors: str | None = None) Iterator[IO[str]]
read_file_stream(file_id: str | toil.fileStores.FileID, encoding: str | None = None, errors: str | None = None) Iterator[IO[bytes]] | Iterator[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:

Iterator[Union[IO[bytes], IO[str]]]

write_shared_file_stream(shared_file_name, encrypted=None, encoding=None, errors=None)

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]]

read_shared_file_stream(shared_file_name, encoding=None, errors=None)

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]]

list_all_file_names(for_job=None)

Get all the file names (not file IDs) of files stored in the job store.

Used for debugging.

Parameters:

for_job (Optional[str]) – If set, restrict the list to files for a particular job.

Return type:

Iterable[str]

write_logs(msg)

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

read_logs(callback, read_all=False)

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:

int

exception toil.cwl.cwltoil.JobStoreUnavailableException

Bases: RuntimeError

Raised when a particular type of job store is requested but can’t be used.

toil.cwl.cwltoil.generate_locator(job_store_type, local_suggestion=None, decoration=None)

Generate a random locator for a job store of the given type. Raises an JobStoreUnavailableException if that job store cannot be used.

Parameters:
  • job_store_type (str) – Registry name of the job store to use.

  • local_suggestion (Optional[str]) – Path to a nonexistent local directory suitable for use as a file job store.

  • decoration (Optional[str]) – Extra string to add to the job store locator, if convenient.

Return str:

Job store locator for a usable job store.

Return type:

str

toil.cwl.cwltoil.mkdtemp(suffix=None, prefix=None, dir=None)

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.

Parameters:
  • suffix (Optional[str])

  • prefix (Optional[str])

  • dir (Optional[str])

Return type:

str

class toil.cwl.cwltoil.ExceptionalThread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)

Bases: threading.Thread

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

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

>>> def f():
...     assert 0
>>> t = ExceptionalThread(target=f)
>>> t.start()
>>> t.join()
Traceback (most recent call last):
...
AssertionError
>>> class MyThread(ExceptionalThread):
...     def tryRun( self ):
...         assert 0
>>> t = MyThread()
>>> t.start()
>>> t.join()
Traceback (most recent call last):
...
AssertionError
exc_info = None
run()

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

Return type:

None

tryRun()
Return type:

None

join(*args, **kwargs)

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

Parameters:
Return type:

None

toil.cwl.cwltoil.DEFAULT_LOGLEVEL
toil.cwl.cwltoil.logger
toil.cwl.cwltoil.DEFAULT_TMPDIR
toil.cwl.cwltoil.DEFAULT_TMPDIR_PREFIX
toil.cwl.cwltoil.cwltoil_was_removed()

Complain about deprecated entrypoint.

Return type:

None

class toil.cwl.cwltoil.UnresolvedDict

Bases: Dict[Any, Any]

Tag to indicate a dict contains promises that must be resolved.

class toil.cwl.cwltoil.SkipNull

Internal sentinel object.

Indicates a null value produced by each port of a skipped conditional step. The CWL 1.2 specification calls for treating this the exactly the same as a null value.

toil.cwl.cwltoil.filter_skip_null(name, value)

Recursively filter out SkipNull objects from ‘value’.

Parameters:
  • name (str) – Name of port producing this value. Only used when we find an unhandled null from a conditional step and we print out a warning. The name allows the user to better localize which step/port was responsible for the unhandled null.

  • value (Any) – port output value object

Return type:

Any

toil.cwl.cwltoil.ensure_no_collisions(directory, dir_description=None)

Make sure no items in the given CWL Directory have the same name.

If any do, raise a WorkflowException about a “File staging conflict”.

Does not recurse into subdirectories.

Parameters:
  • directory (cwltool.utils.DirectoryType)

  • dir_description (Optional[str])

Return type:

None

class toil.cwl.cwltoil.Conditional(expression=None, outputs=None, requirements=None, container_engine='docker')

Object holding conditional expression until we are ready to evaluate it.

Evaluation occurs at the moment the encloses step is ready to run.

Parameters:
  • expression (Optional[str])

  • outputs (Union[Dict[str, cwltool.utils.CWLOutputType], None])

  • requirements (Optional[List[cwltool.utils.CWLObjectType]])

  • container_engine (str)

is_false(job)

Determine if expression evaluates to False given completed step inputs.

Parameters:

job (cwltool.utils.CWLObjectType) – job output object

Returns:

bool

Return type:

bool

skipped_outputs()

Generate a dict of SkipNull objects corresponding to the output structure.

Return type:

Dict[str, SkipNull]

class toil.cwl.cwltoil.ResolveSource(name, input, source_key, promises)

Apply linkMerge and pickValue operators to values coming into a port.

Parameters:
promise_tuples: List[Tuple[str, toil.job.Promise]] | Tuple[str, toil.job.Promise]
__repr__()

Allow for debug printing.

Return type:

str

resolve()

First apply linkMerge then pickValue if either present.

Return type:

Any

Apply linkMerge operator to values object.

Parameters:

values (cwltool.utils.CWLObjectType) – result of step

Return type:

Union[List[cwltool.utils.CWLOutputType], cwltool.utils.CWLOutputType]

pick_value(values)

Apply pickValue operator to values object.

Parameters:

values (Union[List[Union[str, SkipNull]], Any]) – Intended to be a list, but other types will be returned without modification.

Returns:

Return type:

Any

class toil.cwl.cwltoil.StepValueFrom(expr, source, req, container_engine)

A workflow step input which has a valueFrom expression attached to it.

The valueFrom expression will be evaluated to produce the actual input object for the step.

Parameters:
  • expr (str)

  • source (Any)

  • req (List[cwltool.utils.CWLObjectType])

  • container_engine (str)

__repr__()

Allow for debug printing.

Return type:

str

eval_prep(step_inputs, file_store)

Resolve the contents of any file in a set of inputs.

The inputs must be associated with the StepValueFrom object’s self.source.

Called when loadContents is specified.

Parameters:
Return type:

None

resolve()

Resolve the promise in the valueFrom expression’s context.

Returns:

object that will serve as expression context

Return type:

Any

do_eval(inputs)

Evaluate the valueFrom expression with the given input object.

Parameters:

inputs (cwltool.utils.CWLObjectType)

Returns:

object

Return type:

Any

class toil.cwl.cwltoil.DefaultWithSource(default, source)

A workflow step input that has both a source and a default value.

Parameters:
  • default (Any)

  • source (Any)

__repr__()

Allow for debug printing.

Return type:

str

resolve()

Determine the final input value when the time is right.

(when the source can be resolved)

Returns:

dict

Return type:

Any

class toil.cwl.cwltoil.JustAValue(val)

A simple value masquerading as a ‘resolve’-able object.

Parameters:

val (Any)

__repr__()

Allow for debug printing.

Return type:

str

resolve()

Return the value.

Return type:

Any

toil.cwl.cwltoil.resolve_dict_w_promises(dict_w_promises, file_store=None)

Resolve a dictionary of promises evaluate expressions to produce the actual values.

Parameters:
Returns:

dictionary of actual values

Return type:

cwltool.utils.CWLObjectType

toil.cwl.cwltoil.simplify_list(maybe_list)

Turn a length one list loaded by cwltool into a scalar.

Anything else is passed as-is, by reference.

Parameters:

maybe_list (Any)

Return type:

Any

class toil.cwl.cwltoil.ToilPathMapper(referenced_files, basedir, stagedir, separateDirs=True, get_file=None, stage_listing=False, streaming_allowed=True)

Bases: cwltool.pathmapper.PathMapper

Keeps track of files in a Toil way.

Maps between the symbolic identifier of a file (the Toil FileID), its local path on the host (the value returned by readGlobalFile) and the location of the file inside the software container.

Parameters:
  • referenced_files (List[cwltool.utils.CWLObjectType])

  • basedir (str)

  • stagedir (str)

  • separateDirs (bool)

  • get_file (Union[Any, None])

  • stage_listing (bool)

  • streaming_allowed (bool)

visit(obj, stagedir, basedir, copy=False, staged=False)

Iterate over a CWL object, resolving File and Directory path references.

This is called on each File or Directory CWL object. The Files and Directories all have “location” fields. For the Files, these are from upload_file(), and for the Directories, these are from upload_directory() or cwltool internally. With upload_directory(), they and their children will be assigned locations based on listing the Directories using ToilFsAccess. With cwltool, locations will be set as absolute paths.

Parameters:
  • obj (cwltool.utils.CWLObjectType) – The CWL File or Directory to process

  • stagedir (str) – The base path for target paths to be generated under, except when a File or Directory has an overriding parent directory in dirname

  • basedir (str) – The directory from which relative paths should be resolved; used as the base directory for the StdFsAccess that generated the listing being processed.

  • copy (bool) – If set, use writable types for Files and Directories.

  • staged (bool) – Starts as True at the top of the recursion. Set to False when entering a directory that we can actually download, so we don’t stage files and subdirectories separately from the directory as a whole. Controls the staged flag on generated mappings, and therefore whether files and directories are actually placed at their mapped-to target locations. If stage_listing is True, we will leave this True throughout and stage everything.

Return type:

None

Produces one MapperEnt for every unique location for a File or Directory. These MapperEnt objects are instructions to cwltool’s stage_files function: https://github.com/common-workflow-language/cwltool/blob/a3e3a5720f7b0131fa4f9c0b3f73b62a347278a6/cwltool/process.py#L254

The MapperEnt has fields:

resolved: An absolute local path anywhere on the filesystem where the file/directory can be found, or the contents of a file to populate it with if type is CreateWritableFile or CreateFile. Or, a URI understood by the StdFsAccess in use (for example, toilfile:).

target: An absolute path under stagedir that the file or directory will then be placed at by cwltool. Except if a File or Directory has a dirname field, giving its parent path, that is used instead.

type: One of:

File: cwltool will copy or link the file from resolved to target, if possible.

CreateFile: cwltool will create the file at target, treating resolved as the contents.

WritableFile: cwltool will copy the file from resolved to target, making it writable.

CreateWritableFile: cwltool will create the file at target, treating resolved as the contents, and make it writable.

Directory: cwltool will copy or link the directory from resolved to target, if possible. Otherwise, cwltool will make the directory at target if resolved starts with “_:”. Otherwise it will do nothing.

WritableDirectory: cwltool will copy the directory from resolved to target, if possible. Otherwise, cwltool will make the directory at target if resolved starts with “_:”. Otherwise it will do nothing.

staged: if set to False, cwltool will not make or copy anything for this entry

class toil.cwl.cwltoil.ToilSingleJobExecutor

Bases: cwltool.executors.SingleJobExecutor

A SingleJobExecutor that does not assume it is at the top level of the workflow.

We need this because otherwise every job thinks it is top level and tries to discover secondary files, which may exist when they haven’t actually been passed at the top level and thus aren’t supposed to be visible.

run_jobs(process, job_order_object, logger, runtime_context)

run_jobs from SingleJobExecutor, but not in a top level runtime context.

Parameters:
Return type:

None

class toil.cwl.cwltoil.ToilTool(*args, **kwargs)

Mixin to hook Toil into a cwltool tool type.

Parameters:
  • args (Any)

  • kwargs (Any)

connect_toil_job(job)

Attach the Toil tool to the Toil job that is executing it. This allows it to use the Toil job to stop at certain points if debugging flags are set.

Parameters:

job (toil.job.Job)

Return type:

None

make_path_mapper(reffiles, stagedir, runtimeContext, separateDirs)

Create the appropriate PathMapper for the situation.

Parameters:
Return type:

cwltool.pathmapper.PathMapper

__str__()

Return string representation of this tool type.

Return type:

str

class toil.cwl.cwltoil.ToilCommandLineTool(*args, **kwargs)

Bases: ToilTool, cwltool.command_line_tool.CommandLineTool

Subclass the cwltool command line tool to provide the custom ToilPathMapper.

Parameters:
  • args (Any)

  • kwargs (Any)

class toil.cwl.cwltoil.ToilExpressionTool(*args, **kwargs)

Bases: ToilTool, cwltool.command_line_tool.ExpressionTool

Subclass the cwltool expression tool to provide the custom ToilPathMapper.

Parameters:
  • args (Any)

  • kwargs (Any)

toil.cwl.cwltoil.toil_make_tool(toolpath_object, loadingContext)

Emit custom ToilCommandLineTools.

This factory function is meant to be passed to cwltool.load_tool().

Parameters:
Return type:

cwltool.process.Process

toil.cwl.cwltoil.MISSING_FILE = 'missing://'
toil.cwl.cwltoil.DirectoryContents
toil.cwl.cwltoil.check_directory_dict_invariants(contents)

Make sure a directory structure dict makes sense. Throws an error otherwise.

Currently just checks to make sure no empty-string keys exist.

Parameters:

contents (DirectoryContents)

Return type:

None

toil.cwl.cwltoil.decode_directory(dir_path)

Decode a directory from a “toildir:” path to a directory (or a file in it).

Returns the decoded directory dict, the remaining part of the path (which may be None), and the deduplication key string that uniquely identifies the directory.

Parameters:

dir_path (str)

Return type:

Tuple[DirectoryContents, Optional[str], str]

toil.cwl.cwltoil.encode_directory(contents)

Encode a directory from a “toildir:” path to a directory (or a file in it).

Takes the directory dict, which is a dict from name to URI for a file or dict for a subdirectory.

Parameters:

contents (DirectoryContents)

Return type:

str

class toil.cwl.cwltoil.ToilFsAccess(basedir, file_store=None)

Bases: cwltool.stdfsaccess.StdFsAccess

Custom filesystem access class which handles toil filestore references.

Normal file paths will be resolved relative to basedir, but ‘toilfile:’ and ‘toildir:’ URIs will be fulfilled from the Toil file store.

Also supports URLs supported by Toil job store implementations.

Parameters:
glob(pattern)
Parameters:

pattern (str)

Return type:

List[str]

open(fn, mode)
Parameters:
Return type:

IO[Any]

exists(path)

Test for file existence.

Parameters:

path (str)

Return type:

bool

size(path)
Parameters:

path (str)

Return type:

int

isfile(fn)
Parameters:

fn (str)

Return type:

bool

isdir(fn)
Parameters:

fn (str)

Return type:

bool

listdir(fn)
Parameters:

fn (str)

Return type:

List[str]

join(path, *paths)
Parameters:
Return type:

str

realpath(fn)
Parameters:

fn (str)

Return type:

str

toil.cwl.cwltoil.toil_get_file(file_store, index, existing, uri, streamable=False, streaming_allowed=True, pipe_threads=None)

Set up the given file or directory from the Toil jobstore at a file URI where it can be accessed locally.

Run as part of the tool setup, inside jobs on the workers. Also used as part of reorganizing files to get them uploaded at the end of a tool.

Parameters:
  • file_store (toil.fileStores.abstractFileStore.AbstractFileStore) – The Toil file store to download from.

  • index (Dict[str, str]) – Maps from downloaded file path back to input Toil URI.

  • existing (Dict[str, str]) – Maps from URI to downloaded file path.

  • uri (str) – The URI for the file to download.

  • streamable (bool) – If the file is has ‘streamable’ flag set

  • streaming_allowed (bool) – If streaming is allowed

  • pipe_threads (Optional[List[Tuple[threading.Thread, int]]]) – List of threads responsible for streaming the data and open file descriptors corresponding to those files. Caller is responsible to close the file descriptors (to break the pipes) and join the threads

Return type:

str

toil.cwl.cwltoil.write_file(writeFunc, index, existing, file_uri)

Write a file into the Toil jobstore.

‘existing’ is a set of files retrieved as inputs from toil_get_file. This ensures they are mapped back as the same name if passed through.

Returns a toil uri path to the object.

Parameters:
Return type:

str

toil.cwl.cwltoil.path_to_loc(obj)

Make a path into a location.

(If a CWL object has a “path” and not a “location”)

Parameters:

obj (cwltool.utils.CWLObjectType)

Return type:

None

toil.cwl.cwltoil.import_files(import_function, fs_access, fileindex, existing, cwl_object, mark_broken=False, skip_remote=False, bypass_file_store=False, log_level=logging.DEBUG)

Prepare all files and directories.

Will be executed from the leader or worker in the context of the given CWL tool, order, or output object to be used on the workers. Make sure their sizes are set and import all the files.

Recurses inside directories using the fs_access to find files to upload and subdirectory structure to encode, even if their listings are not set or not recursive.

Preserves any listing fields.

If a file cannot be found (like if it is an optional secondary file that doesn’t exist), fails, unless mark_broken is set, in which case it applies a sentinel location.

Also does some miscellaneous normalization.

Parameters:
  • import_function (Callable[[str], toil.fileStores.FileID]) – The function used to upload a URI and get a Toil FileID for it.

  • fs_access (cwltool.stdfsaccess.StdFsAccess) – the CWL FS access object we use to access the filesystem to find files to import. Needs to support the URI schemes used.

  • fileindex (Dict[str, str]) – Forward map to fill in from file URI to Toil storage location, used by write_file to deduplicate writes.

  • existing (Dict[str, str]) – Reverse map to fill in from Toil storage location to file URI. Not read from.

  • cwl_object (Optional[cwltool.utils.CWLObjectType]) – CWL tool (or workflow order) we are importing files for

  • mark_broken (bool) – If True, when files can’t be imported because they e.g. don’t exist, set their locations to MISSING_FILE rather than failing with an error.

  • skp_remote – If True, leave remote URIs in place instead of importing files.

  • bypass_file_store (bool) – If True, leave file:// URIs in place instead of importing files and directories.

  • log_level (int) – Log imported files at the given level.

  • skip_remote (bool)

Return type:

None

toil.cwl.cwltoil.upload_directory(directory_metadata, directory_contents, mark_broken=False)

Upload a Directory object.

Ignores the listing (which may not be recursive and isn’t safe or efficient to touch), and instead uses directory_contents, which is a recursive dict structure from filename to file URI or subdirectory contents dict.

Makes sure the directory actually exists, and rewrites its location to be something we can use on another machine.

If mark_broken is set, ignores missing directories and replaces them with directories containing the given (possibly empty) contents.

We can’t rely on the directory’s listing as visible to the next tool as a complete recursive description of the files we will need to present to the tool, since some tools require it to be cleared or single-level but still expect to see its contents in the filesystem.

Parameters:
  • directory_metadata (cwltool.utils.CWLObjectType)

  • directory_contents (DirectoryContents)

  • mark_broken (bool)

Return type:

None

toil.cwl.cwltoil.upload_file(uploadfunc, fileindex, existing, file_metadata, mark_broken=False, skip_remote=False)

Update a file object so that the file will be accessible from another machine.

Uploads local files to the Toil file store, and sets their location to a reference to the toil file store.

If a file doesn’t exist, fails with an error, unless mark_broken is set, in which case the missing file is given a special sentinel location.

Unless skip_remote is set, downloads remote files into the file store and sets their locations to references into the file store as well.

Parameters:
Return type:

None

toil.cwl.cwltoil.writeGlobalFileWrapper(file_store, fileuri)

Wrap writeGlobalFile to accept file:// URIs.

Parameters:
Return type:

toil.fileStores.FileID

toil.cwl.cwltoil.remove_empty_listings(rec)
Parameters:

rec (cwltool.utils.CWLObjectType)

Return type:

None

class toil.cwl.cwltoil.CWLNamedJob(cores=1, memory='1GiB', disk='1MiB', accelerators=None, preemptible=None, tool_id=None, parent_name=None, subjob_name=None, local=None)

Bases: toil.job.Job

Base class for all CWL jobs that do user work, to give them useful names.

Parameters:
class toil.cwl.cwltoil.ResolveIndirect(cwljob, parent_name=None)

Bases: CWLNamedJob

Helper Job.

Accepts an unresolved dict (containing promises) and produces a dictionary of actual values.

Parameters:
  • cwljob (toil.job.Promised[cwltool.utils.CWLObjectType])

  • parent_name (Optional[str])

run(file_store)

Evaluate the promises and return their values.

Parameters:

file_store (toil.fileStores.abstractFileStore.AbstractFileStore)

Return type:

cwltool.utils.CWLObjectType

toil.cwl.cwltoil.toilStageFiles(toil, cwljob, outdir, destBucket=None, log_level=logging.DEBUG)

Copy input files out of the global file store and update location and path.

Parameters:
  • destBucket (Union[str, None]) – If set, export to this base URL instead of to the local filesystem.

  • log_level (int) – Log each file transferred at the given level.

  • toil (toil.common.Toil)

  • cwljob (Union[cwltool.utils.CWLObjectType, List[cwltool.utils.CWLObjectType]])

  • outdir (str)

Return type:

None

class toil.cwl.cwltoil.CWLJobWrapper(tool, cwljob, runtime_context, parent_name, conditional=None)

Bases: CWLNamedJob

Wrap a CWL job that uses dynamic resources requirement.

When executed, this creates a new child job which has the correct resource requirement set.

Parameters:
run(file_store)

Create a child job with the correct resource requirements set.

Parameters:

file_store (toil.fileStores.abstractFileStore.AbstractFileStore)

Return type:

Any

class toil.cwl.cwltoil.CWLJob(tool, cwljob, runtime_context, parent_name=None, conditional=None)

Bases: CWLNamedJob

Execute a CWL tool using cwltool.executors.SingleJobExecutor.

Parameters:
required_env_vars(cwljob)

Yield environment variables from EnvVarRequirement.

Parameters:

cwljob (Any)

Return type:

Iterator[Tuple[str, str]]

populate_env_vars(cwljob)

Prepare environment variables necessary at runtime for the job.

Env vars specified in the CWL “requirements” section should already be loaded in self.cwltool.requirements, however those specified with “EnvVarRequirement” take precedence and are only populated here. Therefore, this not only returns a dictionary with all evaluated “EnvVarRequirement” env vars, but checks self.cwltool.requirements for any env vars with the same name and replaces their value with that found in the “EnvVarRequirement” env var if it exists.

Parameters:

cwljob (cwltool.utils.CWLObjectType)

Return type:

Dict[str, str]

run(file_store)

Execute the CWL document.

Parameters:

file_store (toil.fileStores.abstractFileStore.AbstractFileStore)

Return type:

Any

toil.cwl.cwltoil.get_container_engine(runtime_context)
Parameters:

runtime_context (cwltool.context.RuntimeContext)

Return type:

str

toil.cwl.cwltoil.makeJob(tool, jobobj, runtime_context, parent_name, conditional)

Create the correct Toil Job object for the CWL tool.

Types: workflow, job, or job wrapper for dynamic resource requirements.

Returns:

“wfjob, followOn” if the input tool is a workflow, and “job, job” otherwise

Parameters:
Return type:

Union[Tuple[CWLWorkflow, ResolveIndirect], Tuple[CWLJob, CWLJob], Tuple[CWLJobWrapper, CWLJobWrapper]]

class toil.cwl.cwltoil.CWLScatter(step, cwljob, runtime_context, parent_name, conditional)

Bases: toil.job.Job

Implement workflow scatter step.

When run, this creates a child job for each parameterization of the scatter.

Parameters:
flat_crossproduct_scatter(joborder, scatter_keys, outputs, postScatterEval)

Cartesian product of the inputs, then flattened.

Parameters:
  • joborder (cwltool.utils.CWLObjectType)

  • scatter_keys (List[str])

  • outputs (List[toil.job.Promised[cwltool.utils.CWLObjectType]])

  • postScatterEval (Callable[[cwltool.utils.CWLObjectType], cwltool.utils.CWLObjectType])

Return type:

None

nested_crossproduct_scatter(joborder, scatter_keys, postScatterEval)

Cartesian product of the inputs.

Parameters:
  • joborder (cwltool.utils.CWLObjectType)

  • scatter_keys (List[str])

  • postScatterEval (Callable[[cwltool.utils.CWLObjectType], cwltool.utils.CWLObjectType])

Return type:

List[toil.job.Promised[cwltool.utils.CWLObjectType]]

run(file_store)

Generate the follow on scatter jobs.

Parameters:

file_store (toil.fileStores.abstractFileStore.AbstractFileStore)

Return type:

List[toil.job.Promised[cwltool.utils.CWLObjectType]]

class toil.cwl.cwltoil.CWLGather(step, outputs)

Bases: toil.job.Job

Follows on to a scatter Job.

This gathers the outputs of each job in the scatter into an array for each output parameter.

Parameters:
static extract(obj, k)

Extract the given key from the obj.

If the object is a list, extract it from all members of the list.

Parameters:
  • obj (Union[cwltool.utils.CWLObjectType, List[cwltool.utils.CWLObjectType]])

  • k (str)

Return type:

Union[cwltool.utils.CWLOutputType, List[cwltool.utils.CWLObjectType]]

run(file_store)

Gather all the outputs of the scatter.

Parameters:

file_store (toil.fileStores.abstractFileStore.AbstractFileStore)

Return type:

Dict[str, Any]

class toil.cwl.cwltoil.SelfJob(j, v)

Bases: toil.job.Job

Fake job object to facilitate implementation of CWLWorkflow.run().

Parameters:
rv(*path)

Return our properties dictionary.

Parameters:

path (Any)

Return type:

Any

addChild(c)

Add a child to our workflow.

Parameters:

c (toil.job.Job)

Return type:

Any

hasChild(c)

Check if the given child is in our workflow.

Parameters:

c (toil.job.Job)

Return type:

Any

toil.cwl.cwltoil.ProcessType
toil.cwl.cwltoil.remove_pickle_problems(obj)

Doc_loader does not pickle correctly, causing Toil errors, remove from objects.

Parameters:

obj (ProcessType)

Return type:

ProcessType

class toil.cwl.cwltoil.CWLWorkflow(cwlwf, cwljob, runtime_context, parent_name=None, conditional=None)

Bases: CWLNamedJob

Toil Job to convert a CWL workflow graph into a Toil job graph.

The Toil job graph will include the appropriate dependencies.

Parameters:
run(file_store)

Convert a CWL Workflow graph into a Toil job graph.

Always runs on the leader, because the batch system knows to schedule it as a local job.

Parameters:

file_store (toil.fileStores.abstractFileStore.AbstractFileStore)

Return type:

Union[UnresolvedDict, Dict[str, SkipNull]]

toil.cwl.cwltoil.visitSteps(cmdline_tool, op)

Iterate over a CWL Process object, running the op on each tool description CWL object.

Parameters:
Return type:

None

toil.cwl.cwltoil.rm_unprocessed_secondary_files(job_params)
Parameters:

job_params (Any)

Return type:

None

toil.cwl.cwltoil.filtered_secondary_files(unfiltered_secondary_files)

Remove unprocessed secondary files.

Interpolated strings and optional inputs in secondary files were added to CWL in version 1.1.

The CWL libraries we call do successfully resolve the interpolated strings, but add the resolved fields to the list of unresolved fields so we remove them here after the fact.

We keep secondary files with anything other than MISSING_FILE as their location. The ‘required’ logic seems to be handled deeper in cwltool.builder.Builder(), and correctly determines which files should be imported. Therefore we remove the files here and if this file is SUPPOSED to exist, it will still give the appropriate file does not exist error, but just a bit further down the track.

Parameters:

unfiltered_secondary_files (cwltool.utils.CWLObjectType)

Return type:

List[cwltool.utils.CWLObjectType]

toil.cwl.cwltoil.scan_for_unsupported_requirements(tool, bypass_file_store=False)

Scan the given CWL tool for any unsupported optional features.

If it has them, raise an informative UnsupportedRequirement.

Parameters:
  • tool (cwltool.process.Process) – The CWL tool to check for unsupported requirements.

  • bypass_file_store (bool) – True if the Toil file store is not being used to transport files between nodes, and raw origin node file:// URIs are exposed to tools instead.

Return type:

None

toil.cwl.cwltoil.determine_load_listing(tool)

Determine the directory.listing feature in CWL.

In CWL, any input directory can have a DIRECTORY_NAME.listing (where DIRECTORY_NAME is any variable name) set to one of the following three options:

  1. no_listing: DIRECTORY_NAME.listing will be undefined.

    e.g.

    inputs.DIRECTORY_NAME.listing == unspecified

  2. shallow_listing: DIRECTORY_NAME.listing will return a list one level

    deep of DIRECTORY_NAME’s contents. e.g.

    inputs.DIRECTORY_NAME.listing == [items in directory]

    inputs.DIRECTORY_NAME.listing[0].listing == undefined inputs.DIRECTORY_NAME.listing.length == # of items in directory

  3. deep_listing: DIRECTORY_NAME.listing will return a list of the entire

    contents of DIRECTORY_NAME. e.g.

    inputs.DIRECTORY_NAME.listing == [items in directory] inputs.DIRECTORY_NAME.listing[0].listing == [items in subdirectory if it exists and is the first item listed] inputs.DIRECTORY_NAME.listing.length == # of items in directory

See https://www.commonwl.org/v1.1/CommandLineTool.html#LoadListingRequirement and https://www.commonwl.org/v1.1/CommandLineTool.html#LoadListingEnum

DIRECTORY_NAME.listing should be determined first from loadListing. If that’s not specified, from LoadListingRequirement. Else, default to “no_listing” if unspecified.

Parameters:

tool (cwltool.process.Process) – ToilCommandLineTool

Return str:

One of ‘no_listing’, ‘shallow_listing’, or ‘deep_listing’.

Return type:

typing_extensions.Literal[no_listing, shallow_listing, deep_listing]

exception toil.cwl.cwltoil.NoAvailableJobStoreException

Bases: Exception

Indicates that no job store name is available.

toil.cwl.cwltoil.generate_default_job_store(batch_system_name, provisioner_name, local_directory)

Choose a default job store appropriate to the requested batch system and provisioner, and installed modules. Raises an error if no good default is available and the user must choose manually.

Parameters:
  • batch_system_name (Optional[str]) – Registry name of the batch system the user has requested, if any. If no name has been requested, should be None.

  • provisioner_name (Optional[str]) – Name of the provisioner the user has requested, if any. Recognized provisioners include ‘aws’ and ‘gce’. None indicates that no provisioner is in use.

  • local_directory (str) – Path to a nonexistent local directory suitable for use as a file job store.

Return str:

Job store specifier for a usable job store.

Return type:

str

toil.cwl.cwltoil.usage_message
toil.cwl.cwltoil.get_options(args)

Parse given args and properly add non-Toil arguments into the cwljob of the Namespace. :param args: List of args from command line :return: options namespace

Parameters:

args (List[str])

Return type:

configargparse.Namespace

toil.cwl.cwltoil.main(args=None, stdout=sys.stdout)

Run the main loop for toil-cwl-runner.

Parameters:
  • args (Optional[List[str]])

  • stdout (TextIO)

Return type:

int

toil.cwl.cwltoil.find_default_container(args, builder)

Find the default constructor by consulting a Toil.options object.

Parameters:
Return type:

Optional[str]