mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(cloudformation): provision Lambda-backed custom resources and layer versions (#1146)
* feat(cloudformation): provision Lambda-backed custom resources and layer versions
Custom::* and AWS::CloudFormation::CustomResource resources were stubbed in the
provisioner, so the ServiceToken Lambda was never invoked. Stacks reported
CREATE_COMPLETE while the custom resource's work silently never ran (e.g. CDK
BucketDeployment left the destination bucket empty).
Provision custom resources by invoking the ServiceToken Lambda synchronously
and capturing the response it PUTs to ResponseURL:
- CfnResponseController (PUT /cfn-response/{token}) receives the callback
- CustomResourceResponseStore correlates it to the waiting provisioner
- ContainerReachableEndpoint (extracted from ContainerLauncher) gives the
ResponseURL an address reachable from inside the Lambda container
ResourceProperties scalars are stringified to match CloudFormation (true ->
"true"); Data is exposed via Fn::GetAtt; ServiceToken + properties are stored so
teardown can re-invoke the handler with RequestType=Delete.
Also provision AWS::Lambda::LayerVersion (previously stubbed) so layer ARNs
resolve and layer content is copied into /opt — required for the common
BucketDeployment case, whose handler shells out to a bundled AwsCliLayer.
Covers the single-Lambda synchronous custom-resource pattern; the async CDK
Provider framework (onEvent/isComplete polling) is not emulated.
Closes #1145
* test: pass ecsService/elbV2Service args to provisioner constructor
The merge with main added two constructor params; update the
custom-resource test's direct instantiation to match.
* fix(cloudformation): match AWS custom-resource event shape
Keep ServiceToken inside ResourceProperties (it is also surfaced at the
top level) to match real CloudFormation events, verified against the moto
reference (cloudformation/custom_model.py). Previously it was stripped.
Also include OldResourceProperties on Update requests, which CloudFormation
marks required so handlers can diff against the previous properties. The
prior values are read from the existing stash before it is overwritten.
* test: pass stepFunctionsService arg to provisioner constructor
origin/main added a StepFunctionsService parameter to the
CloudFormationResourceProvisioner constructor; update the custom-resource
test to match after merging main.
---------
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
08797954d9
commit
5de8d65b1a
9 files changed
+682
-22
No files matched your search
+47
@@ -0,0 +1,47 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* Computes the Floci base URL reachable from <em>inside</em> a Lambda container.
|
||||
*
|
||||
* <p>When the embedded DNS server is active, Lambda containers have it wired as their
|
||||
* resolver and can reach Floci by the configured hostname (or the default DNS suffix).
|
||||
* Otherwise we fall back to the raw Docker host address (e.g. {@code host.docker.internal}
|
||||
* or the bridge IP) resolved by {@link DockerHostResolver}.
|
||||
*
|
||||
* <p>This is the address that must back any URL handed to a Lambda for a callback —
|
||||
* most notably the {@code ResponseURL} a CloudFormation custom resource PUTs its result to.
|
||||
* Extracted from {@code ContainerLauncher} so both the launcher and the CloudFormation
|
||||
* provisioner share one definition of "how a container reaches Floci".
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ContainerReachableEndpoint {
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final DockerHostResolver dockerHostResolver;
|
||||
private final EmbeddedDnsServer embeddedDnsServer;
|
||||
|
||||
@Inject
|
||||
public ContainerReachableEndpoint(EmulatorConfig config,
|
||||
DockerHostResolver dockerHostResolver,
|
||||
EmbeddedDnsServer embeddedDnsServer) {
|
||||
this.config = config;
|
||||
this.dockerHostResolver = dockerHostResolver;
|
||||
this.embeddedDnsServer = embeddedDnsServer;
|
||||
}
|
||||
|
||||
/** The Floci {@code http://host:port} base URL reachable from inside a Lambda container. */
|
||||
public String baseUrl() {
|
||||
int flociPort = URI.create(config.baseUrl()).getPort();
|
||||
String flociHostname = embeddedDnsServer.getServerIp().isPresent()
|
||||
? config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX)
|
||||
: dockerHostResolver.resolve();
|
||||
return "http://" + flociHostname + ":" + flociPort;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Receives the response a CloudFormation custom-resource Lambda PUTs to its {@code ResponseURL}.
|
||||
*
|
||||
* <p>Stands in for the pre-signed S3 URL that real CloudFormation hands out. Floci points each
|
||||
* custom resource's {@code ResponseURL} at {@code <floci>/cfn-response/{token}}; the backing Lambda
|
||||
* PUTs its result document here, and {@link CustomResourceResponseStore} hands it to the waiting
|
||||
* provisioner.
|
||||
*
|
||||
* <p>The literal {@code /cfn-response/...} path takes precedence over the S3 controller's
|
||||
* {@code /{bucket}} template in JAX-RS matching, so this never collides with path-style S3.
|
||||
*/
|
||||
@Path("/cfn-response")
|
||||
public class CfnResponseController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CfnResponseController.class);
|
||||
|
||||
private final CustomResourceResponseStore store;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CfnResponseController(CustomResourceResponseStore store, ObjectMapper objectMapper) {
|
||||
this.store = store;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/{token}")
|
||||
public Response receive(@PathParam("token") String token, String body) {
|
||||
try {
|
||||
store.complete(token, objectMapper.readTree(body));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse custom-resource response for token {0}: {1}", token, e.getMessage());
|
||||
store.complete(token, objectMapper.createObjectNode().put("Status", "FAILED")
|
||||
.put("Reason", "Floci could not parse the custom-resource response body"));
|
||||
}
|
||||
// S3 pre-signed PUT returns 200 with an empty body; cfn-response only checks the status.
|
||||
return Response.ok().build();
|
||||
}
|
||||
}
|
||||
+304
-3
@@ -36,7 +36,9 @@ import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesService;
|
||||
import io.github.hectorvent.floci.services.pipes.model.DesiredState;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
@@ -53,7 +55,12 @@ import io.github.hectorvent.floci.services.cognito.CognitoService;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -62,7 +69,9 @@ import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
@@ -83,6 +92,16 @@ public class CloudFormationResourceProvisioner {
|
||||
private static final int LAMBDA_DEFAULT_EPHEMERAL_STORAGE_MB = 512;
|
||||
private static final String LAMBDA_DEFAULT_TRACING_MODE = "PassThrough";
|
||||
|
||||
/** Reserved attribute keys used to carry custom-resource state to the later Delete invocation. */
|
||||
private static final String CR_SERVICE_TOKEN_ATTR = "__FlociServiceToken";
|
||||
private static final String CR_PROPERTIES_ATTR = "__FlociResourceProperties";
|
||||
/**
|
||||
* How long to wait for the Lambda's ResponseURL callback after the synchronous invoke returns.
|
||||
* The invoke already blocks until the handler finishes, so this only covers a PUT that lands
|
||||
* fractionally after the container returns control.
|
||||
*/
|
||||
private static final Duration CR_RESPONSE_TIMEOUT = Duration.ofSeconds(10);
|
||||
|
||||
private final S3Service s3Service;
|
||||
private final SqsService sqsService;
|
||||
private final SnsService snsService;
|
||||
@@ -98,6 +117,10 @@ public class CloudFormationResourceProvisioner {
|
||||
private final EcrService ecrService;
|
||||
private final PipesService pipesService;
|
||||
private final CognitoService cognitoService;
|
||||
private final LambdaLayerService lambdaLayerService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final CustomResourceResponseStore customResourceResponseStore;
|
||||
private final ContainerReachableEndpoint reachableEndpoint;
|
||||
private final EcsService ecsService;
|
||||
private final ElbV2Service elbV2Service;
|
||||
private final StepFunctionsService stepFunctionsService;
|
||||
@@ -114,6 +137,10 @@ public class CloudFormationResourceProvisioner {
|
||||
EcrService ecrService,
|
||||
PipesService pipesService,
|
||||
CognitoService cognitoService,
|
||||
LambdaLayerService lambdaLayerService,
|
||||
ObjectMapper objectMapper,
|
||||
CustomResourceResponseStore customResourceResponseStore,
|
||||
ContainerReachableEndpoint reachableEndpoint,
|
||||
EcsService ecsService,
|
||||
ElbV2Service elbV2Service,
|
||||
StepFunctionsService stepFunctionsService) {
|
||||
@@ -132,6 +159,10 @@ public class CloudFormationResourceProvisioner {
|
||||
this.ecrService = ecrService;
|
||||
this.pipesService = pipesService;
|
||||
this.cognitoService = cognitoService;
|
||||
this.lambdaLayerService = lambdaLayerService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.customResourceResponseStore = customResourceResponseStore;
|
||||
this.reachableEndpoint = reachableEndpoint;
|
||||
this.ecsService = ecsService;
|
||||
this.elbV2Service = elbV2Service;
|
||||
this.stepFunctionsService = stepFunctionsService;
|
||||
@@ -173,6 +204,8 @@ public class CloudFormationResourceProvisioner {
|
||||
case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" ->
|
||||
provisionDynamoTable(resource, properties, engine, region, accountId, stackName);
|
||||
case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName);
|
||||
case "AWS::Lambda::LayerVersion" ->
|
||||
provisionLambdaLayerVersion(resource, properties, engine, region, stackName);
|
||||
case "AWS::IAM::Role" -> provisionIamRole(resource, properties, engine, accountId, stackName);
|
||||
case "AWS::IAM::User" -> provisionIamUser(resource, properties, engine, stackName);
|
||||
case "AWS::IAM::AccessKey" -> provisionIamAccessKey(resource, properties, engine);
|
||||
@@ -210,6 +243,8 @@ public class CloudFormationResourceProvisioner {
|
||||
provisionCognitoUserPool(resource, properties, engine, region, accountId, stackName);
|
||||
case "AWS::Cognito::UserPoolClient" ->
|
||||
provisionCognitoUserPoolClient(resource, properties, engine, region, accountId, stackName);
|
||||
case "AWS::CloudFormation::CustomResource" ->
|
||||
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
|
||||
case "AWS::ECS::Cluster" -> provisionEcsCluster(resource, properties, engine, region, stackName);
|
||||
case "AWS::ECS::TaskDefinition" -> provisionEcsTaskDefinition(resource, properties, engine, region, stackName);
|
||||
case "AWS::ECS::Service" -> provisionEcsService(resource, properties, engine, region, stackName);
|
||||
@@ -222,9 +257,13 @@ public class CloudFormationResourceProvisioner {
|
||||
case "AWS::ElasticLoadBalancingV2::ListenerRule" ->
|
||||
provisionListenerRule(resource, properties, engine, region);
|
||||
default -> {
|
||||
LOG.debugv("Stubbing unsupported resource type: {0} ({1})", resourceType, logicalId);
|
||||
resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId);
|
||||
if (resourceType != null && resourceType.startsWith("Custom::")) {
|
||||
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
|
||||
} else {
|
||||
LOG.debugv("Stubbing unsupported resource type: {0} ({1})", resourceType, logicalId);
|
||||
resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId);
|
||||
}
|
||||
}
|
||||
}
|
||||
resource.setStatus("CREATE_COMPLETE");
|
||||
@@ -236,6 +275,22 @@ public class CloudFormationResourceProvisioner {
|
||||
return resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a provisioned resource. Custom resources are re-invoked with {@code RequestType=Delete}
|
||||
* (using the ServiceToken + properties stashed at create time); everything else delegates to the
|
||||
* type-keyed {@link #delete(String, String, String)}.
|
||||
*/
|
||||
public void delete(StackResource resource, String region) {
|
||||
String resourceType = resource.getResourceType();
|
||||
boolean custom = "AWS::CloudFormation::CustomResource".equals(resourceType)
|
||||
|| (resourceType != null && resourceType.startsWith("Custom::"));
|
||||
if (custom) {
|
||||
deleteCustomResource(resource, region);
|
||||
return;
|
||||
}
|
||||
delete(resourceType, resource.getPhysicalId(), region);
|
||||
}
|
||||
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
try {
|
||||
switch (resourceType) {
|
||||
@@ -262,6 +317,7 @@ public class CloudFormationResourceProvisioner {
|
||||
case "AWS::Pipes::Pipe" -> pipesService.deletePipe(physicalId, region);
|
||||
case "AWS::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId);
|
||||
case "AWS::Lambda::EventSourceMapping" -> lambdaService.deleteEventSourceMapping(physicalId);
|
||||
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
|
||||
case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);
|
||||
case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);
|
||||
case "AWS::ECS::Cluster" -> ecsService.deleteCluster(physicalId, region);
|
||||
@@ -1837,6 +1893,251 @@ public class CloudFormationResourceProvisioner {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Lambda LayerVersion ──────────────────────────────────────────────────
|
||||
//
|
||||
// Without this, layer versions (e.g. CDK's AwsCliLayer) fall through to the stub, so the
|
||||
// function's Layers ARN can't be resolved and the layer content is never copied into /opt.
|
||||
|
||||
private void provisionLambdaLayerVersion(StackResource r, JsonNode props,
|
||||
CloudFormationTemplateEngine engine, String region,
|
||||
String stackName) {
|
||||
if (props == null || !props.has("Content")) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Lambda LayerVersion " + r.getLogicalId() + " is missing Content", 400);
|
||||
}
|
||||
String layerName = resolveOptional(props, "LayerName", engine);
|
||||
if (layerName == null || layerName.isBlank()) {
|
||||
layerName = generatePhysicalName(stackName, r.getLogicalId(), 140, false);
|
||||
}
|
||||
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("Content", jsonObjectToMap(engine.resolveNode(props.get("Content"))));
|
||||
String description = resolveOptional(props, "Description", engine);
|
||||
if (description != null) {
|
||||
request.put("Description", description);
|
||||
}
|
||||
String licenseInfo = resolveOptional(props, "LicenseInfo", engine);
|
||||
if (licenseInfo != null) {
|
||||
request.put("LicenseInfo", licenseInfo);
|
||||
}
|
||||
List<String> runtimes = resolveStringListOrEmpty(props, "CompatibleRuntimes", engine);
|
||||
if (!runtimes.isEmpty()) {
|
||||
request.put("CompatibleRuntimes", runtimes);
|
||||
}
|
||||
List<String> architectures = resolveStringListOrEmpty(props, "CompatibleArchitectures", engine);
|
||||
if (!architectures.isEmpty()) {
|
||||
request.put("CompatibleArchitectures", architectures);
|
||||
}
|
||||
|
||||
LambdaLayerVersion layer = lambdaLayerService.publishLayerVersion(region, layerName, request);
|
||||
// CloudFormation Ref on a LayerVersion returns the version ARN; the Lambda's Layers list
|
||||
// references it, and ContainerLauncher resolves it back to disk via resolveLayerByArn.
|
||||
r.setPhysicalId(layer.getLayerVersionArn());
|
||||
r.getAttributes().put("Arn", layer.getLayerVersionArn());
|
||||
r.getAttributes().put("LayerVersionArn", layer.getLayerVersionArn());
|
||||
}
|
||||
|
||||
private void deleteLambdaLayerVersion(String physicalId, String region) {
|
||||
LambdaLayerVersion layer = lambdaLayerService.resolveLayerByArn(physicalId);
|
||||
if (layer != null) {
|
||||
lambdaLayerService.deleteLayerVersion(region, layer.getLayerName(), layer.getVersion());
|
||||
}
|
||||
}
|
||||
|
||||
// ── CloudFormation Custom Resources ──────────────────────────────────────
|
||||
//
|
||||
// A Custom::* / AWS::CloudFormation::CustomResource is backed by a Lambda named by its
|
||||
// ServiceToken. CloudFormation invokes that Lambda with a request event and the Lambda PUTs its
|
||||
// result to the event's ResponseURL (it does NOT return it). Floci points ResponseURL at
|
||||
// CfnResponseController and, because the invoke is synchronous, reads the captured response as
|
||||
// soon as the handler returns. Pattern 1 only — single-Lambda synchronous handlers (e.g. CDK
|
||||
// BucketDeployment). The async Provider framework (onEvent/isComplete polling) is not emulated.
|
||||
|
||||
private void provisionCustomResource(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String accountId, String stackName) {
|
||||
if (props == null || !props.has("ServiceToken")) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Custom resource " + r.getLogicalId() + " is missing ServiceToken", 400);
|
||||
}
|
||||
String serviceToken = engine.resolve(props.get("ServiceToken"));
|
||||
if (serviceToken == null || serviceToken.isBlank()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Custom resource " + r.getLogicalId() + " has an unresolved ServiceToken", 400);
|
||||
}
|
||||
|
||||
// Resolve intrinsics to concrete values. CloudFormation keeps ServiceToken inside
|
||||
// ResourceProperties (and also surfaces it at the top level of the event), so we leave it
|
||||
// in place here. CloudFormation stringifies every scalar in ResourceProperties
|
||||
// (true -> "true", 5 -> "5") while preserving list/map structure; handlers (e.g. CDK's)
|
||||
// rely on this and call String methods on the values, so we must match it.
|
||||
JsonNode resolvedProps = engine.resolveNode(props);
|
||||
ObjectNode resolved = resolvedProps.isObject()
|
||||
? ((ObjectNode) resolvedProps).deepCopy()
|
||||
: objectMapper.createObjectNode();
|
||||
ObjectNode resourceProperties = (ObjectNode) stringifyScalars(resolved);
|
||||
|
||||
boolean isUpdate = r.getPhysicalId() != null;
|
||||
String requestType = isUpdate ? "Update" : "Create";
|
||||
String priorPhysicalId = isUpdate ? r.getPhysicalId() : null;
|
||||
|
||||
// On Update, CloudFormation includes the previous ResourceProperties so the handler can diff.
|
||||
// The prior values were stashed at the last create/update; read them before we overwrite below.
|
||||
ObjectNode oldResourceProperties = isUpdate ? readStashedProperties(r) : null;
|
||||
|
||||
JsonNode response = invokeCustomResourceHandler(serviceToken, requestType, r.getLogicalId(),
|
||||
r.getResourceType(), priorPhysicalId, resourceProperties, oldResourceProperties,
|
||||
region, accountId, stackName);
|
||||
|
||||
String status = response.path("Status").asText("FAILED");
|
||||
if (!"SUCCESS".equals(status)) {
|
||||
throw new AwsException("CustomResourceFailed",
|
||||
"Custom resource handler reported FAILED: "
|
||||
+ response.path("Reason").asText("(no reason given)"), 400);
|
||||
}
|
||||
|
||||
String returnedPhysicalId = response.path("PhysicalResourceId").asText(null);
|
||||
if (returnedPhysicalId != null && !returnedPhysicalId.isBlank()) {
|
||||
r.setPhysicalId(returnedPhysicalId);
|
||||
} else if (priorPhysicalId != null) {
|
||||
r.setPhysicalId(priorPhysicalId);
|
||||
} else {
|
||||
r.setPhysicalId(r.getLogicalId() + "-" + UUID.randomUUID().toString().substring(0, 12));
|
||||
}
|
||||
|
||||
// Data.* become Fn::GetAtt attributes on the custom resource.
|
||||
JsonNode data = response.path("Data");
|
||||
if (data.isObject()) {
|
||||
data.fields().forEachRemaining(e ->
|
||||
r.getAttributes().put(e.getKey(), nodeToAttributeValue(e.getValue())));
|
||||
}
|
||||
|
||||
// Stash what a later Delete invocation needs (delete() only gets the StackResource).
|
||||
r.getAttributes().put(CR_SERVICE_TOKEN_ATTR, serviceToken);
|
||||
r.getAttributes().put(CR_PROPERTIES_ATTR, resourceProperties.toString());
|
||||
}
|
||||
|
||||
private void deleteCustomResource(StackResource r, String region) {
|
||||
String serviceToken = r.getAttributes().get(CR_SERVICE_TOKEN_ATTR);
|
||||
if (serviceToken == null || serviceToken.isBlank()) {
|
||||
LOG.debugv("Custom resource {0} has no stored ServiceToken; skipping Delete", r.getLogicalId());
|
||||
return;
|
||||
}
|
||||
ObjectNode stashed = readStashedProperties(r);
|
||||
ObjectNode resourceProperties = stashed != null ? stashed : objectMapper.createObjectNode();
|
||||
try {
|
||||
JsonNode response = invokeCustomResourceHandler(serviceToken, "Delete", r.getLogicalId(),
|
||||
r.getResourceType(), r.getPhysicalId(), resourceProperties, null, region,
|
||||
accountFromArn(serviceToken), "");
|
||||
if (!"SUCCESS".equals(response.path("Status").asText("FAILED"))) {
|
||||
LOG.warnv("Custom resource {0} Delete reported FAILED: {1}",
|
||||
r.getLogicalId(), response.path("Reason").asText("(no reason given)"));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Best-effort, consistent with the rest of delete().
|
||||
LOG.debugv("Custom resource {0} Delete invocation failed: {1}", r.getLogicalId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Reads the ResourceProperties stashed at the last create/update (CR_PROPERTIES_ATTR).
|
||||
// Returns null when nothing is stashed or it cannot be parsed.
|
||||
private ObjectNode readStashedProperties(StackResource r) {
|
||||
String stored = r.getAttributes().get(CR_PROPERTIES_ATTR);
|
||||
if (stored == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode parsed = objectMapper.readTree(stored);
|
||||
return parsed.isObject() ? (ObjectNode) parsed : null;
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not parse stored properties for custom resource {0}: {1}",
|
||||
r.getLogicalId(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode invokeCustomResourceHandler(String serviceToken, String requestType, String logicalId,
|
||||
String resourceType, String physicalId,
|
||||
ObjectNode resourceProperties, ObjectNode oldResourceProperties,
|
||||
String region, String accountId, String stackName) {
|
||||
String token = customResourceResponseStore.register();
|
||||
try {
|
||||
ObjectNode event = objectMapper.createObjectNode();
|
||||
event.put("RequestType", requestType);
|
||||
event.put("ResponseURL", reachableEndpoint.baseUrl() + "/cfn-response/" + token);
|
||||
event.put("StackId", "arn:aws:cloudformation:" + region + ":" + accountId + ":stack/"
|
||||
+ (stackName == null ? "" : stackName) + "/" + UUID.randomUUID());
|
||||
event.put("RequestId", UUID.randomUUID().toString());
|
||||
event.put("ResourceType", resourceType);
|
||||
event.put("LogicalResourceId", logicalId);
|
||||
if (physicalId != null) {
|
||||
event.put("PhysicalResourceId", physicalId);
|
||||
}
|
||||
event.put("ServiceToken", serviceToken);
|
||||
event.set("ResourceProperties", resourceProperties);
|
||||
if (oldResourceProperties != null) {
|
||||
event.set("OldResourceProperties", oldResourceProperties);
|
||||
}
|
||||
|
||||
byte[] payload = objectMapper.writeValueAsBytes(event);
|
||||
InvokeResult result = lambdaService.invoke(region, serviceToken, payload,
|
||||
InvocationType.RequestResponse);
|
||||
if (result.getFunctionError() != null) {
|
||||
String body = result.getPayload() != null
|
||||
? new String(result.getPayload(), StandardCharsets.UTF_8) : "";
|
||||
throw new AwsException("CustomResourceFailed",
|
||||
"Custom resource handler errored (" + result.getFunctionError() + "): " + body, 400);
|
||||
}
|
||||
|
||||
return customResourceResponseStore.await(token, CR_RESPONSE_TIMEOUT);
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (TimeoutException e) {
|
||||
throw new AwsException("CustomResourceTimeout",
|
||||
"Timed out waiting for custom resource " + logicalId
|
||||
+ " to PUT its response to ResponseURL", 504);
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("CustomResourceFailed",
|
||||
"Failed to invoke custom resource " + logicalId + ": " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
private static String nodeToAttributeValue(JsonNode node) {
|
||||
if (node == null || node.isNull()) {
|
||||
return "";
|
||||
}
|
||||
return node.isValueNode() ? node.asText() : node.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors CloudFormation's stringification of custom-resource ResourceProperties: every scalar
|
||||
* (boolean, number, text) becomes a string, while object and array structure is preserved.
|
||||
* Null is left as-is.
|
||||
*/
|
||||
private JsonNode stringifyScalars(JsonNode node) {
|
||||
if (node == null || node.isNull()) {
|
||||
return node;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
node.fields().forEachRemaining(e -> out.set(e.getKey(), stringifyScalars(e.getValue())));
|
||||
return out;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
var out = objectMapper.createArrayNode();
|
||||
node.forEach(e -> out.add(stringifyScalars(e)));
|
||||
return out;
|
||||
}
|
||||
return objectMapper.getNodeFactory().textNode(node.asText());
|
||||
}
|
||||
|
||||
private static String accountFromArn(String arn) {
|
||||
if (arn == null) {
|
||||
return "000000000000";
|
||||
}
|
||||
String[] parts = arn.split(":");
|
||||
return parts.length >= 5 && parts[4].matches("\\d{12}") ? parts[4] : "000000000000";
|
||||
}
|
||||
|
||||
// ── ECS ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionEcsCluster(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
|
||||
+1
-1
@@ -538,7 +538,7 @@ public class CloudFormationService {
|
||||
if (resource.getPhysicalId() != null && "CREATE_COMPLETE".equals(resource.getStatus())) {
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_IN_PROGRESS", null);
|
||||
provisioner.delete(resource.getResourceType(), resource.getPhysicalId(), region);
|
||||
provisioner.delete(resource, region);
|
||||
resource.setStatus("DELETE_COMPLETE");
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_COMPLETE", null);
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
/**
|
||||
* Correlates a CloudFormation custom-resource Lambda invocation with the response the
|
||||
* Lambda PUTs back to its {@code ResponseURL}.
|
||||
*
|
||||
* <p>The AWS custom-resource protocol is callback-based: the backing Lambda does not return
|
||||
* its result, it HTTP PUTs a response document to a pre-signed {@code ResponseURL}. Floci hands
|
||||
* the Lambda a {@code ResponseURL} pointing at {@link CfnResponseController}, which feeds the
|
||||
* body back here keyed by a per-invocation token.
|
||||
*
|
||||
* <p>Because Floci invokes the Lambda synchronously (RequestResponse) and the handler PUTs
|
||||
* before returning, the future is normally already completed by the time the provisioner awaits
|
||||
* it — the timeout only guards a PUT that lands just after the container returns.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CustomResourceResponseStore {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CustomResourceResponseStore.class);
|
||||
|
||||
private final ConcurrentHashMap<String, CompletableFuture<JsonNode>> pending = new ConcurrentHashMap<>();
|
||||
|
||||
/** Registers a fresh token and returns it. Call before invoking the Lambda. */
|
||||
public String register() {
|
||||
String token = UUID.randomUUID().toString();
|
||||
pending.put(token, new CompletableFuture<>());
|
||||
return token;
|
||||
}
|
||||
|
||||
/** Completes the future for {@code token} with the PUT body. No-op for unknown/expired tokens. */
|
||||
public void complete(String token, JsonNode response) {
|
||||
CompletableFuture<JsonNode> future = pending.get(token);
|
||||
if (future != null) {
|
||||
future.complete(response);
|
||||
} else {
|
||||
LOG.debugv("Received custom-resource response for unknown token {0}", token);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits up to {@code timeout} for the Lambda's response, then discards the token.
|
||||
*
|
||||
* @throws TimeoutException if no response arrives in time
|
||||
*/
|
||||
public JsonNode await(String token, Duration timeout) throws TimeoutException {
|
||||
CompletableFuture<JsonNode> future = pending.get(token);
|
||||
if (future == null) {
|
||||
throw new IllegalStateException("No pending custom-resource token: " + token);
|
||||
}
|
||||
try {
|
||||
return future.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
|
||||
} catch (TimeoutException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Interrupted awaiting custom-resource response", e);
|
||||
} finally {
|
||||
pending.remove(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-14
@@ -1,8 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.lambda.launcher;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
@@ -61,8 +61,8 @@ public class ContainerLauncher {
|
||||
private final DockerHostResolver dockerHostResolver;
|
||||
private final EmulatorConfig config;
|
||||
private final EcrRegistryManager ecrRegistryManager;
|
||||
private final EmbeddedDnsServer embeddedDnsServer;
|
||||
private final LambdaLayerService layerService;
|
||||
private final ContainerReachableEndpoint reachableEndpoint;
|
||||
|
||||
/** Matches an AWS-shaped ECR image URI: {@code <account>.dkr.ecr.<region>.amazonaws.com/<repo>[:tag]}. */
|
||||
private static final java.util.regex.Pattern AWS_ECR_URI =
|
||||
@@ -77,8 +77,8 @@ public class ContainerLauncher {
|
||||
DockerHostResolver dockerHostResolver,
|
||||
EmulatorConfig config,
|
||||
EcrRegistryManager ecrRegistryManager,
|
||||
EmbeddedDnsServer embeddedDnsServer,
|
||||
LambdaLayerService layerService) {
|
||||
LambdaLayerService layerService,
|
||||
ContainerReachableEndpoint reachableEndpoint) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
@@ -87,8 +87,8 @@ public class ContainerLauncher {
|
||||
this.dockerHostResolver = dockerHostResolver;
|
||||
this.config = config;
|
||||
this.ecrRegistryManager = ecrRegistryManager;
|
||||
this.embeddedDnsServer = embeddedDnsServer;
|
||||
this.layerService = layerService;
|
||||
this.reachableEndpoint = reachableEndpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -153,15 +153,10 @@ public class ContainerLauncher {
|
||||
String cwLogStream = LOG_STREAM_DATE_FMT.format(LocalDate.now()) + "/[$LATEST]" + shortId;
|
||||
String lambdaRegion = extractRegionFromArn(fn.getFunctionArn(), config.defaultRegion());
|
||||
|
||||
// Floci endpoint reachable from inside the container.
|
||||
// When the embedded DNS server is active, Lambda containers already have it wired as their
|
||||
// resolver and can reach Floci by the configured hostname (or the default DNS suffix).
|
||||
// Fall back to the raw Docker host IP when the embedded DNS is not running (local dev mode).
|
||||
int flociPort = java.net.URI.create(config.baseUrl()).getPort();
|
||||
String flociHostname = embeddedDnsServer.getServerIp().isPresent()
|
||||
? config.hostname().orElse(EmbeddedDnsServer.DEFAULT_SUFFIX)
|
||||
: hostAddress;
|
||||
String flociEndpoint = "http://" + flociHostname + ":" + flociPort;
|
||||
// Floci endpoint reachable from inside the container (shared with the CloudFormation
|
||||
// custom-resource provisioner, which uses the same address for ResponseURL callbacks).
|
||||
String flociEndpoint = reachableEndpoint.baseUrl();
|
||||
String flociHostname = java.net.URI.create(flociEndpoint).getHost();
|
||||
|
||||
// Build env vars
|
||||
List<String> env = new ArrayList<>();
|
||||
|
||||
Reference in new issue
Block a user