Developer Guide

Parsl is a Parallel Scripting Library, designed to enable efficient workflow execution.

Importing

To get all the required functionality, we suggest importing the library as follows:

>>> import parsl
>>> from parsl import *

Logging

Following the general logging philosophy of python libraries, by default Parsl doesn’t log anything. However the following helper functions are provided for logging:

  1. set_stream_logger
    This sets the logger to the StreamHandler. This is quite useful when working from a Jupyter notebook.
  2. set_file_logger
    This sets the logging to a file. This is ideal for reporting issues to the dev team.
parsl.set_stream_logger(name='parsl', level=10, format_string=None)[source]

Add a stream log handler.

Args:
  • name (string) : Set the logger name.
  • level (logging.LEVEL) : Set to logging.DEBUG by default.
  • format_string (sting) : Set to None by default.
Returns:
  • None
parsl.set_file_logger(filename, name='parsl', level=10, format_string=None)[source]

Add a stream log handler.

Args:
  • filename (string): Name of the file to write logs to
  • name (string): Logger name
  • level (logging.LEVEL): Set the logging level.
  • format_string (string): Set the format string
Returns:
  • None

Apps

Apps are parallelized functions that execute independent of the control flow of the main python interpreter. We have two main types of Apps : PythonApps and BashApps. These are subclassed from AppBase.

AppBase

This is the base class that defines the two external facing functions that an App must define. The __init__ () which is called when the interpreter sees the definition of the decorated function, and the __call__ () which is invoked when a decorated function is called by the user.

class parsl.app.app.AppBase(func, executor=None, walltime=60, sites='all', cache=False, exec_type='bash')[source]

This is the base class that defines the two external facing functions that an App must define.

The __init__ () which is called when the interpreter sees the definition of the decorated function, and the __call__ () which is invoked when a decorated function is called by the user.

PythonApp

Concrete subclass of AppBase that implements the Python App functionality.

class parsl.app.python_app.PythonApp(func, executor=None, walltime=60, cache=False, sites='all', fn_hash=None)[source]

Extends AppBase to cover the Python App.

BashApp

Concrete subclass of AppBase that implements the Bash App functionality.

class parsl.app.bash_app.BashApp(func, executor=None, walltime=60, cache=False, sites='all', fn_hash=None)[source]

Futures

Futures are returned as proxies to a parallel execution initiated by a call to an App. We have two kinds of futures in Parsl: AppFutures and DataFutures.

AppFutures

class parsl.dataflow.futures.AppFuture(parent, tid=None, stdout=None, stderr=None)[source]

An AppFuture points at a Future returned from an Executor.

We are simply wrapping a AppFuture, and adding the specific case where, if the future is resolved i.e file exists, then the DataFuture is assumed to be resolved.

__init__(parent, tid=None, stdout=None, stderr=None)[source]

Initialize the AppFuture.

Args:
  • parent (Future) : The parent future if one exists A default value of None should be passed in if app is not launched
KWargs:
  • tid (Int) : Task id should be any unique identifier. Now Int.
  • stdout (str) : Stdout file of the app.
    Default: None
  • stderr (str) : Stderr file of the app.
    Default: None
done()[source]

Check if the future is done.

If a parent is set, we return the status of the parent. else, there is no parent assigned, meaning the status is False.

Returns:
  • True : If the future has successfully resolved.
  • False : Pending resolution
parent_callback(executor_fu)[source]

Callback from executor future to update the parent.

Args:
  • executor_fu (Future): Future returned by the executor along with callback
Returns:
  • None

Updates the super() with the result() or exception()

result(timeout=None)[source]

Result.

Waits for the result of the AppFuture KWargs:

timeout (int): Timeout in seconds
update_parent(fut)[source]

Add a callback to the parent to update the state.

This handles the case where the user has called result on the AppFuture before the parent exists.

DataFutures

class parsl.app.futures.DataFuture(fut, file_obj, parent=None, tid=None)[source]

A datafuture points at an AppFuture.

We are simply wrapping a AppFuture, and adding the specific case where, if the future is resolved i.e file exists, then the DataFuture is assumed to be resolved.

__init__(fut, file_obj, parent=None, tid=None)[source]

Construct the DataFuture object.

If the file_obj is a string convert to a File.

Args:
  • fut (AppFuture) : AppFuture that this DataFuture will track
  • file_obj (string/File obj) : Something representing file(s)
Kwargs:
  • parent ()
  • tid (task_id) : Task id that this DataFuture tracks
cancel()[source]

Cancel the task that this DataFuture is tracking.

Note: This may not work

filename[source]

Filepath of the File object this datafuture represents.

filepath[source]

Filepath of the File object this datafuture represents.

parent_callback(parent_fu)[source]

Callback from executor future to update the parent.

Args:
  • parent_fu (Future): Future returned by the executor along with callback
Returns:
  • None

Updates the super() with the result() or exception()

result(timeout=None)[source]

A blocking call that returns either the result or raises an exception.

Assumptions : A DataFuture always has a parent AppFuture. The AppFuture does callbacks when setup.

Kwargs:
  • timeout (int): Timeout in seconds
Returns:
  • If App completed successfully returns the filepath.
Raises:
  • Exception raised by app if failed.
tid[source]

Returns the task_id of the task that will resolve this DataFuture.

Exceptions

class parsl.app.errors.ParslError[source]

Base class for all exceptions.

Only to be invoked when a more specific error is not available.

class parsl.app.errors.NotFutureError[source]

A non future item was passed to a function that expected a future.

This is basically a type error.

class parsl.app.errors.InvalidAppTypeError[source]

An invalid app type was requested from the @App decorator.

class parsl.app.errors.AppException[source]

An error raised during execution of an app.

What this exception contains depends entirely on context

class parsl.app.errors.AppBadFormatting(reason, exitcode, retries=None)[source]

An error raised during formatting of a bash function.

What this exception contains depends entirely on context Contains: reason(string) exitcode(int) retries(int/None)

class parsl.app.errors.AppFailure(reason, exitcode, retries=None)[source]

An error raised during execution of an app.

What this exception contains depends entirely on context Contains: reason(string) exitcode(int) retries(int/None)

class parsl.app.errors.MissingOutputs(reason, outputs)[source]

Error raised at the end of app execution due to missing output files.

Contains: reason(string) outputs(List of strings/files..)

class parsl.app.errors.DependencyError(dependent_exceptions, reason, outputs)[source]

Error raised at the end of app execution due to missing output files.

Contains: reason(string) outputs(List of strings/files..)

class parsl.dataflow.error.DataFlowException[source]

Base class for all exceptions.

Only to be invoked when only a more specific error is not available.

class parsl.dataflow.error.DuplicateTaskError[source]

Raised by the DataFlowKernel when it finds that a job with the same task-id has been launched before.

class parsl.dataflow.error.MissingFutError[source]

Raised when a particular future is not found within the dataflowkernel’s datastructures.

Deprecated.

DataFlowKernel

class parsl.dataflow.dflow.DataFlowKernel(config=None, executors=None, lazyErrors=True, appCache=True, rundir=None, retries=0, checkpointFiles=None, checkpointMode=None, data_manager=None)[source]

The DataFlowKernel adds dependency awareness to an existing executor.

It is responsible for managing futures, such that when dependencies are resolved, pending tasks move to the runnable state.

Here’s a simplified diagram of what happens internally:

 User             |        DFK         |    Executor
----------------------------------------------------------
                  |                    |
       Task-------+> +Submit           |
     App_Fu<------+--|                 |
                  |  Dependencies met  |
                  |         task-------+--> +Submit
                  |        Ex_Fu<------+----|
__init__(config=None, executors=None, lazyErrors=True, appCache=True, rundir=None, retries=0, checkpointFiles=None, checkpointMode=None, data_manager=None)[source]

Initialize the DataFlowKernel.

Please note that keyword args passed to the DFK here will always override options passed in via the config.

KWargs:
  • config (dict): A single data object encapsulating all config attributes
  • executors (list of Executor objs): Optional, kept for (somewhat) backward compatibility with 0.2.0
  • lazyErrors(bool): Default=True, allow workflow to continue on app failures.
  • appCache (bool): Enable caching of apps
  • rundir (str): Path to run directory. Defaults to ./runinfo/runNNN
  • retries(int): Default=0, Set the number of retry attempts in case of failure
  • checkpointFiles (list of str): List of filepaths to checkpoint files
  • checkpointMode (None, ‘dfk_exit’, ‘task_exit’, ‘periodic’): Method to use.
  • data_manager (DataManager): User created DataManager
Returns:
DataFlowKernel object
__weakref__[source]

list of weak references to the object (if defined)

checkpoint(tasks=None)[source]

Checkpoint the dfk incrementally to a checkpoint file.

When called, every task that has been completed yet not checkpointed is checkpointed to a file.

Kwargs:
  • tasks (List of task ids) : List of task ids to checkpoint. Default=None
    if set to None, we iterate over all tasks held by the DFK.

Note

Checkpointing only works if memoization is enabled

Returns:
Checkpoint dir if checkpoints were written successfully. By default the checkpoints are written to the RUNDIR of the current run under RUNDIR/checkpoints/{tasks.pkl, dfk.pkl}
cleanup()[source]

DataFlowKernel cleanup.

This involves killing resources explicitly and sending die messages to IPP workers.

If the executors are managed, i.e created by the DFK
then : we scale_in each of the executors and call executor.shutdown else : we do nothing. Executor cleanup is left to the user.
config[source]

Returns the fully initialized config that the DFK is actively using.

DO NOT update.

Returns:
  • config (dict)
handle_update(task_id, future, memo_cbk=False)[source]

This function is called only as a callback from a task being done.

Move done task from runnable -> done Move newly doable tasks from pending -> runnable , and launch

Args:
task_id (string) : Task id which is a uuid string future (Future) : The future object corresponding to the task which makes this callback
KWargs:
memo_cbk(Bool) : Indicates that the call is coming from a memo update, that does not require additional memo updates.
launch_task(task_id, executable, *args, **kwargs)[source]

Handle the actual submission of the task to the executor layer.

If the app task has the sites attributes not set (default==’all’) the task is launched on a randomly selected executor from the list of executors. This behavior could later be updates to support binding to sites based on user specified criteria.

If the app task specifies a particular set of sites, it will be targetted at those specific sites.

Args:
task_id (uuid string) : A uuid string that uniquely identifies the task executable (callable) : A callable object args (list of positional args) kwargs (arbitrary keyword arguments)
Returns:
Future that tracks the execution of the submitted executable
load_checkpoints(checkpointDirs)[source]

Load checkpoints from the checkpoint files into a dictionary.

The results are used to pre-populate the memoizer’s lookup_table

Kwargs:
  • checkpointDirs (list) : List of run folder to use as checkpoints Eg. [‘runinfo/001’, ‘runinfo/002’]
Returns:
  • dict containing, hashed -> future mappings
static sanitize_and_wrap(task_id, args, kwargs)[source]

This function should be called ONLY when all the futures we track have been resolved.

If the user hid futures a level below, we will not catch it, and will (most likely) result in a type error .

Args:
task_id (uuid str) : Task id func (Function) : App function args (List) : Positional args to app function kwargs (Dict) : Kwargs to app function
Return:
partial Function evaluated with all dependencies in args, kwargs and kwargs[‘inputs’] evaluated.
submit(func, *args, parsl_sites='all', fn_hash=None, cache=False, **kwargs)[source]

Add task to the dataflow system.

>>> IF all deps are met:
>>>   send to the runnable queue and launch the task
>>> ELSE:
>>>   post the task in the pending queue
Args:
  • func : A function object
  • *args : Args to the function
KWargs :
  • parsl_sites (List|String) : List of sites this call could go to.
    Default=’all’
  • fn_hash (Str) : Hash of the function and inputs
    Default=None
  • cache (Bool) : To enable memoization or not
  • kwargs (dict) : Rest of the kwargs to the fn passed as dict.
Returns:
(AppFuture) [DataFutures,]

Executors

Executors are abstractions that represent available compute resources to which you could submit arbitrary App tasks. An executor initialized with an Execution Provider can dynamically scale with the resources requirements of the workflow.

We currently have thread pools for local execution, remote workers from ipyparallel for executing on high throughput systems such as campus clusters, and a Swift/T executor for HPC systems.

ParslExecutor (Abstract Base Class)

class parsl.executors.base.ParslExecutor[source]

Define the strict interface for all Executor classes.

This is a metaclass that only enforces concrete implementations of functionality by the child classes.

Note

Shutdown is currently missing, as it is not yet supported by some of the executors (threads, for example).

__init__[source]

Initialize self. See help(type(self)) for accurate signature.

scale_in(*args, **kwargs)[source]

Scale in method.

We should have the scale in method simply take resource object which will have the scaling methods, scale_in itself should be a coroutine, since scaling tasks can be slow.

scale_out(*args, **kwargs)[source]

Scale out method.

We should have the scale out method simply take resource object which will have the scaling methods, scale_out itself should be a coroutine, since scaling tasks can be slow.

scaling_enabled[source]

Specify if scaling is enabled.

The callers of ParslExecutors need to differentiate between Executors and Executors wrapped in a resource provider

submit(*args, **kwargs)[source]

Submit.

We haven’t yet decided on what the args to this can be, whether it should just be func, args, kwargs or be the partially evaluated fn

ThreadPoolExecutor

class parsl.executors.threads.ThreadPoolExecutor(max_workers=2, thread_name_prefix='', execution_provider=None, config=None, **kwargs)[source]

The thread pool executor.

__init__(max_workers=2, thread_name_prefix='', execution_provider=None, config=None, **kwargs)[source]

Initialize the thread pool.

Config options that are really used are :

config.sites.site.execution.options = {“maxThreads” : <int>,
“threadNamePrefix” : <string>}
Kwargs:
  • max_workers (int) : Number of threads (Default=2) (keeping name workers/threads for backward compatibility)
  • thread_name_prefix (string) : Thread name prefix (Only supported in python v3.6+
  • execution_provider (ep object) : This is ignored here
  • config (dict): The config dict object for the site:
scale_in(workers=1)[source]

Scale in the number of active workers by 1.

This method is notImplemented for threads and will raise the error if called.

Raises:
NotImplemented exception
scale_out(workers=1)[source]

Scales out the number of active workers by 1.

This method is notImplemented for threads and will raise the error if called.

Raises:
NotImplemented exception
submit(*args, **kwargs)[source]

Submits work to the thread pool.

This method is simply pass through and behaves like a submit call as described here Python docs:

Returns:
Future

IPyParallelExecutor

class parsl.executors.ipp.IPyParallelExecutor(execution_provider=None, reuse_controller=True, engine_json_file='~/.ipython/profile_default/security/ipcontroller-engine.json', engine_dir='.', controller=None, config=None)[source]

The IPython Parallel executor.

This executor allows us to take advantage of multiple processes running locally or remotely via IPythonParallel’s pilot execution system.

Note

Some deficiencies with this executor are:

  1. Ipengine’s execute one task at a time. This means one engine per core is necessary to exploit the full parallelism of a node.
  2. No notion of remaining walltime.
  3. Lack of throttling means tasks could be queued up on a worker.
__init__(execution_provider=None, reuse_controller=True, engine_json_file='~/.ipython/profile_default/security/ipcontroller-engine.json', engine_dir='.', controller=None, config=None)[source]

Initialize the IPyParallel pool. The initialization takes all relevant parameters via KWargs.

Note

If initBlocks > 0, and a scalable execution_provider is attached, then the provider will be initialized here.

Args:
  • self
KWargs:
  • execution_provider (ExecutionProvider object)
  • reuse_controller (Bool) : If True ipp executor will attempt to connect to an available controller. Default: True
  • engine_json_file (str): Path to json engine file that will be used to compose ipp launch commands at scaling events. Default : ‘~/.ipython/profile_default/security/ipcontroller-engine.json’
  • engine_dir (str) : Alternative to above, specify the engine_dir
  • config (dict). Default: ‘.’
compose_launch_cmd(filepath, engine_dir, container_image)[source]

Reads the json contents from filepath and uses that to compose the engine launch command.

Args:
filepath: Path to the engine file engine_dir : CWD for the engines .
scale_in(blocks, *args, **kwargs)[source]

Scale in the number of active workers by 1.

This method is notImplemented for threads and will raise the error if called.

Raises:
NotImplemented exception
scale_out(*args, **kwargs)[source]

Scales out the number of active workers by 1.

This method is notImplemented for threads and will raise the error if called.

submit(*args, **kwargs)[source]

Submits work to the thread pool.

This method is simply pass through and behaves like a submit call as described here Python docs:

Returns:
Future

Swift/Turbine Executor

class parsl.executors.swift_t.TurbineExecutor(swift_attribs=None, config=None, **kwargs)[source]

The Turbine executor.

Bypass the Swift/T language and run on top off the Turbine engines in an MPI environment.

Here is a diagram

             |  Data   |  Executor   |   IPC      | External Process(es)
             |  Flow   |             |            |
        Task | Kernel  |             |            |
      +----->|-------->|------------>|outgoing_q -|-> Worker_Process
      |      |         |             |            |    |         |
Parsl<---Fut-|         |             |            |  result   exception
          ^  |         |             |            |    |         |
          |  |         |   Q_mngmnt  |            |    V         V
          |  |         |    Thread<--|incoming_q<-|--- +---------+
          |  |         |      |      |            |
          |  |         |      |      |            |
          +----update_fut-----+
__init__(swift_attribs=None, config=None, **kwargs)[source]

Initialize the thread pool.

Trying to implement the emews model.

Kwargs:
  • swift_attribs : Takes a dict of swift attribs. Fot future.
_queue_management_worker()[source]

Listen to the queue for task status messages and handle them.

Depending on the message, tasks will be updated with results, exceptions, or updates. It expects the following messages:

{
   "task_id" : <task_id>
   "result"  : serialized result object, if task succeeded
   ... more tags could be added later
}

{
   "task_id" : <task_id>
   "exception" : serialized exception object, on failure
}

We do not support these yet, but they could be added easily.

{
   "task_id" : <task_id>
   "cpu_stat" : <>
   "mem_stat" : <>
   "io_stat"  : <>
   "started"  : tstamp
}

The None message is a die request.

_start_queue_management_thread()[source]

Method to start the management thread as a daemon.

Checks if a thread already exists, then starts it. Could be used later as a restart if the management thread dies.

scale_in(workers=1)[source]

Scale in the number of active workers by 1.

This method is notImplemented for threads and will raise the error if called.

Raises:
NotImplementedError
scale_out(workers=1)[source]

Scales out the number of active workers by 1.

This method is not implemented for threads and will raise the error if called. This would be nice to have, and can be done

Raises:
NotImplementedError
shutdown()[source]

Shutdown method, to kill the threads and workers.

submit(func, *args, **kwargs)[source]

Submits work to the the outgoing_q.

The outgoing_q is an external process listens on this queue for new work. This method is simply pass through and behaves like a submit call as described here Python docs:

Args:
  • func (callable) : Callable function
  • *args (list) : List of arbitrary positional arguments.
Kwargs:
  • **kwargs (dict) : A dictionary of arbitrary keyword args for func.
Returns:
Future
parsl.executors.swift_t.runner(incoming_q, outgoing_q)[source]

This is a function that mocks the Swift-T side.

It listens on the the incoming_q for tasks and posts returns on the outgoing_q.

Args:
  • incoming_q (Queue object) : The queue to listen on
  • outgoing_q (Queue object) : Queue to post results on

The messages posted on the incoming_q will be of the form :

{
   "task_id" : <uuid.uuid4 string>,
   "buffer"  : serialized buffer containing the fn, args and kwargs
}

If None is received, the runner will exit.

Response messages should be of the form:

{
   "task_id" : <uuid.uuid4 string>,
   "result"  : serialized buffer containing result
   "exception" : serialized exception object
}

On exiting the runner will post None to the outgoing_q

Execution Providers

Execution providers are responsible for managing execution resources that have a Local Resource Manager (LRM). For instance, campus clusters and supercomputers generally have LRMs (schedulers) such as Slurm, Torque/PBS, Condor and Cobalt. Clouds, on the other hand, have API interfaces that allow much more fine-grained composition of an execution environment. An execution provider abstracts these types of resources and provides a single uniform interface to them.

ExecutionProvider (Base)

class libsubmit.providers.provider_base.ExecutionProvider[source]

Define the strict interface for all Execution Provider

                      +------------------
                      |
script_string ------->|  submit
     id      <--------|---+
                      |
[ ids ]       ------->|  status
[statuses]   <--------|----+
                      |
[ ids ]       ------->|  cancel
[cancel]     <--------|----+
                      |
[True/False] <--------|  scaling_enabled
                      |
                      +-------------------
__weakref__[source]

list of weak references to the object (if defined)

cancel(job_ids)[source]

Cancels the resources identified by the job_ids provided by the user.

Args:
  • job_ids (list): A list of job identifiers
Returns:
  • A list of status from cancelling the job which can be True, False
Raises:
  • ExecutionProviderExceptions or its subclasses
channels_required[source]

Does the execution provider require a channel to function. Generally all Cloud api’s require no channels while all bash script based systems such as schedulers for campus clusters (slurm, torque, cobalt, condor..) need channels

Returns:
  • Status (Bool)
scaling_enabled[source]

The callers of ParslExecutors need to differentiate between Executors and Executors wrapped in a resource provider

Returns:
  • Status (Bool)
status(job_ids)[source]

Get the status of a list of jobs identified by the job identifiers returned from the submit request.

Args:
  • job_ids (list) : A list of job identifiers
Returns:
  • A list of status from [‘PENDING’, ‘RUNNING’, ‘CANCELLED’, ‘COMPLETED’, ‘FAILED’, ‘TIMEOUT’] corresponding to each job_id in the job_ids list.
Raises:
  • ExecutionProviderExceptions or its subclasses
submit(cmd_string, blocksize, job_name='parsl.auto')[source]

The submit method takes the command string to be executed upon instantiation of a resource most often to start a pilot (such as IPP engine or even Swift-T engines).

Args :
  • cmd_string (str) : The bash command string to be executed.
  • blocksize (int) : Blocksize to be requested
KWargs:
  • job_name (str) : Human friendly name to be assigned to the job request
Returns:
  • A job identifier, this could be an integer, string etc
Raises:
  • ExecutionProviderExceptions or its subclasses

Local

class libsubmit.providers.local.local.Local(config, channel_script_dir=None, channel=None)[source]

Local Execution Provider

This provider is used to launch IPP engines on the localhost.

Warning

Please note that in the config documented below, description and values are placed inside a schema that is delimited by #{ schema.. }

Here’s the scheme for the Local provider:

{ "execution" : { # Definition of all execution aspects of a site

     "executor"   : #{Description: Define the executor used as task executor,
                    # Type : String,
                    # Expected : "ipp",
                    # Required : True},

     "provider"   : #{Description : The provider name, in this case local
                    # Type : String,
                    # Expected : "local",
                    # Required :  True },

     "scriptDir"  : #{Description : Relative or absolute path to a
                    # directory in which intermediate scripts are placed
                    # Type : String,
                    # Default : "./.scripts"},

     "block" : { # Definition of a block

         "initBlocks" : #{Description : # of blocks to provision at the start of
                        # the DFK
                        # Type : Integer
                        # Default : ?
                        # Required :    },

         "minBlocks" :  #{Description : Minimum # of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : 0 },

         "maxBlocks" :  #{Description : Maximum # Of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : ? },
     }
   }
}
__init__(config, channel_script_dir=None, channel=None)[source]

Initialize the local provider class

Args:
  • Config (dict): Dictionary with all the config options.
cancel(job_ids)[source]

Cancels the jobs specified by a list of job ids

Args: job_ids : [<job_id> …]

Returns : [True/False…] : If the cancel operation fails the entire list will be False.

status(job_ids)[source]

Get the status of a list of jobs identified by their ids.

Args:
  • job_ids (List of ids) : List of identifiers for the jobs
Returns:
  • List of status codes.
submit(cmd_string, blocksize, job_name='parsl.auto')[source]

Submits the cmd_string onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted.

If tasks_per_node < 1:
1/tasks_per_node is provisioned
If tasks_per_node == 1:
A single node is provisioned
If tasks_per_node > 1 :
tasks_per_node * blocksize number of nodes are provisioned.
Args:
  • cmd_string :(String) Commandline invocation to be made on the remote side.
  • blocksize :(float) - Not really used for local
Kwargs:
  • job_name (String): Name for job, must be unique
Returns:
  • None: At capacity, cannot provision more
  • job_id: (string) Identifier for the job

Slurm

class libsubmit.providers.slurm.slurm.Slurm(config, channel=None)[source]

Slurm Execution Provider

This provider uses sbatch to submit, squeue for status and scancel to cancel jobs. The sbatch script to be used is created from a template file in this same module.

Warning

Please note that in the config documented below, description and values are placed inside a schema that is delimited by <{ schema.. }>

Here’s a sample config for the Slurm provider:

{ "execution" : { # Definition of all execution aspects of a site

     "executor"   : #{Description: Define the executor used as task executor,
                    # Type : String,
                    # Expected : "ipp",
                    # Required : True},

     "provider"   : #{Description : The provider name, in this case slurm
                    # Type : String,
                    # Expected : "slurm",
                    # Required :  True },

     "scriptDir"  : #{Description : Relative or absolute path to a
                    # directory in which intermediate scripts are placed
                    # Type : String,
                    # Default : "./.scripts"},

     "block" : { # Definition of a block

         "nodes"      : #{Description : # of nodes to provision per block
                        # Type : Integer,
                        # Default: 1},

         "taskBlocks" : #{Description : # of workers to launch per block
                        # as either an number or as a bash expression.
                        # for eg, "1" , "$(($CORES / 2))"
                        # Type : String,
                        #  Default: "1" },

         "walltime"  :  #{Description : Walltime requested per block in HH:MM:SS
                        # Type : String,
                        # Default : "00:20:00" },

         "initBlocks" : #{Description : # of blocks to provision at the start of
                        # the DFK
                        # Type : Integer
                        # Default : ?
                        # Required :    },

         "minBlocks" :  #{Description : Minimum # of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : 0 },

         "maxBlocks" :  #{Description : Maximum # Of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : ? },

         "options"   : {  # Scheduler specific options

             "partition" : #{Description : Slurm partition to request blocks from
                           # Type : String,
                           # Required : True },

             "overrides" : #{"Description : String to append to the #SBATCH blocks
                           # in the submit script to the scheduler
                           # Type : String,
                           # Required : False },
         }
     }
   }
}
__init__(config, channel=None)[source]

Initialize the Slurm class

Args:
  • Config (dict): Dictionary with all the config options.
KWargs:
  • Channel (None): A channel is required for slurm.
cancel(job_ids)[source]

Cancels the jobs specified by a list of job ids

Args: job_ids : [<job_id> …]

Returns : [True/False…] : If the cancel operation fails the entire list will be False.

channels_required[source]

Returns Bool on whether a channel is required

current_capacity[source]

Returns the current blocksize. This may need to return more information in the futures : { minsize, maxsize, current_requested }

status(job_ids)[source]

Get the status of a list of jobs identified by their ids.

Args:
  • job_ids (List of ids) : List of identifiers for the jobs
Returns:
  • List of status codes.
submit(cmd_string, blocksize, job_name='parsl.auto')[source]

Submits the cmd_string onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted.

If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be integer

If tasks_per_node == 1:
A single node is provisioned
If tasks_per_node > 1 :
tasks_per_node * blocksize number of nodes are provisioned.
Args:
  • cmd_string :(String) Commandline invocation to be made on the remote side.
  • blocksize :(float)
Kwargs:
  • job_name (String): Name for job, must be unique
Returns:
  • None: At capacity, cannot provision more
  • job_id: (string) Identifier for the job

Cobalt

class libsubmit.providers.cobalt.cobalt.Cobalt(config, channel=None)[source]

Cobalt Execution Provider

This provider uses cobalt to submit (qsub), obtain the status of (qstat), and cancel (qdel) jobs. Theo script to be used is created from a template file in this same module.

Warning

Please note that in the config documented below, description and values are placed inside a schema that is delimited by #{ schema.. }

Here’s the scheme for the Cobalt provider:

{ "execution" : { # Definition of all execution aspects of a site

     "executor"   : #{Description: Define the executor used as task executor,
                    # Type : String,
                    # Expected : "ipp",
                    # Required : True},

     "provider"   : #{Description : The provider name, in this case cobalt
                    # Type : String,
                    # Expected : "cobalt",
                    # Required :  True },

     "launcher"   : #{Description : Launcher to use for launching workers
                    # it is often necessary to use a launcher that the scheduler supports to
                    # launch workers on multi-node jobs, or to partition MPI jobs
                    # Type : String,
                    # Default : "singleNode" },

     "scriptDir"  : #{Description : Relative or absolute path to a
                    # directory in which intermediate scripts are placed
                    # Type : String,
                    # Default : "./.scripts"},

     "block" : { # Definition of a block

         "nodes"      : #{Description : # of nodes to provision per block
                        # Type : Integer,
                        # Default: 1},

         "taskBlocks" : #{Description : # of workers to launch per block
                        # as either an number or as a bash expression.
                        # for eg, "1" , "$(($CORES / 2))"
                        # Type : String,
                        #  Default: "1" },

         "walltime"  :  #{Description : Walltime requested per block in HH:MM:SS
                        # Type : String,
                        # Default : "01:00:00" },

         "initBlocks" : #{Description : # of blocks to provision at the start of
                        # the DFK
                        # Type : Integer
                        # Default : ?
                        # Required :    },

         "minBlocks" :  #{Description : Minimum # of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : 0 },

         "maxBlocks" :  #{Description : Maximum # Of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : ? },

         "options"   : {  # Scheduler specific options

             "account"   : #{Description : Account that the job will be charged against
                           # Type : String,
                           # Required : True },

             "queue"     : #{Description : Torque queue to request blocks from
                           # Type : String,
                           # Required : False },

             "overrides" : #{"Description : String to append to the Torque submit script
                           # in the submit script to the scheduler
                           # Type : String,
                           # Required : False },
         }
     }
   }
}
__init__(config, channel=None)[source]

Initialize the Cobalt execution provider class

Args:
  • Config (dict): Dictionary with all the config options.
KWargs :
  • channel (channel object) : default=None A channel object
cancel(job_ids)[source]

Cancels the jobs specified by a list of job ids

Args: job_ids : [<job_id> …]

Returns : [True/False…] : If the cancel operation fails the entire list will be False.

channels_required[source]

Returns Bool on whether a channel is required

status(job_ids)[source]

Get the status of a list of jobs identified by their ids.

Args:
  • job_ids (List of ids) : List of identifiers for the jobs
Returns:
  • List of status codes.
submit(cmd_string, blocksize, job_name='parsl.auto')[source]

Submits the cmd_string onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted.

If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be integer

If tasks_per_node == 1:
A single node is provisioned
If tasks_per_node > 1 :
tasks_per_node * blocksize number of nodes are provisioned.
Args:
  • cmd_string :(String) Commandline invocation to be made on the remote side.
  • blocksize :(float)
Kwargs:
  • job_name (String): Name for job, must be unique
Returns:
  • None: At capacity, cannot provision more
  • job_id: (string) Identifier for the job

Condor

class libsubmit.providers.condor.condor.Condor(config, channel=None)[source]

Condor Execution Provider

Warning

Please note that in the config documented below, description and values are placed inside a schema that is delimited by #{ schema.. }

Here’s the schema for the Condor provider:

{ "execution" : { # Definition of all execution aspects of a site

     "executor"   : #{Description: Define the executor used as task executor,
                    # Type : String,
                    # Expected : "ipp",
                    # Required : True},

     "provider"   : #{Description : The provider name, in this case condor
                    # Type : String,
                    # Expected : "condor",
                    # Required :  True },

     "launcher"   : #{Description : Launcher to use for launching workers
                    # Since condor doesn't generally do multi-node, "singleNode" is the
                    # only meaningful launcher.
                    # Type : String,
                    # Default : "singleNode" },

     "scriptDir"  : #{Description : Relative or absolute path to a
                    # directory in which intermediate scripts are placed
                    # Type : String,
                    # Default : "./.scripts"},

     "block" : { # Definition of a block

         "nodes"      : #{Description : # of nodes to provision per block
                        # Type : Integer,
                        # Default: 1},

         "taskBlocks" : #{Description : # of workers to launch per block
                        # as either an number or as a bash expression.
                        # for eg, "1" , "$(($CORES / 2))"
                        # Type : String,
                        #  Default: "1" },

         "walltime"  :  #{Description : Walltime requested per block in HH:MM:SS
                        # Type : String,
                        # Default : "01:00:00" },

         "initBlocks" : #{Description : # of blocks to provision at the start of
                        # the DFK
                        # Type : Integer
                        # Default : ?
                        # Required :    },

         "minBlocks" :  #{Description : Minimum # of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : 0 },

         "maxBlocks" :  #{Description : Maximum # Of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : ? },

         "options"   : {  # Scheduler specific options

             "project"    : #{Description : Project to which the job will be charged against
                            # Type : String,
                            # Required : True },

             "overrides"  : #{"Description : String to add specific condor attributes to the
                            # Condor submit script
                            # Type : String,
                            # Required : False },

             "workerSetup": #{"Description : String that sets up the env for the workers as well
                            # apps to run
                            # Type : String,
                            # Required : False },

             "requirements": #{"Description : Condor requirements
                             # Type : String,
                             # Required : True },
         }
     }
   }
}
__init__(config, channel=None)[source]

Initialize the Condor class

Args:
  • Config (dict): Dictionary with all the config options.
KWargs:
  • Channel (none): A channel is required for htcondor.
cancel(job_ids)[source]

Cancels the jobs specified by a list of job ids

Args: job_ids : [<job_id> …]

Returns : [True/False…] : If the cancel operation fails the entire list will be False.

channels_required[source]

Returns Bool on whether a channel is required

status(job_ids)[source]

Get the status of a list of jobs identified by their ids.

Args:
  • job_ids (List of ids) : List of identifiers for the jobs
Returns:
  • List of status codes.
submit(cmd_string, blocksize, job_name='parsl.auto')[source]

Submits the cmd_string onto an Local Resource Manager job of blocksize parallel elements.

example file with the complex case of multiple submits per job:
Universe =vanilla output = out.$(Cluster).$(Process) error = err.$(Cluster).$(Process) log = log.$(Cluster) leave_in_queue = true executable = test.sh queue 5 executable = foo queue 1

$ condor_submit test.sub Submitting job(s)…… 5 job(s) submitted to cluster 118907. 1 job(s) submitted to cluster 118908.

Torque

class libsubmit.providers.torque.torque.Torque(config, channel=None)[source]

Torque Execution Provider

This provider uses sbatch to submit, squeue for status, and scancel to cancel jobs. The sbatch script to be used is created from a template file in this same module.

Warning

Please note that in the config documented below, description and values are placed inside a schema that is delimited by #{ schema.. }

Here’s the scheme for the Torque provider:

{ "execution" : { # Definition of all execution aspects of a site

     "executor"   : #{Description: Define the executor used as task executor,
                    # Type : String,
                    # Expected : "ipp",
                    # Required : True},

     "provider"   : #{Description : The provider name, in this case torque
                    # Type : String,
                    # Expected : "torque",
                    # Required :  True },

     "scriptDir"  : #{Description : Relative or absolute path to a
                    # directory in which intermediate scripts are placed
                    # Type : String,
                    # Default : "./scripts"},

     "block" : { # Definition of a block

         "nodes"      : #{Description : # of nodes to provision per block
                        # Type : Integer,
                        # Default: 1},

         "taskBlocks" : #{Description : # of workers to launch per block
                        # as either an number or as a bash expression.
                        # for eg, "1" , "$(($CORES / 2))"
                        # Type : String,
                        #  Default: "1" },

         "walltime"  :  #{Description : Walltime requested per block in HH:MM:SS
                        # Type : String,
                        # Default : "00:20:00" },

         "initBlocks" : #{Description : # of blocks to provision at the start of
                        # the DFK
                        # Type : Integer
                        # Default : ?
                        # Required :    },

         "minBlocks" :  #{Description : Minimum # of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : 0 },

         "maxBlocks" :  #{Description : Maximum # Of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : ? },

         "options"   : {  # Scheduler specific options

             "account"   : #{Description : Account the job will be charged against
                           # Type : String,
                           # Required : True },

             "queue"     : #{Description : Torque queue to request blocks from
                           # Type : String,
                           # Required : False },

             "overrides" : #{"Description : String to append to the Torque submit script
                           # in the submit script to the scheduler
                           # Type : String,
                           # Required : False },
         }
     }
   }
}
__init__(config, channel=None)[source]

Initialize the Torque class

Args:
  • Config (dict): Dictionary with all the config options.
KWargs:
  • Channel (None): A channel is required for torque.
cancel(job_ids)[source]

Cancels the jobs specified by a list of job ids

Args: job_ids : [<job_id> …]

Returns : [True/False…] : If the cancel operation fails the entire list will be False.

channels_required[source]

Returns Bool on whether a channel is required

current_capacity[source]

Returns the current blocksize. This may need to return more information in the futures : { minsize, maxsize, current_requested }

status(job_ids)[source]

Get the status of a list of jobs identified by their ids.

Args:
  • job_ids (List of ids) : List of identifiers for the jobs
Returns:
  • List of status codes.
submit(cmd_string, blocksize, job_name='parsl.auto')[source]

Submits the cmd_string onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted.

If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be integer

If tasks_per_node == 1:
A single node is provisioned
If tasks_per_node > 1 :
tasks_per_node * blocksize number of nodes are provisioned.
Args:
  • cmd_string :(String) Commandline invocation to be made on the remote side.
  • blocksize :(float)
Kwargs:
  • job_name (String): Name for job, must be unique
Returns:
  • None: At capacity, cannot provision more
  • job_id: (string) Identifier for the job

GridEngine

Amazon Web Services

class libsubmit.providers.aws.aws.EC2Provider(config, channel=None)[source]

Here’s a sample config for the EC2 provider:

{ "auth" : { # Definition of authentication method for AWS. One of 3 methods are required to authenticate
             # with AWS : keyfile, profile or env_variables. If keyfile or profile is not set Boto3 will
             # look for the following env variables :
             # AWS_ACCESS_KEY_ID : The access key for your AWS account.
             # AWS_SECRET_ACCESS_KEY : The secret key for your AWS account.
             # AWS_SESSION_TOKEN : The session key for your AWS account.

     "keyfile"    : #{Description: Path to json file that contains 'AWSAccessKeyId' and 'AWSSecretKey'
                    # Type : String,
                    # Required : False},

     "profile"    : #{Description: Specify the profile to be used from the standard aws config file
                    # ~/.aws/config.
                    # Type : String,
                    # Expected : "default", # Use the 'default' aws profile
                    # Required : False},

   },

  "execution" : { # Definition of all execution aspects of a site

     "executor"   : #{Description: Define the executor used as task executor,
                    # Type : String,
                    # Expected : "ipp",
                    # Required : True},

     "provider"   : #{Description : The provider name, in this case ec2
                    # Type : String,
                    # Expected : "aws",
                    # Required :  True },

     "block" : { # Definition of a block

         "nodes"      : #{Description : # of nodes to provision per block
                        # Type : Integer,
                        # Default: 1},

         "taskBlocks" : #{Description : # of workers to launch per block
                        # as either an number or as a bash expression.
                        # for eg, "1" , "$(($CORES / 2))"
                        # Type : String,
                        #  Default: "1" },

         "walltime"  :  #{Description : Walltime requested per block in HH:MM:SS
                        # Type : String,
                        # Default : "00:20:00" },

         "initBlocks" : #{Description : # of blocks to provision at the start of
                        # the DFK
                        # Type : Integer
                        # Default : ?
                        # Required :    },

         "minBlocks" :  #{Description : Minimum # of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : 0 },

         "maxBlocks" :  #{Description : Maximum # Of blocks outstanding at any time
                        # WARNING :: Not Implemented
                        # Type : Integer
                        # Default : ? },

         "options"   : {  # Scheduler specific options


             "instanceType" : #{Description : Instance type t2.small|t2...
                              # Type : String,
                              # Required : False
                              # Default : t2.small },

             "imageId"      : #{"Description : String to append to the #SBATCH blocks
                              # in the submit script to the scheduler
                              # Type : String,
                              # Required : False },

             "region"       : #{"Description : AWS region to launch machines in
                              # in the submit script to the scheduler
                              # Type : String,
                              # Default : 'us-east-2',
                              # Required : False },

             "keyName"      : #{"Description : Name of the AWS private key (.pem file)
                              # that is usually generated on the console to allow ssh access
                              # to the EC2 instances, mostly for debugging.
                              # in the submit script to the scheduler
                              # Type : String,
                              # Required : True },

             "spotMaxBid"   : #{"Description : If requesting spot market machines, specify
                              # the max Bid price.
                              # Type : Float,
                              # Required : False },
         }
     }
   }
}
__init__(config, channel=None)[source]

Initialize the EC2Provider class

Args:
  • Config (dict): Dictionary with all the config options.
KWargs:
  • Channel (None): A channel is not required for EC2.
cancel(job_ids)[source]

Cancels the jobs specified by a list of job ids

Args:
job_ids (list) : List of of job identifiers
Returns :
[True/False…] : If the cancel operation fails the entire list will be False.
config_route_table(vpc, internet_gateway)[source]

Configure route table for vpc

[TODO] Args:

  • vpc (type) : ?
  • vpc (type) : ?
create_session()[source]

Here we will first look in the ~/.aws/config file.

First we look in config[“auth”][“keyfile”] for a path to a json file with the credentials. the keyfile should have ‘AWSAccessKeyId’ and ‘AWSSecretKey’

Next we look for config[“auth”][“profile”] for a profile name and try to use the Session call to auto pick up the keys for the profile from the user default keys file ~/.aws/config.

Lastly boto3 will look for the keys in env variables: AWS_ACCESS_KEY_ID : The access key for your AWS account. AWS_SECRET_ACCESS_KEY : The secret key for your AWS account. AWS_SESSION_TOKEN : The session key for your AWS account. This is only needed when you are using temporary credentials. The AWS_SECURITY_TOKEN environment variable can also be used, but is only supported for backwards compatibility purposes. AWS_SESSION_TOKEN is supported by multiple AWS SDKs besides python.

create_vpc()[source]

Create and configure VPC [TODO] Describe this a bit more …

current_capacity[source]

Returns the current blocksize. This may need to return more information in the futures : { minsize, maxsize, current_requested }

get_instance_state(instances=None)[source]

Get stateus of all instances on EC2 which were started by this file

initialize_boto_client()[source]

Use auth configs to initialize the boto client

pretty_configs(configs)[source]

prettyprint config

read_configs(config_file)[source]

Read config file

read_state_file(statefile)[source]

If this script has been run previously, it will be persisitent by writing resource ids to state file. On run, the script looks for a state file before creating new infrastructure

scale_in(size)[source]

Scale cluster in (smaller)

security_group(vpc)[source]

Create and configure security group. Allows all ICMP in, all tcp and udp in within vpc

TODO : Open up only the necessary port ranges.

show_summary()[source]

Print human readable summary of current AWS state to log and to console

shut_down_instance(instances=None)[source]

Shuts down a list of instances if provided or the last instance started up if none provided

[TODO] …

spin_up_instance(cmd_string, job_name)[source]

Starts an instance in the vpc in first available subnet. Starts up n instances if nodes per block > 1 Not supported. We only do 1 node per block

Args:
  • cmd_string (str) : Command string to execute on the node
  • job_name (str) : Name associated with the instances
status(job_ids)[source]

Get the status of a list of jobs identified by their ids.

Args:
  • job_ids (List of ids) : List of identifiers for the jobs
Returns:
  • List of status codes.
submit(cmd_string='sleep 1', blocksize=1, job_name='parsl.auto')[source]

Submits the cmd_string onto a freshly instantiates AWS EC2 instance. Submit returns an ID that corresponds to the task that was just submitted.

Args:
  • cmd_string (str): Commandline invocation to be made on the remote side.
  • blocksize (int) : Number of blocks requested
Kwargs:
  • job_name (String): Prefix for job name
Returns:
  • None: At capacity, cannot provision more
  • job_id: (string) Identifier for the job
teardown()[source]

Terminate all EC2 instances, delete all subnets, delete security group, delete vpc and reset all instance variables

Azure

class libsubmit.providers.azure.azureProvider.AzureProvider(config)[source]
__init__(config)[source]

Initialize Azure provider. Uses Azure python SDK to provide execution resources

cancel()[source]

Destroy an azure VM

status()[source]

Get status of azure VM. Not implemented yet.

submit()[source]

Uses AzureDeployer to spin up an instance and connect it to the iPyParallel controller

Google Cloud Platform

Channels

For certain resources such as campus clusters or supercomputers at research laboratories, resource requirements may require authentication. For instance, some resources may allow access to their job schedulers from only their login-nodes, which require you to authenticate on through SSH, GSI-SSH and sometimes even require two-factor authentication. Channels are simple abstractions that enable the ExecutionProvider component to talk to the resource managers of compute facilities. The simplest Channel, LocalChannel, simply executes commands locally on a shell, while the SshChannel authenticates you to remote systems.

class libsubmit.channels.channel_base.Channel[source]

Define the interface to all channels. Channels are usually called via the execute_wait function. For channels that execute remotely, a push_file function allows you to copy over files.

                      +------------------
                      |
cmd, wtime    ------->|  execute_wait
(ec, stdout, stderr)<-|---+
                      |
cmd, wtime    ------->|  execute_no_wait
(ec, stdout, stderr)<-|---+
                      |
src, dst_dir  ------->|  push_file
   dst_path  <--------|----+
                      |
dst_script_dir <------|  script_dir
                      |
                      +-------------------
__weakref__[source]

list of weak references to the object (if defined)

close()[source]

Closes the channel. Clean out any auth credentials.

Args:
None
Returns:
Bool
execute_no_wait(cmd, walltime, *args, **kwargs)[source]

Optional. THis is infrequently used.

Args:
  • cmd (string): Command string to execute over the channel
  • walltime (int) : Timeout in seconds
Returns:
  • (exit_code(None), stdout, stderr) (int, io_thing, io_thing)
execute_wait(cmd, walltime, *args, **kwargs)[source]

Executes the cmd, with a defined walltime.

Args:
  • cmd (string): Command string to execute over the channel
  • walltime (int) : Timeout in seconds
Returns:
  • (exit_code, stdout, stderr) (int, string, string)
push_file(source, dest_dir)[source]

Channel will take care of moving the file from source to the destination directory

Args:
source (string) : Full filepath of the file to be moved dest_dir (string) : Absolute path of the directory to move to
Returns:
destination_path (string)
script_dir[source]

This is a property. Returns the directory assigned for storing all internal scripts such as scheduler submit scripts. This is usually where error logs from the scheduler would reside on the channel destination side.

Args:
  • None
Returns:
  • Channel script dir

LocalChannel

class libsubmit.channels.local.local.LocalChannel(userhome='.', envs={}, scriptDir='./.scripts', **kwargs)[source]

This is not even really a channel, since opening a local shell is not heavy and done so infrequently that they do not need a persistent channel

__init__(userhome='.', envs={}, scriptDir='./.scripts', **kwargs)[source]

Initialize the local channel. scriptDir is required by set to a default.

KwArgs:
  • userhome (string): (default=’.’) This is provided as a way to override and set a specific userhome
  • envs (dict) : A dictionary of env variables to be set when launching the shell
  • channel_script_dir (string): (default=”./.scripts”) Directory to place scripts
close()[source]

There’s nothing to close here, and this really doesn’t do anything

Returns:
  • False, because it really did not “close” this channel.
execute_no_wait(cmd, walltime)[source]

Synchronously execute a commandline string on the shell.

Args:
  • cmd (string) : Commandline string to execute
  • walltime (int) : walltime in seconds, this is not really used now.

Returns:

  • retcode : Return code from the execution, -1 on fail
  • stdout : stdout string
  • stderr : stderr string
Raises:
None.
execute_wait(cmd, walltime)[source]

Synchronously execute a commandline string on the shell.

Args:
  • cmd (string) : Commandline string to execute
  • walltime (int) : walltime in seconds, this is not really used now.
Returns:
  • retcode : Return code from the execution, -1 on fail
  • stdout : stdout string
  • stderr : stderr string

Raises: None.

push_file(source, dest_dir)[source]

If the source files dirpath is the same as dest_dir, a copy is not necessary, and nothing is done. Else a copy is made.

Args:
  • source (string) : Path to the source file
  • dest_dir (string) : Path to the directory to which the files is to be copied
Returns:
  • destination_path (String) : Absolute path of the destination file
Raises:
  • FileCopyException : If file copy failed.

SshChannel

class libsubmit.channels.ssh.ssh.SshChannel(hostname, username=None, password=None, scriptDir=None, **kwargs)[source]

Ssh persistent channel. This enables remote execution on sites accessible via ssh. It is assumed that the user has setup host keys so as to ssh to the remote host. Which goes to say that the following test on the commandline should work :

>>> ssh <username>@<hostname>
__init__(hostname, username=None, password=None, scriptDir=None, **kwargs)[source]

Initialize a persistent connection to the remote system. We should know at this point whether ssh connectivity is possible

Args:
  • hostname (String) : Hostname
KWargs:
  • username (string) : Username on remote system
  • password (string) : Password for remote system
  • channel_script_dir (string) : Full path to a script dir where generated scripts could be sent to.

Raises:

__weakref__[source]

list of weak references to the object (if defined)

execute_no_wait(cmd, walltime=2, envs={})[source]

Execute asynchronousely without waiting for exitcode

Args:
  • cmd (string): Commandline string to be executed on the remote side
  • walltime (int): timeout to exec_command
KWargs:
  • envs (dict): A dictionary of env variables
Returns:
  • None, stdout (readable stream), stderr (readable stream)
Raises:
  • ChannelExecFailed (reason)
pull_file(remote_source, local_dir)[source]

Transport file on the remote side to a local directory

Args:
  • remote_source (string): remote_source
  • local_dir (string): Local directory to copy to
Returns:
  • str: Local path to file
Raises:
  • FileExists : Name collision at local directory.
  • FileCopyException : FileCopy failed.
push_file(local_source, remote_dir)[source]

Transport a local file to a directory on a remote machine

Args:
  • local_source (string): Path
  • remote_dir (string): Remote path
Returns:
  • str: Path to copied file on remote machine
Raises:
  • BadScriptPath : if script path on the remote side is bad
  • BadPermsScriptPath : You do not have perms to make the channel script dir
  • FileCopyException : FileCopy failed.

SshILChannel

class libsubmit.channels.ssh_il.ssh_il.SshILChannel(hostname, username=None, password=None, scriptDir=None, **kwargs)[source]

Ssh persistent channel. This enables remote execution on sites accessible via ssh. It is assumed that the user has setup host keys so as to ssh to the remote host. Which goes to say that the following test on the commandline should work :

>>> ssh <username>@<hostname>
__init__(hostname, username=None, password=None, scriptDir=None, **kwargs)[source]

Initialize a persistent connection to the remote system. We should know at this point whether ssh connectivity is possible

Args:
  • hostname (String) : Hostname
KWargs:
  • username (string) : Username on remote system
  • password (string) : Password for remote system
  • channel_script_dir (string) : Full path to a script dir where generated scripts could be sent to.

Raises:

Launchers

Launchers are basically wrappers for user submitted scripts as they are submitted to a specific execution resource.

singleNodeLauncher

libsubmit.launchers.singleNodeLauncher(cmd_string, taskBlocks, walltime=None)[source]

Worker launcher that wraps the user’s cmd_string with the framework to launch multiple cmd_string invocations in parallel. This wrapper sets the bash env variable CORES to the number of cores on the machine. By setting taskBlocks to an integer or to a bash expression the number of invocations of the cmd_string to be launched can be controlled.

Args:
  • cmd_string (string): The command string to be launched
  • taskBlock (string) : bash evaluated string.
KWargs:
  • walltime (int) : This is not used by this launcher.

srunLauncher

libsubmit.launchers.srunLauncher(cmd_string, taskBlocks, walltime=None)[source]

Worker launcher that wraps the user’s cmd_string with the SRUN launch framework to launch multiple cmd invocations in parallel on a single job allocation.

Args:
  • cmd_string (string): The command string to be launched
  • taskBlock (string) : bash evaluated string.
KWargs:
  • walltime (int) : This is not used by this launcher.

srunMpiLauncher

libsubmit.launchers.srunMpiLauncher(cmd_string, taskBlocks, walltime=None)[source]

Worker launcher that wraps the user’s cmd_string with the SRUN launch framework to launch multiple cmd invocations in parallel on a single job allocation.

Args:
  • cmd_string (string): The command string to be launched
  • taskBlock (string) : bash evaluated string.
KWargs:
  • walltime (int) : This is not used by this launcher.

Flow Control

This section deals with functionality related to controlling the flow of tasks to various different execution sites.

FlowControl

class parsl.dataflow.flow_control.FlowControl(dfk, config, *args, threshold=20, interval=5)[source]

Implements threshold-interval based flow control.

The overall goal is to trap the flow of apps from the workflow, measure it and redirect it the appropriate executors for processing.

This is based on the following logic:

BEGIN (INTERVAL, THRESHOLD, callback) :
    start = current_time()

    while (current_time()-start < INTERVAL) :
         count = get_events_since(start)
         if count >= THRESHOLD :
             break

    callback()

This logic ensures that the callbacks are activated with a maximum delay of interval for systems with infrequent events as well as systems which would generate large bursts of events.

Once a callback is triggered, the callback generally runs a strategy method on the sites available as well asqeuque

TODO: When the debug logs are enabled this module emits duplicate messages. This issue needs more debugging. What I’ve learnt so far is that the duplicate messages are present only when the timer thread is started, so this could be from a duplicate logger being added by the thread.

close()[source]

Merge the threads and terminate.

make_callback(kind=None)[source]

Makes the callback and resets the timer.

KWargs:
  • kind (str): Default=None, used to pass information on what triggered the callback
notify(event_id)[source]

Let the FlowControl system know that there is an event.

FlowNoControl

class parsl.dataflow.flow_control.FlowNoControl(dfk, config, *args, threshold=2, interval=2)[source]

FlowNoControl implements similar interfaces as FlowControl.

Null handlers are used so as to mimic the FlowControl class.

__init__(dfk, config, *args, threshold=2, interval=2)[source]

Initialize the flowcontrol object. This does nothing.

Args:
  • dfk (DataFlowKernel) : DFK object to track parsl progress
  • config (dict) : Config dict structure
KWargs:
  • threshold (int) : Tasks after which the callback is triggered
  • interval (int) : seconds after which timer expires
__weakref__[source]

list of weak references to the object (if defined)

close()[source]

This close fn does nothing.

notify(event_id)[source]

This notifiy fn does nothing.

Timer

class parsl.dataflow.flow_control.Timer(callback, *args, interval=5)[source]

This timer is a simplified version of the FlowControl timer. This timer does not employ notify events.

This is based on the following logic :

BEGIN (INTERVAL, THRESHOLD, callback) :
    start = current_time()

    while (current_time()-start < INTERVAL) :
         wait()
         break

    callback()
__init__(callback, *args, interval=5)[source]

Initialize the flowcontrol object We start the timer thread here

Args:
  • dfk (DataFlowKernel) : DFK object to track parsl progress
  • config (dict) : Config dict structure
KWargs:
  • threshold (int) : Tasks after which the callback is triggered
  • interval (int) : seconds after which timer expires
__weakref__[source]

list of weak references to the object (if defined)

close()[source]

Merge the threads and terminate.

make_callback(kind=None)[source]

Makes the callback and resets the timer.

Strategy

Strategies are responsible for tracking the compute requirements of a workflow as it is executed and scaling the resources to match it.

class parsl.dataflow.strategy.Strategy(dfk)[source]

FlowControl Strategy.

As a workflow dag is processed by Parsl, new tasks are added and completed asynchronously. Parsl interfaces executors with execution providers to construct scalable execution sites to handle the variable work-load generated by the workflow. This component is responsible for periodically checking outstanding tasks and available compute capacity and trigger scaling events to match workflow needs.

Here’s a diagram of a site. A site consists of blocks, which are usually created by single requests to a Local Resource Manager (LRM) such as slurm, condor, torque, or even AWS API. The blocks could contain several task blocks which are separate instances on workers.

       |<--minBlocks     |<-initBlocks              maxBlocks-->|
       +--------------------------------------------------------+
       |  +--------Block--------+       +--------Block--------+ |
Site = |  | TaskBlock TaskBlock | ...   | TaskBlock TaskBlock | |
       |  +---------------------+       +---------------------+ |
       +--------------------------------------------------------+

The general shape and bounds of a site are user specified through:

  1. minBlocks: Minimum number of blocks to maintain per site
  2. initBlocks: number of blocks to provision at initialization of workflow
  3. maxBlocks: Maximum number of blocks that can be active at a site from one workflow.
slots = current_capacity * taskBlocks

active_tasks = pending_tasks + running_tasks

Parallelism = slots / tasks
            = [0, 1] (i.e,  0 <= p <= 1)

For example:

When p = 0,

=> compute with the least resources possible. infinite tasks are stacked per slot.

blocks =  minBlocks           { if active_tasks = 0
          max(minBlocks, 1)   {  else
When p = 1,

=> compute with the most resources. one task is stacked per slot.

blocks = min ( maxBlocks,
         ceil( active_tasks / slots ) )
When p = 1/2,
=> We stack upto 2 tasks per slot before we overflow and request a new block

let’s say min:init:max = 0:0:4 and taskBlocks=2

In the diagram, X <- task

at 2 tasks :

+---Block---|
|           |
| X      X  |
|slot   slot|
+-----------+

at 5 tasks, we overflow as the capacity of a single block is fully used.

+---Block---|       +---Block---|
| X      X  | ----> |           |
| X      X  |       | X         |
|slot   slot|       |slot   slot|
+-----------+       +-----------+
__init__(dfk)[source]

Initialize strategy.

__weakref__[source]

list of weak references to the object (if defined)

Memoization

class parsl.dataflow.memoization.Memoizer(dfk, memoize=True, checkpoint={})[source]

Memoizer is responsible for ensuring that identical work is not repeated.

When a task is repeated, i.e., the same function is called with the same exact arguments, the result from a previous execution is reused. wiki

The memoizer implementation here does not collapse duplicate calls at call time, but works only when the result of a previous call is available at the time the duplicate call is made.

For instance:

No advantage from                 Memoization helps
memoization here:                 here:

 TaskA                            TaskB
   |   TaskA                        |
   |     |   TaskA                done  (TaskB)
   |     |     |                                (TaskB)
 done    |     |
       done    |
             done

The memoizer creates a lookup table by hashing the function name and its inputs, and storing the results of the function.

When a task is ready for launch, i.e., all of its arguments have resolved, we add its hash to the task datastructure.

__init__(dfk, memoize=True, checkpoint={})[source]

Initialize the memoizer.

If either the global config or the kwarg memoize is set to false, memoization is disabled.

Args:
  • dfk (DFK obj): The DFK object
KWargs:
  • memoize (Bool): enable memoization or not.
  • checkpoint (Dict): A checkpoint loaded as a dict.
__weakref__[source]

list of weak references to the object (if defined)

check_memo(task_id, task)[source]

Create a hash of the task and its inputs and check the lookup table for this hash.

If present, the results are returned. The result is a tuple indicating whether a memo exists and the result, since a Null result is possible and could be confusing. This seems like a reasonable option without relying on an cache_miss exception.

Args:
  • task(task) : task from the dfk.tasks table
Returns:
Tuple of the following: - present (Bool): Is this present in the memo_lookup_table - Result (Py Obj): Result of the function if present in table

This call will also set task[‘hashsum’] to the unique hashsum for the func+inputs.

hash_lookup(hashsum)[source]

Lookup a hash in the memoization table.

Will raise a KeyError if hash is not in the memoization lookup table.

Args:
  • hashsum (str?): The same hashes used to uniquely identify apps+inputs
Returns:
  • Lookup result, this is unlikely to be None, since the hashes are set by this library and could not miss entried in it’s dict.
Raises:
  • KeyError: if hash not in table
make_hash(task)[source]

Create a hash of the task inputs.

This uses a serialization library borrowed from ipyparallel. If this fails here, then all ipp calls are also likely to fail due to failure at serialization.

Args:
  • task (dict) : Task dictionary from dfk.tasks
Returns:
  • hash (str) : A unique hash string
update_memo(task_id, task, r)[source]

Updates the memoization lookup table with the result from a task.

Args:
  • task_id (int): Integer task id
  • task (dict) : A task dict from dfk.tasks
  • r (Result future): Result future

A warning is issued when a hash collision occures during the update. This is not likely.