toil.jobStores.aws.jobStore

Attributes

EC2Regions

boto3_session

s3_boto3_resource

s3_boto3_client

logger

CONSISTENCY_TICKS

CONSISTENCY_TIME

aRepr

custom_repr

Exceptions

ConcurrentFileModificationException

Indicates that the file was attempted to be modified by multiple processes at once.

JobStoreExistsException

Indicates that the specified job store already exists.

NoSuchFileException

Indicates that the specified file does not exist.

NoSuchJobException

Indicates that the specified job does not exist.

NoSuchJobStoreException

Indicates that the specified job store does not exist.

LocatorException

Base exception class for all locator exceptions.

ServerSideCopyProhibitedError

Raised when AWS refuses to perform a server-side copy between S3 keys, and

ChecksumError

Raised when a download from AWS does not contain the correct data.

DomainDoesNotExist

Raised when a domain that is expected to exist does not exist.

BucketLocationConflictException

Base exception class for all locator exceptions.

Classes

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.

AbstractJobStore

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

SDBHelper

A mixin with methods for storing limited amounts of binary data in an SDB item

ReadablePipe

An object-oriented wrapper for os.pipe. Clients should subclass it, implement

ReadableTransformingPipe

A pipe which is constructed around a readable stream, and which provides a

WritablePipe

An object-oriented wrapper for os.pipe. Clients should subclass it, implement

panic

The Python idiom for reraising a primary exception fails when the except block raises a

InnerClass

Note that this is EXPERIMENTAL code.

AWSJobStore

A job store that uses Amazon's S3 for file storage and SimpleDB for storing job info and

Functions

copyKeyMultipart(resource, srcBucketName, srcKeyName, ...)

Copies a key from a source key to a destination key in multiple parts. Note that if the

fileSizeAndTime(localFilePath)

no_such_sdb_domain(e)

retry_sdb([delays, timeout, predicate])

sdb_unavailable(e)

uploadFile(readable, resource, bucketName, fileID[, ...])

Upload a readable object to s3, using multipart uploading if applicable.

uploadFromPath(localFilePath, resource, bucketName, fileID)

Uploads a file to s3, using multipart uploading if applicable

build_tag_dict_from_env([environment])

establish_boto3_session([region_name])

Get a Boto 3 session usable by the current thread.

create_s3_bucket(s3_resource, bucket_name, region)

Create an AWS S3 bucket, using the given Boto3 S3 session, with the

enable_public_objects(bucket_name)

Enable a bucket to contain objects which are public.

flatten_tags(tags)

Convert tags from a key to value dict into a list of 'Key': xxx, 'Value': xxx dicts.

get_bucket_region(bucket_name[, endpoint_url, ...])

Get the AWS region name associated with the given S3 bucket.

get_object_for_url(url[, existing])

Extracts a key (object) from a given parsed s3:// URL.

list_objects_for_url(url)

Extracts a key (object) from a given parsed s3:// URL. The URL will be

retry_s3([delays, timeout, predicate])

Retry iterator of context managers specifically for S3 operations.

retryable_s3_errors(e)

Return true if this is an error from S3 that looks like we ought to retry our request.

boto3_pager(requestor_callable, result_attribute_name, ...)

Yield all the results from calling the given Boto 3 method with the

get_item_from_attributes(attributes, name)

Given a list of attributes, find the attribute associated with the name and return its corresponding value.

compat_bytes(s)

AtomicFileCreate(final_path[, keep])

Context manager to create a temporary file. Entering returns path to

strict_bool(s)

Variant of bool() that only accepts two possible string values.

get_error_code(e)

Get the error code name from a Boto 2 or 3 error, or compatible types.

get_error_status(e)

Get the HTTP status code from a compatible source.

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

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

Module Contents

class toil.jobStores.aws.jobStore.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.jobStores.aws.jobStore.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.jobStores.aws.jobStore.JobDescription(requirements, jobName, unitName='', displayName='', local=None)

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

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

Return type:

toil.bus.Names

get_chain()

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

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

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

Return type:

Iterator[str]

allSuccessors()

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

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

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

Return type:

bool

attach_body(file_store_id, user_script)

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

Drop the body reference from a JobDescription.

Return type:

None

get_body()

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

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)

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)

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)

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

Remove all references to successor and service jobs.

Return type:

None

is_subtree_done()

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)

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)

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)

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

Parameters:

other (JobDescription)

Return type:

bool

addChild(childID)

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

Parameters:

childID (str)

Return type:

None

addFollowOn(followOnID)

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

Parameters:

followOnID (str)

Return type:

None

addServiceHostJob(serviceID, parentServiceID=None)

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)

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

Parameters:

childID (str)

Return type:

bool

hasFollowOn(followOnID)

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

Parameters:

followOnID (str)

Return type:

bool

hasServiceHostJob(serviceID)

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

Return type:

bool

renameReferences(renames)

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

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

Return type:

None

onRegistration(jobStore)

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)

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)

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

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

Produce a useful logging string identifying this job.

Return type:

str

__repr__()

Return repr(self).

reserve_versions(count)

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

Parameters:

count (int)

Return type:

None

pre_update_hook()

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

Called by the job store.

Return type:

None

class toil.jobStores.aws.jobStore.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.jobStores.aws.jobStore.ConcurrentFileModificationException(jobStoreFileID)

Bases: Exception

Indicates that the file was attempted to be modified by multiple processes at once.

Parameters:

jobStoreFileID (toil.fileStores.FileID)

exception toil.jobStores.aws.jobStore.JobStoreExistsException(locator, prefix)

Bases: LocatorException

Indicates that the specified job store already exists.

Parameters:
exception toil.jobStores.aws.jobStore.NoSuchFileException(jobStoreFileID, customName=None, *extra)

Bases: Exception

Indicates that the specified file does not exist.

Parameters:
exception toil.jobStores.aws.jobStore.NoSuchJobException(jobStoreID)

Bases: Exception

Indicates that the specified job does not exist.

Parameters:

jobStoreID (toil.fileStores.FileID)

exception toil.jobStores.aws.jobStore.NoSuchJobStoreException(locator, prefix)

Bases: LocatorException

Indicates that the specified job store does not exist.

Parameters:
exception toil.jobStores.aws.jobStore.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])

class toil.jobStores.aws.jobStore.SDBHelper

A mixin with methods for storing limited amounts of binary data in an SDB item

>>> import os
>>> H=SDBHelper
>>> H.presenceIndicator() 
u'numChunks'
>>> H.binaryToAttributes(None)['numChunks']
0
>>> H.attributesToBinary({u'numChunks': 0})
(None, 0)
>>> H.binaryToAttributes(b'') 
{u'000': b'VQ==', u'numChunks': 1}
>>> H.attributesToBinary({u'numChunks': 1, u'000': b'VQ=='}) 
(b'', 1)

Good pseudo-random data is very likely smaller than its bzip2ed form. Subtract 1 for the type character, i.e ‘C’ or ‘U’, with which the string is prefixed. We should get one full chunk:

>>> s = os.urandom(H.maxRawValueSize-1)
>>> d = H.binaryToAttributes(s)
>>> len(d), len(d['000'])
(2, 1024)
>>> H.attributesToBinary(d) == (s, 1)
True

One byte more and we should overflow four bytes into the second chunk, two bytes for base64-encoding the additional character and two bytes for base64-padding to the next quartet.

>>> s += s[0:1]
>>> d = H.binaryToAttributes(s)
>>> len(d), len(d['000']), len(d['001'])
(3, 1024, 4)
>>> H.attributesToBinary(d) == (s, 2)
True
maxAttributesPerItem = 256
maxValueSize = 1024
maxRawValueSize
classmethod maxBinarySize(extraReservedChunks=0)
classmethod binaryToAttributes(binary)

Turn a bytestring, or None, into SimpleDB attributes.

Return type:

Dict[str, str]

classmethod attributeDictToList(attributes)

Convert the attribute dict (ex: from binaryToAttributes) into a list of attribute typed dicts to be compatible with boto3 argument syntax :param attributes: Dict[str, str], attribute in object form :return: List[AttributeTypeDef], list of attributes in typed dict form

Parameters:

attributes (Dict[str, str])

Return type:

List[mypy_boto3_sdb.type_defs.AttributeTypeDef]

classmethod attributeListToDict(attributes)

Convert the attribute boto3 representation of list of attribute typed dicts back to a dictionary with name, value pairs :param attribute: List[AttributeTypeDef, attribute in typed dict form :return: Dict[str, str], attribute in dict form

Parameters:

attributes (List[mypy_boto3_sdb.type_defs.AttributeTypeDef])

Return type:

Dict[str, str]

classmethod get_attributes_from_item(item, keys)
Parameters:
  • item (mypy_boto3_sdb.type_defs.ItemTypeDef)

  • keys (List[str])

Return type:

List[Optional[str]]

classmethod presenceIndicator()

The key that is guaranteed to be present in the return value of binaryToAttributes(). Assuming that binaryToAttributes() is used with SDB’s PutAttributes, the return value of this method could be used to detect the presence/absence of an item in SDB.

classmethod attributesToBinary(attributes)
Return type:

(str|None,int)

Returns:

the binary data and the number of chunks it was composed from

Parameters:

attributes (List[mypy_boto3_sdb.type_defs.AttributeTypeDef])

exception toil.jobStores.aws.jobStore.ServerSideCopyProhibitedError

Bases: RuntimeError

Raised when AWS refuses to perform a server-side copy between S3 keys, and insists that you pay to download and upload the data yourself instead.

toil.jobStores.aws.jobStore.copyKeyMultipart(resource, srcBucketName, srcKeyName, srcKeyVersion, dstBucketName, dstKeyName, sseAlgorithm=None, sseKey=None, copySourceSseAlgorithm=None, copySourceSseKey=None)

Copies a key from a source key to a destination key in multiple parts. Note that if the destination key exists it will be overwritten implicitly, and if it does not exist a new key will be created. If the destination bucket does not exist an error will be raised.

This function will always do a fast, server-side copy, at least until/unless <https://github.com/boto/boto3/issues/3270> is fixed. In some situations, a fast, server-side copy is not actually possible. For example, when residing in an AWS VPC with an S3 VPC Endpoint configured, copying from a bucket in another region to a bucket in your own region cannot be performed server-side. This is because the VPC Endpoint S3 API servers refuse to perform server-side copies between regions, the source region’s API servers refuse to initiate the copy and refer you to the destination bucket’s region’s API servers, and the VPC routing tables are configured to redirect all access to the current region’s S3 API servers to the S3 Endpoint API servers instead.

If a fast server-side copy is not actually possible, a ServerSideCopyProhibitedError will be raised.

Parameters:
  • resource (mypy_boto3_s3.S3ServiceResource) – boto3 resource

  • srcBucketName (str) – The name of the bucket to be copied from.

  • srcKeyName (str) – The name of the key to be copied from.

  • srcKeyVersion (str) – The version of the key to be copied from.

  • dstBucketName (str) – The name of the destination bucket for the copy.

  • dstKeyName (str) – The name of the destination key that will be created or overwritten.

  • sseAlgorithm (str) – Server-side encryption algorithm for the destination.

  • sseKey (str) – Server-side encryption key for the destination.

  • copySourceSseAlgorithm (str) – Server-side encryption algorithm for the source.

  • copySourceSseKey (str) – Server-side encryption key for the source.

Return type:

str

Returns:

The version of the copied file (or None if versioning is not enabled for dstBucket).

toil.jobStores.aws.jobStore.fileSizeAndTime(localFilePath)
toil.jobStores.aws.jobStore.no_such_sdb_domain(e)
toil.jobStores.aws.jobStore.retry_sdb(delays=DEFAULT_DELAYS, timeout=DEFAULT_TIMEOUT, predicate=retryable_sdb_errors)
toil.jobStores.aws.jobStore.sdb_unavailable(e)
toil.jobStores.aws.jobStore.uploadFile(readable, resource, bucketName, fileID, headerArgs=None, partSize=50 << 20)

Upload a readable object to s3, using multipart uploading if applicable. :param readable: a readable stream or a file path to upload to s3 :param S3.Resource resource: boto3 resource :param str bucketName: name of the bucket to upload to :param str fileID: the name of the file to upload to :param dict headerArgs: http headers to use when uploading - generally used for encryption purposes :param int partSize: max size of each part in the multipart upload, in bytes :return: version of the newly uploaded file

Parameters:
  • bucketName (str)

  • fileID (str)

  • headerArgs (Optional[dict])

  • partSize (int)

toil.jobStores.aws.jobStore.uploadFromPath(localFilePath, resource, bucketName, fileID, headerArgs=None, partSize=50 << 20)

Uploads a file to s3, using multipart uploading if applicable

Parameters:
  • localFilePath (str) – Path of the file to upload to s3

  • resource (S3.Resource) – boto3 resource

  • bucketName (str) – name of the bucket to upload to

  • fileID (str) – the name of the file to upload to

  • headerArgs (dict) – http headers to use when uploading - generally used for encryption purposes

  • partSize (int) – max size of each part in the multipart upload, in bytes

Returns:

version of the newly uploaded file

class toil.jobStores.aws.jobStore.ReadablePipe(encoding=None, errors=None)

Bases: abc.ABC

An object-oriented wrapper for os.pipe. Clients should subclass it, implement writeTo() to place data into the writable end of the pipe, then instantiate the class as a context manager to get the writable end. See the example below.

>>> import sys, shutil
>>> class MyPipe(ReadablePipe):
...     def writeTo(self, writable):
...         writable.write('Hello, world!\n'.encode('utf-8'))
>>> with MyPipe() as readable:
...     shutil.copyfileobj(codecs.getreader('utf-8')(readable), sys.stdout)
Hello, world!

Each instance of this class creates a thread and invokes the writeTo() method in that thread. The thread will be join()ed upon normal exit from the context manager, i.e. the body of the with statement. If an exception occurs, the thread will not be joined but a well-behaved writeTo() implementation will terminate shortly thereafter due to the pipe having been closed.

Now, exceptions in the reader thread will be reraised in the main thread:

>>> class MyPipe(ReadablePipe):
...     def writeTo(self, writable):
...         raise RuntimeError('Hello, world!')
>>> with MyPipe() as readable:
...     pass
Traceback (most recent call last):
...
RuntimeError: Hello, world!

More complicated, less illustrative tests:

Same as above, but proving that handles are closed:

>>> x = os.dup(0); os.close(x)
>>> class MyPipe(ReadablePipe):
...     def writeTo(self, writable):
...         raise RuntimeError('Hello, world!')
>>> with MyPipe() as readable:
...     pass
Traceback (most recent call last):
...
RuntimeError: Hello, world!
>>> y = os.dup(0); os.close(y); x == y
True

Exceptions in the body of the with statement aren’t masked, and handles are closed:

>>> x = os.dup(0); os.close(x)
>>> class MyPipe(ReadablePipe):
...     def writeTo(self, writable):
...         pass
>>> with MyPipe() as readable:
...     raise RuntimeError('Hello, world!')
Traceback (most recent call last):
...
RuntimeError: Hello, world!
>>> y = os.dup(0); os.close(y); x == y
True
abstract writeTo(writable)

Implement this method to write data from the pipe. This method should support both binary and text mode input.

Parameters:

writable (file) – the file object representing the writable end of the pipe. Do not explicitly invoke the close() method of the object, that will be done automatically.

__enter__()
__exit__(exc_type, exc_val, exc_tb)
class toil.jobStores.aws.jobStore.ReadableTransformingPipe(source, encoding=None, errors=None)

Bases: ReadablePipe

A pipe which is constructed around a readable stream, and which provides a context manager that gives a readable stream.

Useful as a base class for pipes which have to transform or otherwise visit bytes that flow through them, instead of just consuming or producing data.

Clients should subclass it and implement transform(), like so:

>>> import sys, shutil
>>> class MyPipe(ReadableTransformingPipe):
...     def transform(self, readable, writable):
...         writable.write(readable.read().decode('utf-8').upper().encode('utf-8'))
>>> class SourcePipe(ReadablePipe):
...     def writeTo(self, writable):
...         writable.write('Hello, world!\n'.encode('utf-8'))
>>> with SourcePipe() as source:
...     with MyPipe(source) as transformed:
...         shutil.copyfileobj(codecs.getreader('utf-8')(transformed), sys.stdout)
HELLO, WORLD!

The transform() method runs in its own thread, and should move data chunk by chunk instead of all at once. It should finish normally if it encounters either an EOF on the readable, or a BrokenPipeError on the writable. This means that it should make sure to actually catch a BrokenPipeError when writing.

See also: toil.lib.misc.WriteWatchingStream.

abstract transform(readable, writable)

Implement this method to ship data through the pipe.

Parameters:
  • readable (file) – the input stream file object to transform.

  • writable (file) – the file object representing the writable end of the pipe. Do not explicitly invoke the close() method of the object, that will be done automatically.

writeTo(writable)

Implement this method to write data from the pipe. This method should support both binary and text mode input.

Parameters:

writable (file) – the file object representing the writable end of the pipe. Do not explicitly invoke the close() method of the object, that will be done automatically.

class toil.jobStores.aws.jobStore.WritablePipe(encoding=None, errors=None)

Bases: abc.ABC

An object-oriented wrapper for os.pipe. Clients should subclass it, implement readFrom() to consume the readable end of the pipe, then instantiate the class as a context manager to get the writable end. See the example below.

>>> import sys, shutil
>>> class MyPipe(WritablePipe):
...     def readFrom(self, readable):
...         shutil.copyfileobj(codecs.getreader('utf-8')(readable), sys.stdout)
>>> with MyPipe() as writable:
...     _ = writable.write('Hello, world!\n'.encode('utf-8'))
Hello, world!

Each instance of this class creates a thread and invokes the readFrom method in that thread. The thread will be join()ed upon normal exit from the context manager, i.e. the body of the with statement. If an exception occurs, the thread will not be joined but a well-behaved readFrom() implementation will terminate shortly thereafter due to the pipe having been closed.

Now, exceptions in the reader thread will be reraised in the main thread:

>>> class MyPipe(WritablePipe):
...     def readFrom(self, readable):
...         raise RuntimeError('Hello, world!')
>>> with MyPipe() as writable:
...     pass
Traceback (most recent call last):
...
RuntimeError: Hello, world!

More complicated, less illustrative tests:

Same as above, but proving that handles are closed:

>>> x = os.dup(0); os.close(x)
>>> class MyPipe(WritablePipe):
...     def readFrom(self, readable):
...         raise RuntimeError('Hello, world!')
>>> with MyPipe() as writable:
...     pass
Traceback (most recent call last):
...
RuntimeError: Hello, world!
>>> y = os.dup(0); os.close(y); x == y
True

Exceptions in the body of the with statement aren’t masked, and handles are closed:

>>> x = os.dup(0); os.close(x)
>>> class MyPipe(WritablePipe):
...     def readFrom(self, readable):
...         pass
>>> with MyPipe() as writable:
...     raise RuntimeError('Hello, world!')
Traceback (most recent call last):
...
RuntimeError: Hello, world!
>>> y = os.dup(0); os.close(y); x == y
True
abstract readFrom(readable)

Implement this method to read data from the pipe. This method should support both binary and text mode output.

Parameters:

readable (file) – the file object representing the readable end of the pipe. Do not explicitly invoke the close() method of the object, that will be done automatically.

__enter__()
__exit__(exc_type, exc_val, exc_tb)
toil.jobStores.aws.jobStore.build_tag_dict_from_env(environment=os.environ)
Parameters:

environment (MutableMapping[str, str])

Return type:

Dict[str, str]

toil.jobStores.aws.jobStore.establish_boto3_session(region_name=None)

Get a Boto 3 session usable by the current thread.

This function may not always establish a new session; it can be memoized.

Parameters:

region_name (Optional[str])

Return type:

boto3.Session

toil.jobStores.aws.jobStore.create_s3_bucket(s3_resource, bucket_name, region)

Create an AWS S3 bucket, using the given Boto3 S3 session, with the given name, in the given region.

Supports the us-east-1 region, where bucket creation is special.

ALL S3 bucket creation should use this function.

Parameters:
  • s3_resource (mypy_boto3_s3.S3ServiceResource)

  • bucket_name (str)

  • region (toil.lib.aws.AWSRegionName)

Return type:

mypy_boto3_s3.service_resource.Bucket

toil.jobStores.aws.jobStore.enable_public_objects(bucket_name)

Enable a bucket to contain objects which are public.

This adjusts the bucket’s Public Access Block setting to not block all public access, and also adjusts the bucket’s Object Ownership setting to a setting which enables object ACLs.

Does not touch the account’s Public Access Block setting, which can also interfere here. That is probably best left to the account administrator.

This configuration used to be the default, and is what most of Toil’s code is written to expect, but it was changed so that new buckets default to the more restrictive setting <https://aws.amazon.com/about-aws/whats-new/2022/12/amazon-s3-automatically-enable-block-public-access-disable-access-control-lists-buckets-april-2023/>, with the expectation that people would write IAM policies for the buckets to allow public access if needed. Toil expects to be able to make arbitrary objects in arbitrary places public, and naming them all in an IAM policy would be a very awkward way to do it. So we restore the old behavior.

Parameters:

bucket_name (str)

Return type:

None

toil.jobStores.aws.jobStore.flatten_tags(tags)

Convert tags from a key to value dict into a list of ‘Key’: xxx, ‘Value’: xxx dicts.

Parameters:

tags (Dict[str, str])

Return type:

List[Dict[str, str]]

toil.jobStores.aws.jobStore.get_bucket_region(bucket_name, endpoint_url=None, only_strategies=None)

Get the AWS region name associated with the given S3 bucket.

Takes an optional S3 API URL override.

Parameters:
  • only_strategies (Optional[Set[int]]) – For testing, use only strategies with 1-based numbers in this set.

  • bucket_name (str)

  • endpoint_url (Optional[str])

Return type:

str

toil.jobStores.aws.jobStore.get_object_for_url(url, existing=None)

Extracts a key (object) from a given parsed s3:// URL.

If existing is true and the object does not exist, raises FileNotFoundError.

Parameters:
  • existing (bool) – If True, key is expected to exist. If False, key is expected not to exists and it will be created. If None, the key will be created if it doesn’t exist.

  • url (urllib.parse.ParseResult)

Return type:

mypy_boto3_s3.service_resource.Object

toil.jobStores.aws.jobStore.list_objects_for_url(url)

Extracts a key (object) from a given parsed s3:// URL. The URL will be supplemented with a trailing slash if it is missing.

Parameters:

url (urllib.parse.ParseResult)

Return type:

List[str]

toil.jobStores.aws.jobStore.retry_s3(delays=DEFAULT_DELAYS, timeout=DEFAULT_TIMEOUT, predicate=retryable_s3_errors)

Retry iterator of context managers specifically for S3 operations.

Parameters:
Return type:

Iterator[ContextManager[None]]

toil.jobStores.aws.jobStore.retryable_s3_errors(e)

Return true if this is an error from S3 that looks like we ought to retry our request.

Parameters:

e (Exception)

Return type:

bool

toil.jobStores.aws.jobStore.boto3_pager(requestor_callable, result_attribute_name, **kwargs)

Yield all the results from calling the given Boto 3 method with the given keyword arguments, paging through the results using the Marker or NextToken, and fetching out and looping over the list in the response with the given attribute name.

Parameters:
  • requestor_callable (Callable[Ellipsis, Any])

  • result_attribute_name (str)

  • kwargs (Any)

Return type:

Iterable[Any]

toil.jobStores.aws.jobStore.get_item_from_attributes(attributes, name)

Given a list of attributes, find the attribute associated with the name and return its corresponding value.

The attribute_list will be a list of TypedDict’s (which boto3 SDB functions commonly return), where each TypedDict has a “Name” and “Value” key value pair. This function grabs the value out of the associated TypedDict.

If the attribute with the name does not exist, the function will return None.

Parameters:
  • attributes (List[mypy_boto3_sdb.type_defs.AttributeTypeDef]) – list of attributes as List[AttributeTypeDef]

  • name (str) – name of the attribute

Returns:

value of the attribute

Return type:

Any

toil.jobStores.aws.jobStore.compat_bytes(s)
Parameters:

s (Union[bytes, str])

Return type:

str

toil.jobStores.aws.jobStore.EC2Regions
class toil.jobStores.aws.jobStore.panic(log=None)

The Python idiom for reraising a primary exception fails when the except block raises a secondary exception, e.g. while trying to cleanup. In that case the original exception is lost and the secondary exception is reraised. The solution seems to be to save the primary exception info as returned from sys.exc_info() and then reraise that.

This is a contextmanager that should be used like this

try:

# do something that can fail

except:
with panic( log ):

# do cleanup that can also fail

If a logging logger is passed to panic(), any secondary Exception raised within the with block will be logged. Otherwise those exceptions are swallowed. At the end of the with block the primary exception will be reraised.

__enter__()
__exit__(*exc_info)
toil.jobStores.aws.jobStore.AtomicFileCreate(final_path, keep=False)

Context manager to create a temporary file. Entering returns path to the temporary file in the same directory as finalPath. If the code in context succeeds, the file renamed to its actually name. If an error occurs, the file is not installed and is removed unless keep is specified.

Parameters:
Return type:

Iterator[str]

toil.jobStores.aws.jobStore.strict_bool(s)

Variant of bool() that only accepts two possible string values.

Parameters:

s (str)

Return type:

bool

class toil.jobStores.aws.jobStore.InnerClass(inner_class)

Note that this is EXPERIMENTAL code.

A nested class (the inner class) decorated with this will have an additional attribute called ‘outer’ referencing the instance of the nesting class (the outer class) that was used to create the inner class. The outer instance does not need to be passed to the inner class’s constructor, it will be set magically. Shamelessly stolen from

http://stackoverflow.com/questions/2278426/inner-classes-how-can-i-get-the-outer-class-object-at-construction-time#answer-2278595.

with names made more descriptive (I hope) and added caching of the BoundInner classes.

Caveat: Within the inner class, self.__class__ will not be the inner class but a dynamically created subclass thereof. It’s name will be the same as that of the inner class, but its __module__ will be different. There will be one such dynamic subclass per inner class and instance of outer class, if that outer class instance created any instances of inner the class.

>>> class Outer(object):
...     def new_inner(self):
...         # self is an instance of the outer class
...         inner = self.Inner()
...         # the inner instance's 'outer' attribute is set to the outer instance
...         assert inner.outer is self
...         return inner
...     @InnerClass
...     class Inner(object):
...         def get_outer(self):
...             return self.outer
...         @classmethod
...         def new_inner(cls):
...             return cls()
>>> o = Outer()
>>> i = o.new_inner()
>>> i 
<toil.lib.objects.Inner...> bound to <toil.lib.objects.Outer object at ...>
>>> i.get_outer() 
<toil.lib.objects.Outer object at ...>

Now with inheritance for both inner and outer:

>>> class DerivedOuter(Outer):
...     def new_inner(self):
...         return self.DerivedInner()
...     @InnerClass
...     class DerivedInner(Outer.Inner):
...         def get_outer(self):
...             assert super( DerivedOuter.DerivedInner, self ).get_outer() == self.outer
...             return self.outer
>>> derived_outer = DerivedOuter()
>>> derived_inner = derived_outer.new_inner()
>>> derived_inner 
<toil.lib.objects...> bound to <toil.lib.objects.DerivedOuter object at ...>
>>> derived_inner.get_outer() 
<toil.lib.objects.DerivedOuter object at ...>

Test a static references: >>> Outer.Inner # doctest: +ELLIPSIS <class ‘toil.lib.objects…Inner’> >>> DerivedOuter.Inner # doctest: +ELLIPSIS <class ‘toil.lib.objects…Inner’> >>> DerivedOuter.DerivedInner #doctest: +ELLIPSIS <class ‘toil.lib.objects…DerivedInner’>

Can’t decorate top-level classes. Unfortunately, this is detected when the instance is created, not when the class is defined. >>> @InnerClass … class Foo(object): … pass >>> Foo() Traceback (most recent call last): … RuntimeError: Inner classes must be nested in another class.

All inner instances should refer to a single outer instance: >>> o = Outer() >>> o.new_inner().outer == o == o.new_inner().outer True

All inner instances should be of the same class … >>> o.new_inner().__class__ == o.new_inner().__class__ True

… but that class isn’t the inner class … >>> o.new_inner().__class__ != Outer.Inner True

… but a subclass of the inner class. >>> isinstance( o.new_inner(), Outer.Inner ) True

Static and class methods, e.g. should work, too

>>> o.Inner.new_inner().outer == o
True
__get__(instance, owner)
__call__(**kwargs)
toil.jobStores.aws.jobStore.get_error_code(e)

Get the error code name from a Boto 2 or 3 error, or compatible types.

Returns empty string for other errors.

Parameters:

e (Exception)

Return type:

str

toil.jobStores.aws.jobStore.get_error_status(e)

Get the HTTP status code from a compatible source.

Such as a Boto 2 or 3 error, kubernetes.client.rest.ApiException, http.client.HTTPException, urllib3.exceptions.HTTPError, requests.exceptions.HTTPError, urllib.error.HTTPError, or compatible type

Returns 0 from other errors.

Parameters:

e (Exception)

Return type:

int

toil.jobStores.aws.jobStore.retry(intervals=None, infinite_retries=False, errors=None, log_message=None, prepare=None)

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

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

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

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

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

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

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

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

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

Returns:

The result of the wrapped function or raise.

Return type:

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

toil.jobStores.aws.jobStore.boto3_session
toil.jobStores.aws.jobStore.s3_boto3_resource
toil.jobStores.aws.jobStore.s3_boto3_client
toil.jobStores.aws.jobStore.logger
toil.jobStores.aws.jobStore.CONSISTENCY_TICKS = 5
toil.jobStores.aws.jobStore.CONSISTENCY_TIME = 1
exception toil.jobStores.aws.jobStore.ChecksumError

Bases: Exception

Raised when a download from AWS does not contain the correct data.

exception toil.jobStores.aws.jobStore.DomainDoesNotExist(domain_name)

Bases: Exception

Raised when a domain that is expected to exist does not exist.

class toil.jobStores.aws.jobStore.AWSJobStore(locator, partSize=50 << 20)

Bases: toil.jobStores.abstractJobStore.AbstractJobStore

A job store that uses Amazon’s S3 for file storage and SimpleDB for storing job info and enforcing strong consistency on the S3 file storage. There will be SDB domains for jobs and files and a versioned S3 bucket for file contents. Job objects are pickled, compressed, partitioned into chunks of 1024 bytes and each chunk is stored as a an attribute of the SDB item representing the job. UUIDs are used to identify jobs and files.

Parameters:
  • locator (str)

  • partSize (int)

bucketNameRe
minBucketNameLen = 3
maxBucketNameLen = 63
maxNameLen = 10
nameSeparator = '--'
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.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

property sseKeyPath: str | None
Return type:

Optional[str]

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

jobsPerBatchInsert = 25
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:

None

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

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)

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 (Union[bytes, str])

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]

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 (toil.fileStores.FileID) – the ID of the job to load

Raises:

NoSuchJobException – if there is no job with the given ID

Return type:

toil.job.Job

update_job(job_description)

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

itemsPerBatchDelete = 25
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

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

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:

toil.fileStores.FileID

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

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

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

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.

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

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

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

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

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

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

sharedFileOwnerID
statsFileOwnerID
readStatsFileOwnerID
class FileInfo(fileID, ownerID, encrypted, version=None, content=None, numContentChunks=0, checksum=None)

Bases: toil.jobStores.aws.utils.SDBHelper

Represents a file in this job store.

outer = None
Type:

AWSJobStore

property fileID
property ownerID
property version
property previousVersion
property content
property checksum
classmethod create(ownerID)
Parameters:

ownerID (str)

classmethod presenceIndicator()

The key that is guaranteed to be present in the return value of binaryToAttributes(). Assuming that binaryToAttributes() is used with SDB’s PutAttributes, the return value of this method could be used to detect the presence/absence of an item in SDB.

classmethod exists(jobStoreFileID)
classmethod load(jobStoreFileID)
classmethod loadOrCreate(jobStoreFileID, ownerID, encrypted)
classmethod loadOrFail(jobStoreFileID, customName=None)
Return type:

AWSJobStore.FileInfo

Returns:

an instance of this class representing the file with the given ID

Raises:

NoSuchFileException – if given file does not exist

classmethod fromItem(item)

Convert an SDB item to an instance of this class.

Parameters:

item (Item)

toItem()

Convert this instance to a dictionary of attribute names to values

Returns:

the attributes dict and an integer specifying the the number of chunk attributes in the dictionary that are used for storing inlined content.

Return type:

Tuple[Dict[str, str], int]

static maxInlinedSize()
save()
upload(localFilePath, calculateChecksum=True)
uploadStream(multipart=True, allowInlining=True, encoding=None, errors=None)

Context manager that gives out a binary or text mode upload stream to upload data.

copyFrom(srcObj)

Copies contents of source key into this file.

Parameters:

srcObj (S3.Object) – The key (object) that will be copied from

copyTo(dstObj)

Copies contents of this file to the given key.

Parameters:

dstObj (S3.Object) – The key (object) to copy this file’s content to

download(localFilePath, verifyChecksum=True)
downloadStream(verifyChecksum=True, encoding=None, errors=None)

Context manager that gives out a download stream to download data.

delete()
getSize()

Return the size of the referenced item in bytes.

__repr__()

Return repr(self).

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

toil.jobStores.aws.jobStore.aRepr
toil.jobStores.aws.jobStore.custom_repr
exception toil.jobStores.aws.jobStore.BucketLocationConflictException(bucketRegion)

Bases: toil.jobStores.abstractJobStore.LocatorException

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