_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q254400 | DataFlowKernel.checkpoint | validation | 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
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}
"""
with self.checkpoint_lock:
checkpoint_queue = None
if tasks:
checkpoint_queue = tasks
else:
checkpoint_queue = self.tasks
checkpoint_dir = '{0}/checkpoint'.format(self.run_dir)
checkpoint_dfk = checkpoint_dir + '/dfk.pkl'
checkpoint_tasks = checkpoint_dir + '/tasks.pkl'
if not os.path.exists(checkpoint_dir):
try:
os.makedirs(checkpoint_dir)
except FileExistsError:
pass
with open(checkpoint_dfk, 'wb') as f:
state = {'rundir': self.run_dir,
'task_count': self.task_count
| python | {
"resource": ""
} |
q254401 | DataFlowKernel._load_checkpoints | validation | 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 the checkpoint, we hash these input params and use it as the key
for the memoized lookup table.
Args:
- checkpointDirs (list) : List of filepaths to checkpoints
Eg. ['runinfo/001', 'runinfo/002']
Returns:
- memoized_lookup_table (dict)
"""
memo_lookup_table = {}
for checkpoint_dir in checkpointDirs:
logger.info("Loading checkpoints from {}".format(checkpoint_dir))
checkpoint_file = os.path.join(checkpoint_dir, 'tasks.pkl')
try:
with open(checkpoint_file, 'rb') as f:
while True:
try:
data = pickle.load(f)
# Copy and hash only the input attributes
memo_fu = Future()
if data['exception']:
memo_fu.set_exception(data['exception'])
else:
memo_fu.set_result(data['result'])
| python | {
"resource": ""
} |
q254402 | DataFlowKernel.load_checkpoints | validation | 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', 'runinfo/002']
Returns:
- dict containing, hashed -> future mappings
"""
self.memo_lookup_table = None
| python | {
"resource": ""
} |
q254403 | DataFlowKernelLoader.load | validation | 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.
| python | {
"resource": ""
} |
q254404 | Interchange.get_tasks | validation | 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 | python | {
"resource": ""
} |
q254405 | Interchange.migrate_tasks_to_internal | validation | 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.info("[TASK_PULL_THREAD] Starting")
task_counter = 0
poller = zmq.Poller()
poller.register(self.task_incoming, zmq.POLLIN)
while not kill_event.is_set():
try:
msg = self.task_incoming.recv_pyobj()
except zmq.Again:
| python | {
"resource": ""
} |
q254406 | Interchange._command_server | validation | 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.debug("[COMMAND] Received command request: {}".format(command_req))
if command_req == "OUTSTANDING_C":
outstanding = self.pending_task_queue.qsize()
for manager in self._ready_manager_queue:
outstanding += len(self._ready_manager_queue[manager]['tasks'])
reply = outstanding
elif command_req == "WORKERS":
num_workers = 0
for manager in self._ready_manager_queue:
num_workers += self._ready_manager_queue[manager]['worker_count']
reply = num_workers
elif command_req == "MANAGERS":
reply = []
for manager in self._ready_manager_queue:
resp = {'manager': manager.decode('utf-8'),
'block_id': self._ready_manager_queue[manager]['block_id'],
'worker_count': self._ready_manager_queue[manager]['worker_count'],
'tasks': len(self._ready_manager_queue[manager]['tasks']),
'active': self._ready_manager_queue[manager]['active']}
reply.append(resp)
elif command_req.startswith("HOLD_WORKER"):
cmd, s_manager = command_req.split(';')
manager | python | {
"resource": ""
} |
q254407 | Manager.start | validation | 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, args=(worker_id,
self.uid,
self.pending_task_queue,
self.pending_result_queue,
self.ready_worker_queue,
))
p.start()
self.procs[worker_id] = p
logger.debug("Manager synced with workers")
self._task_puller_thread = threading.Thread(target=self.pull_tasks,
args=(self._kill_event,))
self._result_pusher_thread = threading.Thread(target=self.push_results,
args=(self._kill_event,))
self._task_puller_thread.start()
self._result_pusher_thread.start()
| python | {
"resource": ""
} |
q254408 | DataManager.get_data_manager | validation | def get_data_manager(cls):
"""Return the DataManager of the currently loaded DataFlowKernel.
"""
from parsl.dataflow.dflow import DataFlowKernelLoader
| python | {
"resource": ""
} |
q254409 | DataManager.shutdown | validation | def shutdown(self, block=False):
"""Shutdown the ThreadPool.
Kwargs:
- block (bool): To block for confirmations or not
"""
| python | {
"resource": ""
} |
q254410 | DataManager.stage_in | validation | 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.
If the executor argument is not specified for a file
with 'globus' scheme, the file will be staged in to
the first executor with the "globus" key in a config.
"""
if file.scheme == 'ftp':
working_dir = self.dfk.executors[executor].working_dir
stage_in_app = self._ftp_stage_in_app(executor=executor)
app_fut = stage_in_app(working_dir, outputs=[file])
return app_fut._outputs[0]
elif file.scheme == 'http' or | python | {
"resource": ""
} |
q254411 | DataManager.stage_out | validation | 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 staged out from.
If the executor argument is not specified for a file
with the 'globus' scheme, the file will be staged in to
the first executor with the "globus" key in a config.
"""
if file.scheme == 'http' or file.scheme | python | {
"resource": ""
} |
q254412 | get_all_checkpoints | validation | 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 runinfo directory
| python | {
"resource": ""
} |
q254413 | get_last_checkpoint | validation | 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) : Path to the runinfo directory
| python | {
"resource": ""
} |
q254414 | interactive | validation | 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 closures, that's kind of the point
if isinstance(f, FunctionType):
mainmod = __import__('__main__')
| python | {
"resource": ""
} |
q254415 | use_pickle | validation | def use_pickle():
"""Revert to using stdlib pickle.
Reverts custom serialization enabled by use_dill|cloudpickle.
"""
from . import serialize
serialize.pickle | python | {
"resource": ""
} |
q254416 | _import_mapping | validation | 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)
except Exception:
if original and key not in original:
# only message on user-added classes
| python | {
"resource": ""
} |
q254417 | can | validation | 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):
| python | {
"resource": ""
} |
q254418 | can_sequence | validation | def can_sequence(obj):
"""Can the elements of a sequence."""
if istype(obj, sequence_types):
t = type(obj)
| python | {
"resource": ""
} |
q254419 | uncan | validation | 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)
| python | {
"resource": ""
} |
q254420 | Strategy.unset_logging | validation | 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 | python | {
"resource": ""
} |
q254421 | Controller.start | validation | 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}.controller.out".format(self.profile)), 'w')
stderr = open(os.path.join(self.ipython_dir, "{0}.controller.err".format(self.profile)), 'w')
else:
stdout = open(os.devnull, 'w')
stderr = open(os.devnull, 'w')
try:
opts = [
'ipcontroller',
'' if self.ipython_dir == '~/.ipython' else '--ipython-dir={}'.format(self.ipython_dir),
self.interfaces if self.interfaces is not None else '--ip=*',
'' if self.profile == 'default' else '--profile={0}'.format(self.profile),
'--reuse' if self.reuse else '',
'--location={}'.format(self.public_ip) if self.public_ip else '',
'--port={}'.format(self.port) if self.port is not None else ''
]
if self.port_range is not None:
opts += [
'--HubFactory.hb={0},{1}'.format(self.hb_ping, self.hb_pong),
| python | {
"resource": ""
} |
q254422 | Controller.engine_file | validation | 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
"""
| python | {
"resource": ""
} |
q254423 | Controller.client_file | validation | 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
"""
| python | {
"resource": ""
} |
q254424 | Controller.close | validation | 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("Ipcontroller not shutting down: Manual mode")
return
try:
pgid = os.getpgid(self.proc.pid)
os.killpg(pgid, signal.SIGTERM)
time.sleep(0.2)
os.killpg(pgid, signal.SIGKILL)
try:
self.proc.wait(timeout=1)
x = self.proc.returncode
if x == 0:
logger.debug("Controller exited with {0}".format(x))
else:
| python | {
"resource": ""
} |
q254425 | Memoizer.make_hash | validation | 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 dfk.tasks
Returns:
- hash (str) : A unique hash string
"""
# Function name TODO: Add fn body later
t = [serialize_object(task['func_name'])[0],
| python | {
"resource": ""
} |
q254426 | Memoizer.check_memo | validation | 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.
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 | python | {
"resource": ""
} |
q254427 | Memoizer.update_memo | validation | 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 hash collision occurs during the update.
This is not likely.
"""
if not self.memoize or not task['memoize']:
return
if task['hashsum'] in self.memo_lookup_table:
| python | {
"resource": ""
} |
q254428 | _nbytes | validation | 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
| python | {
"resource": ""
} |
q254429 | _extract_buffers | validation | 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 larger than threshold, prevent pickling
obj.buffers[i] = None
buffers.append(buf)
# buffer too small for separate send, coerce to bytes
| python | {
"resource": ""
} |
q254430 | _restore_buffers | validation | def _restore_buffers(obj, buffers):
"""Restore extracted buffers."""
if isinstance(obj, CannedObject) and | python | {
"resource": ""
} |
q254431 | serialize_object | validation | 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
to avoid pickling them.
item_threshold : int
The maximum number of items over which canning will iterate.
Containers (lists, dicts) larger than this will be pickled without
introspection.
Returns
-------
[bufs] : list of buffers representing the serialized object.
"""
buffers = []
if istype(obj, sequence_types) and len(obj) < item_threshold:
cobj = can_sequence(obj)
| python | {
"resource": ""
} |
q254432 | deserialize_object | validation | 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 unused buffers.
"""
bufs = list(buffers)
pobj = buffer_to_bytes_py2(bufs.pop(0))
| python | {
"resource": ""
} |
q254433 | pack_apply_message | validation | 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 larger than `threshold` will not have their data copied
(only numpy arrays and bytes/buffers support zero-copy)
Message will be a list of bytes/buffers of | python | {
"resource": ""
} |
q254434 | ClusterProvider._write_submit_script | validation | 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
- job_name (string) : job name
- configs (dict) : configs that get pushed into the template
Returns:
- True: on success
Raises:
SchedulerMissingArgs : If template is missing args
ScriptPathError : Unable to write submit script out
| python | {
"resource": ""
} |
q254435 | LocalProvider.cancel | validation | 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 job/proc_id: {0}".format(job))
# Here we are assuming that for local, the job_ids are the process id's
if self.resources[job]['proc']:
proc = self.resources[job]['proc']
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
self.resources[job]['status'] = 'CANCELLED'
elif self.resources[job]['remote_pid']:
cmd = | python | {
"resource": ""
} |
q254436 | AWSProvider.initialize_boto_client | validation | 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')
| python | {
"resource": ""
} |
q254437 | AWSProvider.read_state_file | validation | 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 groups, and subnets are saved, as
well as running instances and their states.
AWS has a maximum number of VPCs per region per account, so we do not want to
clutter users' AWS accounts with security groups and VPCs that will be used only
once.
"""
try:
| python | {
"resource": ""
} |
q254438 | AWSProvider.write_state_file | validation | 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 = {}
| python | {
"resource": ""
} |
q254439 | AWSProvider.create_session | validation | 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 automatically pick up the keys for the profile from
the user default keys file ~/.aws/config.
Finally, boto3 will look for the keys in environment 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.
"""
session = None
if self.key_file is not None:
credfile = os.path.expandvars(os.path.expanduser(self.key_file))
try:
with open(credfile, 'r') as f:
creds = json.load(f)
except json.JSONDecodeError as e:
logger.error(
"EC2Provider '{}': json decode error in credential file {}".format(self.label, credfile)
)
raise e
except Exception as e:
logger.debug(
"EC2Provider '{0}' caught exception while reading credential file: {1}".format(
| python | {
"resource": ""
} |
q254440 | AWSProvider.create_vpc | validation | 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 enough
for approx. 4000 instances.
Security groups are configured in function security_group.
"""
try:
# We use a large VPC so that the cluster can get large
vpc = self.ec2.create_vpc(
CidrBlock='10.0.0.0/16',
AmazonProvidedIpv6CidrBlock=False,
)
except Exception as e:
# This failure will cause a full abort
logger.error("{}\n".format(e))
raise e
# Attach internet gateway so that our cluster can
# talk to the outside internet
internet_gateway = self.ec2.create_internet_gateway()
internet_gateway.attach_to_vpc(VpcId=vpc.vpc_id) # Returns None
self.internet_gateway = internet_gateway.id
# Create and configure route table to allow proper traffic
route_table = self.config_route_table(vpc, internet_gateway)
self.route_table = route_table.id
# Get all avaliability zones
availability_zones = self.client.describe_availability_zones()
# go through AZs and set up a subnet per
for num, zone in enumerate(availability_zones['AvailabilityZones']):
if zone['State'] == "available":
| python | {
"resource": ""
} |
q254441 | AWSProvider.security_group | validation | 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
changing the allowed port ranges.
Parameters
----------
vpc : VPC instance
VPC in which to set up security group.
"""
sg = vpc.create_security_group(
GroupName="private-subnet", Description="security group for remote executors"
)
ip_ranges = [{'CidrIp': '10.0.0.0/16'}]
# Allows all ICMP in, all TCP and UDP in within VPC
in_permissions = [
{
'IpProtocol': 'TCP',
'FromPort': 0,
'ToPort': 65535,
'IpRanges': ip_ranges,
}, {
'IpProtocol': 'UDP',
'FromPort': 0,
'ToPort': 65535,
'IpRanges': ip_ranges,
}, {
'IpProtocol': 'ICMP',
'FromPort': -1,
'ToPort': -1,
'IpRanges': [{
'CidrIp': '0.0.0.0/0'
}],
}, {
'IpProtocol': 'TCP',
'FromPort': 22,
'ToPort': 22,
'IpRanges': [{
| python | {
"resource": ""
} |
q254442 | AWSProvider.spin_up_instance | validation | 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 to execute on the node.
job_name : str
Name associated with the instances.
"""
command = Template(template_string).substitute(jobname=job_name,
user_script=command,
linger=str(self.linger).lower(),
worker_init=self.worker_init)
instance_type = self.instance_type
subnet = self.sn_ids[0]
ami_id = self.image_id
total_instances = len(self.instances)
if float(self.spot_max_bid) > 0:
spot_options = {
'MarketType': 'spot',
'SpotOptions': {
'MaxPrice': str(self.spot_max_bid),
'SpotInstanceType': 'one-time',
'InstanceInterruptionBehavior': 'terminate'
}
}
else:
spot_options = {}
if total_instances > self.max_nodes:
logger.warn("Exceeded instance limit ({}). Cannot continue\n".format(self.max_nodes))
return [None]
try:
tag_spec = [{"ResourceType": "instance", "Tags": [{'Key': 'Name', 'Value': job_name}]}]
instance = self.ec2.create_instances(
MinCount=1,
MaxCount=1,
InstanceType=instance_type,
ImageId=ami_id,
| python | {
"resource": ""
} |
q254443 | AWSProvider.shut_down_instance | validation | 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.id for i in instances])
except Exception as e:
print(e)
term = self.client.terminate_instances(InstanceIds=instances)
logger.info("Shut down {} instances (ids:{}".format(len(instances), str(instances)))
elif len(self.instances) > 0:
instance | python | {
"resource": ""
} |
q254444 | AWSProvider.get_instance_state | validation | 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:
| python | {
"resource": ""
} |
q254445 | AWSProvider.submit | validation | 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
Command to be invoked on the remote side.
blocksize : int
Number of blocks requested.
tasks_per_node : int (default=1)
Number of command invocations to be launched per node
job_name : str
Prefix for the job name.
Returns
-------
None or str
If at capacity, None will be returned. Otherwise, the job identifier will be returned.
"""
job_name = "parsl.auto.{0}".format(time.time())
wrapped_cmd = self.launcher(command,
tasks_per_node,
| python | {
"resource": ""
} |
q254446 | AWSProvider.cancel | validation | 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 fails. Otherwise, the entry will be True.
"""
if self.linger is True:
logger.debug("Ignoring cancel requests due to linger mode")
return [False for x in job_ids]
try:
self.client.terminate_instances(InstanceIds=list(job_ids))
except Exception as e:
logger.error("Caught error | python | {
"resource": ""
} |
q254447 | AWSProvider.show_summary | validation | 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, self.sg_id, self.instances
)
status_string += "\tInstance States:\n\t\t"
| python | {
"resource": ""
} |
q254448 | AWSProvider.teardown | validation | 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.client.delete_internet_gateway(InternetGatewayId=self.internet_gateway)
self.internet_gateway = None
self.client.delete_route_table(RouteTableId=self.route_table)
| python | {
"resource": ""
} |
q254449 | JetstreamProvider.scale_out | validation | 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_id in range(0, block_size):
instances = self.server_manager.create(
'parsl-{0}-{1}'.format(block_id, instance_id), # Name
| python | {
"resource": ""
} |
q254450 | JetstreamProvider.scale_in | validation | 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]:
| python | {
"resource": ""
} |
q254451 | CondorProvider._status | validation | 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 34524642.0 34524643.0 -af:jr JobStatus
34524642.0 2
34524643.0 1
"""
for | python | {
"resource": ""
} |
q254452 | IPyParallelExecutor.scale_out | validation | 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 range(blocks):
if self.provider:
block = self.provider.submit(self.launch_cmd, 1, self.workers_per_node)
logger.debug("Launched block {}:{}".format(i, block))
if not block:
| python | {
"resource": ""
} |
q254453 | IPyParallelExecutor.scale_in | validation | 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]
if self.provider:
| python | {
"resource": ""
} |
q254454 | IPyParallelExecutor.status | validation | def status(self):
"""Returns the status of the executor via probing the execution providers."""
if self.provider:
| python | {
"resource": ""
} |
q254455 | AppFuture.parent_callback | validation | 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 may not be the current parent future, as the parent future may have
already been updated to point to a retrying execution, and in that case,
this is logged.
In the case that a new parent has been attached, we must immediately discard
this result no matter what it contains (although it might be interesting
to log if it was successful...)
Returns:
- None
Updates the super() with the result() or exception()
"""
with self._update_lock:
if not executor_fu.done():
raise ValueError("done callback called, despite future not reporting itself as done")
# this is for consistency checking
if executor_fu != self.parent:
if executor_fu.exception() is None and not isinstance(executor_fu.result(), RemoteExceptionWrapper):
# ... then we completed with a value, not an exception or wrapped exception,
# but we've got an | python | {
"resource": ""
} |
q254456 | AppFuture.update_parent | validation | 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
| python | {
"resource": ""
} |
q254457 | DataFuture.parent_callback | validation | 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:
| python | {
"resource": ""
} |
q254458 | GoogleCloudProvider.submit | validation | 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.
- blocksize (int) : Blocksize to be requested
- tasks_per_node (int) : command invocations to be launched per node
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 | python | {
"resource": ""
} |
q254459 | GoogleCloudProvider.cancel | validation | 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:
- ExecutionProviderException or its subclasses
'''
statuses = []
for job_id in job_ids:
| python | {
"resource": ""
} |
q254460 | runner | validation | 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
The messages posted on the incoming_q will be of the form :
.. code:: python
{
"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:
.. code:: python
{
"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
"""
logger.debug("[RUNNER] Starting")
def execute_task(bufs):
"""Deserialize the buffer and execute the task.
Returns the serialized result or exception.
"""
user_ns = locals()
user_ns.update({'__builtins__': __builtins__})
f, args, kwargs = unpack_apply_message(bufs, user_ns, copy=False)
fname = getattr(f, '__name__', 'f')
prefix = "parsl_"
fname = prefix + "f"
argname = prefix + "args"
kwargname = prefix + "kwargs"
resultname = prefix + "result"
user_ns.update({fname: f,
argname: args,
kwargname: kwargs,
resultname: resultname})
code = "{0} = {1}(*{2}, **{3})".format(resultname, fname,
argname, kwargname)
try:
logger.debug("[RUNNER] Executing: {0}".format(code))
exec(code, user_ns, user_ns)
except Exception as e:
logger.warning("Caught exception; will raise it: {}".format(e))
raise e
else:
logger.debug("[RUNNER] Result: {0}".format(user_ns.get(resultname)))
return user_ns.get(resultname)
while True:
try:
# Blocking wait on the queue
msg = incoming_q.get(block=True, timeout=10)
except queue.Empty:
# Handle case where | python | {
"resource": ""
} |
q254461 | TurbineExecutor.shutdown | validation | 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
| python | {
"resource": ""
} |
q254462 | TurbineExecutor.submit | validation | 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/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor>`_
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
"""
| python | {
"resource": ""
} |
q254463 | File.filepath | validation | 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:
- filepath (string)
"""
if hasattr(self, 'local_path'):
return self.local_path
if self.scheme in ['ftp', | python | {
"resource": ""
} |
q254464 | LocalChannel.push_file | validation | 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 files is to be copied
Returns:
- destination_path (String) : Absolute path of the destination file
Raises:
- FileCopyException : If file copy failed.
'''
local_dest = dest_dir + '/' + os.path.basename(source)
# Only | python | {
"resource": ""
} |
q254465 | App | validation | 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
managing this app. This can be omitted only
after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`.
- walltime (int) : Walltime for app in seconds,
default=60
- executors (str|list) : Labels of the executors that this app can execute over. Default is 'all'.
- cache (Bool) : Enable caching of the app call
default=False
Returns:
A PythonApp or BashApp object, which when called runs the apps through the executor.
"""
| python | {
"resource": ""
} |
q254466 | python_app | validation | 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,
for example, `@python_app` if using all defaults or `@python_app(walltime=120)`. If the
decorator is used alone, function will be the actual function being decorated, whereas if it
is called with arguments, function will be None. Default is None.
data_flow_kernel : DataFlowKernel
The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for managing this app. This can
be omitted only after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`. Default is None.
walltime : int
Walltime for app in seconds. Default is 60.
executors : string or list
| python | {
"resource": ""
} |
q254467 | bash_app | validation | 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 example, `@bash_app` if using all defaults or `@bash_app(walltime=120)`. If the
decorator is used alone, function will be the actual function being decorated, whereas if it
is called with arguments, function will be None. Default is None.
data_flow_kernel : DataFlowKernel
The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for managing this app. This can
be omitted only after calling :meth:`parsl.dataflow.dflow.DataFlowKernelLoader.load`. Default is None.
walltime : int
Walltime for app in seconds. Default is 60.
executors : string or list
| python | {
"resource": ""
} |
q254468 | make_rundir | validation | 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 (str): String path to a specific run dir
Default : None.
"""
try:
if not os.path.exists(path):
os.makedirs(path)
prev_rundirs = glob(os.path.join(path, "[0-9]*"))
current_rundir = os.path.join(path, '000')
if prev_rundirs:
# Since we globbed on files named as 0-9
| python | {
"resource": ""
} |
q254469 | monitor | validation | 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 values are simple to log. Other information is available in special formats such as memory below.
simple = ["cpu_num", 'cpu_percent', 'create_time', 'cwd', 'exe', 'memory_percent', 'nice', 'name', 'num_threads', 'pid', 'ppid', 'status', 'username']
# values that can be summed up to see total resources used by task process and its children
summable_values = ['cpu_percent', 'memory_percent', 'num_threads']
pm = psutil.Process(pid)
pm.cpu_percent()
first_msg = True
while True:
try:
d = {"psutil_process_" + str(k): v for k, v in pm.as_dict().items() if k in simple}
d["run_id"] = run_id
d["task_id"] = task_id
d['resource_monitoring_interval'] = sleep_dur
d['first_msg'] = first_msg
d['timestamp'] = datetime.datetime.now()
children = pm.children(recursive=True)
d["psutil_cpu_count"] = psutil.cpu_count()
d['psutil_process_memory_virtual'] = pm.memory_info().vms
| python | {
"resource": ""
} |
q254470 | UDPRadio.send | validation | def send(self, message_type, task_id, message):
""" Sends a message to the UDP receiver
Parameter
---------
message_type: monitoring.MessageType (enum)
In this case message type is RESOURCE_INFO most often
task_id: int
Task identifier of the task for which resource monitoring is being reported
message: object
Arbitrary pickle-able object that is to be sent
Returns:
# bytes sent
"""
x = 0
try:
buffer = pickle.dumps((self.source_id, # Identifier for manager
int(time.time()), # epoch timestamp
| python | {
"resource": ""
} |
q254471 | MonitoringHub.monitor_wrapper | validation | def monitor_wrapper(f, task_id, monitoring_hub_url, run_id, sleep_dur):
""" Internal
Wrap the Parsl app with a function that will call the monitor function and point it at the correct pid when the task begins.
"""
def wrapped(*args, **kwargs):
| python | {
"resource": ""
} |
q254472 | SSHChannel.execute_no_wait | validation | def execute_no_wait(self, cmd, walltime=2, envs={}):
''' 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:
- | python | {
"resource": ""
} |
q254473 | SSHChannel.push_file | validation | def push_file(self, local_source, remote_dir):
''' 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.
'''
remote_dest = remote_dir + '/' + os.path.basename(local_source)
try:
self.makedirs(remote_dir, exist_ok=True)
except IOError as e:
logger.exception("Pushing {0} to {1} failed".format(local_source, remote_dir))
if e.errno == 2:
raise BadScriptPath(e, self.hostname)
elif e.errno == 13:
raise BadPermsScriptPath(e, self.hostname)
else:
logger.exception("File push failed due to SFTP client failure")
| python | {
"resource": ""
} |
q254474 | SSHChannel.pull_file | validation | def pull_file(self, remote_source, local_dir):
''' 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.
'''
local_dest = local_dir + '/' + os.path.basename(remote_source)
try:
os.makedirs(local_dir) | python | {
"resource": ""
} |
q254475 | SSHChannel.isdir | validation | def isdir(self, path):
"""Return true if the path refers to an existing directory.
Parameters
----------
path : str
Path of directory on the remote side to check.
"""
result | python | {
"resource": ""
} |
q254476 | SSHChannel.makedirs | validation | def makedirs(self, path, mode=511, exist_ok=False):
"""Create a directory on the remote side.
If intermediate directories do not exist, they will be created.
Parameters
----------
path : str
Path of directory on the remote side to create.
mode : int
Permissions (posix-style) for the newly-created directory.
exist_ok : bool
If False, raise an OSError if the target directory already exists.
"""
| python | {
"resource": ""
} |
q254477 | FlowControl.notify | validation | def notify(self, event_id):
"""Let the FlowControl system know that there is an event."""
self._event_buffer.extend([event_id])
self._event_count += 1
| python | {
"resource": ""
} |
q254478 | KubernetesProvider._create_deployment | validation | def _create_deployment(self, deployment):
""" Create the kubernetes deployment """
api_response = self.kube_client.create_namespaced_deployment(
body=deployment,
| python | {
"resource": ""
} |
q254479 | HighThroughputExecutor.initialize_scaling | validation | def initialize_scaling(self):
""" Compose the launch command and call the scale_out
This should be implemented in the child classes to take care of
executor specific oddities.
"""
debug_opts = "--debug" if self.worker_debug else ""
max_workers = "" if self.max_workers == float('inf') else "--max_workers={}".format(self.max_workers)
worker_logdir = "{}/{}".format(self.run_dir, self.label)
if self.worker_logdir_root is not None:
worker_logdir = "{}/{}".format(self.worker_logdir_root, self.label)
l_cmd = self.launch_cmd.format(debug=debug_opts,
prefetch_capacity=self.prefetch_capacity,
task_url=self.worker_task_url,
| python | {
"resource": ""
} |
q254480 | HighThroughputExecutor._start_local_queue_process | validation | def _start_local_queue_process(self):
""" Starts the interchange process locally
Starts the interchange process locally and uses an internal command queue to
get the worker task and result ports that the interchange has bound to.
"""
comm_q = Queue(maxsize=10)
self.queue_proc = Process(target=interchange.starter,
args=(comm_q,),
kwargs={"client_ports": (self.outgoing_q.port,
self.incoming_q.port,
self.command_client.port),
"worker_ports": self.worker_ports,
| python | {
"resource": ""
} |
q254481 | HighThroughputExecutor.hold_worker | validation | def hold_worker(self, worker_id):
"""Puts a worker on hold, preventing scheduling of additional tasks to it.
This is called "hold" mostly because this only stops scheduling of tasks,
and does not actually kill | python | {
"resource": ""
} |
q254482 | HighThroughputExecutor._hold_block | validation | def _hold_block(self, block_id):
""" Sends hold command to all managers which are in a specific block
Parameters
----------
block_id : str
Block identifier of the block to be put on hold
"""
managers = self.connected_managers
for | python | {
"resource": ""
} |
q254483 | HighThroughputExecutor.scale_out | validation | def scale_out(self, blocks=1):
"""Scales out the number of blocks by "blocks"
Raises:
NotImplementedError
"""
r = []
for i in range(blocks):
if self.provider:
external_block_id = str(len(self.blocks))
launch_cmd = self.launch_cmd.format(block_id=external_block_id)
internal_block = self.provider.submit(launch_cmd, 1, 1)
logger.debug("Launched block {}->{}".format(external_block_id, internal_block))
if not internal_block:
raise(ScalingFailed(self.provider.label,
| python | {
"resource": ""
} |
q254484 | HighThroughputExecutor.status | validation | def status(self):
"""Return status of all blocks."""
status = []
if self.provider:
| python | {
"resource": ""
} |
q254485 | I2CDevice.readinto | validation | def readinto(self, buf, **kwargs):
"""
Read into ``buf`` from the device. The number of bytes read will be the
length of ``buf``.
If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buf[start:end]``. This will not cause an allocation like
``buf[start:end]`` will so it saves memory.
:param bytearray buffer: buffer to write into
| python | {
"resource": ""
} |
q254486 | I2CDevice.write | validation | def write(self, buf, **kwargs):
"""
Write the bytes from ``buffer`` to the device. Transmits a stop bit if
``stop`` is set.
If ``start`` or ``end`` is provided, then the buffer will be sliced
as if ``buffer[start:end]``. This will not cause an allocation like
``buffer[start:end]`` will so it saves | python | {
"resource": ""
} |
q254487 | I2CDevice.write_then_readinto | validation | def write_then_readinto(self, out_buffer, in_buffer, *,
out_start=0, out_end=None, in_start=0, in_end=None, stop=True):
"""
Write the bytes from ``out_buffer`` to the device, then immediately
reads into ``in_buffer`` from the device. The number of bytes read
will be the length of ``in_buffer``.
Transmits a stop bit after the write, if ``stop`` is set.
If ``out_start`` or ``out_end`` is provided, then the output buffer
will be sliced as if ``out_buffer[out_start:out_end]``. This will
not cause an allocation like ``buffer[out_start:out_end]`` will so
it saves memory.
If ``in_start`` or ``in_end`` is provided, then the input buffer
will be sliced as if ``in_buffer[in_start:in_end]``. This will not
cause an allocation like ``in_buffer[in_start:in_end]`` will so
it saves memory.
:param bytearray out_buffer: buffer containing the bytes to write
:param bytearray in_buffer: buffer containing the bytes to read into
:param int out_start: Index to start writing from
:param int out_end: Index to read up to but not include
| python | {
"resource": ""
} |
q254488 | sixteen_oscillator_two_stimulated_ensembles_grid | validation | def sixteen_oscillator_two_stimulated_ensembles_grid():
"Not accurate false due to spikes are observed"
parameters = legion_parameters();
parameters.teta_x = -1.1;
template_dynamic_legion(16, 2000, 1500, conn_type = conn_type.GRID_FOUR, params = parameters, stimulus = [1, 1, 1, 0,
1, 1, 1, 0,
| python | {
"resource": ""
} |
q254489 | cleanup_old_versions | validation | def cleanup_old_versions(
src, keep_last_versions,
config_file='config.yaml', profile_name=None,
):
"""Deletes old deployed versions of the function in AWS Lambda.
Won't delete $Latest and any aliased version
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param int keep_last_versions:
The number of recent versions to keep and not delete
"""
if keep_last_versions <= 0:
print("Won't delete all versions. Please do this manually")
else:
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
profile_name = cfg.get('profile')
aws_access_key_id = cfg.get('aws_access_key_id')
aws_secret_access_key = cfg.get('aws_secret_access_key')
client = get_client(
'lambda', profile_name, aws_access_key_id, aws_secret_access_key,
cfg.get('region'),
)
response = client.list_versions_by_function(
FunctionName=cfg.get('function_name'),
)
versions = response.get('Versions')
if len(response.get('Versions')) < keep_last_versions:
print('Nothing to delete. (Too few | python | {
"resource": ""
} |
q254490 | deploy | validation | def deploy(
src, requirements=None, local_package=None,
config_file='config.yaml', profile_name=None,
preserve_vpc=False
):
"""Deploys a new function to AWS Lambda.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Copy all the pip dependencies required to run your code into a temporary
# folder then add the handler file in the root of this directory.
# Zip the contents of this | python | {
"resource": ""
} |
q254491 | deploy_s3 | validation | def deploy_s3(
src, requirements=None, local_package=None,
config_file='config.yaml', profile_name=None,
preserve_vpc=False
):
"""Deploys a new function via AWS S3.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Copy all the pip dependencies required to run your code into a temporary
# folder then add the handler file in the root of this directory.
# Zip the contents of this folder into a single file and output to the dist
# directory.
| python | {
"resource": ""
} |
q254492 | upload | validation | def upload(
src, requirements=None, local_package=None,
config_file='config.yaml', profile_name=None,
):
"""Uploads a new function to AWS S3.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Copy all the pip dependencies required to run your code into a temporary
# folder | python | {
"resource": ""
} |
q254493 | invoke | validation | def invoke(
src, event_file='event.json',
config_file='config.yaml', profile_name=None,
verbose=False,
):
"""Simulates a call to your function.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str alt_event:
An optional argument to override which event file to use.
:param bool verbose:
Whether to print out verbose details.
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Set AWS_PROFILE environment variable based on `--profile` option.
if profile_name:
os.environ['AWS_PROFILE'] = profile_name
# Load environment variables from the config file into the actual | python | {
"resource": ""
} |
q254494 | init | validation | def init(src, minimal=False):
"""Copies template files to a given directory.
:param str src:
The path to output the template lambda project files.
:param bool minimal:
Minimal possible template files (excludes event.json).
"""
templates_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'project_templates',
)
for filename in os.listdir(templates_path):
| python | {
"resource": ""
} |
q254495 | build | validation | def build(
src, requirements=None, local_package=None,
config_file='config.yaml', profile_name=None,
):
"""Builds the file bundle.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Get the absolute path to the output directory and create it if it doesn't
# already exist.
dist_directory = cfg.get('dist_directory', 'dist')
path_to_dist = os.path.join(src, dist_directory)
mkdir(path_to_dist)
# Combine the name of the Lambda function with the current timestamp to use
# for the output filename.
function_name = cfg.get('function_name')
output_filename = '{0}-{1}.zip'.format(timestamp(), function_name)
path_to_temp = mkdtemp(prefix='aws-lambda')
pip_install_to_target(
path_to_temp,
requirements=requirements,
local_package=local_package,
)
# Hack for Zope.
if 'zope' in os.listdir(path_to_temp):
print(
'Zope packages detected; fixing Zope package paths to '
'make them importable.',
)
# Touch.
with open(os.path.join(path_to_temp, 'zope/__init__.py'), 'wb'):
pass
# Gracefully handle whether ".zip" was included in the filename or not.
output_filename = (
'{0}.zip'.format(output_filename)
if not output_filename.endswith('.zip')
else output_filename
)
# Allow definition of source code directories we want to build into our
# zipped package.
build_config = defaultdict(**cfg.get('build', {}))
build_source_directories = build_config.get('source_directories', '')
build_source_directories = (
build_source_directories
if build_source_directories is not None
else ''
)
source_directories = [
d.strip() for d in build_source_directories.split(',')
]
files = []
for filename in os.listdir(src):
if os.path.isfile(filename):
if filename == '.DS_Store':
continue
| python | {
"resource": ""
} |
q254496 | get_callable_handler_function | validation | def get_callable_handler_function(src, handler):
"""Tranlate a string of the form "module.function" into a callable
function.
:param str src:
The path to your Lambda project containing a valid handler file.
:param str handler:
A dot delimited string representing the `<module>.<function name>`.
"""
# "cd" into `src` directory.
os.chdir(src)
module_name, function_name | python | {
"resource": ""
} |
q254497 | _install_packages | validation | def _install_packages(path, packages):
"""Install all packages listed to the target directory.
Ignores any package that includes Python itself and python-lambda as well
since its only needed for deploying and not running the code
:param str path:
Path to copy installed pip packages to.
:param list packages:
A list of packages to be installed via pip.
"""
def _filter_blacklist(package):
| python | {
"resource": ""
} |
q254498 | get_role_name | validation | def get_role_name(region, account_id, role):
"""Shortcut to insert the `account_id` and `role` into the iam string."""
prefix | python | {
"resource": ""
} |
q254499 | get_account_id | validation | def get_account_id(
profile_name, aws_access_key_id, aws_secret_access_key,
region=None,
):
"""Query STS for a users' account_id"""
client = get_client(
'sts', profile_name, | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.