Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function:def set_path_default_authorizer(self, path, default_authorizer, authorizers): for method_name, method in self.get_path(path).items(): self.set_method_authorizer(path, method_name, default_authorizer, authorizers, default_authorizer=default_authorizer, is_default=True)
[ "\n Sets the DefaultAuthorizer for each method on this path. The DefaultAuthorizer won't be set if an Authorizer\n was defined at the Function/Path/Method level\n\n :param string path: Path name\n :param string default_authorizer: Name of the authorizer to use as the default. Must be a key in the\n authorizers param.\n :param list authorizers: List of Authorizer configurations defined on the related Api.\n " ]
Please provide a description of the function:def add_auth_to_method(self, path, method_name, auth, api): method_authorizer = auth and auth.get('Authorizer') if method_authorizer: api_auth = api.get('Auth') api_authorizers = api_auth and api_auth.get('Authorizers') default_authorizer = api_auth and api_auth.get('DefaultAuthorizer') self.set_method_authorizer(path, method_name, method_authorizer, api_authorizers, default_authorizer)
[ "\n Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers\n but this method will eventually include setting other auth settings such as API Key,\n Resource Policy, etc.\n\n :param string path: Path name\n :param string method_name: Method name\n :param dict auth: Auth configuration such as Authorizers, ApiKey, ResourcePolicy (only Authorizers supported\n currently)\n :param dict api: Reference to the related Api's properties as defined in the template.\n " ]
Please provide a description of the function:def add_gateway_responses(self, gateway_responses): self.gateway_responses = self.gateway_responses or {} for response_type, response in gateway_responses.items(): self.gateway_responses[response_type] = response.generate_swagger()
[ "\n Add Gateway Response definitions to Swagger.\n\n :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated.\n " ]
Please provide a description of the function:def swagger(self): # Make sure any changes to the paths are reflected back in output self._doc["paths"] = self.paths if self.security_definitions: self._doc["securityDefinitions"] = self.security_definitions if self.gateway_responses: self._doc[self._X_APIGW_GATEWAY_RESPONSES] = self.gateway_responses return copy.deepcopy(self._doc)
[ "\n Returns a **copy** of the Swagger document as a dictionary.\n\n :return dict: Dictionary containing the Swagger document\n " ]
Please provide a description of the function:def is_valid(data): return bool(data) and \ isinstance(data, dict) and \ bool(data.get("swagger")) and \ isinstance(data.get('paths'), dict)
[ "\n Checks if the input data is a Swagger document\n\n :param dict data: Data to be validated\n :return: True, if data is a Swagger\n " ]
Please provide a description of the function:def _normalize_method_name(method): if not method or not isinstance(method, string_types): return method method = method.lower() if method == 'any': return SwaggerEditor._X_ANY_METHOD else: return method
[ "\n Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods\n like \"ANY\"\n\n NOTE: Always normalize before using the `method` value passed in as input\n\n :param string method: Name of the HTTP Method\n :return string: Normalized method name\n " ]
Please provide a description of the function:def on_before_transform_template(self, template_dict): try: global_section = Globals(template_dict) except InvalidGlobalsSectionException as ex: raise InvalidDocumentException([ex]) # For each resource in template, try and merge with Globals if necessary template = SamTemplate(template_dict) for logicalId, resource in template.iterate(): resource.properties = global_section.merge(resource.type, resource.properties) template.set(logicalId, resource) # Remove the Globals section from template if necessary Globals.del_section(template_dict)
[ "\n Hook method that runs before a template gets transformed. In this method, we parse and process Globals section\n from the template (if present).\n\n :param dict template_dict: SAM template as a dictionary\n " ]
Please provide a description of the function:def is_type(valid_type): def validate(value, should_raise=True): if not isinstance(value, valid_type): if should_raise: raise TypeError("Expected value of type {expected}, actual value was of type {actual}.".format( expected=valid_type, actual=type(value))) return False return True return validate
[ "Returns a validator function that succeeds only for inputs of the provided valid_type.\n\n :param type valid_type: the type that should be considered valid for the validator\n :returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwise\n :rtype: callable\n " ]
Please provide a description of the function:def list_of(validate_item): def validate(value, should_raise=True): validate_type = is_type(list) if not validate_type(value, should_raise=should_raise): return False for item in value: try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "list contained an invalid item") raise return False return True return validate
[ "Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input\n to the provided validator validate_item.\n\n :param callable validate_item: the validator function for items in the list\n :returns: a function which returns True its input is an list of valid items, and raises TypeError otherwise\n :rtype: callable\n " ]
Please provide a description of the function:def dict_of(validate_key, validate_item): def validate(value, should_raise=True): validate_type = is_type(dict) if not validate_type(value, should_raise=should_raise): return False for key, item in value.items(): try: validate_key(key) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid key") raise return False try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid value") raise return False return True return validate
[ "Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes\n as input to the provided validators validate_key and validate_item, respectively.\n\n :param callable validate_key: the validator function for keys in the dict\n :param callable validate_item: the validator function for values in the list\n :returns: a function which returns True its input is an dict of valid items, and raises TypeError otherwise\n :rtype: callable\n " ]
Please provide a description of the function:def one_of(*validators): def validate(value, should_raise=True): if any(validate(value, should_raise=False) for validate in validators): return True if should_raise: raise TypeError("value did not match any allowable type") return False return validate
[ "Returns a validator function that succeeds only if the input passes at least one of the provided validators.\n\n :param callable validators: the validator functions\n :returns: a function which returns True its input passes at least one of the validators, and raises TypeError\n otherwise\n :rtype: callable\n " ]
Please provide a description of the function:def to_statement(self, parameter_values): missing = self.missing_parameter_values(parameter_values) if len(missing) > 0: # str() of elements of list to prevent any `u` prefix from being displayed in user-facing error message raise InsufficientParameterValues("Following required parameters of template '{}' don't have values: {}" .format(self.name, [str(m) for m in missing])) # Select only necessary parameter_values. this is to prevent malicious or accidental # injection of values for parameters not intended in the template. This is important because "Ref" resolution # will substitute any references for which a value is provided. necessary_parameter_values = {name: value for name, value in parameter_values.items() if name in self.parameters} # Only "Ref" is supported supported_intrinsics = { RefAction.intrinsic_name: RefAction() } resolver = IntrinsicsResolver(necessary_parameter_values, supported_intrinsics) definition_copy = copy.deepcopy(self.definition) return resolver.resolve_parameter_refs(definition_copy)
[ "\n With the given values for each parameter, this method will return a policy statement that can be used\n directly with IAM.\n\n :param dict parameter_values: Dict containing values for each parameter defined in the template\n :return dict: Dictionary containing policy statement\n :raises InvalidParameterValues: If parameter values is not a valid dictionary or does not contain values\n for all parameters\n :raises InsufficientParameterValues: If the parameter values don't have values for all required parameters\n " ]
Please provide a description of the function:def missing_parameter_values(self, parameter_values): if not self._is_valid_parameter_values(parameter_values): raise InvalidParameterValues("Parameter values are required to process a policy template") return list(set(self.parameters.keys()) - set(parameter_values.keys()))
[ "\n Checks if the given input contains values for all parameters used by this template\n\n :param dict parameter_values: Dictionary of values for each parameter used in the template\n :return list: List of names of parameters that are missing.\n :raises InvalidParameterValues: When parameter values is not a valid dictionary\n " ]
Please provide a description of the function:def from_dict(template_name, template_values_dict): parameters = template_values_dict.get("Parameters", {}) definition = template_values_dict.get("Definition", {}) return Template(template_name, parameters, definition)
[ "\n Parses the input and returns an instance of this class.\n\n :param string template_name: Name of the template\n :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed\n the JSON Schema validation.\n :return Template: Instance of this class containing the values provided in this dictionary\n " ]
Please provide a description of the function:def register(self, plugin): if not plugin or not isinstance(plugin, BasePlugin): raise ValueError("Plugin must be implemented as a subclass of BasePlugin class") if self.is_registered(plugin.name): raise ValueError("Plugin with name {} is already registered".format(plugin.name)) self._plugins.append(plugin)
[ "\n Register a plugin. New plugins are added to the end of the plugins list.\n\n :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks\n :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already\n registered\n :return: None\n " ]
Please provide a description of the function:def _get(self, plugin_name): for p in self._plugins: if p.name == plugin_name: return p return None
[ "\n Retrieves the plugin with given name\n\n :param plugin_name: Name of the plugin to retrieve\n :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise\n " ]
Please provide a description of the function:def act(self, event, *args, **kwargs): if not isinstance(event, LifeCycleEvents): raise ValueError("'event' must be an instance of LifeCycleEvents class") method_name = "on_" + event.name for plugin in self._plugins: if not hasattr(plugin, method_name): raise NameError("'{}' method is not found in the plugin with name '{}'" .format(method_name, plugin.name)) try: getattr(plugin, method_name)(*args, **kwargs) except InvalidResourceException as ex: # Don't need to log these because they don't result in crashes raise ex except Exception as ex: logging.exception("Plugin '%s' raised an exception: %s", plugin.name, ex) raise ex
[ "\n Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins.\n *args and **kwargs will be passed directly to the plugin's hook functions\n\n :param samtranslator.plugins.LifeCycleEvents event: Event to act upon\n :return: Nothing\n :raises ValueError: If event is not a valid life cycle event\n :raises NameError: If a plugin does not have the hook method defined\n :raises Exception: Any exception that a plugin raises\n " ]
Please provide a description of the function:def from_dict(cls, logical_id, deployment_preference_dict): enabled = deployment_preference_dict.get('Enabled', True) if not enabled: return DeploymentPreference(None, None, None, None, False, None) if 'Type' not in deployment_preference_dict: raise InvalidResourceException(logical_id, "'DeploymentPreference' is missing required Property 'Type'") deployment_type = deployment_preference_dict['Type'] hooks = deployment_preference_dict.get('Hooks', dict()) if not isinstance(hooks, dict): raise InvalidResourceException(logical_id, "'Hooks' property of 'DeploymentPreference' must be a dictionary") pre_traffic_hook = hooks.get('PreTraffic', None) post_traffic_hook = hooks.get('PostTraffic', None) alarms = deployment_preference_dict.get('Alarms', None) role = deployment_preference_dict.get('Role', None) return DeploymentPreference(deployment_type, pre_traffic_hook, post_traffic_hook, alarms, enabled, role)
[ "\n :param logical_id: the logical_id of the resource that owns this deployment preference\n :param deployment_preference_dict: the dict object taken from the SAM template\n :return:\n " ]
Please provide a description of the function:def decrypt(message): '''decrypt leverages KMS decrypt and base64-encode decrypted blob More info on KMS decrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_decrypt.html ''' try: ret = kms.decrypt( CiphertextBlob=base64.decodestring(message)) decrypted_data = ret.get('Plaintext') except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to decrypt data: ", e) return decrypted_data
[]
Please provide a description of the function:def prepend(exception, message, end=': '): exception.args = exception.args or ('',) exception.args = (message + end + exception.args[0], ) + exception.args[1:] return exception
[ "Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message.\n Useful for reraising exceptions with additional information.\n\n :param BaseException exception: the exception to prepend\n :param str message: the message to prepend\n :param str end: the separator to add to the end of the provided message\n :returns: the exception\n " ]
Please provide a description of the function:def lambda_handler(event, context): # incoming token value token = event['authorizationToken'] print("Method ARN: " + event['methodArn']) ''' Validate the incoming token and produce the principal user identifier associated with the token. This can be accomplished in a number of ways: 1. Call out to the OAuth provider 2. Decode a JWT token inline 3. Lookup in a self-managed DB ''' principalId = 'user|a1b2c3d4' ''' You can send a 401 Unauthorized response to the client by failing like so: raise Exception('Unauthorized') If the token is valid, a policy must be generated which will allow or deny access to the client. If access is denied, the client will receive a 403 Access Denied response. If access is allowed, API Gateway will proceed with the backend integration configured on the method that was called. This function must generate a policy that is associated with the recognized principal user identifier. Depending on your use case, you might store policies in a DB, or generate them on the fly. Keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) and will apply to subsequent calls to any method/resource in the RestApi made with the same token. The example policy below denies access to all resources in the RestApi. ''' tmp = event['methodArn'].split(':') apiGatewayArnTmp = tmp[5].split('/') awsAccountId = tmp[4] policy = AuthPolicy(principalId, awsAccountId) policy.restApiId = apiGatewayArnTmp[0] policy.region = tmp[3] policy.stage = apiGatewayArnTmp[1] policy.denyAllMethods() #policy.allowMethod(HttpVerb.GET, '/pets/*') # Finally, build the policy authResponse = policy.build() # new! -- add additional key-value pairs associated with the authenticated principal # these are made available by APIGW like so: $context.authorizer.<key> # additional context is cached context = { 'key': 'value', # $context.authorizer.key -> value 'number': 1, 'bool': True } # context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it # context['obj'] = {'foo':'bar'} <- also invalid authResponse['context'] = context return authResponse
[]
Please provide a description of the function:def _getStatementForEffect(self, effect, methods): '''This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.''' statements = [] if len(methods) > 0: statement = self._getEmptyStatement(effect) for curMethod in methods: if curMethod['conditions'] is None or len(curMethod['conditions']) == 0: statement['Resource'].append(curMethod['resourceArn']) else: conditionalStatement = self._getEmptyStatement(effect) conditionalStatement['Resource'].append(curMethod['resourceArn']) conditionalStatement['Condition'] = curMethod['conditions'] statements.append(conditionalStatement) if statement['Resource']: statements.append(statement) return statements
[]
Please provide a description of the function:def on_before_transform_resource(self, logical_id, resource_type, resource_properties): if not self._is_supported(resource_type): return function_policies = FunctionPolicies(resource_properties, self._policy_template_processor) if len(function_policies) == 0: # No policies to process return result = [] for policy_entry in function_policies.get(): if policy_entry.type is not PolicyTypes.POLICY_TEMPLATE: # If we don't know the type, skip processing and pass to result as is. result.append(policy_entry.data) continue # We are processing policy templates. We know they have a particular structure: # {"templateName": { parameter_values_dict }} template_data = policy_entry.data template_name = list(template_data.keys())[0] template_parameters = list(template_data.values())[0] try: # 'convert' will return a list of policy statements result.append(self._policy_template_processor.convert(template_name, template_parameters)) except InsufficientParameterValues as ex: # Exception's message will give lot of specific details raise InvalidResourceException(logical_id, str(ex)) except InvalidParameterValues: raise InvalidResourceException(logical_id, "Must specify valid parameter values for policy template '{}'" .format(template_name)) # Save the modified policies list to the input resource_properties[FunctionPolicies.POLICIES_PROPERTY_NAME] = result
[ "\n Hook method that gets called before \"each\" SAM resource gets processed\n\n :param string logical_id: Logical ID of the resource being processed\n :param string resource_type: Type of the resource being processed\n :param dict resource_properties: Properties of the resource\n :return: Nothing\n " ]
Please provide a description of the function:def lambda_handler(event, context): '''A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.''' raw_kpl_records = event['records'] output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records] # Print number of successful and failed records. success_count = sum(1 for record in output if record['result'] == 'Ok') failure_count = sum(1 for record in output if record['result'] == 'ProcessingFailed') print('Processing completed. Successful records: {0}, Failed records: {1}.'.format(success_count, failure_count)) return {'records': output}
[]
Please provide a description of the function:def transform(input_fragment, parameter_values, managed_policy_loader): sam_parser = Parser() translator = Translator(managed_policy_loader.load(), sam_parser) return translator.translate(input_fragment, parameter_values=parameter_values)
[ "Translates the SAM manifest provided in the and returns the translation to CloudFormation.\n\n :param dict input_fragment: the SAM template to transform\n :param dict parameter_values: Parameter values provided by the user\n :returns: the transformed CloudFormation template\n :rtype: dict\n " ]
Please provide a description of the function:def to_dict(self): dict_with_nones = self._asdict() codedeploy_lambda_alias_update_dict = dict((k, v) for k, v in dict_with_nones.items() if v != ref(None) and v is not None) return {'CodeDeployLambdaAliasUpdate': codedeploy_lambda_alias_update_dict}
[ "\n :return: a dict that can be used as part of a cloudformation template\n " ]
Please provide a description of the function:def on_before_transform_template(self, template_dict): template = SamTemplate(template_dict) # Temporarily add Serverless::Api resource corresponding to Implicit API to the template. # This will allow the processing code to work the same way for both Implicit & Explicit APIs # If there are no implicit APIs, we will remove from the template later. # If the customer has explicitly defined a resource with the id of "ServerlessRestApi", # capture it. If the template ends up not defining any implicit api's, instead of just # removing the "ServerlessRestApi" resource, we just restore what the author defined. self.existing_implicit_api_resource = copy.deepcopy(template.get(self.implicit_api_logical_id)) template.set(self.implicit_api_logical_id, ImplicitApiResource().to_dict()) errors = [] for logicalId, function in template.iterate(SamResourceType.Function.value): api_events = self._get_api_events(function) condition = function.condition if len(api_events) == 0: continue try: self._process_api_events(function, api_events, template, condition) except InvalidEventException as ex: errors.append(InvalidResourceException(logicalId, ex.message)) self._maybe_add_condition_to_implicit_api(template_dict) self._maybe_add_conditions_to_implicit_api_paths(template) self._maybe_remove_implicit_api(template) if len(errors) > 0: raise InvalidDocumentException(errors)
[ "\n Hook method that gets called before the SAM template is processed.\n The template has pass the validation and is guaranteed to contain a non-empty \"Resources\" section.\n\n :param dict template_dict: Dictionary of the SAM template\n :return: Nothing\n " ]
Please provide a description of the function:def _get_api_events(self, function): if not (function.valid() and isinstance(function.properties, dict) and isinstance(function.properties.get("Events"), dict) ): # Function resource structure is invalid. return {} api_events = {} for event_id, event in function.properties["Events"].items(): if event and isinstance(event, dict) and event.get("Type") == "Api": api_events[event_id] = event return api_events
[ "\n Method to return a dictionary of API Events on the function\n\n :param SamResource function: Function Resource object\n :return dict: Dictionary of API events along with any other configuration passed to it.\n Example: {\n FooEvent: {Path: \"/foo\", Method: \"post\", RestApiId: blah, MethodSettings: {<something>},\n Cors: {<something>}, Auth: {<something>}},\n BarEvent: {Path: \"/bar\", Method: \"any\", MethodSettings: {<something>}, Cors: {<something>},\n Auth: {<something>}}\"\n }\n " ]
Please provide a description of the function:def _process_api_events(self, function, api_events, template, condition=None): for logicalId, event in api_events.items(): event_properties = event.get("Properties", {}) if not event_properties: continue self._add_implicit_api_id_if_necessary(event_properties) api_id = self._get_api_id(event_properties) try: path = event_properties["Path"] method = event_properties["Method"] except KeyError as e: raise InvalidEventException(logicalId, "Event is missing key {}.".format(e)) if (not isinstance(path, six.string_types)): raise InvalidEventException(logicalId, "Api Event must have a String specified for 'Path'.") if (not isinstance(method, six.string_types)): raise InvalidEventException(logicalId, "Api Event must have a String specified for 'Method'.") api_dict = self.api_conditions.setdefault(api_id, {}) method_conditions = api_dict.setdefault(path, {}) method_conditions[method] = condition self._add_api_to_swagger(logicalId, event_properties, template) api_events[logicalId] = event # We could have made changes to the Events structure. Write it back to function function.properties["Events"].update(api_events)
[ "\n Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api\n resource from the template\n\n :param SamResource function: SAM Function containing the API events to be processed\n :param dict api_events: API Events extracted from the function. These events will be processed\n :param SamTemplate template: SAM Template where Serverless::Api resources can be found\n :param str condition: optional; this is the condition that is on the function with the API event\n " ]
Please provide a description of the function:def _add_api_to_swagger(self, event_id, event_properties, template): # Need to grab the AWS::Serverless::Api resource for this API event and update its Swagger definition api_id = self._get_api_id(event_properties) # RestApiId is not pointing to a valid API resource if isinstance(api_id, dict) or not template.get(api_id): raise InvalidEventException(event_id, "RestApiId must be a valid reference to an 'AWS::Serverless::Api' resource " "in same template") # Make sure Swagger is valid resource = template.get(api_id) if not (resource and isinstance(resource.properties, dict) and SwaggerEditor.is_valid(resource.properties.get("DefinitionBody"))): # This does not have an inline Swagger. Nothing can be done about it. return if not resource.properties.get("__MANAGE_SWAGGER"): # Do not add the api to Swagger, if the resource is not actively managed by SAM. # ie. Implicit API resources are created & managed by SAM on behalf of customers. # But for explicit API resources, customers write their own Swagger and manage it. # If a path is present in Events section but *not* present in the Explicit API Swagger, then it is # customer's responsibility to add to Swagger. We will not modify the Swagger here. # # In the future, we will might expose a flag that will allow SAM to manage explicit API Swagger as well. # Until then, we will not modify explicit explicit APIs. return swagger = resource.properties.get("DefinitionBody") path = event_properties["Path"] method = event_properties["Method"] editor = SwaggerEditor(swagger) editor.add_path(path, method) resource.properties["DefinitionBody"] = editor.swagger template.set(api_id, resource)
[ "\n Adds the API path/method from the given event to the Swagger JSON of Serverless::Api resource this event\n refers to.\n\n :param string event_id: LogicalId of the event\n :param dict event_properties: Properties of the event\n :param SamTemplate template: SAM Template to search for Serverless::Api resources\n " ]
Please provide a description of the function:def _get_api_id(self, event_properties): api_id = event_properties.get("RestApiId") if isinstance(api_id, dict) and "Ref" in api_id: api_id = api_id["Ref"] return api_id
[ "\n Get API logical id from API event properties.\n\n Handles case where API id is not specified or is a reference to a logical id.\n " ]
Please provide a description of the function:def _maybe_add_condition_to_implicit_api(self, template_dict): # Short-circuit if template doesn't have any functions with implicit API events if not self.api_conditions.get(self.implicit_api_logical_id, {}): return # Add a condition to the API resource IFF all of its resource+methods are associated with serverless functions # containing conditions. implicit_api_conditions = self.api_conditions[self.implicit_api_logical_id] all_resource_method_conditions = set([condition for path, method_conditions in implicit_api_conditions.items() for method, condition in method_conditions.items()]) at_least_one_resource_method = len(all_resource_method_conditions) > 0 all_resource_methods_contain_conditions = None not in all_resource_method_conditions if at_least_one_resource_method and all_resource_methods_contain_conditions: implicit_api_resource = template_dict.get('Resources').get(self.implicit_api_logical_id) if len(all_resource_method_conditions) == 1: condition = all_resource_method_conditions.pop() implicit_api_resource['Condition'] = condition else: # If multiple functions with multiple different conditions reference the Implicit Api, we need to # aggregate those conditions in order to conditionally create the Implicit Api. See RFC: # https://github.com/awslabs/serverless-application-model/issues/758 implicit_api_resource['Condition'] = self.implicit_api_condition self._add_combined_condition_to_template( template_dict, self.implicit_api_condition, all_resource_method_conditions)
[ "\n Decides whether to add a condition to the implicit api resource.\n :param dict template_dict: SAM template dictionary\n " ]
Please provide a description of the function:def _add_combined_condition_to_template(self, template_dict, condition_name, conditions_to_combine): # defensive precondition check if not conditions_to_combine or len(conditions_to_combine) < 2: raise ValueError('conditions_to_combine must have at least 2 conditions') template_conditions = template_dict.setdefault('Conditions', {}) new_template_conditions = make_combined_condition(sorted(list(conditions_to_combine)), condition_name) for name, definition in new_template_conditions.items(): template_conditions[name] = definition
[ "\n Add top-level template condition that combines the given list of conditions.\n\n :param dict template_dict: SAM template dictionary\n :param string condition_name: Name of top-level template condition\n :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to form\n top-level condition.\n " ]
Please provide a description of the function:def _maybe_add_conditions_to_implicit_api_paths(self, template): for api_id, api in template.iterate(SamResourceType.Api.value): if not api.properties.get('__MANAGE_SWAGGER'): continue swagger = api.properties.get("DefinitionBody") editor = SwaggerEditor(swagger) for path in editor.iter_on_path(): all_method_conditions = set( [condition for method, condition in self.api_conditions[api_id][path].items()] ) at_least_one_method = len(all_method_conditions) > 0 all_methods_contain_conditions = None not in all_method_conditions if at_least_one_method and all_methods_contain_conditions: if len(all_method_conditions) == 1: editor.make_path_conditional(path, all_method_conditions.pop()) else: path_condition_name = self._path_condition_name(api_id, path) self._add_combined_condition_to_template( template.template_dict, path_condition_name, all_method_conditions) editor.make_path_conditional(path, path_condition_name) api.properties["DefinitionBody"] = editor.swagger template.set(api_id, api)
[ "\n Add conditions to implicit API paths if necessary.\n\n Implicit API resource methods are constructed from API events on individual serverless functions within the SAM\n template. Since serverless functions can have conditions on them, it's possible to have a case where all methods\n under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource\n path should not be defined either. This method checks all resource paths' methods and if all methods under a\n given path contain a condition, a composite condition is added to the overall template Conditions section and\n that composite condition is added to the resource path.\n " ]
Please provide a description of the function:def _path_condition_name(self, api_id, path): # only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain # slashes and curly braces for templated params, e.g., /foo/{customerId}. So we'll replace # non-alphanumeric characters. path_logical_id = path.replace('/', 'SLASH').replace('{', 'OB').replace('}', 'CB') return '{}{}PathCondition'.format(api_id, path_logical_id)
[ "\n Generate valid condition logical id from the given API logical id and swagger resource path.\n " ]
Please provide a description of the function:def _maybe_remove_implicit_api(self, template): # Remove Implicit API resource if no paths got added implicit_api_resource = template.get(self.implicit_api_logical_id) if implicit_api_resource and len(implicit_api_resource.properties["DefinitionBody"]["paths"]) == 0: # If there's no implicit api and the author defined a "ServerlessRestApi" # resource, restore it if self.existing_implicit_api_resource: template.set(self.implicit_api_logical_id, self.existing_implicit_api_resource) else: template.delete(self.implicit_api_logical_id)
[ "\n Implicit API resource are tentatively added to the template for uniform handling of both Implicit & Explicit\n APIs. They need to removed from the template, if there are *no* API events attached to this resource.\n This method removes the Implicit API if it does not contain any Swagger paths (added in response to API events).\n\n :param SamTemplate template: SAM Template containing the Implicit API resource\n " ]
Please provide a description of the function:def make_auto_deployable(self, stage, swagger=None): if not swagger: return # CloudFormation does NOT redeploy the API unless it has a new deployment resource # that points to latest RestApi resource. Append a hash of Swagger Body location to # redeploy only when the API data changes. First 10 characters of hash is good enough # to prevent redeployment when API has not changed # NOTE: `str(swagger)` is for backwards compatibility. Changing it to a JSON or something will break compat generator = logical_id_generator.LogicalIdGenerator(self.logical_id, str(swagger)) self.logical_id = generator.gen() hash = generator.get_hash(length=40) # Get the full hash self.Description = "RestApi deployment id: {}".format(hash) stage.update_deployment_ref(self.logical_id)
[ "\n Sets up the resource such that it will triggers a re-deployment when Swagger changes\n\n :param swagger: Dictionary containing the Swagger definition of the API\n " ]
Please provide a description of the function:def _invoke_internal(self, function_arn, payload, client_context, invocation_type="RequestResponse"): customer_logger.info('Invoking Lambda function "{}" with Greengrass Message "{}"'.format(function_arn, payload)) try: invocation_id = self.ipc.post_work(function_arn, payload, client_context, invocation_type) if invocation_type == "Event": # TODO: Properly return errors based on BOTO response # https://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.invoke return {'Payload': b'', 'FunctionError': ''} work_result_output = self.ipc.get_work_result(function_arn, invocation_id) if not work_result_output.func_err: output_payload = StreamingBody(work_result_output.payload) else: output_payload = work_result_output.payload invoke_output = { 'Payload': output_payload, 'FunctionError': work_result_output.func_err, } return invoke_output except IPCException as e: customer_logger.exception(e) raise InvocationException('Failed to invoke function due to ' + str(e))
[ "\n This private method is seperate from the main, public invoke method so that other code within this SDK can\n give this Lambda client a raw payload/client context to invoke with, rather than having it built for them.\n This lets you include custom ExtensionMap_ values like subject which are needed for our internal pinned Lambdas.\n " ]
Please provide a description of the function:def read(self, amt=None): chunk = self._raw_stream.read(amt) self._amount_read += len(chunk) return chunk
[ "Read at most amt bytes from the stream.\n If the amt argument is omitted, read all data.\n " ]
Please provide a description of the function:def post_work(self, function_arn, input_bytes, client_context, invocation_type="RequestResponse"): url = self._get_url(function_arn) runtime_logger.info('Posting work for function [{}] to {}'.format(function_arn, url)) request = Request(url, input_bytes or b'') request.add_header(HEADER_CLIENT_CONTEXT, client_context) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) request.add_header(HEADER_INVOCATION_TYPE, invocation_type) response = urlopen(request) invocation_id = response.info().get(HEADER_INVOCATION_ID) runtime_logger.info('Work posted with invocation id [{}]'.format(invocation_id)) return invocation_id
[ "\n Send work item to specified :code:`function_arn`.\n\n :param function_arn: Arn of the Lambda function intended to receive the work for processing.\n :type function_arn: string\n\n :param input_bytes: The data making up the work being posted.\n :type input_bytes: bytes\n\n :param client_context: The base64 encoded client context byte string that will be provided to the Lambda\n function being invoked.\n :type client_context: bytes\n\n :returns: Invocation ID for obtaining result of the work.\n :type returns: str\n " ]
Please provide a description of the function:def get_work(self, function_arn): url = self._get_work_url(function_arn) runtime_logger.info('Getting work for function [{}] from {}'.format(function_arn, url)) request = Request(url) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) response = urlopen(request) invocation_id = response.info().get(HEADER_INVOCATION_ID) client_context = response.info().get(HEADER_CLIENT_CONTEXT) runtime_logger.info('Got work item with invocation id [{}]'.format(invocation_id)) return WorkItem( invocation_id=invocation_id, payload=response.read(), client_context=client_context)
[ "\n Retrieve the next work item for specified :code:`function_arn`.\n\n :param function_arn: Arn of the Lambda function intended to receive the work for processing.\n :type function_arn: string\n\n :returns: Next work item to be processed by the function.\n :type returns: WorkItem\n " ]
Please provide a description of the function:def post_work_result(self, function_arn, work_item): url = self._get_work_url(function_arn) runtime_logger.info('Posting work result for invocation id [{}] to {}'.format(work_item.invocation_id, url)) request = Request(url, work_item.payload or b'') request.add_header(HEADER_INVOCATION_ID, work_item.invocation_id) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) urlopen(request) runtime_logger.info('Posted work result for invocation id [{}]'.format(work_item.invocation_id))
[ "\n Post the result of processing work item by :code:`function_arn`.\n\n :param function_arn: Arn of the Lambda function intended to receive the work for processing.\n :type function_arn: string\n\n :param work_item: The WorkItem holding the results of the work being posted.\n :type work_item: WorkItem\n\n :returns: None\n " ]
Please provide a description of the function:def post_handler_err(self, function_arn, invocation_id, handler_err): url = self._get_work_url(function_arn) runtime_logger.info('Posting handler error for invocation id [{}] to {}'.format(invocation_id, url)) payload = json.dumps({ "errorMessage": handler_err, }).encode('utf-8') request = Request(url, payload) request.add_header(HEADER_INVOCATION_ID, invocation_id) request.add_header(HEADER_FUNCTION_ERR_TYPE, "Handled") request.add_header(HEADER_AUTH_TOKEN, self.auth_token) urlopen(request) runtime_logger.info('Posted handler error for invocation id [{}]'.format(invocation_id))
[ "\n Post the error message from executing the function handler for :code:`function_arn`\n with specifid :code:`invocation_id`\n\n\n :param function_arn: Arn of the Lambda function which has the handler error message.\n :type function_arn: string\n\n :param invocation_id: Invocation ID of the work that is being requested\n :type invocation_id: string\n\n :param handler_err: the error message caught from handler\n :type handler_err: string\n " ]
Please provide a description of the function:def get_work_result(self, function_arn, invocation_id): url = self._get_url(function_arn) runtime_logger.info('Getting work result for invocation id [{}] from {}'.format(invocation_id, url)) request = Request(url) request.add_header(HEADER_INVOCATION_ID, invocation_id) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) response = urlopen(request) runtime_logger.info('Got result for invocation id [{}]'.format(invocation_id)) payload = response.read() func_err = response.info().get(HEADER_FUNCTION_ERR_TYPE) return GetWorkResultOutput( payload=payload, func_err=func_err)
[ "\n Retrieve the result of the work processed by :code:`function_arn`\n with specified :code:`invocation_id`.\n\n :param function_arn: Arn of the Lambda function intended to receive the work for processing.\n :type function_arn: string\n\n :param invocation_id: Invocation ID of the work that is being requested\n :type invocation_id: string\n\n :returns: The get work result output contains result payload and function error type if the invoking is failed.\n :type returns: GetWorkResultOutput\n " ]
Please provide a description of the function:def on_before_transform_template(self, template_dict): template = SamTemplate(template_dict) intrinsic_resolvers = self._get_intrinsic_resolvers(template_dict.get('Mappings', {})) service_call = None if self._validate_only: service_call = self._handle_get_application_request else: service_call = self._handle_create_cfn_template_request for logical_id, app in template.iterate(SamResourceType.Application.value): if not self._can_process_application(app): # Handle these cases in the on_before_transform_resource event continue app_id = self._replace_value(app.properties[self.LOCATION_KEY], self.APPLICATION_ID_KEY, intrinsic_resolvers) semver = self._replace_value(app.properties[self.LOCATION_KEY], self.SEMANTIC_VERSION_KEY, intrinsic_resolvers) if isinstance(app_id, dict) or isinstance(semver, dict): key = (json.dumps(app_id), json.dumps(semver)) self._applications[key] = False continue key = (app_id, semver) if key not in self._applications: try: # Lazy initialization of the client- create it when it is needed if not self._sar_client: self._sar_client = boto3.client('serverlessrepo') service_call(app_id, semver, key, logical_id) except InvalidResourceException as e: # Catch all InvalidResourceExceptions, raise those in the before_resource_transform target. self._applications[key] = e
[ "\n Hook method that gets called before the SAM template is processed.\n The template has passed the validation and is guaranteed to contain a non-empty \"Resources\" section.\n\n This plugin needs to run as soon as possible to allow some time for templates to become available.\n This verifies that the user has access to all specified applications.\n\n :param dict template_dict: Dictionary of the SAM template\n :return: Nothing\n " ]
Please provide a description of the function:def _can_process_application(self, app): return (self.LOCATION_KEY in app.properties and isinstance(app.properties[self.LOCATION_KEY], dict) and self.APPLICATION_ID_KEY in app.properties[self.LOCATION_KEY] and self.SEMANTIC_VERSION_KEY in app.properties[self.LOCATION_KEY])
[ "\n Determines whether or not the on_before_transform_template event can process this application\n\n :param dict app: the application and its properties\n " ]
Please provide a description of the function:def _handle_create_cfn_template_request(self, app_id, semver, key, logical_id): create_cfn_template = (lambda app_id, semver: self._sar_client.create_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver) )) response = self._sar_service_call(create_cfn_template, logical_id, app_id, semver) self._applications[key] = response[self.TEMPLATE_URL_KEY] if response['Status'] != "ACTIVE": self._in_progress_templates.append((response[self.APPLICATION_ID_KEY], response['TemplateId']))
[ "\n Method that handles the create_cloud_formation_template API call to the serverless application repo\n\n :param string app_id: ApplicationId\n :param string semver: SemanticVersion\n :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion)\n :param string logical_id: the logical_id of this application resource\n " ]
Please provide a description of the function:def on_before_transform_resource(self, logical_id, resource_type, resource_properties): if not self._resource_is_supported(resource_type): return # Sanitize properties self._check_for_dictionary_key(logical_id, resource_properties, [self.LOCATION_KEY]) # If location isn't a dictionary, don't modify the resource. if not isinstance(resource_properties[self.LOCATION_KEY], dict): resource_properties[self.TEMPLATE_URL_KEY] = resource_properties[self.LOCATION_KEY] return # If it is a dictionary, check for other required parameters self._check_for_dictionary_key(logical_id, resource_properties[self.LOCATION_KEY], [self.APPLICATION_ID_KEY, self.SEMANTIC_VERSION_KEY]) app_id = resource_properties[self.LOCATION_KEY].get(self.APPLICATION_ID_KEY) if not app_id: raise InvalidResourceException(logical_id, "Property 'ApplicationId' cannot be blank.") if isinstance(app_id, dict): raise InvalidResourceException(logical_id, "Property 'ApplicationId' cannot be resolved. Only FindInMap " "and Ref intrinsic functions are supported.") semver = resource_properties[self.LOCATION_KEY].get(self.SEMANTIC_VERSION_KEY) if not semver: raise InvalidResourceException(logical_id, "Property 'SemanticVersion' cannot be blank.") if isinstance(semver, dict): raise InvalidResourceException(logical_id, "Property 'SemanticVersion' cannot be resolved. Only FindInMap " "and Ref intrinsic functions are supported.") key = (app_id, semver) # Throw any resource exceptions saved from the before_transform_template event if isinstance(self._applications[key], InvalidResourceException): raise self._applications[key] # validation does not resolve an actual template url if not self._validate_only: resource_properties[self.TEMPLATE_URL_KEY] = self._applications[key]
[ "\n Hook method that gets called before \"each\" SAM resource gets processed\n\n Replaces the ApplicationId and Semantic Version pairs with a TemplateUrl.\n\n :param string logical_id: Logical ID of the resource being processed\n :param string resource_type: Type of the resource being processed\n :param dict resource_properties: Properties of the resource\n :return: Nothing\n " ]
Please provide a description of the function:def _check_for_dictionary_key(self, logical_id, dictionary, keys): for key in keys: if key not in dictionary: raise InvalidResourceException(logical_id, 'Resource is missing the required [{}] ' 'property.'.format(key))
[ "\n Checks a dictionary to make sure it has a specific key. If it does not, an\n InvalidResourceException is thrown.\n\n :param string logical_id: logical id of this resource\n :param dict dictionary: the dictionary to check\n :param list keys: list of keys that should exist in the dictionary\n " ]
Please provide a description of the function:def on_after_transform_template(self, template): if self._wait_for_template_active_status and not self._validate_only: start_time = time() while (time() - start_time) < self.TEMPLATE_WAIT_TIMEOUT_SECONDS: temp = self._in_progress_templates self._in_progress_templates = [] # Check each resource to make sure it's active for application_id, template_id in temp: get_cfn_template = (lambda application_id, template_id: self._sar_client.get_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(application_id), TemplateId=self._sanitize_sar_str_param(template_id))) response = self._sar_service_call(get_cfn_template, application_id, application_id, template_id) self._handle_get_cfn_template_response(response, application_id, template_id) # Don't sleep if there are no more templates with PREPARING status if len(self._in_progress_templates) == 0: break # Sleep a little so we don't spam service calls sleep(self.SLEEP_TIME_SECONDS) # Not all templates reached active status if len(self._in_progress_templates) != 0: application_ids = [items[0] for items in self._in_progress_templates] raise InvalidResourceException(application_ids, "Timed out waiting for nested stack templates " "to reach ACTIVE status.")
[ "\n Hook method that gets called after the template is processed\n\n Go through all the stored applications and make sure they're all ACTIVE.\n\n :param dict template: Dictionary of the SAM template\n :return: Nothing\n " ]
Please provide a description of the function:def _handle_get_cfn_template_response(self, response, application_id, template_id): status = response['Status'] if status != "ACTIVE": # Other options are PREPARING and EXPIRED. if status == 'EXPIRED': message = ("Template for {} with id {} returned status: {}. Cannot access an expired " "template.".format(application_id, template_id, status)) raise InvalidResourceException(application_id, message) self._in_progress_templates.append((application_id, template_id))
[ "\n Handles the response from the SAR service call\n\n :param dict response: the response dictionary from the app repo\n :param string application_id: the ApplicationId\n :param string template_id: the unique TemplateId for this application\n " ]
Please provide a description of the function:def _sar_service_call(self, service_call_lambda, logical_id, *args): try: response = service_call_lambda(*args) logging.info(response) return response except ClientError as e: error_code = e.response['Error']['Code'] if error_code in ('AccessDeniedException', 'NotFoundException'): raise InvalidResourceException(logical_id, e.response['Error']['Message']) # 'ForbiddenException'- SAR rejects connection logging.exception(e) raise e
[ "\n Handles service calls and exception management for service calls\n to the Serverless Application Repository.\n\n :param lambda service_call_lambda: lambda function that contains the service call\n :param string logical_id: Logical ID of the resource being processed\n :param list *args: arguments for the service call lambda\n " ]
Please provide a description of the function:def _validate(self, sam_template, parameter_values): if parameter_values is None: raise ValueError("`parameter_values` argument is required") 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")]) if (not all(isinstance(sam_resource, dict) for sam_resource in sam_template["Resources"].values())): raise InvalidDocumentException( [InvalidTemplateException( "All 'Resources' must be Objects. If you're using YAML, this may be an " "indentation issue." )]) sam_template_instance = SamTemplate(sam_template) for resource_logical_id, sam_resource in sam_template_instance.iterate(): # NOTE: Properties isn't required for SimpleTable, so we can't check # `not isinstance(sam_resources.get("Properties"), dict)` as this would be a breaking change. # sam_resource.properties defaults to {} in SamTemplate init if (not isinstance(sam_resource.properties, dict)): raise InvalidDocumentException( [InvalidResourceException(resource_logical_id, "All 'Resources' must be Objects and have a 'Properties' Object. If " "you're using YAML, this may be an indentation issue." )]) SamTemplateValidator.validate(sam_template)
[ " Validates the template and parameter values and raises exceptions if there's an issue\n\n :param dict sam_template: SAM template\n :param dict parameter_values: Dictionary of parameter values provided by the user\n " ]
Please provide a description of the function:def iterate(self, resource_type=None): for logicalId, resource_dict in self.resources.items(): resource = SamResource(resource_dict) needs_filter = resource.valid() if resource_type: needs_filter = needs_filter and resource.type == resource_type if needs_filter: yield logicalId, resource
[ "\n Iterate over all resources within the SAM template, optionally filtering by type\n\n :param string resource_type: Optional type to filter the resources by\n :yields (string, SamResource): Tuple containing LogicalId and the resource\n " ]
Please provide a description of the function:def set(self, logicalId, resource): resource_dict = resource if isinstance(resource, SamResource): resource_dict = resource.to_dict() self.resources[logicalId] = resource_dict
[ "\n Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used.\n\n :param string logicalId: Logical Id to set to\n :param SamResource or dict resource: The actual resource data\n " ]
Please provide a description of the function:def get(self, logicalId): if logicalId not in self.resources: return None return SamResource(self.resources.get(logicalId))
[ "\n Gets the resource at the given logicalId if present\n\n :param string logicalId: Id of the resource\n :return SamResource: Resource, if available at the Id. None, otherwise\n " ]
Please provide a description of the function:def prepare_plugins(plugins, parameters={}): required_plugins = [ DefaultDefinitionBodyPlugin(), make_implicit_api_plugin(), GlobalsPlugin(), make_policy_template_for_function_plugin(), ] plugins = [] if not plugins else plugins # If a ServerlessAppPlugin does not yet exist, create one and add to the beginning of the required plugins list. if not any(isinstance(plugin, ServerlessAppPlugin) for plugin in plugins): required_plugins.insert(0, ServerlessAppPlugin(parameters=parameters)) # Execute customer's plugins first before running SAM plugins. It is very important to retain this order because # other plugins will be dependent on this ordering. return SamPlugins(plugins + required_plugins)
[ "\n Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins,\n we will also install a few \"required\" plugins that are necessary to provide complete support for SAM template spec.\n\n :param plugins: list of samtranslator.plugins.BasePlugin plugins: List of plugins to install\n :param parameters: Dictionary of parameter values\n :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins`\n " ]
Please provide a description of the function:def translate(self, sam_template, parameter_values): sam_parameter_values = SamParameterValues(parameter_values) sam_parameter_values.add_default_parameter_values(sam_template) sam_parameter_values.add_pseudo_parameter_values() parameter_values = sam_parameter_values.parameter_values # Create & Install plugins sam_plugins = prepare_plugins(self.plugins, parameter_values) self.sam_parser.parse( sam_template=sam_template, parameter_values=parameter_values, sam_plugins=sam_plugins ) template = copy.deepcopy(sam_template) macro_resolver = ResourceTypeResolver(sam_resources) intrinsics_resolver = IntrinsicsResolver(parameter_values) deployment_preference_collection = DeploymentPreferenceCollection() supported_resource_refs = SupportedResourceReferences() document_errors = [] changed_logical_ids = {} for logical_id, resource_dict in self._get_resources_to_iterate(sam_template, macro_resolver): try: macro = macro_resolver\ .resolve_resource_type(resource_dict)\ .from_dict(logical_id, resource_dict, sam_plugins=sam_plugins) kwargs = macro.resources_to_link(sam_template['Resources']) kwargs['managed_policy_map'] = self.managed_policy_map kwargs['intrinsics_resolver'] = intrinsics_resolver kwargs['deployment_preference_collection'] = deployment_preference_collection translated = macro.to_cloudformation(**kwargs) supported_resource_refs = macro.get_resource_references(translated, supported_resource_refs) # Some resources mutate their logical ids. Track those to change all references to them: if logical_id != macro.logical_id: changed_logical_ids[logical_id] = macro.logical_id del template['Resources'][logical_id] for resource in translated: if verify_unique_logical_id(resource, sam_template['Resources']): template['Resources'].update(resource.to_dict()) else: document_errors.append(DuplicateLogicalIdException( logical_id, resource.logical_id, resource.resource_type)) except (InvalidResourceException, InvalidEventException) as e: document_errors.append(e) if deployment_preference_collection.any_enabled(): template['Resources'].update(deployment_preference_collection.codedeploy_application.to_dict()) if not deployment_preference_collection.can_skip_service_role(): template['Resources'].update(deployment_preference_collection.codedeploy_iam_role.to_dict()) for logical_id in deployment_preference_collection.enabled_logical_ids(): template['Resources'].update(deployment_preference_collection.deployment_group(logical_id).to_dict()) # Run the after-transform plugin target try: sam_plugins.act(LifeCycleEvents.after_transform_template, template) except (InvalidDocumentException, InvalidResourceException) as e: document_errors.append(e) # Cleanup if 'Transform' in template: del template['Transform'] if len(document_errors) == 0: template = intrinsics_resolver.resolve_sam_resource_id_refs(template, changed_logical_ids) template = intrinsics_resolver.resolve_sam_resource_refs(template, supported_resource_refs) return template else: raise InvalidDocumentException(document_errors)
[ "Loads the SAM resources from the given SAM manifest, replaces them with their corresponding\n CloudFormation resources, and returns the resulting CloudFormation template.\n\n :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \\\n CloudFormation transforms.\n :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that\n should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea\n that some functionality that relies on resolving parameter references might not work as expected\n (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is\n why this parameter is required\n\n :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \\\n be dumped into a valid CloudFormation JSON or YAML template\n " ]
Please provide a description of the function:def _get_resources_to_iterate(self, sam_template, macro_resolver): functions = [] apis = [] others = [] resources = sam_template["Resources"] for logicalId, resource in resources.items(): data = (logicalId, resource) # Skip over the resource if it is not a SAM defined Resource if not macro_resolver.can_resolve(resource): continue elif resource["Type"] == "AWS::Serverless::Function": functions.append(data) elif resource["Type"] == "AWS::Serverless::Api": apis.append(data) else: others.append(data) return functions + apis + others
[ "\n Returns a list of resources to iterate, order them based on the following order:\n\n 1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource.\n 2. AWS::Serverless::Api\n 3. Anything else\n\n This is necessary because a Function resource with API Events will modify the API resource's Swagger JSON.\n Therefore API resource needs to be parsed only after all the Swagger modifications are complete.\n\n :param dict sam_template: SAM template\n :param macro_resolver: Resolver that knows if a resource can be processed or not\n :return list: List containing tuple of (logicalId, resource_dict) in the order of processing\n " ]
Please provide a description of the function:def from_dict(cls, logical_id, resource_dict, relative_id=None, sam_plugins=None): resource = cls(logical_id, relative_id=relative_id) resource._validate_resource_dict(logical_id, resource_dict) # Default to empty properties dictionary. If customers skip the Properties section, an empty dictionary # accurately captures the intent. properties = resource_dict.get("Properties", {}) if sam_plugins: sam_plugins.act(LifeCycleEvents.before_transform_resource, logical_id, cls.resource_type, properties) for name, value in properties.items(): setattr(resource, name, value) if 'DependsOn' in resource_dict: resource.depends_on = resource_dict['DependsOn'] # Parse only well known properties. This is consistent with earlier behavior where we used to ignore resource # all resource attributes ie. all attributes were unsupported before for attr in resource._supported_resource_attributes: if attr in resource_dict: resource.set_resource_attribute(attr, resource_dict[attr]) resource.validate_properties() return resource
[ "Constructs a Resource object with the given logical id, based on the given resource dict. The resource dict\n is the value associated with the logical id in a CloudFormation template's Resources section, and takes the\n following format. ::\n\n {\n \"Type\": \"<resource type>\",\n \"Properties\": {\n <set of properties>\n }\n }\n\n :param str logical_id: The logical id of this Resource\n :param dict resource_dict: The value associated with this logical id in the CloudFormation template, a mapping \\\n containing the resource's Type and Properties.\n :param str relative_id: The logical id of this resource relative to the logical_id. This is useful\n to identify sub-resources.\n :param samtranslator.plugins.SamPlugins sam_plugins: Optional plugins object to help enhance functionality of\n translator\n :returns: a Resource object populated from the provided parameters\n :rtype: Resource\n :raises TypeError: if the provided parameters are invalid\n " ]
Please provide a description of the function:def _validate_logical_id(cls, logical_id): pattern = re.compile(r'^[A-Za-z0-9]+$') if logical_id is not None and pattern.match(logical_id): return True raise InvalidResourceException(logical_id, "Logical ids must be alphanumeric.")
[ "Validates that the provided logical id is an alphanumeric string.\n\n :param str logical_id: the logical id to validate\n :returns: True if the logical id is valid\n :rtype: bool\n :raises TypeError: if the logical id is invalid\n " ]
Please provide a description of the function:def _validate_resource_dict(cls, logical_id, resource_dict): if 'Type' not in resource_dict: raise InvalidResourceException(logical_id, "Resource dict missing key 'Type'.") if resource_dict['Type'] != cls.resource_type: raise InvalidResourceException(logical_id, "Resource has incorrect Type; expected '{expected}', " "got '{actual}'".format( expected=cls.resource_type, actual=resource_dict['Type'])) if 'Properties' in resource_dict and not isinstance(resource_dict['Properties'], dict): raise InvalidResourceException(logical_id, "Properties of a resource must be an object.")
[ "Validates that the provided resource dict contains the correct Type string, and the required Properties dict.\n\n :param dict resource_dict: the resource dict to validate\n :returns: True if the resource dict has the expected format\n :rtype: bool\n :raises InvalidResourceException: if the resource dict has an invalid format\n " ]
Please provide a description of the function:def to_dict(self): self.validate_properties() resource_dict = self._generate_resource_dict() return {self.logical_id: resource_dict}
[ "Validates that the required properties for this Resource have been provided, then returns a dict\n corresponding to the given Resource object. This dict will take the format of a single entry in the Resources\n section of a CloudFormation template, and will take the following format. ::\n\n {\n \"<logical id>\": {\n \"Type\": \"<resource type>\",\n \"DependsOn\": \"<value specified by user>\",\n \"Properties\": {\n <set of properties>\n }\n }\n }\n\n The resulting dict can then be serialized to JSON or YAML and included as part of a CloudFormation template.\n\n :returns: a dict corresponding to this Resource's entry in a CloudFormation template\n :rtype: dict\n :raises TypeError: if a required property is missing from this Resource\n " ]
Please provide a description of the function:def _generate_resource_dict(self): resource_dict = {} resource_dict['Type'] = self.resource_type if self.depends_on: resource_dict['DependsOn'] = self.depends_on resource_dict.update(self.resource_attributes) properties_dict = {} for name in self.property_types: value = getattr(self, name) if value is not None: properties_dict[name] = value resource_dict['Properties'] = properties_dict return resource_dict
[ "Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation\n template's Resources section.\n\n :returns: the resource dict for this Resource\n :rtype: dict\n " ]
Please provide a description of the function:def validate_properties(self): for name, property_type in self.property_types.items(): value = getattr(self, name) # If the property value is an intrinsic function, any remaining validation has to be left to CloudFormation if property_type.supports_intrinsics and self._is_intrinsic_function(value): continue # If the property value has not been set, verify that the property is not required. if value is None: if property_type.required: raise InvalidResourceException( self.logical_id, "Missing required property '{property_name}'.".format(property_name=name)) # Otherwise, validate the value of the property. elif not property_type.validate(value, should_raise=False): raise InvalidResourceException( self.logical_id, "Type of property '{property_name}' is invalid.".format(property_name=name))
[ "Validates that the required properties for this Resource have been populated, and that all properties have\n valid values.\n\n :returns: True if all properties are valid\n :rtype: bool\n :raises TypeError: if any properties are invalid\n " ]
Please provide a description of the function:def set_resource_attribute(self, attr, value): if attr not in self._supported_resource_attributes: raise KeyError("Unsupported resource attribute specified: %s" % attr) self.resource_attributes[attr] = value
[ "Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource\n that exist outside of the Properties dictionary\n\n :param attr: Attribute name\n :param value: Attribute value\n :return: None\n :raises KeyError if `attr` is not in the supported attribute list\n " ]
Please provide a description of the function:def get_resource_attribute(self, attr): if attr not in self.resource_attributes: raise KeyError("%s is not in resource attributes" % attr) return self.resource_attributes[attr]
[ "Gets the resource attribute if available\n\n :param attr: Name of the attribute\n :return: Value of the attribute, if set in the resource. None otherwise\n " ]
Please provide a description of the function:def get_runtime_attr(self, attr_name): if attr_name in self.runtime_attrs: return self.runtime_attrs[attr_name](self) else: raise NotImplementedError(attr_name + " attribute is not implemented for resource " + self.resource_type)
[ "\n Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide\n this attribute, then this method raises an exception\n\n :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed\n " ]
Please provide a description of the function:def get_resource_references(self, generated_cfn_resources, supported_resource_refs): if supported_resource_refs is None: raise ValueError("`supported_resource_refs` object is required") # Create a map of {ResourceType: LogicalId} for quick access resource_id_by_type = {resource.resource_type: resource.logical_id for resource in generated_cfn_resources} for property, cfn_type in self.referable_properties.items(): if cfn_type in resource_id_by_type: supported_resource_refs.add(self.logical_id, property, resource_id_by_type[cfn_type]) return supported_resource_refs
[ "\n Constructs the list of supported resource references by going through the list of CFN resources generated\n by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that it\n supports and the type of CFN resource this property resolves to.\n\n :param list of Resource object generated_cfn_resources: List of CloudFormation resources generated by this\n SAM resource\n :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Object\n holding the mapping between property names and LogicalId of the generated CFN resource it maps to\n :return: Updated supported_resource_refs\n " ]
Please provide a description of the function:def resolve_resource_type(self, resource_dict): if not self.can_resolve(resource_dict): raise TypeError("Resource dict has missing or invalid value for key Type. Event Type is: {}.".format( resource_dict.get('Type'))) if resource_dict['Type'] not in self.resource_types: raise TypeError("Invalid resource type {resource_type}".format(resource_type=resource_dict['Type'])) return self.resource_types[resource_dict['Type']]
[ "Returns the Resource class corresponding to the 'Type' key in the given resource dict.\n\n :param dict resource_dict: the resource dict to resolve\n :returns: the resolved Resource class\n :rtype: class\n " ]
Please provide a description of the function:def build_response_card(title, subtitle, options): buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle, 'buttons': buttons }] }
[ "\n Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.\n " ]
Please provide a description of the function:def get_random_int(minimum, maximum): min_int = math.ceil(minimum) max_int = math.floor(maximum) return random.randint(min_int, max_int - 1)
[ "\n Returns a random integer between min (included) and max (excluded)\n " ]
Please provide a description of the function:def get_availabilities(date): day_of_week = dateutil.parser.parse(date).weekday() availabilities = [] available_probability = 0.3 if day_of_week == 0: start_hour = 10 while start_hour <= 16: if random.random() < available_probability: # Add an availability window for the given hour, with duration determined by another random number. appointment_type = get_random_int(1, 4) if appointment_type == 1: availabilities.append('{}:00'.format(start_hour)) elif appointment_type == 2: availabilities.append('{}:30'.format(start_hour)) else: availabilities.append('{}:00'.format(start_hour)) availabilities.append('{}:30'.format(start_hour)) start_hour += 1 if day_of_week == 2 or day_of_week == 4: availabilities.append('10:00') availabilities.append('16:00') availabilities.append('16:30') return availabilities
[ "\n Helper function which in a full implementation would feed into a backend API to provide query schedule availability.\n The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format.\n\n In order to enable quick demonstration of all possible conversation paths supported in this example, the function\n returns a mixture of fixed and randomized results.\n\n On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at\n 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday.\n " ]
Please provide a description of the function:def is_available(time, duration, availabilities): if duration == 30: return time in availabilities elif duration == 60: second_half_hour_time = increment_time_by_thirty_mins(time) return time in availabilities and second_half_hour_time in availabilities # Invalid duration ; throw error. We should not have reached this branch due to earlier validation. raise Exception('Was not able to understand duration {}'.format(duration))
[ "\n Helper function to check if the given time and duration fits within a known set of availability windows.\n Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM.\n " ]
Please provide a description of the function:def get_availabilities_for_duration(duration, availabilities): duration_availabilities = [] start_time = '10:00' while start_time != '17:00': if start_time in availabilities: if duration == 30: duration_availabilities.append(start_time) elif increment_time_by_thirty_mins(start_time) in availabilities: duration_availabilities.append(start_time) start_time = increment_time_by_thirty_mins(start_time) return duration_availabilities
[ "\n Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.\n " ]
Please provide a description of the function:def build_available_time_string(availabilities): prefix = 'We have availabilities at ' if len(availabilities) > 3: prefix = 'We have plenty of availability, including ' prefix += build_time_output_string(availabilities[0]) if len(availabilities) == 2: return '{} and {}'.format(prefix, build_time_output_string(availabilities[1])) return '{}, {} and {}'.format(prefix, build_time_output_string(availabilities[1]), build_time_output_string(availabilities[2]))
[ "\n Build a string eliciting for a possible time slot among at least two availabilities.\n " ]
Please provide a description of the function:def build_options(slot, appointment_type, date, booking_map): day_strings = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] if slot == 'AppointmentType': return [ {'text': 'cleaning (30 min)', 'value': 'cleaning'}, {'text': 'root canal (60 min)', 'value': 'root canal'}, {'text': 'whitening (30 min)', 'value': 'whitening'} ] elif slot == 'Date': # Return the next five weekdays. options = [] potential_date = datetime.datetime.today() while len(options) < 5: potential_date = potential_date + datetime.timedelta(days=1) if potential_date.weekday() < 5: options.append({'text': '{}-{} ({})'.format((potential_date.month), potential_date.day, day_strings[potential_date.weekday()]), 'value': potential_date.strftime('%A, %B %d, %Y')}) return options elif slot == 'Time': # Return the availabilities on the given date. if not appointment_type or not date: return None availabilities = try_ex(lambda: booking_map[date]) if not availabilities: return None availabilities = get_availabilities_for_duration(get_duration(appointment_type), availabilities) if len(availabilities) == 0: return None options = [] for i in range(min(len(availabilities), 5)): options.append({'text': build_time_output_string(availabilities[i]), 'value': build_time_output_string(availabilities[i])}) return options
[ "\n Build a list of potential options for a given slot, to be used in responseCard generation.\n " ]
Please provide a description of the function:def make_appointment(intent_request): appointment_type = intent_request['currentIntent']['slots']['AppointmentType'] date = intent_request['currentIntent']['slots']['Date'] time = intent_request['currentIntent']['slots']['Time'] source = intent_request['invocationSource'] output_session_attributes = intent_request['sessionAttributes'] booking_map = json.loads(try_ex(lambda: output_session_attributes['bookingMap']) or '{}') if source == 'DialogCodeHook': # Perform basic validation on the supplied input slots. slots = intent_request['currentIntent']['slots'] validation_result = validate_book_appointment(appointment_type, date, time) if not validation_result['isValid']: slots[validation_result['violatedSlot']] = None return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, validation_result['violatedSlot'], validation_result['message'], build_response_card( 'Specify {}'.format(validation_result['violatedSlot']), validation_result['message']['content'], build_options(validation_result['violatedSlot'], appointment_type, date, booking_map) ) ) if not appointment_type: return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], intent_request['currentIntent']['slots'], 'AppointmentType', {'contentType': 'PlainText', 'content': 'What type of appointment would you like to schedule?'}, build_response_card( 'Specify Appointment Type', 'What type of appointment would you like to schedule?', build_options('AppointmentType', appointment_type, date, None) ) ) if appointment_type and not date: return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], intent_request['currentIntent']['slots'], 'Date', {'contentType': 'PlainText', 'content': 'When would you like to schedule your {}?'.format(appointment_type)}, build_response_card( 'Specify Date', 'When would you like to schedule your {}?'.format(appointment_type), build_options('Date', appointment_type, date, None) ) ) if appointment_type and date: # Fetch or generate the availabilities for the given date. booking_availabilities = try_ex(lambda: booking_map[date]) if booking_availabilities is None: booking_availabilities = get_availabilities(date) booking_map[date] = booking_availabilities output_session_attributes['bookingMap'] = json.dumps(booking_map) appointment_type_availabilities = get_availabilities_for_duration(get_duration(appointment_type), booking_availabilities) if len(appointment_type_availabilities) == 0: # No availability on this day at all; ask for a new date and time. slots['Date'] = None slots['Time'] = None return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, 'Date', {'contentType': 'PlainText', 'content': 'We do not have any availability on that date, is there another day which works for you?'}, build_response_card( 'Specify Date', 'What day works best for you?', build_options('Date', appointment_type, date, booking_map) ) ) message_content = 'What time on {} works for you? '.format(date) if time: output_session_attributes['formattedTime'] = build_time_output_string(time) # Validate that proposed time for the appointment can be booked by first fetching the availabilities for the given day. To # give consistent behavior in the sample, this is stored in sessionAttributes after the first lookup. if is_available(time, get_duration(appointment_type), booking_availabilities): return delegate(output_session_attributes, slots) message_content = 'The time you requested is not available. ' if len(appointment_type_availabilities) == 1: # If there is only one availability on the given date, try to confirm it. slots['Time'] = appointment_type_availabilities[0] return confirm_intent( output_session_attributes, intent_request['currentIntent']['name'], slots, { 'contentType': 'PlainText', 'content': '{}{} is our only availability, does that work for you?'.format (message_content, build_time_output_string(appointment_type_availabilities[0])) }, build_response_card( 'Confirm Appointment', 'Is {} on {} okay?'.format(build_time_output_string(appointment_type_availabilities[0]), date), [{'text': 'yes', 'value': 'yes'}, {'text': 'no', 'value': 'no'}] ) ) available_time_string = build_available_time_string(appointment_type_availabilities) return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, 'Time', {'contentType': 'PlainText', 'content': '{}{}'.format(message_content, available_time_string)}, build_response_card( 'Specify Time', 'What time works best for you?', build_options('Time', appointment_type, date, booking_map) ) ) return delegate(output_session_attributes, slots) # Book the appointment. In a real bot, this would likely involve a call to a backend service. duration = get_duration(appointment_type) booking_availabilities = booking_map[date] if booking_availabilities: # Remove the availability slot for the given date as it has now been booked. booking_availabilities.remove(time) if duration == 60: second_half_hour_time = increment_time_by_thirty_mins(time) booking_availabilities.remove(second_half_hour_time) booking_map[date] = booking_availabilities output_session_attributes['bookingMap'] = json.dumps(booking_map) else: # This is not treated as an error as this code sample supports functionality either as fulfillment or dialog code hook. logger.debug('Availabilities for {} were null at fulfillment time. ' 'This should have been initialized if this function was configured as the dialog code hook'.format(date)) return close( output_session_attributes, 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Okay, I have booked your appointment. We will see you at {} on {}'.format(build_time_output_string(time), date) } )
[ "\n Performs dialog management and fulfillment for booking a dentists appointment.\n\n Beyond fulfillment, the implementation for this intent demonstrates the following:\n 1) Use of elicitSlot in slot validation and re-prompting\n 2) Use of confirmIntent to support the confirmation of inferred slot values, when confirmation is required\n on the bot model and the inferred slot values fully specify the intent.\n " ]
Please provide a description of the function:def dispatch(intent_request): logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot's intent handlers if intent_name == 'MakeAppointment': return make_appointment(intent_request) raise Exception('Intent with name ' + intent_name + ' not supported')
[ "\n Called when the user specifies an intent for this bot.\n " ]
Please provide a description of the function:def lambda_handler(event, context): '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. TableName provided by template.yaml. To scan a DynamoDB table, make a GET request with optional query string parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body. ''' print("Received event: " + json.dumps(event, indent=2)) operations = { 'DELETE': lambda dynamo, x: dynamo.delete_item(TableName=table_name, **x), 'GET': lambda dynamo, x: dynamo.scan(TableName=table_name, **x) if x else dynamo.scan(TableName=table_name), 'POST': lambda dynamo, x: dynamo.put_item(TableName=table_name, **x), 'PUT': lambda dynamo, x: dynamo.update_item(TableName=table_name, **x), } operation = event['httpMethod'] if operation in operations: payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body']) return respond(None, operations[operation](dynamo, payload)) else: return respond(ValueError('Unsupported method "{}"'.format(operation)))
[]
Please provide a description of the function:def lambda_handler(event, context): '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. To scan a DynamoDB table, make a GET request with the TableName as a query string parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body. ''' #print("Received event: " + json.dumps(event, indent=2)) operations = { 'DELETE': lambda dynamo, x: dynamo.delete_item(**x), 'GET': lambda dynamo, x: dynamo.scan(**x), 'POST': lambda dynamo, x: dynamo.put_item(**x), 'PUT': lambda dynamo, x: dynamo.update_item(**x), } operation = event['httpMethod'] if operation in operations: payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body']) return respond(None, operations[operation](dynamo, payload)) else: return respond(ValueError('Unsupported method "{}"'.format(operation)))
[]
Please provide a description of the function:def make_combined_condition(conditions_list, condition_name): if len(conditions_list) < 2: # Can't make a condition if <2 conditions provided. return None # Total number of conditions allows in an Fn::Or statement. See docs: # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-or max_conditions = 10 conditions = {} conditions_length = len(conditions_list) # Get number of conditions needed, then minus one to use them as 0-based indices zero_based_num_conditions = calculate_number_of_conditions(conditions_length, max_conditions) - 1 while len(conditions_list) > 1: new_condition_name = condition_name # If more than 1 new condition is needed, add a number to the end of the name if zero_based_num_conditions > 0: new_condition_name = '{}{}'.format(condition_name, zero_based_num_conditions) zero_based_num_conditions -= 1 new_condition_content = make_or_condition(conditions_list[:max_conditions]) conditions_list = conditions_list[max_conditions:] conditions_list.append(new_condition_name) conditions[new_condition_name] = new_condition_content return conditions
[ "\n Makes a combined condition using Fn::Or. Since Fn::Or only accepts up to 10 conditions,\n this method optionally creates multiple conditions. These conditions are named based on\n the condition_name parameter that is passed into the method.\n\n :param list conditions_list: list of conditions\n :param string condition_name: base name desired for new condition\n :return: dictionary of condition_name: condition_value\n " ]
Please provide a description of the function:def is_instrinsic(input): if input is not None \ and isinstance(input, dict) \ and len(input) == 1: key = list(input.keys())[0] return key == "Ref" or key == "Condition" or key.startswith("Fn::") return False
[ "\n Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single\n key that is the name of the intrinsics.\n\n :param input: Input value to check if it is an intrinsic\n :return: True, if yes\n " ]
Please provide a description of the function:def can_handle(self, input_dict): return input_dict is not None \ and isinstance(input_dict, dict) \ and len(input_dict) == 1 \ and self.intrinsic_name in input_dict
[ "\n Validates that the input dictionary contains only one key and is of the given intrinsic_name\n\n :param input_dict: Input dictionary representing the intrinsic function\n :return: True if it matches expected structure, False otherwise\n " ]
Please provide a description of the function:def _parse_resource_reference(cls, ref_value): no_result = (None, None) if not isinstance(ref_value, string_types): return no_result splits = ref_value.split(cls._resource_ref_separator, 1) # Either there is no 'dot' (or) one of the values is empty string (Ex: when you split "LogicalId.") if len(splits) != 2 or not all(splits): return no_result return splits[0], splits[1]
[ "\n Splits a resource reference of structure \"LogicalId.Property\" and returns the \"LogicalId\" and \"Property\"\n separately.\n\n :param string ref_value: Input reference value which *may* contain the structure \"LogicalId.Property\"\n :return string, string: Returns two values - logical_id, property. If the input does not contain the structure,\n then both `logical_id` and property will be None\n\n " ]
Please provide a description of the function:def resolve_parameter_refs(self, input_dict, parameters): if not self.can_handle(input_dict): return input_dict param_name = input_dict[self.intrinsic_name] if not isinstance(param_name, string_types): return input_dict if param_name in parameters: return parameters[param_name] else: return input_dict
[ "\n Resolves references that are present in the parameters and returns the value. If it is not in parameters,\n this method simply returns the input unchanged.\n\n :param input_dict: Dictionary representing the Ref function. Must contain only one key and it should be \"Ref\".\n Ex: {Ref: \"foo\"}\n\n :param parameters: Dictionary of parameter values for resolution\n :return:\n " ]
Please provide a description of the function:def resolve_resource_refs(self, input_dict, supported_resource_refs): if not self.can_handle(input_dict): return input_dict ref_value = input_dict[self.intrinsic_name] logical_id, property = self._parse_resource_reference(ref_value) # ref_value could not be parsed if not logical_id: return input_dict resolved_value = supported_resource_refs.get(logical_id, property) if not resolved_value: return input_dict return { self.intrinsic_name: resolved_value }
[ "\n Resolves references to some property of a resource. These are runtime properties which can't be converted\n to a value here. Instead we output another reference that will more actually resolve to the value when\n executed via CloudFormation\n\n Example:\n {\"Ref\": \"LogicalId.Property\"} => {\"Ref\": \"SomeOtherLogicalId\"}\n\n :param dict input_dict: Dictionary representing the Ref function to be resolved.\n :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of\n an `SupportedResourceReferences` object that contain value of the property.\n :return dict: Dictionary with resource references resolved.\n " ]
Please provide a description of the function:def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): if not self.can_handle(input_dict): return input_dict ref_value = input_dict[self.intrinsic_name] if not isinstance(ref_value, string_types) or self._resource_ref_separator in ref_value: return input_dict logical_id = ref_value resolved_value = supported_resource_id_refs.get(logical_id) if not resolved_value: return input_dict return { self.intrinsic_name: resolved_value }
[ "\n Updates references to the old logical id of a resource to the new (generated) logical id.\n\n Example:\n {\"Ref\": \"MyLayer\"} => {\"Ref\": \"MyLayerABC123\"}\n\n :param dict input_dict: Dictionary representing the Ref function to be resolved.\n :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones.\n :return dict: Dictionary with resource references resolved.\n " ]
Please provide a description of the function:def resolve_parameter_refs(self, input_dict, parameters): def do_replacement(full_ref, prop_name): return parameters.get(prop_name, full_ref) return self._handle_sub_action(input_dict, do_replacement)
[ "\n Substitute references found within the string of `Fn::Sub` intrinsic function\n\n :param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be\n `Fn::Sub`. Ex: {\"Fn::Sub\": ...}\n\n :param parameters: Dictionary of parameter values for substitution\n :return: Resolved\n ", "\n Replace parameter references with actual value. Return value of this method is directly replaces the\n reference structure\n\n :param full_ref: => ${logicalId.property}\n :param prop_name: => logicalId.property\n :return: Either the value it resolves to. If not the original reference\n " ]
Please provide a description of the function:def resolve_resource_refs(self, input_dict, supported_resource_refs): def do_replacement(full_ref, ref_value): # Split the value by separator, expecting to separate out LogicalId.Property splits = ref_value.split(self._resource_ref_separator) # If we don't find at least two parts, there is nothing to resolve if len(splits) < 2: return full_ref logical_id = splits[0] property = splits[1] resolved_value = supported_resource_refs.get(logical_id, property) if not resolved_value: # This ID/property combination is not in the supported references return full_ref # We found a LogicalId.Property combination that can be resolved. Construct the output by replacing # the part of the reference string and not constructing a new ref. This allows us to support GetAtt-like # syntax and retain other attributes. Ex: ${LogicalId.Property.Arn} => ${SomeOtherLogicalId.Arn} replacement = self._resource_ref_separator.join([logical_id, property]) return full_ref.replace(replacement, resolved_value) return self._handle_sub_action(input_dict, do_replacement)
[ "\n Resolves reference to some property of a resource. Inside string to be substituted, there could be either a\n \"Ref\" or a \"GetAtt\" usage of this property. They have to be handled differently.\n\n Ref usages are directly converted to a Ref on the resolved value. GetAtt usages are split under the assumption\n that there can be only one property of resource referenced here. Everything else is an attribute reference.\n\n Example:\n\n Let's say `LogicalId.Property` will be resolved to `ResolvedValue`\n\n Ref usage:\n ${LogicalId.Property} => ${ResolvedValue}\n\n GetAtt usage:\n ${LogicalId.Property.Arn} => ${ResolvedValue.Arn}\n ${LogicalId.Property.Attr1.Attr2} => {ResolvedValue.Attr1.Attr2}\n\n\n :param input_dict: Dictionary to be resolved\n :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of\n an `SupportedResourceReferences` object that contain value of the property.\n :return: Resolved dictionary\n ", "\n Perform the appropriate replacement to handle ${LogicalId.Property} type references inside a Sub.\n This method is called to get the replacement string for each reference within Sub's value\n\n :param full_ref: Entire reference string such as \"${LogicalId.Property}\"\n :param ref_value: Just the value of the reference such as \"LogicalId.Property\"\n :return: Resolved reference of the structure \"${SomeOtherLogicalId}\". Result should always include the\n ${} structure since we are not resolving to final value, but just converting one reference to another\n " ]
Please provide a description of the function:def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): def do_replacement(full_ref, ref_value): # Split the value by separator, expecting to separate out LogicalId splits = ref_value.split(self._resource_ref_separator) # If we don't find at least one part, there is nothing to resolve if len(splits) < 1: return full_ref logical_id = splits[0] resolved_value = supported_resource_id_refs.get(logical_id) if not resolved_value: # This ID/property combination is not in the supported references return full_ref # We found a LogicalId.Property combination that can be resolved. Construct the output by replacing # the part of the reference string and not constructing a new ref. This allows us to support GetAtt-like # syntax and retain other attributes. Ex: ${LogicalId.Property.Arn} => ${SomeOtherLogicalId.Arn} return full_ref.replace(logical_id, resolved_value) return self._handle_sub_action(input_dict, do_replacement)
[ "\n Resolves reference to some property of a resource. Inside string to be substituted, there could be either a\n \"Ref\" or a \"GetAtt\" usage of this property. They have to be handled differently.\n\n Ref usages are directly converted to a Ref on the resolved value. GetAtt usages are split under the assumption\n that there can be only one property of resource referenced here. Everything else is an attribute reference.\n\n Example:\n\n Let's say `LogicalId` will be resolved to `NewLogicalId`\n\n Ref usage:\n ${LogicalId} => ${NewLogicalId}\n\n GetAtt usage:\n ${LogicalId.Arn} => ${NewLogicalId.Arn}\n ${LogicalId.Attr1.Attr2} => {NewLogicalId.Attr1.Attr2}\n\n\n :param input_dict: Dictionary to be resolved\n :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones.\n :return: Resolved dictionary\n ", "\n Perform the appropriate replacement to handle ${LogicalId} type references inside a Sub.\n This method is called to get the replacement string for each reference within Sub's value\n\n :param full_ref: Entire reference string such as \"${LogicalId.Property}\"\n :param ref_value: Just the value of the reference such as \"LogicalId.Property\"\n :return: Resolved reference of the structure \"${SomeOtherLogicalId}\". Result should always include the\n ${} structure since we are not resolving to final value, but just converting one reference to another\n " ]
Please provide a description of the function:def _handle_sub_action(self, input_dict, handler): if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name sub_value = input_dict[key] input_dict[key] = self._handle_sub_value(sub_value, handler) return input_dict
[ "\n Handles resolving replacements in the Sub action based on the handler that is passed as an input.\n\n :param input_dict: Dictionary to be resolved\n :param supported_values: One of several different objects that contain the supported values that\n need to be changed. See each method above for specifics on these objects.\n :param handler: handler that is specific to each implementation.\n :return: Resolved value of the Sub dictionary\n " ]
Please provide a description of the function:def _handle_sub_value(self, sub_value, handler_method): # Just handle known references within the string to be substituted and return the whole dictionary # because that's the best we can do here. if isinstance(sub_value, string_types): # Ex: {Fn::Sub: "some string"} sub_value = self._sub_all_refs(sub_value, handler_method) elif isinstance(sub_value, list) and len(sub_value) > 0 and isinstance(sub_value[0], string_types): # Ex: {Fn::Sub: ["some string", {a:b}] } sub_value[0] = self._sub_all_refs(sub_value[0], handler_method) return sub_value
[ "\n Generic method to handle value to Fn::Sub key. We are interested in parsing the ${} syntaxes inside\n the string portion of the value.\n\n :param sub_value: Value of the Sub function\n :param handler_method: Method to be called on every occurrence of `${LogicalId}` structure within the string.\n Implementation could resolve and replace this structure with whatever they seem fit\n :return: Resolved value of the Sub dictionary\n " ]
Please provide a description of the function:def _sub_all_refs(self, text, handler_method): # RegExp to find pattern "${logicalId.property}" and return the word inside bracket logical_id_regex = '[A-Za-z0-9\.]+|AWS::[A-Z][A-Za-z]*' ref_pattern = re.compile(r'\$\{(' + logical_id_regex + ')\}') # Find all the pattern, and call the handler to decide how to substitute them. # Do the substitution and return the final text return re.sub(ref_pattern, # Pass the handler entire string ${logicalId.property} as first parameter and "logicalId.property" # as second parameter. Return value will be substituted lambda match: handler_method(match.group(0), match.group(1)), text)
[ "\n Substitute references within a string that is using ${key} syntax by calling the `handler_method` on every\n occurrence of this structure. The value returned by this method directly replaces the reference structure.\n\n Ex:\n text = \"${key1}-hello-${key2}\n def handler_method(full_ref, ref_value):\n return \"foo\"\n\n _sub_all_refs(text, handler_method) will output \"foo-hello-foo\"\n\n :param string text: Input text\n :param handler_method: Method to be called to handle each occurrence of ${blah} reference structure.\n First parameter to this method is the full reference structure Ex: ${LogicalId.Property}.\n Second parameter is just the value of the reference such as \"LogicalId.Property\"\n\n :return string: Text with all reference structures replaced as necessary\n " ]
Please provide a description of the function:def resolve_resource_refs(self, input_dict, supported_resource_refs): if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name value = input_dict[key] # Value must be an array with *at least* two elements. If not, this is invalid GetAtt syntax. We just pass along # the input to CFN for it to do the "official" validation. if not isinstance(value, list) or len(value) < 2: return input_dict if (not all(isinstance(entry, string_types) for entry in value)): raise InvalidDocumentException( [InvalidTemplateException('Invalid GetAtt value {}. GetAtt expects an array with 2 strings.' .format(value))]) # Value of GetAtt is an array. It can contain any number of elements, with first being the LogicalId of # resource and rest being the attributes. In a SAM template, a reference to a resource can be used in the # first parameter. However tools like AWS CLI might break them down as well. So let's just concatenate # all elements, and break them into separate parts in a more standard way. # # Example: # { Fn::GetAtt: ["LogicalId.Property", "Arn"] } is equivalent to { Fn::GetAtt: ["LogicalId", "Property.Arn"] } # Former is the correct notation. However tools like AWS CLI can construct the later style. # Let's normalize the value into "LogicalId.Property.Arn" to handle both scenarios value_str = self._resource_ref_separator.join(value) splits = value_str.split(self._resource_ref_separator) logical_id = splits[0] property = splits[1] remaining = splits[2:] # if any resolved_value = supported_resource_refs.get(logical_id, property) return self._get_resolved_dictionary(input_dict, key, resolved_value, remaining)
[ "\n Resolve resource references within a GetAtt dict.\n\n Example:\n { \"Fn::GetAtt\": [\"LogicalId.Property\", \"Arn\"] } => {\"Fn::GetAtt\": [\"ResolvedLogicalId\", \"Arn\"]}\n\n\n Theoretically, only the first element of the array can contain reference to SAM resources. The second element\n is name of an attribute (like Arn) of the resource.\n\n However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot\n contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this:\n\n `!GetAtt LogicalId.Property.Arn` => {\"Fn::GetAtt\": [ \"LogicalId\", \"Property.Arn\" ] }\n\n Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains\n a known reference, and resolve it if we can.\n\n :param input_dict: Dictionary to be resolved\n :param samtransaltor.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of\n an `SupportedResourceReferences` object that contain value of the property.\n :return: Resolved dictionary\n " ]
Please provide a description of the function:def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name value = input_dict[key] # Value must be an array with *at least* two elements. If not, this is invalid GetAtt syntax. We just pass along # the input to CFN for it to do the "official" validation. if not isinstance(value, list) or len(value) < 2: return input_dict value_str = self._resource_ref_separator.join(value) splits = value_str.split(self._resource_ref_separator) logical_id = splits[0] remaining = splits[1:] # if any resolved_value = supported_resource_id_refs.get(logical_id) return self._get_resolved_dictionary(input_dict, key, resolved_value, remaining)
[ "\n Resolve resource references within a GetAtt dict.\n\n Example:\n { \"Fn::GetAtt\": [\"LogicalId\", \"Arn\"] } => {\"Fn::GetAtt\": [\"ResolvedLogicalId\", \"Arn\"]}\n\n\n Theoretically, only the first element of the array can contain reference to SAM resources. The second element\n is name of an attribute (like Arn) of the resource.\n\n However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot\n contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this:\n\n `!GetAtt LogicalId.Arn` => {\"Fn::GetAtt\": [ \"LogicalId\", \"Arn\" ] }\n\n Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains\n a known reference, and resolve it if we can.\n\n :param input_dict: Dictionary to be resolved\n :param dict supported_resource_id_refs: Dictionary that maps old logical ids to new ones.\n :return: Resolved dictionary\n " ]
Please provide a description of the function:def _get_resolved_dictionary(self, input_dict, key, resolved_value, remaining): if resolved_value: # We resolved to a new resource logicalId. Use this as the first element and keep remaining elements intact # This is the new value of Fn::GetAtt input_dict[key] = [resolved_value] + remaining return input_dict
[ "\n Resolves the function and returns the updated dictionary\n\n :param input_dict: Dictionary to be resolved\n :param key: Name of this intrinsic.\n :param resolved_value: Resolved or updated value for this action.\n :param remaining: Remaining sections for the GetAtt action.\n " ]
Please provide a description of the function:def resolve_parameter_refs(self, input_dict, parameters): if not self.can_handle(input_dict): return input_dict value = input_dict[self.intrinsic_name] # FindInMap expects an array with 3 values if not isinstance(value, list) or len(value) != 3: raise InvalidDocumentException( [InvalidTemplateException('Invalid FindInMap value {}. FindInMap expects an array with 3 values.' .format(value))]) map_name = self.resolve_parameter_refs(value[0], parameters) top_level_key = self.resolve_parameter_refs(value[1], parameters) second_level_key = self.resolve_parameter_refs(value[2], parameters) if not isinstance(map_name, string_types) or \ not isinstance(top_level_key, string_types) or \ not isinstance(second_level_key, string_types): return input_dict if map_name not in parameters or \ top_level_key not in parameters[map_name] or \ second_level_key not in parameters[map_name][top_level_key]: return input_dict return parameters[map_name][top_level_key][second_level_key]
[ "\n Recursively resolves \"Fn::FindInMap\"references that are present in the mappings and returns the value.\n If it is not in mappings, this method simply returns the input unchanged.\n\n :param input_dict: Dictionary representing the FindInMap function. Must contain only one key and it\n should be \"Fn::FindInMap\".\n\n :param parameters: Dictionary of mappings from the SAM template\n " ]
Please provide a description of the function:def lambda_handler(event, context): ''' Process a RDS enhenced monitoring DATA_MESSAGE, coming from CLOUDWATCH LOGS ''' # event is a dict containing a base64 string gzipped event = json.loads(gzip.GzipFile(fileobj=StringIO(event['awslogs']['data'].decode('base64'))).read()) account = event['owner'] region = context.invoked_function_arn.split(':', 4)[3] log_events = event['logEvents'] for log_event in log_events: message = json.loads(log_event['message']) ts = log_event['timestamp'] / 1000 _process_rds_enhanced_monitoring_message(ts, message, account, region) stats.flush() return {'Status': 'OK'}
[]
Please provide a description of the function:def _construct_rest_api(self): rest_api = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes) rest_api.BinaryMediaTypes = self.binary_media rest_api.MinimumCompressionSize = self.minimum_compression_size if self.endpoint_configuration: self._set_endpoint_configuration(rest_api, self.endpoint_configuration) elif not RegionConfiguration.is_apigw_edge_configuration_supported(): # Since this region does not support EDGE configuration, we explicitly set the endpoint type # to Regional which is the only supported config. self._set_endpoint_configuration(rest_api, "REGIONAL") if self.definition_uri and self.definition_body: raise InvalidResourceException(self.logical_id, "Specify either 'DefinitionUri' or 'DefinitionBody' property and not both") self._add_cors() self._add_auth() self._add_gateway_responses() if self.definition_uri: rest_api.BodyS3Location = self._construct_body_s3_dict() elif self.definition_body: rest_api.Body = self.definition_body if self.name: rest_api.Name = self.name return rest_api
[ "Constructs and returns the ApiGateway RestApi.\n\n :returns: the RestApi to which this SAM Api corresponds\n :rtype: model.apigateway.ApiGatewayRestApi\n " ]