Search is not available for this dataset
text
stringlengths
75
104k
def checkpoint(self, tasks=None): """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 ...
def _load_checkpoints(self, checkpointDirs): """Load a checkpoint file into a lookup table. The data being loaded from the pickle file mostly contains input attributes of the task: func, args, kwargs, env... To simplify the check of whether the exact task has been completed in t...
def load_checkpoints(self, checkpointDirs): """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...
def load(cls, config: Optional[Config] = None): """Load a DataFlowKernel. Args: - config (Config) : Configuration to load. This config will be passed to a new DataFlowKernel instantiation which will be set as the active DataFlowKernel. Returns: - DataFlowKe...
def starter(comm_q, *args, **kwargs): """Start the interchange process The executor is expected to call this function. The args, kwargs match that of the Interchange.__init__ """ # logger = multiprocessing.get_logger() ic = Interchange(*args, **kwargs) comm_q.put((ic.worker_task_port, ...
def get_tasks(self, count): """ Obtains a batch of tasks from the internal pending_task_queue Parameters ---------- count: int Count of tasks to get from the queue Returns ------- List of upto count tasks. May return fewer than count down to an empty...
def migrate_tasks_to_internal(self, kill_event): """Pull tasks from the incoming tasks 0mq pipe onto the internal pending task queue Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die. """ logger...
def _command_server(self, kill_event): """ Command server to run async command to the interchange """ logger.debug("[COMMAND] Command Server Starting") while not kill_event.is_set(): try: command_req = self.command_channel.recv_pyobj() logger.d...
def start(self, poll_period=None): """ Start the NeedNameQeueu Parameters: ---------- TODO: Move task receiving to a thread """ logger.info("Incoming ports bound") if poll_period is None: poll_period = self.poll_period start = time.time() ...
def starter(comm_q, *args, **kwargs): """Start the interchange process The executor is expected to call this function. The args, kwargs match that of the Interchange.__init__ """ # logger = multiprocessing.get_logger() ic = Interchange(*args, **kwargs) comm_q.put(ic.worker_port) ic.start() ...
def start(self): """ TODO: docstring """ logger.info("Starting interchange") # last = time.time() while True: # active_flag = False socks = dict(self.poller.poll(1)) if socks.get(self.task_incoming) == zmq.POLLIN: message = self.task_...
def execute_task(bufs): """Deserialize the buffer and execute the task. Returns the result or throws exception. """ user_ns = locals() user_ns.update({'__builtins__': __builtins__}) f, args, kwargs = unpack_apply_message(bufs, user_ns, copy=False) # We might need to look into callability ...
def push_results(self, kill_event): """ Listens on the pending_result_queue and sends out results via 0mq Parameters: ----------- kill_event : threading.Event Event to let the thread know when it is time to die. """ logger.debug("[RESULT_PUSH_THREAD] Start...
def start(self): """ Start the worker processes. TODO: Move task receiving to a thread """ start = time.time() self._kill_event = threading.Event() self.procs = {} for worker_id in range(self.worker_count): p = multiprocessing.Process(target=worker, ...
def get_data_manager(cls): """Return the DataManager of the currently loaded DataFlowKernel. """ from parsl.dataflow.dflow import DataFlowKernelLoader dfk = DataFlowKernelLoader.dfk() return dfk.executors['data_manager']
def shutdown(self, block=False): """Shutdown the ThreadPool. Kwargs: - block (bool): To block for confirmations or not """ x = self.executor.shutdown(wait=block) logger.debug("Done with executor shutdown") return x
def stage_in(self, file, executor): """Transport the file from the input source to the executor. This function returns a DataFuture. Args: - self - file (File) : file to stage in - executor (str) : an executor the file is going to be staged in to. ...
def stage_out(self, file, executor): """Transport the file from the local filesystem to the remote Globus endpoint. This function returns a DataFuture. Args: - self - file (File) - file to stage out - executor (str) - Which executor the file is going to be s...
def get_all_checkpoints(rundir="runinfo"): """Finds the checkpoints from all last runs. Note that checkpoints are incremental, and this helper will not find previous checkpoints from earlier than the most recent run. It probably should be made to do so. Kwargs: - rundir(str) : Path to the r...
def get_last_checkpoint(rundir="runinfo"): """Find the checkpoint from the last run, if one exists. Note that checkpoints are incremental, and this helper will not find previous checkpoints from earlier than the most recent run. It probably should be made to do so. Kwargs: - rundir(str) : P...
def wtime_to_minutes(time_string): ''' wtime_to_minutes Convert standard wallclock time string to minutes. Args: - Time_string in HH:MM:SS format Returns: (int) minutes ''' hours, mins, seconds = time_string.split(':') total_mins = int(hours) * 60 + int(mins) if total...
def interactive(f): """Decorator for making functions appear as interactively defined. This results in the function being linked to the user_ns as globals() instead of the module globals(). """ # build new FunctionType, so it can have the right globals # interactive functions never have closure...
def use_pickle(): """Revert to using stdlib pickle. Reverts custom serialization enabled by use_dill|cloudpickle. """ from . import serialize serialize.pickle = serialize._stdlib_pickle # restore special function handling can_map[FunctionType] = _original_can_map[FunctionType]
def _import_mapping(mapping, original=None): """Import any string-keys in a type mapping.""" #log = get_logger() #log.debug("Importing canning map") for key, value in list(mapping.items()): if isinstance(key, string_types): try: cls = import_item(key) exce...
def istype(obj, check): """Like isinstance(obj, check), but strict. This won't catch subclasses. """ if isinstance(check, tuple): for cls in check: if type(obj) is cls: return True return False else: return type(obj) is check
def can(obj): """Prepare an object for pickling.""" import_needed = False for cls, canner in iteritems(can_map): if isinstance(cls, string_types): import_needed = True break elif istype(obj, cls): return canner(obj) if import_needed: # perfor...
def can_dict(obj): """Can the *values* of a dict.""" if istype(obj, dict): newobj = {} for k, v in iteritems(obj): newobj[k] = can(v) return newobj else: return obj
def can_sequence(obj): """Can the elements of a sequence.""" if istype(obj, sequence_types): t = type(obj) return t([can(i) for i in obj]) else: return obj
def uncan(obj, g=None): """Invert canning.""" import_needed = False for cls, uncanner in iteritems(uncan_map): if isinstance(cls, string_types): import_needed = True break elif isinstance(obj, cls): return uncanner(obj, g) if import_needed: # ...
def unset_logging(self): """ Mute newly added handlers to the root level, right after calling executor.status """ if self.logger_flag is True: return root_logger = logging.getLogger() for hndlr in root_logger.handlers: if hndlr not in self.prior_loghandl...
def _strategy_simple(self, tasks, *args, kind=None, **kwargs): """Peek at the DFK and the executors specified. We assume here that tasks are not held in a runnable state, and that all tasks from an app would be sent to a single specific executor, i.e tasks cannot be specified to...
def transfer_file(cls, src_ep, dst_ep, src_path, dst_path): tc = globus_sdk.TransferClient(authorizer=cls.authorizer) td = globus_sdk.TransferData(tc, src_ep, dst_ep) td.add_item(src_path, dst_path) try: task = tc.submit_transfer(td) except Exception as e: ...
def get_parsl_logger( logger_name='parsl_monitor_logger', is_logging_server=False, monitoring_config=None, **kwargs): """ Parameters ---------- logger_name : str, optional Name of the logger to use. Prevents adding repeat ha...
def start(self): """Start the controller.""" if self.mode == "manual": return if self.ipython_dir != '~/.ipython': self.ipython_dir = os.path.abspath(os.path.expanduser(self.ipython_dir)) if self.log: stdout = open(os.path.join(self.ipython_dir, "{0...
def engine_file(self): """Specify path to the ipcontroller-engine.json file. This file is stored in in the ipython_dir/profile folders. Returns : - str, File path to engine file """ return os.path.join(self.ipython_dir, 'profile_{0}'.fo...
def client_file(self): """Specify path to the ipcontroller-client.json file. This file is stored in in the ipython_dir/profile folders. Returns : - str, File path to client file """ return os.path.join(self.ipython_dir, 'profile_{0}'.fo...
def close(self): """Terminate the controller process and its child processes. Args: - None """ if self.reuse: logger.debug("Ipcontroller not shutting down: reuse enabled") return if self.mode == "manual": logger.debug("Ipcontrol...
def make_hash(self, task): """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 df...
def check_memo(self, task_id, task): """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. ...
def update_memo(self, task_id, task, r): """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 h...
def _nbytes(buf): """Return byte-size of a memoryview or buffer.""" if isinstance(buf, memoryview): if PY3: # py3 introduces nbytes attribute return buf.nbytes else: # compute nbytes on py2 size = buf.itemsize for dim in buf.shape: ...
def _extract_buffers(obj, threshold=MAX_BYTES): """Extract buffers larger than a certain threshold.""" buffers = [] if isinstance(obj, CannedObject) and obj.buffers: for i, buf in enumerate(obj.buffers): nbytes = _nbytes(buf) if nbytes > threshold: # buffer la...
def _restore_buffers(obj, buffers): """Restore extracted buffers.""" if isinstance(obj, CannedObject) and obj.buffers: for i, buf in enumerate(obj.buffers): if buf is None: obj.buffers[i] = buffers.pop(0)
def serialize_object(obj, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS): """Serialize an object into a list of sendable buffers. Parameters ---------- obj : object The object to be serialized buffer_threshold : int The threshold (in bytes) for pulling out data buffers ...
def deserialize_object(buffers, g=None): """Reconstruct an object serialized by serialize_object from data buffers. Parameters ---------- bufs : list of buffers/bytes g : globals to be used when uncanning Returns ------- (newobj, bufs) : unpacked object, and the list of remaining un...
def pack_apply_message(f, args, kwargs, buffer_threshold=MAX_BYTES, item_threshold=MAX_ITEMS): """Pack up a function, args, and kwargs to be sent over the wire. Each element of args/kwargs will be canned for special treatment, but inspection will not go any deeper than that. Any object whose data is l...
def unpack_apply_message(bufs, g=None, copy=True): """Unpack f,args,kwargs from buffers packed by pack_apply_message(). Returns: original f,args,kwargs """ bufs = list(bufs) # allow us to pop assert len(bufs) >= 2, "not enough buffers!" pf = buffer_to_bytes_py2(bufs.pop(0)) f = uncan(pickl...
def _write_submit_script(self, template, script_filename, job_name, configs): """Generate submit script and write it to a file. Args: - template (string) : The template string to be used for the writing submit script - script_filename (string) : Name of the submit script ...
def status(self, job_ids): """ 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', 'COMPLET...
def status(self, job_ids): ''' 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. ''' logger.debug("Checking status of: {0}".format(job_ids)) ...
def submit(self, command, blocksize, tasks_per_node, job_name="parsl.auto"): ''' Submits the command 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_nod...
def cancel(self, job_ids): ''' 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. ''' for job in job_ids: logger.debug("Terminating j...
def submit(self, command, blocksize, tasks_per_node, job_name="parsl.auto"): """ Submits the command 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_pe...
def initialize_boto_client(self): """Initialize the boto client.""" self.session = self.create_session() self.client = self.session.client('ec2') self.ec2 = self.session.resource('ec2') self.instances = [] self.instance_states = {} self.vpc_id = 0 self.sg...
def read_state_file(self, state_file): """Read the state file, if it exists. If this script has been run previously, resource IDs will have been written to a state file. On starting a run, a state file will be looked for before creating new infrastructure. Information on VPCs, security ...
def write_state_file(self): """Save information that must persist to a file. We do not want to create a new VPC and new identical security groups, so we save information about them in a file between runs. """ fh = open('awsproviderstate.json', 'w') state = {} sta...
def create_session(self): """Create a session. First we look in self.key_file for a path to a json file with the credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'. Next we look at self.profile for a profile name and try to use the Session call to automat...
def create_vpc(self): """Create and configure VPC We create a VPC with CIDR 10.0.0.0/16, which provides up to 64,000 instances. We attach a subnet for each availability zone within the region specified in the config. We give each subnet an ip range like 10.0.X.0/20, which is large enou...
def security_group(self, vpc): """Create and configure a new security group. Allows all ICMP in, all TCP and UDP in within VPC. This security group is very open. It allows all incoming ping requests on all ports. It also allows all outgoing traffic on all ports. This can be limited by ...
def config_route_table(self, vpc, internet_gateway): """Configure route table for Virtual Private Cloud (VPC). Parameters ---------- vpc : dict Representation of the VPC (created by create_vpc()). internet_gateway : dict Representation of the internet gat...
def spin_up_instance(self, command, job_name): """Start an instance in the VPC in the first available subnet. N instances will be started if nodes_per_block > 1. Not supported. We only do 1 node per block. Parameters ---------- command : str Command string t...
def shut_down_instance(self, instances=None): """Shut down a list of instances, if provided. If no instance is provided, the last instance started up will be shut down. """ if instances and len(self.instances) > 0: print(instances) try: print([i....
def get_instance_state(self, instances=None): """Get states of all instances on EC2 which were started by this file.""" if instances: desc = self.client.describe_instances(InstanceIds=instances) else: desc = self.client.describe_instances(InstanceIds=self.instances) ...
def status(self, job_ids): """Get the status of a list of jobs identified by their ids. Parameters ---------- job_ids : list of str Identifiers for the jobs. Returns ------- list of int The status codes of the requsted jobs. """ ...
def submit(self, command='sleep 1', blocksize=1, tasks_per_node=1, job_name="parsl.auto"): """Submit the command onto a freshly instantiated AWS EC2 instance. Submit returns an ID that corresponds to the task that was just submitted. Parameters ---------- command : str ...
def cancel(self, job_ids): """Cancel the jobs specified by a list of job ids. Parameters ---------- job_ids : list of str List of of job identifiers Returns ------- list of bool Each entry in the list will contain False if the operation f...
def show_summary(self): """Print human readable summary of current AWS state to log and to console.""" self.get_instance_state() status_string = "EC2 Summary:\n\tVPC IDs: {}\n\tSubnet IDs: \ {}\n\tSecurity Group ID: {}\n\tRunning Instance IDs: {}\n".format( self.vpc_id, self.sn_ids, ...
def teardown(self): """Teardown the EC2 infastructure. Terminate all EC2 instances, delete all subnets, delete security group, delete VPC, and reset all instance variables. """ self.shut_down_instance(self.instances) self.instances = [] try: self.cli...
def scale_out(self, blocks=1, block_size=1): ''' Scale out the existing resources. ''' self.config['sites.jetstream.{0}'.format(self.pool)]['flavor'] count = 0 if blocks == 1: block_id = len(self.blocks) self.blocks[block_id] = [] for instance_...
def scale_in(self, blocks=0, machines=0, strategy=None): ''' Scale in resources ''' count = 0 instances = self.client.servers.list() for instance in instances[0:machines]: print("Deleting : ", instance) instance.delete() count += 1 ret...
def execute_task(f, args, kwargs, user_ns): """ Deserialize the buffer and execute the task. # Returns the result or exception. """ fname = getattr(f, '__name__', 'f') prefix = "parsl_" fname = prefix + "f" argname = prefix + "args" kwargname = prefix + "kwargs" resultname = pre...
def start_file_logger(filename, rank, name='parsl', level=logging.DEBUG, format_string=None): """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 (s...
def worker(worker_id, task_url, debug=True, logdir="workers", uid="1"): """ TODO: docstring TODO : Cleanup debug, logdir and uid to function correctly """ start_file_logger('{}/{}/worker_{}.log'.format(logdir, uid, worker_id), 0, level=logging.DEBUG if debug...
def _status(self): """Update the resource dictionary with job statuses.""" job_id_list = ' '.join(self.resources.keys()) cmd = "condor_q {0} -af:jr JobStatus".format(job_id_list) retcode, stdout, stderr = super().execute_wait(cmd) """ Example output: $ condor_q ...
def submit(self, command, blocksize, tasks_per_node, job_name="parsl.auto"): """Submits the command 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).$(Proc...
def compose_containerized_launch_cmd(self, filepath, engine_dir, container_image): """Reads the json contents from filepath and uses that to compose the engine launch command. Notes: Add this to the ipengine launch for debug logs : --log-to-file --debug Args: ...
def scale_out(self, blocks=1): """Scales out the number of active workers by 1. This method is notImplemented for threads and will raise the error if called. Parameters: blocks : int Number of blocks to be provisioned. """ r = [] for i in rang...
def scale_in(self, blocks): """Scale in the number of active blocks by the specified number. """ status = dict(zip(self.engines, self.provider.status(self.engines))) # This works for blocks=0 to_kill = [engine for engine in status if status[engine] == "RUNNING"][:blocks] ...
def status(self): """Returns the status of the executor via probing the execution providers.""" if self.provider: status = self.provider.status(self.engines) else: status = [] return status
def shutdown(self, hub=True, targets='all', block=False): """Shutdown the executor, including all workers and controllers. The interface documentation for IPP is `here <http://ipyparallel.readthedocs.io/en/latest/api/ipyparallel.html#ipyparallel.Client.shutdown>`_ Kwargs: - hub (Bo...
def parent_callback(self, executor_fu): """Callback from a parent future to update the AppFuture. Used internally by AppFuture, and should not be called by code using AppFuture. Args: - executor_fu (Future): Future returned by the executor along with callback. This ma...
def update_parent(self, fut): """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. """ self.parent = fut try: fut.add_done_callback(self.parent_callback) ...
def parent_callback(self, parent_fu): """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() """ ...
def remote_side_bash_executor(func, *args, **kwargs): """Execute the bash app type function and return the command line string. This string is reformatted with the *args, and **kwargs from call time. """ import os import time import subprocess import logging import parsl.app.errors ...
def submit(self, command, blocksize, tasks_per_node, job_name="parsl.auto"): ''' The submit method takes the command string to be executed upon instantiation of a resource most often to start a pilot. Args : - command (str) : The bash command string to be executed. - b...
def status(self, job_ids): ''' 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', 'COMPLET...
def cancel(self, job_ids): ''' 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: - Executio...
def runner(incoming_q, outgoing_q): """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 Th...
def _queue_management_worker(self): """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: .. code:: python { "task_id" : <task...
def shutdown(self): """Shutdown method, to kill the threads and workers.""" self.is_alive = False logging.debug("Waking management thread") self.incoming_q.put(None) # Wake up the thread self._queue_management_thread.join() # Force join logging.debug("Exiting thread") ...
def submit(self, func, *args, **kwargs): """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: <https://docs.python.org/3/library/...
def filepath(self): """Return the resolved filepath on the side where it is called from. The appropriate filepath will be returned when called from within an app running remotely as well as regular python on the client side. Args: - self Returns: - file...
def execute_wait(self, cmd, walltime=None, envs={}): ''' 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. Kwargs: - envs (dict) ...
def push_file(self, source, dest_dir): ''' 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 f...
def App(apptype, data_flow_kernel=None, walltime=60, cache=False, executors='all'): """The App decorator function. Args: - apptype (string) : Apptype can be bash|python Kwargs: - data_flow_kernel (DataFlowKernel): The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for ...
def python_app(function=None, data_flow_kernel=None, walltime=60, cache=False, executors='all'): """Decorator function for making python apps. Parameters ---------- function : function Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis, ...
def bash_app(function=None, data_flow_kernel=None, walltime=60, cache=False, executors='all'): """Decorator function for making bash apps. Parameters ---------- function : function Do not pass this keyword argument directly. This is needed in order to allow for omitted parenthesis, for ...
def make_rundir(path): """When a path has not been specified, make the run directory. Creates a rundir with the following hierarchy: ./runinfo <- Home of all run directories |----000 |----001 <- Directories for each run | .... |----NNN Kwargs: - path...
def put(self, task_id, buffer): """ TODO: docstring """ task_id_bytes = task_id.to_bytes(4, "little") message = [b"", task_id_bytes] + buffer self.zmq_socket.send_multipart(message) logger.debug("Sent task {}".format(task_id))
def monitor(pid, task_id, monitoring_hub_url, run_id, sleep_dur=10): """Internal Monitors the Parsl task's resources by pointing psutil to the task's pid and watching it and its children. """ import psutil radio = UDPRadio(monitoring_hub_url, source_id=task_id) # these val...