text
stringlengths
81
112k
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 st...
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 Pa...
Returns the stdout as a byte stream in a Py2/PY3 compatible manner Returns ------- io.BytesIO Byte stream of Stdout def stdout(): """ Returns the stdout as a byte stream in a Py2/PY3 compatible manner Returns ------- io.BytesIO Byte stream of Stdout """ # We w...
Returns the stderr as a byte stream in a Py2/PY3 compatible manner Returns ------- io.BytesIO Byte stream of stderr def stderr(): """ Returns the stderr as a byte stream in a Py2/PY3 compatible manner Returns ------- io.BytesIO Byte stream of stderr """ # We w...
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 Return...
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 -...
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 ----...
Create the Cache directory if it does not exist. Parameters ---------- layer_cache Directory to where the layers should be cached Returns ------- None def _create_cache(layer_cache): """ Create the Cache directory if it does not exist. ...
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 def is_vali...
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 loca...
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_d...
Creates and returns a Formatter capable of nicely formatting Lambda function logs Returns ------- LogsFormatter def formatter(self): """ Creates and returns a Formatter capable of nicely formatting Lambda function logs Returns ------- LogsFormatter ...
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 def log_group_name(self): """ Name of the AWS CloudWatch Log ...
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 ...
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 logi...
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 Op...
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 ...
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_override...
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 ...
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 ...
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. d...
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 runtim...
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 def _extract_apis(self, resources): """ Extract all Implicit Apis (Apis defined through Serverless Func...
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 prope...
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 ...
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 d...
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 ...
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 Dictionar...
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 name...
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) def _normalize_h...
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 def add_apis(self, logical...
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 def add_bin...
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 ---------- ...
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.ApiColle...
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 def _unzip_file(filepath): """ Helper method to unzip a file to a temporary directory :param string filepath: Absolute pa...
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...
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 c...
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 ...
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 ...
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 Strin...
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 m...
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 ...
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 tha...
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) Li...
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: Mountin...
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 ...
Creates a Flask Application that can be started. 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, ...
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-I...
Updates the Flask app with Error Handlers for different Error Codes 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.r...
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 ...
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...
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 def...
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 ...
Creates a Flask Application that can be started. 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_di...
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 def _generate_route_keys(self, methods, path): """ Generates the key...
Updates the Flask app with Error Handlers for different Error Codes 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.rou...
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 ...
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 def _get_current_route(self, flask_request): """ Get the route (Route) based on the current request :param request flas...
Parses the output from the Lambda Container :param str lambda_output: Output from Lambda Invoke :return: Tuple(int, dict, str, bool) def _parse_lambda_output(lambda_output, binary_types, flask_request): """ Parses the output from the Lambda Container :param str lambda_output: ...
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 di...
Helper method that constructs the Event to be passed to Lambda :param request flask_request: Flask Request :return: String representing the event def _construct_event(flask_request, port, binary_types): """ Helper method that constructs the Event to be passed to Lambda :param ...
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 def _...
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...
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 def _...
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.EnvironmentVariabl...
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 def get_aws...
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON :return: dict representing the object def to_dict(self): """ Constructs an dictionary representation of the Identity Object to be used in serializing to JSON :return: dict representing the...
Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON :return: dict representing the object def to_dict(self): """ Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON :return: dict repr...
Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON :return: dict representing the object def to_dict(self): """ Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON :ret...
Implementation of the ``cli`` method 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, ...
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 def is_docker_reachable(self): """ Checks if Docker daemon is running. This is required for us to invoke the...
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...
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 ------ Docker...
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 def has_image(self, image_name): """ Is the container image with given name available? :param string image_name: Name of th...
Publish the application based on command line inputs. 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 User...
Generate detailed success message for published applications. Parameters ---------- publish_output : dict Output from serverlessrepo publish_application Returns ------- str Detailed success message def _gen_success_message(publish_output): """ Generate detailed success...
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 def _print_console_link(region, application_id): """ Print link for the app...
Helper function to create a Lambda Failure Response :return: A Flask Response def lambda_failure_response(*args): """ Helper function to create a Lambda Failure Response :return: A Flask Response """ response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE) ...
Constructs a Flask Response for when a Lambda function is not found for an endpoint :return: a Flask 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 """ res...
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 def route_not_found(*args): """ Constructs a Flask Respon...
Creates a progressbar Parameters ---------- length int Length of the ProgressBar label str Label to give to the progressbar Returns ------- click.progressbar Progressbar def progressbar(length, label): """ Creates a progressbar Parameters ---------...
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 ---------- ...
This starts up the (threaded) Local Server. Note: This is a **blocking call** Raises ------ RuntimeError if the service was not created def run(self): """ This starts up the (threaded) Local Server. Note: This is a **blocking call** Raises ...
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 def service_response(body, headers, status_code): ...
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 ...
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/Exce...
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 def build(self): """ Build the entire application Returns ------- dict Return...
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 ...
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 ...
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 ...
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 con...
This method is unused and a Work In Progress 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(), ...
This method is unused and a Work In Progress 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 s...
Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template 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 ...
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, No...
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 C...
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...
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, res...
Iteratively adds features to the model 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...
Selects features for the model. see explain_instance_with_data to understand the parameters. 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 == 'n...