toil.test.jobStores.jobStoreTest

Attributes

memoize

Memoize a function result based on its parameters using this decorator.

logger

Exceptions

NoSuchFileException

Indicates that the specified file does not exist.

NoSuchJobException

Indicates that the specified job does not exist.

Classes

Config

Class to represent configuration operations for a toil workflow run.

Toil

A context manager that represents a Toil workflow.

FileID

A small wrapper around Python's builtin string class.

Job

Class represents a unit of work in toil.

JobDescription

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

TemporaryID

Placeholder for a unregistered job ID used by a JobDescription.

FileJobStore

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

StatsAndLogging

A thread to aggregate statistics and logging.

ToilTest

A common base class for Toil tests.

AbstractJobStoreTest

Hide abstract base class from unittest's test case loader

AbstractEncryptedJobStoreTest

FileJobStoreTest

A common base class for Toil tests.

GoogleJobStoreTest

A common base class for Toil tests.

AWSJobStoreTest

A common base class for Toil tests.

InvalidAWSJobStoreTest

A common base class for Toil tests.

EncryptedAWSJobStoreTest

A common base class for Toil tests.

StubHttpRequestHandler

Simple HTTP request handler with GET and HEAD commands.

Functions

mkdtemp([suffix, prefix, dir])

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

retry([intervals, infinite_retries, errors, ...])

Retry a function if it fails with any Exception defined in "errors".

make_tests(generalMethod, targetClass, **kwargs)

This method dynamically generates test methods using the generalMethod as a template. Each

needs_aws_s3(test_item)

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

needs_encryption(test_item)

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

needs_google_project(test_item)

Use as a decorator before test classes or methods to run only if we have a Google Cloud project set.

needs_google_storage(test_item)

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

slow(test_item)

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

google_retry(x)

tearDownModule()

Module Contents

class toil.test.jobStores.jobStoreTest.Config[source]

Class to represent configuration operations for a toil workflow run.

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

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

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

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

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

None

prepare_start()[source]

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

Return type:

None

prepare_restart()[source]

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

Return type:

None

setOptions(options)[source]

Creates a config object from the options object.

Parameters:

options (argparse.Namespace)

Return type:

None

check_configuration_consistency()[source]

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

Return type:

None

__eq__(other)[source]

Return self==value.

Parameters:

other (object)

Return type:

bool

__hash__()[source]

Return hash(self).

Return type:

int

class toil.test.jobStores.jobStoreTest.Toil(options)[source]

Bases: ContextManager[Toil]

A context manager that represents a Toil workflow.

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

Parameters:

options (argparse.Namespace)

config: Config
__enter__()[source]

Derive configuration from the command line options.

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

Return type:

Toil

__exit__(exc_type, exc_val, exc_tb)[source]

Clean up after a workflow invocation.

Depending on the configuration, delete the job store.

Parameters:
Return type:

Literal[False]

start(rootJob)[source]

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

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

Parameters:

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

Returns:

The root job’s return value

Return type:

Any

restart()[source]

Restarts a workflow that has been interrupted.

Returns:

The root job’s return value

Return type:

Any

classmethod getJobStore(locator)[source]

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

Parameters:

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

Returns:

an instance of a concrete subclass of AbstractJobStore

Return type:

toil.jobStores.abstractJobStore.AbstractJobStore

static parseLocator(locator)[source]
Parameters:

locator (str)

Return type:

Tuple[str, str]

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

str

classmethod resumeJobStore(locator)[source]
Parameters:

locator (str)

Return type:

toil.jobStores.abstractJobStore.AbstractJobStore

static createBatchSystem(config)[source]

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

Parameters:

config (Config) – the current configuration

Returns:

an instance of a concrete subclass of AbstractBatchSystem

Return type:

toil.batchSystems.abstractBatchSystem.AbstractBatchSystem

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

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

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

Parameters:

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

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

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

None

export_file(file_id, dst_uri)[source]

Export file to destination pointed at by the destination URL.

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

Parameters:
Return type:

None

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

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

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

  • uri (str)

Return type:

str

static getToilWorkDir(configWorkDir=None)[source]

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

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

Parameters:

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

Returns:

Path to the Toil work directory, constant across all machines

Return type:

str

classmethod get_toil_coordination_dir(config_work_dir, config_coordination_dir)[source]

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

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

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

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

Returns:

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

Return type:

str

static get_workflow_path_component(workflow_id)[source]

Get a safe filesystem path component for a workflow.

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

Parameters:

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

Return type:

str

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

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

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

  • workflowID (str)

Returns:

Path to the local workflow directory on this machine

Return type:

str

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

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

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

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

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

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

Returns:

Path to the local workflow coordination directory on this machine.

Return type:

str

class toil.test.jobStores.jobStoreTest.FileID(fileStoreID, size, executable=False)[source]

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()[source]

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

Return type:

str

classmethod forPath(fileStoreID, filePath)[source]
Parameters:
  • fileStoreID (str)

  • filePath (str)

Return type:

FileID

classmethod unpack(packedFileStoreID)[source]

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

Parameters:

packedFileStoreID (str)

Return type:

FileID

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

Class represents a unit of work in toil.

Parameters:
  • memory (Optional[ParseableIndivisibleResource])

  • cores (Optional[ParseableDivisibleResource])

  • disk (Optional[ParseableIndivisibleResource])

  • accelerators (Optional[ParseableAcceleratorRequirement])

  • preemptible (Optional[ParseableFlag])

  • preemptable (Optional[ParseableFlag])

  • unitName (Optional[str])

  • checkpoint (Optional[bool])

  • displayName (Optional[str])

  • descriptionClass (Optional[type])

  • local (Optional[bool])

__str__()[source]

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

check_initialized()[source]

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

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

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

Return type:

None

property jobStoreID: str | TemporaryID

Get the ID of this Job.

Return type:

Union[str, TemporaryID]

property description: JobDescription

Expose the JobDescription that describes this job.

Return type:

JobDescription

property disk: int

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

Return type:

int

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

The number of CPU cores required.

Return type:

Union[int, float]

property accelerators: List[AcceleratorRequirement]

Any accelerators, such as GPUs, that are needed.

Return type:

List[AcceleratorRequirement]

property preemptible: bool

Whether the job can be run on a preemptible node.

Return type:

bool

preemptable()[source]
property checkpoint: bool

Determine if the job is a checkpoint job or not.

Return type:

bool

assignConfig(config)[source]

Assign the given config object.

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

Parameters:

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

Return type:

None

run(fileStore)[source]

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

Parameters:

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

Returns:

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

Return type:

Any

addChild(childJob)[source]

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

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

Returns:

childJob: for call chaining

Parameters:

childJob (Job)

Return type:

Job

hasChild(childJob)[source]

Check if childJob is already a child of this job.

Returns:

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

Parameters:

childJob (Job)

Return type:

bool

addFollowOn(followOnJob)[source]

Add a follow-on job.

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

Returns:

followOnJob for call chaining

Parameters:

followOnJob (Job)

Return type:

Job

hasPredecessor(job)[source]

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

Parameters:

job (Job)

Return type:

bool

hasFollowOn(followOnJob)[source]

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

Returns:

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

Parameters:

followOnJob (Job)

Return type:

bool

addService(service, parentService=None)[source]

Add a service.

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

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

Raises:

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

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

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

Returns:

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

Return type:

Promise

hasService(service)[source]

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

Parameters:

service (Job)

Return type:

bool

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

Add a function as a child job.

Parameters:

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

Returns:

The new child job that wraps fn.

Return type:

FunctionWrappingJob

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

Add a function as a follow-on job.

Parameters:

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

Returns:

The new follow-on job that wraps fn.

Return type:

FunctionWrappingJob

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

Add a job function as a child job.

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

Parameters:

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

Returns:

The new child job that wraps fn.

Return type:

FunctionWrappingJob

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

Add a follow-on job function.

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

Parameters:

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

Returns:

The new follow-on job that wraps fn.

Return type:

FunctionWrappingJob

property tempDir: str

Shortcut to calling job.fileStore.getLocalTempDir().

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

Return type:

str

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

Log using fileStore.log_to_leader().

Parameters:

text (str)

Return type:

None

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

Makes a Job out of a function.

Convenience function for constructor of toil.job.FunctionWrappingJob.

Parameters:

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

Returns:

The new function that wraps fn.

Return type:

FunctionWrappingJob

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

Makes a Job out of a job function.

Convenience function for constructor of toil.job.JobFunctionWrappingJob.

Parameters:

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

Returns:

The new job function that wraps fn.

Return type:

JobFunctionWrappingJob

encapsulate(name=None)[source]

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

Parameters:

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

Returns:

an encapsulated version of this job.

Return type:

EncapsulatedJob

rv(*path)[source]

Create a promise (toil.job.Promise).

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

Parameters:

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

Returns:

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

Return type:

Promise

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

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

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

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

Parameters:

jobStore (toil.jobStores.abstractJobStore.AbstractJobStore)

Return type:

None

checkJobGraphForDeadlocks()[source]

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

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

Raises:

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

getRootJobs()[source]

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

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

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

Return type:

Set[Job]

checkJobGraphConnected()[source]
Raises:

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

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

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

checkJobGraphAcylic()[source]
Raises:

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

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

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

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

checkNewCheckpointsAreLeafVertices()[source]

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

A job is a leaf it is has no successors.

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

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

Raises:

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

Return type:

None

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

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

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

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

  • args (list) – The arguments to the function

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

Return type:

None

class Runner[source]

Used to setup and run Toil workflow.

static getDefaultArgumentParser(jobstore_as_flag=False)[source]

Get argument parser with added toil workflow options.

Parameters:

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

Returns:

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

Return type:

argparse.ArgumentParser

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

Get default options for a toil workflow.

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

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

Returns:

The options used by a toil workflow.

Return type:

argparse.Namespace

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

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

Parameters:
Return type:

None

static startToil(job, options)[source]

Run the toil workflow using the given options.

Deprecated by toil.common.Toil.start.

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

Parameters:

job (Job)

Return type:

Any

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

Bases: Requirer

Abstract class used to define the interface to a service.

Should be subclassed by the user to define services.

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

abstract start(job)[source]

Start the service.

Parameters:

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

Returns:

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

Return type:

Any

abstract stop(job)[source]

Stops the service. Function can block until complete.

Parameters:

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

Return type:

None

check()[source]

Checks the service is still running.

Raises:

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

Returns:

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

Return type:

bool

getUserScript()[source]
Return type:

toil.resource.ModuleDescriptor

getTopologicalOrderingOfJobs()[source]
Returns:

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

Return type:

List[Job]

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

Ignores service jobs.

saveBody(jobStore)[source]

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

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

Does not save the JobDescription.

Parameters:

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

Return type:

None

saveAsRootJob(jobStore)[source]

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

Returns:

the JobDescription describing this job.

Parameters:

jobStore (toil.jobStores.abstractJobStore.AbstractJobStore)

Return type:

JobDescription

classmethod loadJob(job_store, job_description)[source]

Retrieves a toil.job.Job instance from a JobStore

Parameters:
Returns:

The job referenced by the JobDescription.

Return type:

Job

set_debug_flag(flag)[source]

Enable the given debug option on the job.

Parameters:

flag (str)

Return type:

None

has_debug_flag(flag)[source]

Return true if the given debug flag is set.

Parameters:

flag (str)

Return type:

bool

files_downloaded_hook(host_and_job_paths=None)[source]

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

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

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

Parameters:

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

Return type:

None

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

Bases: Requirer

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

This includes:
  • Resource requirements.

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

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

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

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

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

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

  • jobName (str)

  • unitName (Optional[str])

  • displayName (Optional[str])

  • local (Optional[bool])

get_names()[source]

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

Return type:

toil.bus.Names

get_chain()[source]

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

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

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

Return type:

List[toil.bus.Names]

serviceHostIDsInBatches()[source]

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

(in the order they need to start in)

Return type:

Iterator[List[str]]

successorsAndServiceHosts()[source]

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

Return type:

Iterator[str]

allSuccessors()[source]

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

Follow-ons will come before children.

Return type:

Iterator[str]

successors_by_phase()[source]

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

Phases ececute higher numbers to lower numbers.

Return type:

Iterator[Tuple[int, str]]

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

Will be empty if the job has no unfinished services.

has_body()[source]

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

Return type:

bool

attach_body(file_store_id, user_script)[source]

Attach a job body to this JobDescription.

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

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

Parameters:
Return type:

None

detach_body()[source]

Drop the body reference from a JobDescription.

Return type:

None

get_body()[source]

Get the information needed to load the job body.

Returns:

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

Return type:

Tuple[str, toil.resource.ModuleDescriptor]

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

nextSuccessors()[source]

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

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

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

Return type:

Optional[Set[str]]

filterSuccessors(predicate)[source]

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

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

Treats all other successors as complete and forgets them.

Parameters:

predicate (Callable[[str], bool])

Return type:

None

filterServiceHosts(predicate)[source]

Keep only services for which the given predicate approves.

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

Treats all other services as complete and forgets them.

Parameters:

predicate (Callable[[str], bool])

Return type:

None

clear_nonexistent_dependents(job_store)[source]

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

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

Parameters:

job_store (toil.jobStores.abstractJobStore.AbstractJobStore)

Return type:

None

clear_dependents()[source]

Remove all references to successor and service jobs.

Return type:

None

is_subtree_done()[source]

Check if the subtree is done.

Returns:

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

Return type:

bool

replace(other)[source]

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

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

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

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

Parameters:

other (JobDescription) – Job description to replace.

Return type:

None

assert_is_not_newer_than(other)[source]

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

Parameters:

other (JobDescription)

Return type:

None

is_updated_by(other)[source]

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

Parameters:

other (JobDescription)

Return type:

bool

addChild(childID)[source]

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

Parameters:

childID (str)

Return type:

None

addFollowOn(followOnID)[source]

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

Parameters:

followOnID (str)

Return type:

None

addServiceHostJob(serviceID, parentServiceID=None)[source]

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

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

hasChild(childID)[source]

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

Parameters:

childID (str)

Return type:

bool

hasFollowOn(followOnID)[source]

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

Parameters:

followOnID (str)

Return type:

bool

hasServiceHostJob(serviceID)[source]

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

Return type:

bool

renameReferences(renames)[source]

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

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

Parameters:

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

Return type:

None

addPredecessor()[source]

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

Return type:

None

onRegistration(jobStore)[source]

Perform setup work that requires the JobStore.

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

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

Parameters:

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

Return type:

None

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

Configure job after a failure.

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

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

Parameters:
Return type:

None

getLogFileHandle(jobStore)[source]

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

Assumes logJobStoreFileID is set.

property remainingTryCount
Get the number of tries remaining.

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

clearRemainingTryCount()[source]

Clear remainingTryCount and set it back to its default value.

Returns:

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

Return type:

bool

__str__()[source]

Produce a useful logging string identifying this job.

Return type:

str

__repr__()[source]

Return repr(self).

reserve_versions(count)[source]

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

Parameters:

count (int)

Return type:

None

pre_update_hook()[source]

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

Called by the job store.

Return type:

None

class toil.test.jobStores.jobStoreTest.TemporaryID[source]

Placeholder for a unregistered job ID used by a JobDescription.

Needs to be held:
  • By JobDescription objects to record normal relationships.

  • By Jobs to key their connected-component registries and to record predecessor relationships to facilitate EncapsulatedJob adding itself as a child.

  • By Services to tie back to their hosting jobs, so the service tree can be built up from Service objects.

__str__()[source]

Return str(self).

Return type:

str

__repr__()[source]

Return repr(self).

Return type:

str

__hash__()[source]

Return hash(self).

Return type:

int

__eq__(other)[source]

Return self==value.

Parameters:

other (Any)

Return type:

bool

__ne__(other)[source]

Return self!=value.

Parameters:

other (Any)

Return type:

bool

exception toil.test.jobStores.jobStoreTest.NoSuchFileException(jobStoreFileID, customName=None, *extra)[source]

Bases: Exception

Indicates that the specified file does not exist.

Parameters:
exception toil.test.jobStores.jobStoreTest.NoSuchJobException(jobStoreID)[source]

Bases: Exception

Indicates that the specified job does not exist.

Parameters:

jobStoreID (toil.fileStores.FileID)

class toil.test.jobStores.jobStoreTest.FileJobStore(path, fanOut=1000)[source]

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()[source]

Jobstore’s preference as to whether it likes caching or doesn’t care about it. Some jobstores benefit from caching, however on some local configurations it can be flaky.

see https://github.com/DataBiosphere/toil/issues/4218

Return type:

bool

__repr__()[source]

Return repr(self).

initialize(config)[source]

Initialize this job store.

Create the physical storage for this job store, allocate a workflow ID and persist the given Toil configuration to the store.

Parameters:

config – 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()[source]

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()[source]

The inverse of initialize(), this method deletes the physical storage represented by this instance. While not being atomic, this method is at least idempotent, as a means to counteract potential issues with eventual consistency exhibited by the underlying storage mechanisms. This means that if the method fails (raises an exception), it may (and should be) invoked again. If the underlying storage mechanism is eventually consistent, even a successful invocation is not an ironclad guarantee that the physical storage vanished completely and immediately. A successful invocation only guarantees that the deletion will eventually happen. It is therefore recommended to not immediately reuse the same job store location for a new Toil workflow.

assign_job_id(job_description)[source]

Get a new jobStoreID to be used by the described job, and assigns it to the JobDescription.

Files associated with the assigned ID will be accepted even if the JobDescription has never been created or updated.

Parameters:

job_description (toil.job.JobDescription) – The JobDescription to give an ID to

create_job(job_description)[source]

Writes the given JobDescription to the job store. The job must have an ID assigned already.

Must call jobDescription.pre_update_hook()

Returns:

The JobDescription passed.

Return type:

toil.job.JobDescription

batch()[source]

If supported by the batch system, calls to create() with this context manager active will be performed in a batch after the context manager is released.

job_exists(job_id)[source]

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

Return type:

bool

get_public_url(jobStoreFileID)[source]

Returns a publicly accessible URL to the given file in the job store. The returned URL may expire as early as 1h after its been returned. Throw an exception if the file does not exist.

Parameters:

file_name (str) – the jobStoreFileID of the file to generate a URL for

Raises:

NoSuchFileException – if the specified file does not exist in this job store

Return type:

str

get_shared_public_url(sharedFileName)[source]

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)[source]

Loads the description of the job referenced by the given ID, assigns it the job store’s config, and returns it.

May declare the job to have failed (see toil.job.JobDescription.setupJobAfterFailure()) if there is evidence of a failed update attempt.

Parameters:

job_id – the ID of the job to load

Raises:

NoSuchJobException – if there is no job with the given ID

update_job(job)[source]

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

Must call jobDescription.pre_update_hook()

Parameters:

job (toil.job.JobDescription) – the job to write to this job store

delete_job(job_id)[source]

Removes the JobDescription from the store atomically. You may not then subsequently call load(), write(), update(), etc. with the same jobStoreID or any JobDescription bearing it.

This operation is idempotent, i.e. deleting a job twice or deleting a non-existent job will succeed silently.

Parameters:

job_id (str) – the ID of the job to delete from this job store

jobs()[source]

Best effort attempt to return iterator on JobDescriptions for all jobs in the store. The iterator may not return all jobs and may also contain orphaned jobs that have already finished successfully and should not be rerun. To guarantee you get any and all jobs that can be run instead construct a more expensive ToilState object

Returns:

Returns iterator on jobs in the store. The iterator may or may not contain all jobs and may contain invalid jobs

Return type:

Iterator[toil.job.jobDescription]

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

Takes a file (as a path) and places it in this job store. Returns an ID that can be used to retrieve the file at a later time. The file is written in a atomic manner. It will not appear in the jobStore until the write has successfully completed.

Parameters:
  • local_path (str) – the path to the local file that will be uploaded to the job store. The last path component (basename of the file) will remain associated with the file in the file store, if supported, so that the file can be searched for by name or name glob.

  • job_id (str) – the id of a job, or None. If specified, the may be associated with that job in a job-store-specific way. This may influence the returned ID.

  • cleanup (bool) – Whether to attempt to delete the file when the job whose jobStoreID was given as jobStoreID is deleted with jobStore.delete(job). If jobStoreID was not given, does nothing.

Raises:

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)[source]

Similar to writeFile, but returns a context manager yielding a tuple of 1) a file handle which can be written to and 2) the ID of the resulting file in the job store. The yielded file handle does not need to and should not be closed explicitly. The file is written in a atomic manner. It will not appear in the jobStore until the write has successfully completed.

Parameters:
  • job_id (str) – the id of a job, or None. If specified, the may be associated with that job in a job-store-specific way. This may influence the returned ID.

  • cleanup (bool) – Whether to attempt to delete the file when the job whose jobStoreID was given as jobStoreID is deleted with jobStore.delete(job). If jobStoreID was not given, does nothing.

  • basename (str) – If supported by the implementation, use the given file basename so that when searching the job store with a query matching that basename, the file will be detected.

  • encoding (str) – the name of the encoding used to encode the file. Encodings are the same as for encode(). Defaults to None which represents binary mode.

  • errors (str) – an optional string that specifies how encoding errors are to be handled. Errors are the same as for open(). Defaults to ‘strict’ when an encoding is specified.

Raises:

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)[source]

Creates an empty file in the job store and returns its ID. Call to fileExists(getEmptyFileStoreID(jobStoreID)) will return True.

Parameters:
  • job_id (str) – the id of a job, or None. If specified, the may be associated with that job in a job-store-specific way. This may influence the returned ID.

  • cleanup (bool) – Whether to attempt to delete the file when the job whose jobStoreID was given as jobStoreID is deleted with jobStore.delete(job). If jobStoreID was not given, does nothing.

  • basename (str) – If supported by the implementation, use the given file basename so that when searching the job store with a query matching that basename, the file will be detected.

Returns:

a jobStoreFileID that references the newly created file and can be used to reference the file in the future.

Return type:

str

update_file(file_id, local_path)[source]

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

Throws an exception if the file does not exist.

Parameters:
  • 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)[source]

Copies or hard links the file referenced by jobStoreFileID to the given local file path. The version will be consistent with the last copy of the file written/updated. If the file in the job store is later modified via updateFile or updateFileStream, it is implementation-defined whether those writes will be visible at localFilePath. The file is copied in an atomic manner. It will not appear in the local file system until the copy has completed.

The file at the given local path may not be modified after this method returns!

Note! Implementations of readFile need to respect/provide the executable attribute on FileIDs.

Parameters:
  • file_id (str) – ID of the file to be copied

  • local_path (str) – the local path indicating where to place the contents of the given file in the job store

  • symlink (bool) – whether the reader can tolerate a symlink. If set to true, the job store may create a symlink instead of a full copy of the file or a hard link.

Return type:

None

delete_file(file_id)[source]

Deletes the file with the given ID from this job store. This operation is idempotent, i.e. deleting a file twice or deleting a non-existent file will succeed silently.

Parameters:

file_id (str) – ID of the file to delete

file_exists(file_id)[source]

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)[source]

Get the size of the given file in bytes, or 0 if it does not exist when queried.

Note that job stores which encrypt files might return overestimates of file sizes, since the encrypted file may have been padded to the nearest block, augmented with an initialization vector, etc.

Parameters:

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

Return type:

int

update_file_stream(file_id, encoding=None, errors=None)[source]

Replaces the existing version of a file in the job store. Similar to writeFile, but returns a context manager yielding a file handle which can be written to. The yielded file handle does not need to and should not be closed explicitly.

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

  • encoding (str) – the name of the encoding used to encode the file. Encodings are the same as for encode(). Defaults to None which represents binary mode.

  • errors (str) – an optional string that specifies how encoding errors are to be handled. Errors are the same as for open(). Defaults to ‘strict’ when an encoding is specified.

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

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)[source]

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)[source]

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)[source]

Stores a message as a log in the jobstore.

Parameters:

msg (str) – the string to be written

Raises:

ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method

read_logs(callback, read_all=False)[source]

Reads logs accumulated by the write_logs() method. For each log this method calls the given callback function with the message as an argument (rather than returning logs directly, this method must be supplied with a callback which will process log messages).

Only unread logs will be read unless the read_all parameter is set.

Parameters:
  • callback (Callable) – a function to be applied to each of the stats file handles found

  • read_all (bool) – a boolean indicating whether to read the already processed stats files in addition to the unread stats files

Raises:

ConcurrentFileModificationException – if the file was modified concurrently during an invocation of this method

Returns:

the number of stats files processed

Return type:

int

toil.test.jobStores.jobStoreTest.mkdtemp(suffix=None, prefix=None, dir=None)[source]

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

The permissions on the directory will be 711 instead of 700, allowing the group and all other users to traverse the directory. This is necessary if the directory is on NFS and the Docker daemon would like to mount it or a file inside it into a container, because on NFS even the Docker daemon appears bound by the file permissions.

See <https://github.com/DataBiosphere/toil/issues/4644>, and <https://stackoverflow.com/a/67928880> which talks about a similar problem but in the context of user namespaces.

Parameters:
  • suffix (Optional[str])

  • prefix (Optional[str])

  • dir (Optional[str])

Return type:

str

toil.test.jobStores.jobStoreTest.memoize

Memoize a function result based on its parameters using this decorator.

For example, this can be used in place of lazy initialization. If the decorating function is invoked by multiple threads, the decorated function may be called more than once with the same arguments.

toil.test.jobStores.jobStoreTest.retry(intervals=None, infinite_retries=False, errors=None, log_message=None, prepare=None)[source]

Retry a function if it fails with any Exception defined in “errors”.

Does so every x seconds, where x is defined by a list of numbers (ints or floats) in “intervals”. Also accepts ErrorCondition events for more detailed retry attempts.

Parameters:
  • intervals (Optional[List]) – A list of times in seconds we keep retrying until returning failure. Defaults to retrying with the following exponential back-off before failing: 1s, 1s, 2s, 4s, 8s, 16s

  • infinite_retries (bool) – If this is True, reset the intervals when they run out. Defaults to: False.

  • errors (Optional[Sequence[Union[ErrorCondition, Type[Exception]]]]) –

    A list of exceptions OR ErrorCondition objects to catch and retry on. ErrorCondition objects describe more detailed error event conditions than a plain error. An ErrorCondition specifies: - Exception (required) - Error codes that must match to be retried (optional; defaults to not checking) - A string that must be in the error message to be retried (optional; defaults to not checking) - A bool that can be set to False to always error on this condition.

    If not specified, this will default to a generic Exception.

  • log_message (Optional[Tuple[Callable, str]]) – Optional tuple of (“log/print function()”, “message string”) that will precede each attempt.

  • prepare (Optional[List[Callable]]) – Optional list of functions to call, with the function’s arguments, between retries, to reset state.

Returns:

The result of the wrapped function or raise.

Return type:

Callable[[Callable[Ellipsis, RT]], Callable[Ellipsis, RT]]

class toil.test.jobStores.jobStoreTest.StatsAndLogging(jobStore, config)[source]

A thread to aggregate statistics and logging.

Parameters:
start()[source]

Start the stats and logging thread.

Return type:

None

classmethod formatLogStream(stream, stream_name)[source]

Given a stream of text or bytes, and the job name, job itself, or some other optional stringifyable identity info for the job, return a big text string with the formatted job log, suitable for printing for the user.

We don’t want to prefix every line of the job’s log with our own logging info, or we get prefixes wider than any reasonable terminal and longer than the messages.

Parameters:
  • stream (Union[IO[str], IO[bytes]]) – The stream of text or bytes to print for the user.

  • stream_name (str)

Return type:

str

classmethod logWithFormatting(stream_name, jobLogs, method=logger.debug, message=None)[source]
Parameters:
  • stream_name (str)

  • jobLogs (Union[IO[str], IO[bytes]])

  • method (Callable[[str], None])

  • message (Optional[str])

Return type:

None

classmethod writeLogFiles(jobNames, jobLogList, config, failed=False)[source]
Parameters:
Return type:

None

classmethod statsAndLoggingAggregator(jobStore, stop, config)[source]

The following function is used for collating stats/reporting log messages from the workers. Works inside of a thread, collates as long as the stop flag is not True.

Parameters:
Return type:

None

check()[source]

Check on the stats and logging aggregator. :raise RuntimeError: If the underlying thread has quit.

Return type:

None

shutdown()[source]

Finish up the stats/logging aggregation thread.

Return type:

None

class toil.test.jobStores.jobStoreTest.ToilTest(methodName='runTest')[source]

Bases: unittest.TestCase

A common base class for Toil tests.

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

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

setup_method(method)[source]
Parameters:

method (Any)

Return type:

None

classmethod setUpClass()[source]

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

Return type:

None

classmethod tearDownClass()[source]

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

Return type:

None

setUp()[source]

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

Return type:

None

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

Return type:

None

classmethod awsRegion()[source]

Pick an appropriate AWS region.

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

Return type:

str

toil.test.jobStores.jobStoreTest.make_tests(generalMethod, targetClass, **kwargs)[source]

This method dynamically generates test methods using the generalMethod as a template. Each generated function is the result of a unique combination of parameters applied to the generalMethod. Each of the parameters has a corresponding string that will be used to name the method. These generated functions are named in the scheme: test_[generalMethodName]___[ firstParamaterName]_[someValueName]__[secondParamaterName]_…

The arguments following the generalMethodName should be a series of one or more dictionaries of the form {str : type, …} where the key represents the name of the value. The names will be used to represent the permutation of values passed for each parameter in the generalMethod.

The generated method names will list the parameters in lexicographic order by parameter name.

Parameters:
  • generalMethod – A method that will be parameterized with values passed as kwargs. Note that the generalMethod must be a regular method.

  • targetClass – This represents the class to which the generated test methods will be bound. If no targetClass is specified the class of the generalMethod is assumed the target.

  • kwargs – a series of dictionaries defining values, and their respective names where each keyword is the name of a parameter in generalMethod.

>>> class Foo:
...     def has(self, num, letter):
...         return num, letter
...
...     def hasOne(self, num):
...         return num
>>> class Bar(Foo):
...     pass
>>> make_tests(Foo.has, Bar, num={'one':1, 'two':2}, letter={'a':'a', 'b':'b'})
>>> b = Bar()

Note that num comes lexicographically before letter and so appears first in the generated method names.

>>> assert b.test_has__letter_a__num_one() == b.has(1, 'a')
>>> assert b.test_has__letter_b__num_one() == b.has(1, 'b')
>>> assert b.test_has__letter_a__num_two() == b.has(2, 'a')
>>> assert b.test_has__letter_b__num_two() == b.has(2, 'b')
>>> f = Foo()
>>> hasattr(f, 'test_has__num_one__letter_a')  # should be false because Foo has no test methods
False
toil.test.jobStores.jobStoreTest.needs_aws_s3(test_item)[source]

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

Parameters:

test_item (MT)

Return type:

MT

toil.test.jobStores.jobStoreTest.needs_encryption(test_item)[source]

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

Parameters:

test_item (MT)

Return type:

MT

toil.test.jobStores.jobStoreTest.needs_google_project(test_item)[source]

Use as a decorator before test classes or methods to run only if we have a Google Cloud project set.

Parameters:

test_item (MT)

Return type:

MT

toil.test.jobStores.jobStoreTest.needs_google_storage(test_item)[source]

Use as a decorator before test classes or methods to run only if Google Cloud is installed and we ought to be able to access public Google Storage URIs.

Parameters:

test_item (MT)

Return type:

MT

toil.test.jobStores.jobStoreTest.slow(test_item)[source]

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

Parameters:

test_item (MT)

Return type:

MT

toil.test.jobStores.jobStoreTest.google_retry(x)[source]
toil.test.jobStores.jobStoreTest.logger
toil.test.jobStores.jobStoreTest.tearDownModule()[source]
class toil.test.jobStores.jobStoreTest.AbstractJobStoreTest[source]

Hide abstract base class from unittest’s test case loader

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

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

Bases: toil.test.ToilTest

A common base class for Toil tests.

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

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

classmethod setUpClass()[source]

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

setUp()[source]

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

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

testInitialState()[source]

Ensure proper handling of nonexistent files.

testJobCreation()[source]

Test creation of a job.

Does the job exist in the jobstore it is supposed to be in? Are its attributes what is expected?

testConfigEquality()[source]

Ensure that the command line configurations are successfully loaded and stored.

In setUp() self.jobstore1 is created and initialized. In this test, after creating newJobStore, .resume() will look for a previously instantiated job store and load its config options. This is expected to be equal but not the same object.

testJobLoadEquality()[source]

Tests that a job created via one JobStore instance can be loaded from another.

testChildLoadingEquality()[source]

Test that loading a child job operates as expected.

testPersistantFilesToDelete()[source]

Make sure that updating a job persists filesToDelete.

The following demonstrates the job update pattern, where files to be deleted atomically with a job update are referenced in “filesToDelete” array, which is persisted to disk first. If things go wrong during the update, this list of files to delete is used to ensure that the updated job and the files are never both visible at the same time.

testUpdateBehavior()[source]

Tests the proper behavior during updating jobs.

testJobDeletions()[source]

Tests the consequences of deleting jobs.

testSharedFiles()[source]

Tests the sharing of files.

testReadWriteSharedFilesTextMode()[source]

Checks if text mode is compatible for shared file streams.

testReadWriteFileStreamTextMode()[source]

Checks if text mode is compatible for file streams.

testPerJobFiles()[source]

Tests the behavior of files on jobs.

testStatsAndLogging()[source]

Tests behavior of reading and writing stats and logging.

testWriteLogFiles()[source]

Test writing log files.

testBatchCreate()[source]

Test creation of many jobs.

testGrowingAndShrinkingJob()[source]

Make sure jobs update correctly if they grow/shrink.

externalStoreCache
classmethod cleanUpExternalStores()[source]
mpTestPartSize
classmethod makeImportExportTests()[source]
testImportHttpFile()[source]

Test importing a file over HTTP.

testImportFtpFile()[source]

Test importing a file over FTP

testFileDeletion()[source]

Intended to cover the batch deletion of items in the AWSJobStore, but it doesn’t hurt running it on the other job stores.

testMultipartUploads()[source]

This test is meant to cover multi-part uploads in the AWSJobStore but it doesn’t hurt running it against the other job stores as well.

testZeroLengthFiles()[source]

Test reading and writing of empty files.

testLargeFile()[source]

Test the reading and writing of large files.

fetch_url(url)[source]

Fetch the given URL. Throw an error if it cannot be fetched in a reasonable number of attempts.

Parameters:

url (str)

Return type:

None

assertUrl(url)[source]
testCleanCache()[source]
testPartialReadFromStream()[source]

Test whether readFileStream will deadlock on a partial read.

testDestructionOfCorruptedJobStore()[source]
testDestructionIdempotence()[source]
testEmptyFileStoreIDIsReadable()[source]

Simply creates an empty fileStoreID and attempts to read from it.

class toil.test.jobStores.jobStoreTest.AbstractEncryptedJobStoreTest[source]
class Test(methodName='runTest')[source]

Bases: AbstractJobStoreTest

A test of job stores that use encryption

setUp()[source]

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

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

testEncrypted()[source]

Create an encrypted file. Read it in encrypted mode then try with encryption off to ensure that it fails.

class toil.test.jobStores.jobStoreTest.FileJobStoreTest(methodName='runTest')[source]

Bases: AbstractJobStoreTest

A common base class for Toil tests.

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

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

testPreserveFileName()[source]

Check that the fileID ends with the given file name.

Test that if we provide a fileJobStore with a symlink to a directory, it doesn’t de-reference it.

Test that if we link imports into the FileJobStore, we can’t get hardlinks to symlinks.

Test that imported files are symlinked when when expected

class toil.test.jobStores.jobStoreTest.GoogleJobStoreTest(methodName='runTest')[source]

Bases: AbstractJobStoreTest

A common base class for Toil tests.

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

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

projectID
headers
class toil.test.jobStores.jobStoreTest.AWSJobStoreTest(methodName='runTest')[source]

Bases: AbstractJobStoreTest

A common base class for Toil tests.

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

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

testSDBDomainsDeletedOnFailedJobstoreBucketCreation()[source]

This test ensures that SDB domains bound to a jobstore are deleted if the jobstore bucket failed to be created. We simulate a failed jobstore bucket creation by using a bucket in a different region with the same name.

testInlinedFiles()[source]
testOverlargeJob()[source]
testMultiThreadImportFile()[source]

Tests that importFile is thread-safe.

Return type:

None

class toil.test.jobStores.jobStoreTest.InvalidAWSJobStoreTest(methodName='runTest')[source]

Bases: toil.test.ToilTest

A common base class for Toil tests.

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

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

testInvalidJobStoreName()[source]
class toil.test.jobStores.jobStoreTest.EncryptedAWSJobStoreTest(methodName='runTest')[source]

Bases: AWSJobStoreTest, AbstractEncryptedJobStoreTest

A common base class for Toil tests.

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

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

class toil.test.jobStores.jobStoreTest.StubHttpRequestHandler(*args, directory=None, **kwargs)[source]

Bases: http.server.SimpleHTTPRequestHandler

Simple HTTP request handler with GET and HEAD commands.

This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by calling the .guess_type() method.

The GET and HEAD requests are identical except that the HEAD request omits the actual contents of the file.

fileContents = 'A good programmer looks both ways before crossing a one-way street'
do_GET()[source]

Serve a GET request.