repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
awslabs/aws-sam-cli | samcli/commands/local/lib/provider.py | LayerVersion._compute_layer_name | def _compute_layer_name(is_defined_within_template, arn):
"""
Computes a unique name based on the LayerVersion Arn
Format:
<Name of the LayerVersion>-<Version of the LayerVersion>-<sha256 of the arn>
Parameters
----------
is_defined_within_template bool
True if the resource is a Ref to a resource otherwise False
arn str
ARN of the Resource
Returns
-------
str
A unique name that represents the LayerVersion
"""
# 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_within_template:
return arn
try:
_, layer_name, layer_version = arn.rsplit(':', 2)
except ValueError:
raise InvalidLayerVersionArn(arn + " is an Invalid Layer Arn.")
return LayerVersion.LAYER_NAME_DELIMETER.join([layer_name,
layer_version,
hashlib.sha256(arn.encode('utf-8')).hexdigest()[0:10]]) | python | def _compute_layer_name(is_defined_within_template, arn):
"""
Computes a unique name based on the LayerVersion Arn
Format:
<Name of the LayerVersion>-<Version of the LayerVersion>-<sha256 of the arn>
Parameters
----------
is_defined_within_template bool
True if the resource is a Ref to a resource otherwise False
arn str
ARN of the Resource
Returns
-------
str
A unique name that represents the LayerVersion
"""
# 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_within_template:
return arn
try:
_, layer_name, layer_version = arn.rsplit(':', 2)
except ValueError:
raise InvalidLayerVersionArn(arn + " is an Invalid Layer Arn.")
return LayerVersion.LAYER_NAME_DELIMETER.join([layer_name,
layer_version,
hashlib.sha256(arn.encode('utf-8')).hexdigest()[0:10]]) | [
"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_within_template",
":",
"return",
"arn",
"try",
":",
"_",
",",
"layer_name",
",",
"layer_version",
"=",
"arn",
".",
"rsplit",
"(",
"':'",
",",
"2",
")",
"except",
"ValueError",
":",
"raise",
"InvalidLayerVersionArn",
"(",
"arn",
"+",
"\" is an Invalid Layer Arn.\"",
")",
"return",
"LayerVersion",
".",
"LAYER_NAME_DELIMETER",
".",
"join",
"(",
"[",
"layer_name",
",",
"layer_version",
",",
"hashlib",
".",
"sha256",
"(",
"arn",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
"0",
":",
"10",
"]",
"]",
")"
] | Computes a unique name based on the LayerVersion Arn
Format:
<Name of the LayerVersion>-<Version of the LayerVersion>-<sha256 of the arn>
Parameters
----------
is_defined_within_template bool
True if the resource is a Ref to a resource otherwise False
arn str
ARN of the Resource
Returns
-------
str
A unique name that represents the LayerVersion | [
"Computes",
"a",
"unique",
"name",
"based",
"on",
"the",
"LayerVersion",
"Arn"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/provider.py#L102-L134 | train |
awslabs/aws-sam-cli | samcli/lib/utils/osutils.py | mkdir_temp | def mkdir_temp(mode=0o755):
"""
Context manager that makes a temporary directory and yields it name. Directory is deleted
after the context exits
Parameters
----------
mode : octal
Permissions to apply to the directory. Defaults to '755' because don't want directories world writable
Returns
-------
str
Path to the directory
"""
temp_dir = None
try:
temp_dir = tempfile.mkdtemp()
os.chmod(temp_dir, mode)
yield temp_dir
finally:
if temp_dir:
shutil.rmtree(temp_dir) | python | def mkdir_temp(mode=0o755):
"""
Context manager that makes a temporary directory and yields it name. Directory is deleted
after the context exits
Parameters
----------
mode : octal
Permissions to apply to the directory. Defaults to '755' because don't want directories world writable
Returns
-------
str
Path to the directory
"""
temp_dir = None
try:
temp_dir = tempfile.mkdtemp()
os.chmod(temp_dir, mode)
yield temp_dir
finally:
if temp_dir:
shutil.rmtree(temp_dir) | [
"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",
")"
] | Context manager that makes a temporary directory and yields it name. Directory is deleted
after the context exits
Parameters
----------
mode : octal
Permissions to apply to the directory. Defaults to '755' because don't want directories world writable
Returns
-------
str
Path to the directory | [
"Context",
"manager",
"that",
"makes",
"a",
"temporary",
"directory",
"and",
"yields",
"it",
"name",
".",
"Directory",
"is",
"deleted",
"after",
"the",
"context",
"exits"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/utils/osutils.py#L14-L40 | train |
awslabs/aws-sam-cli | samcli/lib/utils/osutils.py | stdout | def stdout():
"""
Returns the stdout as a byte stream in a Py2/PY3 compatible manner
Returns
-------
io.BytesIO
Byte stream of 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 .buffer attribute on stdout in Python3
byte_stdout = sys.stdout
if sys.version_info.major > 2:
byte_stdout = sys.stdout.buffer # pylint: disable=no-member
return byte_stdout | python | def stdout():
"""
Returns the stdout as a byte stream in a Py2/PY3 compatible manner
Returns
-------
io.BytesIO
Byte stream of 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 .buffer attribute on stdout in Python3
byte_stdout = sys.stdout
if sys.version_info.major > 2:
byte_stdout = sys.stdout.buffer # pylint: disable=no-member
return byte_stdout | [
"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 .buffer attribute on stdout in Python3",
"byte_stdout",
"=",
"sys",
".",
"stdout",
"if",
"sys",
".",
"version_info",
".",
"major",
">",
"2",
":",
"byte_stdout",
"=",
"sys",
".",
"stdout",
".",
"buffer",
"# pylint: disable=no-member",
"return",
"byte_stdout"
] | Returns the stdout as a byte stream in a Py2/PY3 compatible manner
Returns
-------
io.BytesIO
Byte stream of Stdout | [
"Returns",
"the",
"stdout",
"as",
"a",
"byte",
"stream",
"in",
"a",
"Py2",
"/",
"PY3",
"compatible",
"manner"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/utils/osutils.py#L43-L61 | train |
awslabs/aws-sam-cli | samcli/lib/utils/osutils.py | stderr | def stderr():
"""
Returns the stderr as a byte stream in a Py2/PY3 compatible manner
Returns
-------
io.BytesIO
Byte stream of 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 .buffer attribute on stderr in Python3
byte_stderr = sys.stderr
if sys.version_info.major > 2:
byte_stderr = sys.stderr.buffer # pylint: disable=no-member
return byte_stderr | python | def stderr():
"""
Returns the stderr as a byte stream in a Py2/PY3 compatible manner
Returns
-------
io.BytesIO
Byte stream of 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 .buffer attribute on stderr in Python3
byte_stderr = sys.stderr
if sys.version_info.major > 2:
byte_stderr = sys.stderr.buffer # pylint: disable=no-member
return byte_stderr | [
"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 .buffer attribute on stderr in Python3",
"byte_stderr",
"=",
"sys",
".",
"stderr",
"if",
"sys",
".",
"version_info",
".",
"major",
">",
"2",
":",
"byte_stderr",
"=",
"sys",
".",
"stderr",
".",
"buffer",
"# pylint: disable=no-member",
"return",
"byte_stderr"
] | Returns the stderr as a byte stream in a Py2/PY3 compatible manner
Returns
-------
io.BytesIO
Byte stream of stderr | [
"Returns",
"the",
"stderr",
"as",
"a",
"byte",
"stream",
"in",
"a",
"Py2",
"/",
"PY3",
"compatible",
"manner"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/utils/osutils.py#L64-L82 | train |
awslabs/aws-sam-cli | samcli/local/layers/layer_downloader.py | LayerDownloader.download_all | def download_all(self, layers, force=False):
"""
Download a list of layers to the cache
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers representing the layer to be downloaded
force bool
True to download the layer even if it exists already on the system
Returns
-------
List(Path)
List of Paths to where the layer was cached
"""
layer_dirs = []
for layer in layers:
layer_dirs.append(self.download(layer, force))
return layer_dirs | python | def download_all(self, layers, force=False):
"""
Download a list of layers to the cache
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers representing the layer to be downloaded
force bool
True to download the layer even if it exists already on the system
Returns
-------
List(Path)
List of Paths to where the layer was cached
"""
layer_dirs = []
for layer in layers:
layer_dirs.append(self.download(layer, force))
return layer_dirs | [
"def",
"download_all",
"(",
"self",
",",
"layers",
",",
"force",
"=",
"False",
")",
":",
"layer_dirs",
"=",
"[",
"]",
"for",
"layer",
"in",
"layers",
":",
"layer_dirs",
".",
"append",
"(",
"self",
".",
"download",
"(",
"layer",
",",
"force",
")",
")",
"return",
"layer_dirs"
] | Download a list of layers to the cache
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers representing the layer to be downloaded
force bool
True to download the layer even if it exists already on the system
Returns
-------
List(Path)
List of Paths to where the layer was cached | [
"Download",
"a",
"list",
"of",
"layers",
"to",
"the",
"cache"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/layers/layer_downloader.py#L54-L74 | train |
awslabs/aws-sam-cli | samcli/local/layers/layer_downloader.py | LayerDownloader.download | def download(self, layer, force=False):
"""
Download a given layer to the local cache.
Parameters
----------
layer samcli.commands.local.lib.provider.Layer
Layer representing the layer to be downloaded.
force bool
True to download the layer even if it exists already on the system
Returns
-------
Path
Path object that represents where the layer is download to
"""
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
# disabling no-member due to https://github.com/PyCQA/pylint/issues/1660
layer_path = Path(self.layer_cache).joinpath(layer.name).resolve() # pylint: disable=no-member
is_layer_downloaded = self._is_layer_cached(layer_path)
layer.codeuri = str(layer_path)
if is_layer_downloaded and not force:
LOG.info("%s is already cached. Skipping download", layer.arn)
return layer
layer_zip_path = layer.codeuri + '.zip'
layer_zip_uri = self._fetch_layer_uri(layer)
unzip_from_uri(layer_zip_uri,
layer_zip_path,
unzip_output_dir=layer.codeuri,
progressbar_label='Downloading {}'.format(layer.layer_arn))
return layer | python | def download(self, layer, force=False):
"""
Download a given layer to the local cache.
Parameters
----------
layer samcli.commands.local.lib.provider.Layer
Layer representing the layer to be downloaded.
force bool
True to download the layer even if it exists already on the system
Returns
-------
Path
Path object that represents where the layer is download to
"""
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
# disabling no-member due to https://github.com/PyCQA/pylint/issues/1660
layer_path = Path(self.layer_cache).joinpath(layer.name).resolve() # pylint: disable=no-member
is_layer_downloaded = self._is_layer_cached(layer_path)
layer.codeuri = str(layer_path)
if is_layer_downloaded and not force:
LOG.info("%s is already cached. Skipping download", layer.arn)
return layer
layer_zip_path = layer.codeuri + '.zip'
layer_zip_uri = self._fetch_layer_uri(layer)
unzip_from_uri(layer_zip_uri,
layer_zip_path,
unzip_output_dir=layer.codeuri,
progressbar_label='Downloading {}'.format(layer.layer_arn))
return layer | [
"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",
"# disabling no-member due to https://github.com/PyCQA/pylint/issues/1660",
"layer_path",
"=",
"Path",
"(",
"self",
".",
"layer_cache",
")",
".",
"joinpath",
"(",
"layer",
".",
"name",
")",
".",
"resolve",
"(",
")",
"# pylint: disable=no-member",
"is_layer_downloaded",
"=",
"self",
".",
"_is_layer_cached",
"(",
"layer_path",
")",
"layer",
".",
"codeuri",
"=",
"str",
"(",
"layer_path",
")",
"if",
"is_layer_downloaded",
"and",
"not",
"force",
":",
"LOG",
".",
"info",
"(",
"\"%s is already cached. Skipping download\"",
",",
"layer",
".",
"arn",
")",
"return",
"layer",
"layer_zip_path",
"=",
"layer",
".",
"codeuri",
"+",
"'.zip'",
"layer_zip_uri",
"=",
"self",
".",
"_fetch_layer_uri",
"(",
"layer",
")",
"unzip_from_uri",
"(",
"layer_zip_uri",
",",
"layer_zip_path",
",",
"unzip_output_dir",
"=",
"layer",
".",
"codeuri",
",",
"progressbar_label",
"=",
"'Downloading {}'",
".",
"format",
"(",
"layer",
".",
"layer_arn",
")",
")",
"return",
"layer"
] | Download a given layer to the local cache.
Parameters
----------
layer samcli.commands.local.lib.provider.Layer
Layer representing the layer to be downloaded.
force bool
True to download the layer even if it exists already on the system
Returns
-------
Path
Path object that represents where the layer is download to | [
"Download",
"a",
"given",
"layer",
"to",
"the",
"local",
"cache",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/layers/layer_downloader.py#L76-L113 | train |
awslabs/aws-sam-cli | samcli/local/layers/layer_downloader.py | LayerDownloader._fetch_layer_uri | def _fetch_layer_uri(self, layer):
"""
Fetch the Layer Uri based on the LayerVersion Arn
Parameters
----------
layer samcli.commands.local.lib.provider.LayerVersion
LayerVersion to fetch
Returns
-------
str
The Uri to download the LayerVersion Content from
Raises
------
samcli.commands.local.cli_common.user_exceptions.NoCredentialsError
When the Credentials given are not sufficient to call AWS Lambda
"""
try:
layer_version_response = self.lambda_client.get_layer_version(LayerName=layer.layer_arn,
VersionNumber=layer.version)
except NoCredentialsError:
raise CredentialsRequired("Layers require credentials to download the layers locally.")
except ClientError as e:
error_code = e.response.get('Error').get('Code')
error_exc = {
'AccessDeniedException': CredentialsRequired(
"Credentials provided are missing lambda:Getlayerversion policy that is needed to download the "
"layer or you do not have permission to download the layer"),
'ResourceNotFoundException': ResourceNotFound("{} was not found.".format(layer.arn))
}
if error_code in error_exc:
raise error_exc[error_code]
# If it was not 'AccessDeniedException' or 'ResourceNotFoundException' re-raise
raise e
return layer_version_response.get("Content").get("Location") | python | def _fetch_layer_uri(self, layer):
"""
Fetch the Layer Uri based on the LayerVersion Arn
Parameters
----------
layer samcli.commands.local.lib.provider.LayerVersion
LayerVersion to fetch
Returns
-------
str
The Uri to download the LayerVersion Content from
Raises
------
samcli.commands.local.cli_common.user_exceptions.NoCredentialsError
When the Credentials given are not sufficient to call AWS Lambda
"""
try:
layer_version_response = self.lambda_client.get_layer_version(LayerName=layer.layer_arn,
VersionNumber=layer.version)
except NoCredentialsError:
raise CredentialsRequired("Layers require credentials to download the layers locally.")
except ClientError as e:
error_code = e.response.get('Error').get('Code')
error_exc = {
'AccessDeniedException': CredentialsRequired(
"Credentials provided are missing lambda:Getlayerversion policy that is needed to download the "
"layer or you do not have permission to download the layer"),
'ResourceNotFoundException': ResourceNotFound("{} was not found.".format(layer.arn))
}
if error_code in error_exc:
raise error_exc[error_code]
# If it was not 'AccessDeniedException' or 'ResourceNotFoundException' re-raise
raise e
return layer_version_response.get("Content").get("Location") | [
"def",
"_fetch_layer_uri",
"(",
"self",
",",
"layer",
")",
":",
"try",
":",
"layer_version_response",
"=",
"self",
".",
"lambda_client",
".",
"get_layer_version",
"(",
"LayerName",
"=",
"layer",
".",
"layer_arn",
",",
"VersionNumber",
"=",
"layer",
".",
"version",
")",
"except",
"NoCredentialsError",
":",
"raise",
"CredentialsRequired",
"(",
"\"Layers require credentials to download the layers locally.\"",
")",
"except",
"ClientError",
"as",
"e",
":",
"error_code",
"=",
"e",
".",
"response",
".",
"get",
"(",
"'Error'",
")",
".",
"get",
"(",
"'Code'",
")",
"error_exc",
"=",
"{",
"'AccessDeniedException'",
":",
"CredentialsRequired",
"(",
"\"Credentials provided are missing lambda:Getlayerversion policy that is needed to download the \"",
"\"layer or you do not have permission to download the layer\"",
")",
",",
"'ResourceNotFoundException'",
":",
"ResourceNotFound",
"(",
"\"{} was not found.\"",
".",
"format",
"(",
"layer",
".",
"arn",
")",
")",
"}",
"if",
"error_code",
"in",
"error_exc",
":",
"raise",
"error_exc",
"[",
"error_code",
"]",
"# If it was not 'AccessDeniedException' or 'ResourceNotFoundException' re-raise",
"raise",
"e",
"return",
"layer_version_response",
".",
"get",
"(",
"\"Content\"",
")",
".",
"get",
"(",
"\"Location\"",
")"
] | Fetch the Layer Uri based on the LayerVersion Arn
Parameters
----------
layer samcli.commands.local.lib.provider.LayerVersion
LayerVersion to fetch
Returns
-------
str
The Uri to download the LayerVersion Content from
Raises
------
samcli.commands.local.cli_common.user_exceptions.NoCredentialsError
When the Credentials given are not sufficient to call AWS Lambda | [
"Fetch",
"the",
"Layer",
"Uri",
"based",
"on",
"the",
"LayerVersion",
"Arn"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/layers/layer_downloader.py#L115-L154 | train |
awslabs/aws-sam-cli | samcli/local/layers/layer_downloader.py | LayerDownloader._create_cache | def _create_cache(layer_cache):
"""
Create the Cache directory if it does not exist.
Parameters
----------
layer_cache
Directory to where the layers should be cached
Returns
-------
None
"""
Path(layer_cache).mkdir(mode=0o700, parents=True, exist_ok=True) | python | def _create_cache(layer_cache):
"""
Create the Cache directory if it does not exist.
Parameters
----------
layer_cache
Directory to where the layers should be cached
Returns
-------
None
"""
Path(layer_cache).mkdir(mode=0o700, parents=True, exist_ok=True) | [
"def",
"_create_cache",
"(",
"layer_cache",
")",
":",
"Path",
"(",
"layer_cache",
")",
".",
"mkdir",
"(",
"mode",
"=",
"0o700",
",",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")"
] | Create the Cache directory if it does not exist.
Parameters
----------
layer_cache
Directory to where the layers should be cached
Returns
-------
None | [
"Create",
"the",
"Cache",
"directory",
"if",
"it",
"does",
"not",
"exist",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/layers/layer_downloader.py#L174-L188 | train |
awslabs/aws-sam-cli | samcli/commands/validate/lib/sam_template_validator.py | SamTemplateValidator.is_valid | def is_valid(self):
"""
Runs the SAM Translator to determine if the template provided is valid. This is similar to running a
ChangeSet in CloudFormation for a SAM Template
Raises
-------
InvalidSamDocumentException
If the template is not valid, an InvalidSamDocumentException is raised
"""
managed_policy_map = self.managed_policy_loader.load()
sam_translator = Translator(managed_policy_map=managed_policy_map,
sam_parser=self.sam_parser,
plugins=[])
self._replace_local_codeuri()
try:
template = sam_translator.translate(sam_template=self.sam_template,
parameter_values={})
LOG.debug("Translated template is:\n%s", yaml_dump(template))
except InvalidDocumentException as e:
raise InvalidSamDocumentException(
functools.reduce(lambda message, error: message + ' ' + str(error), e.causes, str(e))) | python | def is_valid(self):
"""
Runs the SAM Translator to determine if the template provided is valid. This is similar to running a
ChangeSet in CloudFormation for a SAM Template
Raises
-------
InvalidSamDocumentException
If the template is not valid, an InvalidSamDocumentException is raised
"""
managed_policy_map = self.managed_policy_loader.load()
sam_translator = Translator(managed_policy_map=managed_policy_map,
sam_parser=self.sam_parser,
plugins=[])
self._replace_local_codeuri()
try:
template = sam_translator.translate(sam_template=self.sam_template,
parameter_values={})
LOG.debug("Translated template is:\n%s", yaml_dump(template))
except InvalidDocumentException as e:
raise InvalidSamDocumentException(
functools.reduce(lambda message, error: message + ' ' + str(error), e.causes, str(e))) | [
"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",
"=",
"[",
"]",
")",
"self",
".",
"_replace_local_codeuri",
"(",
")",
"try",
":",
"template",
"=",
"sam_translator",
".",
"translate",
"(",
"sam_template",
"=",
"self",
".",
"sam_template",
",",
"parameter_values",
"=",
"{",
"}",
")",
"LOG",
".",
"debug",
"(",
"\"Translated template is:\\n%s\"",
",",
"yaml_dump",
"(",
"template",
")",
")",
"except",
"InvalidDocumentException",
"as",
"e",
":",
"raise",
"InvalidSamDocumentException",
"(",
"functools",
".",
"reduce",
"(",
"lambda",
"message",
",",
"error",
":",
"message",
"+",
"' '",
"+",
"str",
"(",
"error",
")",
",",
"e",
".",
"causes",
",",
"str",
"(",
"e",
")",
")",
")"
] | Runs the SAM Translator to determine if the template provided is valid. This is similar to running a
ChangeSet in CloudFormation for a SAM Template
Raises
-------
InvalidSamDocumentException
If the template is not valid, an InvalidSamDocumentException is raised | [
"Runs",
"the",
"SAM",
"Translator",
"to",
"determine",
"if",
"the",
"template",
"provided",
"is",
"valid",
".",
"This",
"is",
"similar",
"to",
"running",
"a",
"ChangeSet",
"in",
"CloudFormation",
"for",
"a",
"SAM",
"Template"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/validate/lib/sam_template_validator.py#L44-L68 | train |
awslabs/aws-sam-cli | samcli/commands/validate/lib/sam_template_validator.py | SamTemplateValidator._replace_local_codeuri | def _replace_local_codeuri(self):
"""
Replaces the CodeUri in AWS::Serverless::Function and DefinitionUri in AWS::Serverless::Api to a fake
S3 Uri. This is to support running the SAM Translator with valid values for these fields. If this in not done,
the template is invalid in the eyes of SAM Translator (the translator does not support local paths)
"""
all_resources = self.sam_template.get("Resources", {})
for _, resource in all_resources.items():
resource_type = resource.get("Type")
resource_dict = resource.get("Properties")
if resource_type == "AWS::Serverless::Function":
SamTemplateValidator._update_to_s3_uri("CodeUri", resource_dict)
if resource_type == "AWS::Serverless::LayerVersion":
SamTemplateValidator._update_to_s3_uri("ContentUri", resource_dict)
if resource_type == "AWS::Serverless::Api":
if "DefinitionBody" not in resource_dict:
SamTemplateValidator._update_to_s3_uri("DefinitionUri", resource_dict) | python | def _replace_local_codeuri(self):
"""
Replaces the CodeUri in AWS::Serverless::Function and DefinitionUri in AWS::Serverless::Api to a fake
S3 Uri. This is to support running the SAM Translator with valid values for these fields. If this in not done,
the template is invalid in the eyes of SAM Translator (the translator does not support local paths)
"""
all_resources = self.sam_template.get("Resources", {})
for _, resource in all_resources.items():
resource_type = resource.get("Type")
resource_dict = resource.get("Properties")
if resource_type == "AWS::Serverless::Function":
SamTemplateValidator._update_to_s3_uri("CodeUri", resource_dict)
if resource_type == "AWS::Serverless::LayerVersion":
SamTemplateValidator._update_to_s3_uri("ContentUri", resource_dict)
if resource_type == "AWS::Serverless::Api":
if "DefinitionBody" not in resource_dict:
SamTemplateValidator._update_to_s3_uri("DefinitionUri", resource_dict) | [
"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\"",
")",
"if",
"resource_type",
"==",
"\"AWS::Serverless::Function\"",
":",
"SamTemplateValidator",
".",
"_update_to_s3_uri",
"(",
"\"CodeUri\"",
",",
"resource_dict",
")",
"if",
"resource_type",
"==",
"\"AWS::Serverless::LayerVersion\"",
":",
"SamTemplateValidator",
".",
"_update_to_s3_uri",
"(",
"\"ContentUri\"",
",",
"resource_dict",
")",
"if",
"resource_type",
"==",
"\"AWS::Serverless::Api\"",
":",
"if",
"\"DefinitionBody\"",
"not",
"in",
"resource_dict",
":",
"SamTemplateValidator",
".",
"_update_to_s3_uri",
"(",
"\"DefinitionUri\"",
",",
"resource_dict",
")"
] | Replaces the CodeUri in AWS::Serverless::Function and DefinitionUri in AWS::Serverless::Api to a fake
S3 Uri. This is to support running the SAM Translator with valid values for these fields. If this in not done,
the template is invalid in the eyes of SAM Translator (the translator does not support local paths) | [
"Replaces",
"the",
"CodeUri",
"in",
"AWS",
"::",
"Serverless",
"::",
"Function",
"and",
"DefinitionUri",
"in",
"AWS",
"::",
"Serverless",
"::",
"Api",
"to",
"a",
"fake",
"S3",
"Uri",
".",
"This",
"is",
"to",
"support",
"running",
"the",
"SAM",
"Translator",
"with",
"valid",
"values",
"for",
"these",
"fields",
".",
"If",
"this",
"in",
"not",
"done",
"the",
"template",
"is",
"invalid",
"in",
"the",
"eyes",
"of",
"SAM",
"Translator",
"(",
"the",
"translator",
"does",
"not",
"support",
"local",
"paths",
")"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/validate/lib/sam_template_validator.py#L70-L94 | train |
awslabs/aws-sam-cli | samcli/commands/validate/lib/sam_template_validator.py | SamTemplateValidator._update_to_s3_uri | def _update_to_s3_uri(property_key, resource_property_dict, s3_uri_value="s3://bucket/value"):
"""
Updates the 'property_key' in the 'resource_property_dict' to the value of 's3_uri_value'
Note: The function will mutate the resource_property_dict that is pass in
Parameters
----------
property_key str, required
Key in the resource_property_dict
resource_property_dict dict, required
Property dictionary of a Resource in the template to replace
s3_uri_value str, optional
Value to update the value of the property_key to
"""
uri_property = resource_property_dict.get(property_key, ".")
# ignore if dict or already an S3 Uri
if isinstance(uri_property, dict) or SamTemplateValidator.is_s3_uri(uri_property):
return
resource_property_dict[property_key] = s3_uri_value | python | def _update_to_s3_uri(property_key, resource_property_dict, s3_uri_value="s3://bucket/value"):
"""
Updates the 'property_key' in the 'resource_property_dict' to the value of 's3_uri_value'
Note: The function will mutate the resource_property_dict that is pass in
Parameters
----------
property_key str, required
Key in the resource_property_dict
resource_property_dict dict, required
Property dictionary of a Resource in the template to replace
s3_uri_value str, optional
Value to update the value of the property_key to
"""
uri_property = resource_property_dict.get(property_key, ".")
# ignore if dict or already an S3 Uri
if isinstance(uri_property, dict) or SamTemplateValidator.is_s3_uri(uri_property):
return
resource_property_dict[property_key] = s3_uri_value | [
"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",
"SamTemplateValidator",
".",
"is_s3_uri",
"(",
"uri_property",
")",
":",
"return",
"resource_property_dict",
"[",
"property_key",
"]",
"=",
"s3_uri_value"
] | Updates the 'property_key' in the 'resource_property_dict' to the value of 's3_uri_value'
Note: The function will mutate the resource_property_dict that is pass in
Parameters
----------
property_key str, required
Key in the resource_property_dict
resource_property_dict dict, required
Property dictionary of a Resource in the template to replace
s3_uri_value str, optional
Value to update the value of the property_key to | [
"Updates",
"the",
"property_key",
"in",
"the",
"resource_property_dict",
"to",
"the",
"value",
"of",
"s3_uri_value"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/validate/lib/sam_template_validator.py#L115-L136 | train |
awslabs/aws-sam-cli | samcli/commands/logs/logs_context.py | LogsCommandContext.formatter | def formatter(self):
"""
Creates and returns a Formatter capable of nicely formatting Lambda function logs
Returns
-------
LogsFormatter
"""
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
JSONMsgFormatter.format_json,
KeywordHighlighter(self._filter_pattern).highlight_keywords,
]
return LogsFormatter(self.colored, formatter_chain) | python | def formatter(self):
"""
Creates and returns a Formatter capable of nicely formatting Lambda function logs
Returns
-------
LogsFormatter
"""
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
JSONMsgFormatter.format_json,
KeywordHighlighter(self._filter_pattern).highlight_keywords,
]
return LogsFormatter(self.colored, formatter_chain) | [
"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",
"JSONMsgFormatter",
".",
"format_json",
",",
"KeywordHighlighter",
"(",
"self",
".",
"_filter_pattern",
")",
".",
"highlight_keywords",
",",
"]",
"return",
"LogsFormatter",
"(",
"self",
".",
"colored",
",",
"formatter_chain",
")"
] | Creates and returns a Formatter capable of nicely formatting Lambda function logs
Returns
-------
LogsFormatter | [
"Creates",
"and",
"returns",
"a",
"Formatter",
"capable",
"of",
"nicely",
"formatting",
"Lambda",
"function",
"logs"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/logs/logs_context.py#L103-L121 | train |
awslabs/aws-sam-cli | samcli/commands/logs/logs_context.py | LogsCommandContext.log_group_name | def log_group_name(self):
"""
Name of the AWS CloudWatch Log Group that we will be querying. It generates the name based on the
Lambda Function name and stack name provided.
Returns
-------
str
Name of the CloudWatch Log Group
"""
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' in stack '%s' resolves to actual physical ID '%s'",
self._function_name, self._stack_name, function_id)
return LogGroupProvider.for_lambda_function(function_id) | python | def log_group_name(self):
"""
Name of the AWS CloudWatch Log Group that we will be querying. It generates the name based on the
Lambda Function name and stack name provided.
Returns
-------
str
Name of the CloudWatch Log Group
"""
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' in stack '%s' resolves to actual physical ID '%s'",
self._function_name, self._stack_name, function_id)
return LogGroupProvider.for_lambda_function(function_id) | [
"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' in stack '%s' resolves to actual physical ID '%s'\"",
",",
"self",
".",
"_function_name",
",",
"self",
".",
"_stack_name",
",",
"function_id",
")",
"return",
"LogGroupProvider",
".",
"for_lambda_function",
"(",
"function_id",
")"
] | Name of the AWS CloudWatch Log Group that we will be querying. It generates the name based on the
Lambda Function name and stack name provided.
Returns
-------
str
Name of the CloudWatch Log Group | [
"Name",
"of",
"the",
"AWS",
"CloudWatch",
"Log",
"Group",
"that",
"we",
"will",
"be",
"querying",
".",
"It",
"generates",
"the",
"name",
"based",
"on",
"the",
"Lambda",
"Function",
"name",
"and",
"stack",
"name",
"provided",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/logs/logs_context.py#L132-L149 | train |
awslabs/aws-sam-cli | samcli/commands/logs/logs_context.py | LogsCommandContext._parse_time | def _parse_time(time_str, property_name):
"""
Parse the time from the given string, convert to UTC, and return the datetime object
Parameters
----------
time_str : str
The time to parse
property_name : str
Name of the property where this time came from. Used in the exception raised if time is not parseable
Returns
-------
datetime.datetime
Parsed datetime object
Raises
------
samcli.commands.exceptions.UserException
If the string cannot be parsed as a timestamp
"""
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_utc(parsed) | python | def _parse_time(time_str, property_name):
"""
Parse the time from the given string, convert to UTC, and return the datetime object
Parameters
----------
time_str : str
The time to parse
property_name : str
Name of the property where this time came from. Used in the exception raised if time is not parseable
Returns
-------
datetime.datetime
Parsed datetime object
Raises
------
samcli.commands.exceptions.UserException
If the string cannot be parsed as a timestamp
"""
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_utc(parsed) | [
"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_utc",
"(",
"parsed",
")"
] | Parse the time from the given string, convert to UTC, and return the datetime object
Parameters
----------
time_str : str
The time to parse
property_name : str
Name of the property where this time came from. Used in the exception raised if time is not parseable
Returns
-------
datetime.datetime
Parsed datetime object
Raises
------
samcli.commands.exceptions.UserException
If the string cannot be parsed as a timestamp | [
"Parse",
"the",
"time",
"from",
"the",
"given",
"string",
"convert",
"to",
"UTC",
"and",
"return",
"the",
"datetime",
"object"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/logs/logs_context.py#L191-L220 | train |
awslabs/aws-sam-cli | samcli/commands/logs/logs_context.py | LogsCommandContext._get_resource_id_from_stack | def _get_resource_id_from_stack(cfn_client, stack_name, logical_id):
"""
Given the LogicalID of a resource, call AWS CloudFormation to get physical ID of the resource within
the specified stack.
Parameters
----------
cfn_client
CloudFormation client provided by AWS SDK
stack_name : str
Name of the stack to query
logical_id : str
LogicalId of the resource
Returns
-------
str
Physical ID of the resource
Raises
------
samcli.commands.exceptions.UserException
If the stack or resource does not exist
"""
LOG.debug("Getting resource's PhysicalId from AWS CloudFormation stack. StackName=%s, LogicalId=%s",
stack_name, logical_id)
try:
response = cfn_client.describe_stack_resource(StackName=stack_name, LogicalResourceId=logical_id)
LOG.debug("Response from AWS CloudFormation %s", response)
return response["StackResourceDetail"]["PhysicalResourceId"]
except botocore.exceptions.ClientError as ex:
LOG.debug("Unable to fetch resource name from CloudFormation Stack: "
"StackName=%s, ResourceLogicalId=%s, Response=%s", stack_name, logical_id, ex.response)
# The exception message already has a well formatted error message that we can surface to user
raise UserException(str(ex)) | python | def _get_resource_id_from_stack(cfn_client, stack_name, logical_id):
"""
Given the LogicalID of a resource, call AWS CloudFormation to get physical ID of the resource within
the specified stack.
Parameters
----------
cfn_client
CloudFormation client provided by AWS SDK
stack_name : str
Name of the stack to query
logical_id : str
LogicalId of the resource
Returns
-------
str
Physical ID of the resource
Raises
------
samcli.commands.exceptions.UserException
If the stack or resource does not exist
"""
LOG.debug("Getting resource's PhysicalId from AWS CloudFormation stack. StackName=%s, LogicalId=%s",
stack_name, logical_id)
try:
response = cfn_client.describe_stack_resource(StackName=stack_name, LogicalResourceId=logical_id)
LOG.debug("Response from AWS CloudFormation %s", response)
return response["StackResourceDetail"]["PhysicalResourceId"]
except botocore.exceptions.ClientError as ex:
LOG.debug("Unable to fetch resource name from CloudFormation Stack: "
"StackName=%s, ResourceLogicalId=%s, Response=%s", stack_name, logical_id, ex.response)
# The exception message already has a well formatted error message that we can surface to user
raise UserException(str(ex)) | [
"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_client",
".",
"describe_stack_resource",
"(",
"StackName",
"=",
"stack_name",
",",
"LogicalResourceId",
"=",
"logical_id",
")",
"LOG",
".",
"debug",
"(",
"\"Response from AWS CloudFormation %s\"",
",",
"response",
")",
"return",
"response",
"[",
"\"StackResourceDetail\"",
"]",
"[",
"\"PhysicalResourceId\"",
"]",
"except",
"botocore",
".",
"exceptions",
".",
"ClientError",
"as",
"ex",
":",
"LOG",
".",
"debug",
"(",
"\"Unable to fetch resource name from CloudFormation Stack: \"",
"\"StackName=%s, ResourceLogicalId=%s, Response=%s\"",
",",
"stack_name",
",",
"logical_id",
",",
"ex",
".",
"response",
")",
"# The exception message already has a well formatted error message that we can surface to user",
"raise",
"UserException",
"(",
"str",
"(",
"ex",
")",
")"
] | Given the LogicalID of a resource, call AWS CloudFormation to get physical ID of the resource within
the specified stack.
Parameters
----------
cfn_client
CloudFormation client provided by AWS SDK
stack_name : str
Name of the stack to query
logical_id : str
LogicalId of the resource
Returns
-------
str
Physical ID of the resource
Raises
------
samcli.commands.exceptions.UserException
If the stack or resource does not exist | [
"Given",
"the",
"LogicalID",
"of",
"a",
"resource",
"call",
"AWS",
"CloudFormation",
"to",
"get",
"physical",
"ID",
"of",
"the",
"resource",
"within",
"the",
"specified",
"stack",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/logs/logs_context.py#L223-L264 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_base_provider.py | SamBaseProvider.get_template | def get_template(template_dict, parameter_overrides=None):
"""
Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been run
and parameter values have been substituted.
Parameters
----------
template_dict : dict
unprocessed SAM template dictionary
parameter_overrides: dict
Optional dictionary of values for template parameters
Returns
-------
dict
Processed SAM template
"""
template_dict = template_dict or {}
if template_dict:
template_dict = SamTranslatorWrapper(template_dict).run_plugins()
template_dict = SamBaseProvider._resolve_parameters(template_dict, parameter_overrides)
ResourceMetadataNormalizer.normalize(template_dict)
return template_dict | python | def get_template(template_dict, parameter_overrides=None):
"""
Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been run
and parameter values have been substituted.
Parameters
----------
template_dict : dict
unprocessed SAM template dictionary
parameter_overrides: dict
Optional dictionary of values for template parameters
Returns
-------
dict
Processed SAM template
"""
template_dict = template_dict or {}
if template_dict:
template_dict = SamTranslatorWrapper(template_dict).run_plugins()
template_dict = SamBaseProvider._resolve_parameters(template_dict, parameter_overrides)
ResourceMetadataNormalizer.normalize(template_dict)
return template_dict | [
"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_parameters",
"(",
"template_dict",
",",
"parameter_overrides",
")",
"ResourceMetadataNormalizer",
".",
"normalize",
"(",
"template_dict",
")",
"return",
"template_dict"
] | Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been run
and parameter values have been substituted.
Parameters
----------
template_dict : dict
unprocessed SAM template dictionary
parameter_overrides: dict
Optional dictionary of values for template parameters
Returns
-------
dict
Processed SAM template | [
"Given",
"a",
"SAM",
"template",
"dictionary",
"return",
"a",
"cleaned",
"copy",
"of",
"the",
"template",
"where",
"SAM",
"plugins",
"have",
"been",
"run",
"and",
"parameter",
"values",
"have",
"been",
"substituted",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_base_provider.py#L41-L66 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_base_provider.py | SamBaseProvider._resolve_parameters | def _resolve_parameters(template_dict, parameter_overrides):
"""
In the given template, apply parameter values to resolve intrinsic functions
Parameters
----------
template_dict : dict
SAM Template
parameter_overrides : dict
Values for template parameters provided by user
Returns
-------
dict
Resolved SAM template
"""
parameter_values = SamBaseProvider._get_parameter_values(template_dict, parameter_overrides)
supported_intrinsics = {action.intrinsic_name: action() for action in SamBaseProvider._SUPPORTED_INTRINSICS}
# Intrinsics resolver will mutate the original template
return IntrinsicsResolver(parameters=parameter_values, supported_intrinsics=supported_intrinsics)\
.resolve_parameter_refs(template_dict) | python | def _resolve_parameters(template_dict, parameter_overrides):
"""
In the given template, apply parameter values to resolve intrinsic functions
Parameters
----------
template_dict : dict
SAM Template
parameter_overrides : dict
Values for template parameters provided by user
Returns
-------
dict
Resolved SAM template
"""
parameter_values = SamBaseProvider._get_parameter_values(template_dict, parameter_overrides)
supported_intrinsics = {action.intrinsic_name: action() for action in SamBaseProvider._SUPPORTED_INTRINSICS}
# Intrinsics resolver will mutate the original template
return IntrinsicsResolver(parameters=parameter_values, supported_intrinsics=supported_intrinsics)\
.resolve_parameter_refs(template_dict) | [
"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",
".",
"_SUPPORTED_INTRINSICS",
"}",
"# Intrinsics resolver will mutate the original template",
"return",
"IntrinsicsResolver",
"(",
"parameters",
"=",
"parameter_values",
",",
"supported_intrinsics",
"=",
"supported_intrinsics",
")",
".",
"resolve_parameter_refs",
"(",
"template_dict",
")"
] | In the given template, apply parameter values to resolve intrinsic functions
Parameters
----------
template_dict : dict
SAM Template
parameter_overrides : dict
Values for template parameters provided by user
Returns
-------
dict
Resolved SAM template | [
"In",
"the",
"given",
"template",
"apply",
"parameter",
"values",
"to",
"resolve",
"intrinsic",
"functions"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_base_provider.py#L69-L93 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_base_provider.py | SamBaseProvider._get_parameter_values | def _get_parameter_values(template_dict, parameter_overrides):
"""
Construct a final list of values for CloudFormation template parameters based on user-supplied values,
default values provided in template, and sane defaults for pseudo-parameters.
Parameters
----------
template_dict : dict
SAM template dictionary
parameter_overrides : dict
User-supplied values for CloudFormation template parameters
Returns
-------
dict
Values for template parameters to substitute in template with
"""
default_values = SamBaseProvider._get_default_parameter_values(template_dict)
# NOTE: Ordering of following statements is important. It makes sure that any user-supplied values
# override the defaults
parameter_values = {}
parameter_values.update(SamBaseProvider._DEFAULT_PSEUDO_PARAM_VALUES)
parameter_values.update(default_values)
parameter_values.update(parameter_overrides or {})
return parameter_values | python | def _get_parameter_values(template_dict, parameter_overrides):
"""
Construct a final list of values for CloudFormation template parameters based on user-supplied values,
default values provided in template, and sane defaults for pseudo-parameters.
Parameters
----------
template_dict : dict
SAM template dictionary
parameter_overrides : dict
User-supplied values for CloudFormation template parameters
Returns
-------
dict
Values for template parameters to substitute in template with
"""
default_values = SamBaseProvider._get_default_parameter_values(template_dict)
# NOTE: Ordering of following statements is important. It makes sure that any user-supplied values
# override the defaults
parameter_values = {}
parameter_values.update(SamBaseProvider._DEFAULT_PSEUDO_PARAM_VALUES)
parameter_values.update(default_values)
parameter_values.update(parameter_overrides or {})
return parameter_values | [
"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",
"# override the defaults",
"parameter_values",
"=",
"{",
"}",
"parameter_values",
".",
"update",
"(",
"SamBaseProvider",
".",
"_DEFAULT_PSEUDO_PARAM_VALUES",
")",
"parameter_values",
".",
"update",
"(",
"default_values",
")",
"parameter_values",
".",
"update",
"(",
"parameter_overrides",
"or",
"{",
"}",
")",
"return",
"parameter_values"
] | Construct a final list of values for CloudFormation template parameters based on user-supplied values,
default values provided in template, and sane defaults for pseudo-parameters.
Parameters
----------
template_dict : dict
SAM template dictionary
parameter_overrides : dict
User-supplied values for CloudFormation template parameters
Returns
-------
dict
Values for template parameters to substitute in template with | [
"Construct",
"a",
"final",
"list",
"of",
"values",
"for",
"CloudFormation",
"template",
"parameters",
"based",
"on",
"user",
"-",
"supplied",
"values",
"default",
"values",
"provided",
"in",
"template",
"and",
"sane",
"defaults",
"for",
"pseudo",
"-",
"parameters",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_base_provider.py#L96-L124 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_base_provider.py | SamBaseProvider._get_default_parameter_values | def _get_default_parameter_values(sam_template):
"""
Method to read default values for template parameters and return it
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
Default: default_value1
Param2:
Type: String
Default: default_value2
then, this method will grab default value for Param1 and return the following result:
{
Param1: "default_value1",
Param2: "default_value2"
}
:param dict sam_template: SAM template
:return dict: Default values for parameters
"""
default_values = {}
parameter_definition = sam_template.get("Parameters", None)
if not parameter_definition or not isinstance(parameter_definition, dict):
LOG.debug("No Parameters detected in the template")
return default_values
for param_name, value in parameter_definition.items():
if isinstance(value, dict) and "Default" in value:
default_values[param_name] = value["Default"]
LOG.debug("Collected default values for parameters: %s", default_values)
return default_values | python | def _get_default_parameter_values(sam_template):
"""
Method to read default values for template parameters and return it
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
Default: default_value1
Param2:
Type: String
Default: default_value2
then, this method will grab default value for Param1 and return the following result:
{
Param1: "default_value1",
Param2: "default_value2"
}
:param dict sam_template: SAM template
:return dict: Default values for parameters
"""
default_values = {}
parameter_definition = sam_template.get("Parameters", None)
if not parameter_definition or not isinstance(parameter_definition, dict):
LOG.debug("No Parameters detected in the template")
return default_values
for param_name, value in parameter_definition.items():
if isinstance(value, dict) and "Default" in value:
default_values[param_name] = value["Default"]
LOG.debug("Collected default values for parameters: %s", default_values)
return default_values | [
"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 detected in the template\"",
")",
"return",
"default_values",
"for",
"param_name",
",",
"value",
"in",
"parameter_definition",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"\"Default\"",
"in",
"value",
":",
"default_values",
"[",
"param_name",
"]",
"=",
"value",
"[",
"\"Default\"",
"]",
"LOG",
".",
"debug",
"(",
"\"Collected default values for parameters: %s\"",
",",
"default_values",
")",
"return",
"default_values"
] | Method to read default values for template parameters and return it
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
Default: default_value1
Param2:
Type: String
Default: default_value2
then, this method will grab default value for Param1 and return the following result:
{
Param1: "default_value1",
Param2: "default_value2"
}
:param dict sam_template: SAM template
:return dict: Default values for parameters | [
"Method",
"to",
"read",
"default",
"values",
"for",
"template",
"parameters",
"and",
"return",
"it",
"Example",
":",
"If",
"the",
"template",
"contains",
"the",
"following",
"parameters",
"defined",
"Parameters",
":",
"Param1",
":",
"Type",
":",
"String",
"Default",
":",
"default_value1",
"Param2",
":",
"Type",
":",
"String",
"Default",
":",
"default_value2"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_base_provider.py#L127-L161 | train |
awslabs/aws-sam-cli | samcli/local/docker/utils.py | to_posix_path | def to_posix_path(code_path):
"""
Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.
Parameters
----------
code_path : str
Directory in the host operating system that should be mounted within the container.
Returns
-------
str
Posix equivalent of absolute windows style path.
Examples
--------
>>> to_posix_path('/Users/UserName/sam-app')
/Users/UserName/sam-app
>>> to_posix_path('C:\\\\Users\\\\UserName\\\\AppData\\\\Local\\\\Temp\\\\mydir')
/c/Users/UserName/AppData/Local/Temp/mydir
"""
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 | python | def to_posix_path(code_path):
"""
Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.
Parameters
----------
code_path : str
Directory in the host operating system that should be mounted within the container.
Returns
-------
str
Posix equivalent of absolute windows style path.
Examples
--------
>>> to_posix_path('/Users/UserName/sam-app')
/Users/UserName/sam-app
>>> to_posix_path('C:\\\\Users\\\\UserName\\\\AppData\\\\Local\\\\Temp\\\\mydir')
/c/Users/UserName/AppData/Local/Temp/mydir
"""
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 | [
"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"
] | Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.
Parameters
----------
code_path : str
Directory in the host operating system that should be mounted within the container.
Returns
-------
str
Posix equivalent of absolute windows style path.
Examples
--------
>>> to_posix_path('/Users/UserName/sam-app')
/Users/UserName/sam-app
>>> to_posix_path('C:\\\\Users\\\\UserName\\\\AppData\\\\Local\\\\Temp\\\\mydir')
/c/Users/UserName/AppData/Local/Temp/mydir | [
"Change",
"the",
"code_path",
"to",
"be",
"of",
"unix",
"-",
"style",
"if",
"running",
"on",
"windows",
"when",
"supplied",
"with",
"an",
"absolute",
"windows",
"path",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/utils.py#L14-L36 | train |
awslabs/aws-sam-cli | samcli/local/docker/lambda_container.py | LambdaContainer._get_additional_options | def _get_additional_options(runtime, debug_options):
"""
Return additional Docker container options. Used by container debug mode to enable certain container
security options.
:param DebugContext debug_options: DebugContext for the runtime of the container.
:return dict: Dictionary containing additional arguments to be passed to container creation.
"""
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 on docker < 1.12
# See https://github.com/moby/moby/issues/21051
opts["security_opt"] = ["seccomp:unconfined"]
opts["cap_add"] = ["SYS_PTRACE"]
return opts | python | def _get_additional_options(runtime, debug_options):
"""
Return additional Docker container options. Used by container debug mode to enable certain container
security options.
:param DebugContext debug_options: DebugContext for the runtime of the container.
:return dict: Dictionary containing additional arguments to be passed to container creation.
"""
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 on docker < 1.12
# See https://github.com/moby/moby/issues/21051
opts["security_opt"] = ["seccomp:unconfined"]
opts["cap_add"] = ["SYS_PTRACE"]
return opts | [
"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 on docker < 1.12",
"# See https://github.com/moby/moby/issues/21051",
"opts",
"[",
"\"security_opt\"",
"]",
"=",
"[",
"\"seccomp:unconfined\"",
"]",
"opts",
"[",
"\"cap_add\"",
"]",
"=",
"[",
"\"SYS_PTRACE\"",
"]",
"return",
"opts"
] | Return additional Docker container options. Used by container debug mode to enable certain container
security options.
:param DebugContext debug_options: DebugContext for the runtime of the container.
:return dict: Dictionary containing additional arguments to be passed to container creation. | [
"Return",
"additional",
"Docker",
"container",
"options",
".",
"Used",
"by",
"container",
"debug",
"mode",
"to",
"enable",
"certain",
"container",
"security",
"options",
".",
":",
"param",
"DebugContext",
"debug_options",
":",
"DebugContext",
"for",
"the",
"runtime",
"of",
"the",
"container",
".",
":",
"return",
"dict",
":",
"Dictionary",
"containing",
"additional",
"arguments",
"to",
"be",
"passed",
"to",
"container",
"creation",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_container.py#L104-L122 | train |
awslabs/aws-sam-cli | samcli/local/docker/lambda_container.py | LambdaContainer._get_entry_point | def _get_entry_point(runtime, debug_options=None): # pylint: disable=too-many-branches
"""
Returns the entry point for the container. The default value for the entry point is already configured in the
Dockerfile. We override this default specifically when enabling debugging. The overridden entry point includes
a few extra flags to start the runtime in debug mode.
:param string runtime: Lambda function runtime name
:param int debug_port: Optional, port for debugger
:param string debug_args: Optional additional arguments passed to the entry point.
:return list: List containing the new entry points. Each element in the list is one portion of the command.
ie. if command is ``node index.js arg1 arg2``, then this list will be ["node", "index.js", "arg1", "arg2"]
"""
if not debug_options:
return None
if runtime not in LambdaContainer._supported_runtimes():
raise DebuggingNotSupported(
"Debugging is not currently supported for {}".format(runtime))
debug_port = debug_options.debug_port
debug_args_list = []
if debug_options.debug_args:
debug_args_list = debug_options.debug_args.split(" ")
# configs from: https://github.com/lambci/docker-lambda
# to which we add the extra debug mode options
entrypoint = None
if runtime == Runtime.java8.value:
entrypoint = ["/usr/bin/java"] \
+ debug_args_list \
+ [
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,quiet=y,address=" + str(debug_port),
"-XX:MaxHeapSize=2834432k",
"-XX:MaxMetaspaceSize=163840k",
"-XX:ReservedCodeCacheSize=81920k",
"-XX:+UseSerialGC",
# "-Xshare:on", doesn't work in conjunction with the debug options
"-XX:-TieredCompilation",
"-Djava.net.preferIPv4Stack=true",
"-jar",
"/var/runtime/lib/LambdaJavaRTEntry-1.0.jar",
]
elif runtime in (Runtime.dotnetcore20.value, Runtime.dotnetcore21.value):
entrypoint = ["/var/lang/bin/dotnet"] \
+ debug_args_list \
+ [
"/var/runtime/MockBootstraps.dll",
"--debugger-spin-wait"
]
elif runtime == Runtime.go1x.value:
entrypoint = ["/var/runtime/aws-lambda-go"] \
+ debug_args_list \
+ [
"-debug=true",
"-delvePort=" + str(debug_port),
"-delvePath=" + LambdaContainer._DEFAULT_CONTAINER_DBG_GO_PATH,
]
elif runtime == Runtime.nodejs.value:
entrypoint = ["/usr/bin/node"] \
+ debug_args_list \
+ [
"--debug-brk=" + str(debug_port),
"--nolazy",
"--max-old-space-size=1229",
"--max-new-space-size=153",
"--max-executable-size=153",
"--expose-gc",
"/var/runtime/node_modules/awslambda/bin/awslambda",
]
elif runtime == Runtime.nodejs43.value:
entrypoint = ["/usr/local/lib64/node-v4.3.x/bin/node"] \
+ debug_args_list \
+ [
"--debug-brk=" + str(debug_port),
"--nolazy",
"--max-old-space-size=2547",
"--max-semi-space-size=150",
"--max-executable-size=160",
"--expose-gc",
"/var/runtime/node_modules/awslambda/index.js",
]
elif runtime == Runtime.nodejs610.value:
entrypoint = ["/var/lang/bin/node"] \
+ debug_args_list \
+ [
"--debug-brk=" + str(debug_port),
"--nolazy",
"--max-old-space-size=2547",
"--max-semi-space-size=150",
"--max-executable-size=160",
"--expose-gc",
"/var/runtime/node_modules/awslambda/index.js",
]
elif runtime == Runtime.nodejs810.value:
entrypoint = ["/var/lang/bin/node"] \
+ debug_args_list \
+ [
# Node8 requires the host to be explicitly set in order to bind to localhost
# instead of 127.0.0.1. https://github.com/nodejs/node/issues/11591#issuecomment-283110138
"--inspect-brk=0.0.0.0:" + str(debug_port),
"--nolazy",
"--expose-gc",
"--max-semi-space-size=150",
"--max-old-space-size=2707",
"/var/runtime/node_modules/awslambda/index.js",
]
elif runtime == Runtime.python27.value:
entrypoint = ["/usr/bin/python2.7"] \
+ debug_args_list \
+ [
"/var/runtime/awslambda/bootstrap.py"
]
elif runtime == Runtime.python36.value:
entrypoint = ["/var/lang/bin/python3.6"] \
+ debug_args_list \
+ [
"/var/runtime/awslambda/bootstrap.py"
]
elif runtime == Runtime.python37.value:
entrypoint = ["/var/rapid/init",
"--bootstrap",
"/var/lang/bin/python3.7",
"--bootstrap-args",
json.dumps(debug_args_list + ["/var/runtime/bootstrap"])
]
return entrypoint | python | def _get_entry_point(runtime, debug_options=None): # pylint: disable=too-many-branches
"""
Returns the entry point for the container. The default value for the entry point is already configured in the
Dockerfile. We override this default specifically when enabling debugging. The overridden entry point includes
a few extra flags to start the runtime in debug mode.
:param string runtime: Lambda function runtime name
:param int debug_port: Optional, port for debugger
:param string debug_args: Optional additional arguments passed to the entry point.
:return list: List containing the new entry points. Each element in the list is one portion of the command.
ie. if command is ``node index.js arg1 arg2``, then this list will be ["node", "index.js", "arg1", "arg2"]
"""
if not debug_options:
return None
if runtime not in LambdaContainer._supported_runtimes():
raise DebuggingNotSupported(
"Debugging is not currently supported for {}".format(runtime))
debug_port = debug_options.debug_port
debug_args_list = []
if debug_options.debug_args:
debug_args_list = debug_options.debug_args.split(" ")
# configs from: https://github.com/lambci/docker-lambda
# to which we add the extra debug mode options
entrypoint = None
if runtime == Runtime.java8.value:
entrypoint = ["/usr/bin/java"] \
+ debug_args_list \
+ [
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,quiet=y,address=" + str(debug_port),
"-XX:MaxHeapSize=2834432k",
"-XX:MaxMetaspaceSize=163840k",
"-XX:ReservedCodeCacheSize=81920k",
"-XX:+UseSerialGC",
# "-Xshare:on", doesn't work in conjunction with the debug options
"-XX:-TieredCompilation",
"-Djava.net.preferIPv4Stack=true",
"-jar",
"/var/runtime/lib/LambdaJavaRTEntry-1.0.jar",
]
elif runtime in (Runtime.dotnetcore20.value, Runtime.dotnetcore21.value):
entrypoint = ["/var/lang/bin/dotnet"] \
+ debug_args_list \
+ [
"/var/runtime/MockBootstraps.dll",
"--debugger-spin-wait"
]
elif runtime == Runtime.go1x.value:
entrypoint = ["/var/runtime/aws-lambda-go"] \
+ debug_args_list \
+ [
"-debug=true",
"-delvePort=" + str(debug_port),
"-delvePath=" + LambdaContainer._DEFAULT_CONTAINER_DBG_GO_PATH,
]
elif runtime == Runtime.nodejs.value:
entrypoint = ["/usr/bin/node"] \
+ debug_args_list \
+ [
"--debug-brk=" + str(debug_port),
"--nolazy",
"--max-old-space-size=1229",
"--max-new-space-size=153",
"--max-executable-size=153",
"--expose-gc",
"/var/runtime/node_modules/awslambda/bin/awslambda",
]
elif runtime == Runtime.nodejs43.value:
entrypoint = ["/usr/local/lib64/node-v4.3.x/bin/node"] \
+ debug_args_list \
+ [
"--debug-brk=" + str(debug_port),
"--nolazy",
"--max-old-space-size=2547",
"--max-semi-space-size=150",
"--max-executable-size=160",
"--expose-gc",
"/var/runtime/node_modules/awslambda/index.js",
]
elif runtime == Runtime.nodejs610.value:
entrypoint = ["/var/lang/bin/node"] \
+ debug_args_list \
+ [
"--debug-brk=" + str(debug_port),
"--nolazy",
"--max-old-space-size=2547",
"--max-semi-space-size=150",
"--max-executable-size=160",
"--expose-gc",
"/var/runtime/node_modules/awslambda/index.js",
]
elif runtime == Runtime.nodejs810.value:
entrypoint = ["/var/lang/bin/node"] \
+ debug_args_list \
+ [
# Node8 requires the host to be explicitly set in order to bind to localhost
# instead of 127.0.0.1. https://github.com/nodejs/node/issues/11591#issuecomment-283110138
"--inspect-brk=0.0.0.0:" + str(debug_port),
"--nolazy",
"--expose-gc",
"--max-semi-space-size=150",
"--max-old-space-size=2707",
"/var/runtime/node_modules/awslambda/index.js",
]
elif runtime == Runtime.python27.value:
entrypoint = ["/usr/bin/python2.7"] \
+ debug_args_list \
+ [
"/var/runtime/awslambda/bootstrap.py"
]
elif runtime == Runtime.python36.value:
entrypoint = ["/var/lang/bin/python3.6"] \
+ debug_args_list \
+ [
"/var/runtime/awslambda/bootstrap.py"
]
elif runtime == Runtime.python37.value:
entrypoint = ["/var/rapid/init",
"--bootstrap",
"/var/lang/bin/python3.7",
"--bootstrap-args",
json.dumps(debug_args_list + ["/var/runtime/bootstrap"])
]
return entrypoint | [
"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",
"(",
"\"Debugging is not currently supported for {}\"",
".",
"format",
"(",
"runtime",
")",
")",
"debug_port",
"=",
"debug_options",
".",
"debug_port",
"debug_args_list",
"=",
"[",
"]",
"if",
"debug_options",
".",
"debug_args",
":",
"debug_args_list",
"=",
"debug_options",
".",
"debug_args",
".",
"split",
"(",
"\" \"",
")",
"# configs from: https://github.com/lambci/docker-lambda",
"# to which we add the extra debug mode options",
"entrypoint",
"=",
"None",
"if",
"runtime",
"==",
"Runtime",
".",
"java8",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/usr/bin/java\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,quiet=y,address=\"",
"+",
"str",
"(",
"debug_port",
")",
",",
"\"-XX:MaxHeapSize=2834432k\"",
",",
"\"-XX:MaxMetaspaceSize=163840k\"",
",",
"\"-XX:ReservedCodeCacheSize=81920k\"",
",",
"\"-XX:+UseSerialGC\"",
",",
"# \"-Xshare:on\", doesn't work in conjunction with the debug options",
"\"-XX:-TieredCompilation\"",
",",
"\"-Djava.net.preferIPv4Stack=true\"",
",",
"\"-jar\"",
",",
"\"/var/runtime/lib/LambdaJavaRTEntry-1.0.jar\"",
",",
"]",
"elif",
"runtime",
"in",
"(",
"Runtime",
".",
"dotnetcore20",
".",
"value",
",",
"Runtime",
".",
"dotnetcore21",
".",
"value",
")",
":",
"entrypoint",
"=",
"[",
"\"/var/lang/bin/dotnet\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"\"/var/runtime/MockBootstraps.dll\"",
",",
"\"--debugger-spin-wait\"",
"]",
"elif",
"runtime",
"==",
"Runtime",
".",
"go1x",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/var/runtime/aws-lambda-go\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"\"-debug=true\"",
",",
"\"-delvePort=\"",
"+",
"str",
"(",
"debug_port",
")",
",",
"\"-delvePath=\"",
"+",
"LambdaContainer",
".",
"_DEFAULT_CONTAINER_DBG_GO_PATH",
",",
"]",
"elif",
"runtime",
"==",
"Runtime",
".",
"nodejs",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/usr/bin/node\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"\"--debug-brk=\"",
"+",
"str",
"(",
"debug_port",
")",
",",
"\"--nolazy\"",
",",
"\"--max-old-space-size=1229\"",
",",
"\"--max-new-space-size=153\"",
",",
"\"--max-executable-size=153\"",
",",
"\"--expose-gc\"",
",",
"\"/var/runtime/node_modules/awslambda/bin/awslambda\"",
",",
"]",
"elif",
"runtime",
"==",
"Runtime",
".",
"nodejs43",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/usr/local/lib64/node-v4.3.x/bin/node\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"\"--debug-brk=\"",
"+",
"str",
"(",
"debug_port",
")",
",",
"\"--nolazy\"",
",",
"\"--max-old-space-size=2547\"",
",",
"\"--max-semi-space-size=150\"",
",",
"\"--max-executable-size=160\"",
",",
"\"--expose-gc\"",
",",
"\"/var/runtime/node_modules/awslambda/index.js\"",
",",
"]",
"elif",
"runtime",
"==",
"Runtime",
".",
"nodejs610",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/var/lang/bin/node\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"\"--debug-brk=\"",
"+",
"str",
"(",
"debug_port",
")",
",",
"\"--nolazy\"",
",",
"\"--max-old-space-size=2547\"",
",",
"\"--max-semi-space-size=150\"",
",",
"\"--max-executable-size=160\"",
",",
"\"--expose-gc\"",
",",
"\"/var/runtime/node_modules/awslambda/index.js\"",
",",
"]",
"elif",
"runtime",
"==",
"Runtime",
".",
"nodejs810",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/var/lang/bin/node\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"# Node8 requires the host to be explicitly set in order to bind to localhost",
"# instead of 127.0.0.1. https://github.com/nodejs/node/issues/11591#issuecomment-283110138",
"\"--inspect-brk=0.0.0.0:\"",
"+",
"str",
"(",
"debug_port",
")",
",",
"\"--nolazy\"",
",",
"\"--expose-gc\"",
",",
"\"--max-semi-space-size=150\"",
",",
"\"--max-old-space-size=2707\"",
",",
"\"/var/runtime/node_modules/awslambda/index.js\"",
",",
"]",
"elif",
"runtime",
"==",
"Runtime",
".",
"python27",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/usr/bin/python2.7\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"\"/var/runtime/awslambda/bootstrap.py\"",
"]",
"elif",
"runtime",
"==",
"Runtime",
".",
"python36",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/var/lang/bin/python3.6\"",
"]",
"+",
"debug_args_list",
"+",
"[",
"\"/var/runtime/awslambda/bootstrap.py\"",
"]",
"elif",
"runtime",
"==",
"Runtime",
".",
"python37",
".",
"value",
":",
"entrypoint",
"=",
"[",
"\"/var/rapid/init\"",
",",
"\"--bootstrap\"",
",",
"\"/var/lang/bin/python3.7\"",
",",
"\"--bootstrap-args\"",
",",
"json",
".",
"dumps",
"(",
"debug_args_list",
"+",
"[",
"\"/var/runtime/bootstrap\"",
"]",
")",
"]",
"return",
"entrypoint"
] | Returns the entry point for the container. The default value for the entry point is already configured in the
Dockerfile. We override this default specifically when enabling debugging. The overridden entry point includes
a few extra flags to start the runtime in debug mode.
:param string runtime: Lambda function runtime name
:param int debug_port: Optional, port for debugger
:param string debug_args: Optional additional arguments passed to the entry point.
:return list: List containing the new entry points. Each element in the list is one portion of the command.
ie. if command is ``node index.js arg1 arg2``, then this list will be ["node", "index.js", "arg1", "arg2"] | [
"Returns",
"the",
"entry",
"point",
"for",
"the",
"container",
".",
"The",
"default",
"value",
"for",
"the",
"entry",
"point",
"is",
"already",
"configured",
"in",
"the",
"Dockerfile",
".",
"We",
"override",
"this",
"default",
"specifically",
"when",
"enabling",
"debugging",
".",
"The",
"overridden",
"entry",
"point",
"includes",
"a",
"few",
"extra",
"flags",
"to",
"start",
"the",
"runtime",
"in",
"debug",
"mode",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_container.py#L161-L305 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | SamApiProvider._extract_apis | def _extract_apis(self, resources):
"""
Extract all Implicit Apis (Apis defined through Serverless Function with an Api Event
:param dict resources: Dictionary of SAM/CloudFormation resources
:return: List of nametuple Api
"""
# 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 defined on a AWS::Serverless::Api resource with logical ID "ServerlessRestApi". Therefore, no matter
# if it is an implicit API or an explicit API, there is a corresponding resource of type AWS::Serverless::Api
# that contains these additional configurations.
#
# We use this assumption in the following loop to collect information from resources of type
# AWS::Serverless::Api. We also extract API from Serverless::Function resource and add them to the
# corresponding Serverless::Api resource. This is all done using the ``collector``.
collector = ApiCollector()
for logical_id, resource in resources.items():
resource_type = resource.get(SamApiProvider._TYPE)
if resource_type == SamApiProvider._SERVERLESS_FUNCTION:
self._extract_apis_from_function(logical_id, resource, collector)
if resource_type == SamApiProvider._SERVERLESS_API:
self._extract_from_serverless_api(logical_id, resource, collector)
apis = SamApiProvider._merge_apis(collector)
return self._normalize_apis(apis) | python | def _extract_apis(self, resources):
"""
Extract all Implicit Apis (Apis defined through Serverless Function with an Api Event
:param dict resources: Dictionary of SAM/CloudFormation resources
:return: List of nametuple Api
"""
# 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 defined on a AWS::Serverless::Api resource with logical ID "ServerlessRestApi". Therefore, no matter
# if it is an implicit API or an explicit API, there is a corresponding resource of type AWS::Serverless::Api
# that contains these additional configurations.
#
# We use this assumption in the following loop to collect information from resources of type
# AWS::Serverless::Api. We also extract API from Serverless::Function resource and add them to the
# corresponding Serverless::Api resource. This is all done using the ``collector``.
collector = ApiCollector()
for logical_id, resource in resources.items():
resource_type = resource.get(SamApiProvider._TYPE)
if resource_type == SamApiProvider._SERVERLESS_FUNCTION:
self._extract_apis_from_function(logical_id, resource, collector)
if resource_type == SamApiProvider._SERVERLESS_API:
self._extract_from_serverless_api(logical_id, resource, collector)
apis = SamApiProvider._merge_apis(collector)
return self._normalize_apis(apis) | [
"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 defined on a AWS::Serverless::Api resource with logical ID \"ServerlessRestApi\". Therefore, no matter",
"# if it is an implicit API or an explicit API, there is a corresponding resource of type AWS::Serverless::Api",
"# that contains these additional configurations.",
"#",
"# We use this assumption in the following loop to collect information from resources of type",
"# AWS::Serverless::Api. We also extract API from Serverless::Function resource and add them to the",
"# corresponding Serverless::Api resource. This is all done using the ``collector``.",
"collector",
"=",
"ApiCollector",
"(",
")",
"for",
"logical_id",
",",
"resource",
"in",
"resources",
".",
"items",
"(",
")",
":",
"resource_type",
"=",
"resource",
".",
"get",
"(",
"SamApiProvider",
".",
"_TYPE",
")",
"if",
"resource_type",
"==",
"SamApiProvider",
".",
"_SERVERLESS_FUNCTION",
":",
"self",
".",
"_extract_apis_from_function",
"(",
"logical_id",
",",
"resource",
",",
"collector",
")",
"if",
"resource_type",
"==",
"SamApiProvider",
".",
"_SERVERLESS_API",
":",
"self",
".",
"_extract_from_serverless_api",
"(",
"logical_id",
",",
"resource",
",",
"collector",
")",
"apis",
"=",
"SamApiProvider",
".",
"_merge_apis",
"(",
"collector",
")",
"return",
"self",
".",
"_normalize_apis",
"(",
"apis",
")"
] | Extract all Implicit Apis (Apis defined through Serverless Function with an Api Event
:param dict resources: Dictionary of SAM/CloudFormation resources
:return: List of nametuple Api | [
"Extract",
"all",
"Implicit",
"Apis",
"(",
"Apis",
"defined",
"through",
"Serverless",
"Function",
"with",
"an",
"Api",
"Event"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L76-L107 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | SamApiProvider._extract_from_serverless_api | def _extract_from_serverless_api(self, logical_id, api_resource, collector):
"""
Extract APIs from AWS::Serverless::Api resource by reading and parsing Swagger documents. The result is added
to the collector.
Parameters
----------
logical_id : str
Logical ID of the resource
api_resource : dict
Resource definition, including its properties
collector : ApiCollector
Instance of the API collector that where we will save the API information
"""
properties = api_resource.get("Properties", {})
body = properties.get("DefinitionBody")
uri = properties.get("DefinitionUri")
binary_media = properties.get("BinaryMediaTypes", [])
if not body and not uri:
# Swagger is not found anywhere.
LOG.debug("Skipping resource '%s'. Swagger document not found in DefinitionBody and DefinitionUri",
logical_id)
return
reader = SamSwaggerReader(definition_body=body,
definition_uri=uri,
working_dir=self.cwd)
swagger = reader.read()
parser = SwaggerParser(swagger)
apis = parser.get_apis()
LOG.debug("Found '%s' APIs in resource '%s'", len(apis), logical_id)
collector.add_apis(logical_id, apis)
collector.add_binary_media_types(logical_id, parser.get_binary_media_types()) # Binary media from swagger
collector.add_binary_media_types(logical_id, binary_media) | python | def _extract_from_serverless_api(self, logical_id, api_resource, collector):
"""
Extract APIs from AWS::Serverless::Api resource by reading and parsing Swagger documents. The result is added
to the collector.
Parameters
----------
logical_id : str
Logical ID of the resource
api_resource : dict
Resource definition, including its properties
collector : ApiCollector
Instance of the API collector that where we will save the API information
"""
properties = api_resource.get("Properties", {})
body = properties.get("DefinitionBody")
uri = properties.get("DefinitionUri")
binary_media = properties.get("BinaryMediaTypes", [])
if not body and not uri:
# Swagger is not found anywhere.
LOG.debug("Skipping resource '%s'. Swagger document not found in DefinitionBody and DefinitionUri",
logical_id)
return
reader = SamSwaggerReader(definition_body=body,
definition_uri=uri,
working_dir=self.cwd)
swagger = reader.read()
parser = SwaggerParser(swagger)
apis = parser.get_apis()
LOG.debug("Found '%s' APIs in resource '%s'", len(apis), logical_id)
collector.add_apis(logical_id, apis)
collector.add_binary_media_types(logical_id, parser.get_binary_media_types()) # Binary media from swagger
collector.add_binary_media_types(logical_id, binary_media) | [
"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",
"(",
"\"BinaryMediaTypes\"",
",",
"[",
"]",
")",
"if",
"not",
"body",
"and",
"not",
"uri",
":",
"# Swagger is not found anywhere.",
"LOG",
".",
"debug",
"(",
"\"Skipping resource '%s'. Swagger document not found in DefinitionBody and DefinitionUri\"",
",",
"logical_id",
")",
"return",
"reader",
"=",
"SamSwaggerReader",
"(",
"definition_body",
"=",
"body",
",",
"definition_uri",
"=",
"uri",
",",
"working_dir",
"=",
"self",
".",
"cwd",
")",
"swagger",
"=",
"reader",
".",
"read",
"(",
")",
"parser",
"=",
"SwaggerParser",
"(",
"swagger",
")",
"apis",
"=",
"parser",
".",
"get_apis",
"(",
")",
"LOG",
".",
"debug",
"(",
"\"Found '%s' APIs in resource '%s'\"",
",",
"len",
"(",
"apis",
")",
",",
"logical_id",
")",
"collector",
".",
"add_apis",
"(",
"logical_id",
",",
"apis",
")",
"collector",
".",
"add_binary_media_types",
"(",
"logical_id",
",",
"parser",
".",
"get_binary_media_types",
"(",
")",
")",
"# Binary media from swagger",
"collector",
".",
"add_binary_media_types",
"(",
"logical_id",
",",
"binary_media",
")"
] | Extract APIs from AWS::Serverless::Api resource by reading and parsing Swagger documents. The result is added
to the collector.
Parameters
----------
logical_id : str
Logical ID of the resource
api_resource : dict
Resource definition, including its properties
collector : ApiCollector
Instance of the API collector that where we will save the API information | [
"Extract",
"APIs",
"from",
"AWS",
"::",
"Serverless",
"::",
"Api",
"resource",
"by",
"reading",
"and",
"parsing",
"Swagger",
"documents",
".",
"The",
"result",
"is",
"added",
"to",
"the",
"collector",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L109-L147 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | SamApiProvider._merge_apis | def _merge_apis(collector):
"""
Quite often, an API is defined both in Implicit and Explicit API definitions. In such cases, Implicit API
definition wins because that conveys clear intent that the API is backed by a function. This method will
merge two such list of Apis with the right order of precedence. If a Path+Method combination is defined
in both the places, only one wins.
Parameters
----------
collector : ApiCollector
Collector object that holds all the APIs specified in the template
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of APIs obtained by combining both the input lists.
"""
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 ServerlessRestApi
for logical_id, apis in collector:
if logical_id == SamApiProvider._IMPLICIT_API_RESOURCE_ID:
implicit_apis.extend(apis)
else:
explicit_apis.extend(apis)
# We will use "path+method" combination as key to this dictionary and store the Api config for this combination.
# If an path+method combo already exists, then overwrite it if and only if this is an implicit API
all_apis = {}
# By adding implicit APIs to the end of the list, they will be iterated last. If a configuration was already
# written by explicit API, it will be overriden by implicit API, just by virtue of order of iteration.
all_configs = explicit_apis + implicit_apis
for config in all_configs:
# Normalize the methods before de-duping to allow an ANY method in implicit API to override a regular HTTP
# method on explicit API.
for normalized_method in SamApiProvider._normalize_http_methods(config.method):
key = config.path + normalized_method
all_apis[key] = config
result = set(all_apis.values()) # Assign to a set() to de-dupe
LOG.debug("Removed duplicates from '%d' Explicit APIs and '%d' Implicit APIs to produce '%d' APIs",
len(explicit_apis), len(implicit_apis), len(result))
return list(result) | python | def _merge_apis(collector):
"""
Quite often, an API is defined both in Implicit and Explicit API definitions. In such cases, Implicit API
definition wins because that conveys clear intent that the API is backed by a function. This method will
merge two such list of Apis with the right order of precedence. If a Path+Method combination is defined
in both the places, only one wins.
Parameters
----------
collector : ApiCollector
Collector object that holds all the APIs specified in the template
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of APIs obtained by combining both the input lists.
"""
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 ServerlessRestApi
for logical_id, apis in collector:
if logical_id == SamApiProvider._IMPLICIT_API_RESOURCE_ID:
implicit_apis.extend(apis)
else:
explicit_apis.extend(apis)
# We will use "path+method" combination as key to this dictionary and store the Api config for this combination.
# If an path+method combo already exists, then overwrite it if and only if this is an implicit API
all_apis = {}
# By adding implicit APIs to the end of the list, they will be iterated last. If a configuration was already
# written by explicit API, it will be overriden by implicit API, just by virtue of order of iteration.
all_configs = explicit_apis + implicit_apis
for config in all_configs:
# Normalize the methods before de-duping to allow an ANY method in implicit API to override a regular HTTP
# method on explicit API.
for normalized_method in SamApiProvider._normalize_http_methods(config.method):
key = config.path + normalized_method
all_apis[key] = config
result = set(all_apis.values()) # Assign to a set() to de-dupe
LOG.debug("Removed duplicates from '%d' Explicit APIs and '%d' Implicit APIs to produce '%d' APIs",
len(explicit_apis), len(implicit_apis), len(result))
return list(result) | [
"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 ServerlessRestApi",
"for",
"logical_id",
",",
"apis",
"in",
"collector",
":",
"if",
"logical_id",
"==",
"SamApiProvider",
".",
"_IMPLICIT_API_RESOURCE_ID",
":",
"implicit_apis",
".",
"extend",
"(",
"apis",
")",
"else",
":",
"explicit_apis",
".",
"extend",
"(",
"apis",
")",
"# We will use \"path+method\" combination as key to this dictionary and store the Api config for this combination.",
"# If an path+method combo already exists, then overwrite it if and only if this is an implicit API",
"all_apis",
"=",
"{",
"}",
"# By adding implicit APIs to the end of the list, they will be iterated last. If a configuration was already",
"# written by explicit API, it will be overriden by implicit API, just by virtue of order of iteration.",
"all_configs",
"=",
"explicit_apis",
"+",
"implicit_apis",
"for",
"config",
"in",
"all_configs",
":",
"# Normalize the methods before de-duping to allow an ANY method in implicit API to override a regular HTTP",
"# method on explicit API.",
"for",
"normalized_method",
"in",
"SamApiProvider",
".",
"_normalize_http_methods",
"(",
"config",
".",
"method",
")",
":",
"key",
"=",
"config",
".",
"path",
"+",
"normalized_method",
"all_apis",
"[",
"key",
"]",
"=",
"config",
"result",
"=",
"set",
"(",
"all_apis",
".",
"values",
"(",
")",
")",
"# Assign to a set() to de-dupe",
"LOG",
".",
"debug",
"(",
"\"Removed duplicates from '%d' Explicit APIs and '%d' Implicit APIs to produce '%d' APIs\"",
",",
"len",
"(",
"explicit_apis",
")",
",",
"len",
"(",
"implicit_apis",
")",
",",
"len",
"(",
"result",
")",
")",
"return",
"list",
"(",
"result",
")"
] | Quite often, an API is defined both in Implicit and Explicit API definitions. In such cases, Implicit API
definition wins because that conveys clear intent that the API is backed by a function. This method will
merge two such list of Apis with the right order of precedence. If a Path+Method combination is defined
in both the places, only one wins.
Parameters
----------
collector : ApiCollector
Collector object that holds all the APIs specified in the template
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of APIs obtained by combining both the input lists. | [
"Quite",
"often",
"an",
"API",
"is",
"defined",
"both",
"in",
"Implicit",
"and",
"Explicit",
"API",
"definitions",
".",
"In",
"such",
"cases",
"Implicit",
"API",
"definition",
"wins",
"because",
"that",
"conveys",
"clear",
"intent",
"that",
"the",
"API",
"is",
"backed",
"by",
"a",
"function",
".",
"This",
"method",
"will",
"merge",
"two",
"such",
"list",
"of",
"Apis",
"with",
"the",
"right",
"order",
"of",
"precedence",
".",
"If",
"a",
"Path",
"+",
"Method",
"combination",
"is",
"defined",
"in",
"both",
"the",
"places",
"only",
"one",
"wins",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L150-L198 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | SamApiProvider._normalize_apis | def _normalize_apis(apis):
"""
Normalize the APIs to use standard method name
Parameters
----------
apis : list of samcli.commands.local.lib.provider.Api
List of APIs to replace normalize
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of normalized 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 copies of namedtuple
result.append(api._replace(method=normalized_method))
return result | python | def _normalize_apis(apis):
"""
Normalize the APIs to use standard method name
Parameters
----------
apis : list of samcli.commands.local.lib.provider.Api
List of APIs to replace normalize
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of normalized 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 copies of namedtuple
result.append(api._replace(method=normalized_method))
return result | [
"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 copies of namedtuple",
"result",
".",
"append",
"(",
"api",
".",
"_replace",
"(",
"method",
"=",
"normalized_method",
")",
")",
"return",
"result"
] | Normalize the APIs to use standard method name
Parameters
----------
apis : list of samcli.commands.local.lib.provider.Api
List of APIs to replace normalize
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of normalized APIs | [
"Normalize",
"the",
"APIs",
"to",
"use",
"standard",
"method",
"name"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L201-L222 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | SamApiProvider._extract_apis_from_function | def _extract_apis_from_function(logical_id, function_resource, collector):
"""
Fetches a list of APIs configured for this SAM Function resource.
Parameters
----------
logical_id : str
Logical ID of the resource
function_resource : dict
Contents of the function resource including its properties
collector : ApiCollector
Instance of the API collector that where we will save the API information
"""
resource_properties = function_resource.get("Properties", {})
serverless_function_events = resource_properties.get(SamApiProvider._FUNCTION_EVENT, {})
SamApiProvider._extract_apis_from_events(logical_id, serverless_function_events, collector) | python | def _extract_apis_from_function(logical_id, function_resource, collector):
"""
Fetches a list of APIs configured for this SAM Function resource.
Parameters
----------
logical_id : str
Logical ID of the resource
function_resource : dict
Contents of the function resource including its properties
collector : ApiCollector
Instance of the API collector that where we will save the API information
"""
resource_properties = function_resource.get("Properties", {})
serverless_function_events = resource_properties.get(SamApiProvider._FUNCTION_EVENT, {})
SamApiProvider._extract_apis_from_events(logical_id, serverless_function_events, collector) | [
"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",
".",
"_extract_apis_from_events",
"(",
"logical_id",
",",
"serverless_function_events",
",",
"collector",
")"
] | Fetches a list of APIs configured for this SAM Function resource.
Parameters
----------
logical_id : str
Logical ID of the resource
function_resource : dict
Contents of the function resource including its properties
collector : ApiCollector
Instance of the API collector that where we will save the API information | [
"Fetches",
"a",
"list",
"of",
"APIs",
"configured",
"for",
"this",
"SAM",
"Function",
"resource",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L225-L243 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | SamApiProvider._extract_apis_from_events | def _extract_apis_from_events(function_logical_id, serverless_function_events, collector):
"""
Given an AWS::Serverless::Function Event Dictionary, extract out all 'Api' events and store within the
collector
Parameters
----------
function_logical_id : str
LogicalId of the AWS::Serverless::Function
serverless_function_events : dict
Event Dictionary of a AWS::Serverless::Function
collector : ApiCollector
Instance of the API collector that where we will save the API information
"""
count = 0
for _, event in serverless_function_events.items():
if SamApiProvider._FUNCTION_EVENT_TYPE_API == event.get(SamApiProvider._TYPE):
api_resource_id, api = SamApiProvider._convert_event_api(function_logical_id, event.get("Properties"))
collector.add_apis(api_resource_id, [api])
count += 1
LOG.debug("Found '%d' API Events in Serverless function with name '%s'", count, function_logical_id) | python | def _extract_apis_from_events(function_logical_id, serverless_function_events, collector):
"""
Given an AWS::Serverless::Function Event Dictionary, extract out all 'Api' events and store within the
collector
Parameters
----------
function_logical_id : str
LogicalId of the AWS::Serverless::Function
serverless_function_events : dict
Event Dictionary of a AWS::Serverless::Function
collector : ApiCollector
Instance of the API collector that where we will save the API information
"""
count = 0
for _, event in serverless_function_events.items():
if SamApiProvider._FUNCTION_EVENT_TYPE_API == event.get(SamApiProvider._TYPE):
api_resource_id, api = SamApiProvider._convert_event_api(function_logical_id, event.get("Properties"))
collector.add_apis(api_resource_id, [api])
count += 1
LOG.debug("Found '%d' API Events in Serverless function with name '%s'", count, function_logical_id) | [
"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",
")",
":",
"api_resource_id",
",",
"api",
"=",
"SamApiProvider",
".",
"_convert_event_api",
"(",
"function_logical_id",
",",
"event",
".",
"get",
"(",
"\"Properties\"",
")",
")",
"collector",
".",
"add_apis",
"(",
"api_resource_id",
",",
"[",
"api",
"]",
")",
"count",
"+=",
"1",
"LOG",
".",
"debug",
"(",
"\"Found '%d' API Events in Serverless function with name '%s'\"",
",",
"count",
",",
"function_logical_id",
")"
] | Given an AWS::Serverless::Function Event Dictionary, extract out all 'Api' events and store within the
collector
Parameters
----------
function_logical_id : str
LogicalId of the AWS::Serverless::Function
serverless_function_events : dict
Event Dictionary of a AWS::Serverless::Function
collector : ApiCollector
Instance of the API collector that where we will save the API information | [
"Given",
"an",
"AWS",
"::",
"Serverless",
"::",
"Function",
"Event",
"Dictionary",
"extract",
"out",
"all",
"Api",
"events",
"and",
"store",
"within",
"the",
"collector"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L246-L270 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | SamApiProvider._convert_event_api | def _convert_event_api(lambda_logical_id, event_properties):
"""
Converts a AWS::Serverless::Function's Event Property to an Api configuration usable by the provider.
:param str lambda_logical_id: Logical Id of the AWS::Serverless::Function
:param dict event_properties: Dictionary of the Event's Property
:return tuple: tuple of API resource name and Api namedTuple
"""
path = event_properties.get(SamApiProvider._EVENT_PATH)
method = event_properties.get(SamApiProvider._EVENT_METHOD)
# An API Event, can have RestApiId property which designates the resource that owns this API. If omitted,
# the API is owned by Implicit API resource. This could either be a direct resource logical ID or a
# "Ref" of the logicalID
api_resource_id = event_properties.get("RestApiId", SamApiProvider._IMPLICIT_API_RESOURCE_ID)
if isinstance(api_resource_id, dict) and "Ref" in api_resource_id:
api_resource_id = api_resource_id["Ref"]
# This is still a dictionary. Something wrong with the template
if isinstance(api_resource_id, dict):
LOG.debug("Invalid RestApiId property of event %s", event_properties)
raise InvalidSamDocumentException("RestApiId property of resource with logicalId '{}' is invalid. "
"It should either be a LogicalId string or a Ref of a Logical Id string"
.format(lambda_logical_id))
return api_resource_id, Api(path=path, method=method, function_name=lambda_logical_id) | python | def _convert_event_api(lambda_logical_id, event_properties):
"""
Converts a AWS::Serverless::Function's Event Property to an Api configuration usable by the provider.
:param str lambda_logical_id: Logical Id of the AWS::Serverless::Function
:param dict event_properties: Dictionary of the Event's Property
:return tuple: tuple of API resource name and Api namedTuple
"""
path = event_properties.get(SamApiProvider._EVENT_PATH)
method = event_properties.get(SamApiProvider._EVENT_METHOD)
# An API Event, can have RestApiId property which designates the resource that owns this API. If omitted,
# the API is owned by Implicit API resource. This could either be a direct resource logical ID or a
# "Ref" of the logicalID
api_resource_id = event_properties.get("RestApiId", SamApiProvider._IMPLICIT_API_RESOURCE_ID)
if isinstance(api_resource_id, dict) and "Ref" in api_resource_id:
api_resource_id = api_resource_id["Ref"]
# This is still a dictionary. Something wrong with the template
if isinstance(api_resource_id, dict):
LOG.debug("Invalid RestApiId property of event %s", event_properties)
raise InvalidSamDocumentException("RestApiId property of resource with logicalId '{}' is invalid. "
"It should either be a LogicalId string or a Ref of a Logical Id string"
.format(lambda_logical_id))
return api_resource_id, Api(path=path, method=method, function_name=lambda_logical_id) | [
"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 resource that owns this API. If omitted,",
"# the API is owned by Implicit API resource. This could either be a direct resource logical ID or a",
"# \"Ref\" of the logicalID",
"api_resource_id",
"=",
"event_properties",
".",
"get",
"(",
"\"RestApiId\"",
",",
"SamApiProvider",
".",
"_IMPLICIT_API_RESOURCE_ID",
")",
"if",
"isinstance",
"(",
"api_resource_id",
",",
"dict",
")",
"and",
"\"Ref\"",
"in",
"api_resource_id",
":",
"api_resource_id",
"=",
"api_resource_id",
"[",
"\"Ref\"",
"]",
"# This is still a dictionary. Something wrong with the template",
"if",
"isinstance",
"(",
"api_resource_id",
",",
"dict",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Invalid RestApiId property of event %s\"",
",",
"event_properties",
")",
"raise",
"InvalidSamDocumentException",
"(",
"\"RestApiId property of resource with logicalId '{}' is invalid. \"",
"\"It should either be a LogicalId string or a Ref of a Logical Id string\"",
".",
"format",
"(",
"lambda_logical_id",
")",
")",
"return",
"api_resource_id",
",",
"Api",
"(",
"path",
"=",
"path",
",",
"method",
"=",
"method",
",",
"function_name",
"=",
"lambda_logical_id",
")"
] | Converts a AWS::Serverless::Function's Event Property to an Api configuration usable by the provider.
:param str lambda_logical_id: Logical Id of the AWS::Serverless::Function
:param dict event_properties: Dictionary of the Event's Property
:return tuple: tuple of API resource name and Api namedTuple | [
"Converts",
"a",
"AWS",
"::",
"Serverless",
"::",
"Function",
"s",
"Event",
"Property",
"to",
"an",
"Api",
"configuration",
"usable",
"by",
"the",
"provider",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L273-L298 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | SamApiProvider._normalize_http_methods | def _normalize_http_methods(http_method):
"""
Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all
supported Http Methods on Api Gateway.
:param str http_method: Http method
:yield str: Either the input http_method or one of the _ANY_HTTP_METHODS (normalized Http Methods)
"""
if http_method.upper() == 'ANY':
for method in SamApiProvider._ANY_HTTP_METHODS:
yield method.upper()
else:
yield http_method.upper() | python | def _normalize_http_methods(http_method):
"""
Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all
supported Http Methods on Api Gateway.
:param str http_method: Http method
:yield str: Either the input http_method or one of the _ANY_HTTP_METHODS (normalized Http Methods)
"""
if http_method.upper() == 'ANY':
for method in SamApiProvider._ANY_HTTP_METHODS:
yield method.upper()
else:
yield http_method.upper() | [
"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",
"(",
")"
] | Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all
supported Http Methods on Api Gateway.
:param str http_method: Http method
:yield str: Either the input http_method or one of the _ANY_HTTP_METHODS (normalized Http Methods) | [
"Normalizes",
"Http",
"Methods",
".",
"Api",
"Gateway",
"allows",
"a",
"Http",
"Methods",
"of",
"ANY",
".",
"This",
"is",
"a",
"special",
"verb",
"to",
"denote",
"all",
"supported",
"Http",
"Methods",
"on",
"Api",
"Gateway",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L301-L314 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | ApiCollector.add_apis | def add_apis(self, logical_id, apis):
"""
Stores the given APIs tagged under the given logicalId
Parameters
----------
logical_id : str
LogicalId of the AWS::Serverless::Api resource
apis : list of samcli.commands.local.lib.provider.Api
List of APIs available in this resource
"""
properties = self._get_properties(logical_id)
properties.apis.extend(apis) | python | def add_apis(self, logical_id, apis):
"""
Stores the given APIs tagged under the given logicalId
Parameters
----------
logical_id : str
LogicalId of the AWS::Serverless::Api resource
apis : list of samcli.commands.local.lib.provider.Api
List of APIs available in this resource
"""
properties = self._get_properties(logical_id)
properties.apis.extend(apis) | [
"def",
"add_apis",
"(",
"self",
",",
"logical_id",
",",
"apis",
")",
":",
"properties",
"=",
"self",
".",
"_get_properties",
"(",
"logical_id",
")",
"properties",
".",
"apis",
".",
"extend",
"(",
"apis",
")"
] | Stores the given APIs tagged under the given logicalId
Parameters
----------
logical_id : str
LogicalId of the AWS::Serverless::Api resource
apis : list of samcli.commands.local.lib.provider.Api
List of APIs available in this resource | [
"Stores",
"the",
"given",
"APIs",
"tagged",
"under",
"the",
"given",
"logicalId"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L350-L363 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | ApiCollector.add_binary_media_types | def add_binary_media_types(self, logical_id, binary_media_types):
"""
Stores the binary media type configuration for the API with given logical ID
Parameters
----------
logical_id : str
LogicalId of the AWS::Serverless::Api resource
binary_media_types : list of str
List of binary media types supported by this resource
"""
properties = self._get_properties(logical_id)
binary_media_types = binary_media_types or []
for value in binary_media_types:
normalized_value = self._normalize_binary_media_type(value)
# If the value is not supported, then just skip it.
if normalized_value:
properties.binary_media_types.add(normalized_value)
else:
LOG.debug("Unsupported data type of binary media type value of resource '%s'", logical_id) | python | def add_binary_media_types(self, logical_id, binary_media_types):
"""
Stores the binary media type configuration for the API with given logical ID
Parameters
----------
logical_id : str
LogicalId of the AWS::Serverless::Api resource
binary_media_types : list of str
List of binary media types supported by this resource
"""
properties = self._get_properties(logical_id)
binary_media_types = binary_media_types or []
for value in binary_media_types:
normalized_value = self._normalize_binary_media_type(value)
# If the value is not supported, then just skip it.
if normalized_value:
properties.binary_media_types.add(normalized_value)
else:
LOG.debug("Unsupported data type of binary media type value of resource '%s'", logical_id) | [
"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_binary_media_type",
"(",
"value",
")",
"# If the value is not supported, then just skip it.",
"if",
"normalized_value",
":",
"properties",
".",
"binary_media_types",
".",
"add",
"(",
"normalized_value",
")",
"else",
":",
"LOG",
".",
"debug",
"(",
"\"Unsupported data type of binary media type value of resource '%s'\"",
",",
"logical_id",
")"
] | Stores the binary media type configuration for the API with given logical ID
Parameters
----------
logical_id : str
LogicalId of the AWS::Serverless::Api resource
binary_media_types : list of str
List of binary media types supported by this resource | [
"Stores",
"the",
"binary",
"media",
"type",
"configuration",
"for",
"the",
"API",
"with",
"given",
"logical",
"ID"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L365-L388 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | ApiCollector._get_apis_with_config | def _get_apis_with_config(self, logical_id):
"""
Returns the list of APIs in this resource along with other extra configuration such as binary media types,
cors etc. Additional configuration is merged directly into the API data because these properties, although
defined globally, actually apply to each API.
Parameters
----------
logical_id : str
Logical ID of the resource to fetch data for
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of APIs with additional configurations for the resource with given logicalId. If there are no APIs,
then it returns an empty list
"""
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 stable
cors = properties.cors
result = []
for api in properties.apis:
# Create a copy of the API with updated configuration
updated_api = api._replace(binary_media_types=binary_media,
cors=cors)
result.append(updated_api)
return result | python | def _get_apis_with_config(self, logical_id):
"""
Returns the list of APIs in this resource along with other extra configuration such as binary media types,
cors etc. Additional configuration is merged directly into the API data because these properties, although
defined globally, actually apply to each API.
Parameters
----------
logical_id : str
Logical ID of the resource to fetch data for
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of APIs with additional configurations for the resource with given logicalId. If there are no APIs,
then it returns an empty list
"""
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 stable
cors = properties.cors
result = []
for api in properties.apis:
# Create a copy of the API with updated configuration
updated_api = api._replace(binary_media_types=binary_media,
cors=cors)
result.append(updated_api)
return result | [
"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 stable",
"cors",
"=",
"properties",
".",
"cors",
"result",
"=",
"[",
"]",
"for",
"api",
"in",
"properties",
".",
"apis",
":",
"# Create a copy of the API with updated configuration",
"updated_api",
"=",
"api",
".",
"_replace",
"(",
"binary_media_types",
"=",
"binary_media",
",",
"cors",
"=",
"cors",
")",
"result",
".",
"append",
"(",
"updated_api",
")",
"return",
"result"
] | Returns the list of APIs in this resource along with other extra configuration such as binary media types,
cors etc. Additional configuration is merged directly into the API data because these properties, although
defined globally, actually apply to each API.
Parameters
----------
logical_id : str
Logical ID of the resource to fetch data for
Returns
-------
list of samcli.commands.local.lib.provider.Api
List of APIs with additional configurations for the resource with given logicalId. If there are no APIs,
then it returns an empty list | [
"Returns",
"the",
"list",
"of",
"APIs",
"in",
"this",
"resource",
"along",
"with",
"other",
"extra",
"configuration",
"such",
"as",
"binary",
"media",
"types",
"cors",
"etc",
".",
"Additional",
"configuration",
"is",
"merged",
"directly",
"into",
"the",
"API",
"data",
"because",
"these",
"properties",
"although",
"defined",
"globally",
"actually",
"apply",
"to",
"each",
"API",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L390-L421 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_api_provider.py | ApiCollector._get_properties | def _get_properties(self, logical_id):
"""
Returns the properties of resource with given logical ID. If a resource is not found, then it returns an
empty data.
Parameters
----------
logical_id : str
Logical ID of the resource
Returns
-------
samcli.commands.local.lib.sam_api_provider.ApiCollector.Properties
Properties object for this resource.
"""
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
binary_media_types=set(),
cors=None)
return self.by_resource[logical_id] | python | def _get_properties(self, logical_id):
"""
Returns the properties of resource with given logical ID. If a resource is not found, then it returns an
empty data.
Parameters
----------
logical_id : str
Logical ID of the resource
Returns
-------
samcli.commands.local.lib.sam_api_provider.ApiCollector.Properties
Properties object for this resource.
"""
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
binary_media_types=set(),
cors=None)
return self.by_resource[logical_id] | [
"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",
"binary_media_types",
"=",
"set",
"(",
")",
",",
"cors",
"=",
"None",
")",
"return",
"self",
".",
"by_resource",
"[",
"logical_id",
"]"
] | Returns the properties of resource with given logical ID. If a resource is not found, then it returns an
empty data.
Parameters
----------
logical_id : str
Logical ID of the resource
Returns
-------
samcli.commands.local.lib.sam_api_provider.ApiCollector.Properties
Properties object for this resource. | [
"Returns",
"the",
"properties",
"of",
"resource",
"with",
"given",
"logical",
"ID",
".",
"If",
"a",
"resource",
"is",
"not",
"found",
"then",
"it",
"returns",
"an",
"empty",
"data",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_api_provider.py#L423-L445 | train |
awslabs/aws-sam-cli | samcli/local/lambdafn/runtime.py | _unzip_file | def _unzip_file(filepath):
"""
Helper method to unzip a file to a temporary directory
:param string filepath: Absolute path to this file
:return string: Path to the temporary directory where it was unzipped
"""
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 Docker File sharing settings will not resolve
# symlinks. Hence get the real path before passing to Docker.
# Especially useful in Mac OSX which returns /var/folders which is a symlink to /private/var/folders that is a
# part of Docker's Shared Files directories
return os.path.realpath(temp_dir) | python | def _unzip_file(filepath):
"""
Helper method to unzip a file to a temporary directory
:param string filepath: Absolute path to this file
:return string: Path to the temporary directory where it was unzipped
"""
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 Docker File sharing settings will not resolve
# symlinks. Hence get the real path before passing to Docker.
# Especially useful in Mac OSX which returns /var/folders which is a symlink to /private/var/folders that is a
# part of Docker's Shared Files directories
return os.path.realpath(temp_dir) | [
"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 Docker File sharing settings will not resolve",
"# symlinks. Hence get the real path before passing to Docker.",
"# Especially useful in Mac OSX which returns /var/folders which is a symlink to /private/var/folders that is a",
"# part of Docker's Shared Files directories",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"temp_dir",
")"
] | Helper method to unzip a file to a temporary directory
:param string filepath: Absolute path to this file
:return string: Path to the temporary directory where it was unzipped | [
"Helper",
"method",
"to",
"unzip",
"a",
"file",
"to",
"a",
"temporary",
"directory"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/runtime.py#L184-L205 | train |
awslabs/aws-sam-cli | samcli/local/lambdafn/runtime.py | LambdaRuntime.invoke | def invoke(self,
function_config,
event,
debug_context=None,
stdout=None,
stderr=None):
"""
Invoke the given Lambda function locally.
##### NOTE: THIS IS A LONG BLOCKING CALL #####
This method will block until either the Lambda function completes or timed out, which could be seconds.
A blocking call will block the thread preventing any other operations from happening. If you are using this
method in a web-server or in contexts where your application needs to be responsive when function is running,
take care to invoke the function in a separate thread. Co-Routines or micro-threads might not perform well
because the underlying implementation essentially blocks on a socket, which is synchronous.
:param FunctionConfig function_config: Configuration of the function to invoke
:param event: String input event passed to Lambda function
:param DebugContext debug_context: Debugging context for the function (includes port, args, and path)
:param io.IOBase stdout: Optional. IO Stream to that receives stdout text from container.
:param io.IOBase stderr: Optional. IO Stream that receives stderr text from container
:raises Keyboard
"""
timer = None
# Update with event input
environ = function_config.env_vars
environ.add_lambda_event_body(event)
# Generate a dictionary of environment variable key:values
env_vars = environ.resolve()
with self._get_code_dir(function_config.code_abs_path) as code_dir:
container = LambdaContainer(function_config.runtime,
function_config.handler,
code_dir,
function_config.layers,
self._image_builder,
memory_mb=function_config.memory,
env_vars=env_vars,
debug_options=debug_context)
try:
# Start the container. This call returns immediately after the container starts
self._container_manager.run(container)
# Setup appropriate interrupt - timeout or Ctrl+C - before function starts executing.
#
# Start the timer **after** container starts. Container startup takes several seconds, only after which,
# our Lambda function code will run. Starting the timer is a reasonable approximation that function has
# started running.
timer = self._configure_interrupt(function_config.name,
function_config.timeout,
container,
bool(debug_context))
# NOTE: BLOCKING METHOD
# Block the thread waiting to fetch logs from the container. This method will return after container
# terminates, either successfully or killed by one of the interrupt handlers above.
container.wait_for_logs(stdout=stdout, stderr=stderr)
except KeyboardInterrupt:
# When user presses Ctrl+C, we receive a Keyboard Interrupt. This is especially very common when
# container is in debugging mode. We have special handling of Ctrl+C. So handle KeyboardInterrupt
# and swallow the exception. The ``finally`` block will also take care of cleaning it up.
LOG.debug("Ctrl+C was pressed. Aborting Lambda execution")
finally:
# We will be done with execution, if either the execution completed or an interrupt was fired
# Any case, cleanup the timer and container.
#
# If we are in debugging mode, timer would not be created. So skip cleanup of the timer
if timer:
timer.cancel()
self._container_manager.stop(container) | python | def invoke(self,
function_config,
event,
debug_context=None,
stdout=None,
stderr=None):
"""
Invoke the given Lambda function locally.
##### NOTE: THIS IS A LONG BLOCKING CALL #####
This method will block until either the Lambda function completes or timed out, which could be seconds.
A blocking call will block the thread preventing any other operations from happening. If you are using this
method in a web-server or in contexts where your application needs to be responsive when function is running,
take care to invoke the function in a separate thread. Co-Routines or micro-threads might not perform well
because the underlying implementation essentially blocks on a socket, which is synchronous.
:param FunctionConfig function_config: Configuration of the function to invoke
:param event: String input event passed to Lambda function
:param DebugContext debug_context: Debugging context for the function (includes port, args, and path)
:param io.IOBase stdout: Optional. IO Stream to that receives stdout text from container.
:param io.IOBase stderr: Optional. IO Stream that receives stderr text from container
:raises Keyboard
"""
timer = None
# Update with event input
environ = function_config.env_vars
environ.add_lambda_event_body(event)
# Generate a dictionary of environment variable key:values
env_vars = environ.resolve()
with self._get_code_dir(function_config.code_abs_path) as code_dir:
container = LambdaContainer(function_config.runtime,
function_config.handler,
code_dir,
function_config.layers,
self._image_builder,
memory_mb=function_config.memory,
env_vars=env_vars,
debug_options=debug_context)
try:
# Start the container. This call returns immediately after the container starts
self._container_manager.run(container)
# Setup appropriate interrupt - timeout or Ctrl+C - before function starts executing.
#
# Start the timer **after** container starts. Container startup takes several seconds, only after which,
# our Lambda function code will run. Starting the timer is a reasonable approximation that function has
# started running.
timer = self._configure_interrupt(function_config.name,
function_config.timeout,
container,
bool(debug_context))
# NOTE: BLOCKING METHOD
# Block the thread waiting to fetch logs from the container. This method will return after container
# terminates, either successfully or killed by one of the interrupt handlers above.
container.wait_for_logs(stdout=stdout, stderr=stderr)
except KeyboardInterrupt:
# When user presses Ctrl+C, we receive a Keyboard Interrupt. This is especially very common when
# container is in debugging mode. We have special handling of Ctrl+C. So handle KeyboardInterrupt
# and swallow the exception. The ``finally`` block will also take care of cleaning it up.
LOG.debug("Ctrl+C was pressed. Aborting Lambda execution")
finally:
# We will be done with execution, if either the execution completed or an interrupt was fired
# Any case, cleanup the timer and container.
#
# If we are in debugging mode, timer would not be created. So skip cleanup of the timer
if timer:
timer.cancel()
self._container_manager.stop(container) | [
"def",
"invoke",
"(",
"self",
",",
"function_config",
",",
"event",
",",
"debug_context",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"timer",
"=",
"None",
"# Update with event input",
"environ",
"=",
"function_config",
".",
"env_vars",
"environ",
".",
"add_lambda_event_body",
"(",
"event",
")",
"# Generate a dictionary of environment variable key:values",
"env_vars",
"=",
"environ",
".",
"resolve",
"(",
")",
"with",
"self",
".",
"_get_code_dir",
"(",
"function_config",
".",
"code_abs_path",
")",
"as",
"code_dir",
":",
"container",
"=",
"LambdaContainer",
"(",
"function_config",
".",
"runtime",
",",
"function_config",
".",
"handler",
",",
"code_dir",
",",
"function_config",
".",
"layers",
",",
"self",
".",
"_image_builder",
",",
"memory_mb",
"=",
"function_config",
".",
"memory",
",",
"env_vars",
"=",
"env_vars",
",",
"debug_options",
"=",
"debug_context",
")",
"try",
":",
"# Start the container. This call returns immediately after the container starts",
"self",
".",
"_container_manager",
".",
"run",
"(",
"container",
")",
"# Setup appropriate interrupt - timeout or Ctrl+C - before function starts executing.",
"#",
"# Start the timer **after** container starts. Container startup takes several seconds, only after which,",
"# our Lambda function code will run. Starting the timer is a reasonable approximation that function has",
"# started running.",
"timer",
"=",
"self",
".",
"_configure_interrupt",
"(",
"function_config",
".",
"name",
",",
"function_config",
".",
"timeout",
",",
"container",
",",
"bool",
"(",
"debug_context",
")",
")",
"# NOTE: BLOCKING METHOD",
"# Block the thread waiting to fetch logs from the container. This method will return after container",
"# terminates, either successfully or killed by one of the interrupt handlers above.",
"container",
".",
"wait_for_logs",
"(",
"stdout",
"=",
"stdout",
",",
"stderr",
"=",
"stderr",
")",
"except",
"KeyboardInterrupt",
":",
"# When user presses Ctrl+C, we receive a Keyboard Interrupt. This is especially very common when",
"# container is in debugging mode. We have special handling of Ctrl+C. So handle KeyboardInterrupt",
"# and swallow the exception. The ``finally`` block will also take care of cleaning it up.",
"LOG",
".",
"debug",
"(",
"\"Ctrl+C was pressed. Aborting Lambda execution\"",
")",
"finally",
":",
"# We will be done with execution, if either the execution completed or an interrupt was fired",
"# Any case, cleanup the timer and container.",
"#",
"# If we are in debugging mode, timer would not be created. So skip cleanup of the timer",
"if",
"timer",
":",
"timer",
".",
"cancel",
"(",
")",
"self",
".",
"_container_manager",
".",
"stop",
"(",
"container",
")"
] | Invoke the given Lambda function locally.
##### NOTE: THIS IS A LONG BLOCKING CALL #####
This method will block until either the Lambda function completes or timed out, which could be seconds.
A blocking call will block the thread preventing any other operations from happening. If you are using this
method in a web-server or in contexts where your application needs to be responsive when function is running,
take care to invoke the function in a separate thread. Co-Routines or micro-threads might not perform well
because the underlying implementation essentially blocks on a socket, which is synchronous.
:param FunctionConfig function_config: Configuration of the function to invoke
:param event: String input event passed to Lambda function
:param DebugContext debug_context: Debugging context for the function (includes port, args, and path)
:param io.IOBase stdout: Optional. IO Stream to that receives stdout text from container.
:param io.IOBase stderr: Optional. IO Stream that receives stderr text from container
:raises Keyboard | [
"Invoke",
"the",
"given",
"Lambda",
"function",
"locally",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/runtime.py#L42-L116 | train |
awslabs/aws-sam-cli | samcli/local/lambdafn/runtime.py | LambdaRuntime._configure_interrupt | def _configure_interrupt(self, function_name, timeout, container, is_debugging):
"""
When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C and terminate the container.
:param string function_name: Name of the function we are running
:param integer timeout: Timeout in seconds
:param samcli.local.docker.container.Container container: Instance of a container to terminate
:param bool is_debugging: Are we debugging?
:return threading.Timer: Timer object, if we setup a timer. None otherwise
"""
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' timed out after %d seconds", function_name, timeout)
self._container_manager.stop(container)
def signal_handler(sig, frame):
# NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures
LOG.info("Execution of function %s was interrupted", function_name)
self._container_manager.stop(container)
if is_debugging:
LOG.debug("Setting up SIGTERM interrupt handler")
signal.signal(signal.SIGTERM, signal_handler)
else:
# Start a timer, we'll use this to abort the function if it runs beyond the specified timeout
LOG.debug("Starting a timer for %s seconds for function '%s'", timeout, function_name)
timer = threading.Timer(timeout, timer_handler, ())
timer.start()
return timer | python | def _configure_interrupt(self, function_name, timeout, container, is_debugging):
"""
When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C and terminate the container.
:param string function_name: Name of the function we are running
:param integer timeout: Timeout in seconds
:param samcli.local.docker.container.Container container: Instance of a container to terminate
:param bool is_debugging: Are we debugging?
:return threading.Timer: Timer object, if we setup a timer. None otherwise
"""
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' timed out after %d seconds", function_name, timeout)
self._container_manager.stop(container)
def signal_handler(sig, frame):
# NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures
LOG.info("Execution of function %s was interrupted", function_name)
self._container_manager.stop(container)
if is_debugging:
LOG.debug("Setting up SIGTERM interrupt handler")
signal.signal(signal.SIGTERM, signal_handler)
else:
# Start a timer, we'll use this to abort the function if it runs beyond the specified timeout
LOG.debug("Starting a timer for %s seconds for function '%s'", timeout, function_name)
timer = threading.Timer(timeout, timer_handler, ())
timer.start()
return timer | [
"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' timed out after %d seconds\"",
",",
"function_name",
",",
"timeout",
")",
"self",
".",
"_container_manager",
".",
"stop",
"(",
"container",
")",
"def",
"signal_handler",
"(",
"sig",
",",
"frame",
")",
":",
"# NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures",
"LOG",
".",
"info",
"(",
"\"Execution of function %s was interrupted\"",
",",
"function_name",
")",
"self",
".",
"_container_manager",
".",
"stop",
"(",
"container",
")",
"if",
"is_debugging",
":",
"LOG",
".",
"debug",
"(",
"\"Setting up SIGTERM interrupt handler\"",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"signal_handler",
")",
"else",
":",
"# Start a timer, we'll use this to abort the function if it runs beyond the specified timeout",
"LOG",
".",
"debug",
"(",
"\"Starting a timer for %s seconds for function '%s'\"",
",",
"timeout",
",",
"function_name",
")",
"timer",
"=",
"threading",
".",
"Timer",
"(",
"timeout",
",",
"timer_handler",
",",
"(",
")",
")",
"timer",
".",
"start",
"(",
")",
"return",
"timer"
] | When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C and terminate the container.
:param string function_name: Name of the function we are running
:param integer timeout: Timeout in seconds
:param samcli.local.docker.container.Container container: Instance of a container to terminate
:param bool is_debugging: Are we debugging?
:return threading.Timer: Timer object, if we setup a timer. None otherwise | [
"When",
"a",
"Lambda",
"function",
"is",
"executing",
"we",
"setup",
"certain",
"interrupt",
"handlers",
"to",
"stop",
"the",
"execution",
".",
"Usually",
"we",
"setup",
"a",
"function",
"timeout",
"interrupt",
"to",
"kill",
"the",
"container",
"after",
"timeout",
"expires",
".",
"If",
"debugging",
"though",
"we",
"don",
"t",
"enforce",
"a",
"timeout",
".",
"But",
"we",
"setup",
"a",
"SIGINT",
"interrupt",
"to",
"catch",
"Ctrl",
"+",
"C",
"and",
"terminate",
"the",
"container",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/runtime.py#L118-L149 | train |
awslabs/aws-sam-cli | samcli/local/lambdafn/runtime.py | LambdaRuntime._get_code_dir | def _get_code_dir(self, code_path):
"""
Method to get a path to a directory where the Lambda function code is available. This directory will
be mounted directly inside the Docker container.
This method handles a few different cases for ``code_path``:
- ``code_path``is a existent zip/jar file: Unzip in a temp directory and return the temp directory
- ``code_path`` is a existent directory: Return this immediately
- ``code_path`` is a file/dir that does not exist: Return it as is. May be this method is not clever to
detect the existence of the path
:param string code_path: Path to the code. This could be pointing at a file or folder either on a local
disk or in some network file system
:return string: Directory containing Lambda function code. It can be mounted directly in container
"""
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 decompressed_dir
else:
LOG.debug("Code %s is not a zip/jar file", code_path)
yield code_path
finally:
if decompressed_dir:
shutil.rmtree(decompressed_dir) | python | def _get_code_dir(self, code_path):
"""
Method to get a path to a directory where the Lambda function code is available. This directory will
be mounted directly inside the Docker container.
This method handles a few different cases for ``code_path``:
- ``code_path``is a existent zip/jar file: Unzip in a temp directory and return the temp directory
- ``code_path`` is a existent directory: Return this immediately
- ``code_path`` is a file/dir that does not exist: Return it as is. May be this method is not clever to
detect the existence of the path
:param string code_path: Path to the code. This could be pointing at a file or folder either on a local
disk or in some network file system
:return string: Directory containing Lambda function code. It can be mounted directly in container
"""
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 decompressed_dir
else:
LOG.debug("Code %s is not a zip/jar file", code_path)
yield code_path
finally:
if decompressed_dir:
shutil.rmtree(decompressed_dir) | [
"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",
"decompressed_dir",
"else",
":",
"LOG",
".",
"debug",
"(",
"\"Code %s is not a zip/jar file\"",
",",
"code_path",
")",
"yield",
"code_path",
"finally",
":",
"if",
"decompressed_dir",
":",
"shutil",
".",
"rmtree",
"(",
"decompressed_dir",
")"
] | Method to get a path to a directory where the Lambda function code is available. This directory will
be mounted directly inside the Docker container.
This method handles a few different cases for ``code_path``:
- ``code_path``is a existent zip/jar file: Unzip in a temp directory and return the temp directory
- ``code_path`` is a existent directory: Return this immediately
- ``code_path`` is a file/dir that does not exist: Return it as is. May be this method is not clever to
detect the existence of the path
:param string code_path: Path to the code. This could be pointing at a file or folder either on a local
disk or in some network file system
:return string: Directory containing Lambda function code. It can be mounted directly in container | [
"Method",
"to",
"get",
"a",
"path",
"to",
"a",
"directory",
"where",
"the",
"Lambda",
"function",
"code",
"is",
"available",
".",
"This",
"directory",
"will",
"be",
"mounted",
"directly",
"inside",
"the",
"Docker",
"container",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/runtime.py#L152-L181 | train |
awslabs/aws-sam-cli | samcli/local/docker/lambda_image.py | LambdaImage.build | def build(self, runtime, layers):
"""
Build the image if one is not already on the system that matches the runtime and layers
Parameters
----------
runtime str
Name of the Lambda runtime
layers list(samcli.commands.local.lib.provider.Layer)
List of layers
Returns
-------
str
The image to be used (REPOSITORY:TAG)
"""
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 defined")
return base_image
downloaded_layers = self.layer_downloader.download_all(layers, self.force_image_build)
docker_image_version = self._generate_docker_image_version(downloaded_layers, runtime)
image_tag = "{}:{}".format(self._SAM_CLI_REPO_NAME, docker_image_version)
image_not_found = False
try:
self.docker_client.images.get(image_tag)
except docker.errors.ImageNotFound:
LOG.info("Image was not found.")
image_not_found = True
if self.force_image_build or \
image_not_found or \
any(layer.is_defined_within_template for layer in downloaded_layers):
LOG.info("Building image...")
self._build_image(base_image, image_tag, downloaded_layers)
return image_tag | python | def build(self, runtime, layers):
"""
Build the image if one is not already on the system that matches the runtime and layers
Parameters
----------
runtime str
Name of the Lambda runtime
layers list(samcli.commands.local.lib.provider.Layer)
List of layers
Returns
-------
str
The image to be used (REPOSITORY:TAG)
"""
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 defined")
return base_image
downloaded_layers = self.layer_downloader.download_all(layers, self.force_image_build)
docker_image_version = self._generate_docker_image_version(downloaded_layers, runtime)
image_tag = "{}:{}".format(self._SAM_CLI_REPO_NAME, docker_image_version)
image_not_found = False
try:
self.docker_client.images.get(image_tag)
except docker.errors.ImageNotFound:
LOG.info("Image was not found.")
image_not_found = True
if self.force_image_build or \
image_not_found or \
any(layer.is_defined_within_template for layer in downloaded_layers):
LOG.info("Building image...")
self._build_image(base_image, image_tag, downloaded_layers)
return image_tag | [
"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 defined\"",
")",
"return",
"base_image",
"downloaded_layers",
"=",
"self",
".",
"layer_downloader",
".",
"download_all",
"(",
"layers",
",",
"self",
".",
"force_image_build",
")",
"docker_image_version",
"=",
"self",
".",
"_generate_docker_image_version",
"(",
"downloaded_layers",
",",
"runtime",
")",
"image_tag",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"self",
".",
"_SAM_CLI_REPO_NAME",
",",
"docker_image_version",
")",
"image_not_found",
"=",
"False",
"try",
":",
"self",
".",
"docker_client",
".",
"images",
".",
"get",
"(",
"image_tag",
")",
"except",
"docker",
".",
"errors",
".",
"ImageNotFound",
":",
"LOG",
".",
"info",
"(",
"\"Image was not found.\"",
")",
"image_not_found",
"=",
"True",
"if",
"self",
".",
"force_image_build",
"or",
"image_not_found",
"or",
"any",
"(",
"layer",
".",
"is_defined_within_template",
"for",
"layer",
"in",
"downloaded_layers",
")",
":",
"LOG",
".",
"info",
"(",
"\"Building image...\"",
")",
"self",
".",
"_build_image",
"(",
"base_image",
",",
"image_tag",
",",
"downloaded_layers",
")",
"return",
"image_tag"
] | Build the image if one is not already on the system that matches the runtime and layers
Parameters
----------
runtime str
Name of the Lambda runtime
layers list(samcli.commands.local.lib.provider.Layer)
List of layers
Returns
-------
str
The image to be used (REPOSITORY:TAG) | [
"Build",
"the",
"image",
"if",
"one",
"is",
"not",
"already",
"on",
"the",
"system",
"that",
"matches",
"the",
"runtime",
"and",
"layers"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_image.py#L73-L115 | train |
awslabs/aws-sam-cli | samcli/local/docker/lambda_image.py | LambdaImage._generate_docker_image_version | def _generate_docker_image_version(layers, runtime):
"""
Generate the Docker TAG that will be used to create the image
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of the layers
runtime str
Runtime of the image to create
Returns
-------
str
String representing the TAG to be attached to the image
"""
# 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
# specified in the template. This will allow reuse of the runtime and layers across different
# functions that are defined. If two functions use the same runtime with the same layers (in the
# same order), SAM CLI will only produce one image and use this image across both functions for invoke.
return runtime + '-' + hashlib.sha256(
"-".join([layer.name for layer in layers]).encode('utf-8')).hexdigest()[0:25] | python | def _generate_docker_image_version(layers, runtime):
"""
Generate the Docker TAG that will be used to create the image
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of the layers
runtime str
Runtime of the image to create
Returns
-------
str
String representing the TAG to be attached to the image
"""
# 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
# specified in the template. This will allow reuse of the runtime and layers across different
# functions that are defined. If two functions use the same runtime with the same layers (in the
# same order), SAM CLI will only produce one image and use this image across both functions for invoke.
return runtime + '-' + hashlib.sha256(
"-".join([layer.name for layer in layers]).encode('utf-8')).hexdigest()[0:25] | [
"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",
"# specified in the template. This will allow reuse of the runtime and layers across different",
"# functions that are defined. If two functions use the same runtime with the same layers (in the",
"# same order), SAM CLI will only produce one image and use this image across both functions for invoke.",
"return",
"runtime",
"+",
"'-'",
"+",
"hashlib",
".",
"sha256",
"(",
"\"-\"",
".",
"join",
"(",
"[",
"layer",
".",
"name",
"for",
"layer",
"in",
"layers",
"]",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
"0",
":",
"25",
"]"
] | Generate the Docker TAG that will be used to create the image
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of the layers
runtime str
Runtime of the image to create
Returns
-------
str
String representing the TAG to be attached to the image | [
"Generate",
"the",
"Docker",
"TAG",
"that",
"will",
"be",
"used",
"to",
"create",
"the",
"image"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_image.py#L118-L142 | train |
awslabs/aws-sam-cli | samcli/local/docker/lambda_image.py | LambdaImage._build_image | def _build_image(self, base_image, docker_tag, layers):
"""
Builds the image
Parameters
----------
base_image str
Base Image to use for the new image
docker_tag
Docker tag (REPOSITORY:TAG) to use when building the image
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers to be use to mount in the image
Returns
-------
None
Raises
------
samcli.commands.local.cli_common.user_exceptions.ImageBuildException
When docker fails to build the image
"""
dockerfile_content = self._generate_dockerfile(base_image, layers)
# Create dockerfile in the same directory of the layer cache
dockerfile_name = "dockerfile_" + str(uuid.uuid4())
full_dockerfile_path = Path(self.layer_downloader.layer_cache, dockerfile_name)
try:
with open(str(full_dockerfile_path), "w") as dockerfile:
dockerfile.write(dockerfile_content)
tar_paths = {str(full_dockerfile_path): "Dockerfile"}
for layer in layers:
tar_paths[layer.codeuri] = '/' + layer.name
with create_tarball(tar_paths) as tarballfile:
try:
self.docker_client.images.build(fileobj=tarballfile,
custom_context=True,
rm=True,
tag=docker_tag,
pull=not self.skip_pull_image)
except (docker.errors.BuildError, docker.errors.APIError):
LOG.exception("Failed to build Docker Image")
raise ImageBuildException("Building Image failed.")
finally:
if full_dockerfile_path.exists():
full_dockerfile_path.unlink() | python | def _build_image(self, base_image, docker_tag, layers):
"""
Builds the image
Parameters
----------
base_image str
Base Image to use for the new image
docker_tag
Docker tag (REPOSITORY:TAG) to use when building the image
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers to be use to mount in the image
Returns
-------
None
Raises
------
samcli.commands.local.cli_common.user_exceptions.ImageBuildException
When docker fails to build the image
"""
dockerfile_content = self._generate_dockerfile(base_image, layers)
# Create dockerfile in the same directory of the layer cache
dockerfile_name = "dockerfile_" + str(uuid.uuid4())
full_dockerfile_path = Path(self.layer_downloader.layer_cache, dockerfile_name)
try:
with open(str(full_dockerfile_path), "w") as dockerfile:
dockerfile.write(dockerfile_content)
tar_paths = {str(full_dockerfile_path): "Dockerfile"}
for layer in layers:
tar_paths[layer.codeuri] = '/' + layer.name
with create_tarball(tar_paths) as tarballfile:
try:
self.docker_client.images.build(fileobj=tarballfile,
custom_context=True,
rm=True,
tag=docker_tag,
pull=not self.skip_pull_image)
except (docker.errors.BuildError, docker.errors.APIError):
LOG.exception("Failed to build Docker Image")
raise ImageBuildException("Building Image failed.")
finally:
if full_dockerfile_path.exists():
full_dockerfile_path.unlink() | [
"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",
"(",
")",
")",
"full_dockerfile_path",
"=",
"Path",
"(",
"self",
".",
"layer_downloader",
".",
"layer_cache",
",",
"dockerfile_name",
")",
"try",
":",
"with",
"open",
"(",
"str",
"(",
"full_dockerfile_path",
")",
",",
"\"w\"",
")",
"as",
"dockerfile",
":",
"dockerfile",
".",
"write",
"(",
"dockerfile_content",
")",
"tar_paths",
"=",
"{",
"str",
"(",
"full_dockerfile_path",
")",
":",
"\"Dockerfile\"",
"}",
"for",
"layer",
"in",
"layers",
":",
"tar_paths",
"[",
"layer",
".",
"codeuri",
"]",
"=",
"'/'",
"+",
"layer",
".",
"name",
"with",
"create_tarball",
"(",
"tar_paths",
")",
"as",
"tarballfile",
":",
"try",
":",
"self",
".",
"docker_client",
".",
"images",
".",
"build",
"(",
"fileobj",
"=",
"tarballfile",
",",
"custom_context",
"=",
"True",
",",
"rm",
"=",
"True",
",",
"tag",
"=",
"docker_tag",
",",
"pull",
"=",
"not",
"self",
".",
"skip_pull_image",
")",
"except",
"(",
"docker",
".",
"errors",
".",
"BuildError",
",",
"docker",
".",
"errors",
".",
"APIError",
")",
":",
"LOG",
".",
"exception",
"(",
"\"Failed to build Docker Image\"",
")",
"raise",
"ImageBuildException",
"(",
"\"Building Image failed.\"",
")",
"finally",
":",
"if",
"full_dockerfile_path",
".",
"exists",
"(",
")",
":",
"full_dockerfile_path",
".",
"unlink",
"(",
")"
] | Builds the image
Parameters
----------
base_image str
Base Image to use for the new image
docker_tag
Docker tag (REPOSITORY:TAG) to use when building the image
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers to be use to mount in the image
Returns
-------
None
Raises
------
samcli.commands.local.cli_common.user_exceptions.ImageBuildException
When docker fails to build the image | [
"Builds",
"the",
"image"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_image.py#L144-L192 | train |
awslabs/aws-sam-cli | samcli/local/docker/lambda_image.py | LambdaImage._generate_dockerfile | def _generate_dockerfile(base_image, layers):
"""
Generate the Dockerfile contents
A generated Dockerfile will look like the following:
```
FROM lambci/lambda:python3.6
ADD --chown=sbx_user1051:495 layer1 /opt
ADD --chown=sbx_user1051:495 layer2 /opt
```
Parameters
----------
base_image str
Base Image to use for the new image
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers to be use to mount in the image
Returns
-------
str
String representing the Dockerfile contents for the image
"""
dockerfile_content = "FROM {}\n".format(base_image)
for layer in layers:
dockerfile_content = dockerfile_content + \
"ADD --chown=sbx_user1051:495 {} {}\n".format(layer.name, LambdaImage._LAYERS_DIR)
return dockerfile_content | python | def _generate_dockerfile(base_image, layers):
"""
Generate the Dockerfile contents
A generated Dockerfile will look like the following:
```
FROM lambci/lambda:python3.6
ADD --chown=sbx_user1051:495 layer1 /opt
ADD --chown=sbx_user1051:495 layer2 /opt
```
Parameters
----------
base_image str
Base Image to use for the new image
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers to be use to mount in the image
Returns
-------
str
String representing the Dockerfile contents for the image
"""
dockerfile_content = "FROM {}\n".format(base_image)
for layer in layers:
dockerfile_content = dockerfile_content + \
"ADD --chown=sbx_user1051:495 {} {}\n".format(layer.name, LambdaImage._LAYERS_DIR)
return dockerfile_content | [
"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\"",
".",
"format",
"(",
"layer",
".",
"name",
",",
"LambdaImage",
".",
"_LAYERS_DIR",
")",
"return",
"dockerfile_content"
] | Generate the Dockerfile contents
A generated Dockerfile will look like the following:
```
FROM lambci/lambda:python3.6
ADD --chown=sbx_user1051:495 layer1 /opt
ADD --chown=sbx_user1051:495 layer2 /opt
```
Parameters
----------
base_image str
Base Image to use for the new image
layers list(samcli.commands.local.lib.provider.Layer)
List of Layers to be use to mount in the image
Returns
-------
str
String representing the Dockerfile contents for the image | [
"Generate",
"the",
"Dockerfile",
"contents"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_image.py#L195-L225 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/local_api_service.py | LocalApiService.start | def start(self):
"""
Creates and starts the local API Gateway service. This method will block until the service is stopped
manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint
to invoke the Lambda function and receive a response.
NOTE: This is a blocking call that will not return until the thread is interrupted with SIGINT/SIGTERM
"""
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)
# We care about passing only stderr to the Service and not stdout because stdout from Docker container
# contains the response to the API which is sent out as HTTP response. Only stderr needs to be printed
# to the console or a log file. stderr from Docker container contains runtime logs and output of print
# statements from the Lambda function
service = LocalApigwService(routing_list=routing_list,
lambda_runner=self.lambda_runner,
static_dir=static_dir_path,
port=self.port,
host=self.host,
stderr=self.stderr_stream)
service.create()
# Print out the list of routes that will be mounted
self._print_routes(self.api_provider, self.host, self.port)
LOG.info("You can now browse to the above endpoints to invoke your functions. "
"You do not need to restart/reload SAM CLI while working on your functions, "
"changes will be reflected instantly/automatically. You only need to restart "
"SAM CLI if you update your AWS SAM template")
service.run() | python | def start(self):
"""
Creates and starts the local API Gateway service. This method will block until the service is stopped
manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint
to invoke the Lambda function and receive a response.
NOTE: This is a blocking call that will not return until the thread is interrupted with SIGINT/SIGTERM
"""
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)
# We care about passing only stderr to the Service and not stdout because stdout from Docker container
# contains the response to the API which is sent out as HTTP response. Only stderr needs to be printed
# to the console or a log file. stderr from Docker container contains runtime logs and output of print
# statements from the Lambda function
service = LocalApigwService(routing_list=routing_list,
lambda_runner=self.lambda_runner,
static_dir=static_dir_path,
port=self.port,
host=self.host,
stderr=self.stderr_stream)
service.create()
# Print out the list of routes that will be mounted
self._print_routes(self.api_provider, self.host, self.port)
LOG.info("You can now browse to the above endpoints to invoke your functions. "
"You do not need to restart/reload SAM CLI while working on your functions, "
"changes will be reflected instantly/automatically. You only need to restart "
"SAM CLI if you update your AWS SAM template")
service.run() | [
"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",
")",
"# We care about passing only stderr to the Service and not stdout because stdout from Docker container",
"# contains the response to the API which is sent out as HTTP response. Only stderr needs to be printed",
"# to the console or a log file. stderr from Docker container contains runtime logs and output of print",
"# statements from the Lambda function",
"service",
"=",
"LocalApigwService",
"(",
"routing_list",
"=",
"routing_list",
",",
"lambda_runner",
"=",
"self",
".",
"lambda_runner",
",",
"static_dir",
"=",
"static_dir_path",
",",
"port",
"=",
"self",
".",
"port",
",",
"host",
"=",
"self",
".",
"host",
",",
"stderr",
"=",
"self",
".",
"stderr_stream",
")",
"service",
".",
"create",
"(",
")",
"# Print out the list of routes that will be mounted",
"self",
".",
"_print_routes",
"(",
"self",
".",
"api_provider",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"LOG",
".",
"info",
"(",
"\"You can now browse to the above endpoints to invoke your functions. \"",
"\"You do not need to restart/reload SAM CLI while working on your functions, \"",
"\"changes will be reflected instantly/automatically. You only need to restart \"",
"\"SAM CLI if you update your AWS SAM template\"",
")",
"service",
".",
"run",
"(",
")"
] | Creates and starts the local API Gateway service. This method will block until the service is stopped
manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint
to invoke the Lambda function and receive a response.
NOTE: This is a blocking call that will not return until the thread is interrupted with SIGINT/SIGTERM | [
"Creates",
"and",
"starts",
"the",
"local",
"API",
"Gateway",
"service",
".",
"This",
"method",
"will",
"block",
"until",
"the",
"service",
"is",
"stopped",
"manually",
"using",
"an",
"interrupt",
".",
"After",
"the",
"service",
"is",
"started",
"callers",
"can",
"make",
"HTTP",
"requests",
"to",
"the",
"endpoint",
"to",
"invoke",
"the",
"Lambda",
"function",
"and",
"receive",
"a",
"response",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_api_service.py#L47-L83 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/local_api_service.py | LocalApiService._make_routing_list | def _make_routing_list(api_provider):
"""
Returns a list of routes to configure the Local API Service based on the APIs configured in the template.
Parameters
----------
api_provider : samcli.commands.local.lib.sam_api_provider.SamApiProvider
Returns
-------
list(samcli.local.apigw.service.Route)
List of Routes to pass to the service
"""
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)
routes.append(route)
return routes | python | def _make_routing_list(api_provider):
"""
Returns a list of routes to configure the Local API Service based on the APIs configured in the template.
Parameters
----------
api_provider : samcli.commands.local.lib.sam_api_provider.SamApiProvider
Returns
-------
list(samcli.local.apigw.service.Route)
List of Routes to pass to the service
"""
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)
routes.append(route)
return routes | [
"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",
")",
"routes",
".",
"append",
"(",
"route",
")",
"return",
"routes"
] | Returns a list of routes to configure the Local API Service based on the APIs configured in the template.
Parameters
----------
api_provider : samcli.commands.local.lib.sam_api_provider.SamApiProvider
Returns
-------
list(samcli.local.apigw.service.Route)
List of Routes to pass to the service | [
"Returns",
"a",
"list",
"of",
"routes",
"to",
"configure",
"the",
"Local",
"API",
"Service",
"based",
"on",
"the",
"APIs",
"configured",
"in",
"the",
"template",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_api_service.py#L86-L106 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/local_api_service.py | LocalApiService._print_routes | def _print_routes(api_provider, host, port):
"""
Helper method to print the APIs that will be mounted. This method is purely for printing purposes.
This method takes in a list of Route Configurations and prints out the Routes grouped by path.
Grouping routes by Function Name + Path is the bulk of the logic.
Example output:
Mounting Product at http://127.0.0.1:3000/path1/bar [GET, POST, DELETE]
Mounting Product at http://127.0.0.1:3000/path2/bar [HEAD]
:param samcli.commands.local.lib.provider.ApiProvider api_provider: API Provider that can return a list of APIs
:param string host: Host name where the service is running
:param int port: Port number where the service is running
:returns list(string): List of lines that were printed to the console. Helps with testing
"""
grouped_api_configs = {}
for api in api_provider.get_all():
key = "{}-{}".format(api.function_name, api.path)
config = grouped_api_configs.get(key, {})
config.setdefault("methods", [])
config["function_name"] = api.function_name
config["path"] = api.path
config["methods"].append(api.method)
grouped_api_configs[key] = config
print_lines = []
for _, config in grouped_api_configs.items():
methods_str = "[{}]".format(', '.join(config["methods"]))
output = "Mounting {} at http://{}:{}{} {}".format(
config["function_name"],
host,
port,
config["path"],
methods_str)
print_lines.append(output)
LOG.info(output)
return print_lines | python | def _print_routes(api_provider, host, port):
"""
Helper method to print the APIs that will be mounted. This method is purely for printing purposes.
This method takes in a list of Route Configurations and prints out the Routes grouped by path.
Grouping routes by Function Name + Path is the bulk of the logic.
Example output:
Mounting Product at http://127.0.0.1:3000/path1/bar [GET, POST, DELETE]
Mounting Product at http://127.0.0.1:3000/path2/bar [HEAD]
:param samcli.commands.local.lib.provider.ApiProvider api_provider: API Provider that can return a list of APIs
:param string host: Host name where the service is running
:param int port: Port number where the service is running
:returns list(string): List of lines that were printed to the console. Helps with testing
"""
grouped_api_configs = {}
for api in api_provider.get_all():
key = "{}-{}".format(api.function_name, api.path)
config = grouped_api_configs.get(key, {})
config.setdefault("methods", [])
config["function_name"] = api.function_name
config["path"] = api.path
config["methods"].append(api.method)
grouped_api_configs[key] = config
print_lines = []
for _, config in grouped_api_configs.items():
methods_str = "[{}]".format(', '.join(config["methods"]))
output = "Mounting {} at http://{}:{}{} {}".format(
config["function_name"],
host,
port,
config["path"],
methods_str)
print_lines.append(output)
LOG.info(output)
return print_lines | [
"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",
".",
"setdefault",
"(",
"\"methods\"",
",",
"[",
"]",
")",
"config",
"[",
"\"function_name\"",
"]",
"=",
"api",
".",
"function_name",
"config",
"[",
"\"path\"",
"]",
"=",
"api",
".",
"path",
"config",
"[",
"\"methods\"",
"]",
".",
"append",
"(",
"api",
".",
"method",
")",
"grouped_api_configs",
"[",
"key",
"]",
"=",
"config",
"print_lines",
"=",
"[",
"]",
"for",
"_",
",",
"config",
"in",
"grouped_api_configs",
".",
"items",
"(",
")",
":",
"methods_str",
"=",
"\"[{}]\"",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"config",
"[",
"\"methods\"",
"]",
")",
")",
"output",
"=",
"\"Mounting {} at http://{}:{}{} {}\"",
".",
"format",
"(",
"config",
"[",
"\"function_name\"",
"]",
",",
"host",
",",
"port",
",",
"config",
"[",
"\"path\"",
"]",
",",
"methods_str",
")",
"print_lines",
".",
"append",
"(",
"output",
")",
"LOG",
".",
"info",
"(",
"output",
")",
"return",
"print_lines"
] | Helper method to print the APIs that will be mounted. This method is purely for printing purposes.
This method takes in a list of Route Configurations and prints out the Routes grouped by path.
Grouping routes by Function Name + Path is the bulk of the logic.
Example output:
Mounting Product at http://127.0.0.1:3000/path1/bar [GET, POST, DELETE]
Mounting Product at http://127.0.0.1:3000/path2/bar [HEAD]
:param samcli.commands.local.lib.provider.ApiProvider api_provider: API Provider that can return a list of APIs
:param string host: Host name where the service is running
:param int port: Port number where the service is running
:returns list(string): List of lines that were printed to the console. Helps with testing | [
"Helper",
"method",
"to",
"print",
"the",
"APIs",
"that",
"will",
"be",
"mounted",
".",
"This",
"method",
"is",
"purely",
"for",
"printing",
"purposes",
".",
"This",
"method",
"takes",
"in",
"a",
"list",
"of",
"Route",
"Configurations",
"and",
"prints",
"out",
"the",
"Routes",
"grouped",
"by",
"path",
".",
"Grouping",
"routes",
"by",
"Function",
"Name",
"+",
"Path",
"is",
"the",
"bulk",
"of",
"the",
"logic",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_api_service.py#L109-L151 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/local_api_service.py | LocalApiService._make_static_dir_path | def _make_static_dir_path(cwd, static_dir):
"""
This method returns the path to the directory where static files are to be served from. If static_dir is a
relative path, then it is resolved to be relative to the current working directory. If no static directory is
provided, or if the resolved directory does not exist, this method will return None
:param string cwd: Current working directory relative to which we will resolve the static directory
:param string static_dir: Path to the static directory
:return string: Path to the static directory, if it exists. None, otherwise
"""
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_path)
return static_dir_path | python | def _make_static_dir_path(cwd, static_dir):
"""
This method returns the path to the directory where static files are to be served from. If static_dir is a
relative path, then it is resolved to be relative to the current working directory. If no static directory is
provided, or if the resolved directory does not exist, this method will return None
:param string cwd: Current working directory relative to which we will resolve the static directory
:param string static_dir: Path to the static directory
:return string: Path to the static directory, if it exists. None, otherwise
"""
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_path)
return static_dir_path | [
"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_path",
")",
"return",
"static_dir_path"
] | This method returns the path to the directory where static files are to be served from. If static_dir is a
relative path, then it is resolved to be relative to the current working directory. If no static directory is
provided, or if the resolved directory does not exist, this method will return None
:param string cwd: Current working directory relative to which we will resolve the static directory
:param string static_dir: Path to the static directory
:return string: Path to the static directory, if it exists. None, otherwise | [
"This",
"method",
"returns",
"the",
"path",
"to",
"the",
"directory",
"where",
"static",
"files",
"are",
"to",
"be",
"served",
"from",
".",
"If",
"static_dir",
"is",
"a",
"relative",
"path",
"then",
"it",
"is",
"resolved",
"to",
"be",
"relative",
"to",
"the",
"current",
"working",
"directory",
".",
"If",
"no",
"static",
"directory",
"is",
"provided",
"or",
"if",
"the",
"resolved",
"directory",
"does",
"not",
"exist",
"this",
"method",
"will",
"return",
"None"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_api_service.py#L154-L170 | train |
awslabs/aws-sam-cli | samcli/local/lambda_service/local_lambda_invoke_service.py | LocalLambdaInvokeService.create | def create(self):
"""
Creates a Flask Application that can be started.
"""
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_handler,
methods=['POST'],
provide_automatic_options=False)
# setup request validation before Flask calls the view_func
self._app.before_request(LocalLambdaInvokeService.validate_request)
self._construct_error_handling() | python | def create(self):
"""
Creates a Flask Application that can be started.
"""
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_handler,
methods=['POST'],
provide_automatic_options=False)
# setup request validation before Flask calls the view_func
self._app.before_request(LocalLambdaInvokeService.validate_request)
self._construct_error_handling() | [
"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_handler",
",",
"methods",
"=",
"[",
"'POST'",
"]",
",",
"provide_automatic_options",
"=",
"False",
")",
"# setup request validation before Flask calls the view_func",
"self",
".",
"_app",
".",
"before_request",
"(",
"LocalLambdaInvokeService",
".",
"validate_request",
")",
"self",
".",
"_construct_error_handling",
"(",
")"
] | Creates a Flask Application that can be started. | [
"Creates",
"a",
"Flask",
"Application",
"that",
"can",
"be",
"started",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambda_service/local_lambda_invoke_service.py#L38-L54 | train |
awslabs/aws-sam-cli | samcli/local/lambda_service/local_lambda_invoke_service.py | LocalLambdaInvokeService.validate_request | def validate_request():
"""
Validates the incoming request
The following are invalid
1. The Request data is not json serializable
2. Query Parameters are sent to the endpoint
3. The Request Content-Type is not application/json
4. 'X-Amz-Log-Type' header is not 'None'
5. 'X-Amz-Invocation-Type' header is not 'RequestResponse'
Returns
-------
flask.Response
If the request is not valid a flask Response is returned
None:
If the request passes all validation
"""
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_data)
except ValueError as json_error:
LOG.debug("Request body was not json. Exception: %s", str(json_error))
return LambdaErrorResponses.invalid_request_content(
"Could not parse request body into json: No JSON object could be decoded")
if flask_request.args:
LOG.debug("Query parameters are in the request but not supported")
return LambdaErrorResponses.invalid_request_content("Query Parameters are not supported")
request_headers = CaseInsensitiveDict(flask_request.headers)
log_type = request_headers.get('X-Amz-Log-Type', 'None')
if log_type != 'None':
LOG.debug("log-type: %s is not supported. None is only supported.", log_type)
return LambdaErrorResponses.not_implemented_locally(
"log-type: {} is not supported. None is only supported.".format(log_type))
invocation_type = request_headers.get('X-Amz-Invocation-Type', 'RequestResponse')
if invocation_type != 'RequestResponse':
LOG.warning("invocation-type: %s is not supported. RequestResponse is only supported.", invocation_type)
return LambdaErrorResponses.not_implemented_locally(
"invocation-type: {} is not supported. RequestResponse is only supported.".format(invocation_type)) | python | def validate_request():
"""
Validates the incoming request
The following are invalid
1. The Request data is not json serializable
2. Query Parameters are sent to the endpoint
3. The Request Content-Type is not application/json
4. 'X-Amz-Log-Type' header is not 'None'
5. 'X-Amz-Invocation-Type' header is not 'RequestResponse'
Returns
-------
flask.Response
If the request is not valid a flask Response is returned
None:
If the request passes all validation
"""
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_data)
except ValueError as json_error:
LOG.debug("Request body was not json. Exception: %s", str(json_error))
return LambdaErrorResponses.invalid_request_content(
"Could not parse request body into json: No JSON object could be decoded")
if flask_request.args:
LOG.debug("Query parameters are in the request but not supported")
return LambdaErrorResponses.invalid_request_content("Query Parameters are not supported")
request_headers = CaseInsensitiveDict(flask_request.headers)
log_type = request_headers.get('X-Amz-Log-Type', 'None')
if log_type != 'None':
LOG.debug("log-type: %s is not supported. None is only supported.", log_type)
return LambdaErrorResponses.not_implemented_locally(
"log-type: {} is not supported. None is only supported.".format(log_type))
invocation_type = request_headers.get('X-Amz-Invocation-Type', 'RequestResponse')
if invocation_type != 'RequestResponse':
LOG.warning("invocation-type: %s is not supported. RequestResponse is only supported.", invocation_type)
return LambdaErrorResponses.not_implemented_locally(
"invocation-type: {} is not supported. RequestResponse is only supported.".format(invocation_type)) | [
"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_data",
")",
"except",
"ValueError",
"as",
"json_error",
":",
"LOG",
".",
"debug",
"(",
"\"Request body was not json. Exception: %s\"",
",",
"str",
"(",
"json_error",
")",
")",
"return",
"LambdaErrorResponses",
".",
"invalid_request_content",
"(",
"\"Could not parse request body into json: No JSON object could be decoded\"",
")",
"if",
"flask_request",
".",
"args",
":",
"LOG",
".",
"debug",
"(",
"\"Query parameters are in the request but not supported\"",
")",
"return",
"LambdaErrorResponses",
".",
"invalid_request_content",
"(",
"\"Query Parameters are not supported\"",
")",
"request_headers",
"=",
"CaseInsensitiveDict",
"(",
"flask_request",
".",
"headers",
")",
"log_type",
"=",
"request_headers",
".",
"get",
"(",
"'X-Amz-Log-Type'",
",",
"'None'",
")",
"if",
"log_type",
"!=",
"'None'",
":",
"LOG",
".",
"debug",
"(",
"\"log-type: %s is not supported. None is only supported.\"",
",",
"log_type",
")",
"return",
"LambdaErrorResponses",
".",
"not_implemented_locally",
"(",
"\"log-type: {} is not supported. None is only supported.\"",
".",
"format",
"(",
"log_type",
")",
")",
"invocation_type",
"=",
"request_headers",
".",
"get",
"(",
"'X-Amz-Invocation-Type'",
",",
"'RequestResponse'",
")",
"if",
"invocation_type",
"!=",
"'RequestResponse'",
":",
"LOG",
".",
"warning",
"(",
"\"invocation-type: %s is not supported. RequestResponse is only supported.\"",
",",
"invocation_type",
")",
"return",
"LambdaErrorResponses",
".",
"not_implemented_locally",
"(",
"\"invocation-type: {} is not supported. RequestResponse is only supported.\"",
".",
"format",
"(",
"invocation_type",
")",
")"
] | Validates the incoming request
The following are invalid
1. The Request data is not json serializable
2. Query Parameters are sent to the endpoint
3. The Request Content-Type is not application/json
4. 'X-Amz-Log-Type' header is not 'None'
5. 'X-Amz-Invocation-Type' header is not 'RequestResponse'
Returns
-------
flask.Response
If the request is not valid a flask Response is returned
None:
If the request passes all validation | [
"Validates",
"the",
"incoming",
"request"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambda_service/local_lambda_invoke_service.py#L57-L107 | train |
awslabs/aws-sam-cli | samcli/local/lambda_service/local_lambda_invoke_service.py | LocalLambdaInvokeService._construct_error_handling | def _construct_error_handling(self):
"""
Updates the Flask app with Error Handlers for different Error Codes
"""
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, LambdaErrorResponses.generic_method_not_allowed) | python | def _construct_error_handling(self):
"""
Updates the Flask app with Error Handlers for different Error Codes
"""
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, LambdaErrorResponses.generic_method_not_allowed) | [
"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",
",",
"LambdaErrorResponses",
".",
"generic_method_not_allowed",
")"
] | Updates the Flask app with Error Handlers for different Error Codes | [
"Updates",
"the",
"Flask",
"app",
"with",
"Error",
"Handlers",
"for",
"different",
"Error",
"Codes"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambda_service/local_lambda_invoke_service.py#L109-L116 | train |
awslabs/aws-sam-cli | samcli/local/lambda_service/local_lambda_invoke_service.py | LocalLambdaInvokeService._invoke_request_handler | def _invoke_request_handler(self, function_name):
"""
Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming
request and invoking the Local Lambda Function
Parameters
----------
function_name str
Name of the function to invoke
Returns
-------
A Flask Response response object as if it was returned from Lambda
"""
flask_request = request
request_data = flask_request.get_data()
if not request_data:
request_data = b'{}'
request_data = request_data.decode('utf-8')
stdout_stream = io.BytesIO()
stdout_stream_writer = StreamWriter(stdout_stream, self.is_debugging)
try:
self.lambda_runner.invoke(function_name, request_data, stdout=stdout_stream_writer, stderr=self.stderr)
except FunctionNotFound:
LOG.debug('%s was not found to invoke.', function_name)
return LambdaErrorResponses.resource_not_found(function_name)
lambda_response, lambda_logs, is_lambda_user_error_response = \
LambdaOutputParser.get_lambda_output(stdout_stream)
if self.stderr and lambda_logs:
# Write the logs to stderr if available.
self.stderr.write(lambda_logs)
if is_lambda_user_error_response:
return self.service_response(lambda_response,
{'Content-Type': 'application/json', 'x-amz-function-error': 'Unhandled'},
200)
return self.service_response(lambda_response, {'Content-Type': 'application/json'}, 200) | python | def _invoke_request_handler(self, function_name):
"""
Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming
request and invoking the Local Lambda Function
Parameters
----------
function_name str
Name of the function to invoke
Returns
-------
A Flask Response response object as if it was returned from Lambda
"""
flask_request = request
request_data = flask_request.get_data()
if not request_data:
request_data = b'{}'
request_data = request_data.decode('utf-8')
stdout_stream = io.BytesIO()
stdout_stream_writer = StreamWriter(stdout_stream, self.is_debugging)
try:
self.lambda_runner.invoke(function_name, request_data, stdout=stdout_stream_writer, stderr=self.stderr)
except FunctionNotFound:
LOG.debug('%s was not found to invoke.', function_name)
return LambdaErrorResponses.resource_not_found(function_name)
lambda_response, lambda_logs, is_lambda_user_error_response = \
LambdaOutputParser.get_lambda_output(stdout_stream)
if self.stderr and lambda_logs:
# Write the logs to stderr if available.
self.stderr.write(lambda_logs)
if is_lambda_user_error_response:
return self.service_response(lambda_response,
{'Content-Type': 'application/json', 'x-amz-function-error': 'Unhandled'},
200)
return self.service_response(lambda_response, {'Content-Type': 'application/json'}, 200) | [
"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_stream",
"=",
"io",
".",
"BytesIO",
"(",
")",
"stdout_stream_writer",
"=",
"StreamWriter",
"(",
"stdout_stream",
",",
"self",
".",
"is_debugging",
")",
"try",
":",
"self",
".",
"lambda_runner",
".",
"invoke",
"(",
"function_name",
",",
"request_data",
",",
"stdout",
"=",
"stdout_stream_writer",
",",
"stderr",
"=",
"self",
".",
"stderr",
")",
"except",
"FunctionNotFound",
":",
"LOG",
".",
"debug",
"(",
"'%s was not found to invoke.'",
",",
"function_name",
")",
"return",
"LambdaErrorResponses",
".",
"resource_not_found",
"(",
"function_name",
")",
"lambda_response",
",",
"lambda_logs",
",",
"is_lambda_user_error_response",
"=",
"LambdaOutputParser",
".",
"get_lambda_output",
"(",
"stdout_stream",
")",
"if",
"self",
".",
"stderr",
"and",
"lambda_logs",
":",
"# Write the logs to stderr if available.",
"self",
".",
"stderr",
".",
"write",
"(",
"lambda_logs",
")",
"if",
"is_lambda_user_error_response",
":",
"return",
"self",
".",
"service_response",
"(",
"lambda_response",
",",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'x-amz-function-error'",
":",
"'Unhandled'",
"}",
",",
"200",
")",
"return",
"self",
".",
"service_response",
"(",
"lambda_response",
",",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
",",
"200",
")"
] | Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming
request and invoking the Local Lambda Function
Parameters
----------
function_name str
Name of the function to invoke
Returns
-------
A Flask Response response object as if it was returned from Lambda | [
"Request",
"Handler",
"for",
"the",
"Local",
"Lambda",
"Invoke",
"path",
".",
"This",
"method",
"is",
"responsible",
"for",
"understanding",
"the",
"incoming",
"request",
"and",
"invoking",
"the",
"Local",
"Lambda",
"Function"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambda_service/local_lambda_invoke_service.py#L118-L162 | train |
awslabs/aws-sam-cli | samcli/local/lambdafn/zip.py | unzip | def unzip(zip_file_path, output_dir, permission=None):
"""
Unzip the given file into the given directory while preserving file permissions in the process.
Parameters
----------
zip_file_path : str
Path to the zip file
output_dir : str
Path to the directory where the it should be unzipped to
permission : octal int
Permission to set
"""
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 = file_info.filename
extracted_path = os.path.join(output_dir, name)
zip_ref.extract(name, output_dir)
_set_permissions(file_info, extracted_path)
_override_permissions(extracted_path, permission)
_override_permissions(output_dir, permission) | python | def unzip(zip_file_path, output_dir, permission=None):
"""
Unzip the given file into the given directory while preserving file permissions in the process.
Parameters
----------
zip_file_path : str
Path to the zip file
output_dir : str
Path to the directory where the it should be unzipped to
permission : octal int
Permission to set
"""
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 = file_info.filename
extracted_path = os.path.join(output_dir, name)
zip_ref.extract(name, output_dir)
_set_permissions(file_info, extracted_path)
_override_permissions(extracted_path, permission)
_override_permissions(output_dir, permission) | [
"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",
"=",
"file_info",
".",
"filename",
"extracted_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"name",
")",
"zip_ref",
".",
"extract",
"(",
"name",
",",
"output_dir",
")",
"_set_permissions",
"(",
"file_info",
",",
"extracted_path",
")",
"_override_permissions",
"(",
"extracted_path",
",",
"permission",
")",
"_override_permissions",
"(",
"output_dir",
",",
"permission",
")"
] | Unzip the given file into the given directory while preserving file permissions in the process.
Parameters
----------
zip_file_path : str
Path to the zip file
output_dir : str
Path to the directory where the it should be unzipped to
permission : octal int
Permission to set | [
"Unzip",
"the",
"given",
"file",
"into",
"the",
"given",
"directory",
"while",
"preserving",
"file",
"permissions",
"in",
"the",
"process",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/zip.py#L23-L51 | train |
awslabs/aws-sam-cli | samcli/local/lambdafn/zip.py | _set_permissions | def _set_permissions(zip_file_info, extracted_path):
"""
Sets permissions on the extracted file by reading the ``external_attr`` property of given file info.
Parameters
----------
zip_file_info : zipfile.ZipInfo
Object containing information about a file within a zip archive
extracted_path : str
Path where the file has been extracted to
"""
# 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 permission information on them.
# Skip setting a permission on these files.
LOG.debug("File %s in zipfile does not have permission information", zip_file_info.filename)
return
os.chmod(extracted_path, permission) | python | def _set_permissions(zip_file_info, extracted_path):
"""
Sets permissions on the extracted file by reading the ``external_attr`` property of given file info.
Parameters
----------
zip_file_info : zipfile.ZipInfo
Object containing information about a file within a zip archive
extracted_path : str
Path where the file has been extracted to
"""
# 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 permission information on them.
# Skip setting a permission on these files.
LOG.debug("File %s in zipfile does not have permission information", zip_file_info.filename)
return
os.chmod(extracted_path, permission) | [
"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 permission information on them.",
"# Skip setting a permission on these files.",
"LOG",
".",
"debug",
"(",
"\"File %s in zipfile does not have permission information\"",
",",
"zip_file_info",
".",
"filename",
")",
"return",
"os",
".",
"chmod",
"(",
"extracted_path",
",",
"permission",
")"
] | Sets permissions on the extracted file by reading the ``external_attr`` property of given file info.
Parameters
----------
zip_file_info : zipfile.ZipInfo
Object containing information about a file within a zip archive
extracted_path : str
Path where the file has been extracted to | [
"Sets",
"permissions",
"on",
"the",
"extracted",
"file",
"by",
"reading",
"the",
"external_attr",
"property",
"of",
"given",
"file",
"info",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/zip.py#L70-L91 | train |
awslabs/aws-sam-cli | samcli/local/lambdafn/zip.py | unzip_from_uri | def unzip_from_uri(uri, layer_zip_path, unzip_output_dir, progressbar_label):
"""
Download the LayerVersion Zip to the Layer Pkg Cache
Parameters
----------
uri str
Uri to download from
layer_zip_path str
Path to where the content from the uri should be downloaded to
unzip_output_dir str
Path to unzip the zip to
progressbar_label str
Label to use in the Progressbar
"""
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_length = int(get_request.headers['Content-length'])
with progressbar(file_length, progressbar_label) as p_bar:
# Set the chunk size to None. Since we are streaming the request, None will allow the data to be
# read as it arrives in whatever size the chunks are received.
for data in get_request.iter_content(chunk_size=None):
local_layer_file.write(data)
p_bar.update(len(data))
# Forcefully set the permissions to 700 on files and directories. This is to ensure the owner
# of the files is the only one that can read, write, or execute the files.
unzip(layer_zip_path, unzip_output_dir, permission=0o700)
finally:
# Remove the downloaded zip file
path_to_layer = Path(layer_zip_path)
if path_to_layer.exists():
path_to_layer.unlink() | python | def unzip_from_uri(uri, layer_zip_path, unzip_output_dir, progressbar_label):
"""
Download the LayerVersion Zip to the Layer Pkg Cache
Parameters
----------
uri str
Uri to download from
layer_zip_path str
Path to where the content from the uri should be downloaded to
unzip_output_dir str
Path to unzip the zip to
progressbar_label str
Label to use in the Progressbar
"""
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_length = int(get_request.headers['Content-length'])
with progressbar(file_length, progressbar_label) as p_bar:
# Set the chunk size to None. Since we are streaming the request, None will allow the data to be
# read as it arrives in whatever size the chunks are received.
for data in get_request.iter_content(chunk_size=None):
local_layer_file.write(data)
p_bar.update(len(data))
# Forcefully set the permissions to 700 on files and directories. This is to ensure the owner
# of the files is the only one that can read, write, or execute the files.
unzip(layer_zip_path, unzip_output_dir, permission=0o700)
finally:
# Remove the downloaded zip file
path_to_layer = Path(layer_zip_path)
if path_to_layer.exists():
path_to_layer.unlink() | [
"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_length",
"=",
"int",
"(",
"get_request",
".",
"headers",
"[",
"'Content-length'",
"]",
")",
"with",
"progressbar",
"(",
"file_length",
",",
"progressbar_label",
")",
"as",
"p_bar",
":",
"# Set the chunk size to None. Since we are streaming the request, None will allow the data to be",
"# read as it arrives in whatever size the chunks are received.",
"for",
"data",
"in",
"get_request",
".",
"iter_content",
"(",
"chunk_size",
"=",
"None",
")",
":",
"local_layer_file",
".",
"write",
"(",
"data",
")",
"p_bar",
".",
"update",
"(",
"len",
"(",
"data",
")",
")",
"# Forcefully set the permissions to 700 on files and directories. This is to ensure the owner",
"# of the files is the only one that can read, write, or execute the files.",
"unzip",
"(",
"layer_zip_path",
",",
"unzip_output_dir",
",",
"permission",
"=",
"0o700",
")",
"finally",
":",
"# Remove the downloaded zip file",
"path_to_layer",
"=",
"Path",
"(",
"layer_zip_path",
")",
"if",
"path_to_layer",
".",
"exists",
"(",
")",
":",
"path_to_layer",
".",
"unlink",
"(",
")"
] | Download the LayerVersion Zip to the Layer Pkg Cache
Parameters
----------
uri str
Uri to download from
layer_zip_path str
Path to where the content from the uri should be downloaded to
unzip_output_dir str
Path to unzip the zip to
progressbar_label str
Label to use in the Progressbar | [
"Download",
"the",
"LayerVersion",
"Zip",
"to",
"the",
"Layer",
"Pkg",
"Cache"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/zip.py#L94-L130 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService.create | def create(self):
"""
Creates a Flask Application that can be started.
"""
self._app = Flask(__name__,
static_url_path="", # Mount static files at root '/'
static_folder=self.static_dir # Serve static files from this directory
)
for api_gateway_route in self.routing_list:
path = PathConverter.convert_path_to_flask(api_gateway_route.path)
for route_key in self._generate_route_keys(api_gateway_route.methods,
path):
self._dict_of_routes[route_key] = api_gateway_route
self._app.add_url_rule(path,
endpoint=path,
view_func=self._request_handler,
methods=api_gateway_route.methods,
provide_automatic_options=False)
self._construct_error_handling() | python | def create(self):
"""
Creates a Flask Application that can be started.
"""
self._app = Flask(__name__,
static_url_path="", # Mount static files at root '/'
static_folder=self.static_dir # Serve static files from this directory
)
for api_gateway_route in self.routing_list:
path = PathConverter.convert_path_to_flask(api_gateway_route.path)
for route_key in self._generate_route_keys(api_gateway_route.methods,
path):
self._dict_of_routes[route_key] = api_gateway_route
self._app.add_url_rule(path,
endpoint=path,
view_func=self._request_handler,
methods=api_gateway_route.methods,
provide_automatic_options=False)
self._construct_error_handling() | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"_app",
"=",
"Flask",
"(",
"__name__",
",",
"static_url_path",
"=",
"\"\"",
",",
"# Mount static files at root '/'",
"static_folder",
"=",
"self",
".",
"static_dir",
"# Serve static files from this directory",
")",
"for",
"api_gateway_route",
"in",
"self",
".",
"routing_list",
":",
"path",
"=",
"PathConverter",
".",
"convert_path_to_flask",
"(",
"api_gateway_route",
".",
"path",
")",
"for",
"route_key",
"in",
"self",
".",
"_generate_route_keys",
"(",
"api_gateway_route",
".",
"methods",
",",
"path",
")",
":",
"self",
".",
"_dict_of_routes",
"[",
"route_key",
"]",
"=",
"api_gateway_route",
"self",
".",
"_app",
".",
"add_url_rule",
"(",
"path",
",",
"endpoint",
"=",
"path",
",",
"view_func",
"=",
"self",
".",
"_request_handler",
",",
"methods",
"=",
"api_gateway_route",
".",
"methods",
",",
"provide_automatic_options",
"=",
"False",
")",
"self",
".",
"_construct_error_handling",
"(",
")"
] | Creates a Flask Application that can be started. | [
"Creates",
"a",
"Flask",
"Application",
"that",
"can",
"be",
"started",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L68-L90 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService._generate_route_keys | def _generate_route_keys(self, methods, path):
"""
Generates the key to the _dict_of_routes based on the list of methods
and path supplied
:param list(str) methods: List of HTTP Methods
:param str path: Path off the base url
:return: str of Path:Method
"""
for method in methods:
yield self._route_key(method, path) | python | def _generate_route_keys(self, methods, path):
"""
Generates the key to the _dict_of_routes based on the list of methods
and path supplied
:param list(str) methods: List of HTTP Methods
:param str path: Path off the base url
:return: str of Path:Method
"""
for method in methods:
yield self._route_key(method, path) | [
"def",
"_generate_route_keys",
"(",
"self",
",",
"methods",
",",
"path",
")",
":",
"for",
"method",
"in",
"methods",
":",
"yield",
"self",
".",
"_route_key",
"(",
"method",
",",
"path",
")"
] | Generates the key to the _dict_of_routes based on the list of methods
and path supplied
:param list(str) methods: List of HTTP Methods
:param str path: Path off the base url
:return: str of Path:Method | [
"Generates",
"the",
"key",
"to",
"the",
"_dict_of_routes",
"based",
"on",
"the",
"list",
"of",
"methods",
"and",
"path",
"supplied"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L92-L102 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService._construct_error_handling | def _construct_error_handling(self):
"""
Updates the Flask app with Error Handlers for different Error Codes
"""
# Both path and method not present
self._app.register_error_handler(404, ServiceErrorResponses.route_not_found)
# Path is present, but method not allowed
self._app.register_error_handler(405, ServiceErrorResponses.route_not_found)
# Something went wrong
self._app.register_error_handler(500, ServiceErrorResponses.lambda_failure_response) | python | def _construct_error_handling(self):
"""
Updates the Flask app with Error Handlers for different Error Codes
"""
# Both path and method not present
self._app.register_error_handler(404, ServiceErrorResponses.route_not_found)
# Path is present, but method not allowed
self._app.register_error_handler(405, ServiceErrorResponses.route_not_found)
# Something went wrong
self._app.register_error_handler(500, ServiceErrorResponses.lambda_failure_response) | [
"def",
"_construct_error_handling",
"(",
"self",
")",
":",
"# Both path and method not present",
"self",
".",
"_app",
".",
"register_error_handler",
"(",
"404",
",",
"ServiceErrorResponses",
".",
"route_not_found",
")",
"# Path is present, but method not allowed",
"self",
".",
"_app",
".",
"register_error_handler",
"(",
"405",
",",
"ServiceErrorResponses",
".",
"route_not_found",
")",
"# Something went wrong",
"self",
".",
"_app",
".",
"register_error_handler",
"(",
"500",
",",
"ServiceErrorResponses",
".",
"lambda_failure_response",
")"
] | Updates the Flask app with Error Handlers for different Error Codes | [
"Updates",
"the",
"Flask",
"app",
"with",
"Error",
"Handlers",
"for",
"different",
"Error",
"Codes"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L108-L117 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService._request_handler | def _request_handler(self, **kwargs):
"""
We handle all requests to the host:port. The general flow of handling a request is as follows
* Fetch request from the Flask Global state. This is where Flask places the request and is per thread so
multiple requests are still handled correctly
* Find the Lambda function to invoke by doing a look up based on the request.endpoint and method
* If we don't find the function, we will throw a 502 (just like the 404 and 405 responses we get
from Flask.
* Since we found a Lambda function to invoke, we construct the Lambda Event from the request
* Then Invoke the Lambda function (docker container)
* We then transform the response or errors we get from the Invoke and return the data back to
the caller
Parameters
----------
kwargs dict
Keyword Args that are passed to the function from Flask. This happens when we have path parameters
Returns
-------
Response object
"""
route = self._get_current_route(request)
try:
event = self._construct_event(request, self.port, route.binary_types)
except UnicodeDecodeError:
return ServiceErrorResponses.lambda_failure_response()
stdout_stream = io.BytesIO()
stdout_stream_writer = StreamWriter(stdout_stream, self.is_debugging)
try:
self.lambda_runner.invoke(route.function_name, event, stdout=stdout_stream_writer, stderr=self.stderr)
except FunctionNotFound:
return ServiceErrorResponses.lambda_not_found_response()
lambda_response, lambda_logs, _ = LambdaOutputParser.get_lambda_output(stdout_stream)
if self.stderr and lambda_logs:
# Write the logs to stderr if available.
self.stderr.write(lambda_logs)
try:
(status_code, headers, body) = self._parse_lambda_output(lambda_response,
route.binary_types,
request)
except (KeyError, TypeError, ValueError):
LOG.error("Function returned an invalid response (must include one of: body, headers or "
"statusCode in the response object). Response received: %s", lambda_response)
return ServiceErrorResponses.lambda_failure_response()
return self.service_response(body, headers, status_code) | python | def _request_handler(self, **kwargs):
"""
We handle all requests to the host:port. The general flow of handling a request is as follows
* Fetch request from the Flask Global state. This is where Flask places the request and is per thread so
multiple requests are still handled correctly
* Find the Lambda function to invoke by doing a look up based on the request.endpoint and method
* If we don't find the function, we will throw a 502 (just like the 404 and 405 responses we get
from Flask.
* Since we found a Lambda function to invoke, we construct the Lambda Event from the request
* Then Invoke the Lambda function (docker container)
* We then transform the response or errors we get from the Invoke and return the data back to
the caller
Parameters
----------
kwargs dict
Keyword Args that are passed to the function from Flask. This happens when we have path parameters
Returns
-------
Response object
"""
route = self._get_current_route(request)
try:
event = self._construct_event(request, self.port, route.binary_types)
except UnicodeDecodeError:
return ServiceErrorResponses.lambda_failure_response()
stdout_stream = io.BytesIO()
stdout_stream_writer = StreamWriter(stdout_stream, self.is_debugging)
try:
self.lambda_runner.invoke(route.function_name, event, stdout=stdout_stream_writer, stderr=self.stderr)
except FunctionNotFound:
return ServiceErrorResponses.lambda_not_found_response()
lambda_response, lambda_logs, _ = LambdaOutputParser.get_lambda_output(stdout_stream)
if self.stderr and lambda_logs:
# Write the logs to stderr if available.
self.stderr.write(lambda_logs)
try:
(status_code, headers, body) = self._parse_lambda_output(lambda_response,
route.binary_types,
request)
except (KeyError, TypeError, ValueError):
LOG.error("Function returned an invalid response (must include one of: body, headers or "
"statusCode in the response object). Response received: %s", lambda_response)
return ServiceErrorResponses.lambda_failure_response()
return self.service_response(body, headers, status_code) | [
"def",
"_request_handler",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"route",
"=",
"self",
".",
"_get_current_route",
"(",
"request",
")",
"try",
":",
"event",
"=",
"self",
".",
"_construct_event",
"(",
"request",
",",
"self",
".",
"port",
",",
"route",
".",
"binary_types",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"ServiceErrorResponses",
".",
"lambda_failure_response",
"(",
")",
"stdout_stream",
"=",
"io",
".",
"BytesIO",
"(",
")",
"stdout_stream_writer",
"=",
"StreamWriter",
"(",
"stdout_stream",
",",
"self",
".",
"is_debugging",
")",
"try",
":",
"self",
".",
"lambda_runner",
".",
"invoke",
"(",
"route",
".",
"function_name",
",",
"event",
",",
"stdout",
"=",
"stdout_stream_writer",
",",
"stderr",
"=",
"self",
".",
"stderr",
")",
"except",
"FunctionNotFound",
":",
"return",
"ServiceErrorResponses",
".",
"lambda_not_found_response",
"(",
")",
"lambda_response",
",",
"lambda_logs",
",",
"_",
"=",
"LambdaOutputParser",
".",
"get_lambda_output",
"(",
"stdout_stream",
")",
"if",
"self",
".",
"stderr",
"and",
"lambda_logs",
":",
"# Write the logs to stderr if available.",
"self",
".",
"stderr",
".",
"write",
"(",
"lambda_logs",
")",
"try",
":",
"(",
"status_code",
",",
"headers",
",",
"body",
")",
"=",
"self",
".",
"_parse_lambda_output",
"(",
"lambda_response",
",",
"route",
".",
"binary_types",
",",
"request",
")",
"except",
"(",
"KeyError",
",",
"TypeError",
",",
"ValueError",
")",
":",
"LOG",
".",
"error",
"(",
"\"Function returned an invalid response (must include one of: body, headers or \"",
"\"statusCode in the response object). Response received: %s\"",
",",
"lambda_response",
")",
"return",
"ServiceErrorResponses",
".",
"lambda_failure_response",
"(",
")",
"return",
"self",
".",
"service_response",
"(",
"body",
",",
"headers",
",",
"status_code",
")"
] | We handle all requests to the host:port. The general flow of handling a request is as follows
* Fetch request from the Flask Global state. This is where Flask places the request and is per thread so
multiple requests are still handled correctly
* Find the Lambda function to invoke by doing a look up based on the request.endpoint and method
* If we don't find the function, we will throw a 502 (just like the 404 and 405 responses we get
from Flask.
* Since we found a Lambda function to invoke, we construct the Lambda Event from the request
* Then Invoke the Lambda function (docker container)
* We then transform the response or errors we get from the Invoke and return the data back to
the caller
Parameters
----------
kwargs dict
Keyword Args that are passed to the function from Flask. This happens when we have path parameters
Returns
-------
Response object | [
"We",
"handle",
"all",
"requests",
"to",
"the",
"host",
":",
"port",
".",
"The",
"general",
"flow",
"of",
"handling",
"a",
"request",
"is",
"as",
"follows"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L119-L172 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService._get_current_route | def _get_current_route(self, flask_request):
"""
Get the route (Route) based on the current request
:param request flask_request: Flask Request
:return: Route matching the endpoint and method of the request
"""
endpoint = flask_request.endpoint
method = flask_request.method
route_key = self._route_key(method, endpoint)
route = self._dict_of_routes.get(route_key, None)
if not route:
LOG.debug("Lambda function for the route not found. This should not happen because Flask is "
"already configured to serve all path/methods given to the service. "
"Path=%s Method=%s RouteKey=%s", endpoint, method, route_key)
raise KeyError("Lambda function for the route not found")
return route | python | def _get_current_route(self, flask_request):
"""
Get the route (Route) based on the current request
:param request flask_request: Flask Request
:return: Route matching the endpoint and method of the request
"""
endpoint = flask_request.endpoint
method = flask_request.method
route_key = self._route_key(method, endpoint)
route = self._dict_of_routes.get(route_key, None)
if not route:
LOG.debug("Lambda function for the route not found. This should not happen because Flask is "
"already configured to serve all path/methods given to the service. "
"Path=%s Method=%s RouteKey=%s", endpoint, method, route_key)
raise KeyError("Lambda function for the route not found")
return route | [
"def",
"_get_current_route",
"(",
"self",
",",
"flask_request",
")",
":",
"endpoint",
"=",
"flask_request",
".",
"endpoint",
"method",
"=",
"flask_request",
".",
"method",
"route_key",
"=",
"self",
".",
"_route_key",
"(",
"method",
",",
"endpoint",
")",
"route",
"=",
"self",
".",
"_dict_of_routes",
".",
"get",
"(",
"route_key",
",",
"None",
")",
"if",
"not",
"route",
":",
"LOG",
".",
"debug",
"(",
"\"Lambda function for the route not found. This should not happen because Flask is \"",
"\"already configured to serve all path/methods given to the service. \"",
"\"Path=%s Method=%s RouteKey=%s\"",
",",
"endpoint",
",",
"method",
",",
"route_key",
")",
"raise",
"KeyError",
"(",
"\"Lambda function for the route not found\"",
")",
"return",
"route"
] | Get the route (Route) based on the current request
:param request flask_request: Flask Request
:return: Route matching the endpoint and method of the request | [
"Get",
"the",
"route",
"(",
"Route",
")",
"based",
"on",
"the",
"current",
"request"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L174-L193 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService._parse_lambda_output | def _parse_lambda_output(lambda_output, binary_types, flask_request):
"""
Parses the output from the Lambda Container
:param str lambda_output: Output from Lambda Invoke
:return: Tuple(int, dict, str, bool)
"""
json_output = json.loads(lambda_output)
if not isinstance(json_output, dict):
raise TypeError("Lambda returned %{s} instead of dict", type(json_output))
status_code = json_output.get("statusCode") or 200
headers = CaseInsensitiveDict(json_output.get("headers") or {})
body = json_output.get("body") or "no data"
is_base_64_encoded = json_output.get("isBase64Encoded") or False
try:
status_code = int(status_code)
if status_code <= 0:
raise ValueError
except ValueError:
message = "statusCode must be a positive int"
LOG.error(message)
raise TypeError(message)
# If the customer doesn't define Content-Type default to application/json
if "Content-Type" not in headers:
LOG.info("No Content-Type given. Defaulting to 'application/json'.")
headers["Content-Type"] = "application/json"
if LocalApigwService._should_base64_decode_body(binary_types, flask_request, headers, is_base_64_encoded):
body = base64.b64decode(body)
return status_code, headers, body | python | def _parse_lambda_output(lambda_output, binary_types, flask_request):
"""
Parses the output from the Lambda Container
:param str lambda_output: Output from Lambda Invoke
:return: Tuple(int, dict, str, bool)
"""
json_output = json.loads(lambda_output)
if not isinstance(json_output, dict):
raise TypeError("Lambda returned %{s} instead of dict", type(json_output))
status_code = json_output.get("statusCode") or 200
headers = CaseInsensitiveDict(json_output.get("headers") or {})
body = json_output.get("body") or "no data"
is_base_64_encoded = json_output.get("isBase64Encoded") or False
try:
status_code = int(status_code)
if status_code <= 0:
raise ValueError
except ValueError:
message = "statusCode must be a positive int"
LOG.error(message)
raise TypeError(message)
# If the customer doesn't define Content-Type default to application/json
if "Content-Type" not in headers:
LOG.info("No Content-Type given. Defaulting to 'application/json'.")
headers["Content-Type"] = "application/json"
if LocalApigwService._should_base64_decode_body(binary_types, flask_request, headers, is_base_64_encoded):
body = base64.b64decode(body)
return status_code, headers, body | [
"def",
"_parse_lambda_output",
"(",
"lambda_output",
",",
"binary_types",
",",
"flask_request",
")",
":",
"json_output",
"=",
"json",
".",
"loads",
"(",
"lambda_output",
")",
"if",
"not",
"isinstance",
"(",
"json_output",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Lambda returned %{s} instead of dict\"",
",",
"type",
"(",
"json_output",
")",
")",
"status_code",
"=",
"json_output",
".",
"get",
"(",
"\"statusCode\"",
")",
"or",
"200",
"headers",
"=",
"CaseInsensitiveDict",
"(",
"json_output",
".",
"get",
"(",
"\"headers\"",
")",
"or",
"{",
"}",
")",
"body",
"=",
"json_output",
".",
"get",
"(",
"\"body\"",
")",
"or",
"\"no data\"",
"is_base_64_encoded",
"=",
"json_output",
".",
"get",
"(",
"\"isBase64Encoded\"",
")",
"or",
"False",
"try",
":",
"status_code",
"=",
"int",
"(",
"status_code",
")",
"if",
"status_code",
"<=",
"0",
":",
"raise",
"ValueError",
"except",
"ValueError",
":",
"message",
"=",
"\"statusCode must be a positive int\"",
"LOG",
".",
"error",
"(",
"message",
")",
"raise",
"TypeError",
"(",
"message",
")",
"# If the customer doesn't define Content-Type default to application/json",
"if",
"\"Content-Type\"",
"not",
"in",
"headers",
":",
"LOG",
".",
"info",
"(",
"\"No Content-Type given. Defaulting to 'application/json'.\"",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"if",
"LocalApigwService",
".",
"_should_base64_decode_body",
"(",
"binary_types",
",",
"flask_request",
",",
"headers",
",",
"is_base_64_encoded",
")",
":",
"body",
"=",
"base64",
".",
"b64decode",
"(",
"body",
")",
"return",
"status_code",
",",
"headers",
",",
"body"
] | Parses the output from the Lambda Container
:param str lambda_output: Output from Lambda Invoke
:return: Tuple(int, dict, str, bool) | [
"Parses",
"the",
"output",
"from",
"the",
"Lambda",
"Container"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L197-L231 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService._should_base64_decode_body | def _should_base64_decode_body(binary_types, flask_request, lamba_response_headers, is_base_64_encoded):
"""
Whether or not the body should be decoded from Base64 to Binary
Parameters
----------
binary_types list(basestring)
Corresponds to self.binary_types (aka. what is parsed from SAM Template
flask_request flask.request
Flask request
lamba_response_headers dict
Headers Lambda returns
is_base_64_encoded bool
True if the body is Base64 encoded
Returns
-------
True if the body from the request should be converted to binary, otherwise false
"""
best_match_mimetype = flask_request.accept_mimetypes.best_match([lamba_response_headers["Content-Type"]])
is_best_match_in_binary_types = best_match_mimetype in binary_types or '*/*' in binary_types
return best_match_mimetype and is_best_match_in_binary_types and is_base_64_encoded | python | def _should_base64_decode_body(binary_types, flask_request, lamba_response_headers, is_base_64_encoded):
"""
Whether or not the body should be decoded from Base64 to Binary
Parameters
----------
binary_types list(basestring)
Corresponds to self.binary_types (aka. what is parsed from SAM Template
flask_request flask.request
Flask request
lamba_response_headers dict
Headers Lambda returns
is_base_64_encoded bool
True if the body is Base64 encoded
Returns
-------
True if the body from the request should be converted to binary, otherwise false
"""
best_match_mimetype = flask_request.accept_mimetypes.best_match([lamba_response_headers["Content-Type"]])
is_best_match_in_binary_types = best_match_mimetype in binary_types or '*/*' in binary_types
return best_match_mimetype and is_best_match_in_binary_types and is_base_64_encoded | [
"def",
"_should_base64_decode_body",
"(",
"binary_types",
",",
"flask_request",
",",
"lamba_response_headers",
",",
"is_base_64_encoded",
")",
":",
"best_match_mimetype",
"=",
"flask_request",
".",
"accept_mimetypes",
".",
"best_match",
"(",
"[",
"lamba_response_headers",
"[",
"\"Content-Type\"",
"]",
"]",
")",
"is_best_match_in_binary_types",
"=",
"best_match_mimetype",
"in",
"binary_types",
"or",
"'*/*'",
"in",
"binary_types",
"return",
"best_match_mimetype",
"and",
"is_best_match_in_binary_types",
"and",
"is_base_64_encoded"
] | Whether or not the body should be decoded from Base64 to Binary
Parameters
----------
binary_types list(basestring)
Corresponds to self.binary_types (aka. what is parsed from SAM Template
flask_request flask.request
Flask request
lamba_response_headers dict
Headers Lambda returns
is_base_64_encoded bool
True if the body is Base64 encoded
Returns
-------
True if the body from the request should be converted to binary, otherwise false | [
"Whether",
"or",
"not",
"the",
"body",
"should",
"be",
"decoded",
"from",
"Base64",
"to",
"Binary"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L234-L257 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService._construct_event | def _construct_event(flask_request, port, binary_types):
"""
Helper method that constructs the Event to be passed to Lambda
:param request flask_request: Flask Request
:return: String representing the event
"""
identity = ContextIdentity(source_ip=flask_request.remote_addr)
endpoint = PathConverter.convert_path_to_api_gateway(flask_request.endpoint)
method = flask_request.method
request_data = flask_request.get_data()
request_mimetype = flask_request.mimetype
is_base_64 = LocalApigwService._should_base64_encode(binary_types, request_mimetype)
if is_base_64:
LOG.debug("Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda.")
request_data = base64.b64encode(request_data)
if request_data:
# Flask does not parse/decode the request data. We should do it ourselves
request_data = request_data.decode('utf-8')
context = RequestContext(resource_path=endpoint,
http_method=method,
stage="prod",
identity=identity,
path=endpoint)
event_headers = dict(flask_request.headers)
event_headers["X-Forwarded-Proto"] = flask_request.scheme
event_headers["X-Forwarded-Port"] = str(port)
# APIGW does not support duplicate query parameters. Flask gives query params as a list so
# we need to convert only grab the first item unless many were given, were we grab the last to be consistent
# with APIGW
query_string_dict = LocalApigwService._query_string_params(flask_request)
event = ApiGatewayLambdaEvent(http_method=method,
body=request_data,
resource=endpoint,
request_context=context,
query_string_params=query_string_dict,
headers=event_headers,
path_parameters=flask_request.view_args,
path=flask_request.path,
is_base_64_encoded=is_base_64)
event_str = json.dumps(event.to_dict())
LOG.debug("Constructed String representation of Event to invoke Lambda. Event: %s", event_str)
return event_str | python | def _construct_event(flask_request, port, binary_types):
"""
Helper method that constructs the Event to be passed to Lambda
:param request flask_request: Flask Request
:return: String representing the event
"""
identity = ContextIdentity(source_ip=flask_request.remote_addr)
endpoint = PathConverter.convert_path_to_api_gateway(flask_request.endpoint)
method = flask_request.method
request_data = flask_request.get_data()
request_mimetype = flask_request.mimetype
is_base_64 = LocalApigwService._should_base64_encode(binary_types, request_mimetype)
if is_base_64:
LOG.debug("Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda.")
request_data = base64.b64encode(request_data)
if request_data:
# Flask does not parse/decode the request data. We should do it ourselves
request_data = request_data.decode('utf-8')
context = RequestContext(resource_path=endpoint,
http_method=method,
stage="prod",
identity=identity,
path=endpoint)
event_headers = dict(flask_request.headers)
event_headers["X-Forwarded-Proto"] = flask_request.scheme
event_headers["X-Forwarded-Port"] = str(port)
# APIGW does not support duplicate query parameters. Flask gives query params as a list so
# we need to convert only grab the first item unless many were given, were we grab the last to be consistent
# with APIGW
query_string_dict = LocalApigwService._query_string_params(flask_request)
event = ApiGatewayLambdaEvent(http_method=method,
body=request_data,
resource=endpoint,
request_context=context,
query_string_params=query_string_dict,
headers=event_headers,
path_parameters=flask_request.view_args,
path=flask_request.path,
is_base_64_encoded=is_base_64)
event_str = json.dumps(event.to_dict())
LOG.debug("Constructed String representation of Event to invoke Lambda. Event: %s", event_str)
return event_str | [
"def",
"_construct_event",
"(",
"flask_request",
",",
"port",
",",
"binary_types",
")",
":",
"identity",
"=",
"ContextIdentity",
"(",
"source_ip",
"=",
"flask_request",
".",
"remote_addr",
")",
"endpoint",
"=",
"PathConverter",
".",
"convert_path_to_api_gateway",
"(",
"flask_request",
".",
"endpoint",
")",
"method",
"=",
"flask_request",
".",
"method",
"request_data",
"=",
"flask_request",
".",
"get_data",
"(",
")",
"request_mimetype",
"=",
"flask_request",
".",
"mimetype",
"is_base_64",
"=",
"LocalApigwService",
".",
"_should_base64_encode",
"(",
"binary_types",
",",
"request_mimetype",
")",
"if",
"is_base_64",
":",
"LOG",
".",
"debug",
"(",
"\"Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda.\"",
")",
"request_data",
"=",
"base64",
".",
"b64encode",
"(",
"request_data",
")",
"if",
"request_data",
":",
"# Flask does not parse/decode the request data. We should do it ourselves",
"request_data",
"=",
"request_data",
".",
"decode",
"(",
"'utf-8'",
")",
"context",
"=",
"RequestContext",
"(",
"resource_path",
"=",
"endpoint",
",",
"http_method",
"=",
"method",
",",
"stage",
"=",
"\"prod\"",
",",
"identity",
"=",
"identity",
",",
"path",
"=",
"endpoint",
")",
"event_headers",
"=",
"dict",
"(",
"flask_request",
".",
"headers",
")",
"event_headers",
"[",
"\"X-Forwarded-Proto\"",
"]",
"=",
"flask_request",
".",
"scheme",
"event_headers",
"[",
"\"X-Forwarded-Port\"",
"]",
"=",
"str",
"(",
"port",
")",
"# APIGW does not support duplicate query parameters. Flask gives query params as a list so",
"# we need to convert only grab the first item unless many were given, were we grab the last to be consistent",
"# with APIGW",
"query_string_dict",
"=",
"LocalApigwService",
".",
"_query_string_params",
"(",
"flask_request",
")",
"event",
"=",
"ApiGatewayLambdaEvent",
"(",
"http_method",
"=",
"method",
",",
"body",
"=",
"request_data",
",",
"resource",
"=",
"endpoint",
",",
"request_context",
"=",
"context",
",",
"query_string_params",
"=",
"query_string_dict",
",",
"headers",
"=",
"event_headers",
",",
"path_parameters",
"=",
"flask_request",
".",
"view_args",
",",
"path",
"=",
"flask_request",
".",
"path",
",",
"is_base_64_encoded",
"=",
"is_base_64",
")",
"event_str",
"=",
"json",
".",
"dumps",
"(",
"event",
".",
"to_dict",
"(",
")",
")",
"LOG",
".",
"debug",
"(",
"\"Constructed String representation of Event to invoke Lambda. Event: %s\"",
",",
"event_str",
")",
"return",
"event_str"
] | Helper method that constructs the Event to be passed to Lambda
:param request flask_request: Flask Request
:return: String representing the event | [
"Helper",
"method",
"that",
"constructs",
"the",
"Event",
"to",
"be",
"passed",
"to",
"Lambda"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L260-L314 | train |
awslabs/aws-sam-cli | samcli/local/apigw/local_apigw_service.py | LocalApigwService._query_string_params | def _query_string_params(flask_request):
"""
Constructs an APIGW equivalent query string dictionary
Parameters
----------
flask_request request
Request from Flask
Returns dict (str: str)
-------
Empty dict if no query params where in the request otherwise returns a dictionary of key to value
"""
query_string_dict = {}
# Flask returns an ImmutableMultiDict so convert to a dictionary that becomes
# a dict(str: list) then iterate over
for query_string_key, query_string_list in flask_request.args.lists():
query_string_value_length = len(query_string_list)
# if the list is empty, default to empty string
if not query_string_value_length:
query_string_dict[query_string_key] = ""
else:
# APIGW doesn't handle duplicate query string keys, picking the last one in the list
query_string_dict[query_string_key] = query_string_list[-1]
return query_string_dict | python | def _query_string_params(flask_request):
"""
Constructs an APIGW equivalent query string dictionary
Parameters
----------
flask_request request
Request from Flask
Returns dict (str: str)
-------
Empty dict if no query params where in the request otherwise returns a dictionary of key to value
"""
query_string_dict = {}
# Flask returns an ImmutableMultiDict so convert to a dictionary that becomes
# a dict(str: list) then iterate over
for query_string_key, query_string_list in flask_request.args.lists():
query_string_value_length = len(query_string_list)
# if the list is empty, default to empty string
if not query_string_value_length:
query_string_dict[query_string_key] = ""
else:
# APIGW doesn't handle duplicate query string keys, picking the last one in the list
query_string_dict[query_string_key] = query_string_list[-1]
return query_string_dict | [
"def",
"_query_string_params",
"(",
"flask_request",
")",
":",
"query_string_dict",
"=",
"{",
"}",
"# Flask returns an ImmutableMultiDict so convert to a dictionary that becomes",
"# a dict(str: list) then iterate over",
"for",
"query_string_key",
",",
"query_string_list",
"in",
"flask_request",
".",
"args",
".",
"lists",
"(",
")",
":",
"query_string_value_length",
"=",
"len",
"(",
"query_string_list",
")",
"# if the list is empty, default to empty string",
"if",
"not",
"query_string_value_length",
":",
"query_string_dict",
"[",
"query_string_key",
"]",
"=",
"\"\"",
"else",
":",
"# APIGW doesn't handle duplicate query string keys, picking the last one in the list",
"query_string_dict",
"[",
"query_string_key",
"]",
"=",
"query_string_list",
"[",
"-",
"1",
"]",
"return",
"query_string_dict"
] | Constructs an APIGW equivalent query string dictionary
Parameters
----------
flask_request request
Request from Flask
Returns dict (str: str)
-------
Empty dict if no query params where in the request otherwise returns a dictionary of key to value | [
"Constructs",
"an",
"APIGW",
"equivalent",
"query",
"string",
"dictionary"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/local_apigw_service.py#L317-L345 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/local_lambda.py | LocalLambdaRunner.invoke | def invoke(self, function_name, event, stdout=None, stderr=None):
"""
Find the Lambda function with given name and invoke it. Pass the given event to the function and return
response through the given streams.
This function will block until either the function completes or times out.
Parameters
----------
function_name str
Name of the Lambda function to invoke
event str
Event data passed to the function. Must be a valid JSON String.
stdout samcli.lib.utils.stream_writer.StreamWriter
Stream writer to write the output of the Lambda function to.
stderr samcli.lib.utils.stream_writer.StreamWriter
Stream writer to write the Lambda runtime logs to.
Raises
------
FunctionNotfound
When we cannot find a function with the given name
"""
# Generate the correct configuration based on given inputs
function = self.provider.get(function_name)
if not function:
all_functions = [f.name for f in self.provider.get_all()]
available_function_message = "{} not found. Possible options in your template: {}"\
.format(function_name, all_functions)
LOG.info(available_function_message)
raise FunctionNotFound("Unable to find a Function with name '%s'", function_name)
LOG.debug("Found one Lambda function with name '%s'", function_name)
LOG.info("Invoking %s (%s)", function.handler, function.runtime)
config = self._get_invoke_config(function)
# Invoke the function
self.local_runtime.invoke(config, event, debug_context=self.debug_context, stdout=stdout, stderr=stderr) | python | def invoke(self, function_name, event, stdout=None, stderr=None):
"""
Find the Lambda function with given name and invoke it. Pass the given event to the function and return
response through the given streams.
This function will block until either the function completes or times out.
Parameters
----------
function_name str
Name of the Lambda function to invoke
event str
Event data passed to the function. Must be a valid JSON String.
stdout samcli.lib.utils.stream_writer.StreamWriter
Stream writer to write the output of the Lambda function to.
stderr samcli.lib.utils.stream_writer.StreamWriter
Stream writer to write the Lambda runtime logs to.
Raises
------
FunctionNotfound
When we cannot find a function with the given name
"""
# Generate the correct configuration based on given inputs
function = self.provider.get(function_name)
if not function:
all_functions = [f.name for f in self.provider.get_all()]
available_function_message = "{} not found. Possible options in your template: {}"\
.format(function_name, all_functions)
LOG.info(available_function_message)
raise FunctionNotFound("Unable to find a Function with name '%s'", function_name)
LOG.debug("Found one Lambda function with name '%s'", function_name)
LOG.info("Invoking %s (%s)", function.handler, function.runtime)
config = self._get_invoke_config(function)
# Invoke the function
self.local_runtime.invoke(config, event, debug_context=self.debug_context, stdout=stdout, stderr=stderr) | [
"def",
"invoke",
"(",
"self",
",",
"function_name",
",",
"event",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"# Generate the correct configuration based on given inputs",
"function",
"=",
"self",
".",
"provider",
".",
"get",
"(",
"function_name",
")",
"if",
"not",
"function",
":",
"all_functions",
"=",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"self",
".",
"provider",
".",
"get_all",
"(",
")",
"]",
"available_function_message",
"=",
"\"{} not found. Possible options in your template: {}\"",
".",
"format",
"(",
"function_name",
",",
"all_functions",
")",
"LOG",
".",
"info",
"(",
"available_function_message",
")",
"raise",
"FunctionNotFound",
"(",
"\"Unable to find a Function with name '%s'\"",
",",
"function_name",
")",
"LOG",
".",
"debug",
"(",
"\"Found one Lambda function with name '%s'\"",
",",
"function_name",
")",
"LOG",
".",
"info",
"(",
"\"Invoking %s (%s)\"",
",",
"function",
".",
"handler",
",",
"function",
".",
"runtime",
")",
"config",
"=",
"self",
".",
"_get_invoke_config",
"(",
"function",
")",
"# Invoke the function",
"self",
".",
"local_runtime",
".",
"invoke",
"(",
"config",
",",
"event",
",",
"debug_context",
"=",
"self",
".",
"debug_context",
",",
"stdout",
"=",
"stdout",
",",
"stderr",
"=",
"stderr",
")"
] | Find the Lambda function with given name and invoke it. Pass the given event to the function and return
response through the given streams.
This function will block until either the function completes or times out.
Parameters
----------
function_name str
Name of the Lambda function to invoke
event str
Event data passed to the function. Must be a valid JSON String.
stdout samcli.lib.utils.stream_writer.StreamWriter
Stream writer to write the output of the Lambda function to.
stderr samcli.lib.utils.stream_writer.StreamWriter
Stream writer to write the Lambda runtime logs to.
Raises
------
FunctionNotfound
When we cannot find a function with the given name | [
"Find",
"the",
"Lambda",
"function",
"with",
"given",
"name",
"and",
"invoke",
"it",
".",
"Pass",
"the",
"given",
"event",
"to",
"the",
"function",
"and",
"return",
"response",
"through",
"the",
"given",
"streams",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_lambda.py#L49-L89 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/local_lambda.py | LocalLambdaRunner._get_invoke_config | def _get_invoke_config(self, function):
"""
Returns invoke configuration to pass to Lambda Runtime to invoke the given function
:param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for
:return samcli.local.lambdafn.config.FunctionConfig: Function configuration to pass to Lambda runtime
"""
env_vars = self._make_env_vars(function)
code_abs_path = resolve_code_path(self.cwd, function.codeuri)
LOG.debug("Resolved absolute path to code is %s", code_abs_path)
function_timeout = function.timeout
# The Runtime container handles timeout inside the container. When debugging with short timeouts, this can
# cause the container execution to stop. When in debug mode, we set the timeout in the container to a max 10
# hours. This will ensure the container doesn't unexpectedly stop while debugging function code
if self.is_debugging():
function_timeout = self.MAX_DEBUG_TIMEOUT
return FunctionConfig(name=function.name,
runtime=function.runtime,
handler=function.handler,
code_abs_path=code_abs_path,
layers=function.layers,
memory=function.memory,
timeout=function_timeout,
env_vars=env_vars) | python | def _get_invoke_config(self, function):
"""
Returns invoke configuration to pass to Lambda Runtime to invoke the given function
:param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for
:return samcli.local.lambdafn.config.FunctionConfig: Function configuration to pass to Lambda runtime
"""
env_vars = self._make_env_vars(function)
code_abs_path = resolve_code_path(self.cwd, function.codeuri)
LOG.debug("Resolved absolute path to code is %s", code_abs_path)
function_timeout = function.timeout
# The Runtime container handles timeout inside the container. When debugging with short timeouts, this can
# cause the container execution to stop. When in debug mode, we set the timeout in the container to a max 10
# hours. This will ensure the container doesn't unexpectedly stop while debugging function code
if self.is_debugging():
function_timeout = self.MAX_DEBUG_TIMEOUT
return FunctionConfig(name=function.name,
runtime=function.runtime,
handler=function.handler,
code_abs_path=code_abs_path,
layers=function.layers,
memory=function.memory,
timeout=function_timeout,
env_vars=env_vars) | [
"def",
"_get_invoke_config",
"(",
"self",
",",
"function",
")",
":",
"env_vars",
"=",
"self",
".",
"_make_env_vars",
"(",
"function",
")",
"code_abs_path",
"=",
"resolve_code_path",
"(",
"self",
".",
"cwd",
",",
"function",
".",
"codeuri",
")",
"LOG",
".",
"debug",
"(",
"\"Resolved absolute path to code is %s\"",
",",
"code_abs_path",
")",
"function_timeout",
"=",
"function",
".",
"timeout",
"# The Runtime container handles timeout inside the container. When debugging with short timeouts, this can",
"# cause the container execution to stop. When in debug mode, we set the timeout in the container to a max 10",
"# hours. This will ensure the container doesn't unexpectedly stop while debugging function code",
"if",
"self",
".",
"is_debugging",
"(",
")",
":",
"function_timeout",
"=",
"self",
".",
"MAX_DEBUG_TIMEOUT",
"return",
"FunctionConfig",
"(",
"name",
"=",
"function",
".",
"name",
",",
"runtime",
"=",
"function",
".",
"runtime",
",",
"handler",
"=",
"function",
".",
"handler",
",",
"code_abs_path",
"=",
"code_abs_path",
",",
"layers",
"=",
"function",
".",
"layers",
",",
"memory",
"=",
"function",
".",
"memory",
",",
"timeout",
"=",
"function_timeout",
",",
"env_vars",
"=",
"env_vars",
")"
] | Returns invoke configuration to pass to Lambda Runtime to invoke the given function
:param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for
:return samcli.local.lambdafn.config.FunctionConfig: Function configuration to pass to Lambda runtime | [
"Returns",
"invoke",
"configuration",
"to",
"pass",
"to",
"Lambda",
"Runtime",
"to",
"invoke",
"the",
"given",
"function"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_lambda.py#L103-L131 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/local_lambda.py | LocalLambdaRunner._make_env_vars | def _make_env_vars(self, function):
"""Returns the environment variables configuration for this function
Parameters
----------
function : samcli.commands.local.lib.provider.Function
Lambda function to generate the configuration for
Returns
-------
samcli.local.lambdafn.env_vars.EnvironmentVariables
Environment variable configuration for this function
Raises
------
samcli.commands.local.lib.exceptions.OverridesNotWellDefinedError
If the environment dict is in the wrong format to process environment vars
"""
name = function.name
variables = None
if function.environment and isinstance(function.environment, dict) and "Variables" in function.environment:
variables = function.environment["Variables"]
else:
LOG.debug("No environment variables found for function '%s'", name)
# This could either be in standard format, or a CloudFormation parameter file format.
#
# Standard format is {FunctionName: {key:value}, FunctionName: {key:value}}
# CloudFormation parameter file is {"Parameters": {key:value}}
for env_var_value in self.env_vars_values.values():
if not isinstance(env_var_value, dict):
reason = """
Environment variables must be in either CloudFormation parameter file
format or in {FunctionName: {key:value}} JSON pairs
"""
LOG.debug(reason)
raise OverridesNotWellDefinedError(reason)
if "Parameters" in self.env_vars_values:
LOG.debug("Environment variables overrides data is in CloudFormation parameter file format")
# CloudFormation parameter file format
overrides = self.env_vars_values["Parameters"]
else:
# Standard format
LOG.debug("Environment variables overrides data is standard format")
overrides = self.env_vars_values.get(name, None)
shell_env = os.environ
aws_creds = self.get_aws_creds()
return EnvironmentVariables(function.memory,
function.timeout,
function.handler,
variables=variables,
shell_env_values=shell_env,
override_values=overrides,
aws_creds=aws_creds) | python | def _make_env_vars(self, function):
"""Returns the environment variables configuration for this function
Parameters
----------
function : samcli.commands.local.lib.provider.Function
Lambda function to generate the configuration for
Returns
-------
samcli.local.lambdafn.env_vars.EnvironmentVariables
Environment variable configuration for this function
Raises
------
samcli.commands.local.lib.exceptions.OverridesNotWellDefinedError
If the environment dict is in the wrong format to process environment vars
"""
name = function.name
variables = None
if function.environment and isinstance(function.environment, dict) and "Variables" in function.environment:
variables = function.environment["Variables"]
else:
LOG.debug("No environment variables found for function '%s'", name)
# This could either be in standard format, or a CloudFormation parameter file format.
#
# Standard format is {FunctionName: {key:value}, FunctionName: {key:value}}
# CloudFormation parameter file is {"Parameters": {key:value}}
for env_var_value in self.env_vars_values.values():
if not isinstance(env_var_value, dict):
reason = """
Environment variables must be in either CloudFormation parameter file
format or in {FunctionName: {key:value}} JSON pairs
"""
LOG.debug(reason)
raise OverridesNotWellDefinedError(reason)
if "Parameters" in self.env_vars_values:
LOG.debug("Environment variables overrides data is in CloudFormation parameter file format")
# CloudFormation parameter file format
overrides = self.env_vars_values["Parameters"]
else:
# Standard format
LOG.debug("Environment variables overrides data is standard format")
overrides = self.env_vars_values.get(name, None)
shell_env = os.environ
aws_creds = self.get_aws_creds()
return EnvironmentVariables(function.memory,
function.timeout,
function.handler,
variables=variables,
shell_env_values=shell_env,
override_values=overrides,
aws_creds=aws_creds) | [
"def",
"_make_env_vars",
"(",
"self",
",",
"function",
")",
":",
"name",
"=",
"function",
".",
"name",
"variables",
"=",
"None",
"if",
"function",
".",
"environment",
"and",
"isinstance",
"(",
"function",
".",
"environment",
",",
"dict",
")",
"and",
"\"Variables\"",
"in",
"function",
".",
"environment",
":",
"variables",
"=",
"function",
".",
"environment",
"[",
"\"Variables\"",
"]",
"else",
":",
"LOG",
".",
"debug",
"(",
"\"No environment variables found for function '%s'\"",
",",
"name",
")",
"# This could either be in standard format, or a CloudFormation parameter file format.",
"#",
"# Standard format is {FunctionName: {key:value}, FunctionName: {key:value}}",
"# CloudFormation parameter file is {\"Parameters\": {key:value}}",
"for",
"env_var_value",
"in",
"self",
".",
"env_vars_values",
".",
"values",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"env_var_value",
",",
"dict",
")",
":",
"reason",
"=",
"\"\"\"\n Environment variables must be in either CloudFormation parameter file\n format or in {FunctionName: {key:value}} JSON pairs\n \"\"\"",
"LOG",
".",
"debug",
"(",
"reason",
")",
"raise",
"OverridesNotWellDefinedError",
"(",
"reason",
")",
"if",
"\"Parameters\"",
"in",
"self",
".",
"env_vars_values",
":",
"LOG",
".",
"debug",
"(",
"\"Environment variables overrides data is in CloudFormation parameter file format\"",
")",
"# CloudFormation parameter file format",
"overrides",
"=",
"self",
".",
"env_vars_values",
"[",
"\"Parameters\"",
"]",
"else",
":",
"# Standard format",
"LOG",
".",
"debug",
"(",
"\"Environment variables overrides data is standard format\"",
")",
"overrides",
"=",
"self",
".",
"env_vars_values",
".",
"get",
"(",
"name",
",",
"None",
")",
"shell_env",
"=",
"os",
".",
"environ",
"aws_creds",
"=",
"self",
".",
"get_aws_creds",
"(",
")",
"return",
"EnvironmentVariables",
"(",
"function",
".",
"memory",
",",
"function",
".",
"timeout",
",",
"function",
".",
"handler",
",",
"variables",
"=",
"variables",
",",
"shell_env_values",
"=",
"shell_env",
",",
"override_values",
"=",
"overrides",
",",
"aws_creds",
"=",
"aws_creds",
")"
] | Returns the environment variables configuration for this function
Parameters
----------
function : samcli.commands.local.lib.provider.Function
Lambda function to generate the configuration for
Returns
-------
samcli.local.lambdafn.env_vars.EnvironmentVariables
Environment variable configuration for this function
Raises
------
samcli.commands.local.lib.exceptions.OverridesNotWellDefinedError
If the environment dict is in the wrong format to process environment vars | [
"Returns",
"the",
"environment",
"variables",
"configuration",
"for",
"this",
"function"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_lambda.py#L133-L193 | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/local_lambda.py | LocalLambdaRunner.get_aws_creds | def get_aws_creds(self):
"""
Returns AWS credentials obtained from the shell environment or given profile
:return dict: A dictionary containing credentials. This dict has the structure
{"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved,
this returns None
"""
result = {}
# to pass command line arguments for region & profile to setup boto3 default session
if boto3.DEFAULT_SESSION:
session = boto3.DEFAULT_SESSION
else:
session = boto3.session.Session()
profile_name = session.profile_name if session else None
LOG.debug("Loading AWS credentials from session with profile '%s'", profile_name)
if not session:
return result
# Load the credentials from profile/environment
creds = session.get_credentials()
if not creds:
# If we were unable to load credentials, then just return empty. We will use the default
return result
# After loading credentials, region name might be available here.
if hasattr(session, 'region_name') and session.region_name:
result["region"] = session.region_name
# Only add the key, if its value is present
if hasattr(creds, 'access_key') and creds.access_key:
result["key"] = creds.access_key
if hasattr(creds, 'secret_key') and creds.secret_key:
result["secret"] = creds.secret_key
if hasattr(creds, 'token') and creds.token:
result["sessiontoken"] = creds.token
return result | python | def get_aws_creds(self):
"""
Returns AWS credentials obtained from the shell environment or given profile
:return dict: A dictionary containing credentials. This dict has the structure
{"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved,
this returns None
"""
result = {}
# to pass command line arguments for region & profile to setup boto3 default session
if boto3.DEFAULT_SESSION:
session = boto3.DEFAULT_SESSION
else:
session = boto3.session.Session()
profile_name = session.profile_name if session else None
LOG.debug("Loading AWS credentials from session with profile '%s'", profile_name)
if not session:
return result
# Load the credentials from profile/environment
creds = session.get_credentials()
if not creds:
# If we were unable to load credentials, then just return empty. We will use the default
return result
# After loading credentials, region name might be available here.
if hasattr(session, 'region_name') and session.region_name:
result["region"] = session.region_name
# Only add the key, if its value is present
if hasattr(creds, 'access_key') and creds.access_key:
result["key"] = creds.access_key
if hasattr(creds, 'secret_key') and creds.secret_key:
result["secret"] = creds.secret_key
if hasattr(creds, 'token') and creds.token:
result["sessiontoken"] = creds.token
return result | [
"def",
"get_aws_creds",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"# to pass command line arguments for region & profile to setup boto3 default session",
"if",
"boto3",
".",
"DEFAULT_SESSION",
":",
"session",
"=",
"boto3",
".",
"DEFAULT_SESSION",
"else",
":",
"session",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
")",
"profile_name",
"=",
"session",
".",
"profile_name",
"if",
"session",
"else",
"None",
"LOG",
".",
"debug",
"(",
"\"Loading AWS credentials from session with profile '%s'\"",
",",
"profile_name",
")",
"if",
"not",
"session",
":",
"return",
"result",
"# Load the credentials from profile/environment",
"creds",
"=",
"session",
".",
"get_credentials",
"(",
")",
"if",
"not",
"creds",
":",
"# If we were unable to load credentials, then just return empty. We will use the default",
"return",
"result",
"# After loading credentials, region name might be available here.",
"if",
"hasattr",
"(",
"session",
",",
"'region_name'",
")",
"and",
"session",
".",
"region_name",
":",
"result",
"[",
"\"region\"",
"]",
"=",
"session",
".",
"region_name",
"# Only add the key, if its value is present",
"if",
"hasattr",
"(",
"creds",
",",
"'access_key'",
")",
"and",
"creds",
".",
"access_key",
":",
"result",
"[",
"\"key\"",
"]",
"=",
"creds",
".",
"access_key",
"if",
"hasattr",
"(",
"creds",
",",
"'secret_key'",
")",
"and",
"creds",
".",
"secret_key",
":",
"result",
"[",
"\"secret\"",
"]",
"=",
"creds",
".",
"secret_key",
"if",
"hasattr",
"(",
"creds",
",",
"'token'",
")",
"and",
"creds",
".",
"token",
":",
"result",
"[",
"\"sessiontoken\"",
"]",
"=",
"creds",
".",
"token",
"return",
"result"
] | Returns AWS credentials obtained from the shell environment or given profile
:return dict: A dictionary containing credentials. This dict has the structure
{"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved,
this returns None | [
"Returns",
"AWS",
"credentials",
"obtained",
"from",
"the",
"shell",
"environment",
"or",
"given",
"profile"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_lambda.py#L195-L238 | train |
awslabs/aws-sam-cli | samcli/local/events/api_event.py | ContextIdentity.to_dict | def to_dict(self):
"""
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object
"""
json_dict = {"apiKey": self.api_key,
"userArn": self.user_arn,
"cognitoAuthenticationType": self.cognito_authentication_type,
"caller": self.caller,
"userAgent": self.user_agent,
"user": self.user,
"cognitoIdentityPoolId": self.cognito_identity_pool_id,
"cognitoAuthenticationProvider": self.cognito_authentication_provider,
"sourceIp": self.source_ip,
"accountId": self.account_id
}
return json_dict | python | def to_dict(self):
"""
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object
"""
json_dict = {"apiKey": self.api_key,
"userArn": self.user_arn,
"cognitoAuthenticationType": self.cognito_authentication_type,
"caller": self.caller,
"userAgent": self.user_agent,
"user": self.user,
"cognitoIdentityPoolId": self.cognito_identity_pool_id,
"cognitoAuthenticationProvider": self.cognito_authentication_provider,
"sourceIp": self.source_ip,
"accountId": self.account_id
}
return json_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"json_dict",
"=",
"{",
"\"apiKey\"",
":",
"self",
".",
"api_key",
",",
"\"userArn\"",
":",
"self",
".",
"user_arn",
",",
"\"cognitoAuthenticationType\"",
":",
"self",
".",
"cognito_authentication_type",
",",
"\"caller\"",
":",
"self",
".",
"caller",
",",
"\"userAgent\"",
":",
"self",
".",
"user_agent",
",",
"\"user\"",
":",
"self",
".",
"user",
",",
"\"cognitoIdentityPoolId\"",
":",
"self",
".",
"cognito_identity_pool_id",
",",
"\"cognitoAuthenticationProvider\"",
":",
"self",
".",
"cognito_authentication_provider",
",",
"\"sourceIp\"",
":",
"self",
".",
"source_ip",
",",
"\"accountId\"",
":",
"self",
".",
"account_id",
"}",
"return",
"json_dict"
] | Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object | [
"Constructs",
"an",
"dictionary",
"representation",
"of",
"the",
"Identity",
"Object",
"to",
"be",
"used",
"in",
"serializing",
"to",
"JSON"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/events/api_event.py#L42-L60 | train |
awslabs/aws-sam-cli | samcli/local/events/api_event.py | RequestContext.to_dict | def to_dict(self):
"""
Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON
:return: dict representing the object
"""
identity_dict = {}
if self.identity:
identity_dict = self.identity.to_dict()
json_dict = {"resourceId": self.resource_id,
"apiId": self.api_id,
"resourcePath": self.resource_path,
"httpMethod": self.http_method,
"requestId": self.request_id,
"accountId": self.account_id,
"stage": self.stage,
"identity": identity_dict,
"extendedRequestId": self.extended_request_id,
"path": self.path
}
return json_dict | python | def to_dict(self):
"""
Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON
:return: dict representing the object
"""
identity_dict = {}
if self.identity:
identity_dict = self.identity.to_dict()
json_dict = {"resourceId": self.resource_id,
"apiId": self.api_id,
"resourcePath": self.resource_path,
"httpMethod": self.http_method,
"requestId": self.request_id,
"accountId": self.account_id,
"stage": self.stage,
"identity": identity_dict,
"extendedRequestId": self.extended_request_id,
"path": self.path
}
return json_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"identity_dict",
"=",
"{",
"}",
"if",
"self",
".",
"identity",
":",
"identity_dict",
"=",
"self",
".",
"identity",
".",
"to_dict",
"(",
")",
"json_dict",
"=",
"{",
"\"resourceId\"",
":",
"self",
".",
"resource_id",
",",
"\"apiId\"",
":",
"self",
".",
"api_id",
",",
"\"resourcePath\"",
":",
"self",
".",
"resource_path",
",",
"\"httpMethod\"",
":",
"self",
".",
"http_method",
",",
"\"requestId\"",
":",
"self",
".",
"request_id",
",",
"\"accountId\"",
":",
"self",
".",
"account_id",
",",
"\"stage\"",
":",
"self",
".",
"stage",
",",
"\"identity\"",
":",
"identity_dict",
",",
"\"extendedRequestId\"",
":",
"self",
".",
"extended_request_id",
",",
"\"path\"",
":",
"self",
".",
"path",
"}",
"return",
"json_dict"
] | Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON
:return: dict representing the object | [
"Constructs",
"an",
"dictionary",
"representation",
"of",
"the",
"RequestContext",
"Object",
"to",
"be",
"used",
"in",
"serializing",
"to",
"JSON"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/events/api_event.py#L102-L124 | train |
awslabs/aws-sam-cli | samcli/local/events/api_event.py | ApiGatewayLambdaEvent.to_dict | def to_dict(self):
"""
Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON
:return: dict representing the object
"""
request_context_dict = {}
if self.request_context:
request_context_dict = self.request_context.to_dict()
json_dict = {"httpMethod": self.http_method,
"body": self.body if self.body else None,
"resource": self.resource,
"requestContext": request_context_dict,
"queryStringParameters": dict(self.query_string_params) if self.query_string_params else None,
"headers": dict(self.headers) if self.headers else None,
"pathParameters": dict(self.path_parameters) if self.path_parameters else None,
"stageVariables": dict(self.stage_variables) if self.stage_variables else None,
"path": self.path,
"isBase64Encoded": self.is_base_64_encoded
}
return json_dict | python | def to_dict(self):
"""
Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON
:return: dict representing the object
"""
request_context_dict = {}
if self.request_context:
request_context_dict = self.request_context.to_dict()
json_dict = {"httpMethod": self.http_method,
"body": self.body if self.body else None,
"resource": self.resource,
"requestContext": request_context_dict,
"queryStringParameters": dict(self.query_string_params) if self.query_string_params else None,
"headers": dict(self.headers) if self.headers else None,
"pathParameters": dict(self.path_parameters) if self.path_parameters else None,
"stageVariables": dict(self.stage_variables) if self.stage_variables else None,
"path": self.path,
"isBase64Encoded": self.is_base_64_encoded
}
return json_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"request_context_dict",
"=",
"{",
"}",
"if",
"self",
".",
"request_context",
":",
"request_context_dict",
"=",
"self",
".",
"request_context",
".",
"to_dict",
"(",
")",
"json_dict",
"=",
"{",
"\"httpMethod\"",
":",
"self",
".",
"http_method",
",",
"\"body\"",
":",
"self",
".",
"body",
"if",
"self",
".",
"body",
"else",
"None",
",",
"\"resource\"",
":",
"self",
".",
"resource",
",",
"\"requestContext\"",
":",
"request_context_dict",
",",
"\"queryStringParameters\"",
":",
"dict",
"(",
"self",
".",
"query_string_params",
")",
"if",
"self",
".",
"query_string_params",
"else",
"None",
",",
"\"headers\"",
":",
"dict",
"(",
"self",
".",
"headers",
")",
"if",
"self",
".",
"headers",
"else",
"None",
",",
"\"pathParameters\"",
":",
"dict",
"(",
"self",
".",
"path_parameters",
")",
"if",
"self",
".",
"path_parameters",
"else",
"None",
",",
"\"stageVariables\"",
":",
"dict",
"(",
"self",
".",
"stage_variables",
")",
"if",
"self",
".",
"stage_variables",
"else",
"None",
",",
"\"path\"",
":",
"self",
".",
"path",
",",
"\"isBase64Encoded\"",
":",
"self",
".",
"is_base_64_encoded",
"}",
"return",
"json_dict"
] | Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON
:return: dict representing the object | [
"Constructs",
"an",
"dictionary",
"representation",
"of",
"the",
"ApiGatewayLambdaEvent",
"Object",
"to",
"be",
"used",
"in",
"serializing",
"to",
"JSON"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/events/api_event.py#L179-L201 | train |
awslabs/aws-sam-cli | samcli/commands/logs/command.py | do_cli | def do_cli(function_name, stack_name, filter_pattern, tailing, start_time, end_time):
"""
Implementation of the ``cli`` method
"""
LOG.debug("'logs' command is called")
with LogsCommandContext(function_name,
stack_name=stack_name,
filter_pattern=filter_pattern,
start_time=start_time,
end_time=end_time,
# output_file is not yet supported by CLI
output_file=None) as context:
if tailing:
events_iterable = context.fetcher.tail(context.log_group_name,
filter_pattern=context.filter_pattern,
start=context.start_time)
else:
events_iterable = context.fetcher.fetch(context.log_group_name,
filter_pattern=context.filter_pattern,
start=context.start_time,
end=context.end_time)
formatted_events = context.formatter.do_format(events_iterable)
for event in formatted_events:
# New line is not necessary. It is already in the log events sent by CloudWatch
click.echo(event, nl=False) | python | def do_cli(function_name, stack_name, filter_pattern, tailing, start_time, end_time):
"""
Implementation of the ``cli`` method
"""
LOG.debug("'logs' command is called")
with LogsCommandContext(function_name,
stack_name=stack_name,
filter_pattern=filter_pattern,
start_time=start_time,
end_time=end_time,
# output_file is not yet supported by CLI
output_file=None) as context:
if tailing:
events_iterable = context.fetcher.tail(context.log_group_name,
filter_pattern=context.filter_pattern,
start=context.start_time)
else:
events_iterable = context.fetcher.fetch(context.log_group_name,
filter_pattern=context.filter_pattern,
start=context.start_time,
end=context.end_time)
formatted_events = context.formatter.do_format(events_iterable)
for event in formatted_events:
# New line is not necessary. It is already in the log events sent by CloudWatch
click.echo(event, nl=False) | [
"def",
"do_cli",
"(",
"function_name",
",",
"stack_name",
",",
"filter_pattern",
",",
"tailing",
",",
"start_time",
",",
"end_time",
")",
":",
"LOG",
".",
"debug",
"(",
"\"'logs' command is called\"",
")",
"with",
"LogsCommandContext",
"(",
"function_name",
",",
"stack_name",
"=",
"stack_name",
",",
"filter_pattern",
"=",
"filter_pattern",
",",
"start_time",
"=",
"start_time",
",",
"end_time",
"=",
"end_time",
",",
"# output_file is not yet supported by CLI",
"output_file",
"=",
"None",
")",
"as",
"context",
":",
"if",
"tailing",
":",
"events_iterable",
"=",
"context",
".",
"fetcher",
".",
"tail",
"(",
"context",
".",
"log_group_name",
",",
"filter_pattern",
"=",
"context",
".",
"filter_pattern",
",",
"start",
"=",
"context",
".",
"start_time",
")",
"else",
":",
"events_iterable",
"=",
"context",
".",
"fetcher",
".",
"fetch",
"(",
"context",
".",
"log_group_name",
",",
"filter_pattern",
"=",
"context",
".",
"filter_pattern",
",",
"start",
"=",
"context",
".",
"start_time",
",",
"end",
"=",
"context",
".",
"end_time",
")",
"formatted_events",
"=",
"context",
".",
"formatter",
".",
"do_format",
"(",
"events_iterable",
")",
"for",
"event",
"in",
"formatted_events",
":",
"# New line is not necessary. It is already in the log events sent by CloudWatch",
"click",
".",
"echo",
"(",
"event",
",",
"nl",
"=",
"False",
")"
] | Implementation of the ``cli`` method | [
"Implementation",
"of",
"the",
"cli",
"method"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/logs/command.py#L76-L105 | train |
awslabs/aws-sam-cli | samcli/local/docker/manager.py | ContainerManager.is_docker_reachable | def is_docker_reachable(self):
"""
Checks if Docker daemon is running. This is required for us to invoke the function locally
Returns
-------
bool
True, if Docker is available, False otherwise
"""
try:
self.docker_client.ping()
return True
# When Docker is not installed, a request.exceptions.ConnectionError is thrown.
except (docker.errors.APIError, requests.exceptions.ConnectionError):
LOG.debug("Docker is not reachable", exc_info=True)
return False | python | def is_docker_reachable(self):
"""
Checks if Docker daemon is running. This is required for us to invoke the function locally
Returns
-------
bool
True, if Docker is available, False otherwise
"""
try:
self.docker_client.ping()
return True
# When Docker is not installed, a request.exceptions.ConnectionError is thrown.
except (docker.errors.APIError, requests.exceptions.ConnectionError):
LOG.debug("Docker is not reachable", exc_info=True)
return False | [
"def",
"is_docker_reachable",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"docker_client",
".",
"ping",
"(",
")",
"return",
"True",
"# When Docker is not installed, a request.exceptions.ConnectionError is thrown.",
"except",
"(",
"docker",
".",
"errors",
".",
"APIError",
",",
"requests",
".",
"exceptions",
".",
"ConnectionError",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Docker is not reachable\"",
",",
"exc_info",
"=",
"True",
")",
"return",
"False"
] | Checks if Docker daemon is running. This is required for us to invoke the function locally
Returns
-------
bool
True, if Docker is available, False otherwise | [
"Checks",
"if",
"Docker",
"daemon",
"is",
"running",
".",
"This",
"is",
"required",
"for",
"us",
"to",
"invoke",
"the",
"function",
"locally"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/manager.py#L40-L57 | train |
awslabs/aws-sam-cli | samcli/local/docker/manager.py | ContainerManager.run | def run(self, container, input_data=None, warm=False):
"""
Create and run a Docker container based on the given configuration.
:param samcli.local.docker.container.Container container: Container to create and run
:param input_data: Optional. Input data sent to the container through container's stdin.
:param bool warm: Indicates if an existing container can be reused. Defaults False ie. a new container will
be created for every request.
:raises DockerImagePullFailedException: If the Docker image was not available in the server
"""
if warm:
raise ValueError("The facility to invoke warm container does not exist")
image_name = container.image
is_image_local = self.has_image(image_name)
# Skip Pulling a new image if: a) Image name is samcli/lambda OR b) Image is available AND
# c) We are asked to skip pulling the image
if (is_image_local and self.skip_pull_image) or image_name.startswith('samcli/lambda'):
LOG.info("Requested to skip pulling images ...\n")
else:
try:
self.pull_image(image_name)
except DockerImagePullFailedException:
if not is_image_local:
raise DockerImagePullFailedException(
"Could not find {} image locally and failed to pull it from docker.".format(image_name))
LOG.info(
"Failed to download a new %s image. Invoking with the already downloaded image.", image_name)
if not container.is_created():
# Create the container first before running.
# Create the container in appropriate Docker network
container.network_id = self.docker_network_id
container.create()
container.start(input_data=input_data) | python | def run(self, container, input_data=None, warm=False):
"""
Create and run a Docker container based on the given configuration.
:param samcli.local.docker.container.Container container: Container to create and run
:param input_data: Optional. Input data sent to the container through container's stdin.
:param bool warm: Indicates if an existing container can be reused. Defaults False ie. a new container will
be created for every request.
:raises DockerImagePullFailedException: If the Docker image was not available in the server
"""
if warm:
raise ValueError("The facility to invoke warm container does not exist")
image_name = container.image
is_image_local = self.has_image(image_name)
# Skip Pulling a new image if: a) Image name is samcli/lambda OR b) Image is available AND
# c) We are asked to skip pulling the image
if (is_image_local and self.skip_pull_image) or image_name.startswith('samcli/lambda'):
LOG.info("Requested to skip pulling images ...\n")
else:
try:
self.pull_image(image_name)
except DockerImagePullFailedException:
if not is_image_local:
raise DockerImagePullFailedException(
"Could not find {} image locally and failed to pull it from docker.".format(image_name))
LOG.info(
"Failed to download a new %s image. Invoking with the already downloaded image.", image_name)
if not container.is_created():
# Create the container first before running.
# Create the container in appropriate Docker network
container.network_id = self.docker_network_id
container.create()
container.start(input_data=input_data) | [
"def",
"run",
"(",
"self",
",",
"container",
",",
"input_data",
"=",
"None",
",",
"warm",
"=",
"False",
")",
":",
"if",
"warm",
":",
"raise",
"ValueError",
"(",
"\"The facility to invoke warm container does not exist\"",
")",
"image_name",
"=",
"container",
".",
"image",
"is_image_local",
"=",
"self",
".",
"has_image",
"(",
"image_name",
")",
"# Skip Pulling a new image if: a) Image name is samcli/lambda OR b) Image is available AND",
"# c) We are asked to skip pulling the image",
"if",
"(",
"is_image_local",
"and",
"self",
".",
"skip_pull_image",
")",
"or",
"image_name",
".",
"startswith",
"(",
"'samcli/lambda'",
")",
":",
"LOG",
".",
"info",
"(",
"\"Requested to skip pulling images ...\\n\"",
")",
"else",
":",
"try",
":",
"self",
".",
"pull_image",
"(",
"image_name",
")",
"except",
"DockerImagePullFailedException",
":",
"if",
"not",
"is_image_local",
":",
"raise",
"DockerImagePullFailedException",
"(",
"\"Could not find {} image locally and failed to pull it from docker.\"",
".",
"format",
"(",
"image_name",
")",
")",
"LOG",
".",
"info",
"(",
"\"Failed to download a new %s image. Invoking with the already downloaded image.\"",
",",
"image_name",
")",
"if",
"not",
"container",
".",
"is_created",
"(",
")",
":",
"# Create the container first before running.",
"# Create the container in appropriate Docker network",
"container",
".",
"network_id",
"=",
"self",
".",
"docker_network_id",
"container",
".",
"create",
"(",
")",
"container",
".",
"start",
"(",
"input_data",
"=",
"input_data",
")"
] | Create and run a Docker container based on the given configuration.
:param samcli.local.docker.container.Container container: Container to create and run
:param input_data: Optional. Input data sent to the container through container's stdin.
:param bool warm: Indicates if an existing container can be reused. Defaults False ie. a new container will
be created for every request.
:raises DockerImagePullFailedException: If the Docker image was not available in the server | [
"Create",
"and",
"run",
"a",
"Docker",
"container",
"based",
"on",
"the",
"given",
"configuration",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/manager.py#L59-L98 | train |
awslabs/aws-sam-cli | samcli/local/docker/manager.py | ContainerManager.pull_image | def pull_image(self, image_name, stream=None):
"""
Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output to. Defaults to stderr
Raises
------
DockerImagePullFailedException
If the Docker image was not available in the server
"""
stream_writer = stream or StreamWriter(sys.stderr)
try:
result_itr = self.docker_client.api.pull(image_name, stream=True, decode=True)
except docker.errors.APIError as ex:
LOG.debug("Failed to download image with name %s", image_name)
raise DockerImagePullFailedException(str(ex))
# io streams, especially StringIO, work only with unicode strings
stream_writer.write(u"\nFetching {} Docker container image...".format(image_name))
# Each line contains information on progress of the pull. Each line is a JSON string
for _ in result_itr:
# For every line, print a dot to show progress
stream_writer.write(u'.')
stream_writer.flush()
# We are done. Go to the next line
stream_writer.write(u"\n") | python | def pull_image(self, image_name, stream=None):
"""
Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output to. Defaults to stderr
Raises
------
DockerImagePullFailedException
If the Docker image was not available in the server
"""
stream_writer = stream or StreamWriter(sys.stderr)
try:
result_itr = self.docker_client.api.pull(image_name, stream=True, decode=True)
except docker.errors.APIError as ex:
LOG.debug("Failed to download image with name %s", image_name)
raise DockerImagePullFailedException(str(ex))
# io streams, especially StringIO, work only with unicode strings
stream_writer.write(u"\nFetching {} Docker container image...".format(image_name))
# Each line contains information on progress of the pull. Each line is a JSON string
for _ in result_itr:
# For every line, print a dot to show progress
stream_writer.write(u'.')
stream_writer.flush()
# We are done. Go to the next line
stream_writer.write(u"\n") | [
"def",
"pull_image",
"(",
"self",
",",
"image_name",
",",
"stream",
"=",
"None",
")",
":",
"stream_writer",
"=",
"stream",
"or",
"StreamWriter",
"(",
"sys",
".",
"stderr",
")",
"try",
":",
"result_itr",
"=",
"self",
".",
"docker_client",
".",
"api",
".",
"pull",
"(",
"image_name",
",",
"stream",
"=",
"True",
",",
"decode",
"=",
"True",
")",
"except",
"docker",
".",
"errors",
".",
"APIError",
"as",
"ex",
":",
"LOG",
".",
"debug",
"(",
"\"Failed to download image with name %s\"",
",",
"image_name",
")",
"raise",
"DockerImagePullFailedException",
"(",
"str",
"(",
"ex",
")",
")",
"# io streams, especially StringIO, work only with unicode strings",
"stream_writer",
".",
"write",
"(",
"u\"\\nFetching {} Docker container image...\"",
".",
"format",
"(",
"image_name",
")",
")",
"# Each line contains information on progress of the pull. Each line is a JSON string",
"for",
"_",
"in",
"result_itr",
":",
"# For every line, print a dot to show progress",
"stream_writer",
".",
"write",
"(",
"u'.'",
")",
"stream_writer",
".",
"flush",
"(",
")",
"# We are done. Go to the next line",
"stream_writer",
".",
"write",
"(",
"u\"\\n\"",
")"
] | Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output to. Defaults to stderr
Raises
------
DockerImagePullFailedException
If the Docker image was not available in the server | [
"Ask",
"Docker",
"to",
"pull",
"the",
"container",
"image",
"with",
"given",
"name",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/manager.py#L108-L142 | train |
awslabs/aws-sam-cli | samcli/local/docker/manager.py | ContainerManager.has_image | def has_image(self, image_name):
"""
Is the container image with given name available?
:param string image_name: Name of the image
:return bool: True, if image is available. False, otherwise
"""
try:
self.docker_client.images.get(image_name)
return True
except docker.errors.ImageNotFound:
return False | python | def has_image(self, image_name):
"""
Is the container image with given name available?
:param string image_name: Name of the image
:return bool: True, if image is available. False, otherwise
"""
try:
self.docker_client.images.get(image_name)
return True
except docker.errors.ImageNotFound:
return False | [
"def",
"has_image",
"(",
"self",
",",
"image_name",
")",
":",
"try",
":",
"self",
".",
"docker_client",
".",
"images",
".",
"get",
"(",
"image_name",
")",
"return",
"True",
"except",
"docker",
".",
"errors",
".",
"ImageNotFound",
":",
"return",
"False"
] | Is the container image with given name available?
:param string image_name: Name of the image
:return bool: True, if image is available. False, otherwise | [
"Is",
"the",
"container",
"image",
"with",
"given",
"name",
"available?"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/manager.py#L144-L156 | train |
awslabs/aws-sam-cli | samcli/commands/publish/command.py | do_cli | def do_cli(ctx, template, semantic_version):
"""Publish the application based on command line inputs."""
try:
template_data = get_template_data(template)
except ValueError as ex:
click.secho("Publish Failed", fg='red')
raise UserException(str(ex))
# Override SemanticVersion in template metadata when provided in command input
if semantic_version and SERVERLESS_REPO_APPLICATION in template_data.get(METADATA, {}):
template_data.get(METADATA).get(SERVERLESS_REPO_APPLICATION)[SEMANTIC_VERSION] = semantic_version
try:
publish_output = publish_application(template_data)
click.secho("Publish Succeeded", fg="green")
click.secho(_gen_success_message(publish_output))
except InvalidS3UriError:
click.secho("Publish Failed", fg='red')
raise UserException(
"Your SAM template contains invalid S3 URIs. Please make sure that you have uploaded application "
"artifacts to S3 by packaging the template. See more details in {}".format(SAM_PACKAGE_DOC))
except ServerlessRepoError as ex:
click.secho("Publish Failed", fg='red')
LOG.debug("Failed to publish application to serverlessrepo", exc_info=True)
error_msg = '{}\nPlease follow the instructions in {}'.format(str(ex), SAM_PUBLISH_DOC)
raise UserException(error_msg)
application_id = publish_output.get('application_id')
_print_console_link(ctx.region, application_id) | python | def do_cli(ctx, template, semantic_version):
"""Publish the application based on command line inputs."""
try:
template_data = get_template_data(template)
except ValueError as ex:
click.secho("Publish Failed", fg='red')
raise UserException(str(ex))
# Override SemanticVersion in template metadata when provided in command input
if semantic_version and SERVERLESS_REPO_APPLICATION in template_data.get(METADATA, {}):
template_data.get(METADATA).get(SERVERLESS_REPO_APPLICATION)[SEMANTIC_VERSION] = semantic_version
try:
publish_output = publish_application(template_data)
click.secho("Publish Succeeded", fg="green")
click.secho(_gen_success_message(publish_output))
except InvalidS3UriError:
click.secho("Publish Failed", fg='red')
raise UserException(
"Your SAM template contains invalid S3 URIs. Please make sure that you have uploaded application "
"artifacts to S3 by packaging the template. See more details in {}".format(SAM_PACKAGE_DOC))
except ServerlessRepoError as ex:
click.secho("Publish Failed", fg='red')
LOG.debug("Failed to publish application to serverlessrepo", exc_info=True)
error_msg = '{}\nPlease follow the instructions in {}'.format(str(ex), SAM_PUBLISH_DOC)
raise UserException(error_msg)
application_id = publish_output.get('application_id')
_print_console_link(ctx.region, application_id) | [
"def",
"do_cli",
"(",
"ctx",
",",
"template",
",",
"semantic_version",
")",
":",
"try",
":",
"template_data",
"=",
"get_template_data",
"(",
"template",
")",
"except",
"ValueError",
"as",
"ex",
":",
"click",
".",
"secho",
"(",
"\"Publish Failed\"",
",",
"fg",
"=",
"'red'",
")",
"raise",
"UserException",
"(",
"str",
"(",
"ex",
")",
")",
"# Override SemanticVersion in template metadata when provided in command input",
"if",
"semantic_version",
"and",
"SERVERLESS_REPO_APPLICATION",
"in",
"template_data",
".",
"get",
"(",
"METADATA",
",",
"{",
"}",
")",
":",
"template_data",
".",
"get",
"(",
"METADATA",
")",
".",
"get",
"(",
"SERVERLESS_REPO_APPLICATION",
")",
"[",
"SEMANTIC_VERSION",
"]",
"=",
"semantic_version",
"try",
":",
"publish_output",
"=",
"publish_application",
"(",
"template_data",
")",
"click",
".",
"secho",
"(",
"\"Publish Succeeded\"",
",",
"fg",
"=",
"\"green\"",
")",
"click",
".",
"secho",
"(",
"_gen_success_message",
"(",
"publish_output",
")",
")",
"except",
"InvalidS3UriError",
":",
"click",
".",
"secho",
"(",
"\"Publish Failed\"",
",",
"fg",
"=",
"'red'",
")",
"raise",
"UserException",
"(",
"\"Your SAM template contains invalid S3 URIs. Please make sure that you have uploaded application \"",
"\"artifacts to S3 by packaging the template. See more details in {}\"",
".",
"format",
"(",
"SAM_PACKAGE_DOC",
")",
")",
"except",
"ServerlessRepoError",
"as",
"ex",
":",
"click",
".",
"secho",
"(",
"\"Publish Failed\"",
",",
"fg",
"=",
"'red'",
")",
"LOG",
".",
"debug",
"(",
"\"Failed to publish application to serverlessrepo\"",
",",
"exc_info",
"=",
"True",
")",
"error_msg",
"=",
"'{}\\nPlease follow the instructions in {}'",
".",
"format",
"(",
"str",
"(",
"ex",
")",
",",
"SAM_PUBLISH_DOC",
")",
"raise",
"UserException",
"(",
"error_msg",
")",
"application_id",
"=",
"publish_output",
".",
"get",
"(",
"'application_id'",
")",
"_print_console_link",
"(",
"ctx",
".",
"region",
",",
"application_id",
")"
] | Publish the application based on command line inputs. | [
"Publish",
"the",
"application",
"based",
"on",
"command",
"line",
"inputs",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/publish/command.py#L55-L83 | train |
awslabs/aws-sam-cli | samcli/commands/publish/command.py | _gen_success_message | def _gen_success_message(publish_output):
"""
Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message
"""
application_id = publish_output.get('application_id')
details = json.dumps(publish_output.get('details'), indent=2)
if CREATE_APPLICATION in publish_output.get('actions'):
return "Created new application with the following metadata:\n{}".format(details)
return 'The following metadata of application "{}" has been updated:\n{}'.format(application_id, details) | python | def _gen_success_message(publish_output):
"""
Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message
"""
application_id = publish_output.get('application_id')
details = json.dumps(publish_output.get('details'), indent=2)
if CREATE_APPLICATION in publish_output.get('actions'):
return "Created new application with the following metadata:\n{}".format(details)
return 'The following metadata of application "{}" has been updated:\n{}'.format(application_id, details) | [
"def",
"_gen_success_message",
"(",
"publish_output",
")",
":",
"application_id",
"=",
"publish_output",
".",
"get",
"(",
"'application_id'",
")",
"details",
"=",
"json",
".",
"dumps",
"(",
"publish_output",
".",
"get",
"(",
"'details'",
")",
",",
"indent",
"=",
"2",
")",
"if",
"CREATE_APPLICATION",
"in",
"publish_output",
".",
"get",
"(",
"'actions'",
")",
":",
"return",
"\"Created new application with the following metadata:\\n{}\"",
".",
"format",
"(",
"details",
")",
"return",
"'The following metadata of application \"{}\" has been updated:\\n{}'",
".",
"format",
"(",
"application_id",
",",
"details",
")"
] | Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message | [
"Generate",
"detailed",
"success",
"message",
"for",
"published",
"applications",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/publish/command.py#L86-L106 | train |
awslabs/aws-sam-cli | samcli/commands/publish/command.py | _print_console_link | def _print_console_link(region, application_id):
"""
Print link for the application in AWS Serverless Application Repository console.
Parameters
----------
region : str
AWS region name
application_id : str
The Amazon Resource Name (ARN) of the application
"""
if not region:
region = boto3.Session().region_name
console_link = SERVERLESSREPO_CONSOLE_URL.format(region, application_id.replace('/', '~'))
msg = "Click the link below to view your application in AWS console:\n{}".format(console_link)
click.secho(msg, fg="yellow") | python | def _print_console_link(region, application_id):
"""
Print link for the application in AWS Serverless Application Repository console.
Parameters
----------
region : str
AWS region name
application_id : str
The Amazon Resource Name (ARN) of the application
"""
if not region:
region = boto3.Session().region_name
console_link = SERVERLESSREPO_CONSOLE_URL.format(region, application_id.replace('/', '~'))
msg = "Click the link below to view your application in AWS console:\n{}".format(console_link)
click.secho(msg, fg="yellow") | [
"def",
"_print_console_link",
"(",
"region",
",",
"application_id",
")",
":",
"if",
"not",
"region",
":",
"region",
"=",
"boto3",
".",
"Session",
"(",
")",
".",
"region_name",
"console_link",
"=",
"SERVERLESSREPO_CONSOLE_URL",
".",
"format",
"(",
"region",
",",
"application_id",
".",
"replace",
"(",
"'/'",
",",
"'~'",
")",
")",
"msg",
"=",
"\"Click the link below to view your application in AWS console:\\n{}\"",
".",
"format",
"(",
"console_link",
")",
"click",
".",
"secho",
"(",
"msg",
",",
"fg",
"=",
"\"yellow\"",
")"
] | Print link for the application in AWS Serverless Application Repository console.
Parameters
----------
region : str
AWS region name
application_id : str
The Amazon Resource Name (ARN) of the application | [
"Print",
"link",
"for",
"the",
"application",
"in",
"AWS",
"Serverless",
"Application",
"Repository",
"console",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/publish/command.py#L109-L126 | train |
awslabs/aws-sam-cli | samcli/local/apigw/service_error_responses.py | ServiceErrorResponses.lambda_failure_response | def lambda_failure_response(*args):
"""
Helper function to create a Lambda Failure Response
:return: A Flask Response
"""
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | python | def lambda_failure_response(*args):
"""
Helper function to create a Lambda Failure Response
:return: A Flask Response
"""
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | [
"def",
"lambda_failure_response",
"(",
"*",
"args",
")",
":",
"response_data",
"=",
"jsonify",
"(",
"ServiceErrorResponses",
".",
"_LAMBDA_FAILURE",
")",
"return",
"make_response",
"(",
"response_data",
",",
"ServiceErrorResponses",
".",
"HTTP_STATUS_CODE_502",
")"
] | Helper function to create a Lambda Failure Response
:return: A Flask Response | [
"Helper",
"function",
"to",
"create",
"a",
"Lambda",
"Failure",
"Response"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/service_error_responses.py#L16-L23 | train |
awslabs/aws-sam-cli | samcli/local/apigw/service_error_responses.py | ServiceErrorResponses.lambda_not_found_response | def lambda_not_found_response(*args):
"""
Constructs a Flask Response for when a Lambda function is not found for an endpoint
:return: a Flask Response
"""
response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | python | def lambda_not_found_response(*args):
"""
Constructs a Flask Response for when a Lambda function is not found for an endpoint
:return: a Flask Response
"""
response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | [
"def",
"lambda_not_found_response",
"(",
"*",
"args",
")",
":",
"response_data",
"=",
"jsonify",
"(",
"ServiceErrorResponses",
".",
"_NO_LAMBDA_INTEGRATION",
")",
"return",
"make_response",
"(",
"response_data",
",",
"ServiceErrorResponses",
".",
"HTTP_STATUS_CODE_502",
")"
] | Constructs a Flask Response for when a Lambda function is not found for an endpoint
:return: a Flask Response | [
"Constructs",
"a",
"Flask",
"Response",
"for",
"when",
"a",
"Lambda",
"function",
"is",
"not",
"found",
"for",
"an",
"endpoint"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/service_error_responses.py#L26-L33 | train |
awslabs/aws-sam-cli | samcli/local/apigw/service_error_responses.py | ServiceErrorResponses.route_not_found | def route_not_found(*args):
"""
Constructs a Flask Response for when a API Route (path+method) is not found. This is usually
HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840)
:return: a Flask Response
"""
response_data = jsonify(ServiceErrorResponses._MISSING_AUTHENTICATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_403) | python | def route_not_found(*args):
"""
Constructs a Flask Response for when a API Route (path+method) is not found. This is usually
HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840)
:return: a Flask Response
"""
response_data = jsonify(ServiceErrorResponses._MISSING_AUTHENTICATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_403) | [
"def",
"route_not_found",
"(",
"*",
"args",
")",
":",
"response_data",
"=",
"jsonify",
"(",
"ServiceErrorResponses",
".",
"_MISSING_AUTHENTICATION",
")",
"return",
"make_response",
"(",
"response_data",
",",
"ServiceErrorResponses",
".",
"HTTP_STATUS_CODE_403",
")"
] | Constructs a Flask Response for when a API Route (path+method) is not found. This is usually
HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840)
:return: a Flask Response | [
"Constructs",
"a",
"Flask",
"Response",
"for",
"when",
"a",
"API",
"Route",
"(",
"path",
"+",
"method",
")",
"is",
"not",
"found",
".",
"This",
"is",
"usually",
"HTTP",
"404",
"but",
"with",
"API",
"Gateway",
"this",
"is",
"a",
"HTTP",
"403",
"(",
"https",
":",
"//",
"forums",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"thread",
".",
"jspa?threadID",
"=",
"2166840",
")"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/service_error_responses.py#L36-L44 | train |
awslabs/aws-sam-cli | samcli/lib/utils/progressbar.py | progressbar | def progressbar(length, label):
"""
Creates a progressbar
Parameters
----------
length int
Length of the ProgressBar
label str
Label to give to the progressbar
Returns
-------
click.progressbar
Progressbar
"""
return click.progressbar(length=length, label=label, show_pos=True) | python | def progressbar(length, label):
"""
Creates a progressbar
Parameters
----------
length int
Length of the ProgressBar
label str
Label to give to the progressbar
Returns
-------
click.progressbar
Progressbar
"""
return click.progressbar(length=length, label=label, show_pos=True) | [
"def",
"progressbar",
"(",
"length",
",",
"label",
")",
":",
"return",
"click",
".",
"progressbar",
"(",
"length",
"=",
"length",
",",
"label",
"=",
"label",
",",
"show_pos",
"=",
"True",
")"
] | Creates a progressbar
Parameters
----------
length int
Length of the ProgressBar
label str
Label to give to the progressbar
Returns
-------
click.progressbar
Progressbar | [
"Creates",
"a",
"progressbar"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/utils/progressbar.py#L8-L25 | train |
awslabs/aws-sam-cli | samcli/cli/types.py | CfnParameterOverridesType._unquote | def _unquote(value):
r"""
Removes wrapping double quotes and any '\ ' characters. They are usually added to preserve spaces when passing
value thru shell.
Examples
--------
>>> _unquote('val\ ue')
value
>>> _unquote("hel\ lo")
hello
Parameters
----------
value : str
Input to unquote
Returns
-------
Unquoted string
"""
if value and (value[0] == value[-1] == '"'):
# Remove quotes only if the string is wrapped in quotes
value = value.strip('"')
return value.replace("\\ ", " ").replace('\\"', '"') | python | def _unquote(value):
r"""
Removes wrapping double quotes and any '\ ' characters. They are usually added to preserve spaces when passing
value thru shell.
Examples
--------
>>> _unquote('val\ ue')
value
>>> _unquote("hel\ lo")
hello
Parameters
----------
value : str
Input to unquote
Returns
-------
Unquoted string
"""
if value and (value[0] == value[-1] == '"'):
# Remove quotes only if the string is wrapped in quotes
value = value.strip('"')
return value.replace("\\ ", " ").replace('\\"', '"') | [
"def",
"_unquote",
"(",
"value",
")",
":",
"if",
"value",
"and",
"(",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
")",
":",
"# Remove quotes only if the string is wrapped in quotes",
"value",
"=",
"value",
".",
"strip",
"(",
"'\"'",
")",
"return",
"value",
".",
"replace",
"(",
"\"\\\\ \"",
",",
"\" \"",
")",
".",
"replace",
"(",
"'\\\\\"'",
",",
"'\"'",
")"
] | r"""
Removes wrapping double quotes and any '\ ' characters. They are usually added to preserve spaces when passing
value thru shell.
Examples
--------
>>> _unquote('val\ ue')
value
>>> _unquote("hel\ lo")
hello
Parameters
----------
value : str
Input to unquote
Returns
-------
Unquoted string | [
"r",
"Removes",
"wrapping",
"double",
"quotes",
"and",
"any",
"\\",
"characters",
".",
"They",
"are",
"usually",
"added",
"to",
"preserve",
"spaces",
"when",
"passing",
"value",
"thru",
"shell",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/cli/types.py#L42-L68 | train |
awslabs/aws-sam-cli | samcli/local/services/base_local_service.py | BaseLocalService.run | def run(self):
"""
This starts up the (threaded) Local Server.
Note: This is a **blocking call**
Raises
------
RuntimeError
if the service was not created
"""
if not self._app:
raise RuntimeError("The application must be created before running")
# Flask can operate as a single threaded server (which is default) and a multi-threaded server which is
# more for development. When the Lambda container is going to be debugged, then it does not make sense
# to turn on multi-threading because customers can realistically attach only one container at a time to
# the debugger. Keeping this single threaded also enables the Lambda Runner to handle Ctrl+C in order to
# kill the container gracefully (Ctrl+C can be handled only by the main thread)
multi_threaded = not self.is_debugging
LOG.debug("Localhost server is starting up. Multi-threading = %s", multi_threaded)
# This environ signifies we are running a main function for Flask. This is true, since we are using it within
# our cli and not on a production server.
os.environ['WERKZEUG_RUN_MAIN'] = 'true'
self._app.run(threaded=multi_threaded, host=self.host, port=self.port) | python | def run(self):
"""
This starts up the (threaded) Local Server.
Note: This is a **blocking call**
Raises
------
RuntimeError
if the service was not created
"""
if not self._app:
raise RuntimeError("The application must be created before running")
# Flask can operate as a single threaded server (which is default) and a multi-threaded server which is
# more for development. When the Lambda container is going to be debugged, then it does not make sense
# to turn on multi-threading because customers can realistically attach only one container at a time to
# the debugger. Keeping this single threaded also enables the Lambda Runner to handle Ctrl+C in order to
# kill the container gracefully (Ctrl+C can be handled only by the main thread)
multi_threaded = not self.is_debugging
LOG.debug("Localhost server is starting up. Multi-threading = %s", multi_threaded)
# This environ signifies we are running a main function for Flask. This is true, since we are using it within
# our cli and not on a production server.
os.environ['WERKZEUG_RUN_MAIN'] = 'true'
self._app.run(threaded=multi_threaded, host=self.host, port=self.port) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_app",
":",
"raise",
"RuntimeError",
"(",
"\"The application must be created before running\"",
")",
"# Flask can operate as a single threaded server (which is default) and a multi-threaded server which is",
"# more for development. When the Lambda container is going to be debugged, then it does not make sense",
"# to turn on multi-threading because customers can realistically attach only one container at a time to",
"# the debugger. Keeping this single threaded also enables the Lambda Runner to handle Ctrl+C in order to",
"# kill the container gracefully (Ctrl+C can be handled only by the main thread)",
"multi_threaded",
"=",
"not",
"self",
".",
"is_debugging",
"LOG",
".",
"debug",
"(",
"\"Localhost server is starting up. Multi-threading = %s\"",
",",
"multi_threaded",
")",
"# This environ signifies we are running a main function for Flask. This is true, since we are using it within",
"# our cli and not on a production server.",
"os",
".",
"environ",
"[",
"'WERKZEUG_RUN_MAIN'",
"]",
"=",
"'true'",
"self",
".",
"_app",
".",
"run",
"(",
"threaded",
"=",
"multi_threaded",
",",
"host",
"=",
"self",
".",
"host",
",",
"port",
"=",
"self",
".",
"port",
")"
] | This starts up the (threaded) Local Server.
Note: This is a **blocking call**
Raises
------
RuntimeError
if the service was not created | [
"This",
"starts",
"up",
"the",
"(",
"threaded",
")",
"Local",
"Server",
".",
"Note",
":",
"This",
"is",
"a",
"**",
"blocking",
"call",
"**"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/services/base_local_service.py#L55-L81 | train |
awslabs/aws-sam-cli | samcli/local/services/base_local_service.py | BaseLocalService.service_response | def service_response(body, headers, status_code):
"""
Constructs a Flask Response from the body, headers, and status_code.
:param str body: Response body as a string
:param dict headers: headers for the response
:param int status_code: status_code for response
:return: Flask Response
"""
response = Response(body)
response.headers = headers
response.status_code = status_code
return response | python | def service_response(body, headers, status_code):
"""
Constructs a Flask Response from the body, headers, and status_code.
:param str body: Response body as a string
:param dict headers: headers for the response
:param int status_code: status_code for response
:return: Flask Response
"""
response = Response(body)
response.headers = headers
response.status_code = status_code
return response | [
"def",
"service_response",
"(",
"body",
",",
"headers",
",",
"status_code",
")",
":",
"response",
"=",
"Response",
"(",
"body",
")",
"response",
".",
"headers",
"=",
"headers",
"response",
".",
"status_code",
"=",
"status_code",
"return",
"response"
] | Constructs a Flask Response from the body, headers, and status_code.
:param str body: Response body as a string
:param dict headers: headers for the response
:param int status_code: status_code for response
:return: Flask Response | [
"Constructs",
"a",
"Flask",
"Response",
"from",
"the",
"body",
"headers",
"and",
"status_code",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/services/base_local_service.py#L84-L96 | train |
awslabs/aws-sam-cli | samcli/local/services/base_local_service.py | LambdaOutputParser.get_lambda_output | def get_lambda_output(stdout_stream):
"""
This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using System.out.println or equivalents.
Parameters
----------
stdout_stream : io.BaseIO
Stream to fetch data from
Returns
-------
str
String data containing response from Lambda function
str
String data containng logs statements, if any.
bool
If the response is an error/exception from the container
"""
# We only want the last line of stdout, because it's possible that
# the function may have written directly to stdout using
# System.out.println or similar, before docker-lambda output the result
stdout_data = stdout_stream.getvalue().rstrip(b'\n')
# Usually the output is just one line and contains response as JSON string, but if the Lambda function
# wrote anything directly to stdout, there will be additional lines. So just extract the last line as
# response and everything else as log output.
lambda_response = stdout_data
lambda_logs = None
last_line_position = stdout_data.rfind(b'\n')
if last_line_position >= 0:
# So there are multiple lines. Separate them out.
# Everything but the last line are logs
lambda_logs = stdout_data[:last_line_position]
# Last line is Lambda response. Make sure to strip() so we get rid of extra whitespaces & newlines around
lambda_response = stdout_data[last_line_position:].strip()
lambda_response = lambda_response.decode('utf-8')
# When the Lambda Function returns an Error/Exception, the output is added to the stdout of the container. From
# our perspective, the container returned some value, which is not always true. Since the output is the only
# information we have, we need to inspect this to understand if the container returned a some data or raised an
# error
is_lambda_user_error_response = LambdaOutputParser.is_lambda_error_response(lambda_response)
return lambda_response, lambda_logs, is_lambda_user_error_response | python | def get_lambda_output(stdout_stream):
"""
This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using System.out.println or equivalents.
Parameters
----------
stdout_stream : io.BaseIO
Stream to fetch data from
Returns
-------
str
String data containing response from Lambda function
str
String data containng logs statements, if any.
bool
If the response is an error/exception from the container
"""
# We only want the last line of stdout, because it's possible that
# the function may have written directly to stdout using
# System.out.println or similar, before docker-lambda output the result
stdout_data = stdout_stream.getvalue().rstrip(b'\n')
# Usually the output is just one line and contains response as JSON string, but if the Lambda function
# wrote anything directly to stdout, there will be additional lines. So just extract the last line as
# response and everything else as log output.
lambda_response = stdout_data
lambda_logs = None
last_line_position = stdout_data.rfind(b'\n')
if last_line_position >= 0:
# So there are multiple lines. Separate them out.
# Everything but the last line are logs
lambda_logs = stdout_data[:last_line_position]
# Last line is Lambda response. Make sure to strip() so we get rid of extra whitespaces & newlines around
lambda_response = stdout_data[last_line_position:].strip()
lambda_response = lambda_response.decode('utf-8')
# When the Lambda Function returns an Error/Exception, the output is added to the stdout of the container. From
# our perspective, the container returned some value, which is not always true. Since the output is the only
# information we have, we need to inspect this to understand if the container returned a some data or raised an
# error
is_lambda_user_error_response = LambdaOutputParser.is_lambda_error_response(lambda_response)
return lambda_response, lambda_logs, is_lambda_user_error_response | [
"def",
"get_lambda_output",
"(",
"stdout_stream",
")",
":",
"# We only want the last line of stdout, because it's possible that",
"# the function may have written directly to stdout using",
"# System.out.println or similar, before docker-lambda output the result",
"stdout_data",
"=",
"stdout_stream",
".",
"getvalue",
"(",
")",
".",
"rstrip",
"(",
"b'\\n'",
")",
"# Usually the output is just one line and contains response as JSON string, but if the Lambda function",
"# wrote anything directly to stdout, there will be additional lines. So just extract the last line as",
"# response and everything else as log output.",
"lambda_response",
"=",
"stdout_data",
"lambda_logs",
"=",
"None",
"last_line_position",
"=",
"stdout_data",
".",
"rfind",
"(",
"b'\\n'",
")",
"if",
"last_line_position",
">=",
"0",
":",
"# So there are multiple lines. Separate them out.",
"# Everything but the last line are logs",
"lambda_logs",
"=",
"stdout_data",
"[",
":",
"last_line_position",
"]",
"# Last line is Lambda response. Make sure to strip() so we get rid of extra whitespaces & newlines around",
"lambda_response",
"=",
"stdout_data",
"[",
"last_line_position",
":",
"]",
".",
"strip",
"(",
")",
"lambda_response",
"=",
"lambda_response",
".",
"decode",
"(",
"'utf-8'",
")",
"# When the Lambda Function returns an Error/Exception, the output is added to the stdout of the container. From",
"# our perspective, the container returned some value, which is not always true. Since the output is the only",
"# information we have, we need to inspect this to understand if the container returned a some data or raised an",
"# error",
"is_lambda_user_error_response",
"=",
"LambdaOutputParser",
".",
"is_lambda_error_response",
"(",
"lambda_response",
")",
"return",
"lambda_response",
",",
"lambda_logs",
",",
"is_lambda_user_error_response"
] | This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using System.out.println or equivalents.
Parameters
----------
stdout_stream : io.BaseIO
Stream to fetch data from
Returns
-------
str
String data containing response from Lambda function
str
String data containng logs statements, if any.
bool
If the response is an error/exception from the container | [
"This",
"method",
"will",
"extract",
"read",
"the",
"given",
"stream",
"and",
"return",
"the",
"response",
"from",
"Lambda",
"function",
"separated",
"out",
"from",
"any",
"log",
"statements",
"it",
"might",
"have",
"outputted",
".",
"Logs",
"end",
"up",
"in",
"the",
"stdout",
"stream",
"if",
"the",
"Lambda",
"function",
"wrote",
"directly",
"to",
"stdout",
"using",
"System",
".",
"out",
".",
"println",
"or",
"equivalents",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/services/base_local_service.py#L102-L149 | train |
awslabs/aws-sam-cli | samcli/local/services/base_local_service.py | LambdaOutputParser.is_lambda_error_response | def is_lambda_error_response(lambda_response):
"""
Check to see if the output from the container is in the form of an Error/Exception from the Lambda invoke
Parameters
----------
lambda_response str
The response the container returned
Returns
-------
bool
True if the output matches the Error/Exception Dictionary otherwise False
"""
is_lambda_user_error_response = False
try:
lambda_response_dict = json.loads(lambda_response)
# This is a best effort attempt to determine if the output (lambda_response) from the container was an
# Error/Exception that was raised/returned/thrown from the container. To ensure minimal false positives in
# this checking, we check for all three keys that can occur in Lambda raised/thrown/returned an
# Error/Exception. This still risks false positives when the data returned matches exactly a dictionary with
# the keys 'errorMessage', 'errorType' and 'stackTrace'.
if isinstance(lambda_response_dict, dict) and \
len(lambda_response_dict) == 3 and \
'errorMessage' in lambda_response_dict and \
'errorType' in lambda_response_dict and \
'stackTrace' in lambda_response_dict:
is_lambda_user_error_response = True
except ValueError:
# If you can't serialize the output into a dict, then do nothing
pass
return is_lambda_user_error_response | python | def is_lambda_error_response(lambda_response):
"""
Check to see if the output from the container is in the form of an Error/Exception from the Lambda invoke
Parameters
----------
lambda_response str
The response the container returned
Returns
-------
bool
True if the output matches the Error/Exception Dictionary otherwise False
"""
is_lambda_user_error_response = False
try:
lambda_response_dict = json.loads(lambda_response)
# This is a best effort attempt to determine if the output (lambda_response) from the container was an
# Error/Exception that was raised/returned/thrown from the container. To ensure minimal false positives in
# this checking, we check for all three keys that can occur in Lambda raised/thrown/returned an
# Error/Exception. This still risks false positives when the data returned matches exactly a dictionary with
# the keys 'errorMessage', 'errorType' and 'stackTrace'.
if isinstance(lambda_response_dict, dict) and \
len(lambda_response_dict) == 3 and \
'errorMessage' in lambda_response_dict and \
'errorType' in lambda_response_dict and \
'stackTrace' in lambda_response_dict:
is_lambda_user_error_response = True
except ValueError:
# If you can't serialize the output into a dict, then do nothing
pass
return is_lambda_user_error_response | [
"def",
"is_lambda_error_response",
"(",
"lambda_response",
")",
":",
"is_lambda_user_error_response",
"=",
"False",
"try",
":",
"lambda_response_dict",
"=",
"json",
".",
"loads",
"(",
"lambda_response",
")",
"# This is a best effort attempt to determine if the output (lambda_response) from the container was an",
"# Error/Exception that was raised/returned/thrown from the container. To ensure minimal false positives in",
"# this checking, we check for all three keys that can occur in Lambda raised/thrown/returned an",
"# Error/Exception. This still risks false positives when the data returned matches exactly a dictionary with",
"# the keys 'errorMessage', 'errorType' and 'stackTrace'.",
"if",
"isinstance",
"(",
"lambda_response_dict",
",",
"dict",
")",
"and",
"len",
"(",
"lambda_response_dict",
")",
"==",
"3",
"and",
"'errorMessage'",
"in",
"lambda_response_dict",
"and",
"'errorType'",
"in",
"lambda_response_dict",
"and",
"'stackTrace'",
"in",
"lambda_response_dict",
":",
"is_lambda_user_error_response",
"=",
"True",
"except",
"ValueError",
":",
"# If you can't serialize the output into a dict, then do nothing",
"pass",
"return",
"is_lambda_user_error_response"
] | Check to see if the output from the container is in the form of an Error/Exception from the Lambda invoke
Parameters
----------
lambda_response str
The response the container returned
Returns
-------
bool
True if the output matches the Error/Exception Dictionary otherwise False | [
"Check",
"to",
"see",
"if",
"the",
"output",
"from",
"the",
"container",
"is",
"in",
"the",
"form",
"of",
"an",
"Error",
"/",
"Exception",
"from",
"the",
"Lambda",
"invoke"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/services/base_local_service.py#L152-L184 | train |
awslabs/aws-sam-cli | samcli/lib/build/app_builder.py | ApplicationBuilder.build | def build(self):
"""
Build the entire application
Returns
-------
dict
Returns the path to where each resource was built as a map of resource's LogicalId to the path string
"""
result = {}
for lambda_function in self._functions_to_build:
LOG.info("Building resource '%s'", lambda_function.name)
result[lambda_function.name] = self._build_function(lambda_function.name,
lambda_function.codeuri,
lambda_function.runtime)
return result | python | def build(self):
"""
Build the entire application
Returns
-------
dict
Returns the path to where each resource was built as a map of resource's LogicalId to the path string
"""
result = {}
for lambda_function in self._functions_to_build:
LOG.info("Building resource '%s'", lambda_function.name)
result[lambda_function.name] = self._build_function(lambda_function.name,
lambda_function.codeuri,
lambda_function.runtime)
return result | [
"def",
"build",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"lambda_function",
"in",
"self",
".",
"_functions_to_build",
":",
"LOG",
".",
"info",
"(",
"\"Building resource '%s'\"",
",",
"lambda_function",
".",
"name",
")",
"result",
"[",
"lambda_function",
".",
"name",
"]",
"=",
"self",
".",
"_build_function",
"(",
"lambda_function",
".",
"name",
",",
"lambda_function",
".",
"codeuri",
",",
"lambda_function",
".",
"runtime",
")",
"return",
"result"
] | Build the entire application
Returns
-------
dict
Returns the path to where each resource was built as a map of resource's LogicalId to the path string | [
"Build",
"the",
"entire",
"application"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/build/app_builder.py#L91-L110 | train |
awslabs/aws-sam-cli | samcli/lib/build/app_builder.py | ApplicationBuilder.update_template | def update_template(self, template_dict, original_template_path, built_artifacts):
"""
Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path : str
Path where the template file will be written to
built_artifacts : dict
Map of LogicalId of a resource to the path where the the built artifacts for this resource lives
Returns
-------
dict
Updated template
"""
original_dir = os.path.dirname(original_template_path)
for logical_id, resource in template_dict.get("Resources", {}).items():
if logical_id not in built_artifacts:
# this resource was not built. So skip it
continue
# Artifacts are written relative to the template because it makes the template portable
# Ex: A CI/CD pipeline build stage could zip the output folder and pass to a
# package stage running on a different machine
artifact_relative_path = os.path.relpath(built_artifacts[logical_id], original_dir)
resource_type = resource.get("Type")
properties = resource.setdefault("Properties", {})
if resource_type == "AWS::Serverless::Function":
properties["CodeUri"] = artifact_relative_path
if resource_type == "AWS::Lambda::Function":
properties["Code"] = artifact_relative_path
return template_dict | python | def update_template(self, template_dict, original_template_path, built_artifacts):
"""
Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path : str
Path where the template file will be written to
built_artifacts : dict
Map of LogicalId of a resource to the path where the the built artifacts for this resource lives
Returns
-------
dict
Updated template
"""
original_dir = os.path.dirname(original_template_path)
for logical_id, resource in template_dict.get("Resources", {}).items():
if logical_id not in built_artifacts:
# this resource was not built. So skip it
continue
# Artifacts are written relative to the template because it makes the template portable
# Ex: A CI/CD pipeline build stage could zip the output folder and pass to a
# package stage running on a different machine
artifact_relative_path = os.path.relpath(built_artifacts[logical_id], original_dir)
resource_type = resource.get("Type")
properties = resource.setdefault("Properties", {})
if resource_type == "AWS::Serverless::Function":
properties["CodeUri"] = artifact_relative_path
if resource_type == "AWS::Lambda::Function":
properties["Code"] = artifact_relative_path
return template_dict | [
"def",
"update_template",
"(",
"self",
",",
"template_dict",
",",
"original_template_path",
",",
"built_artifacts",
")",
":",
"original_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"original_template_path",
")",
"for",
"logical_id",
",",
"resource",
"in",
"template_dict",
".",
"get",
"(",
"\"Resources\"",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"if",
"logical_id",
"not",
"in",
"built_artifacts",
":",
"# this resource was not built. So skip it",
"continue",
"# Artifacts are written relative to the template because it makes the template portable",
"# Ex: A CI/CD pipeline build stage could zip the output folder and pass to a",
"# package stage running on a different machine",
"artifact_relative_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"built_artifacts",
"[",
"logical_id",
"]",
",",
"original_dir",
")",
"resource_type",
"=",
"resource",
".",
"get",
"(",
"\"Type\"",
")",
"properties",
"=",
"resource",
".",
"setdefault",
"(",
"\"Properties\"",
",",
"{",
"}",
")",
"if",
"resource_type",
"==",
"\"AWS::Serverless::Function\"",
":",
"properties",
"[",
"\"CodeUri\"",
"]",
"=",
"artifact_relative_path",
"if",
"resource_type",
"==",
"\"AWS::Lambda::Function\"",
":",
"properties",
"[",
"\"Code\"",
"]",
"=",
"artifact_relative_path",
"return",
"template_dict"
] | Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path : str
Path where the template file will be written to
built_artifacts : dict
Map of LogicalId of a resource to the path where the the built artifacts for this resource lives
Returns
-------
dict
Updated template | [
"Given",
"the",
"path",
"to",
"built",
"artifacts",
"update",
"the",
"template",
"to",
"point",
"appropriate",
"resource",
"CodeUris",
"to",
"the",
"artifacts",
"folder"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/build/app_builder.py#L112-L153 | train |
awslabs/aws-sam-cli | samcli/lib/build/app_builder.py | ApplicationBuilder._build_function | def _build_function(self, function_name, codeuri, runtime):
"""
Given the function information, this method will build the Lambda function. Depending on the configuration
it will either build the function in process or by spinning up a Docker container.
Parameters
----------
function_name : str
Name or LogicalId of the function
codeuri : str
Path to where the code lives
runtime : str
AWS Lambda function runtime
Returns
-------
str
Path to the location where built artifacts are available
"""
# Create the arguments to pass to the builder
# Code is always relative to the given base directory.
code_dir = str(pathlib.Path(self._base_dir, codeuri).resolve())
config = get_workflow_config(runtime, code_dir, self._base_dir)
# artifacts directory will be created by the builder
artifacts_dir = str(pathlib.Path(self._build_dir, function_name))
with osutils.mkdir_temp() as scratch_dir:
manifest_path = self._manifest_path_override or os.path.join(code_dir, config.manifest_name)
# By default prefer to build in-process for speed
build_method = self._build_function_in_process
if self._container_manager:
build_method = self._build_function_on_container
return build_method(config,
code_dir,
artifacts_dir,
scratch_dir,
manifest_path,
runtime) | python | def _build_function(self, function_name, codeuri, runtime):
"""
Given the function information, this method will build the Lambda function. Depending on the configuration
it will either build the function in process or by spinning up a Docker container.
Parameters
----------
function_name : str
Name or LogicalId of the function
codeuri : str
Path to where the code lives
runtime : str
AWS Lambda function runtime
Returns
-------
str
Path to the location where built artifacts are available
"""
# Create the arguments to pass to the builder
# Code is always relative to the given base directory.
code_dir = str(pathlib.Path(self._base_dir, codeuri).resolve())
config = get_workflow_config(runtime, code_dir, self._base_dir)
# artifacts directory will be created by the builder
artifacts_dir = str(pathlib.Path(self._build_dir, function_name))
with osutils.mkdir_temp() as scratch_dir:
manifest_path = self._manifest_path_override or os.path.join(code_dir, config.manifest_name)
# By default prefer to build in-process for speed
build_method = self._build_function_in_process
if self._container_manager:
build_method = self._build_function_on_container
return build_method(config,
code_dir,
artifacts_dir,
scratch_dir,
manifest_path,
runtime) | [
"def",
"_build_function",
"(",
"self",
",",
"function_name",
",",
"codeuri",
",",
"runtime",
")",
":",
"# Create the arguments to pass to the builder",
"# Code is always relative to the given base directory.",
"code_dir",
"=",
"str",
"(",
"pathlib",
".",
"Path",
"(",
"self",
".",
"_base_dir",
",",
"codeuri",
")",
".",
"resolve",
"(",
")",
")",
"config",
"=",
"get_workflow_config",
"(",
"runtime",
",",
"code_dir",
",",
"self",
".",
"_base_dir",
")",
"# artifacts directory will be created by the builder",
"artifacts_dir",
"=",
"str",
"(",
"pathlib",
".",
"Path",
"(",
"self",
".",
"_build_dir",
",",
"function_name",
")",
")",
"with",
"osutils",
".",
"mkdir_temp",
"(",
")",
"as",
"scratch_dir",
":",
"manifest_path",
"=",
"self",
".",
"_manifest_path_override",
"or",
"os",
".",
"path",
".",
"join",
"(",
"code_dir",
",",
"config",
".",
"manifest_name",
")",
"# By default prefer to build in-process for speed",
"build_method",
"=",
"self",
".",
"_build_function_in_process",
"if",
"self",
".",
"_container_manager",
":",
"build_method",
"=",
"self",
".",
"_build_function_on_container",
"return",
"build_method",
"(",
"config",
",",
"code_dir",
",",
"artifacts_dir",
",",
"scratch_dir",
",",
"manifest_path",
",",
"runtime",
")"
] | Given the function information, this method will build the Lambda function. Depending on the configuration
it will either build the function in process or by spinning up a Docker container.
Parameters
----------
function_name : str
Name or LogicalId of the function
codeuri : str
Path to where the code lives
runtime : str
AWS Lambda function runtime
Returns
-------
str
Path to the location where built artifacts are available | [
"Given",
"the",
"function",
"information",
"this",
"method",
"will",
"build",
"the",
"Lambda",
"function",
".",
"Depending",
"on",
"the",
"configuration",
"it",
"will",
"either",
"build",
"the",
"function",
"in",
"process",
"or",
"by",
"spinning",
"up",
"a",
"Docker",
"container",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/build/app_builder.py#L155-L199 | train |
awslabs/aws-sam-cli | samcli/local/docker/lambda_build_container.py | LambdaBuildContainer._get_container_dirs | def _get_container_dirs(source_dir, manifest_dir):
"""
Provides paths to directories within the container that is required by the builder
Parameters
----------
source_dir : str
Path to the function source code
manifest_dir : str
Path to the directory containing manifest
Returns
-------
dict
Contains paths to source, artifacts, scratch & manifest directories
"""
base = "/tmp/samcli"
result = {
"source_dir": "{}/source".format(base),
"artifacts_dir": "{}/artifacts".format(base),
"scratch_dir": "{}/scratch".format(base),
"manifest_dir": "{}/manifest".format(base)
}
if pathlib.PurePath(source_dir) == pathlib.PurePath(manifest_dir):
# It is possible that the manifest resides within the source. In that case, we won't mount the manifest
# directory separately.
result["manifest_dir"] = result["source_dir"]
return result | python | def _get_container_dirs(source_dir, manifest_dir):
"""
Provides paths to directories within the container that is required by the builder
Parameters
----------
source_dir : str
Path to the function source code
manifest_dir : str
Path to the directory containing manifest
Returns
-------
dict
Contains paths to source, artifacts, scratch & manifest directories
"""
base = "/tmp/samcli"
result = {
"source_dir": "{}/source".format(base),
"artifacts_dir": "{}/artifacts".format(base),
"scratch_dir": "{}/scratch".format(base),
"manifest_dir": "{}/manifest".format(base)
}
if pathlib.PurePath(source_dir) == pathlib.PurePath(manifest_dir):
# It is possible that the manifest resides within the source. In that case, we won't mount the manifest
# directory separately.
result["manifest_dir"] = result["source_dir"]
return result | [
"def",
"_get_container_dirs",
"(",
"source_dir",
",",
"manifest_dir",
")",
":",
"base",
"=",
"\"/tmp/samcli\"",
"result",
"=",
"{",
"\"source_dir\"",
":",
"\"{}/source\"",
".",
"format",
"(",
"base",
")",
",",
"\"artifacts_dir\"",
":",
"\"{}/artifacts\"",
".",
"format",
"(",
"base",
")",
",",
"\"scratch_dir\"",
":",
"\"{}/scratch\"",
".",
"format",
"(",
"base",
")",
",",
"\"manifest_dir\"",
":",
"\"{}/manifest\"",
".",
"format",
"(",
"base",
")",
"}",
"if",
"pathlib",
".",
"PurePath",
"(",
"source_dir",
")",
"==",
"pathlib",
".",
"PurePath",
"(",
"manifest_dir",
")",
":",
"# It is possible that the manifest resides within the source. In that case, we won't mount the manifest",
"# directory separately.",
"result",
"[",
"\"manifest_dir\"",
"]",
"=",
"result",
"[",
"\"source_dir\"",
"]",
"return",
"result"
] | Provides paths to directories within the container that is required by the builder
Parameters
----------
source_dir : str
Path to the function source code
manifest_dir : str
Path to the directory containing manifest
Returns
-------
dict
Contains paths to source, artifacts, scratch & manifest directories | [
"Provides",
"paths",
"to",
"directories",
"within",
"the",
"container",
"that",
"is",
"required",
"by",
"the",
"builder"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_build_container.py#L150-L180 | train |
awslabs/aws-sam-cli | samcli/local/docker/lambda_build_container.py | LambdaBuildContainer._convert_to_container_dirs | def _convert_to_container_dirs(host_paths_to_convert, host_to_container_path_mapping):
"""
Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
the Lambda Builder running within the container.
If a host path is not mounted within the container, then this method simply passes the path to the result
without any changes.
Ex:
[ "/home/foo", "/home/bar", "/home/not/mounted"] => ["/tmp/source", "/tmp/manifest", "/home/not/mounted"]
Parameters
----------
host_paths_to_convert : list
List of paths in host that needs to be converted
host_to_container_path_mapping : dict
Mapping of paths in host to the equivalent paths within the container
Returns
-------
list
Equivalent paths within the container
"""
if not host_paths_to_convert:
# Nothing to do
return host_paths_to_convert
# Make sure the key is absolute host path. Relative paths are tricky to work with because two different
# relative paths can point to the same directory ("../foo", "../../foo")
mapping = {str(pathlib.Path(p).resolve()): v for p, v in host_to_container_path_mapping.items()}
result = []
for original_path in host_paths_to_convert:
abspath = str(pathlib.Path(original_path).resolve())
if abspath in mapping:
result.append(mapping[abspath])
else:
result.append(original_path)
LOG.debug("Cannot convert host path '%s' to its equivalent path within the container. "
"Host path is not mounted within the container", abspath)
return result | python | def _convert_to_container_dirs(host_paths_to_convert, host_to_container_path_mapping):
"""
Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
the Lambda Builder running within the container.
If a host path is not mounted within the container, then this method simply passes the path to the result
without any changes.
Ex:
[ "/home/foo", "/home/bar", "/home/not/mounted"] => ["/tmp/source", "/tmp/manifest", "/home/not/mounted"]
Parameters
----------
host_paths_to_convert : list
List of paths in host that needs to be converted
host_to_container_path_mapping : dict
Mapping of paths in host to the equivalent paths within the container
Returns
-------
list
Equivalent paths within the container
"""
if not host_paths_to_convert:
# Nothing to do
return host_paths_to_convert
# Make sure the key is absolute host path. Relative paths are tricky to work with because two different
# relative paths can point to the same directory ("../foo", "../../foo")
mapping = {str(pathlib.Path(p).resolve()): v for p, v in host_to_container_path_mapping.items()}
result = []
for original_path in host_paths_to_convert:
abspath = str(pathlib.Path(original_path).resolve())
if abspath in mapping:
result.append(mapping[abspath])
else:
result.append(original_path)
LOG.debug("Cannot convert host path '%s' to its equivalent path within the container. "
"Host path is not mounted within the container", abspath)
return result | [
"def",
"_convert_to_container_dirs",
"(",
"host_paths_to_convert",
",",
"host_to_container_path_mapping",
")",
":",
"if",
"not",
"host_paths_to_convert",
":",
"# Nothing to do",
"return",
"host_paths_to_convert",
"# Make sure the key is absolute host path. Relative paths are tricky to work with because two different",
"# relative paths can point to the same directory (\"../foo\", \"../../foo\")",
"mapping",
"=",
"{",
"str",
"(",
"pathlib",
".",
"Path",
"(",
"p",
")",
".",
"resolve",
"(",
")",
")",
":",
"v",
"for",
"p",
",",
"v",
"in",
"host_to_container_path_mapping",
".",
"items",
"(",
")",
"}",
"result",
"=",
"[",
"]",
"for",
"original_path",
"in",
"host_paths_to_convert",
":",
"abspath",
"=",
"str",
"(",
"pathlib",
".",
"Path",
"(",
"original_path",
")",
".",
"resolve",
"(",
")",
")",
"if",
"abspath",
"in",
"mapping",
":",
"result",
".",
"append",
"(",
"mapping",
"[",
"abspath",
"]",
")",
"else",
":",
"result",
".",
"append",
"(",
"original_path",
")",
"LOG",
".",
"debug",
"(",
"\"Cannot convert host path '%s' to its equivalent path within the container. \"",
"\"Host path is not mounted within the container\"",
",",
"abspath",
")",
"return",
"result"
] | Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
the Lambda Builder running within the container.
If a host path is not mounted within the container, then this method simply passes the path to the result
without any changes.
Ex:
[ "/home/foo", "/home/bar", "/home/not/mounted"] => ["/tmp/source", "/tmp/manifest", "/home/not/mounted"]
Parameters
----------
host_paths_to_convert : list
List of paths in host that needs to be converted
host_to_container_path_mapping : dict
Mapping of paths in host to the equivalent paths within the container
Returns
-------
list
Equivalent paths within the container | [
"Use",
"this",
"method",
"to",
"convert",
"a",
"list",
"of",
"host",
"paths",
"to",
"a",
"list",
"of",
"equivalent",
"paths",
"within",
"the",
"container",
"where",
"the",
"given",
"host",
"path",
"is",
"mounted",
".",
"This",
"is",
"necessary",
"when",
"SAM",
"CLI",
"needs",
"to",
"pass",
"path",
"information",
"to",
"the",
"Lambda",
"Builder",
"running",
"within",
"the",
"container",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_build_container.py#L183-L228 | train |
awslabs/aws-sam-cli | samcli/lib/samlib/wrapper.py | SamTranslatorWrapper.__translate | def __translate(self, parameter_values):
"""
This method is unused and a Work In Progress
"""
template_copy = self.template
sam_parser = Parser()
sam_translator = Translator(managed_policy_map=self.__managed_policy_map(),
sam_parser=sam_parser,
# Default plugins are already initialized within the Translator
plugins=self.extra_plugins)
return sam_translator.translate(sam_template=template_copy,
parameter_values=parameter_values) | python | def __translate(self, parameter_values):
"""
This method is unused and a Work In Progress
"""
template_copy = self.template
sam_parser = Parser()
sam_translator = Translator(managed_policy_map=self.__managed_policy_map(),
sam_parser=sam_parser,
# Default plugins are already initialized within the Translator
plugins=self.extra_plugins)
return sam_translator.translate(sam_template=template_copy,
parameter_values=parameter_values) | [
"def",
"__translate",
"(",
"self",
",",
"parameter_values",
")",
":",
"template_copy",
"=",
"self",
".",
"template",
"sam_parser",
"=",
"Parser",
"(",
")",
"sam_translator",
"=",
"Translator",
"(",
"managed_policy_map",
"=",
"self",
".",
"__managed_policy_map",
"(",
")",
",",
"sam_parser",
"=",
"sam_parser",
",",
"# Default plugins are already initialized within the Translator",
"plugins",
"=",
"self",
".",
"extra_plugins",
")",
"return",
"sam_translator",
".",
"translate",
"(",
"sam_template",
"=",
"template_copy",
",",
"parameter_values",
"=",
"parameter_values",
")"
] | This method is unused and a Work In Progress | [
"This",
"method",
"is",
"unused",
"and",
"a",
"Work",
"In",
"Progress"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/samlib/wrapper.py#L74-L88 | train |
awslabs/aws-sam-cli | samcli/lib/samlib/wrapper.py | SamTranslatorWrapper.__managed_policy_map | def __managed_policy_map(self):
"""
This method is unused and a Work In Progress
"""
try:
iam_client = boto3.client('iam')
return ManagedPolicyLoader(iam_client).load()
except Exception as ex:
if self._offline_fallback:
# If offline flag is set, then fall back to the list of default managed policies
# This should be sufficient for most cases
with open(self._DEFAULT_MANAGED_POLICIES_FILE, 'r') as fp:
return json.load(fp)
# Offline is not enabled. So just raise the exception
raise ex | python | def __managed_policy_map(self):
"""
This method is unused and a Work In Progress
"""
try:
iam_client = boto3.client('iam')
return ManagedPolicyLoader(iam_client).load()
except Exception as ex:
if self._offline_fallback:
# If offline flag is set, then fall back to the list of default managed policies
# This should be sufficient for most cases
with open(self._DEFAULT_MANAGED_POLICIES_FILE, 'r') as fp:
return json.load(fp)
# Offline is not enabled. So just raise the exception
raise ex | [
"def",
"__managed_policy_map",
"(",
"self",
")",
":",
"try",
":",
"iam_client",
"=",
"boto3",
".",
"client",
"(",
"'iam'",
")",
"return",
"ManagedPolicyLoader",
"(",
"iam_client",
")",
".",
"load",
"(",
")",
"except",
"Exception",
"as",
"ex",
":",
"if",
"self",
".",
"_offline_fallback",
":",
"# If offline flag is set, then fall back to the list of default managed policies",
"# This should be sufficient for most cases",
"with",
"open",
"(",
"self",
".",
"_DEFAULT_MANAGED_POLICIES_FILE",
",",
"'r'",
")",
"as",
"fp",
":",
"return",
"json",
".",
"load",
"(",
"fp",
")",
"# Offline is not enabled. So just raise the exception",
"raise",
"ex"
] | This method is unused and a Work In Progress | [
"This",
"method",
"is",
"unused",
"and",
"a",
"Work",
"In",
"Progress"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/samlib/wrapper.py#L94-L110 | train |
awslabs/aws-sam-cli | samcli/lib/samlib/wrapper.py | _SamParserReimplemented._validate | def _validate(self, sam_template):
""" Validates the template and parameter values and raises exceptions if there's an issue
:param dict sam_template: SAM template
"""
if "Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) \
or not sam_template["Resources"]:
raise InvalidDocumentException(
[InvalidTemplateException("'Resources' section is required")])
SamTemplateValidator.validate(sam_template) | python | def _validate(self, sam_template):
""" Validates the template and parameter values and raises exceptions if there's an issue
:param dict sam_template: SAM template
"""
if "Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) \
or not sam_template["Resources"]:
raise InvalidDocumentException(
[InvalidTemplateException("'Resources' section is required")])
SamTemplateValidator.validate(sam_template) | [
"def",
"_validate",
"(",
"self",
",",
"sam_template",
")",
":",
"if",
"\"Resources\"",
"not",
"in",
"sam_template",
"or",
"not",
"isinstance",
"(",
"sam_template",
"[",
"\"Resources\"",
"]",
",",
"dict",
")",
"or",
"not",
"sam_template",
"[",
"\"Resources\"",
"]",
":",
"raise",
"InvalidDocumentException",
"(",
"[",
"InvalidTemplateException",
"(",
"\"'Resources' section is required\"",
")",
"]",
")",
"SamTemplateValidator",
".",
"validate",
"(",
"sam_template",
")"
] | Validates the template and parameter values and raises exceptions if there's an issue
:param dict sam_template: SAM template | [
"Validates",
"the",
"template",
"and",
"parameter",
"values",
"and",
"raises",
"exceptions",
"if",
"there",
"s",
"an",
"issue"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/samlib/wrapper.py#L136-L147 | train |
awslabs/aws-sam-cli | samcli/commands/local/generate_event/event_generation.py | ServiceCommand.get_command | def get_command(self, ctx, cmd_name):
"""
gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSubCommand:
returns subcommand if successful, None if not.
"""
if cmd_name not in self.all_cmds:
return None
return EventTypeSubCommand(self.events_lib, cmd_name, self.all_cmds[cmd_name]) | python | def get_command(self, ctx, cmd_name):
"""
gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSubCommand:
returns subcommand if successful, None if not.
"""
if cmd_name not in self.all_cmds:
return None
return EventTypeSubCommand(self.events_lib, cmd_name, self.all_cmds[cmd_name]) | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"if",
"cmd_name",
"not",
"in",
"self",
".",
"all_cmds",
":",
"return",
"None",
"return",
"EventTypeSubCommand",
"(",
"self",
".",
"events_lib",
",",
"cmd_name",
",",
"self",
".",
"all_cmds",
"[",
"cmd_name",
"]",
")"
] | gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSubCommand:
returns subcommand if successful, None if not. | [
"gets",
"the",
"subcommands",
"under",
"the",
"service",
"name"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/generate_event/event_generation.py#L45-L63 | train |
awslabs/aws-sam-cli | samcli/commands/local/generate_event/event_generation.py | EventTypeSubCommand.get_command | def get_command(self, ctx, cmd_name):
"""
gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
the Click Commands that can be called from the CLI
"""
if cmd_name not in self.subcmd_definition:
return None
parameters = []
for param_name in self.subcmd_definition[cmd_name][self.TAGS].keys():
default = self.subcmd_definition[cmd_name][self.TAGS][param_name]["default"]
parameters.append(click.Option(
["--{}".format(param_name)],
default=default,
help="Specify the {} name you'd like, otherwise the default = {}".format(param_name, default)
))
command_callback = functools.partial(self.cmd_implementation,
self.events_lib,
self.top_level_cmd_name,
cmd_name)
cmd = click.Command(name=cmd_name,
short_help=self.subcmd_definition[cmd_name]["help"],
params=parameters,
callback=command_callback)
cmd = debug_option(cmd)
return cmd | python | def get_command(self, ctx, cmd_name):
"""
gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
the Click Commands that can be called from the CLI
"""
if cmd_name not in self.subcmd_definition:
return None
parameters = []
for param_name in self.subcmd_definition[cmd_name][self.TAGS].keys():
default = self.subcmd_definition[cmd_name][self.TAGS][param_name]["default"]
parameters.append(click.Option(
["--{}".format(param_name)],
default=default,
help="Specify the {} name you'd like, otherwise the default = {}".format(param_name, default)
))
command_callback = functools.partial(self.cmd_implementation,
self.events_lib,
self.top_level_cmd_name,
cmd_name)
cmd = click.Command(name=cmd_name,
short_help=self.subcmd_definition[cmd_name]["help"],
params=parameters,
callback=command_callback)
cmd = debug_option(cmd)
return cmd | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"if",
"cmd_name",
"not",
"in",
"self",
".",
"subcmd_definition",
":",
"return",
"None",
"parameters",
"=",
"[",
"]",
"for",
"param_name",
"in",
"self",
".",
"subcmd_definition",
"[",
"cmd_name",
"]",
"[",
"self",
".",
"TAGS",
"]",
".",
"keys",
"(",
")",
":",
"default",
"=",
"self",
".",
"subcmd_definition",
"[",
"cmd_name",
"]",
"[",
"self",
".",
"TAGS",
"]",
"[",
"param_name",
"]",
"[",
"\"default\"",
"]",
"parameters",
".",
"append",
"(",
"click",
".",
"Option",
"(",
"[",
"\"--{}\"",
".",
"format",
"(",
"param_name",
")",
"]",
",",
"default",
"=",
"default",
",",
"help",
"=",
"\"Specify the {} name you'd like, otherwise the default = {}\"",
".",
"format",
"(",
"param_name",
",",
"default",
")",
")",
")",
"command_callback",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"cmd_implementation",
",",
"self",
".",
"events_lib",
",",
"self",
".",
"top_level_cmd_name",
",",
"cmd_name",
")",
"cmd",
"=",
"click",
".",
"Command",
"(",
"name",
"=",
"cmd_name",
",",
"short_help",
"=",
"self",
".",
"subcmd_definition",
"[",
"cmd_name",
"]",
"[",
"\"help\"",
"]",
",",
"params",
"=",
"parameters",
",",
"callback",
"=",
"command_callback",
")",
"cmd",
"=",
"debug_option",
"(",
"cmd",
")",
"return",
"cmd"
] | gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
the Click Commands that can be called from the CLI | [
"gets",
"the",
"Click",
"Commands",
"underneath",
"a",
"service",
"name"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/generate_event/event_generation.py#L119-L157 | train |
awslabs/aws-sam-cli | samcli/commands/local/generate_event/event_generation.py | EventTypeSubCommand.cmd_implementation | def cmd_implementation(self, events_lib, top_level_cmd_name, subcmd_name, *args, **kwargs):
"""
calls for value substitution in the event json and returns the
customized json as a string
Parameters
----------
events_lib
top_level_cmd_name: string
the name of the service
subcmd_name: string
the name of the event under the service
args: tuple
any arguments passed in before kwargs
kwargs: dict
the keys and values for substitution in the json
Returns
-------
event: string
returns the customized event json as a string
"""
event = events_lib.generate_event(top_level_cmd_name, subcmd_name, kwargs)
click.echo(event)
return event | python | def cmd_implementation(self, events_lib, top_level_cmd_name, subcmd_name, *args, **kwargs):
"""
calls for value substitution in the event json and returns the
customized json as a string
Parameters
----------
events_lib
top_level_cmd_name: string
the name of the service
subcmd_name: string
the name of the event under the service
args: tuple
any arguments passed in before kwargs
kwargs: dict
the keys and values for substitution in the json
Returns
-------
event: string
returns the customized event json as a string
"""
event = events_lib.generate_event(top_level_cmd_name, subcmd_name, kwargs)
click.echo(event)
return event | [
"def",
"cmd_implementation",
"(",
"self",
",",
"events_lib",
",",
"top_level_cmd_name",
",",
"subcmd_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"event",
"=",
"events_lib",
".",
"generate_event",
"(",
"top_level_cmd_name",
",",
"subcmd_name",
",",
"kwargs",
")",
"click",
".",
"echo",
"(",
"event",
")",
"return",
"event"
] | calls for value substitution in the event json and returns the
customized json as a string
Parameters
----------
events_lib
top_level_cmd_name: string
the name of the service
subcmd_name: string
the name of the event under the service
args: tuple
any arguments passed in before kwargs
kwargs: dict
the keys and values for substitution in the json
Returns
-------
event: string
returns the customized event json as a string | [
"calls",
"for",
"value",
"substitution",
"in",
"the",
"event",
"json",
"and",
"returns",
"the",
"customized",
"json",
"as",
"a",
"string"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/generate_event/event_generation.py#L173-L196 | train |
marcotcr/lime | lime/lime_base.py | LimeBase.generate_lars_path | def generate_lars_path(weighted_data, weighted_labels):
"""Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, respectively
"""
x_vector = weighted_data
alphas, _, coefs = lars_path(x_vector,
weighted_labels,
method='lasso',
verbose=False)
return alphas, coefs | python | def generate_lars_path(weighted_data, weighted_labels):
"""Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, respectively
"""
x_vector = weighted_data
alphas, _, coefs = lars_path(x_vector,
weighted_labels,
method='lasso',
verbose=False)
return alphas, coefs | [
"def",
"generate_lars_path",
"(",
"weighted_data",
",",
"weighted_labels",
")",
":",
"x_vector",
"=",
"weighted_data",
"alphas",
",",
"_",
",",
"coefs",
"=",
"lars_path",
"(",
"x_vector",
",",
"weighted_labels",
",",
"method",
"=",
"'lasso'",
",",
"verbose",
"=",
"False",
")",
"return",
"alphas",
",",
"coefs"
] | Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, respectively | [
"Generates",
"the",
"lars",
"path",
"for",
"weighted",
"data",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_base.py#L31-L47 | train |
marcotcr/lime | lime/lime_base.py | LimeBase.forward_selection | def forward_selection(self, data, labels, weights, num_features):
"""Iteratively adds features to the model"""
clf = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state)
used_features = []
for _ in range(min(num_features, data.shape[1])):
max_ = -100000000
best = 0
for feature in range(data.shape[1]):
if feature in used_features:
continue
clf.fit(data[:, used_features + [feature]], labels,
sample_weight=weights)
score = clf.score(data[:, used_features + [feature]],
labels,
sample_weight=weights)
if score > max_:
best = feature
max_ = score
used_features.append(best)
return np.array(used_features) | python | def forward_selection(self, data, labels, weights, num_features):
"""Iteratively adds features to the model"""
clf = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state)
used_features = []
for _ in range(min(num_features, data.shape[1])):
max_ = -100000000
best = 0
for feature in range(data.shape[1]):
if feature in used_features:
continue
clf.fit(data[:, used_features + [feature]], labels,
sample_weight=weights)
score = clf.score(data[:, used_features + [feature]],
labels,
sample_weight=weights)
if score > max_:
best = feature
max_ = score
used_features.append(best)
return np.array(used_features) | [
"def",
"forward_selection",
"(",
"self",
",",
"data",
",",
"labels",
",",
"weights",
",",
"num_features",
")",
":",
"clf",
"=",
"Ridge",
"(",
"alpha",
"=",
"0",
",",
"fit_intercept",
"=",
"True",
",",
"random_state",
"=",
"self",
".",
"random_state",
")",
"used_features",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"min",
"(",
"num_features",
",",
"data",
".",
"shape",
"[",
"1",
"]",
")",
")",
":",
"max_",
"=",
"-",
"100000000",
"best",
"=",
"0",
"for",
"feature",
"in",
"range",
"(",
"data",
".",
"shape",
"[",
"1",
"]",
")",
":",
"if",
"feature",
"in",
"used_features",
":",
"continue",
"clf",
".",
"fit",
"(",
"data",
"[",
":",
",",
"used_features",
"+",
"[",
"feature",
"]",
"]",
",",
"labels",
",",
"sample_weight",
"=",
"weights",
")",
"score",
"=",
"clf",
".",
"score",
"(",
"data",
"[",
":",
",",
"used_features",
"+",
"[",
"feature",
"]",
"]",
",",
"labels",
",",
"sample_weight",
"=",
"weights",
")",
"if",
"score",
">",
"max_",
":",
"best",
"=",
"feature",
"max_",
"=",
"score",
"used_features",
".",
"append",
"(",
"best",
")",
"return",
"np",
".",
"array",
"(",
"used_features",
")"
] | Iteratively adds features to the model | [
"Iteratively",
"adds",
"features",
"to",
"the",
"model"
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_base.py#L49-L68 | train |
marcotcr/lime | lime/lime_base.py | LimeBase.feature_selection | def feature_selection(self, data, labels, weights, num_features, method):
"""Selects features for the model. see explain_instance_with_data to
understand the parameters."""
if method == 'none':
return np.array(range(data.shape[1]))
elif method == 'forward_selection':
return self.forward_selection(data, labels, weights, num_features)
elif method == 'highest_weights':
clf = Ridge(alpha=0, fit_intercept=True,
random_state=self.random_state)
clf.fit(data, labels, sample_weight=weights)
feature_weights = sorted(zip(range(data.shape[0]),
clf.coef_ * data[0]),
key=lambda x: np.abs(x[1]),
reverse=True)
return np.array([x[0] for x in feature_weights[:num_features]])
elif method == 'lasso_path':
weighted_data = ((data - np.average(data, axis=0, weights=weights))
* np.sqrt(weights[:, np.newaxis]))
weighted_labels = ((labels - np.average(labels, weights=weights))
* np.sqrt(weights))
nonzero = range(weighted_data.shape[1])
_, coefs = self.generate_lars_path(weighted_data,
weighted_labels)
for i in range(len(coefs.T) - 1, 0, -1):
nonzero = coefs.T[i].nonzero()[0]
if len(nonzero) <= num_features:
break
used_features = nonzero
return used_features
elif method == 'auto':
if num_features <= 6:
n_method = 'forward_selection'
else:
n_method = 'highest_weights'
return self.feature_selection(data, labels, weights,
num_features, n_method) | python | def feature_selection(self, data, labels, weights, num_features, method):
"""Selects features for the model. see explain_instance_with_data to
understand the parameters."""
if method == 'none':
return np.array(range(data.shape[1]))
elif method == 'forward_selection':
return self.forward_selection(data, labels, weights, num_features)
elif method == 'highest_weights':
clf = Ridge(alpha=0, fit_intercept=True,
random_state=self.random_state)
clf.fit(data, labels, sample_weight=weights)
feature_weights = sorted(zip(range(data.shape[0]),
clf.coef_ * data[0]),
key=lambda x: np.abs(x[1]),
reverse=True)
return np.array([x[0] for x in feature_weights[:num_features]])
elif method == 'lasso_path':
weighted_data = ((data - np.average(data, axis=0, weights=weights))
* np.sqrt(weights[:, np.newaxis]))
weighted_labels = ((labels - np.average(labels, weights=weights))
* np.sqrt(weights))
nonzero = range(weighted_data.shape[1])
_, coefs = self.generate_lars_path(weighted_data,
weighted_labels)
for i in range(len(coefs.T) - 1, 0, -1):
nonzero = coefs.T[i].nonzero()[0]
if len(nonzero) <= num_features:
break
used_features = nonzero
return used_features
elif method == 'auto':
if num_features <= 6:
n_method = 'forward_selection'
else:
n_method = 'highest_weights'
return self.feature_selection(data, labels, weights,
num_features, n_method) | [
"def",
"feature_selection",
"(",
"self",
",",
"data",
",",
"labels",
",",
"weights",
",",
"num_features",
",",
"method",
")",
":",
"if",
"method",
"==",
"'none'",
":",
"return",
"np",
".",
"array",
"(",
"range",
"(",
"data",
".",
"shape",
"[",
"1",
"]",
")",
")",
"elif",
"method",
"==",
"'forward_selection'",
":",
"return",
"self",
".",
"forward_selection",
"(",
"data",
",",
"labels",
",",
"weights",
",",
"num_features",
")",
"elif",
"method",
"==",
"'highest_weights'",
":",
"clf",
"=",
"Ridge",
"(",
"alpha",
"=",
"0",
",",
"fit_intercept",
"=",
"True",
",",
"random_state",
"=",
"self",
".",
"random_state",
")",
"clf",
".",
"fit",
"(",
"data",
",",
"labels",
",",
"sample_weight",
"=",
"weights",
")",
"feature_weights",
"=",
"sorted",
"(",
"zip",
"(",
"range",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
")",
",",
"clf",
".",
"coef_",
"*",
"data",
"[",
"0",
"]",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"np",
".",
"abs",
"(",
"x",
"[",
"1",
"]",
")",
",",
"reverse",
"=",
"True",
")",
"return",
"np",
".",
"array",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"feature_weights",
"[",
":",
"num_features",
"]",
"]",
")",
"elif",
"method",
"==",
"'lasso_path'",
":",
"weighted_data",
"=",
"(",
"(",
"data",
"-",
"np",
".",
"average",
"(",
"data",
",",
"axis",
"=",
"0",
",",
"weights",
"=",
"weights",
")",
")",
"*",
"np",
".",
"sqrt",
"(",
"weights",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
")",
")",
"weighted_labels",
"=",
"(",
"(",
"labels",
"-",
"np",
".",
"average",
"(",
"labels",
",",
"weights",
"=",
"weights",
")",
")",
"*",
"np",
".",
"sqrt",
"(",
"weights",
")",
")",
"nonzero",
"=",
"range",
"(",
"weighted_data",
".",
"shape",
"[",
"1",
"]",
")",
"_",
",",
"coefs",
"=",
"self",
".",
"generate_lars_path",
"(",
"weighted_data",
",",
"weighted_labels",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"coefs",
".",
"T",
")",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"nonzero",
"=",
"coefs",
".",
"T",
"[",
"i",
"]",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"nonzero",
")",
"<=",
"num_features",
":",
"break",
"used_features",
"=",
"nonzero",
"return",
"used_features",
"elif",
"method",
"==",
"'auto'",
":",
"if",
"num_features",
"<=",
"6",
":",
"n_method",
"=",
"'forward_selection'",
"else",
":",
"n_method",
"=",
"'highest_weights'",
"return",
"self",
".",
"feature_selection",
"(",
"data",
",",
"labels",
",",
"weights",
",",
"num_features",
",",
"n_method",
")"
] | Selects features for the model. see explain_instance_with_data to
understand the parameters. | [
"Selects",
"features",
"for",
"the",
"model",
".",
"see",
"explain_instance_with_data",
"to",
"understand",
"the",
"parameters",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_base.py#L70-L106 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.