|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"). |
| 5 | + * You may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.amazon.aws.partners.saasfactory.saasboost; |
| 18 | + |
| 19 | +import com.amazonaws.services.lambda.runtime.Context; |
| 20 | +import com.amazonaws.services.lambda.runtime.RequestHandler; |
| 21 | +import com.amazonaws.services.lambda.runtime.events.SNSEvent; |
| 22 | +import org.slf4j.Logger; |
| 23 | +import org.slf4j.LoggerFactory; |
| 24 | +import software.amazon.awssdk.core.exception.SdkServiceException; |
| 25 | +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; |
| 26 | +import software.amazon.awssdk.services.cloudformation.model.*; |
| 27 | +import software.amazon.awssdk.services.cloudformation.model.Stack; |
| 28 | +import software.amazon.awssdk.services.eventbridge.EventBridgeClient; |
| 29 | + |
| 30 | +import java.util.*; |
| 31 | +import java.util.regex.Pattern; |
| 32 | + |
| 33 | +public class OnboardingAppStackListener implements RequestHandler<SNSEvent, Object> { |
| 34 | + |
| 35 | + private static final Logger LOGGER = LoggerFactory.getLogger(OnboardingAppStackListener.class); |
| 36 | + private static final String AWS_REGION = System.getenv("AWS_REGION"); |
| 37 | + private static final String SAAS_BOOST_ENV = System.getenv("SAAS_BOOST_ENV"); |
| 38 | + private static final String SAAS_BOOST_EVENT_BUS = System.getenv("SAAS_BOOST_EVENT_BUS"); |
| 39 | + private static final String UPDATE_TENANT_RESOURCES = "Tenant Update Resources"; |
| 40 | + private static final String EVENT_SOURCE = "saas-boost"; |
| 41 | + private static final Pattern STACK_NAME_PATTERN = Pattern |
| 42 | + .compile("^sb-" + SAAS_BOOST_ENV + "-tenant-[a-z0-9]{8}-app-.+-.+$"); |
| 43 | + private static final Collection<String> EVENTS_OF_INTEREST = Collections.unmodifiableCollection( |
| 44 | + Arrays.asList("CREATE_COMPLETE", "UPDATE_COMPLETE")); |
| 45 | + private final CloudFormationClient cfn; |
| 46 | + private final EventBridgeClient eventBridge; |
| 47 | + |
| 48 | + public OnboardingAppStackListener() { |
| 49 | + final long startTimeMillis = System.currentTimeMillis(); |
| 50 | + if (Utils.isBlank(AWS_REGION)) { |
| 51 | + throw new IllegalStateException("Missing required environment variable AWS_REGION"); |
| 52 | + } |
| 53 | + if (Utils.isBlank(SAAS_BOOST_EVENT_BUS)) { |
| 54 | + throw new IllegalStateException("Missing required environment variable SAAS_BOOST_EVENT_BUS"); |
| 55 | + } |
| 56 | + this.cfn = Utils.sdkClient(CloudFormationClient.builder(), CloudFormationClient.SERVICE_NAME); |
| 57 | + this.eventBridge = Utils.sdkClient(EventBridgeClient.builder(), EventBridgeClient.SERVICE_NAME); |
| 58 | + LOGGER.info("Constructor init: {}", System.currentTimeMillis() - startTimeMillis); |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public Object handleRequest(SNSEvent event, Context context) { |
| 63 | + LOGGER.info(Utils.toJson(event)); |
| 64 | + |
| 65 | + List<SNSEvent.SNSRecord> records = event.getRecords(); |
| 66 | + SNSEvent.SNS sns = records.get(0).getSNS(); |
| 67 | + String message = sns.getMessage(); |
| 68 | + |
| 69 | + CloudFormationEvent cloudFormationEvent = CloudFormationEventDeserializer.deserialize(message); |
| 70 | + |
| 71 | + // CloudFormation sends SNS notifications for every resource in a stack going through each status change. |
| 72 | + // We want to process the resources of the tenant-onboarding-app.yaml CloudFormation stack only after the |
| 73 | + // stack has finished being created or updated so we don't trigger anything downstream prematurely. |
| 74 | + if (filter(cloudFormationEvent)) { |
| 75 | + String stackName = cloudFormationEvent.getStackName(); |
| 76 | + String stackStatus = cloudFormationEvent.getResourceStatus(); |
| 77 | + LOGGER.info("Stack " + stackName + " is in status " + stackStatus); |
| 78 | + |
| 79 | + // We need to get the tenant and the application service this stack was run for |
| 80 | + String tenantId = null; |
| 81 | + String serviceName = null; |
| 82 | + try { |
| 83 | + DescribeStacksResponse stacks = cfn.describeStacks(req -> req |
| 84 | + .stackName(cloudFormationEvent.getStackId()) |
| 85 | + ); |
| 86 | + Stack stack = stacks.stacks().get(0); |
| 87 | + for (Parameter parameter : stack.parameters()) { |
| 88 | + if ("TenantId".equals(parameter.parameterKey())) { |
| 89 | + tenantId = parameter.parameterValue(); |
| 90 | + } |
| 91 | + if ("ServiceName".equals(parameter.parameterKey())) { |
| 92 | + serviceName = parameter.parameterValue(); |
| 93 | + } |
| 94 | + } |
| 95 | + } catch (SdkServiceException cfnError) { |
| 96 | + LOGGER.error("cfn:DescribeStacks error", cfnError); |
| 97 | + LOGGER.error(Utils.getFullStackTrace(cfnError)); |
| 98 | + throw cfnError; |
| 99 | + } |
| 100 | + |
| 101 | + // We use these to build the ARN of the resources we're interested in if we don't |
| 102 | + // get the ARN straight from the CloudFormation physical resource id |
| 103 | + final String[] lambdaArn = context.getInvokedFunctionArn().split(":"); |
| 104 | + final String partition = lambdaArn[1]; |
| 105 | + final String accountId = lambdaArn[4]; |
| 106 | + |
| 107 | + // We're looking for CodePipeline repository resources in a CREATE_COMPLETE state. There could be |
| 108 | + // multiple pipelines provisioned depending on how the application services are configured. |
| 109 | + try { |
| 110 | + ListStackResourcesResponse resources = cfn.listStackResources(req -> req |
| 111 | + .stackName(cloudFormationEvent.getStackId()) |
| 112 | + ); |
| 113 | + for (StackResourceSummary resource : resources.stackResourceSummaries()) { |
| 114 | +// LOGGER.debug("Processing resource {} {} {} {}", resource.resourceType(), |
| 115 | +// resource.resourceStatusAsString(), resource.logicalResourceId(), |
| 116 | +// resource.physicalResourceId()); |
| 117 | + if ("CREATE_COMPLETE".equals(resource.resourceStatusAsString())) { |
| 118 | + if ("AWS::CodePipeline::Pipeline".equals(resource.resourceType())) { |
| 119 | + String codePipeline = resource.physicalResourceId(); |
| 120 | + // The resources collection on the tenant object is Map<String, Resource> |
| 121 | + // so we need a unique key per service code pipeline. We'll prefix the |
| 122 | + // key with SERVICE_ and suffix it with _CODE_PIPELINE so we can find |
| 123 | + // all of the tenant's code pipelines later on by looking for that pattern. |
| 124 | + String key = serviceNameResourceKey(serviceName, AwsResource.CODE_PIPELINE.name()); |
| 125 | + LOGGER.info("Publishing update tenant resources event for tenant {} {} {}", tenantId, |
| 126 | + key, codePipeline); |
| 127 | + |
| 128 | + Map<String, Object> tenantResource = new HashMap<>(); |
| 129 | + tenantResource.put(key, Map.of( |
| 130 | + "name", codePipeline, |
| 131 | + "arn", AwsResource.CODE_PIPELINE.formatArn(partition, AWS_REGION, accountId, |
| 132 | + codePipeline), |
| 133 | + "consoleUrl", AwsResource.CODE_PIPELINE.formatUrl(AWS_REGION, codePipeline) |
| 134 | + )); |
| 135 | + |
| 136 | + // The update tenant resources API call is additive, so we don't need to pull the |
| 137 | + // current tenant object ourselves. |
| 138 | + Utils.publishEvent(eventBridge, SAAS_BOOST_EVENT_BUS, EVENT_SOURCE, |
| 139 | + UPDATE_TENANT_RESOURCES, |
| 140 | + Map.of("tenantId", tenantId, "resources", Utils.toJson(tenantResource)) |
| 141 | + ); |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + } catch (SdkServiceException cfnError) { |
| 146 | + LOGGER.error("cfn:ListStackResources error", cfnError); |
| 147 | + LOGGER.error(Utils.getFullStackTrace(cfnError)); |
| 148 | + throw cfnError; |
| 149 | + } |
| 150 | + } |
| 151 | + return null; |
| 152 | + } |
| 153 | + |
| 154 | + protected static String serviceNameResourceKey(String serviceName, String resourceType) { |
| 155 | + if (Utils.isBlank(serviceName)) { |
| 156 | + throw new IllegalArgumentException("Service name must not be blank"); |
| 157 | + } |
| 158 | + if (Utils.isBlank(resourceType)) { |
| 159 | + throw new IllegalArgumentException("Resource type must not be blank"); |
| 160 | + } |
| 161 | + return "SERVICE_" |
| 162 | + + serviceName.toUpperCase().replaceAll("\\s+", "_") |
| 163 | + + "_" |
| 164 | + + resourceType; |
| 165 | + } |
| 166 | + |
| 167 | + protected static boolean filter(CloudFormationEvent cloudFormationEvent) { |
| 168 | + return ("AWS::CloudFormation::Stack".equals(cloudFormationEvent.getResourceType()) |
| 169 | + && STACK_NAME_PATTERN.matcher(cloudFormationEvent.getStackName()).matches() |
| 170 | + && EVENTS_OF_INTEREST.contains(cloudFormationEvent.getResourceStatus())); |
| 171 | + } |
| 172 | +} |
0 commit comments