INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Calls Docker API to start the container. The container must be created at the first place to run. It waits for the container to complete fetches both stdout and stderr logs and returns through the given streams.
def start(self, input_data=None): """ Calls Docker API to start the container. The container must be created at the first place to run. It waits for the container to complete, fetches both stdout and stderr logs and returns through the given streams. Parameters ---------...
Based on the data returned from the Container output via the iterator write it to the appropriate streams
def _write_container_output(output_itr, stdout=None, stderr=None): """ Based on the data returned from the Container output, via the iterator, write it to the appropriate streams Parameters ---------- output_itr: Iterator Iterator returned by the Docker Attach comman...
\ b Initialize a serverless application with a SAM template folder structure for your Lambda functions connected to an event source such as APIs S3 Buckets or DynamoDB Tables. This application includes everything you need to get started with serverless and eventually grow into a production scale application. \ b This c...
def cli(ctx, location, runtime, dependency_manager, output_dir, name, no_input): """ \b Initialize a serverless application with a SAM template, folder structure for your Lambda functions, connected to an event source such as APIs, S3 Buckets or DynamoDB Tables. This application includes eve...
Implementation of the cli method just separated out for unit testing purposes
def do_cli(ctx, location, runtime, dependency_manager, output_dir, name, no_input): """ Implementation of the ``cli`` method, just separated out for unit testing purposes """ LOG.debug("Init command") click.secho("[+] Initializing project structure...", fg="green") no_build_msg = """ Project ge...
Implementation of the cli method
def do_cli(function_identifier, # pylint: disable=too-many-locals template, base_dir, build_dir, clean, use_container, manifest_path, docker_network, skip_pull_image, parameter_overrides, mode): """ Im...
Parses a swagger document and returns a list of APIs configured in the document.
def get_apis(self): """ Parses a swagger document and returns a list of APIs configured in the document. Swagger documents have the following structure { "/path1": { # path "get": { # method "x-amazon-apigateway-integration": { # in...
Tries to parse the Lambda Function name from the Integration defined in the method configuration. Integration configuration is defined under the special x - amazon - apigateway - integration key. We care only about Lambda integrations which are of type aws_proxy and ignore the rest. Integration URI is complex and hard ...
def _get_integration_function_name(self, method_config): """ Tries to parse the Lambda Function name from the Integration defined in the method configuration. Integration configuration is defined under the special "x-amazon-apigateway-integration" key. We care only about Lambda integrati...
Implementation of the cli method just separated out for unit testing purposes
def do_cli(ctx, host, port, template, env_vars, debug_port, debug_args, # pylint: disable=R0914 debugger_path, docker_volume_basedir, docker_network, log_file, layer_cache_basedir, skip_pull_image, force_image_build, parameter_overrides): """ Implementation of the ``cli`` method, just sep...
Formats the given CloudWatch Logs Event dictionary as necessary and returns an iterable that will return the formatted string. This can be used to parse and format the events based on context ie. In Lambda Function logs a formatter may wish to color the ERROR keywords red or highlight a filter keyword separately etc.
def do_format(self, event_iterable): """ Formats the given CloudWatch Logs Event dictionary as necessary and returns an iterable that will return the formatted string. This can be used to parse and format the events based on context ie. In Lambda Function logs, a formatter may wish to co...
Basic formatter to convert an event object to string
def _pretty_print_event(event, colored): """ Basic formatter to convert an event object to string """ event.timestamp = colored.yellow(event.timestamp) event.log_stream_name = colored.cyan(event.log_stream_name) return ' '.join([event.log_stream_name, event.timestamp, ev...
Highlights some commonly known Lambda error cases in red: - Nodejs process crashes - Lambda function timeouts
def colorize_errors(event, colored): """ Highlights some commonly known Lambda error cases in red: - Nodejs process crashes - Lambda function timeouts """ nodejs_crash_msg = "Process exited before completing request" timeout_msg = "Task timed out" ...
Highlight the keyword in the log statement by drawing an underline
def highlight_keywords(self, event, colored): """ Highlight the keyword in the log statement by drawing an underline """ if self.keyword: highlight = colored.underline(self.keyword) event.message = event.message.replace(self.keyword, highlight) return eve...
If the event message is a JSON string then pretty print the JSON with 2 indents and sort the keys. This makes it very easy to visually parse and search JSON data
def format_json(event, colored): """ If the event message is a JSON string, then pretty print the JSON with 2 indents and sort the keys. This makes it very easy to visually parse and search JSON data """ try: if event.message.startswith("{"): msg_dict...
Read the template file parse it as JSON/ YAML and return the template as a dictionary.
def get_template_data(template_file): """ Read the template file, parse it as JSON/YAML and return the template as a dictionary. Parameters ---------- template_file : string Path to the template to read Returns ------- Template data as a dictionary """ if not pathlib.P...
Move the SAM/ CloudFormation template from src_template_path to dest_template_path. For convenience this method accepts a dictionary of template data template_dict that will be written to the destination instead of reading from the source file.
def move_template(src_template_path, dest_template_path, template_dict): """ Move the SAM/CloudFormation template from ``src_template_path`` to ``dest_template_path``. For convenience, this method accepts a dictionary of template data ``template_dict`` that will be writte...
SAM/ CloudFormation template can contain certain properties whose value is a relative path to a local file/ folder. This path is usually relative to the template s location. If the template is being moved from original location original_root to new location new_root use this method to update these paths to be relative ...
def _update_relative_paths(template_dict, original_root, new_root): """ SAM/CloudFormation template can contain certain properties whose value is a relative path to a local file/folder. This path is usually relative to the template's location. If the tem...
Update relative paths in AWS:: Include directive. This directive can be present at any part of the template and not just within resources.
def _update_aws_include_relative_path(template_dict, original_root, new_root): """ Update relative paths in "AWS::Include" directive. This directive can be present at any part of the template, and not just within resources. """ for key, val in template_dict.items(): if key == "Fn::Transform...
If the given path is a relative path then assume it is relative to original_root. This method will update the path to be resolve it relative to new_root and return.
def _resolve_relative_to(path, original_root, new_root): """ If the given ``path`` is a relative path, then assume it is relative to ``original_root``. This method will update the path to be resolve it relative to ``new_root`` and return. Examples ------- # Assume a file called template.txt...
If the input data is an AWS:: Include data then parse and return the location of the included file.
def parse_aws_include_transform(data): """ If the input data is an AWS::Include data, then parse and return the location of the included file. AWS::Include transform data usually has the following format: { "Fn::Transform": { "Name": "AWS::Include", "Parameters": { ...
Gets the Swagger document from either of the given locations. If we fail to retrieve or parse the Swagger file this method will return None.
def read(self): """ Gets the Swagger document from either of the given locations. If we fail to retrieve or parse the Swagger file, this method will return None. Returns ------- dict: Swagger document. None, if we cannot retrieve the document """ ...
Read the Swagger document from DefinitionBody. It could either be an inline Swagger dictionary or an AWS:: Include macro that contains location of the included Swagger. In the later case we will download and parse the Swagger document.
def _read_from_definition_body(self): """ Read the Swagger document from DefinitionBody. It could either be an inline Swagger dictionary or an AWS::Include macro that contains location of the included Swagger. In the later case, we will download and parse the Swagger document. R...
Download the file from given local or remote location and return it
def _download_swagger(self, location): """ Download the file from given local or remote location and return it Parameters ---------- location : str or dict Local path or S3 path to Swagger file to download. Consult the ``__init__.py`` documentation for specifics ...
Download a file from given S3 location if available.
def _download_from_s3(bucket, key, version=None): """ Download a file from given S3 location, if available. Parameters ---------- bucket : str S3 Bucket name key : str S3 Bucket Key aka file path version : str Optional Versio...
Parses the given location input as a S3 Location and returns the file s bucket key and version as separate values. Input can be in two different formats:
def _parse_s3_location(location): """ Parses the given location input as a S3 Location and returns the file's bucket, key and version as separate values. Input can be in two different formats: 1. Dictionary with ``Bucket``, ``Key``, ``Version`` keys 2. String of S3 URI in format...
Turn on debug logging if necessary.
def debug(self, value): """ Turn on debug logging if necessary. :param value: Value of debug flag """ self._debug = value if self._debug: # Turn on debug logging logging.getLogger().setLevel(logging.DEBUG)
Update boto3 s default session by creating a new session based on values set in the context. Some properties of the Boto3 s session object are read - only. Therefore when Click parses new AWS session related properties ( like region & profile ) it will call this method to create a new session with latest values for the...
def _refresh_session(self): """ Update boto3's default session by creating a new session based on values set in the context. Some properties of the Boto3's session object are read-only. Therefore when Click parses new AWS session related properties (like region & profile), it will call t...
Generates project using cookiecutter and options given
def generate_project( location=None, runtime="nodejs", dependency_manager=None, output_dir=".", name='sam-sample-app', no_input=False): """Generates project using cookiecutter and options given Generate project scaffolds a project using default templates if user doesn't provide one via loca...
Convert the given date to UTC if the date contains a timezone.
def to_utc(some_time): """ Convert the given date to UTC, if the date contains a timezone. Parameters ---------- some_time : datetime.datetime datetime object to convert to UTC Returns ------- datetime.datetime Converted datetime object """ # Convert timezone a...
Parse the given string as datetime object. This parser supports in almost any string formats.
def parse_date(date_string): """ Parse the given string as datetime object. This parser supports in almost any string formats. For relative times, like `10min ago`, this parser computes the actual time relative to current UTC time. This allows time to always be in UTC if an explicit time zone is not pr...
Returns name of the function to invoke. If no function identifier is provided this method will return name of the only function from the template
def function_name(self): """ Returns name of the function to invoke. If no function identifier is provided, this method will return name of the only function from the template :return string: Name of the function :raises InvokeContextException: If function identifier is not prov...
Returns an instance of the runner capable of running Lambda functions locally
def local_lambda_runner(self): """ Returns an instance of the runner capable of running Lambda functions locally :return samcli.commands.local.lib.local_lambda.LocalLambdaRunner: Runner configured to run Lambda functions locally """ layer_downloader = LayerDownloade...
Returns stream writer for stdout to output Lambda function logs to
def stdout(self): """ Returns stream writer for stdout to output Lambda function logs to Returns ------- samcli.lib.utils.stream_writer.StreamWriter Stream writer for stdout """ stream = self._log_file_handle if self._log_file_handle else osutils.stdo...
Returns stream writer for stderr to output Lambda function errors to
def stderr(self): """ Returns stream writer for stderr to output Lambda function errors to Returns ------- samcli.lib.utils.stream_writer.StreamWriter Stream writer for stderr """ stream = self._log_file_handle if self._log_file_handle else osutils.st...
Get the working directory. This is usually relative to the directory that contains the template. If a Docker volume location is specified it takes preference
def get_cwd(self): """ Get the working directory. This is usually relative to the directory that contains the template. If a Docker volume location is specified, it takes preference All Lambda function code paths are resolved relative to this working directory :return string: W...
If the user provided a file containing values of environment variables this method will read the file and return its value
def _get_env_vars_value(filename): """ If the user provided a file containing values of environment variables, this method will read the file and return its value :param string filename: Path to file containing environment variable values :return dict: Value of environment varia...
Creates a DebugContext if the InvokeContext is in a debugging mode
def _get_debug_context(debug_port, debug_args, debugger_path): """ Creates a DebugContext if the InvokeContext is in a debugging mode Parameters ---------- debug_port int Port to bind the debugger to debug_args str Additional arguments passed to ...
The stdout and stderr data from the container multiplexed into one stream of response from the Docker API. It follows the protocol described here https:// docs. docker. com/ engine/ api/ v1. 30/ #operation/ ContainerAttach. The stream starts with a 8 byte header that contains the frame type and also payload size. Follw...
def _read_socket(socket): """ The stdout and stderr data from the container multiplexed into one stream of response from the Docker API. It follows the protocol described here https://docs.docker.com/engine/api/v1.30/#operation/ContainerAttach. The stream starts with a 8 byte header that contains the fr...
From the given socket reads and yields payload of the given size. With sockets we don t receive all data at once. Therefore this method will yield each time we read some data from the socket until the payload_size has reached or socket has no more data.
def _read_payload(socket, payload_size): """ From the given socket, reads and yields payload of the given size. With sockets, we don't receive all data at once. Therefore this method will yield each time we read some data from the socket until the payload_size has reached or socket has no more data. ...
Configures -- debug option for CLI
def debug_option(f): """ Configures --debug option for CLI :param f: Callback Function to be passed to Click """ def callback(ctx, param, value): state = ctx.ensure_object(Context) state.debug = value return value return click.option('--debug', e...
Configures -- region option for CLI
def region_option(f): """ Configures --region option for CLI :param f: Callback Function to be passed to Click """ def callback(ctx, param, value): state = ctx.ensure_object(Context) state.region = value return value return click.option('--region', ...
Configures -- profile option for CLI
def profile_option(f): """ Configures --profile option for CLI :param f: Callback Function to be passed to Click """ def callback(ctx, param, value): state = ctx.ensure_object(Context) state.profile = value return value return click.option('--profile', ...
Creates a Lambda Service ResourceNotFound Response
def resource_not_found(function_name): """ Creates a Lambda Service ResourceNotFound Response Parameters ---------- function_name str Name of the function that was requested to invoke Returns ------- Flask.Response A response obje...
Creates a Lambda Service InvalidRequestContent Response
def invalid_request_content(message): """ Creates a Lambda Service InvalidRequestContent Response Parameters ---------- message str Message to be added to the body of the response Returns ------- Flask.Response A response object r...
Creates a Lambda Service UnsupportedMediaType Response
def unsupported_media_type(content_type): """ Creates a Lambda Service UnsupportedMediaType Response Parameters ---------- content_type str Content Type of the request that was made Returns ------- Flask.Response A response object...
Creates a Lambda Service Generic ServiceException Response
def generic_service_exception(*args): """ Creates a Lambda Service Generic ServiceException Response Parameters ---------- args list List of arguments Flask passes to the method Returns ------- Flask.Response A response object rep...
Creates a Lambda Service Generic PathNotFound Response
def generic_path_not_found(*args): """ Creates a Lambda Service Generic PathNotFound Response Parameters ---------- args list List of arguments Flask passes to the method Returns ------- Flask.Response A response object representi...
Creates a Lambda Service Generic MethodNotAllowed Response
def generic_method_not_allowed(*args): """ Creates a Lambda Service Generic MethodNotAllowed Response Parameters ---------- args list List of arguments Flask passes to the method Returns ------- Flask.Response A response object re...
Implementation of the cli method just separated out for unit testing purposes
def do_cli(ctx, template): """ Implementation of the ``cli`` method, just separated out for unit testing purposes """ sam_template = _read_sam_file(template) iam_client = boto3.client('iam') validator = SamTemplateValidator(sam_template, ManagedPolicyLoader(iam_client)) try: valid...
Reads the file ( json and yaml supported ) provided and returns the dictionary representation of the file.
def _read_sam_file(template): """ Reads the file (json and yaml supported) provided and returns the dictionary representation of the file. :param str template: Path to the template file :return dict: Dictionary representing the SAM Template :raises: SamTemplateNotFoundException when the template fi...
Returns path to the function code resolved based on current working directory.
def resolve_code_path(cwd, codeuri): """ Returns path to the function code resolved based on current working directory. Parameters ---------- cwd str Current working directory codeuri CodeURI of the function. This should contain the path to the function code Returns ---...
Converts a Path from an Api Gateway defined path to one that is accepted by Flask
def convert_path_to_flask(path): """ Converts a Path from an Api Gateway defined path to one that is accepted by Flask Examples: '/id/{id}' => '/id/<id>' '/{proxy+}' => '/<path:proxy>' :param str path: Path to convert to Flask defined path :return str: Path rep...
Converts a Path from a Flask defined path to one that is accepted by Api Gateway
def convert_path_to_api_gateway(path): """ Converts a Path from a Flask defined path to one that is accepted by Api Gateway Examples: '/id/<id>' => '/id/{id}' '/<path:proxy>' => '/{proxy+}' :param str path: Path to convert to Api Gateway defined path :return st...
Gets the name of the function from the Integration URI ARN. This is a best effort service which returns None if function name could not be parsed. This can happen when the ARN is an intrinsic function which is too complex or the ARN is not a Lambda integration.
def get_function_name(integration_uri): """ Gets the name of the function from the Integration URI ARN. This is a best effort service which returns None if function name could not be parsed. This can happen when the ARN is an intrinsic function which is too complex or the ARN is not a La...
Integration URI can be expressed in various shapes and forms. This method normalizes the Integration URI ARN and returns the Lambda Function ARN. Here are the different forms of Integration URI ARN:
def _get_function_arn(uri_data): """ Integration URI can be expressed in various shapes and forms. This method normalizes the Integration URI ARN and returns the Lambda Function ARN. Here are the different forms of Integration URI ARN: - String: - Fully resolved ARN ...
Given the integration ARN extract the Lambda function name from the ARN. If there are stage variables or other unsupported formats this function will return None.
def _get_function_name_from_arn(function_arn): """ Given the integration ARN, extract the Lambda function name from the ARN. If there are stage variables, or other unsupported formats, this function will return None. Parameters ---------- function_arn : basestring or Non...
Tries to resolve an Integration URI which contains Fn:: Sub intrinsic function. This method tries to resolve and produce a string output.
def _resolve_fn_sub(uri_data): """ Tries to resolve an Integration URI which contains Fn::Sub intrinsic function. This method tries to resolve and produce a string output. Example: { "Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/funct...
Is this input data a Fn:: Sub intrinsic function
def _is_sub_intrinsic(data): """ Is this input data a Fn::Sub intrinsic function Parameters ---------- data Data to check Returns ------- bool True if the data Fn::Sub intrinsic function """ return isinstance(data,...
Implementation of the cli method just separated out for unit testing purposes
def do_cli(ctx, function_identifier, template, event, no_event, env_vars, debug_port, # pylint: disable=R0914 debug_args, debugger_path, docker_volume_basedir, docker_network, log_file, layer_cache_basedir, skip_pull_image, force_image_build, parameter_overrides): """ Implementation of th...
Read the event JSON data from the given file. If no file is provided read the event from stdin.
def _get_event(event_file_name): """ Read the event JSON data from the given file. If no file is provided, read the event from stdin. :param string event_file_name: Path to event file, or '-' for stdin :return string: Contents of the event file or stdin """ if event_file_name == STDIN_FILE_NAM...
Normalize all Resources in the template with the Metadata Key on the resource.
def normalize(template_dict): """ Normalize all Resources in the template with the Metadata Key on the resource. This method will mutate the template Parameters ---------- template_dict dict Dictionary representing the template """ resources...
Replace a property with an asset on a given resource
def _replace_property(property_key, property_value, resource, logical_id): """ Replace a property with an asset on a given resource This method will mutate the template Parameters ---------- property str The property to replace on the resource proper...
Extract the command name from package name. Last part of the module path is the command ie. if path is foo. bar. baz then baz is the command name.
def _set_commands(package_names): """ Extract the command name from package name. Last part of the module path is the command ie. if path is foo.bar.baz, then "baz" is the command name. :param package_names: List of package names :return: Dictionary with command name as key and ...
Overrides method from click. MultiCommand that returns Click CLI object for given command name if found.
def get_command(self, ctx, cmd_name): """ Overrides method from ``click.MultiCommand`` that returns Click CLI object for given command name, if found. :param ctx: Click context :param cmd_name: Top-level command name :return: Click object representing the command """ ...
Writes specified text to the underlying stream
def write(self, output): """ Writes specified text to the underlying stream Parameters ---------- output bytes-like object Bytes to write """ self._stream.write(output) if self._auto_flush: self._stream.flush()
Get a workflow config that corresponds to the runtime provided. This method examines contents of the project and code directories to determine the most appropriate workflow for the given runtime. Currently the decision is based on the presence of a supported manifest file. For runtimes that have more than one workflow ...
def get_workflow_config(runtime, code_dir, project_dir): """ Get a workflow config that corresponds to the runtime provided. This method examines contents of the project and code directories to determine the most appropriate workflow for the given runtime. Currently the decision is based on the presence...
Given a workflow config this method provides a boolean on whether the workflow can run within a container or not.
def supports_build_in_container(config): """ Given a workflow config, this method provides a boolean on whether the workflow can run within a container or not. Parameters ---------- config namedtuple(Capability) Config specifying the particular build workflow Returns ------- tu...
Finds a configuration by looking for a manifest in the given directories.
def get_config(self, code_dir, project_dir): """ Finds a configuration by looking for a manifest in the given directories. Returns ------- samcli.lib.build.workflow_config.CONFIG A supported configuration if one is found Raises ------ ValueEr...
YAML constructor to parse CloudFormation intrinsics. This will return a dictionary with key being the instrinsic name
def intrinsics_multi_constructor(loader, tag_prefix, node): """ YAML constructor to parse CloudFormation intrinsics. This will return a dictionary with key being the instrinsic name """ # Get the actual tag name excluding the first exclamation tag = node.tag[1:] # Some intrinsic functions ...
Parse a yaml string
def yaml_parse(yamlstr): """Parse a yaml string""" try: # PyYAML doesn't support json as well as it should, so if the input # is actually just json it is better to parse it with the standard # json parser. return json.loads(yamlstr) except ValueError: yaml.SafeLoader....
reads the encoding type from the event - mapping. json and determines whether a value needs encoding
def encode(self, tags, encoding, values_to_sub): """ reads the encoding type from the event-mapping.json and determines whether a value needs encoding Parameters ---------- tags: dict the values of a particular event that can be substituted within...
opens the event json substitutes the values in and returns the customized event json
def generate_event(self, service_name, event_type, values_to_sub): """ opens the event json, substitutes the values in, and returns the customized event json Parameters ---------- service_name: string name of the top level service (S3, apigateway, etc) ...
Underline the input
def underline(self, msg): """Underline the input""" return click.style(msg, underline=True) if self.colorize else msg
Internal helper method to add colors to input
def _color(self, msg, color): """Internal helper method to add colors to input""" kwargs = {'fg': color} return click.style(msg, **kwargs) if self.colorize else msg
Fetch logs from all streams under the given CloudWatch Log Group and yields in the output. Optionally caller can filter the logs using a pattern or a start/ end time.
def fetch(self, log_group_name, start=None, end=None, filter_pattern=None): """ Fetch logs from all streams under the given CloudWatch Log Group and yields in the output. Optionally, caller can filter the logs using a pattern or a start/end time. Parameters ---------- lo...
** This is a long blocking call **
def tail(self, log_group_name, start=None, filter_pattern=None, max_retries=1000, poll_interval=0.3): """ ** This is a long blocking call ** Fetches logs from CloudWatch logs similar to the ``fetch`` method, but instead of stopping after all logs have been fetched, this method continues...
Parses out the Layer version from the arn
def _compute_layer_version(is_defined_within_template, arn): """ Parses out the Layer version from 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 Resourc...
Computes a unique name based on the LayerVersion Arn
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 ...
Context manager that makes a temporary directory and yields it name. Directory is deleted after the context exits
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 the stdout as a byte stream in a Py2/ PY3 compatible manner
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 t...
Returns the stderr as a byte stream in a Py2/ PY3 compatible manner
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 t...
Download a list of layers to the cache
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 ...
Download a given layer to the local cache.
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 i...
Fetch the Layer Uri based on the LayerVersion Arn
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...
Create the Cache directory if it does not exist.
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...
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
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 InvalidSam...
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 )
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 o...
Updates the property_key in the resource_property_dict to the value of s3_uri_value
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 ----...
Creates and returns a Formatter capable of nicely formatting Lambda function logs
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 t...
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.
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...
Parse the time from the given string convert to UTC and return the datetime object
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 cam...
Given the LogicalID of a resource call AWS CloudFormation to get physical ID of the resource within the specified 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 ...
Given a SAM template dictionary return a cleaned copy of the template where SAM plugins have been run and parameter values have been substituted.
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 unproc...
In the given template apply parameter values to resolve intrinsic functions
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 p...
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.
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 ---------- t...
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
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: defaul...
Change the code_path to be of unix - style if running on windows when supplied with an absolute windows 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 ------- ...
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.
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: Dictiona...
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.
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 entr...
Extract all Implicit Apis ( Apis defined through Serverless Function with an Api Event
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, Co...
Extract APIs from AWS:: Serverless:: Api resource by reading and parsing Swagger documents. The result is added to the collector.
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 ...