3 O4\ƈ@sddZddlmZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZmZmZdd lmZmZdd lmZdd lmZdd lmZmZdd lmZmZddlm Z m!Z!ddl"m#Z#m$Z$m%Z%m&Z&ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-ddl.m/Z/ddl0m1Z1GdddeZ2GdddeZ3GdddeZ4GdddeZ5GdddeZ6dS)z SAM macro definitions ) string_typesN) ApiGenerator)construct_s3_location_object) get_tag_list) PropertyTypeSamResourceMacroResourceTypeResolver)ApiGatewayDeploymentApiGatewayStage) NestedStack) DynamoDBTable)InvalidEventExceptionInvalidResourceException)FunctionPolicies PolicyTypes)IAMRoleIAMRolePolicies)LambdaFunction LambdaVersion LambdaAliasLambdaLayerVersion)dict_ofis_stris_typelist_ofone_ofany_type)logical_id_generator) ArnGeneratorc@seZdZdZdZedeeee edeedeedeeee edeeee edee edeedee edee edee edeedeee eeee ee edeede eee ede eee edee edeee eedeee eedee ede ede eeee edeeededZeejjejjjejjjejjjZdddZejejd Zd d Zd d ZddZddZddZddZ ddZ!d#ddZ"ddZ#ddZ$dd Z%d!d"Z&dS)$ SamFunctionzSAM function macro. zAWS::Serverless::FunctionFT) FunctionNameHandlerRuntimeCodeUri InlineCodeDeadLetterQueue Description MemorySizeTimeout VpcConfigRolePoliciesPermissionsBoundary EnvironmentEventsTagsTracing KmsKeyArnDeploymentPreferenceReservedConcurrentExecutionsLayersAutoPublishAliasVersionDescriptionzsqs:SendMessagez sns:Publish)ZSQSZSNS)ZAliasVersioncCsDyd|j|iStk r>}zt|j|jWYdd}~XnXdS)Nevent_resources)_event_resources_to_linkrr logical_idmessage)self resourceser@/Users/sshvans/Documents/Work/Quickstart/python-virtual-environments/env/lib/python3.6/site-packages/samtranslator/model/sam_resources.pyresources_to_linkHszSamFunction.resources_to_linkc Ks.g}|d}|jr|j|j}|j|d}|jrv|jd|j|}|j||d}|j|||}|j||j||jr|j |j dd|||j di}|st dd} |j dkr|j |} | jd|_ |j| y||j|| |d |d 7}Wn2tk r(} zt|j| jWYdd} ~ XnX|S) aiReturns the Lambda function, role, and event resources to which this SAM Function corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Function expands :rtype: list intrinsics_resolverNr6)rC deployment_preference_collectionmanaged_policy_mapz/Managed policy map is empty, but should not be.Zarnr9) lambda_alias)r& _validate_dlq_construct_lambda_functionappendr6_get_resolved_alias_name_construct_version_construct_aliasr35_validate_deployment_preference_and_add_update_policyget Exceptionr+_construct_roleget_runtime_attr_generate_event_resourcesrrr;r<) r=kwargsr>rClambda_functionrFZ alias_namelambda_versionrEexecution_roler?r@r@rAto_cloudformationPs>          zSamFunction.to_cloudformationcCs*|j|}t|ts&t|jdj||S)a Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function was used), then this method raises an exception. If alias name is just a plain string, it will return as is :param dict or string original_alias_value: Value of Alias property as provided by the customer :param samtranslator.intrinsics.resolver.IntrinsicsResolver intrinsics_resolver: Instance of the resolver that knows how to resolve parameter references :return string: Alias name :raises InvalidResourceException: If the value is a complex intrinsic function that cannot be resolved z6'{}' must be a string or a Ref to a template parameter)resolve_parameter_refs isinstancerrr;format)r=Z property_nameZoriginal_alias_valuerCZresolved_alias_namer@r@rArJs   z$SamFunction._get_resolved_alias_namecCst|j|j|jd}|jr"|j|_|j|_|j|_|j|_|j|_|j |_ |j |_ |j |_ |j |_ |j |_|j|_|j|_|j|j|_|j|_|jrd|ji|_|jrd|jdi|_|S)zConstructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list ) depends_on attributesZMode TargetArn)rr;r[resource_attributesr!r"r#r'r(r)r*r+r._construct_code_dictCoder2r4_construct_tag_listr0r5r1Z TracingConfigr&ZDeadLetterConfig)r=rTr@r@rArHs,    z&SamFunction._construct_lambda_functionc CsHt|jd|jd}tj|_tjdg}|jrB|j tjdt d|j idd}g}|j r|j tj |j|j d|j d xt|jD]\}}|jtjkr|j |jd t||jd q|jtjkr|j}t|jtr|j|kr||j}||kr"|j |qt|jd j|qWt||_|p8d|_ |j|_|S) zConstructs a Lambda execution role based on this SAM function's Policies property. :returns: the generated IAM Role :rtype: model.iam.IAMRole r+)r\z(service-role/AWSLambdaBasicExecutionRoleZAWSXrayWriteOnlyAccessr,N)Zpolicy_template_processorTyper]Policy)Z PolicyNameZPolicyDocumentz:Policy at index {} in the 'Policies' property is not valid)rr;#get_passthrough_resource_attributesrZlambda_assume_role_policyZAssumeRolePolicyDocumentrZgenerate_aws_managed_policy_arnr1rIrr,r&Zdead_letter_queue_policy dead_letter_queue_policy_actions enumeraterNtyperZPOLICY_STATEMENTstrdataZMANAGED_POLICYrYrrrZlistZManagedPolicyArnsr-) r=rErVZmanaged_policy_arnsZfunction_policiesZpolicy_documentsindexZ policy_entryZ policy_arnr@r@rArPs<          zSamFunction._construct_rolecCsftt|jj}|jjd s.|jjd r@t|jdj||jd|jkrbt|jdj|dS)zoValidates whether the DeadLetterQueue LogicalId is validation :raise: InvalidResourceException rbr]zH'DeadLetterQueue' requires Type and TargetArn properties to be specifiedz%'DeadLetterQueue' requires Type of {}N) rhrjrekeysr&rNrr;rZ)r=Zvalid_dlq_typesr@r@rArGszSamFunction._validate_dlqcCsi}|jrxx|jjD]j\}}y |jj|j|j|||}Wn2tk rp}zt|dj|WYdd}~XnX|j |||<qW|S)Nz{}) r/itemsevent_resolverresolve_resource_type from_dictr; TypeErrorrrZrB)r=r>r9r; event_dictZ event_sourcer?r@r@rAr:s "z$SamFunction._event_resources_to_linkNc Csg}|jrx|jjD]\}}y |jj|j|j|||}Wn2tk rp} zt|dj| WYdd} ~ XnX|px||d} x ||jD]\} } | | | <qW||j f| 7}qW|S)a+Generates and returns the resources associated with this function's events. :param model.lambda_.LambdaFunction lambda_function: generated Lambda function :param iam.IAMRole execution_role: generated Lambda execution role :param implicit_api: Global Implicit API resource where the implicit APIs get attached to, if necessary :param implicit_api_stage: Global implicit API stage resource where implicit APIs get attached to, if necessary :param event_resources: All the event sources associated with this Lambda function :param model.lambda_.LambdaAlias lambda_alias: Optional Lambda Alias resource if we want to connect the event sources to this alias :returns: a list containing the function's event resources :rtype: list z{}N)functionZrole) r/rmrnrorpr;rqrrZrW) r=rTrVr9rFr>r;rrZ eventsourcer?rSnameresourcer@r@rArRs " z%SamFunction._generate_event_resourcescCs6|jrd|jiS|jr&t|j|jdSt|jddS)NZipFiler$z,Either 'InlineCode' or 'CodeUri' must be set)r%r$rr;r)r=r@r@rAr_7s  z SamFunction._construct_code_dictcCs|j}|std|std|j|}dj|jd}tj||j}|j}|dkrZi}d|d<t ||d}|j d |_ |j |_ |S) aConstructs a Lambda Version resource that will be auto-published when CodeUri of the function changes. Old versions will not be deleted without a direct reference from the CloudFormation template. :param model.lambda_.LambdaFunction function: Lambda function object that is being connected to a version :param model.intrinsics.resolver.IntrinsicsResolver intrinsics_resolver: Class that can help resolve references to parameters present in CodeUri. It is a common usecase to set S3Key of Code to be a template parameter. Need to resolve the values otherwise we will never detect a change in Code dict :return: Lambda function Version resource z9Lambda function code must be a valid non-empty dictionaryz5intrinsics_resolver is required for versions creationz {id}Version)idNRetainDeletionPolicy)r;r\rt)r` ValueErrorrXrZr;rLogicalIdGeneratorgenrdrrQr!r7r')r=rsrCZ code_dictprefixr;r\rUr@r@rArKAs    zSamFunction._construct_versioncCsR|st|jddj|j|d}t||jd}||_|jd|_|jd|_|S)aConstructs a Lambda Alias for the given function and pointing to the given version :param string name: Name of the alias :param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with :param model.lambda_.LambdaVersion version: Lambda version object to associate the alias with :return: Lambda alias object :rtype model.lambda_.LambdaAlias z)Alias name is required to create an aliasz{id}Alias{suffix})rwsuffix)r;r\rtversion) rr;rZrrdNamerQr!ZFunctionVersion)r=rtrsrr;aliasr@r@rArLus    zSamFunction._construct_aliascCsd|jkr<|j|jd|jd<t|jdtr # 4r c@s$eZdZdZdZedeeedee ee edee ee edee edee ee edeeede edee ede edee edee edee edee ee edee edee edee edee edeedZ ejejdZddZd S) SamApizSAM rest API macro. zAWS::Serverless::ApiFT)Z__MANAGE_SWAGGERr StageNameDefinitionBody DefinitionUriCacheClusterEnabledCacheClusterSize VariablesEndpointConfigurationMethodSettingsBinaryMediaTypesMinimumCompressionSizeCorsAuthGatewayResponsesAccessLogSetting CanarySettingTracingEnabled)ZStageZ DeploymentcKsg}t|j|j|j|j|j|j|j|j|j |j |j |j |j |j|j|j|j|j|j|j|jd}|j\}}}}|j|||g|j||S)adReturns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Function expands :rtype: list ) Zendpoint_configurationZmethod_settingsZ binary_mediaZminimum_compression_sizeZcorsZauthZgateway_responsesZaccess_log_settingZcanary_settingZtracing_enabledr^Zpassthrough_resource_attributes)rr;rrrr[rrrrrrrrrrrrrrr^rdrWextend)r=rSr>Z api_generatorZrest_apiZ deploymentZstageZ permissionsr@r@rArWs4  zSamApi.to_cloudformationN)rrrrrrrboolrrrrjrrr r rrWr@r@r@rArs.              rc @seZdZdZdZedeeeedeeee e e e edeee e ede e ede e dZ ddddZ d d Zd d Zd dZdS)SamSimpleTablezSAM simple table macro. zAWS::Serverless::SimpleTableF) PrimaryKeyProvisionedThroughput TableNamer0SSESpecificationSNB)StringNumberZBinarycKs|j}|gS)N)_construct_dynamodb_table)r=rSZdynamodb_resourcesr@r@rArWsz SamSimpleTable.to_cloudformationcCst|j|j|jd}|jr8|jd|j|jdd}n ddd}|g|_|ddd g|_|jrl|j|_nd |_ |j r|j |_ |j r|j |_ t |j rt|j |_ |S) N)r[r\rrb) AttributeNameZ AttributeTyperwrrHASH)rZKeyTypeZPAY_PER_REQUEST)r r;r[r^r_convert_attribute_typeZAttributeDefinitionsZ KeySchemarZ BillingModerrrr0r)r=Zdynamodb_tableZ primary_keyr@r@rArs$     z(SamSimpleTable._construct_dynamodb_tablecCs,||jkr|j|St|jdj|ddS)NzInvalid 'Type' "{actual}".)actual)attribute_type_conversionsrr;rZ)r=Zattribute_typer@r@rAr(s  z&SamSimpleTable._convert_attribute_typeN)rrrrrrrrrrrrrrrWrrr@r@r@rArs "rc @seZdZdZdZdZdZedee e e ede ede e ede e ede e ede e dZdd Zd d Zd d ZdS)SamApplicationzSAM application macro. Z ApplicationIdSemanticVersionzAWS::Serverless::ApplicationTF)Location TemplateUrl ParametersNotificationArnsr0TimeoutInMinutescKs|j}|gS)zJReturns the stack with the proper parameters for this application )_construct_nested_stack)r=rS nested_stackr@r@rArWAsz SamApplication.to_cloudformationcCs\t|j|j|jd}|j|_|j|_|j}|j|j||_|j |_ |j rR|j nd|_ |S)z9Constructs a AWS::CloudFormation::Stack resource )r[r\) r r;r[rdrr_get_application_tagsrar0rrZ TemplateURL)r=rapplication_tagsr@r@rArGs  z&SamApplication._construct_nested_stackcCsxi}t|jtrt|j|jjkrB|j|jdk rB|j|j||j<|j|jjkrt|j|jdk rt|j|j||j<|S)zQAdds tags to the stack if this resource is using the serverless app repo N)rYrrAPPLICATION_ID_KEYrlZ _SAR_APP_KEYSEMANTIC_VERSION_KEYZ_SAR_SEMVER_KEY)r=rr@r@rArUs z$SamApplication._get_application_tagsN)rrrrrrrrrrrrrrrrWrrr@r@r@rAr.s   rc@seZdZdZdZedeeee edeedeeee ede eedeededZ dZ dZ e je jgZdd Zd d Zd d ZdS)SamLayerVersionz SAM Layer macro zAWS::Serverless::LayerVersionFT) LayerNamer' ContentUriCompatibleRuntimes LicenseInfoRetentionPolicyrxDeletecKs g}|d}|j|j||S)aHReturns the Lambda layer to which this SAM Layer corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Function expands :rtype: list rC)rI_construct_lambda_layer)r=rSr>rCr@r@rArWtsz!SamLayerVersion.to_cloudformationcCs|j||jd|_|j||jd|_|j||jd|_|j||jd|_|j}|j}|dkrdi}||d<|j}tj ||j j }||_t |j|j |d}|js||_|j|_|j|_t|j|jd|_|j|_|j|_|S) zConstructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list rrr'rNry)r[r\r)Z_resolve_string_parameterrrr'r_get_retention_policy_valuerdr;rr{rr|rr[rrZContentr)r=rCZretention_policy_valuer\Zold_logical_idZnew_logical_idZ lambda_layerr@r@rArs,  z'SamLayerVersion._construct_lambda_layercCsn|jdks|jj|jjkr$|jS|jj|jjkr>|jS|jj|jkrjt|jdjd|j|jgdS)z Sets the deletion policy on this resource. The default is 'Retain'. :return: value for the DeletionPolicy attribute. Nz.'{}' must be one of the following options: {}.r)rlowerRETAINDELETEretention_policy_optionsrr;rZ)r=r@r@rArsz+SamLayerVersion._get_retention_policy_valueN)rrrrrrrrrrrrrrrrrWrrr@r@r@rArcs  .r)7rsixrZ samtranslator.model.eventsourcesrZ%samtranslator.model.eventsources.pullZ%samtranslator.model.eventsources.pushZ/samtranslator.model.eventsources.cloudwatchlogsZapi.api_generatorrZs3_utils.uri_parserrZtags.resource_taggingrZsamtranslator.modelrrr Zsamtranslator.model.apigatewayr r Z"samtranslator.model.cloudformationr Zsamtranslator.model.dynamodbr Zsamtranslator.model.exceptionsrrZ%samtranslator.model.function_policiesrrZsamtranslator.model.iamrrZsamtranslator.model.lambda_rrrrZsamtranslator.model.typesrrrrrrZsamtranslator.translatorrZ&samtranslator.translator.arn_generatorrr rrrrr@r@r@rAs6          L>5