Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def function_name(self):
if self._function_identifier:
return self._function_identifier
# Function Identifier is *not* provided. If there is only one function in the template,
# default to it.
all_functions = [f for f in... | [
"\n Returns name of the function to invoke. If no function identifier is provided, this method will return name of\n the only function from the template\n\n :return string: Name of the function\n :raises InvokeContextException: If function identifier is not provided\n "
] |
Please provide a description of the function:def local_lambda_runner(self):
layer_downloader = LayerDownloader(self._layer_cache_basedir, self.get_cwd())
image_builder = LambdaImage(layer_downloader,
self._skip_pull_image,
... | [
"\n Returns an instance of the runner capable of running Lambda functions locally\n\n :return samcli.commands.local.lib.local_lambda.LocalLambdaRunner: Runner configured to run Lambda functions\n locally\n "
] |
Please provide a description of the function:def stdout(self):
stream = self._log_file_handle if self._log_file_handle else osutils.stdout()
return StreamWriter(stream, self._is_debugging) | [
"\n Returns stream writer for stdout to output Lambda function logs to\n\n Returns\n -------\n samcli.lib.utils.stream_writer.StreamWriter\n Stream writer for stdout\n "
] |
Please provide a description of the function:def stderr(self):
stream = self._log_file_handle if self._log_file_handle else osutils.stderr()
return StreamWriter(stream, self._is_debugging) | [
"\n Returns stream writer for stderr to output Lambda function errors to\n\n Returns\n -------\n samcli.lib.utils.stream_writer.StreamWriter\n Stream writer for stderr\n "
] |
Please provide a description of the function:def get_cwd(self):
cwd = os.path.dirname(os.path.abspath(self._template_file))
if self._docker_volume_basedir:
cwd = self._docker_volume_basedir
return cwd | [
"\n Get the working directory. This is usually relative to the directory that contains the template. If a Docker\n volume location is specified, it takes preference\n\n All Lambda function code paths are resolved relative to this working directory\n\n :return string: Working directory\n ... |
Please provide a description of the function:def _get_env_vars_value(filename):
if not filename:
return None
# Try to read the file and parse it as JSON
try:
with open(filename, 'r') as fp:
return json.load(fp)
except Exception as ex:
... | [
"\n If the user provided a file containing values of environment variables, this method will read the file and\n return its value\n\n :param string filename: Path to file containing environment variable values\n :return dict: Value of environment variables, if provided. None otherwise\n ... |
Please provide a description of the function:def _get_debug_context(debug_port, debug_args, debugger_path):
if debug_port and debugger_path:
try:
debugger = Path(debugger_path).resolve(strict=True)
except OSError as error:
if error.errno == errno.... | [
"\n Creates a DebugContext if the InvokeContext is in a debugging mode\n\n Parameters\n ----------\n debug_port int\n Port to bind the debugger to\n debug_args str\n Additional arguments passed to the debugger\n debugger_path str\n Path to ... |
Please provide a description of the function:def _read_socket(socket):
# Keep reading the stream until the stream terminates
while True:
try:
payload_type, payload_size = _read_header(socket)
if payload_size < 0:
# Something is wrong with the data stream. ... | [
"\n The stdout and stderr data from the container multiplexed into one stream of response from the Docker API.\n It follows the protocol described here https://docs.docker.com/engine/api/v1.30/#operation/ContainerAttach.\n The stream starts with a 8 byte header that contains the frame type and also payload... |
Please provide a description of the function:def _read_payload(socket, payload_size):
remaining = payload_size
while remaining > 0:
# Try and read as much as possible
data = read(socket, remaining)
if data is None:
# ``read`` will terminate with an empty string. This i... | [
"\n From the given socket, reads and yields payload of the given size. With sockets, we don't receive all data at\n once. Therefore this method will yield each time we read some data from the socket until the payload_size has\n reached or socket has no more data.\n\n Parameters\n ----------\n sock... |
Please provide a description of the function:def debug_option(f):
def callback(ctx, param, value):
state = ctx.ensure_object(Context)
state.debug = value
return value
return click.option('--debug',
expose_value=False,
is_flag=True,
... | [
"\n Configures --debug option for CLI\n\n :param f: Callback Function to be passed to Click\n "
] |
Please provide a description of the function:def region_option(f):
def callback(ctx, param, value):
state = ctx.ensure_object(Context)
state.region = value
return value
return click.option('--region',
expose_value=False,
help='Set the... | [
"\n Configures --region option for CLI\n\n :param f: Callback Function to be passed to Click\n "
] |
Please provide a description of the function:def profile_option(f):
def callback(ctx, param, value):
state = ctx.ensure_object(Context)
state.profile = value
return value
return click.option('--profile',
expose_value=False,
help='Sele... | [
"\n Configures --profile option for CLI\n\n :param f: Callback Function to be passed to Click\n "
] |
Please provide a description of the function:def resource_not_found(function_name):
exception_tuple = LambdaErrorResponses.ResourceNotFoundException
return BaseLocalService.service_response(
LambdaErrorResponses._construct_error_response_body(
LambdaErrorResponses.U... | [
"\n Creates a Lambda Service ResourceNotFound Response\n\n Parameters\n ----------\n function_name str\n Name of the function that was requested to invoke\n\n Returns\n -------\n Flask.Response\n A response object representing the ResourceNotFou... |
Please provide a description of the function:def invalid_request_content(message):
exception_tuple = LambdaErrorResponses.InvalidRequestContentException
return BaseLocalService.service_response(
LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.USER_ERROR, me... | [
"\n Creates a Lambda Service InvalidRequestContent Response\n\n Parameters\n ----------\n message str\n Message to be added to the body of the response\n\n Returns\n -------\n Flask.Response\n A response object representing the InvalidRequestCon... |
Please provide a description of the function:def unsupported_media_type(content_type):
exception_tuple = LambdaErrorResponses.UnsupportedMediaTypeException
return BaseLocalService.service_response(
LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.USER_ERROR,... | [
"\n Creates a Lambda Service UnsupportedMediaType Response\n\n Parameters\n ----------\n content_type str\n Content Type of the request that was made\n\n Returns\n -------\n Flask.Response\n A response object representing the UnsupportedMediaTyp... |
Please provide a description of the function:def generic_service_exception(*args):
exception_tuple = LambdaErrorResponses.ServiceException
return BaseLocalService.service_response(
LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.SERVICE_ERROR, "ServiceExcep... | [
"\n Creates a Lambda Service Generic ServiceException Response\n\n Parameters\n ----------\n args list\n List of arguments Flask passes to the method\n\n Returns\n -------\n Flask.Response\n A response object representing the GenericServiceExcep... |
Please provide a description of the function:def generic_path_not_found(*args):
exception_tuple = LambdaErrorResponses.PathNotFoundException
return BaseLocalService.service_response(
LambdaErrorResponses._construct_error_response_body(
LambdaErrorResponses.LOCAL_SER... | [
"\n Creates a Lambda Service Generic PathNotFound Response\n\n Parameters\n ----------\n args list\n List of arguments Flask passes to the method\n\n Returns\n -------\n Flask.Response\n A response object representing the GenericPathNotFound Err... |
Please provide a description of the function:def generic_method_not_allowed(*args):
exception_tuple = LambdaErrorResponses.MethodNotAllowedException
return BaseLocalService.service_response(
LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.LOCAL_SERVICE_ERRO... | [
"\n Creates a Lambda Service Generic MethodNotAllowed Response\n\n Parameters\n ----------\n args list\n List of arguments Flask passes to the method\n\n Returns\n -------\n Flask.Response\n A response object representing the GenericMethodNotAll... |
Please provide a description of the function:def do_cli(ctx, template):
sam_template = _read_sam_file(template)
iam_client = boto3.client('iam')
validator = SamTemplateValidator(sam_template, ManagedPolicyLoader(iam_client))
try:
validator.is_valid()
except InvalidSamDocumentExceptio... | [
"\n Implementation of the ``cli`` method, just separated out for unit testing purposes\n "
] |
Please provide a description of the function:def _read_sam_file(template):
if not os.path.exists(template):
click.secho("SAM Template Not Found", bg='red')
raise SamTemplateNotFoundException("Template at {} is not found".format(template))
with click.open_file(template, 'r') as sam_template... | [
"\n Reads the file (json and yaml supported) provided and returns the dictionary representation of the file.\n\n :param str template: Path to the template file\n :return dict: Dictionary representing the SAM Template\n :raises: SamTemplateNotFoundException when the template file does not exist\n "
] |
Please provide a description of the function:def resolve_code_path(cwd, codeuri):
LOG.debug("Resolving code path. Cwd=%s, CodeUri=%s", cwd, codeuri)
# First, let us figure out the current working directory.
# If current working directory is not provided, then default to the directory where the CLI is ... | [
"\n Returns path to the function code resolved based on current working directory.\n\n Parameters\n ----------\n cwd str\n Current working directory\n codeuri\n CodeURI of the function. This should contain the path to the function code\n\n Returns\n -------\n str\n Absol... |
Please provide a description of the function:def convert_path_to_flask(path):
proxy_sub_path = APIGW_TO_FLASK_REGEX.sub(FLASK_CAPTURE_ALL_PATH, path)
# Replace the '{' and '}' with '<' and '>' respectively
return proxy_sub_path.replace(LEFT_BRACKET, LEFT_ANGLE_BRACKET).replace(RIGHT_BR... | [
"\n Converts a Path from an Api Gateway defined path to one that is accepted by Flask\n\n Examples:\n\n '/id/{id}' => '/id/<id>'\n '/{proxy+}' => '/<path:proxy>'\n\n :param str path: Path to convert to Flask defined path\n :return str: Path representing a Flask path\n ... |
Please provide a description of the function:def convert_path_to_api_gateway(path):
proxy_sub_path = FLASK_TO_APIGW_REGEX.sub(PROXY_PATH_PARAMS, path)
# Replace the '<' and '>' with '{' and '}' respectively
return proxy_sub_path.replace(LEFT_ANGLE_BRACKET, LEFT_BRACKET).replace(RIGHT_A... | [
"\n Converts a Path from a Flask defined path to one that is accepted by Api Gateway\n\n Examples:\n\n '/id/<id>' => '/id/{id}'\n '/<path:proxy>' => '/{proxy+}'\n\n :param str path: Path to convert to Api Gateway defined path\n :return str: Path representing an Api Gateway ... |
Please provide a description of the function:def get_function_name(integration_uri):
arn = LambdaUri._get_function_arn(integration_uri)
LOG.debug("Extracted Function ARN: %s", arn)
return LambdaUri._get_function_name_from_arn(arn) | [
"\n Gets the name of the function from the Integration URI ARN. This is a best effort service which returns None\n if function name could not be parsed. This can happen when the ARN is an intrinsic function which is too\n complex or the ARN is not a Lambda integration.\n\n Parameters\n ... |
Please provide a description of the function:def _get_function_arn(uri_data):
if not uri_data:
return None
if LambdaUri._is_sub_intrinsic(uri_data):
uri_data = LambdaUri._resolve_fn_sub(uri_data)
LOG.debug("Resolved Sub intrinsic function: %s", uri_data)
... | [
"\n Integration URI can be expressed in various shapes and forms. This method normalizes the Integration URI ARN\n and returns the Lambda Function ARN. Here are the different forms of Integration URI ARN:\n\n - String:\n - Fully resolved ARN\n - ARN with Stage Variables:\n... |
Please provide a description of the function:def _get_function_name_from_arn(function_arn):
if not function_arn:
return None
matches = re.match(LambdaUri._REGEX_GET_FUNCTION_NAME, function_arn)
if not matches or not matches.groups():
LOG.debug("No Lambda functi... | [
"\n Given the integration ARN, extract the Lambda function name from the ARN. If there\n are stage variables, or other unsupported formats, this function will return None.\n\n Parameters\n ----------\n function_arn : basestring or None\n Function ARN from the swagger do... |
Please provide a description of the function:def _resolve_fn_sub(uri_data):
# Try the short form of Fn::Sub syntax where the value is the ARN
arn = uri_data[LambdaUri._FN_SUB]
if isinstance(arn, list):
# This is the long form of Fn::Sub syntax
#
# {... | [
"\n Tries to resolve an Integration URI which contains Fn::Sub intrinsic function. This method tries to resolve\n and produce a string output.\n\n Example:\n {\n \"Fn::Sub\":\n \"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/... |
Please provide a description of the function:def _is_sub_intrinsic(data):
return isinstance(data, dict) and len(data) == 1 and LambdaUri._FN_SUB in data | [
"\n Is this input data a Fn::Sub intrinsic function\n\n Parameters\n ----------\n data\n Data to check\n\n Returns\n -------\n bool\n True if the data Fn::Sub intrinsic function\n "
] |
Please provide a description of the function:def do_cli(ctx, function_identifier, template, event, no_event, env_vars, debug_port, # pylint: disable=R0914
debug_args, debugger_path, docker_volume_basedir, docker_network, log_file, layer_cache_basedir,
skip_pull_image, force_image_build, parameter... | [
"\n Implementation of the ``cli`` method, just separated out for unit testing purposes\n "
] |
Please provide a description of the function:def _get_event(event_file_name):
if event_file_name == STDIN_FILE_NAME:
# If event is empty, listen to stdin for event data until EOF
LOG.info("Reading invoke payload from stdin (you can also pass it from file with --event)")
# click.open_file ... | [
"\n Read the event JSON data from the given file. If no file is provided, read the event from stdin.\n\n :param string event_file_name: Path to event file, or '-' for stdin\n :return string: Contents of the event file or stdin\n "
] |
Please provide a description of the function:def normalize(template_dict):
resources = template_dict.get(RESOURCES_KEY, {})
for logical_id, resource in resources.items():
resource_metadata = resource.get(METADATA_KEY, {})
asset_path = resource_metadata.get(ASSET_PATH_ME... | [
"\n Normalize all Resources in the template with the Metadata Key on the resource.\n\n This method will mutate the template\n\n Parameters\n ----------\n template_dict dict\n Dictionary representing the template\n\n "
] |
Please provide a description of the function:def _replace_property(property_key, property_value, resource, logical_id):
if property_key and property_value:
resource.get(PROPERTIES_KEY, {})[property_key] = property_value
elif property_key or property_value:
LOG.info("WARN... | [
"\n Replace a property with an asset on a given resource\n\n This method will mutate the template\n\n Parameters\n ----------\n property str\n The property to replace on the resource\n property_value str\n The new value of the property\n resourc... |
Please provide a description of the function:def _set_commands(package_names):
commands = {}
for pkg_name in package_names:
cmd_name = pkg_name.split('.')[-1]
commands[cmd_name] = pkg_name
return commands | [
"\n Extract the command name from package name. Last part of the module path is the command\n ie. if path is foo.bar.baz, then \"baz\" is the command name.\n\n :param package_names: List of package names\n :return: Dictionary with command name as key and the package name as value.\n ... |
Please provide a description of the function:def get_command(self, ctx, cmd_name):
if cmd_name not in self._commands:
logger.error("Command %s not available", cmd_name)
return
pkg_name = self._commands[cmd_name]
try:
mod = importlib.import_module(pk... | [
"\n Overrides method from ``click.MultiCommand`` that returns Click CLI object for given command name, if found.\n\n :param ctx: Click context\n :param cmd_name: Top-level command name\n :return: Click object representing the command\n "
] |
Please provide a description of the function:def write(self, output):
self._stream.write(output)
if self._auto_flush:
self._stream.flush() | [
"\n Writes specified text to the underlying stream\n\n Parameters\n ----------\n output bytes-like object\n Bytes to write\n "
] |
Please provide a description of the function:def get_workflow_config(runtime, code_dir, project_dir):
selectors_by_runtime = {
"python2.7": BasicWorkflowSelector(PYTHON_PIP_CONFIG),
"python3.6": BasicWorkflowSelector(PYTHON_PIP_CONFIG),
"python3.7": BasicWorkflowSelector(PYTHON_PIP_CON... | [
"\n Get a workflow config that corresponds to the runtime provided. This method examines contents of the project\n and code directories to determine the most appropriate workflow for the given runtime. Currently the decision is\n based on the presence of a supported manifest file. For runtimes that have mo... |
Please provide a description of the function:def supports_build_in_container(config):
def _key(c):
return str(c.language) + str(c.dependency_manager) + str(c.application_framework)
# This information could have beeen bundled inside the Workflow Config object. But we this way because
# ultimat... | [
"\n Given a workflow config, this method provides a boolean on whether the workflow can run within a container or not.\n\n Parameters\n ----------\n config namedtuple(Capability)\n Config specifying the particular build workflow\n\n Returns\n -------\n tuple(bool, str)\n True, if ... |
Please provide a description of the function:def get_config(self, code_dir, project_dir):
# Search for manifest first in code directory and then in the project directory.
# Search order is important here because we want to prefer the manifest present within the code directory over
# a ... | [
"\n Finds a configuration by looking for a manifest in the given directories.\n\n Returns\n -------\n samcli.lib.build.workflow_config.CONFIG\n A supported configuration if one is found\n\n Raises\n ------\n ValueError\n If none of the supported... |
Please provide a description of the function:def intrinsics_multi_constructor(loader, tag_prefix, node):
# Get the actual tag name excluding the first exclamation
tag = node.tag[1:]
# Some intrinsic functions doesn't support prefix "Fn::"
prefix = "Fn::"
if tag in ["Ref", "Condition"]:
... | [
"\n YAML constructor to parse CloudFormation intrinsics.\n This will return a dictionary with key being the instrinsic name\n "
] |
Please provide a description of the function:def yaml_parse(yamlstr):
try:
# PyYAML doesn't support json as well as it should, so if the input
# is actually just json it is better to parse it with the standard
# json parser.
return json.loads(yamlstr)
except ValueError:
... | [
"Parse a yaml string"
] |
Please provide a description of the function:def encode(self, tags, encoding, values_to_sub):
for tag in tags:
if tags[tag].get(encoding) != "None":
if tags[tag].get(encoding) == "url":
values_to_sub[tag] = self.url_encode(values_to_sub[tag])
... | [
"\n reads the encoding type from the event-mapping.json\n and determines whether a value needs encoding\n\n Parameters\n ----------\n tags: dict\n the values of a particular event that can be substituted\n within the event json\n encoding: string\n ... |
Please provide a description of the function:def generate_event(self, service_name, event_type, values_to_sub):
# set variables for easy calling
tags = self.event_mapping[service_name][event_type]['tags']
values_to_sub = self.encode(tags, 'encoding', values_to_sub)
# construct... | [
"\n opens the event json, substitutes the values in, and\n returns the customized event json\n\n Parameters\n ----------\n service_name: string\n name of the top level service (S3, apigateway, etc)\n event_type: string\n name of the event underneath th... |
Please provide a description of the function:def underline(self, msg):
return click.style(msg, underline=True) if self.colorize else msg | [
"Underline the input"
] |
Please provide a description of the function:def _color(self, msg, color):
kwargs = {'fg': color}
return click.style(msg, **kwargs) if self.colorize else msg | [
"Internal helper method to add colors to input"
] |
Please provide a description of the function:def fetch(self, log_group_name, start=None, end=None, filter_pattern=None):
kwargs = {
"logGroupName": log_group_name,
"interleaved": True
}
if start:
kwargs["startTime"] = to_timestamp(start)
if... | [
"\n Fetch logs from all streams under the given CloudWatch Log Group and yields in the output. Optionally, caller\n can filter the logs using a pattern or a start/end time.\n\n Parameters\n ----------\n log_group_name : string\n Name of CloudWatch Logs Group to query.\n... |
Please provide a description of the function:def tail(self, log_group_name, start=None, filter_pattern=None, max_retries=1000, poll_interval=0.3):
# On every poll, startTime of the API call is the timestamp of last record observed
latest_event_time = 0 # Start of epoch
if start:
... | [
"\n ** This is a long blocking call **\n\n Fetches logs from CloudWatch logs similar to the ``fetch`` method, but instead of stopping after all logs have\n been fetched, this method continues to poll CloudWatch for new logs. So this essentially simulates the\n ``tail -f`` bash command.\n... |
Please provide a description of the function:def _compute_layer_version(is_defined_within_template, arn):
if is_defined_within_template:
return None
try:
_, layer_version = arn.rsplit(':', 1)
layer_version = int(layer_version)
except ValueError:
... | [
"\n Parses out the Layer version from the arn\n\n Parameters\n ----------\n is_defined_within_template bool\n True if the resource is a Ref to a resource otherwise False\n arn str\n ARN of the Resource\n\n Returns\n -------\n int\n ... |
Please provide a description of the function:def _compute_layer_name(is_defined_within_template, arn):
# If the Layer is defined in the template, the arn will represent the LogicalId of the LayerVersion Resource,
# which does not require creating a name based on the arn.
if is_defined_... | [
"\n Computes a unique name based on the LayerVersion Arn\n\n Format:\n <Name of the LayerVersion>-<Version of the LayerVersion>-<sha256 of the arn>\n\n Parameters\n ----------\n is_defined_within_template bool\n True if the resource is a Ref to a resource otherwi... |
Please provide a description of the function:def mkdir_temp(mode=0o755):
temp_dir = None
try:
temp_dir = tempfile.mkdtemp()
os.chmod(temp_dir, mode)
yield temp_dir
finally:
if temp_dir:
shutil.rmtree(temp_dir) | [
"\n Context manager that makes a temporary directory and yields it name. Directory is deleted\n after the context exits\n\n Parameters\n ----------\n mode : octal\n Permissions to apply to the directory. Defaults to '755' because don't want directories world writable\n\n Returns\n ------... |
Please provide a description of the function:def stdout():
# We write all of the data to stdout with bytes, typically io.BytesIO. stdout in Python2
# accepts bytes but Python3 does not. This is due to a type change on the attribute. To keep
# this consistent, we leave Python2 the same and get the .buf... | [
"\n Returns the stdout as a byte stream in a Py2/PY3 compatible manner\n\n Returns\n -------\n io.BytesIO\n Byte stream of Stdout\n "
] |
Please provide a description of the function:def stderr():
# We write all of the data to stderr with bytes, typically io.BytesIO. stderr in Python2
# accepts bytes but Python3 does not. This is due to a type change on the attribute. To keep
# this consistent, we leave Python2 the same and get the .buf... | [
"\n Returns the stderr as a byte stream in a Py2/PY3 compatible manner\n\n Returns\n -------\n io.BytesIO\n Byte stream of stderr\n "
] |
Please provide a description of the function:def download_all(self, layers, force=False):
layer_dirs = []
for layer in layers:
layer_dirs.append(self.download(layer, force))
return layer_dirs | [
"\n Download a list of layers to the cache\n\n Parameters\n ----------\n layers list(samcli.commands.local.lib.provider.Layer)\n List of Layers representing the layer to be downloaded\n force bool\n True to download the layer even if it exists already on the ... |
Please provide a description of the function:def download(self, layer, force=False):
if layer.is_defined_within_template:
LOG.info("%s is a local Layer in the template", layer.name)
layer.codeuri = resolve_code_path(self.cwd, layer.codeuri)
return layer
# di... | [
"\n Download a given layer to the local cache.\n\n Parameters\n ----------\n layer samcli.commands.local.lib.provider.Layer\n Layer representing the layer to be downloaded.\n force bool\n True to download the layer even if it exists already on the system\n\n ... |
Please provide a description of the function:def _fetch_layer_uri(self, layer):
try:
layer_version_response = self.lambda_client.get_layer_version(LayerName=layer.layer_arn,
VersionNumber=layer.version)
except... | [
"\n Fetch the Layer Uri based on the LayerVersion Arn\n\n Parameters\n ----------\n layer samcli.commands.local.lib.provider.LayerVersion\n LayerVersion to fetch\n\n Returns\n -------\n str\n The Uri to download the LayerVersion Content from\n\n... |
Please provide a description of the function:def _create_cache(layer_cache):
Path(layer_cache).mkdir(mode=0o700, parents=True, exist_ok=True) | [
"\n Create the Cache directory if it does not exist.\n\n Parameters\n ----------\n layer_cache\n Directory to where the layers should be cached\n\n Returns\n -------\n None\n\n "
] |
Please provide a description of the function:def is_valid(self):
managed_policy_map = self.managed_policy_loader.load()
sam_translator = Translator(managed_policy_map=managed_policy_map,
sam_parser=self.sam_parser,
plugins... | [
"\n Runs the SAM Translator to determine if the template provided is valid. This is similar to running a\n ChangeSet in CloudFormation for a SAM Template\n\n Raises\n -------\n InvalidSamDocumentException\n If the template is not valid, an InvalidSamDocumentException i... |
Please provide a description of the function:def _replace_local_codeuri(self):
all_resources = self.sam_template.get("Resources", {})
for _, resource in all_resources.items():
resource_type = resource.get("Type")
resource_dict = resource.get("Properties")
... | [
"\n Replaces the CodeUri in AWS::Serverless::Function and DefinitionUri in AWS::Serverless::Api to a fake\n S3 Uri. This is to support running the SAM Translator with valid values for these fields. If this in not done,\n the template is invalid in the eyes of SAM Translator (the translator does... |
Please provide a description of the function:def _update_to_s3_uri(property_key, resource_property_dict, s3_uri_value="s3://bucket/value"):
uri_property = resource_property_dict.get(property_key, ".")
# ignore if dict or already an S3 Uri
if isinstance(uri_property, dict) or SamTemplat... | [
"\n Updates the 'property_key' in the 'resource_property_dict' to the value of 's3_uri_value'\n\n Note: The function will mutate the resource_property_dict that is pass in\n\n Parameters\n ----------\n property_key str, required\n Key in the resource_property_dict\n ... |
Please provide a description of the function:def formatter(self):
formatter_chain = [
LambdaLogMsgFormatters.colorize_errors,
# Format JSON "before" highlighting the keywords. Otherwise, JSON will be invalid from all the
# ANSI color codes and fail to pretty print
... | [
"\n Creates and returns a Formatter capable of nicely formatting Lambda function logs\n\n Returns\n -------\n LogsFormatter\n "
] |
Please provide a description of the function:def log_group_name(self):
function_id = self._function_name
if self._stack_name:
function_id = self._get_resource_id_from_stack(self._cfn_client, self._stack_name, self._function_name)
LOG.debug("Function with LogicalId '%s' ... | [
"\n Name of the AWS CloudWatch Log Group that we will be querying. It generates the name based on the\n Lambda Function name and stack name provided.\n\n Returns\n -------\n str\n Name of the CloudWatch Log Group\n "
] |
Please provide a description of the function:def _parse_time(time_str, property_name):
if not time_str:
return
parsed = parse_date(time_str)
if not parsed:
raise UserException("Unable to parse the time provided by '{}'".format(property_name))
return to_... | [
"\n Parse the time from the given string, convert to UTC, and return the datetime object\n\n Parameters\n ----------\n time_str : str\n The time to parse\n\n property_name : str\n Name of the property where this time came from. Used in the exception raised if... |
Please provide a description of the function:def _get_resource_id_from_stack(cfn_client, stack_name, logical_id):
LOG.debug("Getting resource's PhysicalId from AWS CloudFormation stack. StackName=%s, LogicalId=%s",
stack_name, logical_id)
try:
response = cfn_clie... | [
"\n Given the LogicalID of a resource, call AWS CloudFormation to get physical ID of the resource within\n the specified stack.\n\n Parameters\n ----------\n cfn_client\n CloudFormation client provided by AWS SDK\n\n stack_name : str\n Name of the stac... |
Please provide a description of the function:def get_template(template_dict, parameter_overrides=None):
template_dict = template_dict or {}
if template_dict:
template_dict = SamTranslatorWrapper(template_dict).run_plugins()
template_dict = SamBaseProvider._resolve_paramete... | [
"\n Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been run\n and parameter values have been substituted.\n\n Parameters\n ----------\n template_dict : dict\n unprocessed SAM template dictionary\n\n parameter_overrid... |
Please provide a description of the function:def _resolve_parameters(template_dict, parameter_overrides):
parameter_values = SamBaseProvider._get_parameter_values(template_dict, parameter_overrides)
supported_intrinsics = {action.intrinsic_name: action() for action in SamBaseProvider._SUPPORT... | [
"\n In the given template, apply parameter values to resolve intrinsic functions\n\n Parameters\n ----------\n template_dict : dict\n SAM Template\n\n parameter_overrides : dict\n Values for template parameters provided by user\n\n Returns\n ---... |
Please provide a description of the function:def _get_parameter_values(template_dict, parameter_overrides):
default_values = SamBaseProvider._get_default_parameter_values(template_dict)
# NOTE: Ordering of following statements is important. It makes sure that any user-supplied values
... | [
"\n Construct a final list of values for CloudFormation template parameters based on user-supplied values,\n default values provided in template, and sane defaults for pseudo-parameters.\n\n Parameters\n ----------\n template_dict : dict\n SAM template dictionary\n\n ... |
Please provide a description of the function:def _get_default_parameter_values(sam_template):
default_values = {}
parameter_definition = sam_template.get("Parameters", None)
if not parameter_definition or not isinstance(parameter_definition, dict):
LOG.debug("No Parameters... | [
"\n Method to read default values for template parameters and return it\n Example:\n If the template contains the following parameters defined\n Parameters:\n Param1:\n Type: String\n Default: default_value1\n Param2:\n T... |
Please provide a description of the function:def to_posix_path(code_path):
return re.sub("^([A-Za-z])+:",
lambda match: posixpath.sep + match.group().replace(":", "").lower(),
pathlib.PureWindowsPath(code_path).as_posix()) if os.name == "nt" else code_path | [
"\n Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.\n\n Parameters\n ----------\n code_path : str\n Directory in the host operating system that should be mounted within the container.\n Returns\n -------\n str\n Posix equ... |
Please provide a description of the function:def _get_additional_options(runtime, debug_options):
if not debug_options:
return None
opts = {}
if runtime == Runtime.go1x.value:
# These options are required for delve to function properly inside a docker container... | [
"\n Return additional Docker container options. Used by container debug mode to enable certain container\n security options.\n :param DebugContext debug_options: DebugContext for the runtime of the container.\n :return dict: Dictionary containing additional arguments to be passed to cont... |
Please provide a description of the function:def _get_entry_point(runtime, debug_options=None): # pylint: disable=too-many-branches
if not debug_options:
return None
if runtime not in LambdaContainer._supported_runtimes():
raise DebuggingNotSupported(
... | [
"\n Returns the entry point for the container. The default value for the entry point is already configured in the\n Dockerfile. We override this default specifically when enabling debugging. The overridden entry point includes\n a few extra flags to start the runtime in debug mode.\n\n :... |
Please provide a description of the function:def _extract_apis(self, resources):
# Some properties like BinaryMediaTypes, Cors are set once on the resource but need to be applied to each API.
# For Implicit APIs, which are defined on the Function resource, these properties
# are define... | [
"\n Extract all Implicit Apis (Apis defined through Serverless Function with an Api Event\n\n :param dict resources: Dictionary of SAM/CloudFormation resources\n :return: List of nametuple Api\n "
] |
Please provide a description of the function:def _extract_from_serverless_api(self, logical_id, api_resource, collector):
properties = api_resource.get("Properties", {})
body = properties.get("DefinitionBody")
uri = properties.get("DefinitionUri")
binary_media = properties.get(... | [
"\n Extract APIs from AWS::Serverless::Api resource by reading and parsing Swagger documents. The result is added\n to the collector.\n\n Parameters\n ----------\n logical_id : str\n Logical ID of the resource\n\n api_resource : dict\n Resource definit... |
Please provide a description of the function:def _merge_apis(collector):
implicit_apis = []
explicit_apis = []
# Store implicit and explicit APIs separately in order to merge them later in the correct order
# Implicit APIs are defined on a resource with logicalID ServerlessRes... | [
"\n Quite often, an API is defined both in Implicit and Explicit API definitions. In such cases, Implicit API\n definition wins because that conveys clear intent that the API is backed by a function. This method will\n merge two such list of Apis with the right order of precedence. If a Path+Me... |
Please provide a description of the function:def _normalize_apis(apis):
result = list()
for api in apis:
for normalized_method in SamApiProvider._normalize_http_methods(api.method):
# _replace returns a copy of the namedtuple. This is the official way of creating co... | [
"\n Normalize the APIs to use standard method name\n\n Parameters\n ----------\n apis : list of samcli.commands.local.lib.provider.Api\n List of APIs to replace normalize\n\n Returns\n -------\n list of samcli.commands.local.lib.provider.Api\n L... |
Please provide a description of the function:def _extract_apis_from_function(logical_id, function_resource, collector):
resource_properties = function_resource.get("Properties", {})
serverless_function_events = resource_properties.get(SamApiProvider._FUNCTION_EVENT, {})
SamApiProvider.... | [
"\n Fetches a list of APIs configured for this SAM Function resource.\n\n Parameters\n ----------\n logical_id : str\n Logical ID of the resource\n\n function_resource : dict\n Contents of the function resource including its properties\n\n collector : ... |
Please provide a description of the function:def _extract_apis_from_events(function_logical_id, serverless_function_events, collector):
count = 0
for _, event in serverless_function_events.items():
if SamApiProvider._FUNCTION_EVENT_TYPE_API == event.get(SamApiProvider._TYPE):
... | [
"\n Given an AWS::Serverless::Function Event Dictionary, extract out all 'Api' events and store within the\n collector\n\n Parameters\n ----------\n function_logical_id : str\n LogicalId of the AWS::Serverless::Function\n\n serverless_function_events : dict\n ... |
Please provide a description of the function:def _convert_event_api(lambda_logical_id, event_properties):
path = event_properties.get(SamApiProvider._EVENT_PATH)
method = event_properties.get(SamApiProvider._EVENT_METHOD)
# An API Event, can have RestApiId property which designates the... | [
"\n Converts a AWS::Serverless::Function's Event Property to an Api configuration usable by the provider.\n\n :param str lambda_logical_id: Logical Id of the AWS::Serverless::Function\n :param dict event_properties: Dictionary of the Event's Property\n :return tuple: tuple of API resourc... |
Please provide a description of the function:def _normalize_http_methods(http_method):
if http_method.upper() == 'ANY':
for method in SamApiProvider._ANY_HTTP_METHODS:
yield method.upper()
else:
yield http_method.upper() | [
"\n Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all\n supported Http Methods on Api Gateway.\n\n :param str http_method: Http method\n :yield str: Either the input http_method or one of the _ANY_HTTP_METHODS (normalized Http Methods... |
Please provide a description of the function:def add_apis(self, logical_id, apis):
properties = self._get_properties(logical_id)
properties.apis.extend(apis) | [
"\n Stores the given APIs tagged under the given logicalId\n\n Parameters\n ----------\n logical_id : str\n LogicalId of the AWS::Serverless::Api resource\n\n apis : list of samcli.commands.local.lib.provider.Api\n List of APIs available in this resource\n ... |
Please provide a description of the function:def add_binary_media_types(self, logical_id, binary_media_types):
properties = self._get_properties(logical_id)
binary_media_types = binary_media_types or []
for value in binary_media_types:
normalized_value = self._normalize_bin... | [
"\n Stores the binary media type configuration for the API with given logical ID\n\n Parameters\n ----------\n logical_id : str\n LogicalId of the AWS::Serverless::Api resource\n\n binary_media_types : list of str\n List of binary media types supported by thi... |
Please provide a description of the function:def _get_apis_with_config(self, logical_id):
properties = self._get_properties(logical_id)
# These configs need to be applied to each API
binary_media = sorted(list(properties.binary_media_types)) # Also sort the list to keep the ordering ... | [
"\n Returns the list of APIs in this resource along with other extra configuration such as binary media types,\n cors etc. Additional configuration is merged directly into the API data because these properties, although\n defined globally, actually apply to each API.\n\n Parameters\n ... |
Please provide a description of the function:def _get_properties(self, logical_id):
if logical_id not in self.by_resource:
self.by_resource[logical_id] = self.Properties(apis=[],
# Use a set() to be able to easily de-dupe
... | [
"\n Returns the properties of resource with given logical ID. If a resource is not found, then it returns an\n empty data.\n\n Parameters\n ----------\n logical_id : str\n Logical ID of the resource\n\n Returns\n -------\n samcli.commands.local.lib.... |
Please provide a description of the function:def _unzip_file(filepath):
temp_dir = tempfile.mkdtemp()
if os.name == 'posix':
os.chmod(temp_dir, 0o755)
LOG.info("Decompressing %s", filepath)
unzip(filepath, temp_dir)
# The directory that Python returns might have symlinks. The Docke... | [
"\n Helper method to unzip a file to a temporary directory\n\n :param string filepath: Absolute path to this file\n :return string: Path to the temporary directory where it was unzipped\n "
] |
Please provide a description of the function:def invoke(self,
function_config,
event,
debug_context=None,
stdout=None,
stderr=None):
timer = None
# Update with event input
environ = function_config.env_vars
... | [
"\n Invoke the given Lambda function locally.\n\n ##### NOTE: THIS IS A LONG BLOCKING CALL #####\n This method will block until either the Lambda function completes or timed out, which could be seconds.\n A blocking call will block the thread preventing any other operations from happenin... |
Please provide a description of the function:def _configure_interrupt(self, function_name, timeout, container, is_debugging):
def timer_handler():
# NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures
LOG.info("Function '%s' ... | [
"\n When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.\n Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,\n we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C an... |
Please provide a description of the function:def _get_code_dir(self, code_path):
decompressed_dir = None
try:
if os.path.isfile(code_path) and code_path.endswith(self.SUPPORTED_ARCHIVE_EXTENSIONS):
decompressed_dir = _unzip_file(code_path)
yield de... | [
"\n Method to get a path to a directory where the Lambda function code is available. This directory will\n be mounted directly inside the Docker container.\n\n This method handles a few different cases for ``code_path``:\n - ``code_path``is a existent zip/jar file: Unzip in a temp di... |
Please provide a description of the function:def build(self, runtime, layers):
base_image = "{}:{}".format(self._DOCKER_LAMBDA_REPO_NAME, runtime)
# Don't build the image if there are no layers.
if not layers:
LOG.debug("Skipping building an image since no layers were defin... | [
"\n Build the image if one is not already on the system that matches the runtime and layers\n\n Parameters\n ----------\n runtime str\n Name of the Lambda runtime\n layers list(samcli.commands.local.lib.provider.Layer)\n List of layers\n\n Returns\n ... |
Please provide a description of the function:def _generate_docker_image_version(layers, runtime):
# Docker has a concept of a TAG on an image. This is plus the REPOSITORY is a way to determine
# a version of the image. We will produced a TAG for a combination of the runtime with the layers
... | [
"\n Generate the Docker TAG that will be used to create the image\n\n Parameters\n ----------\n layers list(samcli.commands.local.lib.provider.Layer)\n List of the layers\n\n runtime str\n Runtime of the image to create\n\n Returns\n -------\n ... |
Please provide a description of the function:def _build_image(self, base_image, docker_tag, layers):
dockerfile_content = self._generate_dockerfile(base_image, layers)
# Create dockerfile in the same directory of the layer cache
dockerfile_name = "dockerfile_" + str(uuid.uuid4())
... | [
"\n Builds the image\n\n Parameters\n ----------\n base_image str\n Base Image to use for the new image\n docker_tag\n Docker tag (REPOSITORY:TAG) to use when building the image\n layers list(samcli.commands.local.lib.provider.Layer)\n List ... |
Please provide a description of the function:def _generate_dockerfile(base_image, layers):
dockerfile_content = "FROM {}\n".format(base_image)
for layer in layers:
dockerfile_content = dockerfile_content + \
"ADD --chown=sbx_user1051:495 {} {}\n".fo... | [
"\n Generate the Dockerfile contents\n\n A generated Dockerfile will look like the following:\n ```\n FROM lambci/lambda:python3.6\n\n ADD --chown=sbx_user1051:495 layer1 /opt\n ADD --chown=sbx_user1051:495 layer2 /opt\n ```\n\n Parameters\n ----------\... |
Please provide a description of the function:def start(self):
routing_list = self._make_routing_list(self.api_provider)
if not routing_list:
raise NoApisDefined("No APIs available in SAM template")
static_dir_path = self._make_static_dir_path(self.cwd, self.static_dir)
... | [
"\n Creates and starts the local API Gateway service. This method will block until the service is stopped\n manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint\n to invoke the Lambda function and receive a response.\n\n NOTE: This is ... |
Please provide a description of the function:def _make_routing_list(api_provider):
routes = []
for api in api_provider.get_all():
route = Route(methods=[api.method], function_name=api.function_name, path=api.path,
binary_types=api.binary_media_types)
... | [
"\n Returns a list of routes to configure the Local API Service based on the APIs configured in the template.\n\n Parameters\n ----------\n api_provider : samcli.commands.local.lib.sam_api_provider.SamApiProvider\n\n Returns\n -------\n list(samcli.local.apigw.servic... |
Please provide a description of the function:def _print_routes(api_provider, host, port):
grouped_api_configs = {}
for api in api_provider.get_all():
key = "{}-{}".format(api.function_name, api.path)
config = grouped_api_configs.get(key, {})
config.setdefau... | [
"\n Helper method to print the APIs that will be mounted. This method is purely for printing purposes.\n This method takes in a list of Route Configurations and prints out the Routes grouped by path.\n Grouping routes by Function Name + Path is the bulk of the logic.\n\n Example output:\... |
Please provide a description of the function:def _make_static_dir_path(cwd, static_dir):
if not static_dir:
return None
static_dir_path = os.path.join(cwd, static_dir)
if os.path.exists(static_dir_path):
LOG.info("Mounting static files from %s at /", static_dir_... | [
"\n This method returns the path to the directory where static files are to be served from. If static_dir is a\n relative path, then it is resolved to be relative to the current working directory. If no static directory is\n provided, or if the resolved directory does not exist, this method wil... |
Please provide a description of the function:def create(self):
self._app = Flask(__name__)
path = '/2015-03-31/functions/<function_name>/invocations'
self._app.add_url_rule(path,
endpoint=path,
view_func=self._invoke_request... | [
"\n Creates a Flask Application that can be started.\n "
] |
Please provide a description of the function:def validate_request():
flask_request = request
request_data = flask_request.get_data()
if not request_data:
request_data = b'{}'
request_data = request_data.decode('utf-8')
try:
json.loads(request_d... | [
"\n Validates the incoming request\n\n The following are invalid\n 1. The Request data is not json serializable\n 2. Query Parameters are sent to the endpoint\n 3. The Request Content-Type is not application/json\n 4. 'X-Amz-Log-Type' header is not 'None'\n ... |
Please provide a description of the function:def _construct_error_handling(self):
self._app.register_error_handler(500, LambdaErrorResponses.generic_service_exception)
self._app.register_error_handler(404, LambdaErrorResponses.generic_path_not_found)
self._app.register_error_handler(405... | [
"\n Updates the Flask app with Error Handlers for different Error Codes\n\n "
] |
Please provide a description of the function:def _invoke_request_handler(self, function_name):
flask_request = request
request_data = flask_request.get_data()
if not request_data:
request_data = b'{}'
request_data = request_data.decode('utf-8')
stdout_str... | [
"\n Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming\n request and invoking the Local Lambda Function\n\n Parameters\n ----------\n function_name str\n Name of the function to invoke\n\n Returns\n ... |
Please provide a description of the function:def unzip(zip_file_path, output_dir, permission=None):
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
# For each item in the zip file, extract the file and set permissions if available
for file_info in zip_ref.infolist():
name = f... | [
"\n Unzip the given file into the given directory while preserving file permissions in the process.\n\n Parameters\n ----------\n zip_file_path : str\n Path to the zip file\n\n output_dir : str\n Path to the directory where the it should be unzipped to\n\n permission : octal int\n ... |
Please provide a description of the function:def _set_permissions(zip_file_info, extracted_path):
# Permission information is stored in first two bytes.
permission = zip_file_info.external_attr >> 16
if not permission:
# Zips created on certain Windows machines, however, might not have any per... | [
"\n Sets permissions on the extracted file by reading the ``external_attr`` property of given file info.\n\n Parameters\n ----------\n zip_file_info : zipfile.ZipInfo\n Object containing information about a file within a zip archive\n\n extracted_path : str\n Path where the file has bee... |
Please provide a description of the function:def unzip_from_uri(uri, layer_zip_path, unzip_output_dir, progressbar_label):
try:
get_request = requests.get(uri, stream=True, verify=os.environ.get('AWS_CA_BUNDLE', True))
with open(layer_zip_path, 'wb') as local_layer_file:
file_lengt... | [
"\n Download the LayerVersion Zip to the Layer Pkg Cache\n\n Parameters\n ----------\n uri str\n Uri to download from\n layer_zip_path str\n Path to where the content from the uri should be downloaded to\n unzip_output_dir str\n Path to unzip the zip to\n progressbar_label ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.